sessions.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. /**
  2. * 会话模型。
  3. */
  4. "use strict";
  5. let RedisClient = require('../../repository/redis/redis.client.js');
  6. let RedisModel = require('./../redis.model.js');
  7. let ModelUtil = require('../../util/model.util');
  8. let Messages = require('../messages/messages');
  9. let Users = require('../user/users');
  10. let Participants = require('./Participants');
  11. let SessionRepo = require('../../repository/mysql/session.repo');
  12. let ParticipantRepo = require('../../repository/mysql/participant.repo');
  13. let WechatClient = require("../client/wechat.client.js");
  14. let AppClient = require("../client/app.client.js");
  15. let configFile = require('../../include/commons').CONFIG_FILE;
  16. let config = require('../../resources/config/' + configFile);
  17. let redis = RedisClient.redisClient().connection;
  18. let logger = require('../../util/log.js');
  19. let mongoose = require('mongoose');
  20. let async = require("async");
  21. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  22. const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
  23. const STICKY_SESSION_BASE_SCORE = require('../../include/commons').STICKY_SESSION_BASE_SCORE;
  24. const SESSION_BUSINESS_TYPE = require('../../include/commons').SESSION_BUSINESS_TYPE;
  25. class Sessions extends RedisModel {
  26. constructor() {
  27. super();
  28. }
  29. /**
  30. * 创建会话。会话的ID来源:
  31. * MUC:患者的ID
  32. * P2P:对成员的ID排序后,取hash值
  33. * GROUP:团队的ID
  34. *
  35. * @param sessionId
  36. * @param name 会话名称
  37. * @param type 会话类型
  38. * @param participantArray 会话成员
  39. * @param handler 回调,仅MUC模式使用
  40. */
  41. createSession(sessionId, name, type, participantArray, handler) {
  42. let self = this;
  43. if (type == SESSION_TYPES.P2P||type==SESSION_TYPES.SYSTEM) {
  44. var participantIdArray = [];
  45. for (let i in participantArray) {
  46. participantIdArray.push(participantArray[i].split(":")[0]);
  47. }
  48. if (participantIdArray.length != 2) {
  49. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "P2P session only allow 2 participants."});
  50. return false;
  51. }
  52. ParticipantRepo.findSessionIdByParticipantIds(participantIdArray[0], participantIdArray[1], function (err, res) {
  53. sessionId = res;
  54. callBusinessType(sessionId);
  55. });
  56. } else {
  57. callBusinessType(sessionId);
  58. }
  59. var businessType = SESSION_BUSINESS_TYPE.DOCTOR;
  60. function callBusinessType(sessionId) {
  61. for (var j = 0; j < participantArray.length; j++)
  62. callIsPatient(j, participantArray.length);
  63. }
  64. function callIsPatient(j, length) {
  65. Users.isPatientId(participantArray[j], function (isPatient) {
  66. if (isPatient) {
  67. businessType = SESSION_BUSINESS_TYPE.PATIENT
  68. }
  69. if (length - 1 == j || businessType == SESSION_BUSINESS_TYPE.PATIENT) {
  70. callCreate(sessionId, businessType);
  71. }
  72. })
  73. }
  74. function callCreate(sessionId, businessType) {
  75. SessionRepo.findOne(sessionId, function (err, res) {
  76. if (res.length > 0) {
  77. let session = res[0];
  78. ModelUtil.emitOK(self.eventEmitter, {
  79. id: session.id,
  80. name: session.name,
  81. type: session.type,
  82. business_type: session.business_type || businessType,
  83. create_date: session.create_date
  84. });
  85. return;
  86. }
  87. let createDate = new Date();
  88. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  89. // 保存会话及成员至MySQL中
  90. self.saveSessionToMysql(sessionId, name, type, createDate, businessType, function (err, res) {
  91. Participants.saveParticipantsToMysql(sessionId, participantArray, function (err, res) {
  92. if (err) {
  93. ModelUtil.emitError(self.eventEmitter, err.message);
  94. return;
  95. }
  96. // 保存会话及成员至Redis中,并更新会话的最后状态
  97. let isMucSession = SESSION_TYPES.MUC == type;
  98. let message = {
  99. sender_id: "System",
  100. sender_name: "System",
  101. content_type: 1,
  102. content: "",
  103. timestamp: createDate
  104. };
  105. Messages.updateLastContent(sessionKey, type, name, message);
  106. Participants.saveParticipantsToRedis(sessionId, participantArray, createDate, function (res) {
  107. if (isMucSession&&handler) {
  108. handler(true, sessionId);
  109. } else {
  110. ModelUtil.emitOK(self.eventEmitter, {id: sessionId});
  111. }
  112. });
  113. });
  114. });
  115. });
  116. }
  117. }
  118. /**
  119. * 保存session到MySQL
  120. * @param sessionId
  121. * @param name
  122. * @param type
  123. * @param createDate
  124. * @param handler
  125. */
  126. saveSessionToMysql(sessionId, name, type, createDate, businessType, handler) {
  127. SessionRepo.saveSession(sessionId, name, type, createDate, businessType, handler);
  128. }
  129. /**
  130. * 获取某个用户的全部session列表
  131. * @param userId
  132. * @param handler
  133. */
  134. getUserSessionsFromMysql(userId, handler) {
  135. SessionRepo.findAll(userId, handler);
  136. }
  137. /**
  138. * 获取session单个对象
  139. * @param sessionId
  140. * @param handler
  141. */
  142. getSessions(sessionId, handler) {
  143. SessionRepo.findOne(sessionId, handler);
  144. }
  145. /**
  146. * 根据用户ID获取用户的session列表
  147. * @param userId
  148. * @param page
  149. * @param size
  150. */
  151. getUserSessions(userId, page, size, businessType) {
  152. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  153. let self = this;
  154. if (page > 0) {
  155. if (page == 1) {
  156. page = 0;
  157. }
  158. page = page + page * size;
  159. }
  160. async.waterfall([
  161. // 获取会话ID列表
  162. function (callback) {
  163. redis.zrevrangeAsync(userSessionKey, page, size)
  164. .then(function (sessionIds) {
  165. if (sessionIds.length == 0) {
  166. ModelUtil.emitOK(self.eventEmitter, []);
  167. return;
  168. }
  169. callback(null, sessionIds);
  170. })
  171. },
  172. // 遍历会话
  173. function (sessionIds, callback) {
  174. let sessionList = [];
  175. sessionIds.forEach(function (sessionId) {
  176. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  177. let participantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  178. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  179. redis.multi()
  180. .hgetall(sessionKey) // 会话实体
  181. .hget(participantsRoleKey, userId) // 用户在此会话中的角色
  182. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  183. .execAsync()
  184. .then(function (res) {
  185. let session = res[0];
  186. let role = res[1];
  187. let lastFetchTime = res[2];
  188. if (businessType && businessType != session.business_type) {
  189. logger.info("businessType:" + businessType + "<>" + session.business_type);
  190. } else {
  191. // 计算未读消息数
  192. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  193. redis.zcountAsync(messagesByTimestampKey, lastFetchTime, new Date().getTime())
  194. .then(function (count) {
  195. sessionList.push({
  196. id: sessionId,
  197. name: session.name,
  198. create_date: session.create_date,
  199. last_content_type: session.last_content_type,
  200. last_content: session.last_content,
  201. sender_id: session.sender_id,
  202. type: session.type,
  203. sender_name: session.sender_name,
  204. unread_count: count,
  205. business_type: session.business_type,
  206. my_role: role
  207. });
  208. if (sessionId === sessionIds[sessionIds.length - 1]) {
  209. ModelUtil.emitOK(self.eventEmitter, sessionList);
  210. }
  211. })
  212. }
  213. ;
  214. })
  215. .catch(function (err) {
  216. ModelUtil.emitError(self.eventEmitter, "Get sessions failed: " + err);
  217. });
  218. });
  219. }
  220. ]);
  221. }
  222. /**
  223. * 获取会话消息。全部,不管已读/未读状态。
  224. *
  225. * @param sessionId 会话ID
  226. * @param userId 拉取消息的人
  227. * @param page 第几页
  228. * @param pagesize 分页数量
  229. * @param start_msg_id 消息会话最新的一条消息的ID
  230. * @param end_msg_id 消息会话刚开始的消息ID
  231. */
  232. getMessages(sessionId, user, start_msg_id, end_msg_id, page, pagesize, isoffset) {
  233. let self = this;
  234. let message_timestamp_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  235. if (!start_msg_id && !end_msg_id) {
  236. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  237. if (res.length == 0) {
  238. ModelUtil.emitOK(self.eventEmitter, res);
  239. return;
  240. }
  241. start_msg_id = res[0];
  242. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  243. if (res.length == 0) {
  244. ModelUtil.emitOK(self.eventEmitter, res);
  245. return;
  246. }
  247. end_msg_id = res[0];
  248. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  249. if (err) {
  250. logger.error("getMessagesByPage error" + err);
  251. ModelUtil.emitError(self.eventEmitter, err, err);
  252. } else {
  253. ModelUtil.emitOK(self.eventEmitter, res);
  254. }
  255. })
  256. })
  257. })
  258. } else if (!start_msg_id) {
  259. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  260. if (res.length == 0) {
  261. ModelUtil.emitOK(self.eventEmitter, res);
  262. return;
  263. }
  264. start_msg_id = res[0];
  265. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  266. if (err) {
  267. logger.error("getMessagesByPage error" + err);
  268. ModelUtil.emitError(self.eventEmitter, err, err);
  269. } else {
  270. ModelUtil.emitOK(self.eventEmitter, res);
  271. }
  272. })
  273. })
  274. } else if (!end_msg_id) {
  275. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  276. if (res.length == 0) {
  277. ModelUtil.emitOK(self.eventEmitter, res);
  278. return;
  279. }
  280. end_msg_id = res[0];
  281. self.getMessagesByPage(sessionId, user, start_msg_id, end_msg_id, page, pagesize, isoffset, function (err, res) {
  282. if (err) {
  283. logger.error("getMessagesByPage error" + err);
  284. ModelUtil.emitError(self.eventEmitter, err, err);
  285. } else {
  286. ModelUtil.emitOK(self.eventEmitter, res);
  287. }
  288. })
  289. })
  290. } else {
  291. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  292. if (err) {
  293. logger.error("getMessagesByPage error" + err);
  294. ModelUtil.emitError(self.eventEmitter, err, err);
  295. } else {
  296. ModelUtil.emitOK(self.eventEmitter, res);
  297. }
  298. })
  299. }
  300. }
  301. /**
  302. * 分页获取会话消息。
  303. *
  304. * @param sessionId 必选。会话ID
  305. * @param userId 必选。用户ID
  306. * @param startMsgId 必选。会话的的起始消息ID,作为检索的起始依据
  307. * @param endMsgId 必选。会话中的结束消息ID
  308. * @param page 必选。页码
  309. * @param size 必选。页面大小
  310. * @param handler 必选。回调
  311. */
  312. getMessagesByPage(sessionId, userId, startMsgId, endMsgId, page, size, isoffset, handler) {
  313. let messagesTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  314. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  315. let participants = new Participants();
  316. let offset = (page - 1 < 0 ? 0 : page - 1) * size;
  317. let count = size;
  318. if (page > 1 || isoffset == 1) {
  319. offset += 1; // 翻页由于闭区间,需跳过本身数据
  320. }
  321. participants.existsParticipant(sessionId, userId, function (err, res) {
  322. if (!res) {
  323. handler(Error("User not found in session " + sessionId), null);
  324. } else {
  325. //将消息ID转换成分值
  326. redis.multi()
  327. .zscore(messagesTimestampKey, startMsgId)
  328. .zscore(messagesTimestampKey, endMsgId)
  329. .execAsync()
  330. .then(function (res) {
  331. let startMsgScore = res[1];
  332. let endMsgScore = res[0];
  333. if (startMsgScore == null || endMsgScore == null || startMsgScore == endMsgScore) {
  334. handler(null, []);
  335. return;
  336. }
  337. // 从消息时间表中过滤出要获取的消息ID列表,倒序取出消息
  338. redis.zrevrangebyscoreAsync(messagesTimestampKey, startMsgScore, endMsgScore, "limit", offset, count)
  339. .then(function (res) {
  340. if (res.length == 0) {
  341. handler(null, []);
  342. return;
  343. }
  344. redis.hmgetAsync(messagesKey, res).then(function (messages) {
  345. handler(null, messages);
  346. }).then(function () {
  347. Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
  348. })
  349. })
  350. .catch(function (res) {
  351. handler(res, false);
  352. })
  353. })
  354. }
  355. })
  356. }
  357. /**
  358. * 获取所有会话的未读消息数。
  359. */
  360. getAllSessionsUnreadMessageCount(userId) {
  361. let self = this;
  362. ModelUtil.emitError(self.eventEmitter, {message: "not implemented."}, null);
  363. }
  364. /**
  365. * 获取会话的未读消息数。根据成员最后一次获取消息的时候与当前时间。
  366. *
  367. * @param sessionId
  368. * @param userId
  369. */
  370. getSessionUnreadMessageCount(sessionId, userId) {
  371. let self = this;
  372. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  373. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  374. async.waterfall([
  375. // 此成员最后获取消息的时间
  376. function (callback) {
  377. redis.zscoreAsync(participantsKey, userId)
  378. .then(function (lastFetchTime) {
  379. callback(null, lastFetchTime);
  380. })
  381. },
  382. // 计算最后获取消息的时间之后到现在有多少条消息
  383. function (lastFetchTime, callback) {
  384. if (!lastFetchTime) lastFetchTime = 0;
  385. let now = new Date().getTime();
  386. redis.zcountAsync(messagesByTimestampKey, lastFetchTime, now)
  387. .then(function (count) {
  388. ModelUtil.emitOK(self.eventEmitter, {count: count});
  389. })
  390. }
  391. ], function (err, res) {
  392. if (err) {
  393. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  394. }
  395. });
  396. }
  397. /**
  398. * 获取会话未读消息数。根据成员最后一次获取消息的时候与当前时间。
  399. */
  400. getSessionUnreadMessages(sessionId, userId) {
  401. let self = this;
  402. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  403. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  404. async.waterfall([
  405. // 此成员最后获取消息的时间
  406. function (callback) {
  407. redis.zscoreAsync(participantsKey, userId)
  408. .then(function (lastFetchTime) {
  409. callback(null, lastFetchTime);
  410. })
  411. },
  412. // 最后获取消息的时间之后到现在的消息ID列表
  413. function (lastFetchTime, callback) {
  414. if (!lastFetchTime) lastFetchTime = 0;
  415. let now = new Date().getTime();
  416. redis.zrangebyscoreAsync(messagesByTimestampKey, lastFetchTime, now)
  417. .then(function (messageIds) {
  418. callback(null, messageIds);
  419. })
  420. },
  421. // 获取消息
  422. function (messageIds, callback) {
  423. if (messageIds.length == 0) {
  424. ModelUtil.emitOK(self.eventEmitter, []);
  425. return;
  426. }
  427. let startMsgId = messageIds[0];
  428. let endMsgId = messageIds[messageIds.length - 1];
  429. self.getMessagesByPage(sessionId, userId, startMsgId, endMsgId, 0, messageIds.length, 0, function (err, res) {
  430. if (err) {
  431. ModelUtil.emitError(self.eventEmitter, err.message);
  432. return;
  433. }
  434. ModelUtil.emitOK(self.eventEmitter, res);
  435. });
  436. }
  437. ], function (err, res) {
  438. if (err) {
  439. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  440. }
  441. });
  442. }
  443. /**
  444. * 保存消息。
  445. *
  446. * 也可以根据议题保存消息,但最终还是保存到与会话对象。
  447. *
  448. * see also: saveMessageByTopic
  449. *
  450. * @param message
  451. * @param sessionId
  452. */
  453. saveMessageBySession(sessionId, message) {
  454. let self = this;
  455. let messages = new Messages();
  456. let participants = new Participants();
  457. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  458. let messageId = mongoose.Types.ObjectId().toString();
  459. message.id = messageId;
  460. // 检查会话中是否存在此成员
  461. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  462. if (err) {
  463. ModelUtil.emitError(self.eventEmitter, "Check session paticipant failed: ", err);
  464. return;
  465. }
  466. if (res) {
  467. redis.hmgetAsync(sessionKey, ["type", "name"]).then(function (res) {
  468. let sessionType = res[0];
  469. if (sessionType == null) {
  470. ModelUtil.emitError(self.eventEmitter, "Session with id " + sessionId + " not found.");
  471. return;
  472. }
  473. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  474. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  475. messages.saveMessageToMysql(sessionId, sessionType, messageId, message, function (err, res) {
  476. if (err) {
  477. ModelUtil.emitError(self.eventEmitter, {message: "Failed to save message to mysql: " + err});
  478. } else {
  479. message.timestamp = message.timestamp.getTime();
  480. ModelUtil.emitOK(self.eventEmitter, {count: 1, messages: [message]});
  481. }
  482. });
  483. }).then(function (res) {
  484. // 推送消息
  485. ParticipantRepo.findIds(sessionId, function (err, res) {
  486. if (err) {
  487. ModelUtil.logError("Push message from session: get participant's id list failed: ", err);
  488. } else {
  489. message.session_id = sessionId;
  490. res.forEach(function (participant) {
  491. if (participant.id !== message.sender_id) {
  492. Sessions.pushNotification(participant.id, message);
  493. }
  494. });
  495. }
  496. })
  497. }).catch(function (err) {
  498. ModelUtil.emitError(self.eventEmitter, {message: "Error occurred while save message to session: " + err});
  499. })
  500. } else {
  501. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "当前会话找不到此发送者"});
  502. }
  503. });
  504. }
  505. /**
  506. * 保存消息
  507. *
  508. * @param message
  509. * @param sessionId
  510. * @param handler
  511. */
  512. saveMessageByTopic(message, sessionId, handler) {
  513. let messages = new Messages();
  514. let participants = new Participants();
  515. let session_key = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  516. let messageId = mongoose.Types.ObjectId().toString();
  517. let sessionType = 0;
  518. let sessionName = "";
  519. message.id = messageId;
  520. // 发送成员必须处于会话中
  521. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  522. if (res) {
  523. redis.hmgetAsync(session_key, ["type", "name"]).then(function (res) {
  524. sessionType = res[0];
  525. sessionName = res[1];
  526. if (!sessionType || !sessionName) {
  527. logger.error("session is error for key " + session_key);
  528. throw "session is not found";
  529. }
  530. }).then(function (res) {
  531. // 更新消息存储
  532. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  533. messages.saveMessageToMysql(sessionId, sessionType, messageId, message);
  534. // 更新会话最新状态及成员最后一次消息获取时间
  535. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  536. Messages.updateLastContent(session_key, sessionType, sessionName, message);
  537. handler(null, messageId);
  538. }).then(function (res) {
  539. // 推送消息
  540. ParticipantRepo.findIds(sessionId, function (err, res) {
  541. if (err) {
  542. ModelUtil.logError("Push message from topic: get participant's id list failed: ", err);
  543. } else {
  544. message.session_id = sessionId;
  545. res.forEach(function (participant) {
  546. if (participant.id !== message.sender_id) {
  547. Sessions.pushNotification(participant.id, message);
  548. }
  549. });
  550. }
  551. })
  552. }).catch(function (err) {
  553. ModelUtil.emitError(self.eventEmitter, {message: "Error occurred while save message to topic: " + err});
  554. handler(err, messageId)
  555. })
  556. } else {
  557. handler("用户不在此会话当中!", messageId);
  558. }
  559. })
  560. }
  561. /**
  562. * 置顶操作
  563. */
  564. stickSession(sessionId, user) {
  565. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  566. let self = this;
  567. //取出最大的session
  568. redis.zrevrangeAsync(user_session_key, 0, 0).then(function (res) {
  569. //获取该session的时间搓
  570. redis.zscoreAsync(user_session_key, res).then(function (scoreres) {
  571. let nowtime = new Date().getTime();
  572. //当前时间搓比redis的时间搓更早证明没有置顶过
  573. if (scoreres <= nowtime) {
  574. //初始化置顶
  575. redis.zaddAsync(user_session_key, STICKY_SESSION_BASE_SCORE, sessionId).then(function (res) {
  576. logger.info("stickSession:" + sessionId + ",res:" + res);
  577. ModelUtil.emitOK(self.eventEmitter, {});
  578. }).then(function () {
  579. SessionRepo.saveStickySession(sessionId, user, STICKY_SESSION_BASE_SCORE);
  580. })
  581. } else {
  582. //已有置顶的数据,取出来加1保存回去
  583. scoreres = Number(scoreres) + 1;
  584. redis.zaddAsync(user_session_key, scoreres, sessionId).then(function () {
  585. logger.info("stickSession:" + sessionId + ",res:" + res);
  586. ModelUtil.emitOK(self.eventEmitter, {});
  587. }).then(function () {
  588. SessionRepo.saveStickySession(sessionId, user, scoreres);
  589. })
  590. }
  591. })
  592. })
  593. }
  594. /**
  595. * 取消会话置顶
  596. */
  597. cancelStickSession(sessionId, user) {
  598. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  599. let participants_key = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  600. let self = this;
  601. redis.zscoreAsync(participants_key, user).then(function (res) {
  602. if (!res) {
  603. res = new Date().getTime();
  604. }
  605. redis.zaddAsync(user_session_key, res, sessionId).then(function (res) {
  606. logger.info("cancelStickSession:" + sessionId);
  607. ModelUtil.emitOK(self.eventEmitter, {});
  608. }).then(function () {
  609. SessionRepo.unstickSession(sessionId, user);
  610. });
  611. })
  612. }
  613. /**
  614. * 更新会话参与者的最后消息获取时间。
  615. *
  616. * @param sessionId
  617. * @param userId
  618. */
  619. static updateParticipantLastFetchTime(sessionId, userId, score) {
  620. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  621. redis.zaddAsync(participantsKey, score, userId)
  622. .then(function (res) {
  623. ParticipantRepo.updateLastFetchTime(new Date(score), sessionId, userId, function (err, res) {
  624. if (err) {
  625. logger.error("Update participant last fetch time failed: ", err);
  626. }
  627. });
  628. })
  629. .catch(function (err) {
  630. logger.error("Update participant last fetch time failed: ", err);
  631. });
  632. }
  633. /**
  634. * 向用户推送通知,微信端用户直接推送消息,APP端通过个推发送通知消息。
  635. *
  636. * @param targetUserId
  637. * @param message
  638. */
  639. static pushNotification(targetUserId, message) {
  640. Users.isPatientId(targetUserId, function (err, isPatient) {
  641. if (isPatient) {
  642. WechatClient.sendMessage(targetUserId, message);
  643. }
  644. else {
  645. AppClient.sendNotification(targetUserId, message);
  646. }
  647. });
  648. }
  649. }
  650. // Expose class
  651. module.exports = Sessions;