ChatGptAccountServiceImpl.java 40 KB

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