ChatGptAccountServiceImpl.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. package com.cyksj.service.chatgpt.impl;
  2. import cn.hutool.core.date.DateTime;
  3. import cn.hutool.core.lang.UUID;
  4. import cn.hutool.http.HttpRequest;
  5. import cn.hutool.http.HttpResponse;
  6. import cn.hutool.http.HttpUtil;
  7. import cn.hutool.http.Method;
  8. import cn.hutool.json.JSONObject;
  9. import cn.hutool.json.JSONUtil;
  10. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  11. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  12. import com.cyksj.common.exception.BusinessRuntimeException;
  13. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  14. import com.cyksj.common.util.StringUtil;
  15. import com.cyksj.mapper.*;
  16. import com.cyksj.model.entity.*;
  17. import com.cyksj.model.request.gpt.ConversationRequest;
  18. import com.cyksj.model.response.ConversationLimitResponse;
  19. import com.cyksj.model.views.ChatGptUserConversationRecordHistoryView;
  20. import com.cyksj.model.views.ChatGptUserView;
  21. import com.cyksj.model.views.ChatgptCarInfoView;
  22. import com.cyksj.redis.RedisService;
  23. import com.cyksj.service.chatgpt.ChatGptAccountService;
  24. import com.cyksj.service.user.UserBindRelationService;
  25. import com.ejlchina.searcher.BeanSearcher;
  26. import com.ejlchina.searcher.SearchResult;
  27. import com.ejlchina.searcher.util.MapUtils;
  28. import lombok.RequiredArgsConstructor;
  29. import lombok.extern.slf4j.Slf4j;
  30. import org.apache.commons.lang3.StringUtils;
  31. import org.springframework.beans.factory.annotation.Value;
  32. import org.springframework.dao.DuplicateKeyException;
  33. import org.springframework.data.redis.core.ZSetOperations;
  34. import org.springframework.stereotype.Service;
  35. import javax.annotation.PostConstruct;
  36. import javax.imageio.stream.FileImageOutputStream;
  37. import java.nio.file.Files;
  38. import java.nio.file.Path;
  39. import java.time.LocalDateTime;
  40. import java.util.*;
  41. import java.util.stream.Collectors;
  42. /**
  43. * @author chan
  44. * @date 2024/3/19 11:01
  45. */
  46. @Service
  47. @Slf4j
  48. @RequiredArgsConstructor
  49. public class ChatGptAccountServiceImpl implements ChatGptAccountService {
  50. @Value("${chatgpt.domain}")
  51. private String GPT_DOMAIN;
  52. @Value("${chatgpt.car.domain}")
  53. private String CAR_GPT_DOMAIN;
  54. private static final String GPT_PROXY = "https://chat-chan-87jztgkf257d.xyhelper.net";
  55. private static final int MAX_REQUESTS = 40; // 3小时内最大请求次数
  56. private static final long WINDOW_SIZE = 3 * 60 * 60; // 3小时窗口的秒数
  57. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  58. private final RedisService redisService;
  59. private final ChatgptUserMapper chatgptUserMapper;
  60. private final ChatgptSessionMapper chatgptSessionMapper;
  61. private final GroupsRelationMapper groupsRelationMapper;
  62. private final GroupsMapper groupsMapper;
  63. private final GoodsDonSkuMapper skuMapper;
  64. private final UserMapper userMapper;
  65. private final UserBindRelationService userBindRelationService;
  66. private final ChatgptUserConversationRecordMapper chatgptUserConversationRecordMapper;
  67. private final ChatgptUserConversationMapper chatgptUserConversationMapper;
  68. private final AccountMapper accountMapper;
  69. private final BeanSearcher beanSearcher;
  70. @Override
  71. public String addAccount(Account account) {
  72. if (isAccountExists(account)) {
  73. throw BusinessRuntimeException.getInstance("镜像服务该账号已存在.");
  74. }
  75. String refreshToken = "";
  76. String officialSession = "";
  77. try {
  78. JSONObject loginResult = getLoginResult(account);
  79. if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
  80. throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
  81. }
  82. refreshToken = loginResult.getStr("refresh_token");
  83. officialSession = loginResult.toString();
  84. } catch (Exception e) {
  85. throw BusinessRuntimeException.getInstance("登录获取token错误 error:" + e.getMessage());
  86. }
  87. createChatgptSession(account, officialSession);
  88. return refreshToken;
  89. }
  90. @Override
  91. public String getGptSession(String account, String password) {
  92. String officialSession = "";
  93. try {
  94. Account at = new Account();
  95. at.setAccount(account);
  96. at.setPassword(password);
  97. JSONObject loginResult = getLoginResult(at);
  98. if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
  99. throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
  100. }
  101. officialSession = loginResult.toString();
  102. } catch (Exception e) {
  103. throw BusinessRuntimeException.getInstance("登录获取token错误 error:" + e.getMessage());
  104. }
  105. return officialSession;
  106. }
  107. /**
  108. * 判断账号是否存在
  109. *
  110. * @param account 账号
  111. * @return 是否存在
  112. */
  113. private boolean isAccountExists(Account account) {
  114. Integer count = chatgptSessionMapper.selectCount(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getEmail, account.getAccount()));
  115. return count > 0;
  116. }
  117. /**
  118. * 获取登录结果
  119. *
  120. * @param account
  121. * @return
  122. * @throws Exception
  123. */
  124. private JSONObject getLoginResult(Account account) throws Exception {
  125. HttpRequest request = new HttpRequest(GPT_PROXY + "/getsession");
  126. request.form("username", account.getAccount());
  127. request.form("password", account.getPassword());
  128. request.header("Content-Type", "application/x-www-form-urlencoded");
  129. HttpResponse execute = request.method(Method.POST).execute();
  130. return new JSONObject(execute.body());
  131. }
  132. /**
  133. * 创建chatgptSession
  134. *
  135. * @param account
  136. * @param officialSession
  137. */
  138. private void createChatgptSession(Account account, String officialSession) {
  139. ChatgptSession chatgptSession = new ChatgptSession();
  140. chatgptSession.setOfficialSession(officialSession);
  141. chatgptSession.setEmail(account.getAccount());
  142. chatgptSession.setPassword(account.getPassword());
  143. chatgptSession.setIsPlus(1);
  144. chatgptSession.setAccountId(account.getId());
  145. chatgptSession.setStatus(1);
  146. chatgptSessionMapper.insert(chatgptSession);
  147. }
  148. /**
  149. * 更新账号
  150. *
  151. * @param account
  152. */
  153. @Override
  154. public void upAccount(Account account) {
  155. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getEmail, account.getAccount()));
  156. if (chatgptSession != null) {
  157. if (StringUtils.isNotBlank(account.getGptRefreshToken())) {
  158. chatgptSession.setOfficialSession(account.getGptRefreshToken());
  159. }
  160. chatgptSession.setEmail(account.getAccount());
  161. chatgptSession.setPassword(account.getPassword());
  162. chatgptSession.setIsPlus(1);
  163. chatgptSession.setAccountId(account.getId());
  164. chatgptSession.setStatus(1);
  165. chatgptSessionMapper.updateById(chatgptSession);
  166. }
  167. }
  168. /**
  169. * 获取登录url
  170. *
  171. * @param userId
  172. * @param relationId
  173. * @return
  174. */
  175. @Override
  176. public String getLoginUrl(Long userId, Long relationId) {
  177. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  178. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  179. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  180. if (goodsDonSku != null && goodsDonSku.getIsMirror()) {
  181. ChatgptUser chatgptUser = getChatgptUser(userId, relationId, groupsRelation, groupsTrips, goodsDonSku);
  182. return GPT_DOMAIN + "/login_token?access_token=" + chatgptUser.getUserToken();
  183. } else {
  184. throw BusinessRuntimeException.getInstance("服务器出了点问题");
  185. }
  186. }
  187. /**
  188. * 获取车队登录url
  189. *
  190. * @param userId
  191. * @param carId
  192. * @return
  193. */
  194. @Override
  195. public String getCarLoginUrl(Long userId, Long relationId, String carId) {
  196. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  197. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  198. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  199. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  200. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  201. return CAR_GPT_DOMAIN + "/auth/logintoken?carid=" + carId + "&usertoken=" + chatgptUser.getUserToken();
  202. } else {
  203. throw BusinessRuntimeException.getInstance("服务器出了点问题");
  204. }
  205. }
  206. /**
  207. * 获取车位信息
  208. *
  209. * @param userId
  210. * @param relationId
  211. * @return
  212. */
  213. private GroupsRelation getGroupsRelation(Long userId, Long relationId) {
  214. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  215. GroupsRelation groupsRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).in(GroupsRelation::getUserId, userIdList).eq(GroupsRelation::getId, relationId));
  216. if (groupsRelation == null) {
  217. throw BusinessRuntimeException.getInstance("车票不存在");
  218. }
  219. return groupsRelation;
  220. }
  221. /**
  222. * 获取车队信息
  223. *
  224. * @param groupsRelation
  225. * @return
  226. */
  227. private GroupsTrips getGroupsTrips(GroupsRelation groupsRelation) {
  228. GroupsTrips groupsTrips = groupsMapper.selectById(groupsRelation.getGroupsId());
  229. if (groupsTrips == null) {
  230. throw BusinessRuntimeException.getInstance("车队异常");
  231. }
  232. return groupsTrips;
  233. }
  234. private ChatgptUser getChatgptUser(Long userId, Long relationId, GroupsRelation groupsRelation, GroupsTrips groupsTrips, GoodsDonSku goodsDonSku) {
  235. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  236. User user = userMapper.selectById(userId);
  237. if (chatgptUser == null) {
  238. chatgptUser = createChatgptUser(groupsRelation, groupsTrips, user, goodsDonSku);
  239. } else {
  240. updateChatgptUser(groupsRelation, user, chatgptUser);
  241. }
  242. return chatgptUser;
  243. }
  244. private ChatgptUser getChatgptCarUser(Long userId, Long relationId, GroupsRelation groupsRelation, GoodsDonSku goodsDonSku) {
  245. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  246. User user = userMapper.selectById(userId);
  247. if (chatgptUser == null) {
  248. chatgptUser = createChatgptUser(groupsRelation, null, user, goodsDonSku);
  249. } else {
  250. updateChatgptUser(groupsRelation, user, chatgptUser);
  251. }
  252. return chatgptUser;
  253. }
  254. /**
  255. * 创建chatgptUser
  256. */
  257. private synchronized ChatgptUser createChatgptUser(GroupsRelation groupsRelation, GroupsTrips groupsTrips, User user, GoodsDonSku goodsDonSku) {
  258. ChatgptUser chatgptUser = new ChatgptUser();
  259. if (!goodsDonSku.getIsCar()) {
  260. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
  261. if (chatgptSession == null) {
  262. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  263. String officialSession = "";
  264. try {
  265. JSONObject loginResult = getLoginResult(account);
  266. if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
  267. throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
  268. }
  269. officialSession = loginResult.toString();
  270. } catch (Exception e) {
  271. throw BusinessRuntimeException.getInstance("配置账号错误 msg: " + e.getMessage());
  272. }
  273. createChatgptSession(account, officialSession);
  274. chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
  275. }
  276. chatgptUser.setSessionId(chatgptSession.getId());
  277. }
  278. if (goodsDonSku.getIsCar()) {
  279. chatgptUser.setIsCar(true);
  280. chatgptUser.setLimitNum(goodsDonSku.getGptLimitNum());
  281. chatgptUser.setLimitTime(goodsDonSku.getGptLimitTime());
  282. }
  283. try {
  284. chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
  285. chatgptUser.setIsPlus(1);
  286. chatgptUser.setName(user.getNickname());
  287. chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
  288. chatgptUser.setRelationId(groupsRelation.getId());
  289. chatgptUser.setUserToken(UUID.randomUUID().toString());
  290. chatgptUserMapper.insert(chatgptUser);
  291. } catch (DuplicateKeyException e) {
  292. }
  293. return chatgptUser;
  294. }
  295. private void updateChatgptUser(GroupsRelation groupsRelation, User user, ChatgptUser chatgptUser) {
  296. chatgptUser.setName(user.getNickname());
  297. chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
  298. chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
  299. chatgptUserMapper.updateById(chatgptUser);
  300. }
  301. /**
  302. * 更换wx头像至oss
  303. */
  304. private String getWxImg(String headimgurl, User user) {
  305. if (headimgurl.contains("thirdwx.qlogo.cn")) {
  306. try {
  307. byte[] body = HttpUtil.downloadBytes(headimgurl);
  308. Path tempFile = Files.createTempFile("wxheadimg-" + user.getId(), ".jpeg");
  309. try (FileImageOutputStream imageOutput = new FileImageOutputStream(tempFile.toFile())) {
  310. imageOutput.write(body, 0, body.length);
  311. }
  312. Map<String, Object> paramMap = new HashMap<>();
  313. paramMap.put("file", tempFile.toFile());
  314. JSONObject result = JSONUtil.parseObj(HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap));
  315. return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
  316. } catch (Exception ex) {
  317. log.error("上传微信头像错误!msg:{}", StringUtil.getErrorText(ex));
  318. return "./avatars.png";
  319. }
  320. } else {
  321. return user.getHeadimgurl();
  322. }
  323. }
  324. @Override
  325. public ChatgptUser findByUserTokenAndExpireTimeAfter(String userToken, LocalDateTime now) {
  326. return chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken).gt(ChatgptUser::getExpireTime, now));
  327. }
  328. @Override
  329. public void saveConversationRecord(String userToken, ConversationRequest conversationRequest) {
  330. LambdaQueryWrapper<ChatgptSession> wrapper = Wrappers.lambdaQuery(ChatgptSession.class);
  331. if(StringUtils.isNotBlank(conversationRequest.getCarId())){
  332. wrapper.eq(ChatgptSession::getCarId, conversationRequest.getCarId());
  333. }else {
  334. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken));
  335. if (chatgptUser.getSessionId() != null) {
  336. wrapper.eq(ChatgptSession::getId, chatgptUser.getSessionId());
  337. }
  338. }
  339. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(wrapper);
  340. ChatgptUserConversationRecord chatgptUserConversationRecord = new ChatgptUserConversationRecord();
  341. chatgptUserConversationRecord.setUserToken(userToken);
  342. chatgptUserConversationRecord.setCarId(chatgptSession.getCarId());
  343. chatgptUserConversationRecord.setCarName(chatgptSession.getCarName());
  344. if (StringUtils.isBlank(conversationRequest.getConversation_id())) {
  345. chatgptUserConversationRecord.setMessageId(conversationRequest.getMessages().get(0).getId());
  346. } else {
  347. chatgptUserConversationRecord.setConversationId(conversationRequest.getConversation_id());
  348. }
  349. chatgptUserConversationRecord.setModel(conversationRequest.getModel());
  350. chatgptUserConversationRecordMapper.insert(chatgptUserConversationRecord);
  351. if(StringUtils.isNotBlank(chatgptSession.getCarId())){
  352. updateExperienceAndScore(chatgptSession.getCarId(), !"text-davinci-002-render-sha".equals(conversationRequest.getModel()), System.currentTimeMillis());
  353. }
  354. }
  355. @Override
  356. public ConversationLimitResponse conversationLimit(String userToken, String model, String carId, ChatgptUser chatgptUser, Boolean isCar) {
  357. ConversationLimitResponse conversationLimitResponse = new ConversationLimitResponse();
  358. conversationLimitResponse.setLimited(false);
  359. if (!"text-davinci-002-render-sha".equals(model)) {
  360. //如果不为车队 直接返回
  361. if (chatgptUser.getIsCar()) {
  362. conversationLimitResponse = isConversationAllowed(userToken, chatgptUser.getLimitNum(), chatgptUser.getLimitTime());
  363. }
  364. }
  365. return conversationLimitResponse;
  366. }
  367. /**
  368. * 检查是否允许进行进行提问
  369. *
  370. * @param userToken 用户token
  371. * @return true 如果允许请求,false 如果请求被限制
  372. */
  373. public ConversationLimitResponse isConversationAllowed(String userToken, int limit, Long limitTime) {
  374. String key = RedisService.key.CHATGPT_CONVERSATION_LIMIT.getName() + ":" + userToken;
  375. long currentTimeMillis = System.currentTimeMillis();
  376. long windowStartMillis = currentTimeMillis - (limitTime * 60 * 60) * 1000;
  377. ConversationLimitResponse conversationLimitResponse = new ConversationLimitResponse();
  378. // 清除时间窗口之前的请求记录
  379. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  380. Long currentSize = redisService.zCard(key);
  381. if (currentSize != null && currentSize >= limit) {
  382. // 如果当前请求次数超过限制,则拒绝请求
  383. Set<Object> times = redisService.zRangeByScore(key, 0, currentTimeMillis, 0, 1);
  384. Long oldestTime = (Long) times.stream().findFirst().orElse(null);
  385. if (oldestTime != null) {
  386. // 下一次可用时间是最早请求时间之后的3小时
  387. long nextAvailableTime = oldestTime + (limitTime * 60 * 60 * 1000);
  388. conversationLimitResponse.setNextAvailableTime(nextAvailableTime);
  389. }
  390. conversationLimitResponse.setLimited(true);
  391. return conversationLimitResponse;
  392. } else {
  393. // 如果未超过限制,记录当前请求的时间戳
  394. redisService.zAdd(key, currentTimeMillis, currentTimeMillis);
  395. // 设置ZSet的过期时间,窗口大小加上一段冗余时间
  396. redisService.expire(key, (limitTime * 60 * 60) + 20);
  397. conversationLimitResponse.setLimited(false);
  398. return conversationLimitResponse;
  399. }
  400. }
  401. /**
  402. * 获取指定用户ID在滑动窗口内的提问次数
  403. *
  404. * @param userToken 用户token
  405. * @return 滑动窗口内的请求次数
  406. */
  407. @Override
  408. public Long getConversationCount(String userToken, Long limitTime) {
  409. String key = RedisService.key.CHATGPT_CONVERSATION_LIMIT.getName() + ":" + userToken;
  410. long currentTimeMillis = System.currentTimeMillis();
  411. long windowStartMillis = currentTimeMillis - (limitTime * 60 * 60) * 1000;
  412. // 清除时间窗口之前的请求记录(可选,根据需要决定是否在此处清理过期记录)
  413. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  414. // 获取当前窗口内的请求次数
  415. Long currentSize = redisService.zCard(key);
  416. return currentSize != null ? currentSize : 0L;
  417. }
  418. /**
  419. * 获取指定车队ID在滑动窗口内的提问次数
  420. *
  421. * @param carId 车队ID
  422. * @return 滑动窗口内的请求次数
  423. */
  424. private Long getCarConversationCount(String carId, Long limitTime) {
  425. // 定义键名
  426. String key = RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId;
  427. long timestamp = System.currentTimeMillis();
  428. long windowStartMillis = timestamp - (limitTime * 60 * 60 * 1000);
  429. // 清除时间窗口之前的请求记录(可选,根据需要决定是否在此处清理过期记录)
  430. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  431. // 获取当前窗口内的请求次数
  432. Long currentSize = redisService.zCard(key);
  433. return currentSize != null ? currentSize : 0L;
  434. }
  435. @Override
  436. public ChatgptSession checkSession(String carId) {
  437. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getCarId, carId).eq(ChatgptSession::getIsCar, true).last(" limit 1"));
  438. if (chatgptSession == null) {
  439. throw BusinessRuntimeException.getInstance("车队不存在");
  440. }
  441. return chatgptSession;
  442. }
  443. private Long carOaiLimit(String carId) {
  444. if (redisService.hasKey("chatgpt:clears_in:" + carId)) {
  445. return redisService.getExpire("chatgpt:clears_in:" + carId);
  446. }
  447. return 0L;
  448. }
  449. @Override
  450. public Boolean checkCarAccount(long userId, Long relationId) {
  451. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  452. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  453. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  454. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  455. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  456. return true;
  457. } else {
  458. return false;
  459. }
  460. }
  461. @Override
  462. public ChatgptUser getCarChatGptUser(long userId, Long relationId) {
  463. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  464. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  465. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  466. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  467. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  468. return chatgptUser;
  469. }
  470. return null;
  471. }
  472. /**
  473. * 获取车队信息
  474. */
  475. @Override
  476. public Set<ChatgptCarInfoView> getCarInfoList(String userToken) {
  477. SearchResult<ChatGptUserConversationRecordHistoryView> search = beanSearcher.search(ChatGptUserConversationRecordHistoryView.class, MapUtils.builder().field("userToken", userToken).limit(0, 2).build());
  478. Set<ChatgptCarInfoView> res = search.getDataList().stream()
  479. .map((historyView) -> {
  480. ChatgptCarInfoView chatgptCarInfoView = buildChatgptCarInfoView(historyView.getCarId(), historyView.getCarName(), historyView.getIsPLus(), redisService.zScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), historyView.getCarId()));
  481. chatgptCarInfoView.setIsHistory(true);
  482. chatgptCarInfoView.setScore(Math.min(redisService.zScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), historyView.getCarId()), 100));
  483. return chatgptCarInfoView;
  484. }).collect(Collectors.toCollection(LinkedHashSet::new));
  485. Set<ChatgptCarInfoView> lowestScoreFleets = getLowestScoreFleets(10);
  486. res.addAll(lowestScoreFleets);
  487. return res;
  488. }
  489. // 更新体验并计算评分
  490. public void updateExperienceAndScore(String carId, boolean isHighLevel, long timestamp) {
  491. // 定义键名
  492. String key = isHighLevel ? RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId : RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId;
  493. double scoreToAdd = isHighLevel ? 2.0 : 1.0; // 分数更新规则
  494. // 更新体验数据
  495. redisService.zAdd(key, timestamp, String.valueOf(timestamp));
  496. // 更新车队评分
  497. redisService.zIncrementScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), carId, scoreToAdd);
  498. // 清理旧数据(可选)和重新计算评分(根据需要实现)
  499. cleanupOldExperiencesAndRecalculateScore(carId, timestamp);
  500. }
  501. // 清理旧数据和重新计算评分
  502. public void cleanupOldExperiencesAndRecalculateScore(String carId, long currentTimestamp) {
  503. long threeHoursAgo = currentTimestamp - (3 * 60 * 60 * 1000); // 3小时前的时间戳
  504. // 清理高级体验旧数据
  505. redisService.zRemoveRangeByScore(RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId, 0, threeHoursAgo);
  506. // 清理低级体验旧数据
  507. redisService.zRemoveRangeByScore(RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId, 0, threeHoursAgo);
  508. // 重新计算评分
  509. recalculateScore(carId, currentTimestamp);
  510. }
  511. // 重新计算指定车队的评分
  512. private void recalculateScore(String carId, long currentTimestamp) {
  513. // 实际应用中,你需要根据高级体验和低级体验的数量重新计算得分
  514. Double highExperienceScore = (double) redisService.zCount(RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId, currentTimestamp - (3 * 60 * 60 * 1000), currentTimestamp) * 2;
  515. Double lowExperienceScore = (double) redisService.zCount(RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId, currentTimestamp - (3 * 60 * 60 * 1000), currentTimestamp);
  516. double newScore = highExperienceScore + lowExperienceScore;
  517. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), newScore, carId);
  518. }
  519. // 获取得分最低的N个车队的方法
  520. public Set<ChatgptCarInfoView> getLowestScoreFleets(int count) {
  521. Set<ZSetOperations.TypedTuple<Object>> lowestScorecarIds;
  522. Long fleetsSize = redisService.zCard(RedisService.key.CHATGPT_CAR_SCORES.getName());
  523. // 构建ChatgptCarInfoView集合
  524. if (fleetsSize != null && fleetsSize > 10) {
  525. TASK_EXECUTOR.execute(() -> {
  526. initFleets(true);
  527. });
  528. } else {
  529. initFleets(false);
  530. }
  531. lowestScorecarIds = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, count - 1);
  532. Map<Object, Double> collect = lowestScorecarIds.stream().collect(Collectors.toMap(ZSetOperations.TypedTuple::getValue, ZSetOperations.TypedTuple::getScore));
  533. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(Wrappers.lambdaQuery(ChatgptSession.class).in(ChatgptSession::getCarId, collect.keySet()));
  534. return chatgptSessions.stream().map((chatgptSession)-> buildChatgptCarInfoView(chatgptSession.getCarId(),chatgptSession.getCarName(), chatgptSession.getIsPlus(), collect.get(chatgptSession.getCarId())))
  535. .sorted(Comparator.comparing(ChatgptCarInfoView::getScore)).collect(Collectors.toCollection(LinkedHashSet::new));
  536. }
  537. public void initFleets(Boolean flag) {
  538. LambdaQueryWrapper<ChatgptSession> wrapper = Wrappers.lambdaQuery(ChatgptSession.class);
  539. if (flag) {
  540. Set<ZSetOperations.TypedTuple<Object>> fleets = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, -1);
  541. List<Object> collect = fleets.stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList());
  542. wrapper.notIn(collect.size() > 0, ChatgptSession::getCarId, collect);
  543. }
  544. //如果存在未存在redis中的车辆则同步进 chatgpt:car:scores
  545. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(wrapper.eq(ChatgptSession::getIsCar, true));
  546. chatgptSessions.forEach((chatgptSession) -> {
  547. if (!redisService.checkValueExistsInZSet(RedisService.key.CHATGPT_CAR_SCORES.getName(), chatgptSession.getCarId())) {
  548. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0, chatgptSession.getCarId());
  549. }
  550. });
  551. }
  552. // 构建ChatgptCarInfoView对象
  553. private ChatgptCarInfoView buildChatgptCarInfoView(String carId, String carName, Integer isPlus, Double score) {
  554. // 在这里根据carId获取相关信息并填充到ChatgptCarInfoView对象中
  555. ChatgptCarInfoView view = new ChatgptCarInfoView();
  556. view.setCarId(carId);
  557. // 假设以下方法从Redis或其他服务获取数据
  558. view.setScore(Math.min(score,100));
  559. view.setStatus(score >= 50 ? "繁忙" : "空闲"); // 或“繁忙”
  560. view.setType(isPlus == 1 ? "plus" : "3.5");
  561. view.setGptLimit(40); // 假设值
  562. int use = getCarConversationCount(carId, 3L).intValue();
  563. view.setUse(Math.min(use, 40));
  564. Long aLong = carOaiLimit(carId);
  565. if (aLong != 0L) {
  566. view.setStatus("停运");
  567. view.setExpTime(new DateTime(System.currentTimeMillis() + aLong * 1000));
  568. }
  569. view.setCarName(carName);
  570. return view;
  571. }
  572. @Override
  573. public ChatGptUserView getUserInfo(long userId, Long relationId) {
  574. if (checkCarAccount(userId, relationId)) {
  575. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  576. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  577. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  578. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  579. return ChatGptUserView.builder()
  580. .skuName(goodsDonSku.getSubTitle())
  581. .expireTime(chatgptUser.getExpireTime())
  582. .limitNum(chatgptUser.getLimitNum())
  583. .limitTime(chatgptUser.getLimitTime())
  584. .use(getConversationCount(chatgptUser.getUserToken(), chatgptUser.getLimitTime()))
  585. .build();
  586. } else {
  587. throw BusinessRuntimeException.getInstance("您还未购买该车票");
  588. }
  589. }
  590. @Override
  591. public void genTitleSync(String conversationId, String carid, String userToken) {
  592. //同步对话
  593. if (!StringUtils.isAnyBlank(conversationId, carid, userToken)) {
  594. ChatgptUserConversationRecord chatgptUserConversationRecord = chatgptUserConversationRecordMapper.selectOne(Wrappers.lambdaQuery(ChatgptUserConversationRecord.class)
  595. .isNull(ChatgptUserConversationRecord::getConversationId)
  596. .eq(ChatgptUserConversationRecord::getCarId, carid)
  597. .eq(ChatgptUserConversationRecord::getUserToken, userToken)
  598. .orderByDesc(ChatgptUserConversationRecord::getId)
  599. .last(" limit 1"));
  600. chatgptUserConversationRecord.setConversationId(conversationId);
  601. chatgptUserConversationRecordMapper.updateById(chatgptUserConversationRecord);
  602. }
  603. }
  604. @Override
  605. public void carLimited(String carId, String userToken, Long expTime) {
  606. if(carId == null){
  607. if (StringUtils.isNotBlank(userToken)) {
  608. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken));
  609. if (chatgptUser != null && chatgptUser.getSessionId() != null) {
  610. ChatgptSession chatgptSession = chatgptSessionMapper.selectById(chatgptUser.getSessionId());
  611. if(chatgptSession != null){
  612. carId = chatgptSession.getCarId();
  613. }
  614. }
  615. }
  616. }
  617. redisService.set("chatgpt:clears_in:" + carId, expTime, expTime);
  618. }
  619. @PostConstruct
  620. public void init() {
  621. //如果存在未存在redis中的车辆则同步进 chatgpt:car:scores
  622. TASK_EXECUTOR.execute(() -> {
  623. Set<ZSetOperations.TypedTuple<Object>> lowestScorecarIds = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, -1);
  624. List<Object> collect = lowestScorecarIds.stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList());
  625. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(Wrappers.lambdaQuery(ChatgptSession.class).notIn(collect.size() > 0, ChatgptSession::getCarId, collect).eq(ChatgptSession::getIsCar, true));
  626. chatgptSessions.forEach((chatgptSession) -> {
  627. if (!redisService.checkValueExistsInZSet(RedisService.key.CHATGPT_CAR_SCORES.getName(), chatgptSession.getCarId())) {
  628. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0, chatgptSession.getCarId());
  629. }
  630. });
  631. });
  632. }
  633. }