sessions.js 104 KB

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