sessions.js 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  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 DoctorRepo = require('../../repository/oracle/doctor.repo');
  11. let Participants = require('./participants');
  12. let SessionRepo = require('../../repository/oracle/session.repo');
  13. let TopicRepo = require('../../repository/oracle/topics.repo');
  14. let MessageRepo = require('../../repository/oracle/message.repo');
  15. let ParticipantRepo = require('../../repository/oracle/participant.repo');
  16. let ImDb = require('../../repository/oracle/db/im.db');
  17. let WlyySDK = require("../../util/wlyy.sdk");
  18. let ObjectUtil = require("../../util/object.util.js");
  19. let WechatClient = require("../client/wechat.client.js");
  20. let AppClient = require("../client/app.client.js");
  21. let configFile = require('../../include/commons').CONFIG_FILE;
  22. let config = require('../../resources/config/' + configFile);
  23. let redis = RedisClient.redisClient().connection;
  24. let logger = require('../../util/log.js');
  25. let mongoose = require('mongoose');
  26. let async = require("async");
  27. let log = require("../../util/log.js");
  28. let pubSub = require("../redis/pubSub.js");
  29. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  30. const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
  31. const STICKY_SESSION_BASE_SCORE = require('../../include/commons').STICKY_SESSION_BASE_SCORE;
  32. const PARTICIPANT_ROLES = require('../../include/commons').PARTICIPANT_ROLES;
  33. const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES;
  34. const SESSION_BUSINESS_TYPE = require('../../include/commons').SESSION_BUSINESS_TYPE;
  35. const SESSION_STATUS = require('../../include/commons').SESSION_STATUS;
  36. class Sessions extends RedisModel {
  37. constructor() {
  38. super();
  39. }
  40. /**
  41. * 创建会话。会话的ID来源:
  42. * MUC:患者的ID
  43. * P2P:对成员的ID排序后,取hash值
  44. * GROUP:团队的ID
  45. *
  46. * @param sessionId
  47. * @param name 会话名称
  48. * @param type 会话类型
  49. * @param participantArray 会话成员
  50. * @param handler 回调,仅MUC模式使用
  51. */
  52. createSession(sessionId, name, type, participantArray, handler) {
  53. let self = this;
  54. let messageId = mongoose.Types.ObjectId().toString();
  55. //创建session到mysql
  56. self.createSessionToMysql(sessionId, name, type, participantArray, messageId, function (err, res) {
  57. if (err) {
  58. if (handler) {
  59. handler(err, null);
  60. return;
  61. }
  62. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  63. } else {
  64. name = res.name;
  65. //创建session到redis
  66. self.createSessionToRedis(sessionId, name, type, participantArray, messageId, function (err, res) {
  67. if (err) {
  68. if (handler) {
  69. handler(err, null);
  70. return;
  71. }
  72. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  73. } else {
  74. if (handler) {
  75. handler(null, res);
  76. return;
  77. }
  78. ModelUtil.emitOK(self.eventEmitter, {status: 200, data: res});
  79. }
  80. });
  81. }
  82. });
  83. }
  84. /**
  85. * 创建会话。REDIS
  86. * @param sessionId
  87. * @param name
  88. * @param type
  89. * @param participantArray
  90. * @param messageId
  91. * @param handler
  92. * @returns {boolean}
  93. */
  94. createSessionToRedis(sessionId, name, type, participantArray, messageId, handler) {
  95. let self = this;
  96. let messages = new Messages();
  97. let participantIdArray = [];
  98. for (let i in participantArray) {
  99. participantIdArray.push(participantArray[i].split(":")[0]);
  100. }
  101. if (type == SESSION_TYPES.P2P || type == SESSION_TYPES.SYSTEM) {
  102. if (sessionId) {
  103. callBusinessType(sessionId);
  104. return;
  105. }
  106. else if (participantIdArray.length != 2) {
  107. handler("P2P session only allow 2 participants.", null);
  108. return false;
  109. }else{
  110. ParticipantRepo.findSessionIdByParticipantIds(participantIdArray[0], participantIdArray[1], function (err, res) {
  111. sessionId = res;
  112. callBusinessType(sessionId);
  113. return;
  114. });
  115. }
  116. } else {
  117. if (!sessionId) {
  118. if(type == SESSION_TYPES.DISCUSSION){
  119. sessionId = messageId;
  120. }else {
  121. handler("MUC OR GROUP session sessionId is not allow null .", null);
  122. return;
  123. }
  124. }
  125. callBusinessType(sessionId);
  126. }
  127. function callBusinessType(sessionId) {
  128. if(type == SESSION_TYPES.MUC||
  129. type == SESSION_TYPES.PRESCRIPTION ||
  130. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  131. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  132. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  133. SESSION_TYPES.GENERAL_EXPERT ||
  134. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  135. SESSION_TYPES.MUC_VIDEO ||
  136. SESSION_TYPES.ONDOOR_NURSING){
  137. callCreate(sessionId, SESSION_BUSINESS_TYPE.PATIENT);
  138. }else if(type==SESSION_TYPES.DISCUSSION||type==SESSION_TYPES.GROUP){
  139. callCreate(sessionId, SESSION_BUSINESS_TYPE.DOCTOR);
  140. }else {
  141. ParticipantRepo.getBusinessType(participantIdArray, function (err, businessType) {
  142. callCreate(sessionId, businessType);
  143. });
  144. }
  145. }
  146. function callCreate(sessionId, businessType) {
  147. let createDate = new Date();
  148. Participants.saveParticipantsToRedis(sessionId, participantArray, createDate, function (res) {
  149. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  150. if (type == SESSION_TYPES.MUC||
  151. type == SESSION_TYPES.PRESCRIPTION ||
  152. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  153. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  154. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  155. SESSION_TYPES.GENERAL_EXPERT ||
  156. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  157. SESSION_TYPES.MUC_VIDEO ||
  158. SESSION_TYPES.ONDOOR_NURSING) {
  159. businessType = 2;
  160. }
  161. let session = {
  162. id: sessionId,
  163. name: name,
  164. type: type,
  165. create_date: createDate.getTime(),
  166. business_type: businessType
  167. };
  168. //如果会话已经存在的就不需要发送会话成功的消息不更新最后一条消息
  169. redis.hexistsAsync(sessionKey, sessionId).then(function(res){
  170. if(res==0){
  171. redis.hmsetAsync(sessionKey, session).then(function () {
  172. handler(null, session);
  173. })
  174. }
  175. })
  176. });
  177. }
  178. }
  179. /**
  180. * 创建会话。mysql
  181. * @param sessionId
  182. * @param name
  183. * @param type
  184. * @param participantArray
  185. * @param messageId
  186. * @param handler
  187. */
  188. createSessionToMysql(sessionId, name, type, participantArray, messageId, handler) {
  189. let self = this;
  190. //如果sessionId不存在则执行创建sessionId过程
  191. let participantIdArray = [];
  192. for (let i in participantArray) {
  193. participantIdArray.push(participantArray[i].split(":")[0]);
  194. }
  195. //流程1-判断是否存在sessionId不存在则创建对应的sessionId;
  196. if (!sessionId) {
  197. if (type == SESSION_TYPES.P2P || type == SESSION_TYPES.SYSTEM) {
  198. ParticipantRepo.findSessionIdByParticipantIds(participantIdArray[0], participantIdArray[1], function (err, res) {
  199. sessionId = res;
  200. callBusinessType();
  201. });
  202. } else if(type == SESSION_TYPES.DISCUSSION){
  203. sessionId = messageId;
  204. callBusinessType();
  205. } else {
  206. return handler("MUC模式和团队模式,不允许sessionId为空!", null);
  207. }
  208. } else {
  209. callBusinessType();
  210. }
  211. //流程2-判断session的业务类型;
  212. function callBusinessType() {
  213. if(type==SESSION_TYPES.MUC||
  214. type==SESSION_TYPES.PRESCRIPTION ||
  215. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  216. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  217. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  218. SESSION_TYPES.GENERAL_EXPERT ||
  219. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  220. SESSION_TYPES.MUC_VIDEO ||
  221. SESSION_TYPES.ONDOOR_NURSING){
  222. callCreateSession(SESSION_BUSINESS_TYPE.PATIENT);
  223. }else if(type==SESSION_TYPES.SPECIALISTGROUP||type==SESSION_TYPES.DISCUSSION){
  224. callCreateSession(SESSION_BUSINESS_TYPE.DOCTOR);
  225. }else{
  226. ParticipantRepo.getBusinessType(participantIdArray, function (err, businessType) {
  227. if (err) {
  228. handler(err, null);
  229. return;
  230. }
  231. callCreateSession(businessType);
  232. });
  233. }
  234. }
  235. //流程3-发起session创建 返回session实例
  236. function callCreateSession(businessType) {
  237. //查找该sessionId是否存在存在则直接返回实例
  238. SessionRepo.findOne(sessionId, function (err, res) {
  239. if (res && res.length > 0) {//已经存在
  240. //已存在的会话不修改名称
  241. name = res[0].name;
  242. //更新成员
  243. Participants.saveParticipantsToMysql(sessionId, participantArray, function (err, update) {
  244. handler(null, res[0]);
  245. return;
  246. })
  247. let createDate = new Date();
  248. self.saveSessionToMysql(sessionId, name, type, createDate, businessType, function (err, res) {
  249. logger.info("update session status is true");
  250. })
  251. } else {
  252. let createDate = new Date();
  253. let session = {
  254. id: sessionId,
  255. name: name,
  256. type: type,
  257. create_date: createDate.getTime(),
  258. business_type: businessType
  259. };
  260. //将session写入数据库
  261. self.saveSessionToMysql(sessionId, name, type, createDate, businessType, function (err, res) {
  262. if (err) {
  263. handler(err, null);
  264. return;
  265. }
  266. callCreateParticipants(session);
  267. })
  268. }
  269. });
  270. }
  271. //流程4-发起session成员创建
  272. function callCreateParticipants(session) {
  273. Participants.saveParticipantsToMysql(sessionId, participantArray, function (err, res) {
  274. if (err) {
  275. handler(err, null);
  276. return;
  277. } else {
  278. handler(null, session);
  279. return;
  280. }
  281. })
  282. }
  283. }
  284. /**
  285. * 最近会话列表,7天内。
  286. *
  287. * @param userId
  288. * @param dateSpan
  289. */
  290. getRecentSessions(userId, dateSpan) {
  291. let self = this;
  292. SessionRepo.findAllByTimestampAndType(userId, dateSpan, function (err, res) {
  293. if (err) {
  294. ModelUtil.emitError(self.eventEmitter, "Get recent sessions failed", err);
  295. return;
  296. }
  297. let sessions = [];
  298. res.forEach(function (session) {
  299. //最近列表用于转发,过滤不可用的咨询
  300. if(session.last_content_type != CONTENT_TYPES.TopicEnd){
  301. sessions.push({
  302. id: session.id,
  303. name: session.name,
  304. type: session.type,
  305. business_type: session.business_type,
  306. create_date: session.create_date
  307. })
  308. }
  309. });
  310. ModelUtil.emitOK(self.eventEmitter, sessions);
  311. });
  312. }
  313. /**
  314. * 保存session到MySQL
  315. * @param sessionId
  316. * @param name
  317. * @param type
  318. * @param createDate
  319. * @param businessType
  320. * @param handler
  321. */
  322. saveSessionToMysql(sessionId, name, type, createDate, businessType, handler) {
  323. SessionRepo.saveSession(sessionId, name, type, createDate, businessType, handler);
  324. }
  325. /**
  326. * 获取某个用户的全部session列表
  327. * @param userId
  328. * @param handler
  329. */
  330. getUserSessionsFromMysql(userId, handler) {
  331. SessionRepo.findAll(userId, handler);
  332. }
  333. /**
  334. * 获取session单个对象
  335. * @param sessionId
  336. * @param handler
  337. */
  338. getSessions(sessionId, handler) {
  339. SessionRepo.findOne(sessionId, handler);
  340. }
  341. /**
  342. * 判断会话是否存在
  343. * @param sessionId
  344. * @param handler
  345. */
  346. isExist(sessionId) {
  347. let self = this;
  348. SessionRepo.findOne(sessionId, function (err, res) {
  349. if(err){
  350. log.error(err);
  351. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  352. } else if(res&&res.length>0){
  353. ModelUtil.emitOK(self.eventEmitter, {sessionId: res[0].id, status: 200});
  354. }else {
  355. ModelUtil.emitOK(self.eventEmitter, {sessionId: '', status: 200});
  356. }
  357. });
  358. }
  359. getSession(sessionId,userId,handler){
  360. let self = this;
  361. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  362. redis.hgetallAsync(sessionKey).then(function(session){
  363. if(session.type==SESSION_TYPES.P2P){
  364. ParticipantRepo.findNameById(userId, function (err, res) {
  365. session.name = res[0].name;
  366. if(handler){
  367. handler(null,session);
  368. return;
  369. }
  370. ModelUtil.emitOK(self.eventEmitter, session);
  371. })
  372. }else{
  373. if(handler){
  374. handler(null,session);
  375. return;
  376. }
  377. ModelUtil.emitOK(self.eventEmitter, session);
  378. }
  379. }).catch(function (err) {
  380. logger.error("Get session failed: ", err);
  381. if(handler){
  382. handler(null,session);
  383. return;
  384. }
  385. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  386. })
  387. }
  388. /**
  389. *MDT 医生数据转换,根据手机号查询医生CODE
  390. */
  391. conversionAarticipant(doctorMobile, callback) {
  392. let doctorProto = DoctorRepo;
  393. doctorProto.findByMobile(doctorMobile, function (err, oDoctor) {
  394. if(oDoctor.length>0 && oDoctor[0].id){
  395. if(callback){
  396. callback(oDoctor[0].id)
  397. }
  398. }else {
  399. if(callback){
  400. logger.error("Get doctoc code failed: mobile:", doctorMobile);
  401. callback(doctorMobile)
  402. }
  403. }
  404. });
  405. }
  406. /**
  407. * 根据用户ID获取用户的session列表
  408. * @param userId
  409. * @param page
  410. * @param size
  411. * @param businessType
  412. */
  413. getUserSessions(userId, page, size, businessType) {
  414. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  415. let self = this;
  416. if (page > 0) {
  417. if (page == 1) {
  418. page = 0;
  419. }
  420. page = page + page * size;
  421. }
  422. async.waterfall([
  423. // 获取会话ID列表
  424. // function (callback) {
  425. // redis.zrevrangeAsync(userSessionKey, page, size)
  426. // .then(function (sessionIds) {
  427. // if (sessionIds.length == 0) {
  428. // ModelUtil.emitOK(self.eventEmitter, []);
  429. // return;
  430. // }
  431. // callback(null, sessionIds);
  432. // })
  433. // },
  434. function (callback) {
  435. SessionRepo.findAllByType(userId,businessType,page,size,function(err,res){
  436. if (res.length == 0) {
  437. ModelUtil.emitOK(self.eventEmitter, []);
  438. return;
  439. }
  440. var sessionIds=[];
  441. for(var j in res){
  442. sessionIds.push(res[j].id);
  443. }
  444. callback(null,sessionIds);
  445. })
  446. },
  447. // 遍历会话
  448. function (sessionIds) {
  449. let sessionList = [];
  450. let functionList = [];
  451. log.info("sessionIds.length:" + sessionIds.length);
  452. for (let j = 0; j < sessionIds.length; j++) {
  453. let fun = function (index, callback) {
  454. log.info("!callback:" + !callback);
  455. if (!callback) {
  456. callback = index, index = 0
  457. }
  458. let sessionId = sessionIds[index];
  459. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  460. log.info("sessionKey:" + sessionKey);
  461. let participantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  462. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  463. redis.multi()
  464. .hgetall(sessionKey) // 会话实体
  465. .hget(participantsRoleKey, userId) // 用户在此会话中的角色
  466. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  467. .zrange(sessionParticipantsKey, 0, -1)
  468. .zrange(sessionParticipantsKey, 0,-1,'withscores') // 所有用户在此会话中最后一次获取未读消息的时间
  469. .hgetall(participantsRoleKey) // 所有用户在此会话中角色
  470. .execAsync()
  471. .then(function (res) {
  472. let session = res[0];
  473. log.info("top.session.id:" + session.id);
  474. log.info("top.session.name:" + session.name);
  475. log.info("tope.session.business_type:" + session.business_type);
  476. let role = res[1];
  477. let lastFetchTime = res[2];
  478. let users = res[3];
  479. let participantsTimeArray = res[4];
  480. let userRoles = res[5];
  481. let participantsTime = [];
  482. let isInvite = true;
  483. //处理session未加入redis的bug
  484. log.info("1.session==null:" + session==null);
  485. if(session==null){
  486. let lastLoginTime = new Date();
  487. SessionRepo.findOne(sessionId, function (err, res) {
  488. if(res){
  489. session = res;
  490. log.info("1.session.id:" + session.id);
  491. log.info("1.session.name:" + session.name);
  492. log.info("1.session.business_type:" + session.business_type);
  493. let redisSession = [
  494. "id", session.id,
  495. "name", session.name,
  496. "type", session.type,
  497. "business_type", session.business_type,
  498. "last_sender_id", session.last_sender_id||"",
  499. "last_sender_name", session.last_sender_name||"",
  500. "last_content_type", session.last_content_type||"",
  501. "last_content", session.last_content||"",
  502. "last_message_time", session.last_message_time||"",
  503. "create_date", ObjectUtil.timestampToLong(session.create_date),
  504. "status",session.status==null?0:session.status
  505. ];
  506. // cache sessions
  507. redis.multi()
  508. .zadd(REDIS_KEYS.Sessions, lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  509. .zadd(RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  510. .hmset(RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId), redisSession)
  511. .execAsync()
  512. .then(function (res) {
  513. // cache participants
  514. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  515. let sessionParticipantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  516. ParticipantRepo.findAll(sessionId, function (err, participants) {
  517. if (err) {
  518. ModelUtil.emitError(self.eventEmitter, err.message);
  519. return;
  520. }
  521. let multi = redis.multi();
  522. participants.forEach(function (participant) {
  523. let participantId = participant.id;
  524. let participantRole = participant.role;
  525. let score = ObjectUtil.timestampToLong(participant.last_fetch_time||(new Date()));
  526. multi = multi.zadd(sessionParticipantsKey, score, participantId)
  527. .hset(sessionParticipantsRoleKey, participantId, participantRole);
  528. });
  529. multi.execAsync()
  530. .then(function (res) {
  531. })
  532. .catch(function (ex) {
  533. log.error("Login failed while caching participants: ", ex);
  534. });
  535. });
  536. // cache messages
  537. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  538. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  539. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, null, function (err, messages) {
  540. if (err) {
  541. ModelUtil.emitError(self.eventEmitter, err.message);
  542. return;
  543. }
  544. let multi = redis.multi();
  545. messages.forEach(function (message) {
  546. let msgJson = {
  547. id: message.id,
  548. sender_id: message.sender_id,
  549. sender_name: message.sender_name,
  550. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  551. content_type: message.content_type,
  552. content: message.content
  553. };
  554. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  555. .zadd(messagesByTimestampKey, ObjectUtil.timestampToLong(message.timestamp), message.id);
  556. });
  557. multi.execAsync()
  558. .then(function (res) {
  559. })
  560. .catch(function (ex) {
  561. log.error("Login failed while caching messages: ", ex);
  562. });
  563. });
  564. // cache topics for MUC
  565. let topicsKey = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  566. TopicRepo.findAllBySessionId(sessionId, function (err, topics) {
  567. if (err) {
  568. ModelUtil.emitError(self.eventEmitter, err.message);
  569. return;
  570. }
  571. topics.forEach(function (topic) {
  572. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  573. let topicId = topic.id;
  574. let name = topic.name == null ? "" : topic.name;
  575. let createTime = ObjectUtil.timestampToLong(topic.create_time);
  576. let endBy = topic.end_by == null ? "" : topic.end_by;
  577. let endTime = topic.end_time == null ? 0 : ObjectUtil.timestampToLong(topic.end_time);
  578. let startMessageId = topic.start_message_id == null ? "" : topic.start_message_id;
  579. let endMessageId = topic.end_message_id == null ? "" : topic.end_message_id;
  580. let description = topic.description == null ? "" : topic.description;
  581. let status = topic.status == null ? 0 : topic.status;
  582. redisConn.multi()
  583. .zadd(topicsKey, createTime, topicId)
  584. .hmset(topicKey,
  585. 'name', name,
  586. 'session_id', sessionId,
  587. 'create_time', createTime,
  588. 'end_by', endBy,
  589. 'end_time', endTime,
  590. 'start_message_id', startMessageId,
  591. 'end_message_id', endMessageId,
  592. 'description', description,
  593. 'status', status)
  594. .execAsync()
  595. .catch(function (ex) {
  596. log.error("Login failed while caching topics: ", ex);
  597. });
  598. });
  599. });
  600. })
  601. .catch(function (ex) {
  602. log.error("Login failed while caching sessions: ", ex);
  603. });
  604. }
  605. });
  606. }
  607. for(var j in userRoles){
  608. if(userRoles[j]==1){
  609. isInvite = false;
  610. break;
  611. }
  612. }
  613. for(var j = 0 ;j<participantsTimeArray.length;j++){
  614. if(j%2!=0)continue;
  615. let participantsTimeJson = {};
  616. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  617. participantsTime.push(participantsTimeJson);
  618. }
  619. let sessionName = "";
  620. let otherUserId = "";
  621. if (session.type == SESSION_TYPES.P2P) {
  622. for (let j in users) {
  623. if (users[j] != userId) {
  624. otherUserId = users[j];
  625. }
  626. }
  627. }
  628. if (!role) role = 0;
  629. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  630. // 计算未读消息数
  631. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  632. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  633. .then(function (count) {
  634. if (!otherUserId) otherUserId = userId;
  635. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  636. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  637. sessionName = session.name;
  638. } else {
  639. sessionName = res[0].name;
  640. }
  641. var bir = new Date().getTime();
  642. if (res.length != 0 && res[0].birthdate) {
  643. bir = res[0].birthdate.getTime();
  644. }
  645. var sex = 1;
  646. if (res.length != 0 && res[0].sex) {
  647. sex = res[0].sex;
  648. }
  649. //end
  650. log.info("2.session.id:" + sessionId);
  651. log.info("2.session.name:" + sessionName);
  652. log.info("2.session.business_type:" + session.business_type);
  653. sessionList.push({
  654. id: sessionId,
  655. name: sessionName,
  656. create_date: session.create_date,
  657. last_content_type: session.last_content_type||"",
  658. last_content: session.last_content||"",
  659. sender_id: session.last_sender_id||"",
  660. type: session.type,
  661. sender_name: session.last_sender_name||"",
  662. unread_count: count,
  663. // business_type: session.business_type,
  664. business_type: businessType,
  665. my_role: role,
  666. sender_sex: sex,
  667. sender_birthday: bir,
  668. participantsTimeArray:participantsTime,
  669. status:session.status,
  670. is_invite:isInvite
  671. });
  672. index = (parseInt(index) + 1);
  673. if (index == sessionIds.length) {
  674. ModelUtil.emitOK(self.eventEmitter, sessionList);
  675. } else {
  676. callback(null, index);
  677. }
  678. })
  679. })
  680. })
  681. .catch(function (err) {
  682. logger.error("Get sessions failed: ", err);
  683. });
  684. };
  685. functionList.push(fun);
  686. }
  687. async.waterfall(functionList);
  688. }
  689. ]);
  690. }
  691. /**
  692. * 查找会话数
  693. * @param userId
  694. * @param type
  695. * @param status
  696. * @param handler
  697. */
  698. getSessionCountByType(userId,type,status,handler){
  699. let self = this;
  700. SessionRepo.findSessionCountByType(userId,type,status,function (err,res) {
  701. if(res){
  702. ModelUtil.emitOK(self.eventEmitter,{status:200,count:res[0].count});
  703. return;
  704. }else {
  705. ModelUtil.emitOK(self.eventEmitter,{status:200,count:0});
  706. return;
  707. }
  708. })
  709. }
  710. /**
  711. * 根据用户类型获取用户的session列表
  712. * @param userId
  713. * @param page
  714. * @param size
  715. * @param businessType
  716. * @param status 0:进行中的会话1:结束的会话
  717. */
  718. getUserSessionsByType(userId,type,page, size,status) {
  719. logger.info("根据用户类型获取用户的session列表1: ");
  720. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  721. let self = this;
  722. logger.info("根据用户类型获取用户的session列表2: ");
  723. async.waterfall([
  724. // 获取会话ID列表
  725. function (callback) {
  726. SessionRepo.findListByType(userId,type,page,size,status,function(err,res){
  727. logger.info("根据用户类型获取用户的session列表: res :"+res.toString());
  728. logger.info("根据用户类型获取用户的session列表: res.length :"+res.length);
  729. if (res == null || res.length == 0) {
  730. ModelUtil.emitOK(self.eventEmitter, []);
  731. return;
  732. }
  733. callback(null,res);
  734. })
  735. },
  736. // 遍历会话
  737. function (sessionIds) {
  738. let sessionList = [];
  739. let functionList = [];
  740. for (let j = 0; j < sessionIds.length; j++) {
  741. let fun = function (index, callback) {
  742. if (!callback) {
  743. callback = index, index = 0
  744. }
  745. let mysqlSession = sessionIds[index];
  746. let sessionId = mysqlSession.id;
  747. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  748. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  749. redis.multi()
  750. .hgetall(sessionKey) // 会话实体
  751. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  752. .zrange(sessionParticipantsKey, 0, -1)
  753. .zrange(sessionParticipantsKey, 0,-1,'withscores') // 所有用户在此会话中最后一次获取未读消息的时间
  754. .execAsync()
  755. .then(function (res) {
  756. let session = res[0];
  757. let lastFetchTime = res[1];
  758. let users = res[2];
  759. let participantsTimeArray = res[3];
  760. let participantsTime = [];
  761. for(var j = 0 ;j<participantsTimeArray.length;j++){
  762. if(j%2!=0)continue;
  763. let participantsTimeJson = {};
  764. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  765. participantsTime.push(participantsTimeJson);
  766. }
  767. let sessionName = "";
  768. let otherUserId = "";
  769. if (session.type == SESSION_TYPES.P2P) {
  770. for (let j in users) {
  771. if (users[j] != userId) {
  772. otherUserId = users[j];
  773. }
  774. }
  775. }
  776. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  777. // 计算未读消息数
  778. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  779. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  780. .then(function (count) {
  781. if (!otherUserId) otherUserId = userId;
  782. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  783. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  784. sessionName = session.name;
  785. } else {
  786. sessionName = res[0].name;
  787. }
  788. var bir = new Date().getTime();
  789. if (res && res.length != 0 && res[0].birthdate) {
  790. bir = res[0].birthdate.getTime();
  791. }
  792. var sex = 1;
  793. if (res && res.length != 0 && res[0].sex) {
  794. sex = res[0].sex;
  795. }
  796. sessionList.push({
  797. id: sessionId,
  798. name: sessionName,
  799. create_date: new Date(mysqlSession.last_message_time).getTime(),
  800. last_content_type: session.last_content_type,
  801. last_content: session.last_content,
  802. sender_id: session.last_sender_id,
  803. type: session.type,
  804. sender_name: session.last_sender_name,
  805. unread_count: count,
  806. business_type: session.business_type,
  807. sender_sex: sex,
  808. sender_birthday: bir,
  809. participantsTimeArray:participantsTime,
  810. status:session.status,
  811. });
  812. index = (parseInt(index) + 1);
  813. if (index == sessionIds.length) {
  814. ModelUtil.emitOK(self.eventEmitter, sessionList);
  815. } else {
  816. callback(null, index);
  817. }
  818. })
  819. })
  820. })
  821. .catch(function (err) {
  822. logger.error("Get sessions:"+sessionId+" failed: ", err);
  823. });
  824. };
  825. functionList.push(fun);
  826. }
  827. async.waterfall(functionList);
  828. }
  829. ]);
  830. }
  831. /**
  832. * 根据用户ID获取用户已经结束咨询的session列表
  833. * @param userId
  834. * @param page
  835. * @param size
  836. * @param businessType
  837. */
  838. getUserStatusSessions(userId,status,businessType,page, size) {
  839. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  840. log.info(userId);
  841. let self = this;
  842. async.waterfall([
  843. // 获取会话ID列表
  844. function (callback) {
  845. SessionRepo.findAllByTypeAndStatus(userId,businessType,status,page,size,function(err,res){
  846. if (res && res.length == 0) {
  847. ModelUtil.emitOK(self.eventEmitter, []);
  848. return;
  849. }
  850. // var sessionIds=[];
  851. // for(var j in res){
  852. // sessionIds.push(res[j].id);
  853. // }
  854. callback(null,res);
  855. })
  856. },
  857. // 遍历会话
  858. function (sessionIds) {
  859. let sessionList = [];
  860. let functionList = [];
  861. for (let j = 0; j < sessionIds.length; j++) {
  862. let fun = function (index, callback) {
  863. if (!callback) {
  864. callback = index, index = 0
  865. }
  866. let mysqlSession = sessionIds[index];
  867. let sessionId = mysqlSession.id;
  868. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  869. let participantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  870. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  871. redis.multi()
  872. .hgetall(sessionKey) // 会话实体
  873. .hget(participantsRoleKey, userId) // 用户在此会话中的角色
  874. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  875. .zrange(sessionParticipantsKey, 0, -1)
  876. .zrange(sessionParticipantsKey, 0,-1,'withscores') // 所有用户在此会话中最后一次获取未读消息的时间
  877. .hgetall(participantsRoleKey) // 所有用户在此会话中角色
  878. .execAsync()
  879. .then(function (res) {
  880. let session = res[0];
  881. let role = res[1];
  882. let lastFetchTime = res[2];
  883. let users = res[3];
  884. let participantsTimeArray = res[4];
  885. let userRoles = res[5];
  886. let participantsTime = [];
  887. let isInvite = true;
  888. for(var j in userRoles){
  889. if(userRoles[j]==1){
  890. isInvite = false;
  891. break;
  892. }
  893. }
  894. for(var j = 0 ;j<participantsTimeArray.length;j++){
  895. if(j%2!=0)continue;
  896. let participantsTimeJson = {};
  897. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  898. participantsTime.push(participantsTimeJson);
  899. }
  900. let sessionName = "";
  901. let otherUserId = "";
  902. if (session.type == SESSION_TYPES.P2P) {
  903. for (let j in users) {
  904. if (users[j] != userId) {
  905. otherUserId = users[j];
  906. }
  907. }
  908. }
  909. if (!role) role = 0;
  910. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  911. // 计算未读消息数
  912. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  913. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  914. .then(function (count) {
  915. if (!otherUserId) otherUserId = userId;
  916. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  917. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  918. sessionName = session.name;
  919. } else {
  920. sessionName = res[0].name;
  921. }
  922. var bir = new Date().getTime();
  923. if (res && res.length != 0 && res[0].birthdate) {
  924. bir = res[0].birthdate.getTime();
  925. }
  926. var sex = 1;
  927. if (res.length != 0 && res[0].sex) {
  928. sex = res[0].sex;
  929. }
  930. sessionList.push({
  931. id: sessionId,
  932. name: sessionName,
  933. create_date: new Date(mysqlSession.last_message_time).getTime(),
  934. last_content_type: session.last_content_type,
  935. last_content: session.last_content,
  936. sender_id: session.last_sender_id,
  937. type: session.type,
  938. sender_name: session.last_sender_name,
  939. unread_count: count,
  940. business_type: session.business_type,
  941. my_role: role,
  942. sender_sex: sex,
  943. sender_birthday: bir,
  944. participantsTimeArray:participantsTime,
  945. status:session.status,
  946. is_invite:isInvite
  947. });
  948. index = (parseInt(index) + 1);
  949. if (index == sessionIds.length) {
  950. ModelUtil.emitOK(self.eventEmitter, sessionList);
  951. } else {
  952. callback(null, index);
  953. }
  954. })
  955. })
  956. })
  957. .catch(function (err) {
  958. logger.error("Get sessions:"+sessionId+" failed: ", err);
  959. });
  960. };
  961. functionList.push(fun);
  962. }
  963. async.waterfall(functionList);
  964. }
  965. ]);
  966. }
  967. /**
  968. * 获取会话消息。全部,不管已读/未读状态。
  969. *
  970. * @param sessionId 会话ID
  971. * @param userId 拉取消息的人
  972. * @param page 第几页
  973. * @param pagesize 分页数量
  974. * @param start_msg_id 消息会话最新的一条消息的ID
  975. * @param end_msg_id 消息会话刚开始的消息ID
  976. * @remark
  977. * start_msg_id end_msg_id 为空取会话倒序的根据分页的消息数据
  978. * start_msg_id 为空 end_msg_id 不为空根据end_msg_id取旧的消息(offset=1可以排除本身)返回指定分页的数据
  979. * end_msg_id 为空 start_msg_id 不为空 根据 start_msg_id 取出新消息(offset=1可以排除本身)返回指定分页的数据
  980. * end_msg_id start_msg_id 都不为空返回指定区间的消息
  981. */
  982. getMessages(sessionId, user, start_msg_id, end_msg_id, page, pagesize, isoffset, handler) {
  983. let self = this;
  984. let message_timestamp_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  985. if (!start_msg_id && !end_msg_id) {
  986. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  987. logger.info("redis return res-----"+res);
  988. // log.info("session.js--830---getMessages res.length: " + res.length);
  989. if (res && res.length == 0) {
  990. //修复应redis没有缓冲聊天记录导致会话列表加载不出来
  991. // cache messages
  992. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  993. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, null, function (err, messages) {
  994. if (err) {
  995. ModelUtil.emitError(self.eventEmitter, err.message);
  996. return;
  997. }
  998. let multi = redis.multi();
  999. messages.forEach(function (message) {
  1000. let msgJson = {
  1001. id: message.id,
  1002. sender_id: message.sender_id,
  1003. sender_name: message.sender_name,
  1004. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  1005. content_type: message.content_type,
  1006. content: message.content
  1007. };
  1008. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  1009. .zadd(message_timestamp_key, ObjectUtil.timestampToLong(message.timestamp), message.id);
  1010. });
  1011. multi.execAsync()
  1012. .then(function (res) {
  1013. })
  1014. .catch(function (ex) {
  1015. log.error("Login failed while caching messages: ", ex);
  1016. ModelUtil.emitOK(self.eventEmitter, res);
  1017. return;
  1018. });
  1019. });
  1020. // if (handler) {
  1021. // handler(null, res);
  1022. // return;
  1023. // }
  1024. // ModelUtil.emitOK(self.eventEmitter, res);
  1025. // return;
  1026. }
  1027. start_msg_id = res[0];
  1028. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1029. if (res && res.length == 0) {
  1030. if (handler) {
  1031. handler(null, res);
  1032. return;
  1033. }
  1034. ModelUtil.emitOK(self.eventEmitter, res);
  1035. return;
  1036. }
  1037. end_msg_id = res[0];
  1038. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  1039. if (err) {
  1040. if (handler) {
  1041. handler(err, null);
  1042. return;
  1043. }
  1044. logger.error("getMessagesByPage error" + err);
  1045. ModelUtil.emitError(self.eventEmitter, err, err);
  1046. } else {
  1047. if (handler) {
  1048. handler(null, res);
  1049. return;
  1050. }
  1051. ModelUtil.emitOK(self.eventEmitter, res);
  1052. }
  1053. })
  1054. })
  1055. })
  1056. } else if (!start_msg_id) {
  1057. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1058. if (res && res.length == 0) {
  1059. if (handler) {
  1060. handler(null, res);
  1061. return;
  1062. }
  1063. ModelUtil.emitOK(self.eventEmitter, res);
  1064. return;
  1065. }
  1066. start_msg_id = res[0];
  1067. self.getMessagesByPage(sessionId, user, start_msg_id,end_msg_id , page, pagesize, isoffset, function (err, res) {
  1068. if (err) {
  1069. if (handler) {
  1070. handler(err, null);
  1071. return;
  1072. }
  1073. logger.error("getMessagesByPage error" + err);
  1074. ModelUtil.emitError(self.eventEmitter, err, err);
  1075. } else {
  1076. if (handler) {
  1077. handler(null, res);
  1078. return;
  1079. }
  1080. ModelUtil.emitOK(self.eventEmitter, res);
  1081. }
  1082. })
  1083. })
  1084. } else if (!end_msg_id) {
  1085. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1086. if (res && res.length == 0) {
  1087. ModelUtil.emitOK(self.eventEmitter, res);
  1088. return;
  1089. }
  1090. end_msg_id = res[0];
  1091. self.getMessagesByPage(sessionId, user, end_msg_id,start_msg_id, page, pagesize, isoffset, function (err, res) {
  1092. if (err) {
  1093. if (handler) {
  1094. handler(err, null);
  1095. return;
  1096. }
  1097. logger.error("getMessagesByPage error" + err);
  1098. ModelUtil.emitError(self.eventEmitter, err, err);
  1099. } else {
  1100. if (handler) {
  1101. handler(null, res);
  1102. return;
  1103. }
  1104. ModelUtil.emitOK(self.eventEmitter, res);
  1105. }
  1106. })
  1107. })
  1108. } else {
  1109. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  1110. if (err) {
  1111. if (handler) {
  1112. handler(err, null);
  1113. return;
  1114. }
  1115. logger.error("getMessagesByPage error" + err);
  1116. ModelUtil.emitError(self.eventEmitter, err, err);
  1117. } else {
  1118. if (handler) {
  1119. handler(null, res);
  1120. return;
  1121. }
  1122. ModelUtil.emitOK(self.eventEmitter, res);
  1123. }
  1124. })
  1125. }
  1126. }
  1127. /**
  1128. * 分页获取会话消息。
  1129. *
  1130. * @param sessionId 必选。会话ID
  1131. * @param userId 必选。用户ID
  1132. * @param startMsgId 必选。会话的的起始消息ID,作为检索的起始依据
  1133. * @param endMsgId 必选。会话中的结束消息ID
  1134. * @param page 必选。页码
  1135. * @param size 必选。页面大小
  1136. * @param handler 必选。回调
  1137. */
  1138. getMessagesByPage(sessionId, userId, startMsgId, endMsgId, page, size, isoffset, handler) {
  1139. let messagesTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1140. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  1141. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1142. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1143. let participants = new Participants();
  1144. let offset = (page - 1 < 0 ? 0 : page - 1) * size;
  1145. let count = size;
  1146. if (page > 1 || isoffset == 1) {
  1147. offset += 1; // 翻页由于闭区间,需跳过本身数据
  1148. }
  1149. participants.existsParticipant(sessionId, userId, function (err, res) {
  1150. log.info("1151-userId=" + userId);
  1151. log.info(" res[0].exist=" + res[0].exist);
  1152. log.info(!res[0].exist && userId != "system");
  1153. if (! res[0].exist && userId != "system") {
  1154. handler(Error("User not found in session " + sessionId), null);
  1155. } else {
  1156. //将消息ID转换成分值
  1157. redis.multi()
  1158. .zscore(messagesTimestampKey, startMsgId)
  1159. .zscore(messagesTimestampKey, endMsgId)
  1160. .hgetall(sessionKey)
  1161. .zrange(sessionParticipantsKey, 0, -1)
  1162. .execAsync()
  1163. .then(function (res) {
  1164. let startMsgScore = res[1];
  1165. let endMsgScore = res[0];
  1166. let session = res[2];
  1167. let users = res[3];
  1168. if (startMsgScore == null || endMsgScore == null || (startMsgScore == endMsgScore && isoffset == 1)) {
  1169. handler(null, []);
  1170. return;
  1171. }
  1172. //结束大于开始,正序取数据,返回的数据顺序也是逆序的,反向拉取数据,
  1173. // 当end>start取出来都是空的,为了给前端获取新数据使用,一般不出现这种情况
  1174. if(endMsgScore>startMsgScore){
  1175. redis.zrangebyscoreAsync(messagesTimestampKey, startMsgScore, endMsgScore, "limit", offset, count)
  1176. .then(function (res) {
  1177. if (res && res.length == 0) {
  1178. handler(null, []);
  1179. return;
  1180. }
  1181. redis.hmgetAsync(messagesKey, res).then(function (messages) {
  1182. messages.reverse();
  1183. handler(null, messages);
  1184. }).then(function () {
  1185. Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
  1186. if(session.type == SESSION_TYPES.P2P){
  1187. for(var j in users){
  1188. if(users[j]==userId)continue;
  1189. WechatClient.sendAllRead(users[j],sessionId);
  1190. }
  1191. }else if(session.type == SESSION_TYPES.MUC ||
  1192. session.type == SESSION_TYPES.PRESCRIPTION ||
  1193. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1194. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1195. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1196. SESSION_TYPES.GENERAL_EXPERT ||
  1197. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1198. SESSION_TYPES.MUC_VIDEO ||
  1199. SESSION_TYPES.ONDOOR_NURSING){
  1200. for(var j in users){
  1201. if(users[j]==userId)continue;
  1202. WechatClient.sendMucAllRead(users[j],userId,sessionId);
  1203. }
  1204. }
  1205. })
  1206. })
  1207. .catch(function (err) {
  1208. logger.error("Get message by page failed: ", err);
  1209. handler(err, false);
  1210. })
  1211. }else{
  1212. // 从消息时间表中过滤出要获取的消息ID列表,倒序取出消息
  1213. redis.zrevrangebyscoreAsync(messagesTimestampKey, startMsgScore, endMsgScore, "limit", offset, count)
  1214. .then(function (res) {
  1215. if (res && res.length == 0) {
  1216. handler(null, []);
  1217. return;
  1218. }
  1219. redis.hmgetAsync(messagesKey, res).then(function (messages) {
  1220. handler(null, messages);
  1221. }).then(function () {
  1222. Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
  1223. if(session.type == SESSION_TYPES.P2P){
  1224. for(var j in users){
  1225. if(users[j]==userId)continue;
  1226. //通知对方自己已经读取数据
  1227. WechatClient.sendAllRead(users[j],sessionId);
  1228. }
  1229. }else if(session.type == SESSION_TYPES.MUC ||
  1230. session.type == SESSION_TYPES.PRESCRIPTION ||
  1231. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1232. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1233. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1234. SESSION_TYPES.GENERAL_EXPERT ||
  1235. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1236. SESSION_TYPES.MUC_VIDEO ||
  1237. SESSION_TYPES.ONDOOR_NURSING){
  1238. for(var j in users){
  1239. if(users[j]==userId)continue;
  1240. //如果是患者拉取数据告诉在线的医生患者已经读取数据
  1241. WechatClient.sendMucAllRead(users[j],userId,sessionId);
  1242. }
  1243. }
  1244. })
  1245. })
  1246. .catch(function (err) {
  1247. logger.error("Get message by page failed: ", err);
  1248. handler(err, false);
  1249. })
  1250. }
  1251. })
  1252. }
  1253. })
  1254. }
  1255. /**
  1256. * 获取所有会话的未读消息数。
  1257. */
  1258. getAllSessionsUnreadMessageCount(userId,type,handler) {
  1259. let self = this;
  1260. let count = 0;
  1261. let patientCount = 0;
  1262. let doctorCount = 0;
  1263. let patientEndCount = 0;
  1264. SessionRepo.findAll(userId, function (err, res) {
  1265. // SessionRepo.findUnEndAll(userId, function (err, res) {
  1266. if (err) {
  1267. if(handler)
  1268. {
  1269. handler(err,res);
  1270. return;
  1271. }
  1272. ModelUtil.logError("getAllSessionsUnreadMessageCount is failed", err);
  1273. return;
  1274. }
  1275. if (res && res.length == 0) {
  1276. if(handler)
  1277. {
  1278. handler(err,count);
  1279. return;
  1280. }
  1281. ModelUtil.emitOK(self.eventEmitter, {count: count});
  1282. return;
  1283. }
  1284. for (let j in res) {
  1285. //是否过滤指定类型
  1286. if( type != null){
  1287. if(type != res[j].type){
  1288. continue;
  1289. }
  1290. }
  1291. if (res[j].type == SESSION_TYPES.SYSTEM) {
  1292. if (j == res.length - 1) {
  1293. if(handler){
  1294. handler(err,count);
  1295. return;
  1296. }
  1297. ModelUtil.emitOK(self.eventEmitter, {count: count, patient: patientCount, doctor: doctorCount});
  1298. }
  1299. continue;
  1300. }
  1301. callback(res, j, res[j]);
  1302. }
  1303. });
  1304. function callback(res, j, session) {
  1305. self.getSessionUnreadMessageCount(res[j].id, userId, function (err, con) {
  1306. if (err) {
  1307. if(handler)
  1308. {
  1309. handler(err,count);
  1310. return;
  1311. }
  1312. ModelUtil.logError("getAllSessionsUnreadMessageCount is failed", err);
  1313. }
  1314. count = count + con;
  1315. if (session.business_type == SESSION_BUSINESS_TYPE.PATIENT) {
  1316. if(session.status == SESSION_STATUS.ENDED){//新增判断是否咨询结束
  1317. patientEndCount = patientEndCount + con;
  1318. }else{
  1319. patientCount = patientCount + con;
  1320. }
  1321. } else {
  1322. doctorCount = doctorCount + con;
  1323. }
  1324. if (j == res.length - 1) {
  1325. if(handler)
  1326. {
  1327. handler(err,count)
  1328. return;
  1329. }
  1330. ModelUtil.emitOK(self.eventEmitter, {count: count, patient: patientCount,patientEnd: patientEndCount, doctor: doctorCount});
  1331. }
  1332. })
  1333. }
  1334. }
  1335. /**
  1336. * 获取会话的未读消息数。根据成员最后一次获取消息的时候与当前时间。
  1337. *
  1338. * @param sessionId
  1339. * @param userId
  1340. */
  1341. getSessionUnreadMessageCount(sessionId, userId, handler) {
  1342. let self = this;
  1343. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1344. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1345. async.waterfall([
  1346. // 此成员最后获取消息的时间
  1347. function (callback) {
  1348. redis.zscoreAsync(participantsKey, userId)
  1349. .then(function (lastFetchTime) {
  1350. callback(null, lastFetchTime);
  1351. })
  1352. },
  1353. // 计算最后获取消息的时间之后到现在有多少条消息
  1354. function (lastFetchTime, callback) {
  1355. if (!lastFetchTime) lastFetchTime = 0;
  1356. let now = new Date().getTime();
  1357. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, now)
  1358. .then(function (count) {
  1359. if (handler) {
  1360. handler(null, count);
  1361. } else {
  1362. ModelUtil.emitOK(self.eventEmitter, {count: count});
  1363. }
  1364. })
  1365. }
  1366. ], function (err, res) {
  1367. if (err) {
  1368. if (handler) {
  1369. handler(err, 0);
  1370. } else {
  1371. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  1372. }
  1373. }
  1374. });
  1375. }
  1376. /**
  1377. * 获取会话未读消息数。根据成员最后一次获取消息的时候与当前时间。
  1378. */
  1379. getSessionUnreadMessages(sessionId, userId) {
  1380. let self = this;
  1381. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1382. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1383. async.waterfall([
  1384. // 此成员最后获取消息的时间
  1385. function (callback) {
  1386. redis.zscoreAsync(participantsKey, userId)
  1387. .then(function (lastFetchTime) {
  1388. callback(null, lastFetchTime);
  1389. })
  1390. },
  1391. // 最后获取消息的时间之后到现在的消息ID列表
  1392. function (lastFetchTime, callback) {
  1393. if (!lastFetchTime) lastFetchTime = 0;
  1394. let now = new Date().getTime();
  1395. redis.zrangebyscoreAsync(messagesByTimestampKey, lastFetchTime, now)
  1396. .then(function (messageIds) {
  1397. callback(null, messageIds);
  1398. })
  1399. },
  1400. // 获取消息
  1401. function (messageIds, callback) {
  1402. if (messageIds.length == 0) {
  1403. ModelUtil.emitOK(self.eventEmitter, []);
  1404. return;
  1405. }
  1406. let startMsgId = messageIds[0];
  1407. let endMsgId = messageIds[messageIds.length - 1];
  1408. self.getMessagesByPage(sessionId, userId, startMsgId, endMsgId, 0, messageIds.length, 0, function (err, res) {
  1409. if (err) {
  1410. ModelUtil.emitError(self.eventEmitter, err.message);
  1411. return;
  1412. }
  1413. ModelUtil.emitOK(self.eventEmitter, res);
  1414. });
  1415. }
  1416. ], function (err, res) {
  1417. if (err) {
  1418. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  1419. }
  1420. });
  1421. }
  1422. /**
  1423. * 保存消息。
  1424. *
  1425. * 也可以根据议题保存消息,但最终还是保存到与会话对象。
  1426. *
  1427. * see also: saveMessageByTopic
  1428. *
  1429. * @param message
  1430. * @param sessionId
  1431. */
  1432. saveMessageBySession(sessionId, message) {
  1433. let self = this;
  1434. let messages = new Messages();
  1435. let participants = new Participants();
  1436. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1437. let messageId = mongoose.Types.ObjectId().toString();
  1438. let sessionType =0;
  1439. let sessionName;
  1440. message.id = messageId;
  1441. // 检查会话中是否存在此成员
  1442. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1443. if (err) {
  1444. ModelUtil.emitError(self.eventEmitter, "Check session participant failed: ", err);
  1445. return;
  1446. }
  1447. logger.info("session.js--1443--res[0].exist" + res[0].exist);
  1448. log.info("message.sender_id=" + message.sender_id);
  1449. if ( res[0].exist || message.sender_id == "system") {
  1450. redis.hmgetAsync(sessionKey, ["type", "name"]).then(function (res) {
  1451. sessionType = res[0];
  1452. let sessionName = res[1];
  1453. if (sessionType == null) {
  1454. self.getSessions(sessionId,function(err,res){
  1455. if (err){
  1456. logger.error("session data is error");
  1457. } else {
  1458. sessionName=res[0].name;
  1459. sessionType = res[0].type;
  1460. }
  1461. });
  1462. let participantArray = [];
  1463. let participantsStr="{";
  1464. ParticipantRepo.findAll(sessionId, function (err, participants) {
  1465. if (err) {
  1466. ModelUtil.emitError(self.eventEmitter, err.message);
  1467. return;
  1468. }
  1469. participants.forEach(function (participant) {
  1470. let participantId = participant.id;
  1471. let participantRole = participant.role;
  1472. let score = ObjectUtil.timestampToLong(participant.last_fetch_time||(new Date()));
  1473. participantsStr +="\""+participantId+"\":\""+participantRole+"\",";
  1474. });
  1475. participantsStr = participantsStr.substring(0,participantsStr.length-1)+'}';
  1476. participantsStr = JSON.parse(participantsStr);
  1477. for (let j in participantsStr) {
  1478. participantArray.push(j + ":" + participantsStr[j]);
  1479. }
  1480. //创建session到redis
  1481. self.createSessionToRedis(sessionId, sessionName, sessionType, participantArray, messageId, function (err, res) {
  1482. if (err) {
  1483. if (handler) {
  1484. handler(err, null);
  1485. }
  1486. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  1487. } else {
  1488. if (handler) {
  1489. handler(null, res);
  1490. }
  1491. ModelUtil.emitOK(self.eventEmitter, {status: 200, data: res});
  1492. }
  1493. });
  1494. });
  1495. }
  1496. if(sessionType == SESSION_TYPES.MUC ||
  1497. sessionType == SESSION_TYPES.PRESCRIPTION ||
  1498. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1499. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1500. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1501. SESSION_TYPES.GENERAL_EXPERT ||
  1502. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1503. SESSION_TYPES.MUC_VIDEO ||
  1504. SESSION_TYPES.ONDOOR_NURSING){
  1505. if(message.content_type == CONTENT_TYPES.PlainText ||
  1506. message.content_type == CONTENT_TYPES.Image ||
  1507. message.content_type == CONTENT_TYPES.Audio||
  1508. message.content_type == CONTENT_TYPES.Video){
  1509. TopicRepo.findLastBySessionId(sessionId,function(err,res){
  1510. if(res&&res.length>0&&res[0].reply==0){
  1511. TopicRepo.replyTopic(message.sender_id,message.id,res[0].id,function(err,res){
  1512. if(err){
  1513. logger.error("update topic reply error");
  1514. }else{
  1515. logger.warn("update topic reply success");
  1516. }
  1517. });
  1518. }
  1519. })
  1520. }
  1521. }
  1522. // 消息保存到Redis,并更新会话最后状态、用户最后消息获取时间
  1523. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1524. Messages.updateLastContent(sessionKey, sessionType, sessionName, message);
  1525. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1526. // 更新MYSQL中会话的最新状态,并保存消息
  1527. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1528. messages.saveMessageToMysql(sessionId, sessionType, messageId, message, function (err, res) {
  1529. if (err) {
  1530. ModelUtil.emitError(self.eventEmitter, {message: "Failed to save message to mysql: " + err});
  1531. } else {
  1532. message.timestamp = message.timestamp.getTime();
  1533. ModelUtil.emitOK(self.eventEmitter, {count: 1, messages: [message]});
  1534. }
  1535. });
  1536. }).then(function (res) {
  1537. // 推送消息
  1538. ParticipantRepo.findIds(sessionId, function (err, res) {
  1539. if (err) {
  1540. ModelUtil.logError("Push message from session: get participant's id list failed: ", err);
  1541. } else {
  1542. message.session_id = sessionId;
  1543. res.forEach(function (participant) {
  1544. if (participant.id == message.sender_id||sessionType==SESSION_TYPES.SYSTEM){
  1545. message.sender_img = participant.avatar;
  1546. callPush(res,message);
  1547. }
  1548. })
  1549. }
  1550. })
  1551. }).catch(function (err) {
  1552. ModelUtil.emitError(self.eventEmitter, {message: "Error occurred while save message to session: " + err});
  1553. })
  1554. } else {
  1555. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "当前会话找不到此发送者"});
  1556. }
  1557. });
  1558. function callPush(participants,message){
  1559. participants.forEach(function (participant) {
  1560. if (participant.id !== message.sender_id &&
  1561. participant.participant_role == PARTICIPANT_ROLES.HOST) {
  1562. Sessions.pushNotification(participant.id, participant.name, message,sessionType);
  1563. }
  1564. });
  1565. }
  1566. }
  1567. sendTopicMessages(topicId, message) {
  1568. let self = this;
  1569. TopicRepo.findAllByTopicId(topicId, function (err, res) {
  1570. if (err || res.length == 0) {
  1571. ModelUtil.emitOK(self.eventEmitter, {status: -1, "message": "议题获取失败"});
  1572. return;
  1573. }
  1574. self.saveMessageByTopic(message, res[0].session_id, function (err, messageId) {
  1575. if (err) {
  1576. ModelUtil.emitOK(self.eventEmitter, {status: -1, "message": err});
  1577. } else {
  1578. message.id = messageId;
  1579. ModelUtil.emitOK(self.eventEmitter, {status: 200, "message": "发送成功", data: message});
  1580. }
  1581. });
  1582. });
  1583. }
  1584. /**
  1585. * 保存消息
  1586. *
  1587. * @param message
  1588. * @param sessionId
  1589. * @param handler
  1590. */
  1591. saveMessageByTopic(message, sessionId, handler) {
  1592. let messages = new Messages();
  1593. let participants = new Participants();
  1594. let session_key = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1595. let messageId = mongoose.Types.ObjectId().toString();
  1596. let self = this;
  1597. let sessionType = 0;
  1598. let sessionName = "";
  1599. let agent = message.agent;//代理人
  1600. message.id = messageId;
  1601. if(!message.timestamp){
  1602. message.timestamp = new Date();
  1603. }
  1604. // 发送成员必须处于会话中
  1605. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1606. log.info("1599-message.sender_id=" + message.sender_id);
  1607. log.info("res[0].exist=" + res[0].exist);
  1608. if ( res[0].exist || message.sender_id == "system") {
  1609. redis.hmgetAsync(session_key, ["type", "name"]).then(function (res) {
  1610. sessionType = res[0];
  1611. sessionName = res[1];
  1612. if (!sessionType || !sessionName) {
  1613. logger.error("Unknown session key " + session_key);
  1614. if (handler) {
  1615. handler(new Error("Unknown session key " + session_key));return;
  1616. };
  1617. }
  1618. }).then(function (res) {
  1619. // 消息数据双写,并更新用户最后消息获取时间,会话新状态等
  1620. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1621. messages.saveMessageToMysql(sessionId, sessionType, messageId, message);
  1622. // 更新会话最新状态及成员最后一次消息获取时间
  1623. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1624. Messages.updateLastContent(session_key, sessionType, sessionName, message);
  1625. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1626. if (handler) {
  1627. handler(null, messageId);
  1628. return;
  1629. }
  1630. }).then(function (res) {
  1631. // 推送消息
  1632. ParticipantRepo.findIds(sessionId, function (err, res) {
  1633. if (err) {
  1634. logger.error(err);
  1635. } else {
  1636. message.session_id = sessionId;
  1637. res.forEach(function (participant) {
  1638. if (participant.id == message.sender_id){
  1639. message.sender_img = participant.avatar;
  1640. callPush(res,message);
  1641. }
  1642. })
  1643. }
  1644. })
  1645. }).catch(function (err) {
  1646. log.error(err);
  1647. return;
  1648. })
  1649. } else {
  1650. if (handler){ handler("用户不在此会话当中!", messageId);return;}
  1651. }
  1652. });
  1653. function callPush(participants,message){
  1654. participants.forEach(function (participant) {
  1655. if ((participant.id !== message.sender_id||message.content_type == CONTENT_TYPES.PrescriptionBloodStatus ||
  1656. message.content_type == CONTENT_TYPES.PrescriptionFollowupContent) &&
  1657. participant.participant_role == PARTICIPANT_ROLES.HOST) {
  1658. Sessions.pushNotification(participant.id, participant.name, message,sessionType);
  1659. }
  1660. });
  1661. }
  1662. }
  1663. /**
  1664. * 保存代理人进入的消息
  1665. *
  1666. * @param message
  1667. * @param sessionId
  1668. * @param handler
  1669. */
  1670. saveIntoMessageByTopic(message, sessionId, handler) {
  1671. log.info("2--保存代理人进入的消息:");
  1672. let messages = new Messages();
  1673. let participants = new Participants();
  1674. let session_key = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1675. let messageId = mongoose.Types.ObjectId().toString();
  1676. let self = this;
  1677. let sessionType = 0;
  1678. let sessionName = "";
  1679. let agent = message.agent;//代理人
  1680. message.id = messageId;
  1681. if(!message.timestamp){
  1682. message.timestamp = new Date();
  1683. }
  1684. // 发送成员必须处于会话中
  1685. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1686. log.info("session.js--1477--res[0].exist" + res[0].exist);
  1687. log.info("message.sender_id=" + message.sender_id);
  1688. if (res[0].exist || message.sender_id == "system") {
  1689. redis.hmgetAsync(session_key, ["type", "name"]).then(function (res) {
  1690. sessionType = res[0];
  1691. sessionName = res[1];
  1692. if (!sessionType || !sessionName) {
  1693. logger.error("Unknown session key " + session_key);
  1694. if (handler) {
  1695. handler(new Error("Unknown session key " + session_key));return;
  1696. };
  1697. }
  1698. }).then(function (res) {
  1699. //查找最后一条数据,如果一致就不保存
  1700. MessageRepo.findLastMessage(sessionId,sessionType,function (err, res) {
  1701. if (err) {
  1702. logger.error(err);
  1703. } else {
  1704. res.forEach(function (mes) {
  1705. // if(mes.content==message.content&&message.content_type==mes.content_type){
  1706. if(mes.agent==message.agent){
  1707. handler(null, messageId);
  1708. return;
  1709. }else {
  1710. // 消息数据双写,并更新用户最后消息获取时间,会话新状态等
  1711. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1712. messages.saveMessageToMysql(sessionId, sessionType, messageId, message);
  1713. // 更新会话最新状态及成员最后一次消息获取时间
  1714. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1715. Messages.updateLastContent(session_key, sessionType, sessionName, message);
  1716. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1717. if (handler) {
  1718. handler(null, messageId);
  1719. return;
  1720. }
  1721. }
  1722. })
  1723. }
  1724. });
  1725. }).then(function (res) {
  1726. // 推送消息
  1727. ParticipantRepo.findDoctorIds(sessionId, function (err, res) {
  1728. if (err) {
  1729. logger.error(err);
  1730. } else {
  1731. message.session_id = sessionId;
  1732. res.forEach(function (participant) {
  1733. Sessions.pushIntoNotification(participant.id, participant.name, message,sessionType);
  1734. })
  1735. }
  1736. })
  1737. }).catch(function (err) {
  1738. log.error(err);
  1739. return;
  1740. })
  1741. } else {
  1742. log.info("4--用户不在此会话当中!");
  1743. if (handler){ handler("用户不在此会话当中!", messageId);return;}
  1744. }
  1745. });
  1746. }
  1747. /**
  1748. * 置顶操作
  1749. */
  1750. stickSession(sessionId, user) {
  1751. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  1752. let self = this;
  1753. //取出最大的session
  1754. redis.zrevrangeAsync(user_session_key, 0, 0).then(function (res) {
  1755. //获取该session的时间搓
  1756. redis.zscoreAsync(user_session_key, res).then(function (scoreres) {
  1757. let nowtime = new Date().getTime();
  1758. //当前时间搓比redis的时间搓更早证明没有置顶过
  1759. if (scoreres <= nowtime) {
  1760. //初始化置顶
  1761. redis.zaddAsync(user_session_key, STICKY_SESSION_BASE_SCORE, sessionId).then(function (res) {
  1762. logger.info("stickSession:" + sessionId + ",res:" + res);
  1763. ModelUtil.emitOK(self.eventEmitter, {});
  1764. }).then(function () {
  1765. SessionRepo.saveStickySession(sessionId, user, STICKY_SESSION_BASE_SCORE);
  1766. })
  1767. } else {
  1768. //已有置顶的数据,取出来加1保存回去
  1769. scoreres = Number(scoreres) + 1;
  1770. redis.zaddAsync(user_session_key, scoreres, sessionId).then(function () {
  1771. logger.info("stickSession:" + sessionId + ",res:" + res);
  1772. ModelUtil.emitOK(self.eventEmitter, {});
  1773. }).then(function () {
  1774. SessionRepo.saveStickySession(sessionId, user, scoreres);
  1775. })
  1776. }
  1777. })
  1778. })
  1779. }
  1780. /**
  1781. * 取消会话置顶
  1782. */
  1783. cancelStickSession(sessionId, user) {
  1784. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  1785. let participants_key = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1786. let self = this;
  1787. redis.zscoreAsync(participants_key, user).then(function (res) {
  1788. if (!res) {
  1789. res = new Date().getTime();
  1790. }
  1791. redis.zaddAsync(user_session_key, res, sessionId).then(function (res) {
  1792. logger.info("cancelStickSession:" + sessionId);
  1793. ModelUtil.emitOK(self.eventEmitter, {});
  1794. }).then(function () {
  1795. SessionRepo.unStickySession(sessionId, user);
  1796. });
  1797. })
  1798. }
  1799. /**
  1800. * 更新会话参与者的最后消息获取时间。
  1801. *
  1802. * @param sessionId
  1803. * @param userId
  1804. */
  1805. static updateParticipantLastFetchTime(sessionId, userId, score) {
  1806. score = score + 1;
  1807. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1808. redis.zaddAsync(participantsKey, score, userId)
  1809. .then(function (res) {
  1810. ParticipantRepo.updateLastFetchTime(new Date(score), sessionId, userId, function (err, res) {
  1811. if (err) {
  1812. logger.error("Update participant last fetch time failed: ", err);
  1813. }
  1814. });
  1815. })
  1816. .catch(function (err) {
  1817. logger.error("Update participant last fetch time failed: ", err);
  1818. });
  1819. }
  1820. /**
  1821. * 向用户推送通知,微信端用户直接推送消息,APP端通过个推发送通知消息。
  1822. *
  1823. * @param targetUserId
  1824. * @param message
  1825. */
  1826. static pushNotification(targetUserId, targetUserName, message,sessionType) {
  1827. let self = this;
  1828. Users.isPatientId(targetUserId, function (err, isPatient) {
  1829. if (isPatient) {
  1830. if(config.environment!='local'){//pc版不直接发送给居民,通过redis的publish
  1831. WechatClient.sendMessage(targetUserId, targetUserName, message);
  1832. }
  1833. message.targetUserId = targetUserId;
  1834. message.targetUserName = targetUserName;
  1835. message.sessionType = sessionType;
  1836. message.targetType = 'patient';
  1837. } else {
  1838. if(sessionType==SESSION_TYPES.P2P){
  1839. WechatClient.sendReadDoctorByDoctorId(targetUserId, message);
  1840. }
  1841. //告知医生新消息
  1842. WechatClient.sendSocketMessageToDoctor(targetUserId,message);
  1843. let count = 0;
  1844. //系统消息
  1845. // MessageRepo.getWlyyMessageCount(targetUserId,function (err,res) {
  1846. // if(res){
  1847. // count = res[0].count;
  1848. // }
  1849. // });
  1850. //im消息
  1851. let sessions = new Sessions();
  1852. sessions.getAllSessionsUnreadMessageCount(targetUserId,null,function (err,res) {
  1853. if(res){
  1854. count += res;
  1855. }
  1856. });
  1857. if(config.environment!='local'){//pc版不推送个推,通过redis的publish
  1858. log.info("推送医生智能助手")
  1859. AppClient.sendNotification(targetUserId, message,sessionType,count);
  1860. }
  1861. //外网pcim通过socket推送
  1862. WechatClient.sendPcImSocket(targetUserId,message,sessionType);
  1863. // WlyySDK.request(targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
  1864. // let count = 0;
  1865. // if(err){
  1866. // logger.error(err);
  1867. // }else {
  1868. // logger.error(res);
  1869. // res = JSON.parse(res)
  1870. // if (res.status == 200) {
  1871. // let data = res.data;
  1872. // count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
  1873. // }
  1874. // }
  1875. // if(config.environment!='local'){//pc版不推送个推,通过redis的publish
  1876. // AppClient.sendNotification(targetUserId, message,sessionType,count);
  1877. // }
  1878. // //外网pcim通过socket推送
  1879. // WechatClient.sendPcImSocket(targetUserId,message,sessionType);
  1880. // });
  1881. message.targetUserId = targetUserId;
  1882. message.targetUserName = targetUserName;
  1883. message.sessionType = sessionType;
  1884. message.targetType = 'doctor';
  1885. //推送MDT,医生外层新消息
  1886. WechatClient.sendMDTSocketMessageToDoctor(targetUserId,message);
  1887. }
  1888. //redis发布消息
  1889. if(config.pubSubSwitch) {//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
  1890. pubSub.publish(config.pubChannel,JSON.stringify(message));
  1891. }
  1892. });
  1893. }
  1894. /**
  1895. * 获取redis订阅消息,并处理
  1896. * @param targetUserId
  1897. * @param targetUserName
  1898. * @param message
  1899. * @param sessionType
  1900. */
  1901. static getRedisPushNotification(message) {
  1902. if (message.targetType=='patient') {
  1903. if(config.environment!='local'){//pc版接收要发给居民的消息不做处理
  1904. WechatClient.sendMessage(message.targetUserId, message.targetUserName, message);
  1905. }
  1906. } else {
  1907. if(message.sessionType==SESSION_TYPES.P2P){
  1908. WechatClient.sendReadDoctorByDoctorId(message.targetUserId, message);
  1909. }
  1910. //告知医生新消息
  1911. WechatClient.sendSocketMessageToDoctor(message.targetUserId,message);
  1912. if(config.environment!='local'){//pc版不推送个推
  1913. WlyySDK.request(message.targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
  1914. let count = 0;
  1915. res = JSON.parse(res)
  1916. if (res.status == 200) {
  1917. let data = res.data;
  1918. count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
  1919. }
  1920. AppClient.sendNotification(message.targetUserId, message,message.sessionType,count);
  1921. });
  1922. }
  1923. }
  1924. }
  1925. /**
  1926. * 向APP端通过socket发送通知消息。
  1927. *
  1928. * @param targetUserId
  1929. * @param message
  1930. */
  1931. static pushIntoNotification(targetUserId, targetUserName, message,sessionType) {
  1932. if(sessionType==SESSION_TYPES.P2P){
  1933. WechatClient.sendReadDoctorByDoctorId(targetUserId, message);
  1934. }
  1935. //告知医生新消息
  1936. WechatClient.sendSocketMessageToDoctor(targetUserId,message);
  1937. }
  1938. /**
  1939. * 针对MUC模式更新会话的当前状态
  1940. * @param sessionId
  1941. */
  1942. updateSessionStatus(sessionId,status,handler){
  1943. let self = this;
  1944. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session,sessionId);
  1945. redis.hsetAsync(sessionKey,"status",status).then(function(res){
  1946. SessionRepo.updateSessionStatus(sessionId,status,function(err,sqlResult){
  1947. if(handler){
  1948. handler(err,sqlResult);
  1949. return;
  1950. }
  1951. if(err){
  1952. logger.error("set session status to mysql is error !");
  1953. }else{
  1954. logger.info("set session status is success");
  1955. ModelUtil.emitOK(self.eventEmitter, []);
  1956. }
  1957. });
  1958. });
  1959. }
  1960. /**
  1961. * 针对专科医生和家医模式更新会话的名称
  1962. * @param sessionId
  1963. * @param name
  1964. */
  1965. updateSessionName(sessionId,name,handler){
  1966. let self = this;
  1967. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session,sessionId);
  1968. redis.hsetAsync(sessionKey,"name",name).then(function(res){
  1969. SessionRepo.updateSessionName(sessionId,name,function(err,sqlResult){
  1970. if(handler){
  1971. handler(err,sqlResult);
  1972. return;
  1973. }
  1974. if(err){
  1975. logger.error("set session name to mysql is error !");
  1976. ModelUtil.emitError(self.eventEmitter,"set session name to mysql is error !",err)
  1977. }else{
  1978. logger.info("set session name is success");
  1979. ModelUtil.emitOK(self.eventEmitter, []);
  1980. }
  1981. });
  1982. });
  1983. }
  1984. }
  1985. // Expose class
  1986. module.exports = Sessions;