ChatGptAccountServiceImpl.java 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. if(214610L == relationId){
  183. return "https://cdn.galaxydvd.com/login_token?access_token=" + chatgptUser.getUserToken();
  184. }
  185. return GPT_DOMAIN + "/login_token?access_token=" + chatgptUser.getUserToken();
  186. } else {
  187. throw BusinessRuntimeException.getInstance("服务器出了点问题");
  188. }
  189. }
  190. /**
  191. * 获取车队登录url
  192. *
  193. * @param userId
  194. * @param carId
  195. * @return
  196. */
  197. @Override
  198. public String getCarLoginUrl(Long userId, Long relationId, String carId) {
  199. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  200. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  201. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  202. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  203. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  204. return CAR_GPT_DOMAIN + "/auth/logintoken?carid=" + carId + "&usertoken=" + chatgptUser.getUserToken();
  205. } else {
  206. throw BusinessRuntimeException.getInstance("服务器出了点问题");
  207. }
  208. }
  209. /**
  210. * 获取车位信息
  211. *
  212. * @param userId
  213. * @param relationId
  214. * @return
  215. */
  216. private GroupsRelation getGroupsRelation(Long userId, Long relationId) {
  217. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  218. GroupsRelation groupsRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).in(GroupsRelation::getUserId, userIdList).eq(GroupsRelation::getId, relationId));
  219. if (groupsRelation == null) {
  220. throw BusinessRuntimeException.getInstance("车票不存在");
  221. }
  222. return groupsRelation;
  223. }
  224. /**
  225. * 获取车队信息
  226. *
  227. * @param groupsRelation
  228. * @return
  229. */
  230. private GroupsTrips getGroupsTrips(GroupsRelation groupsRelation) {
  231. GroupsTrips groupsTrips = groupsMapper.selectById(groupsRelation.getGroupsId());
  232. if (groupsTrips == null) {
  233. throw BusinessRuntimeException.getInstance("车队异常");
  234. }
  235. return groupsTrips;
  236. }
  237. private ChatgptUser getChatgptUser(Long userId, Long relationId, GroupsRelation groupsRelation, GroupsTrips groupsTrips, GoodsDonSku goodsDonSku) {
  238. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  239. User user = userMapper.selectById(userId);
  240. if (chatgptUser == null) {
  241. chatgptUser = createChatgptUser(groupsRelation, groupsTrips, user, goodsDonSku);
  242. } else {
  243. updateChatgptUser(groupsRelation, user, chatgptUser);
  244. }
  245. return chatgptUser;
  246. }
  247. private ChatgptUser getChatgptCarUser(Long userId, Long relationId, GroupsRelation groupsRelation, GoodsDonSku goodsDonSku) {
  248. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  249. User user = userMapper.selectById(userId);
  250. if (chatgptUser == null) {
  251. chatgptUser = createChatgptUser(groupsRelation, null, user, goodsDonSku);
  252. } else {
  253. updateChatgptUser(groupsRelation, user, chatgptUser);
  254. }
  255. return chatgptUser;
  256. }
  257. /**
  258. * 创建chatgptUser
  259. */
  260. private synchronized ChatgptUser createChatgptUser(GroupsRelation groupsRelation, GroupsTrips groupsTrips, User user, GoodsDonSku goodsDonSku) {
  261. ChatgptUser chatgptUser = new ChatgptUser();
  262. if (!goodsDonSku.getIsCar()) {
  263. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
  264. if (chatgptSession == null) {
  265. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  266. String officialSession = "";
  267. try {
  268. JSONObject loginResult = getLoginResult(account);
  269. if (StringUtils.isBlank(loginResult.getStr("accessToken"))) {
  270. throw BusinessRuntimeException.getInstance(loginResult.getStr("detail"));
  271. }
  272. officialSession = loginResult.toString();
  273. } catch (Exception e) {
  274. throw BusinessRuntimeException.getInstance("配置账号错误 msg: " + e.getMessage());
  275. }
  276. createChatgptSession(account, officialSession);
  277. chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getAccountId, groupsTrips.getAccountId()));
  278. }
  279. chatgptUser.setSessionId(chatgptSession.getId());
  280. }
  281. if (goodsDonSku.getIsCar()) {
  282. chatgptUser.setIsCar(true);
  283. chatgptUser.setLimitNum(goodsDonSku.getGptLimitNum());
  284. chatgptUser.setLimitTime(goodsDonSku.getGptLimitTime());
  285. }
  286. try {
  287. chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
  288. chatgptUser.setIsPlus(1);
  289. chatgptUser.setName(user.getNickname());
  290. chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
  291. chatgptUser.setRelationId(groupsRelation.getId());
  292. chatgptUser.setUserToken(UUID.randomUUID().toString());
  293. chatgptUserMapper.insert(chatgptUser);
  294. } catch (DuplicateKeyException e) {
  295. }
  296. return chatgptUser;
  297. }
  298. private void updateChatgptUser(GroupsRelation groupsRelation, User user, ChatgptUser chatgptUser) {
  299. chatgptUser.setName(user.getNickname());
  300. chatgptUser.setImg(getWxImg(user.getHeadimgurl(), user));
  301. chatgptUser.setExpireTime(groupsRelation.getExpiryTime());
  302. chatgptUserMapper.updateById(chatgptUser);
  303. }
  304. /**
  305. * 更换wx头像至oss
  306. */
  307. private String getWxImg(String headimgurl, User user) {
  308. if (headimgurl.contains("thirdwx.qlogo.cn")) {
  309. try {
  310. byte[] body = HttpUtil.downloadBytes(headimgurl);
  311. Path tempFile = Files.createTempFile("wxheadimg-" + user.getId(), ".jpeg");
  312. try (FileImageOutputStream imageOutput = new FileImageOutputStream(tempFile.toFile())) {
  313. imageOutput.write(body, 0, body.length);
  314. }
  315. Map<String, Object> paramMap = new HashMap<>();
  316. paramMap.put("file", tempFile.toFile());
  317. JSONObject result = JSONUtil.parseObj(HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap));
  318. return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
  319. } catch (Exception ex) {
  320. log.error("上传微信头像错误!msg:{}", StringUtil.getErrorText(ex));
  321. return "./avatars.png";
  322. }
  323. } else {
  324. return user.getHeadimgurl();
  325. }
  326. }
  327. @Override
  328. public ChatgptUser findByUserTokenAndExpireTimeAfter(String userToken, LocalDateTime now) {
  329. return chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken).gt(ChatgptUser::getExpireTime, now));
  330. }
  331. @Override
  332. public void saveConversationRecord(String userToken, ConversationRequest conversationRequest) {
  333. LambdaQueryWrapper<ChatgptSession> wrapper = Wrappers.lambdaQuery(ChatgptSession.class);
  334. if(StringUtils.isNotBlank(conversationRequest.getCarId())){
  335. wrapper.eq(ChatgptSession::getCarId, conversationRequest.getCarId());
  336. }else {
  337. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken));
  338. if (chatgptUser.getSessionId() != null) {
  339. wrapper.eq(ChatgptSession::getId, chatgptUser.getSessionId());
  340. }
  341. }
  342. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(wrapper);
  343. ChatgptUserConversationRecord chatgptUserConversationRecord = new ChatgptUserConversationRecord();
  344. chatgptUserConversationRecord.setUserToken(userToken);
  345. chatgptUserConversationRecord.setCarId(chatgptSession.getCarId());
  346. chatgptUserConversationRecord.setCarName(chatgptSession.getCarName());
  347. if (StringUtils.isBlank(conversationRequest.getConversation_id())) {
  348. chatgptUserConversationRecord.setMessageId(conversationRequest.getMessages().get(0).getId());
  349. } else {
  350. chatgptUserConversationRecord.setConversationId(conversationRequest.getConversation_id());
  351. }
  352. chatgptUserConversationRecord.setModel(conversationRequest.getModel());
  353. chatgptUserConversationRecordMapper.insert(chatgptUserConversationRecord);
  354. if(StringUtils.isNotBlank(chatgptSession.getCarId())){
  355. updateExperienceAndScore(chatgptSession.getCarId(), !"text-davinci-002-render-sha".equals(conversationRequest.getModel()), System.currentTimeMillis());
  356. }
  357. }
  358. @Override
  359. public ConversationLimitResponse conversationLimit(String userToken, String model, String carId, ChatgptUser chatgptUser, Boolean isCar) {
  360. ConversationLimitResponse conversationLimitResponse = new ConversationLimitResponse();
  361. conversationLimitResponse.setLimited(false);
  362. if (!"text-davinci-002-render-sha".equals(model)) {
  363. //如果不为车队 直接返回
  364. if (chatgptUser.getIsCar()) {
  365. conversationLimitResponse = isConversationAllowed(userToken, chatgptUser.getLimitNum(), chatgptUser.getLimitTime());
  366. }
  367. }
  368. return conversationLimitResponse;
  369. }
  370. /**
  371. * 检查是否允许进行进行提问
  372. *
  373. * @param userToken 用户token
  374. * @return true 如果允许请求,false 如果请求被限制
  375. */
  376. public ConversationLimitResponse isConversationAllowed(String userToken, int limit, Long limitTime) {
  377. String key = RedisService.key.CHATGPT_CONVERSATION_LIMIT.getName() + ":" + userToken;
  378. long currentTimeMillis = System.currentTimeMillis();
  379. long windowStartMillis = currentTimeMillis - (limitTime * 60 * 60) * 1000;
  380. ConversationLimitResponse conversationLimitResponse = new ConversationLimitResponse();
  381. // 清除时间窗口之前的请求记录
  382. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  383. Long currentSize = redisService.zCard(key);
  384. if (currentSize != null && currentSize >= limit) {
  385. // 如果当前请求次数超过限制,则拒绝请求
  386. Set<Object> times = redisService.zRangeByScore(key, 0, currentTimeMillis, 0, 1);
  387. Long oldestTime = (Long) times.stream().findFirst().orElse(null);
  388. if (oldestTime != null) {
  389. // 下一次可用时间是最早请求时间之后的3小时
  390. long nextAvailableTime = oldestTime + (limitTime * 60 * 60 * 1000);
  391. conversationLimitResponse.setNextAvailableTime(nextAvailableTime);
  392. }
  393. conversationLimitResponse.setLimited(true);
  394. return conversationLimitResponse;
  395. } else {
  396. // 如果未超过限制,记录当前请求的时间戳
  397. redisService.zAdd(key, currentTimeMillis, currentTimeMillis);
  398. // 设置ZSet的过期时间,窗口大小加上一段冗余时间
  399. redisService.expire(key, (limitTime * 60 * 60) + 20);
  400. conversationLimitResponse.setLimited(false);
  401. return conversationLimitResponse;
  402. }
  403. }
  404. /**
  405. * 获取指定用户ID在滑动窗口内的提问次数
  406. *
  407. * @param userToken 用户token
  408. * @return 滑动窗口内的请求次数
  409. */
  410. @Override
  411. public Long getConversationCount(String userToken, Long limitTime) {
  412. String key = RedisService.key.CHATGPT_CONVERSATION_LIMIT.getName() + ":" + userToken;
  413. long currentTimeMillis = System.currentTimeMillis();
  414. long windowStartMillis = currentTimeMillis - (limitTime * 60 * 60) * 1000;
  415. // 清除时间窗口之前的请求记录(可选,根据需要决定是否在此处清理过期记录)
  416. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  417. // 获取当前窗口内的请求次数
  418. Long currentSize = redisService.zCard(key);
  419. return currentSize != null ? currentSize : 0L;
  420. }
  421. /**
  422. * 获取指定车队ID在滑动窗口内的提问次数
  423. *
  424. * @param carId 车队ID
  425. * @return 滑动窗口内的请求次数
  426. */
  427. private Long getCarConversationCount(String carId, Long limitTime) {
  428. // 定义键名
  429. String key = RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId;
  430. long timestamp = System.currentTimeMillis();
  431. long windowStartMillis = timestamp - (limitTime * 60 * 60 * 1000);
  432. // 清除时间窗口之前的请求记录(可选,根据需要决定是否在此处清理过期记录)
  433. redisService.zRemoveRangeByScore(key, 0, windowStartMillis);
  434. // 获取当前窗口内的请求次数
  435. Long currentSize = redisService.zCard(key);
  436. return currentSize != null ? currentSize : 0L;
  437. }
  438. @Override
  439. public ChatgptSession checkSession(String carId) {
  440. ChatgptSession chatgptSession = chatgptSessionMapper.selectOne(Wrappers.lambdaQuery(ChatgptSession.class).eq(ChatgptSession::getCarId, carId).eq(ChatgptSession::getIsCar, true).last(" limit 1"));
  441. if (chatgptSession == null) {
  442. throw BusinessRuntimeException.getInstance("车队不存在");
  443. }
  444. return chatgptSession;
  445. }
  446. private Long carOaiLimit(String carId) {
  447. if (redisService.hasKey("chatgpt:clears_in:" + carId)) {
  448. return redisService.getExpire("chatgpt:clears_in:" + carId);
  449. }
  450. return 0L;
  451. }
  452. @Override
  453. public Boolean checkCarAccount(long userId, Long relationId) {
  454. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  455. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  456. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  457. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  458. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  459. return true;
  460. } else {
  461. return false;
  462. }
  463. }
  464. @Override
  465. public ChatgptUser getCarChatGptUser(long userId, Long relationId) {
  466. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  467. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  468. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  469. if (goodsDonSku != null && goodsDonSku.getIsMirror() && goodsDonSku.getIsCar()) {
  470. ChatgptUser chatgptUser = getChatgptCarUser(userId, relationId, groupsRelation, goodsDonSku);
  471. return chatgptUser;
  472. }
  473. return null;
  474. }
  475. /**
  476. * 获取车队信息
  477. */
  478. @Override
  479. public Set<ChatgptCarInfoView> getCarInfoList(String userToken) {
  480. SearchResult<ChatGptUserConversationRecordHistoryView> search = beanSearcher.search(ChatGptUserConversationRecordHistoryView.class, MapUtils.builder().field("userToken", userToken).limit(0, 2).build());
  481. Set<ChatgptCarInfoView> res = search.getDataList().stream()
  482. .map((historyView) -> {
  483. ChatgptCarInfoView chatgptCarInfoView = buildChatgptCarInfoView(historyView.getCarId(), historyView.getCarName(), historyView.getIsPLus(), redisService.zScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), historyView.getCarId()));
  484. chatgptCarInfoView.setIsHistory(true);
  485. chatgptCarInfoView.setScore(Math.min(redisService.zScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), historyView.getCarId()), 100));
  486. return chatgptCarInfoView;
  487. }).collect(Collectors.toCollection(LinkedHashSet::new));
  488. Set<ChatgptCarInfoView> lowestScoreFleets = getLowestScoreFleets(10);
  489. res.addAll(lowestScoreFleets);
  490. return res;
  491. }
  492. // 更新体验并计算评分
  493. public void updateExperienceAndScore(String carId, boolean isHighLevel, long timestamp) {
  494. // 定义键名
  495. String key = isHighLevel ? RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId : RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId;
  496. double scoreToAdd = isHighLevel ? 2.0 : 1.0; // 分数更新规则
  497. // 更新体验数据
  498. redisService.zAdd(key, timestamp, String.valueOf(timestamp));
  499. // 更新车队评分
  500. redisService.zIncrementScore(RedisService.key.CHATGPT_CAR_SCORES.getName(), carId, scoreToAdd);
  501. // 清理旧数据(可选)和重新计算评分(根据需要实现)
  502. cleanupOldExperiencesAndRecalculateScore(carId, timestamp);
  503. }
  504. // 清理旧数据和重新计算评分
  505. public void cleanupOldExperiencesAndRecalculateScore(String carId, long currentTimestamp) {
  506. long threeHoursAgo = currentTimestamp - (3 * 60 * 60 * 1000); // 3小时前的时间戳
  507. // 清理高级体验旧数据
  508. redisService.zRemoveRangeByScore(RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId, 0, threeHoursAgo);
  509. // 清理低级体验旧数据
  510. redisService.zRemoveRangeByScore(RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId, 0, threeHoursAgo);
  511. // 重新计算评分
  512. recalculateScore(carId, currentTimestamp);
  513. }
  514. // 重新计算指定车队的评分
  515. private void recalculateScore(String carId, long currentTimestamp) {
  516. // 实际应用中,你需要根据高级体验和低级体验的数量重新计算得分
  517. Double highExperienceScore = (double) redisService.zCount(RedisService.key.CHATGPT_CAR_HIGH_CHAT.getName() + carId, currentTimestamp - (3 * 60 * 60 * 1000), currentTimestamp) * 2;
  518. Double lowExperienceScore = (double) redisService.zCount(RedisService.key.CHATGPT_CAR_LOW_CHAT.getName() + carId, currentTimestamp - (3 * 60 * 60 * 1000), currentTimestamp);
  519. double newScore = highExperienceScore + lowExperienceScore;
  520. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), newScore, carId);
  521. }
  522. // 获取得分最低的N个车队的方法
  523. public Set<ChatgptCarInfoView> getLowestScoreFleets(int count) {
  524. Set<ZSetOperations.TypedTuple<Object>> lowestScorecarIds;
  525. Long fleetsSize = redisService.zCard(RedisService.key.CHATGPT_CAR_SCORES.getName());
  526. // 构建ChatgptCarInfoView集合
  527. if (fleetsSize != null && fleetsSize > 10) {
  528. TASK_EXECUTOR.execute(() -> {
  529. initFleets(true);
  530. });
  531. } else {
  532. initFleets(false);
  533. }
  534. lowestScorecarIds = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, count - 1);
  535. Map<Object, Double> collect = lowestScorecarIds.stream().collect(Collectors.toMap(ZSetOperations.TypedTuple::getValue, ZSetOperations.TypedTuple::getScore));
  536. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(Wrappers.lambdaQuery(ChatgptSession.class).in(ChatgptSession::getCarId, collect.keySet()));
  537. return chatgptSessions.stream().map((chatgptSession)-> buildChatgptCarInfoView(chatgptSession.getCarId(),chatgptSession.getCarName(), chatgptSession.getIsPlus(), collect.get(chatgptSession.getCarId())))
  538. .sorted(Comparator.comparing(ChatgptCarInfoView::getScore)).collect(Collectors.toCollection(LinkedHashSet::new));
  539. }
  540. public void initFleets(Boolean flag) {
  541. LambdaQueryWrapper<ChatgptSession> wrapper = Wrappers.lambdaQuery(ChatgptSession.class);
  542. if (flag) {
  543. Set<ZSetOperations.TypedTuple<Object>> fleets = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, -1);
  544. List<Object> collect = fleets.stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList());
  545. wrapper.notIn(collect.size() > 0, ChatgptSession::getCarId, collect);
  546. }
  547. //如果存在未存在redis中的车辆则同步进 chatgpt:car:scores
  548. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(wrapper.eq(ChatgptSession::getIsCar, true));
  549. chatgptSessions.forEach((chatgptSession) -> {
  550. if (!redisService.checkValueExistsInZSet(RedisService.key.CHATGPT_CAR_SCORES.getName(), chatgptSession.getCarId())) {
  551. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0, chatgptSession.getCarId());
  552. }
  553. });
  554. }
  555. // 构建ChatgptCarInfoView对象
  556. private ChatgptCarInfoView buildChatgptCarInfoView(String carId, String carName, Integer isPlus, Double score) {
  557. // 在这里根据carId获取相关信息并填充到ChatgptCarInfoView对象中
  558. ChatgptCarInfoView view = new ChatgptCarInfoView();
  559. view.setCarId(carId);
  560. // 假设以下方法从Redis或其他服务获取数据
  561. view.setScore(Math.min(score,100));
  562. view.setStatus(score >= 50 ? "繁忙" : "空闲"); // 或“繁忙”
  563. view.setType(isPlus == 1 ? "plus" : "3.5");
  564. view.setGptLimit(40); // 假设值
  565. int use = getCarConversationCount(carId, 3L).intValue();
  566. view.setUse(Math.min(use, 40));
  567. Long aLong = carOaiLimit(carId);
  568. if (aLong != 0L) {
  569. view.setStatus("停运");
  570. view.setExpTime(new DateTime(System.currentTimeMillis() + aLong * 1000));
  571. }
  572. view.setCarName(carName);
  573. return view;
  574. }
  575. @Override
  576. public ChatGptUserView getUserInfo(long userId, Long relationId) {
  577. if (checkCarAccount(userId, relationId)) {
  578. GroupsRelation groupsRelation = getGroupsRelation(userId, relationId);
  579. GroupsTrips groupsTrips = getGroupsTrips(groupsRelation);
  580. GoodsDonSku goodsDonSku = skuMapper.selectById(groupsTrips.getSkuId());
  581. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, relationId));
  582. return ChatGptUserView.builder()
  583. .skuName(goodsDonSku.getSubTitle())
  584. .expireTime(chatgptUser.getExpireTime())
  585. .limitNum(chatgptUser.getLimitNum())
  586. .limitTime(chatgptUser.getLimitTime())
  587. .use(getConversationCount(chatgptUser.getUserToken(), chatgptUser.getLimitTime()))
  588. .build();
  589. } else {
  590. throw BusinessRuntimeException.getInstance("您还未购买该车票");
  591. }
  592. }
  593. @Override
  594. public void genTitleSync(String conversationId, String carid, String userToken) {
  595. //同步对话
  596. if (!StringUtils.isAnyBlank(conversationId, carid, userToken)) {
  597. ChatgptUserConversationRecord chatgptUserConversationRecord = chatgptUserConversationRecordMapper.selectOne(Wrappers.lambdaQuery(ChatgptUserConversationRecord.class)
  598. .isNull(ChatgptUserConversationRecord::getConversationId)
  599. .eq(ChatgptUserConversationRecord::getCarId, carid)
  600. .eq(ChatgptUserConversationRecord::getUserToken, userToken)
  601. .orderByDesc(ChatgptUserConversationRecord::getId)
  602. .last(" limit 1"));
  603. chatgptUserConversationRecord.setConversationId(conversationId);
  604. chatgptUserConversationRecordMapper.updateById(chatgptUserConversationRecord);
  605. }
  606. }
  607. @Override
  608. public void carLimited(String carId, String userToken, Long expTime) {
  609. if(carId == null){
  610. if (StringUtils.isNotBlank(userToken)) {
  611. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getUserToken, userToken));
  612. if (chatgptUser != null && chatgptUser.getSessionId() != null) {
  613. ChatgptSession chatgptSession = chatgptSessionMapper.selectById(chatgptUser.getSessionId());
  614. if(chatgptSession != null){
  615. carId = chatgptSession.getCarId();
  616. }
  617. }
  618. }
  619. }
  620. redisService.set("chatgpt:clears_in:" + carId, expTime, expTime);
  621. }
  622. @PostConstruct
  623. public void init() {
  624. //如果存在未存在redis中的车辆则同步进 chatgpt:car:scores
  625. TASK_EXECUTOR.execute(() -> {
  626. Set<ZSetOperations.TypedTuple<Object>> lowestScorecarIds = redisService.zRangeWithScores(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0L, -1);
  627. List<Object> collect = lowestScorecarIds.stream().map(ZSetOperations.TypedTuple::getValue).collect(Collectors.toList());
  628. List<ChatgptSession> chatgptSessions = chatgptSessionMapper.selectList(Wrappers.lambdaQuery(ChatgptSession.class).notIn(collect.size() > 0, ChatgptSession::getCarId, collect).eq(ChatgptSession::getIsCar, true));
  629. chatgptSessions.forEach((chatgptSession) -> {
  630. if (!redisService.checkValueExistsInZSet(RedisService.key.CHATGPT_CAR_SCORES.getName(), chatgptSession.getCarId())) {
  631. redisService.zAdd(RedisService.key.CHATGPT_CAR_SCORES.getName(), 0, chatgptSession.getCarId());
  632. }
  633. });
  634. });
  635. }
  636. }