sessions.js 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  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/mysql/doctor.repo');
  11. let Participants = require('./participants');
  12. let SessionRepo = require('../../repository/mysql/session.repo');
  13. let TopicRepo = require('../../repository/mysql/topics.repo');
  14. let MessageRepo = require('../../repository/mysql/message.repo');
  15. let ParticipantRepo = require('../../repository/mysql/participant.repo');
  16. let ImDb = require('../../repository/mysql/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. let backTopid = null;
  484. //处理session未加入redis的bug
  485. log.info("1.session==null:" + session==null);
  486. if(session==null){
  487. let lastLoginTime = new Date();
  488. SessionRepo.findOne(sessionId, function (err, res) {
  489. if(res){
  490. session = res;
  491. log.info("1.session.id:" + session.id);
  492. log.info("1.session.name:" + session.name);
  493. log.info("1.session.business_type:" + session.business_type);
  494. let redisSession = [
  495. "id", session.id,
  496. "name", session.name,
  497. "type", session.type,
  498. "business_type", session.business_type,
  499. "last_sender_id", session.last_sender_id||"",
  500. "last_sender_name", session.last_sender_name||"",
  501. "last_content_type", session.last_content_type||"",
  502. "last_content", session.last_content||"",
  503. "last_message_time", session.last_message_time||"",
  504. "create_date", ObjectUtil.timestampToLong(session.create_date),
  505. "status",session.status==null?0:session.status
  506. ];
  507. // cache sessions
  508. redis.multi()
  509. .zadd(REDIS_KEYS.Sessions, lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  510. .zadd(RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId), lastLoginTime.getTime(), sessionId) // 会话的最后活动时间设置为此用户的登录时间
  511. .hmset(RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId), redisSession)
  512. .execAsync()
  513. .then(function (res) {
  514. // cache participants
  515. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  516. let sessionParticipantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  517. ParticipantRepo.findAll(sessionId, function (err, participants) {
  518. if (err) {
  519. ModelUtil.emitError(self.eventEmitter, err.message);
  520. return;
  521. }
  522. let multi = redis.multi();
  523. participants.forEach(function (participant) {
  524. let participantId = participant.id;
  525. let participantRole = participant.role;
  526. let score = ObjectUtil.timestampToLong(participant.last_fetch_time||(new Date()));
  527. multi = multi.zadd(sessionParticipantsKey, score, participantId)
  528. .hset(sessionParticipantsRoleKey, participantId, participantRole);
  529. });
  530. multi.execAsync()
  531. .then(function (res) {
  532. })
  533. .catch(function (ex) {
  534. log.error("Login failed while caching participants: ", ex);
  535. });
  536. });
  537. // cache messages
  538. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  539. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  540. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, null, function (err, messages) {
  541. if (err) {
  542. ModelUtil.emitError(self.eventEmitter, err.message);
  543. return;
  544. }
  545. let multi = redis.multi();
  546. messages.forEach(function (message) {
  547. let msgJson = {
  548. id: message.id,
  549. sender_id: message.sender_id,
  550. sender_name: message.sender_name,
  551. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  552. content_type: message.content_type,
  553. content: message.content
  554. };
  555. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  556. .zadd(messagesByTimestampKey, ObjectUtil.timestampToLong(message.timestamp), message.id);
  557. });
  558. multi.execAsync()
  559. .then(function (res) {
  560. })
  561. .catch(function (ex) {
  562. log.error("Login failed while caching messages: ", ex);
  563. });
  564. });
  565. // cache topics for MUC
  566. let topicsKey = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
  567. log.info("gettopicid====")
  568. TopicRepo.findAllBySessionId(sessionId, function (err, topics) {
  569. log.info("gettopicid====1")
  570. if (err) {
  571. ModelUtil.emitError(self.eventEmitter, err.message);
  572. return;
  573. }
  574. topics.forEach(function (topic) {
  575. log.info("gettopicid====2")
  576. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  577. let topicId = topic.id;
  578. backTopid = topicId;
  579. let name = topic.name == null ? "" : topic.name;
  580. let createTime = ObjectUtil.timestampToLong(topic.create_time);
  581. let endBy = topic.end_by == null ? "" : topic.end_by;
  582. let endTime = topic.end_time == null ? 0 : ObjectUtil.timestampToLong(topic.end_time);
  583. let startMessageId = topic.start_message_id == null ? "" : topic.start_message_id;
  584. let endMessageId = topic.end_message_id == null ? "" : topic.end_message_id;
  585. let description = topic.description == null ? "" : topic.description;
  586. let status = topic.status == null ? 0 : topic.status;
  587. redisConn.multi()
  588. .zadd(topicsKey, createTime, topicId)
  589. .hmset(topicKey,
  590. 'name', name,
  591. 'session_id', sessionId,
  592. 'create_time', createTime,
  593. 'end_by', endBy,
  594. 'end_time', endTime,
  595. 'start_message_id', startMessageId,
  596. 'end_message_id', endMessageId,
  597. 'description', description,
  598. 'topic_id', topicId,
  599. 'status', status)
  600. .execAsync()
  601. .catch(function (ex) {
  602. log.error("Login failed while caching topics: ", ex);
  603. });
  604. });
  605. });
  606. })
  607. .catch(function (ex) {
  608. log.error("Login failed while caching sessions: ", ex);
  609. });
  610. }
  611. });
  612. }
  613. for(var j in userRoles){
  614. if(userRoles[j]==1){
  615. isInvite = false;
  616. break;
  617. }
  618. }
  619. for(var j = 0 ;j<participantsTimeArray.length;j++){
  620. if(j%2!=0)continue;
  621. let participantsTimeJson = {};
  622. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  623. participantsTime.push(participantsTimeJson);
  624. }
  625. let sessionName = "";
  626. let otherUserId = "";
  627. if (session.type == SESSION_TYPES.P2P) {
  628. for (let j in users) {
  629. if (users[j] != userId) {
  630. otherUserId = users[j];
  631. }
  632. }
  633. }
  634. if (!role) role = 0;
  635. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  636. // 计算未读消息数
  637. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  638. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  639. .then(function (count) {
  640. if (!otherUserId) otherUserId = userId;
  641. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  642. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  643. sessionName = session.name;
  644. } else {
  645. sessionName = res[0].name;
  646. }
  647. var bir = new Date().getTime();
  648. if (res.length != 0 && res[0].birthdate) {
  649. bir = res[0].birthdate.getTime();
  650. }
  651. var sex = 1;
  652. if (res.length != 0 && res[0].sex) {
  653. sex = res[0].sex;
  654. }
  655. //end
  656. log.info("2.session.id:" + sessionId);
  657. log.info("2.session.name:" + sessionName);
  658. log.info("2.session.business_type:" + session.business_type);
  659. TopicRepo.findAllBySessionId(sessionId, function (err, topics) {
  660. log.info("gettopicid====1")
  661. if (err) {
  662. ModelUtil.emitError(self.eventEmitter, err.message);
  663. return;
  664. }
  665. topics.forEach(function (topic) {
  666. log.info("gettopicid====2")
  667. let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topic.id);
  668. let topicId = topic.id;
  669. });
  670. });
  671. sessionList.push({
  672. id: sessionId,
  673. name: sessionName,
  674. create_date: session.create_date,
  675. last_content_type: session.last_content_type||"",
  676. last_content: session.last_content||"",
  677. sender_id: session.last_sender_id||"",
  678. type: session.type,
  679. sender_name: session.last_sender_name||"",
  680. unread_count: count,
  681. // business_type: session.business_type,
  682. business_type: businessType,
  683. my_role: role,
  684. sender_sex: sex,
  685. sender_birthday: bir,
  686. participantsTimeArray:participantsTime,
  687. status:session.status,
  688. is_invite:isInvite,
  689. backTopid:backTopid
  690. });
  691. index = (parseInt(index) + 1);
  692. if (index == sessionIds.length) {
  693. ModelUtil.emitOK(self.eventEmitter, sessionList);
  694. } else {
  695. callback(null, index);
  696. }
  697. })
  698. })
  699. })
  700. .catch(function (err) {
  701. logger.error("Get sessions failed: ", err);
  702. });
  703. };
  704. functionList.push(fun);
  705. }
  706. async.waterfall(functionList);
  707. }
  708. ]);
  709. }
  710. /**
  711. * 查找会话数
  712. * @param userId
  713. * @param type
  714. * @param status
  715. * @param handler
  716. */
  717. getSessionCountByType(userId,type,status,handler){
  718. let self = this;
  719. SessionRepo.findSessionCountByType(userId,type,status,function (err,res) {
  720. if(res){
  721. ModelUtil.emitOK(self.eventEmitter,{status:200,count:res[0].count});
  722. return;
  723. }else {
  724. ModelUtil.emitOK(self.eventEmitter,{status:200,count:0});
  725. return;
  726. }
  727. })
  728. }
  729. /**
  730. * 根据用户类型获取用户的session列表
  731. * @param userId
  732. * @param page
  733. * @param size
  734. * @param businessType
  735. * @param status 0:进行中的会话1:结束的会话
  736. */
  737. getUserSessionsByType(userId,type,page, size,status) {
  738. logger.info("根据用户类型获取用户的session列表1: ");
  739. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  740. let self = this;
  741. logger.info("根据用户类型获取用户的session列表2: ");
  742. async.waterfall([
  743. // 获取会话ID列表
  744. function (callback) {
  745. SessionRepo.findListByType(userId,type,page,size,status,function(err,res){
  746. logger.info("根据用户类型获取用户的session列表: res :"+res);
  747. if (res == null || res.length == 0) {
  748. ModelUtil.emitOK(self.eventEmitter, []);
  749. return;
  750. }
  751. callback(null,res);
  752. })
  753. },
  754. // 遍历会话
  755. function (sessionIds) {
  756. let sessionList = [];
  757. let functionList = [];
  758. for (let j = 0; j < sessionIds.length; j++) {
  759. let fun = function (index, callback) {
  760. if (!callback) {
  761. callback = index, index = 0
  762. }
  763. let mysqlSession = sessionIds[index];
  764. let sessionId = mysqlSession.id;
  765. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  766. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  767. redis.multi()
  768. .hgetall(sessionKey) // 会话实体
  769. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  770. .zrange(sessionParticipantsKey, 0, -1)
  771. .zrange(sessionParticipantsKey, 0,-1,'withscores') // 所有用户在此会话中最后一次获取未读消息的时间
  772. .execAsync()
  773. .then(function (res) {
  774. let session = res[0];
  775. let lastFetchTime = res[1];
  776. let users = res[2];
  777. let participantsTimeArray = res[3];
  778. let participantsTime = [];
  779. for(var j = 0 ;j<participantsTimeArray.length;j++){
  780. if(j%2!=0)continue;
  781. let participantsTimeJson = {};
  782. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  783. participantsTime.push(participantsTimeJson);
  784. }
  785. let sessionName = "";
  786. let otherUserId = "";
  787. if (session.type == SESSION_TYPES.P2P) {
  788. for (let j in users) {
  789. if (users[j] != userId) {
  790. otherUserId = users[j];
  791. }
  792. }
  793. }
  794. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  795. // 计算未读消息数
  796. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  797. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  798. .then(function (count) {
  799. if (!otherUserId) otherUserId = userId;
  800. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  801. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  802. sessionName = session.name;
  803. } else {
  804. sessionName = res[0].name;
  805. }
  806. var bir = new Date().getTime();
  807. if (res && res.length != 0 && res[0].birthdate) {
  808. bir = res[0].birthdate.getTime();
  809. }
  810. var sex = 1;
  811. if (res && res.length != 0 && res[0].sex) {
  812. sex = res[0].sex;
  813. }
  814. sessionList.push({
  815. id: sessionId,
  816. name: sessionName,
  817. create_date: new Date(mysqlSession.last_message_time).getTime(),
  818. last_content_type: session.last_content_type,
  819. last_content: session.last_content,
  820. sender_id: session.last_sender_id,
  821. type: session.type,
  822. sender_name: session.last_sender_name,
  823. unread_count: count,
  824. business_type: session.business_type,
  825. sender_sex: sex,
  826. sender_birthday: bir,
  827. participantsTimeArray:participantsTime,
  828. status:session.status,
  829. });
  830. index = (parseInt(index) + 1);
  831. if (index == sessionIds.length) {
  832. ModelUtil.emitOK(self.eventEmitter, sessionList);
  833. } else {
  834. callback(null, index);
  835. }
  836. })
  837. })
  838. })
  839. .catch(function (err) {
  840. logger.error("Get sessions:"+sessionId+" failed: ", err);
  841. });
  842. };
  843. functionList.push(fun);
  844. }
  845. async.waterfall(functionList);
  846. }
  847. ]);
  848. }
  849. /**
  850. * 根据用户ID获取用户已经结束咨询的session列表
  851. * @param userId
  852. * @param page
  853. * @param size
  854. * @param businessType
  855. */
  856. getUserStatusSessions(userId,status,businessType,page, size) {
  857. let userSessionKey = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, userId);
  858. log.info(userId);
  859. let self = this;
  860. async.waterfall([
  861. // 获取会话ID列表
  862. function (callback) {
  863. SessionRepo.findAllByTypeAndStatus(userId,businessType,status,page,size,function(err,res){
  864. if (res && res.length == 0) {
  865. ModelUtil.emitOK(self.eventEmitter, []);
  866. return;
  867. }
  868. // var sessionIds=[];
  869. // for(var j in res){
  870. // sessionIds.push(res[j].id);
  871. // }
  872. callback(null,res);
  873. })
  874. },
  875. // 遍历会话
  876. function (sessionIds) {
  877. let sessionList = [];
  878. let functionList = [];
  879. for (let j = 0; j < sessionIds.length; j++) {
  880. let fun = function (index, callback) {
  881. if (!callback) {
  882. callback = index, index = 0
  883. }
  884. let mysqlSession = sessionIds[index];
  885. let sessionId = mysqlSession.id;
  886. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  887. let participantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
  888. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  889. redis.multi()
  890. .hgetall(sessionKey) // 会话实体
  891. .hget(participantsRoleKey, userId) // 用户在此会话中的角色
  892. .zscore(sessionParticipantsKey, userId) // 用户在此会话中最后一次获取未读消息的时间
  893. .zrange(sessionParticipantsKey, 0, -1)
  894. .zrange(sessionParticipantsKey, 0,-1,'withscores') // 所有用户在此会话中最后一次获取未读消息的时间
  895. .hgetall(participantsRoleKey) // 所有用户在此会话中角色
  896. .execAsync()
  897. .then(function (res) {
  898. let session = res[0];
  899. let role = res[1];
  900. let lastFetchTime = res[2];
  901. let users = res[3];
  902. let participantsTimeArray = res[4];
  903. let userRoles = res[5];
  904. let participantsTime = [];
  905. let isInvite = true;
  906. for(var j in userRoles){
  907. if(userRoles[j]==1){
  908. isInvite = false;
  909. break;
  910. }
  911. }
  912. for(var j = 0 ;j<participantsTimeArray.length;j++){
  913. if(j%2!=0)continue;
  914. let participantsTimeJson = {};
  915. participantsTimeJson[participantsTimeArray[j]] = participantsTimeArray[j+1];
  916. participantsTime.push(participantsTimeJson);
  917. }
  918. let sessionName = "";
  919. let otherUserId = "";
  920. if (session.type == SESSION_TYPES.P2P) {
  921. for (let j in users) {
  922. if (users[j] != userId) {
  923. otherUserId = users[j];
  924. }
  925. }
  926. }
  927. if (!role) role = 0;
  928. if (!lastFetchTime) lastFetchTime = new Date().getTime();
  929. // 计算未读消息数
  930. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  931. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, new Date().getTime())
  932. .then(function (count) {
  933. if (!otherUserId) otherUserId = userId;
  934. ParticipantRepo.findNameById(otherUserId, function (err, res) {
  935. if ((res && res.length == 0) || session.type != SESSION_TYPES.P2P) {
  936. sessionName = session.name;
  937. } else {
  938. sessionName = res[0].name;
  939. }
  940. var bir = new Date().getTime();
  941. if (res && res.length != 0 && res[0].birthdate) {
  942. bir = res[0].birthdate.getTime();
  943. }
  944. var sex = 1;
  945. if (res.length != 0 && res[0].sex) {
  946. sex = res[0].sex;
  947. }
  948. sessionList.push({
  949. id: sessionId,
  950. name: sessionName,
  951. create_date: new Date(mysqlSession.last_message_time).getTime(),
  952. last_content_type: session.last_content_type,
  953. last_content: session.last_content,
  954. sender_id: session.last_sender_id,
  955. type: session.type,
  956. sender_name: session.last_sender_name,
  957. unread_count: count,
  958. business_type: session.business_type,
  959. my_role: role,
  960. sender_sex: sex,
  961. sender_birthday: bir,
  962. participantsTimeArray:participantsTime,
  963. status:session.status,
  964. is_invite:isInvite
  965. });
  966. index = (parseInt(index) + 1);
  967. if (index == sessionIds.length) {
  968. ModelUtil.emitOK(self.eventEmitter, sessionList);
  969. } else {
  970. callback(null, index);
  971. }
  972. })
  973. })
  974. })
  975. .catch(function (err) {
  976. logger.error("Get sessions:"+sessionId+" failed: ", err);
  977. });
  978. };
  979. functionList.push(fun);
  980. }
  981. async.waterfall(functionList);
  982. }
  983. ]);
  984. }
  985. /**
  986. * 获取会话消息。全部,不管已读/未读状态。
  987. *
  988. * @param sessionId 会话ID
  989. * @param userId 拉取消息的人
  990. * @param page 第几页
  991. * @param pagesize 分页数量
  992. * @param start_msg_id 消息会话最新的一条消息的ID
  993. * @param end_msg_id 消息会话刚开始的消息ID
  994. * @remark
  995. * start_msg_id end_msg_id 为空取会话倒序的根据分页的消息数据
  996. * start_msg_id 为空 end_msg_id 不为空根据end_msg_id取旧的消息(offset=1可以排除本身)返回指定分页的数据
  997. * end_msg_id 为空 start_msg_id 不为空 根据 start_msg_id 取出新消息(offset=1可以排除本身)返回指定分页的数据
  998. * end_msg_id start_msg_id 都不为空返回指定区间的消息
  999. */
  1000. getMessages(sessionId, user, start_msg_id, end_msg_id, page, pagesize, isoffset, handler) {
  1001. let self = this;
  1002. let message_timestamp_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1003. if (!start_msg_id && !end_msg_id) {
  1004. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1005. logger.info("redis return res-----"+res);
  1006. // log.info("session.js--830---getMessages res.length: " + res.length);
  1007. if (res && res.length == 0) {
  1008. //修复应redis没有缓冲聊天记录导致会话列表加载不出来
  1009. // cache messages
  1010. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  1011. MessageRepo.findBySessionId(sessionId, 0, config.sessionConfig.maxMessageCount, null, function (err, messages) {
  1012. if (err) {
  1013. ModelUtil.emitError(self.eventEmitter, err.message);
  1014. return;
  1015. }
  1016. let multi = redis.multi();
  1017. messages.forEach(function (message) {
  1018. let msgJson = {
  1019. id: message.id,
  1020. sender_id: message.sender_id,
  1021. sender_name: message.sender_name,
  1022. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  1023. content_type: message.content_type,
  1024. content: message.content
  1025. };
  1026. multi = multi.hset(messagesKey, message.id, JSON.stringify(msgJson))
  1027. .zadd(message_timestamp_key, ObjectUtil.timestampToLong(message.timestamp), message.id);
  1028. });
  1029. multi.execAsync()
  1030. .then(function (res) {
  1031. })
  1032. .catch(function (ex) {
  1033. log.error("Login failed while caching messages: ", ex);
  1034. ModelUtil.emitOK(self.eventEmitter, res);
  1035. return;
  1036. });
  1037. });
  1038. // if (handler) {
  1039. // handler(null, res);
  1040. // return;
  1041. // }
  1042. // ModelUtil.emitOK(self.eventEmitter, res);
  1043. // return;
  1044. }
  1045. start_msg_id = res[0];
  1046. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1047. if (res && res.length == 0) {
  1048. if (handler) {
  1049. handler(null, res);
  1050. return;
  1051. }
  1052. ModelUtil.emitOK(self.eventEmitter, res);
  1053. return;
  1054. }
  1055. end_msg_id = res[0];
  1056. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  1057. if (err) {
  1058. if (handler) {
  1059. handler(err, null);
  1060. return;
  1061. }
  1062. logger.error("getMessagesByPage error" + err);
  1063. ModelUtil.emitError(self.eventEmitter, err, err);
  1064. } else {
  1065. if (handler) {
  1066. handler(null, res);
  1067. return;
  1068. }
  1069. ModelUtil.emitOK(self.eventEmitter, res);
  1070. }
  1071. })
  1072. })
  1073. })
  1074. } else if (!start_msg_id) {
  1075. redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1076. if (res && res.length == 0) {
  1077. if (handler) {
  1078. handler(null, res);
  1079. return;
  1080. }
  1081. ModelUtil.emitOK(self.eventEmitter, res);
  1082. return;
  1083. }
  1084. start_msg_id = res[0];
  1085. self.getMessagesByPage(sessionId, user, start_msg_id,end_msg_id , page, pagesize, isoffset, function (err, res) {
  1086. if (err) {
  1087. if (handler) {
  1088. handler(err, null);
  1089. return;
  1090. }
  1091. logger.error("getMessagesByPage error" + err);
  1092. ModelUtil.emitError(self.eventEmitter, err, err);
  1093. } else {
  1094. if (handler) {
  1095. handler(null, res);
  1096. return;
  1097. }
  1098. ModelUtil.emitOK(self.eventEmitter, res);
  1099. }
  1100. })
  1101. })
  1102. } else if (!end_msg_id) {
  1103. redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
  1104. if (res && res.length == 0) {
  1105. ModelUtil.emitOK(self.eventEmitter, res);
  1106. return;
  1107. }
  1108. end_msg_id = res[0];
  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. } else {
  1127. self.getMessagesByPage(sessionId, user, end_msg_id, start_msg_id, page, pagesize, isoffset, function (err, res) {
  1128. if (err) {
  1129. if (handler) {
  1130. handler(err, null);
  1131. return;
  1132. }
  1133. logger.error("getMessagesByPage error" + err);
  1134. ModelUtil.emitError(self.eventEmitter, err, err);
  1135. } else {
  1136. if (handler) {
  1137. handler(null, res);
  1138. return;
  1139. }
  1140. ModelUtil.emitOK(self.eventEmitter, res);
  1141. }
  1142. })
  1143. }
  1144. }
  1145. /**
  1146. * 分页获取会话消息。
  1147. *
  1148. * @param sessionId 必选。会话ID
  1149. * @param userId 必选。用户ID
  1150. * @param startMsgId 必选。会话的的起始消息ID,作为检索的起始依据
  1151. * @param endMsgId 必选。会话中的结束消息ID
  1152. * @param page 必选。页码
  1153. * @param size 必选。页面大小
  1154. * @param handler 必选。回调
  1155. */
  1156. getMessagesByPage(sessionId, userId, startMsgId, endMsgId, page, size, isoffset, handler) {
  1157. let messagesTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1158. let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
  1159. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1160. let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1161. let participants = new Participants();
  1162. let offset = (page - 1 < 0 ? 0 : page - 1) * size;
  1163. let count = size;
  1164. if (page > 1 || isoffset == 1) {
  1165. offset += 1; // 翻页由于闭区间,需跳过本身数据
  1166. }
  1167. participants.existsParticipant(sessionId, userId, function (err, res) {
  1168. log.info("1151-userId=" + userId);
  1169. log.info(" res[0].exist=" + res[0].exist);
  1170. log.info(!res[0].exist && userId != "system");
  1171. if (! res[0].exist && userId != "system") {
  1172. handler(Error("User not found in session " + sessionId), null);
  1173. } else {
  1174. //将消息ID转换成分值
  1175. redis.multi()
  1176. .zscore(messagesTimestampKey, startMsgId)
  1177. .zscore(messagesTimestampKey, endMsgId)
  1178. .hgetall(sessionKey)
  1179. .zrange(sessionParticipantsKey, 0, -1)
  1180. .execAsync()
  1181. .then(function (res) {
  1182. let startMsgScore = res[1];
  1183. let endMsgScore = res[0];
  1184. let session = res[2];
  1185. let users = res[3];
  1186. if (startMsgScore == null || endMsgScore == null || (startMsgScore == endMsgScore && isoffset == 1)) {
  1187. handler(null, []);
  1188. return;
  1189. }
  1190. //结束大于开始,正序取数据,返回的数据顺序也是逆序的,反向拉取数据,
  1191. // 当end>start取出来都是空的,为了给前端获取新数据使用,一般不出现这种情况
  1192. if(endMsgScore>startMsgScore){
  1193. redis.zrangebyscoreAsync(messagesTimestampKey, startMsgScore, endMsgScore, "limit", offset, count)
  1194. .then(function (res) {
  1195. if (res && res.length == 0) {
  1196. handler(null, []);
  1197. return;
  1198. }
  1199. redis.hmgetAsync(messagesKey, res).then(function (messages) {
  1200. messages.reverse();
  1201. handler(null, messages);
  1202. }).then(function () {
  1203. Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
  1204. if(session.type == SESSION_TYPES.P2P){
  1205. for(var j in users){
  1206. if(users[j]==userId)continue;
  1207. WechatClient.sendAllRead(users[j],sessionId);
  1208. }
  1209. }else if(session.type == SESSION_TYPES.MUC ||
  1210. session.type == SESSION_TYPES.PRESCRIPTION ||
  1211. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1212. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1213. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1214. SESSION_TYPES.GENERAL_EXPERT ||
  1215. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1216. SESSION_TYPES.MUC_VIDEO ||
  1217. SESSION_TYPES.ONDOOR_NURSING){
  1218. for(var j in users){
  1219. if(users[j]==userId)continue;
  1220. WechatClient.sendMucAllRead(users[j],userId,sessionId);
  1221. }
  1222. }
  1223. })
  1224. })
  1225. .catch(function (err) {
  1226. logger.error("Get message by page failed: ", err);
  1227. handler(err, false);
  1228. })
  1229. }else{
  1230. // 从消息时间表中过滤出要获取的消息ID列表,倒序取出消息
  1231. redis.zrevrangebyscoreAsync(messagesTimestampKey, startMsgScore, endMsgScore, "limit", offset, count)
  1232. .then(function (res) {
  1233. if (res && res.length == 0) {
  1234. handler(null, []);
  1235. return;
  1236. }
  1237. redis.hmgetAsync(messagesKey, res).then(function (messages) {
  1238. handler(null, messages);
  1239. }).then(function () {
  1240. Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
  1241. if(session.type == SESSION_TYPES.P2P){
  1242. for(var j in users){
  1243. if(users[j]==userId)continue;
  1244. //通知对方自己已经读取数据
  1245. WechatClient.sendAllRead(users[j],sessionId);
  1246. }
  1247. }else if(session.type == SESSION_TYPES.MUC ||
  1248. session.type == SESSION_TYPES.PRESCRIPTION ||
  1249. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1250. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1251. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1252. SESSION_TYPES.GENERAL_EXPERT ||
  1253. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1254. SESSION_TYPES.MUC_VIDEO ||
  1255. SESSION_TYPES.ONDOOR_NURSING){
  1256. for(var j in users){
  1257. if(users[j]==userId)continue;
  1258. //如果是患者拉取数据告诉在线的医生患者已经读取数据
  1259. WechatClient.sendMucAllRead(users[j],userId,sessionId);
  1260. }
  1261. }
  1262. })
  1263. })
  1264. .catch(function (err) {
  1265. logger.error("Get message by page failed: ", err);
  1266. handler(err, false);
  1267. })
  1268. }
  1269. })
  1270. }
  1271. })
  1272. }
  1273. /**
  1274. * 获取所有会话的未读消息数。
  1275. */
  1276. getAllSessionsUnreadMessageCount(userId,type,handler) {
  1277. let self = this;
  1278. let count = 0;
  1279. let patientCount = 0;
  1280. let doctorCount = 0;
  1281. let patientEndCount = 0;
  1282. SessionRepo.findAll(userId, function (err, res) {
  1283. // SessionRepo.findUnEndAll(userId, function (err, res) {
  1284. if (err) {
  1285. if(handler)
  1286. {
  1287. handler(err,res);
  1288. return;
  1289. }
  1290. ModelUtil.logError("getAllSessionsUnreadMessageCount is failed", err);
  1291. return;
  1292. }
  1293. if (res && res.length == 0) {
  1294. if(handler)
  1295. {
  1296. handler(err,count);
  1297. return;
  1298. }
  1299. ModelUtil.emitOK(self.eventEmitter, {count: count});
  1300. return;
  1301. }
  1302. for (let j in res) {
  1303. //是否过滤指定类型
  1304. if( type != null){
  1305. if(type != res[j].type){
  1306. continue;
  1307. }
  1308. }
  1309. if (res[j].type == SESSION_TYPES.SYSTEM) {
  1310. if (j == res.length - 1) {
  1311. if(handler){
  1312. handler(err,count);
  1313. return;
  1314. }
  1315. ModelUtil.emitOK(self.eventEmitter, {count: count, patient: patientCount, doctor: doctorCount});
  1316. }
  1317. continue;
  1318. }
  1319. callback(res, j, res[j]);
  1320. }
  1321. });
  1322. function callback(res, j, session) {
  1323. self.getSessionUnreadMessageCount(res[j].id, userId, function (err, con) {
  1324. if (err) {
  1325. if(handler)
  1326. {
  1327. handler(err,count);
  1328. return;
  1329. }
  1330. ModelUtil.logError("getAllSessionsUnreadMessageCount is failed", err);
  1331. }
  1332. count = count + con;
  1333. if (session.business_type == SESSION_BUSINESS_TYPE.PATIENT) {
  1334. if(session.status == SESSION_STATUS.ENDED){//新增判断是否咨询结束
  1335. patientEndCount = patientEndCount + con;
  1336. }else{
  1337. patientCount = patientCount + con;
  1338. }
  1339. } else {
  1340. doctorCount = doctorCount + con;
  1341. }
  1342. if (j == res.length - 1) {
  1343. if(handler)
  1344. {
  1345. handler(err,count)
  1346. return;
  1347. }
  1348. ModelUtil.emitOK(self.eventEmitter, {count: count, patient: patientCount,patientEnd: patientEndCount, doctor: doctorCount});
  1349. }
  1350. })
  1351. }
  1352. }
  1353. /**
  1354. * 获取会话的未读消息数。根据成员最后一次获取消息的时候与当前时间。
  1355. *
  1356. * @param sessionId
  1357. * @param userId
  1358. */
  1359. getSessionUnreadMessageCount(sessionId, userId, handler) {
  1360. let self = this;
  1361. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1362. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1363. async.waterfall([
  1364. // 此成员最后获取消息的时间
  1365. function (callback) {
  1366. redis.zscoreAsync(participantsKey, userId)
  1367. .then(function (lastFetchTime) {
  1368. callback(null, lastFetchTime);
  1369. })
  1370. },
  1371. // 计算最后获取消息的时间之后到现在有多少条消息
  1372. function (lastFetchTime, callback) {
  1373. if (!lastFetchTime) lastFetchTime = 0;
  1374. let now = new Date().getTime();
  1375. redis.zcountAsync(messagesByTimestampKey, parseInt(lastFetchTime)+1, now)
  1376. .then(function (count) {
  1377. if (handler) {
  1378. handler(null, count);
  1379. } else {
  1380. ModelUtil.emitOK(self.eventEmitter, {count: count});
  1381. }
  1382. })
  1383. }
  1384. ], function (err, res) {
  1385. if (err) {
  1386. if (handler) {
  1387. handler(err, 0);
  1388. } else {
  1389. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  1390. }
  1391. }
  1392. });
  1393. }
  1394. /**
  1395. * 获取会话未读消息数。根据成员最后一次获取消息的时候与当前时间。
  1396. */
  1397. getSessionUnreadMessages(sessionId, userId) {
  1398. let self = this;
  1399. let messagesByTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
  1400. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1401. async.waterfall([
  1402. // 此成员最后获取消息的时间
  1403. function (callback) {
  1404. redis.zscoreAsync(participantsKey, userId)
  1405. .then(function (lastFetchTime) {
  1406. callback(null, lastFetchTime);
  1407. })
  1408. },
  1409. // 最后获取消息的时间之后到现在的消息ID列表
  1410. function (lastFetchTime, callback) {
  1411. if (!lastFetchTime) lastFetchTime = 0;
  1412. let now = new Date().getTime();
  1413. redis.zrangebyscoreAsync(messagesByTimestampKey, lastFetchTime, now)
  1414. .then(function (messageIds) {
  1415. callback(null, messageIds);
  1416. })
  1417. },
  1418. // 获取消息
  1419. function (messageIds, callback) {
  1420. if (messageIds.length == 0) {
  1421. ModelUtil.emitOK(self.eventEmitter, []);
  1422. return;
  1423. }
  1424. let startMsgId = messageIds[0];
  1425. let endMsgId = messageIds[messageIds.length - 1];
  1426. self.getMessagesByPage(sessionId, userId, startMsgId, endMsgId, 0, messageIds.length, 0, function (err, res) {
  1427. if (err) {
  1428. ModelUtil.emitError(self.eventEmitter, err.message);
  1429. return;
  1430. }
  1431. ModelUtil.emitOK(self.eventEmitter, res);
  1432. });
  1433. }
  1434. ], function (err, res) {
  1435. if (err) {
  1436. ModelUtil.emitError(self.eventEmitter, "Get session unread message count failed.")
  1437. }
  1438. });
  1439. }
  1440. /**
  1441. * 保存消息。
  1442. *
  1443. * 也可以根据议题保存消息,但最终还是保存到与会话对象。
  1444. *
  1445. * see also: saveMessageByTopic
  1446. *
  1447. * @param message
  1448. * @param sessionId
  1449. */
  1450. saveMessageBySession(sessionId, message) {
  1451. let self = this;
  1452. let messages = new Messages();
  1453. let participants = new Participants();
  1454. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1455. let messageId = mongoose.Types.ObjectId().toString();
  1456. let sessionType =0;
  1457. let sessionName;
  1458. message.id = messageId;
  1459. // 检查会话中是否存在此成员
  1460. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1461. if (err) {
  1462. ModelUtil.emitError(self.eventEmitter, "Check session participant failed: ", err);
  1463. return;
  1464. }
  1465. logger.info("session.js--1443--res[0].exist" + res[0].exist);
  1466. log.info("message.sender_id=" + message.sender_id);
  1467. if ( res[0].exist || message.sender_id == "system") {
  1468. redis.hmgetAsync(sessionKey, ["type", "name"]).then(function (res) {
  1469. sessionType = res[0];
  1470. let sessionName = res[1];
  1471. if (sessionType == null) {
  1472. self.getSessions(sessionId,function(err,res){
  1473. if (err){
  1474. logger.error("session data is error");
  1475. } else {
  1476. sessionName=res[0].name;
  1477. sessionType = res[0].type;
  1478. }
  1479. });
  1480. let participantArray = [];
  1481. let participantsStr="{";
  1482. ParticipantRepo.findAll(sessionId, function (err, participants) {
  1483. if (err) {
  1484. ModelUtil.emitError(self.eventEmitter, err.message);
  1485. return;
  1486. }
  1487. participants.forEach(function (participant) {
  1488. let participantId = participant.id;
  1489. let participantRole = participant.role;
  1490. let score = ObjectUtil.timestampToLong(participant.last_fetch_time||(new Date()));
  1491. participantsStr +="\""+participantId+"\":\""+participantRole+"\",";
  1492. });
  1493. participantsStr = participantsStr.substring(0,participantsStr.length-1)+'}';
  1494. participantsStr = JSON.parse(participantsStr);
  1495. for (let j in participantsStr) {
  1496. participantArray.push(j + ":" + participantsStr[j]);
  1497. }
  1498. //创建session到redis
  1499. self.createSessionToRedis(sessionId, sessionName, sessionType, participantArray, messageId, function (err, res) {
  1500. if (err) {
  1501. if (handler) {
  1502. handler(err, null);
  1503. }
  1504. ModelUtil.emitError(self.eventEmitter, {message: err, status: -1}, null);
  1505. } else {
  1506. if (handler) {
  1507. handler(null, res);
  1508. }
  1509. ModelUtil.emitOK(self.eventEmitter, {status: 200, data: res});
  1510. }
  1511. });
  1512. });
  1513. }
  1514. if(sessionType == SESSION_TYPES.MUC ||
  1515. sessionType == SESSION_TYPES.PRESCRIPTION ||
  1516. SESSION_TYPES.PRESCRIPTION_HOSPITAL ||
  1517. SESSION_TYPES.COLLABORATION_HOSPITAL ||
  1518. SESSION_TYPES.GUIDANCE_HOSPITAL ||
  1519. SESSION_TYPES.GENERAL_EXPERT ||
  1520. SESSION_TYPES.PRESCRIPTION_HOSPITAL_VIDEO ||
  1521. SESSION_TYPES.MUC_VIDEO ||
  1522. SESSION_TYPES.ONDOOR_NURSING){
  1523. if(message.content_type == CONTENT_TYPES.PlainText ||
  1524. message.content_type == CONTENT_TYPES.Image ||
  1525. message.content_type == CONTENT_TYPES.Audio||
  1526. message.content_type == CONTENT_TYPES.Video){
  1527. TopicRepo.findLastBySessionId(sessionId,function(err,res){
  1528. if(res&&res.length>0&&res[0].reply==0){
  1529. TopicRepo.replyTopic(message.sender_id,message.id,res[0].id,function(err,res){
  1530. if(err){
  1531. logger.error("update topic reply error");
  1532. }else{
  1533. logger.warn("update topic reply success");
  1534. }
  1535. });
  1536. }
  1537. })
  1538. }
  1539. }
  1540. // 消息保存到Redis,并更新会话最后状态、用户最后消息获取时间
  1541. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1542. Messages.updateLastContent(sessionKey, sessionType, sessionName, message);
  1543. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1544. // 更新MYSQL中会话的最新状态,并保存消息
  1545. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1546. messages.saveMessageToMysql(sessionId, sessionType, messageId, message, function (err, res) {
  1547. if (err) {
  1548. ModelUtil.emitError(self.eventEmitter, {message: "Failed to save message to mysql: " + err});
  1549. } else {
  1550. message.timestamp = message.timestamp.getTime();
  1551. ModelUtil.emitOK(self.eventEmitter, {count: 1, messages: [message]});
  1552. }
  1553. });
  1554. }).then(function (res) {
  1555. // 推送消息
  1556. ParticipantRepo.findIds(sessionId, function (err, res) {
  1557. if (err) {
  1558. ModelUtil.logError("Push message from session: get participant's id list failed: ", err);
  1559. } else {
  1560. message.session_id = sessionId;
  1561. res.forEach(function (participant) {
  1562. if (participant.id == message.sender_id||sessionType==SESSION_TYPES.SYSTEM){
  1563. message.sender_img = participant.avatar;
  1564. callPush(res,message);
  1565. }
  1566. })
  1567. }
  1568. })
  1569. }).catch(function (err) {
  1570. ModelUtil.emitError(self.eventEmitter, {message: "Error occurred while save message to session: " + err});
  1571. })
  1572. } else {
  1573. ModelUtil.emitDataNotFound(self.eventEmitter, {message: "当前会话找不到此发送者"});
  1574. }
  1575. });
  1576. function callPush(participants,message){
  1577. participants.forEach(function (participant) {
  1578. // if (
  1579. // // participant.id !== message.sender_id &&
  1580. // participant.participant_role == PARTICIPANT_ROLES.HOST) {
  1581. Sessions.pushNotification(participant.id, participant.name, message,sessionType);
  1582. // }
  1583. });
  1584. }
  1585. }
  1586. sendTopicMessages(topicId, message) {
  1587. let self = this;
  1588. TopicRepo.findAllByTopicId(topicId, function (err, res) {
  1589. if (err || res.length == 0) {
  1590. ModelUtil.emitOK(self.eventEmitter, {status: -1, "message": "议题获取失败"});
  1591. return;
  1592. }
  1593. self.saveMessageByTopic(message, res[0].session_id, function (err, messageId) {
  1594. if (err) {
  1595. ModelUtil.emitOK(self.eventEmitter, {status: -1, "message": err});
  1596. } else {
  1597. message.id = messageId;
  1598. ModelUtil.emitOK(self.eventEmitter, {status: 200, "message": "发送成功", data: message});
  1599. }
  1600. });
  1601. });
  1602. }
  1603. /**
  1604. * 保存消息
  1605. *
  1606. * @param message
  1607. * @param sessionId
  1608. * @param handler
  1609. */
  1610. saveMessageByTopic(message, sessionId, handler) {
  1611. let messages = new Messages();
  1612. let participants = new Participants();
  1613. let session_key = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1614. let messageId = mongoose.Types.ObjectId().toString();
  1615. let self = this;
  1616. let sessionType = 0;
  1617. let sessionName = "";
  1618. let agent = message.agent;//代理人
  1619. message.id = messageId;
  1620. if(!message.timestamp){
  1621. message.timestamp = new Date();
  1622. }
  1623. // 发送成员必须处于会话中
  1624. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1625. log.info("1599-message.sender_id=" + message.sender_id);
  1626. log.info("res[0].exist=" + res[0].exist);
  1627. if ( res[0].exist || message.sender_id == "system") {
  1628. redis.hmgetAsync(session_key, ["type", "name"]).then(function (res) {
  1629. sessionType = res[0];
  1630. sessionName = res[1];
  1631. if (!sessionType || !sessionName) {
  1632. logger.error("Unknown session key " + session_key);
  1633. if (handler) {
  1634. handler(new Error("Unknown session key " + session_key));return;
  1635. };
  1636. }
  1637. }).then(function (res) {
  1638. // 消息数据双写,并更新用户最后消息获取时间,会话新状态等
  1639. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1640. messages.saveMessageToMysql(sessionId, sessionType, messageId, message);
  1641. // 更新会话最新状态及成员最后一次消息获取时间
  1642. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1643. Messages.updateLastContent(session_key, sessionType, sessionName, message);
  1644. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1645. if (handler) {
  1646. handler(null, messageId);
  1647. return;
  1648. }
  1649. }).then(function (res) {
  1650. // 推送消息
  1651. ParticipantRepo.findIds(sessionId, function (err, res) {
  1652. if (err) {
  1653. logger.error(err);
  1654. } else {
  1655. message.session_id = sessionId;
  1656. res.forEach(function (participant) {
  1657. if (participant.id == message.sender_id){
  1658. message.sender_img = participant.avatar;
  1659. callPush(res,message);
  1660. }
  1661. })
  1662. }
  1663. })
  1664. }).catch(function (err) {
  1665. log.error(err);
  1666. return;
  1667. })
  1668. } else {
  1669. if (handler){ handler("用户不在此会话当中!", messageId);return;}
  1670. }
  1671. });
  1672. function callPush(participants,message){
  1673. participants.forEach(function (participant) {
  1674. if ((participant.id !== message.sender_id||message.content_type == CONTENT_TYPES.PrescriptionBloodStatus ||
  1675. message.content_type == CONTENT_TYPES.PrescriptionFollowupContent) &&
  1676. participant.participant_role == PARTICIPANT_ROLES.HOST) {
  1677. Sessions.pushNotification(participant.id, participant.name, message,sessionType);
  1678. }
  1679. });
  1680. }
  1681. }
  1682. /**
  1683. * 保存代理人进入的消息
  1684. *
  1685. * @param message
  1686. * @param sessionId
  1687. * @param handler
  1688. */
  1689. saveIntoMessageByTopic(message, sessionId, handler) {
  1690. log.info("2--保存代理人进入的消息:");
  1691. let messages = new Messages();
  1692. let participants = new Participants();
  1693. let session_key = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
  1694. let messageId = mongoose.Types.ObjectId().toString();
  1695. let self = this;
  1696. let sessionType = 0;
  1697. let sessionName = "";
  1698. let agent = message.agent;//代理人
  1699. message.id = messageId;
  1700. if(!message.timestamp){
  1701. message.timestamp = new Date();
  1702. }
  1703. // 发送成员必须处于会话中
  1704. participants.existsParticipant(sessionId, message.sender_id, function (err, res) {
  1705. log.info("session.js--1477--res[0].exist" + res[0].exist);
  1706. log.info("message.sender_id=" + message.sender_id);
  1707. if (res[0].exist || message.sender_id == "system") {
  1708. redis.hmgetAsync(session_key, ["type", "name"]).then(function (res) {
  1709. sessionType = res[0];
  1710. sessionName = res[1];
  1711. if (!sessionType || !sessionName) {
  1712. logger.error("Unknown session key " + session_key);
  1713. if (handler) {
  1714. handler(new Error("Unknown session key " + session_key));return;
  1715. };
  1716. }
  1717. }).then(function (res) {
  1718. //查找最后一条数据,如果一致就不保存
  1719. MessageRepo.findLastMessage(sessionId,sessionType,function (err, res) {
  1720. if (err) {
  1721. logger.error(err);
  1722. } else {
  1723. res.forEach(function (mes) {
  1724. // if(mes.content==message.content&&message.content_type==mes.content_type){
  1725. if(mes.agent==message.agent){
  1726. handler(null, messageId);
  1727. return;
  1728. }else {
  1729. // 消息数据双写,并更新用户最后消息获取时间,会话新状态等
  1730. messages.saveMessageToRedis(sessionId, sessionType, messageId, message);
  1731. messages.saveMessageToMysql(sessionId, sessionType, messageId, message);
  1732. // 更新会话最新状态及成员最后一次消息获取时间
  1733. Sessions.updateParticipantLastFetchTime(sessionId, message.sender_id, message.timestamp.getTime());
  1734. Messages.updateLastContent(session_key, sessionType, sessionName, message);
  1735. SessionRepo.updateSessionLastStatus(message.sender_id, message.sender_name, message.timestamp, message.content, message.content_type, sessionId);
  1736. if (handler) {
  1737. handler(null, messageId);
  1738. return;
  1739. }
  1740. }
  1741. })
  1742. }
  1743. });
  1744. }).then(function (res) {
  1745. // 推送消息
  1746. ParticipantRepo.findDoctorIds(sessionId, function (err, res) {
  1747. if (err) {
  1748. logger.error(err);
  1749. } else {
  1750. message.session_id = sessionId;
  1751. res.forEach(function (participant) {
  1752. Sessions.pushIntoNotification(participant.id, participant.name, message,sessionType);
  1753. })
  1754. }
  1755. })
  1756. }).catch(function (err) {
  1757. log.error(err);
  1758. return;
  1759. })
  1760. } else {
  1761. log.info("4--用户不在此会话当中!");
  1762. if (handler){ handler("用户不在此会话当中!", messageId);return;}
  1763. }
  1764. });
  1765. }
  1766. /**
  1767. * 置顶操作
  1768. */
  1769. stickSession(sessionId, user) {
  1770. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  1771. let self = this;
  1772. //取出最大的session
  1773. redis.zrevrangeAsync(user_session_key, 0, 0).then(function (res) {
  1774. //获取该session的时间搓
  1775. redis.zscoreAsync(user_session_key, res).then(function (scoreres) {
  1776. let nowtime = new Date().getTime();
  1777. //当前时间搓比redis的时间搓更早证明没有置顶过
  1778. if (scoreres <= nowtime) {
  1779. //初始化置顶
  1780. redis.zaddAsync(user_session_key, STICKY_SESSION_BASE_SCORE, sessionId).then(function (res) {
  1781. logger.info("stickSession:" + sessionId + ",res:" + res);
  1782. ModelUtil.emitOK(self.eventEmitter, {});
  1783. }).then(function () {
  1784. SessionRepo.saveStickySession(sessionId, user, STICKY_SESSION_BASE_SCORE);
  1785. })
  1786. } else {
  1787. //已有置顶的数据,取出来加1保存回去
  1788. scoreres = Number(scoreres) + 1;
  1789. redis.zaddAsync(user_session_key, scoreres, sessionId).then(function () {
  1790. logger.info("stickSession:" + sessionId + ",res:" + res);
  1791. ModelUtil.emitOK(self.eventEmitter, {});
  1792. }).then(function () {
  1793. SessionRepo.saveStickySession(sessionId, user, scoreres);
  1794. })
  1795. }
  1796. })
  1797. })
  1798. }
  1799. /**
  1800. * 取消会话置顶
  1801. */
  1802. cancelStickSession(sessionId, user) {
  1803. let user_session_key = RedisModel.makeRedisKey(REDIS_KEYS.UserSessions, user);
  1804. let participants_key = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1805. let self = this;
  1806. redis.zscoreAsync(participants_key, user).then(function (res) {
  1807. if (!res) {
  1808. res = new Date().getTime();
  1809. }
  1810. redis.zaddAsync(user_session_key, res, sessionId).then(function (res) {
  1811. logger.info("cancelStickSession:" + sessionId);
  1812. ModelUtil.emitOK(self.eventEmitter, {});
  1813. }).then(function () {
  1814. SessionRepo.unStickySession(sessionId, user);
  1815. });
  1816. })
  1817. }
  1818. /**
  1819. * 更新会话参与者的最后消息获取时间。
  1820. *
  1821. * @param sessionId
  1822. * @param userId
  1823. */
  1824. static updateParticipantLastFetchTime(sessionId, userId, score) {
  1825. score = score + 1;
  1826. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  1827. redis.zaddAsync(participantsKey, score, userId)
  1828. .then(function (res) {
  1829. ParticipantRepo.updateLastFetchTime(new Date(score), sessionId, userId, function (err, res) {
  1830. if (err) {
  1831. logger.error("Update participant last fetch time failed: ", err);
  1832. }
  1833. });
  1834. })
  1835. .catch(function (err) {
  1836. logger.error("Update participant last fetch time failed: ", err);
  1837. });
  1838. }
  1839. /**
  1840. * 向用户推送通知,微信端用户直接推送消息,APP端通过个推发送通知消息。
  1841. *
  1842. * @param targetUserId
  1843. * @param message
  1844. */
  1845. static pushNotification(targetUserId, targetUserName, message,sessionType) {
  1846. let self = this;
  1847. Users.isPatientId(targetUserId, function (err, isPatient) {
  1848. if (isPatient) {
  1849. if(config.environment!='local'){//pc版不直接发送给居民,通过redis的publish
  1850. WechatClient.sendMessage(targetUserId, targetUserName, message);
  1851. }
  1852. message.targetUserId = targetUserId;
  1853. message.targetUserName = targetUserName;
  1854. message.sessionType = sessionType;
  1855. message.targetType = 'patient';
  1856. } else {
  1857. if(sessionType==SESSION_TYPES.P2P){
  1858. WechatClient.sendReadDoctorByDoctorId(targetUserId, message);
  1859. }
  1860. //告知医生新消息
  1861. WechatClient.sendSocketMessageToDoctor(targetUserId,message);
  1862. let count = 0;
  1863. //系统消息
  1864. // MessageRepo.getWlyyMessageCount(targetUserId,function (err,res) {
  1865. // if(res){
  1866. // count = res[0].count;
  1867. // }
  1868. // });
  1869. //im消息
  1870. let sessions = new Sessions();
  1871. sessions.getAllSessionsUnreadMessageCount(targetUserId,null,function (err,res) {
  1872. if(res){
  1873. count += res;
  1874. }
  1875. });
  1876. if(config.environment!='local'){//pc版不推送个推,通过redis的publish
  1877. log.info("推送医生智能助手")
  1878. AppClient.sendNotification(targetUserId, message,sessionType,count);
  1879. }
  1880. //外网pcim通过socket推送
  1881. WechatClient.sendPcImSocket(targetUserId,message,sessionType);
  1882. // WlyySDK.request(targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
  1883. // let count = 0;
  1884. // if(err){
  1885. // logger.error(err);
  1886. // }else {
  1887. // logger.error(res);
  1888. // res = JSON.parse(res)
  1889. // if (res.status == 200) {
  1890. // let data = res.data;
  1891. // count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
  1892. // }
  1893. // }
  1894. // if(config.environment!='local'){//pc版不推送个推,通过redis的publish
  1895. // AppClient.sendNotification(targetUserId, message,sessionType,count);
  1896. // }
  1897. // //外网pcim通过socket推送
  1898. // WechatClient.sendPcImSocket(targetUserId,message,sessionType);
  1899. // });
  1900. message.targetUserId = targetUserId;
  1901. message.targetUserName = targetUserName;
  1902. message.sessionType = sessionType;
  1903. message.targetType = 'doctor';
  1904. //推送MDT,医生外层新消息
  1905. WechatClient.sendMDTSocketMessageToDoctor(targetUserId,message);
  1906. }
  1907. //redis发布消息
  1908. if(config.pubSubSwitch) {//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
  1909. pubSub.publish(config.pubChannel,JSON.stringify(message));
  1910. }
  1911. });
  1912. }
  1913. /**
  1914. * 获取redis订阅消息,并处理
  1915. * @param targetUserId
  1916. * @param targetUserName
  1917. * @param message
  1918. * @param sessionType
  1919. */
  1920. static getRedisPushNotification(message) {
  1921. if (message.targetType=='patient') {
  1922. if(config.environment!='local'){//pc版接收要发给居民的消息不做处理
  1923. WechatClient.sendMessage(message.targetUserId, message.targetUserName, message);
  1924. }
  1925. } else {
  1926. if(message.sessionType==SESSION_TYPES.P2P){
  1927. WechatClient.sendReadDoctorByDoctorId(message.targetUserId, message);
  1928. }
  1929. //告知医生新消息
  1930. WechatClient.sendSocketMessageToDoctor(message.targetUserId,message);
  1931. if(config.environment!='local'){//pc版不推送个推
  1932. WlyySDK.request(message.targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
  1933. let count = 0;
  1934. res = JSON.parse(res)
  1935. if (res.status == 200) {
  1936. let data = res.data;
  1937. count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
  1938. }
  1939. AppClient.sendNotification(message.targetUserId, message,message.sessionType,count);
  1940. });
  1941. }
  1942. }
  1943. }
  1944. /**
  1945. * 向APP端通过socket发送通知消息。
  1946. *
  1947. * @param targetUserId
  1948. * @param message
  1949. */
  1950. static pushIntoNotification(targetUserId, targetUserName, message,sessionType) {
  1951. if(sessionType==SESSION_TYPES.P2P){
  1952. WechatClient.sendReadDoctorByDoctorId(targetUserId, message);
  1953. }
  1954. //告知医生新消息
  1955. WechatClient.sendSocketMessageToDoctor(targetUserId,message);
  1956. }
  1957. /**
  1958. * 针对MUC模式更新会话的当前状态
  1959. * @param sessionId
  1960. */
  1961. updateSessionStatus(sessionId,status,handler){
  1962. let self = this;
  1963. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session,sessionId);
  1964. redis.hsetAsync(sessionKey,"status",status).then(function(res){
  1965. SessionRepo.updateSessionStatus(sessionId,status,function(err,sqlResult){
  1966. if(handler){
  1967. handler(err,sqlResult);
  1968. return;
  1969. }
  1970. if(err){
  1971. logger.error("set session status to mysql is error !");
  1972. }else{
  1973. logger.info("set session status is success");
  1974. ModelUtil.emitOK(self.eventEmitter, []);
  1975. }
  1976. });
  1977. });
  1978. }
  1979. /**
  1980. * 针对专科医生和家医模式更新会话的名称
  1981. * @param sessionId
  1982. * @param name
  1983. */
  1984. updateSessionName(sessionId,name,handler){
  1985. let self = this;
  1986. let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session,sessionId);
  1987. redis.hsetAsync(sessionKey,"name",name).then(function(res){
  1988. SessionRepo.updateSessionName(sessionId,name,function(err,sqlResult){
  1989. if(handler){
  1990. handler(err,sqlResult);
  1991. return;
  1992. }
  1993. if(err){
  1994. logger.error("set session name to mysql is error !");
  1995. ModelUtil.emitError(self.eventEmitter,"set session name to mysql is error !",err)
  1996. }else{
  1997. logger.info("set session name is success");
  1998. ModelUtil.emitOK(self.eventEmitter, []);
  1999. }
  2000. });
  2001. });
  2002. }
  2003. }
  2004. // Expose class
  2005. module.exports = Sessions;