wechat.client.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. /**
  2. * 用户微信客户端。
  3. */
  4. "use strict";
  5. let RedisClient = require('../../repository/redis/redis.client');
  6. let RedisModel = require('../redis.model');
  7. let ObjectUtil = require("../../util/object.util.js");
  8. let ModelUtil = require('../../util/model.util');
  9. let WechatSDK = require('../../util/wechat.sdk');
  10. let PatientRepo = require('../../repository/mysql/patient.repo');
  11. let TopicRepo = require("../../repository/mysql/topics.repo.js");
  12. let ParticipantRepo = require("../../repository/mysql/participant.repo");
  13. let redisConn = RedisClient.redisClient().connection;
  14. let clientCache = require('../socket.io/client.cache').clientCache();
  15. let configFile = require('../../include/commons').CONFIG_FILE;
  16. let config = require('../../resources/config/' + configFile);
  17. let log = require("../../util/log.js");
  18. let https = require('https');
  19. let http = require('http');
  20. let async = require('async');
  21. let querystring = require('querystring');
  22. let HlwyyWechatAssistantSDK = require("../../util/hlwyyWechatAssistant.sdk");
  23. var reqq = require('request');
  24. const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES;
  25. const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
  26. const SOCKET_TYPES = require('../../include/commons').SOCKET_TYPES;
  27. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  28. class WechatClient extends RedisModel {
  29. constructor() {
  30. super();
  31. }
  32. /**
  33. * 取得用户微信端状态。若Redis中找不到,则从MySQL中查找。
  34. *
  35. * @param userId
  36. * @param handler
  37. */
  38. static getWechatStatus(userId, handler) {
  39. redisConn.hgetallAsync(RedisModel.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId))
  40. .then(function (status) {
  41. if (status == null) {
  42. PatientRepo.findWechatOpenId(userId, handler);
  43. } else {
  44. handler(null, {openid: status.openid});
  45. }
  46. })
  47. .catch(function (err) {
  48. handler(err, null);
  49. });
  50. }
  51. /**
  52. * 向微信端用户发送消息。若用户微信端在线,通过Web Socket推送给患者,如果不在线则通过微信的模板消息。
  53. *
  54. * 只推送文本、图片及语音消息
  55. *
  56. * @param targetUserId
  57. * @param message 消息体
  58. */
  59. static sendMessage(targetUserId, targetUserName, message) {
  60. if (message&&(message.content_type == CONTENT_TYPES.PlainText ||
  61. message.content_type == CONTENT_TYPES.Image ||
  62. message.content_type == CONTENT_TYPES.Audio||
  63. message.content_type == CONTENT_TYPES.PrescriptionBloodStatus ||
  64. message.content_type == CONTENT_TYPES.PrescriptionFollowupContent ||
  65. message.content_type == CONTENT_TYPES.ReservationDoorCardInfo ||
  66. message.content_type == CONTENT_TYPES.ChangeDoorCardInfo ||
  67. message.content_type == CONTENT_TYPES.ChangeDoorDoctor ||
  68. message.content_type == CONTENT_TYPES.ChangeDoorPackageItems ||
  69. message.content_type == CONTENT_TYPES.VideoAnswerStatus ||
  70. message.content_type == CONTENT_TYPES.Screening ||
  71. message.content_type == CONTENT_TYPES.PrescriptionReject ||
  72. message.content_type == CONTENT_TYPES.PrescriptionSuggest ||
  73. message.content_type == CONTENT_TYPES.ConsultSuggest ||
  74. message.content_type == CONTENT_TYPES.PayMessage||
  75. message.content_type== CONTENT_TYPES.Article||
  76. message.content_type==CONTENT_TYPES.surveyMessage
  77. )) {
  78. let patientClient = clientCache.findById(targetUserId);
  79. let pc_patientClient = clientCache.findById("pcpatient_"+targetUserId);
  80. let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
  81. let pc_doctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
  82. let pc_patient_system_Client = clientCache.findByIdAndType("pcpatient_system_"+targetUserId,SOCKET_TYPES.PC_PATIENT_SYSTEM);
  83. var count = 0;
  84. if (patientClient || pc_patientClient || pc_patient_system_Client) {
  85. if(patientClient){
  86. log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId);
  87. WechatClient.sendViaWebSocket(patientClient.socket, message);
  88. }
  89. if(pc_patientClient){
  90. log.warn("User's pc endpoint is online, sending via web socket. User id: ", targetUserId);
  91. WechatClient.sendViaWebSocket(pc_patientClient.socket, message);
  92. }
  93. if(pc_patient_system_Client){
  94. log.warn("User's pc systme endpoint is online, sending via web socket. User id: ", targetUserId);
  95. WechatClient.sendViaWebSocket(pc_patient_system_Client.socket, message);
  96. }
  97. if(doctorClient && (patientClient || pc_patientClient) ){
  98. log.error("doctor sessionid "+doctorClient.sessionId);
  99. if(patientClient && patientClient.sessionId==doctorClient.sessionId){
  100. log.error("patient sessionid "+patientClient.sessionId);
  101. //用户socket在线,推送给用户后,告知医生此消息已读
  102. WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  103. WechatClient.sendReadDoctor(doctorClient.socket, message);
  104. }
  105. if(pc_patientClient && pc_patientClient.sessionId==doctorClient.sessionId){
  106. log.error("pc_patient sessionid "+pc_patientClient.sessionId);
  107. //用户socket在线,推送给用户后,告知医生此消息已读
  108. WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  109. WechatClient.sendReadDoctor(doctorClient.socket, message);
  110. }
  111. }else{
  112. count++;
  113. }
  114. if(pc_doctorClient){
  115. log.error("pc_doctor sessionid "+pc_doctorClient.sessionId);
  116. if(patientClient){
  117. log.error("patient sessionid "+patientClient.sessionId);
  118. if(patientClient.sessionId==pc_doctorClient.sessionId){
  119. //用户socket在线,推送给用户后,告知医生此消息已读
  120. WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  121. WechatClient.sendReadDoctor(pc_doctorClient.socket, message);
  122. }
  123. }
  124. if(pc_patientClient){
  125. log.error("pc_patient sessionid "+pc_patientClient.sessionId);
  126. if(pc_patientClient.sessionId==pc_doctorClient.sessionId){
  127. //用户socket在线,推送给用户后,告知医生此消息已读
  128. WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  129. WechatClient.sendReadDoctor(pc_doctorClient.socket, message);
  130. }
  131. }
  132. }else{
  133. count++;
  134. }
  135. if(count==0){
  136. log.error("doctor client not found");
  137. }
  138. } else {
  139. log.info("User's wechat and pc endpoint is not online, sending via wechat template message. User id: ", targetUserId);
  140. var isSendWXTem = true;//是否发送微信模板
  141. if(message.content_type == CONTENT_TYPES.PrescriptionBloodStatus||message.content_type == CONTENT_TYPES.PrescriptionFollowupContent){
  142. var content = JSON.parse(message.content);
  143. if(content.isSendWxTemplate){
  144. message.content = content.text;
  145. }else {
  146. isSendWXTem = false;
  147. }
  148. }
  149. if(isSendWXTem){
  150. //发送第三方接口的微信模版消息
  151. WechatClient.sendThirdMessageTemplate(targetUserId, targetUserName, message);
  152. //发送厦门i健康的微信模版消息
  153. // WechatClient.sendViaMessageTemplate(targetUserId, targetUserName, message);
  154. }
  155. }
  156. } else if(message.content_type == CONTENT_TYPES.TopicEnd){
  157. let patientClient = clientCache.findById(targetUserId);
  158. if(patientClient){//结束咨询的告知患者
  159. WechatClient.sendViaWebSocket(patientClient.socket, message);
  160. }
  161. let pc_patientClient = clientCache.findById("pcpatient_"+targetUserId);
  162. if(pc_patientClient)//结束咨询的告知患者
  163. {
  164. WechatClient.sendViaWebSocket(pc_patientClient.socket, message);
  165. }
  166. }
  167. };
  168. static sendViaWebSocket(socket, message) {
  169. socket.emit('message', {
  170. id: message.id,
  171. session_id: message.session_id,
  172. sender_id: message.sender_id,
  173. sender_name: message.sender_name,
  174. content_type: message.content_type,
  175. content: message.content,
  176. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  177. type: message.content_type, // legacy support
  178. name: message.sender_name,
  179. sender_img : message.sender_img
  180. });
  181. }
  182. static sendAllRead(doctorId,sessionId){
  183. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  184. let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
  185. if(doctorClient){
  186. if(doctorClient.sessionId==sessionId){
  187. doctorClient.socket.emit('message',{ read:"all"});
  188. }else{
  189. log.warn(" doctor not in the same session ");
  190. }
  191. }else{
  192. if(pc_doctorClient && pc_doctorClient.sessionId == sessionId){
  193. pc_doctorClient.socket.emit('message',{ read:"all"});
  194. }else{
  195. log.warn(doctorId+" target doctor is not online!");
  196. }
  197. }
  198. }
  199. static sendMucAllRead(doctorId,loginUserId,sessionId){
  200. let loginClinet = clientCache.findByIdAndType(loginUserId,SOCKET_TYPES.DOCTOR);
  201. if(loginClinet){
  202. //muc是医生来获取数据不能更新成已读
  203. log.warn("type is muc login is doctor not send all read to other doctor!")
  204. return;
  205. }
  206. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  207. let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
  208. if(doctorClient){
  209. if(doctorClient.sessionId==sessionId){
  210. doctorClient.socket.emit('message',{ read:"all"});
  211. }else{
  212. log.warn(" doctor not in the same session ");
  213. }
  214. }else{
  215. if(pc_doctorClient && pc_doctorClient.sessionId == sessionId){
  216. pc_doctorClient.socket.emit('message',{ read:"all"});
  217. }else{
  218. log.warn(doctorId+" target doctor is not online!");
  219. }
  220. }
  221. }
  222. static sendReadDoctor(socket, message) {
  223. socket.emit('message', {
  224. id: message.id,
  225. session_id: message.session_id,
  226. sender_id: message.sender_id,
  227. sender_name: message.sender_name,
  228. content_type: message.content_type,
  229. content: message.content,
  230. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  231. type: message.content_type, // legacy support
  232. name: message.sender_name,
  233. read:"one"
  234. });
  235. }
  236. static sendReadDoctorByDoctorId(doctorId, message) {
  237. if(doctorId==message.sender_id){
  238. return;
  239. }
  240. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  241. let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
  242. if(!doctorClient&&!pc_doctorClient){
  243. log.warn("target doctor is not online!");
  244. return;
  245. }
  246. let sendDoctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
  247. if(!sendDoctorClient){
  248. sendDoctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
  249. }
  250. var count = 0;
  251. if(doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==doctorClient.sessionId){
  252. WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
  253. sendDoctorClient.socket.emit('message', {
  254. id: message.id,
  255. session_id: message.session_id,
  256. sender_id: message.sender_id,
  257. sender_name: message.sender_name,
  258. content_type: message.content_type,
  259. content: message.content,
  260. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  261. type: message.content_type, // legacy support
  262. name: message.sender_name,
  263. read:"one"
  264. });
  265. }else{
  266. count++;
  267. }
  268. //发送pc版医生端
  269. if(pc_doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==pc_doctorClient.sessionId){
  270. WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
  271. pc_doctorClient.socket.emit('message', {
  272. id: message.id,
  273. session_id: message.session_id,
  274. sender_id: message.sender_id,
  275. sender_name: message.sender_name,
  276. content_type: message.content_type,
  277. content: message.content,
  278. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  279. type: message.content_type, // legacy support
  280. name: message.sender_name,
  281. read:"one"
  282. });
  283. }else{
  284. count++;
  285. }
  286. if(count==2){
  287. log.warn("doctor is not in the same session or is not online");
  288. }
  289. }
  290. static sendSocketMessageToDoctor(doctorId, message) {
  291. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  292. let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
  293. if(!doctorClient&&!pc_doctorClient){
  294. log.warn("target doctor is not online!");
  295. return;
  296. }
  297. // let sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);//app医生发送的消息
  298. // if(!sendClient){//pc医生发送的消息
  299. // sendClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
  300. // }
  301. // if(!sendClient){//居民发送的消息
  302. // sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.PATIENT);
  303. // }
  304. var count = 0;
  305. if(doctorClient&&message.session_id==doctorClient.sessionId){
  306. WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
  307. doctorClient.socket.emit('message', {
  308. id: message.id,
  309. session_id: message.session_id,
  310. sender_id: message.sender_id,
  311. sender_name: message.sender_name,
  312. content_type: message.content_type,
  313. content: message.content,
  314. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  315. type: message.content_type, // legacy support
  316. name: message.sender_name,
  317. });
  318. }else{
  319. count++;
  320. }
  321. //发送pc端 - PC端消息不做sessionid的判断,前端自己判断消息归属于哪个会话,自行渲染--20191012-huangwenjie
  322. // if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){
  323. if(pc_doctorClient){
  324. WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
  325. pc_doctorClient.socket.emit('message', {
  326. id: message.id,
  327. session_id: message.session_id,
  328. sender_id: message.sender_id,
  329. sender_name: message.sender_name,
  330. content_type: message.content_type,
  331. content: message.content,
  332. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  333. type: message.content_type, // legacy support
  334. name: message.sender_name,
  335. });
  336. }else{
  337. count++;
  338. }
  339. if(count==2){
  340. log.warn("doctor is not in the same session or is not online");
  341. }
  342. }
  343. /**
  344. * 推送MDT,医生外层新消息
  345. * @param doctorId
  346. * @param message
  347. */
  348. static sendMDTSocketMessageToDoctor(doctorId, message) {
  349. // let doctorMDTClient = clientCache.findByIdAndType("pcim_"+doctorId,SOCKET_TYPES.PCIM_DOCTOR);
  350. let doctorSYSTEMClient = clientCache.findByIdAndType("pc_system_"+doctorId,SOCKET_TYPES.PC_DOCTOR_SYSTEM);
  351. let doctorAPPSYSTEMClient = clientCache.findByIdAndType("doctor_system_"+doctorId,SOCKET_TYPES.DOCTOR_SYSTEM);
  352. //外层
  353. if(!doctorSYSTEMClient){
  354. log.warn("target system doctor is not online!");
  355. }else{
  356. doctorSYSTEMClient.socket.emit('message', {
  357. id: message.id,
  358. session_id: message.session_id,
  359. sender_id: message.sender_id,
  360. sender_name: message.sender_name,
  361. content_type: 1,
  362. content: {"socket_sms_type":4},
  363. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  364. type: message.content_type, // legacy support
  365. name: message.sender_name,
  366. patient_name:message.patient_name,
  367. patient_age:message.patient_age,
  368. patient_sex:message.patient_sex
  369. });
  370. }
  371. if(!doctorAPPSYSTEMClient){
  372. log.warn("target system app doctor is not online!");
  373. }else{
  374. doctorAPPSYSTEMClient.socket.emit('message', {
  375. id: message.id,
  376. session_id: message.session_id,
  377. sender_id: message.sender_id,
  378. sender_name: message.sender_name,
  379. content_type: 1,
  380. content: {"socket_sms_type":4},
  381. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  382. type: message.content_type, // legacy support
  383. name: message.sender_name,
  384. patient_name:message.patient_name,
  385. patient_age:message.patient_age,
  386. patient_sex:message.patient_sex
  387. });
  388. }
  389. }
  390. static sendPcImSocket(targetId, message, sessionType) {
  391. if (message.content_type == CONTENT_TYPES.PlainText ||
  392. message.content_type == CONTENT_TYPES.Image ||
  393. message.content_type == CONTENT_TYPES.Audio||
  394. message.content_type == CONTENT_TYPES.Video||
  395. message.content_type == CONTENT_TYPES.GoTo||
  396. sessionType==SESSION_TYPES.SYSTEM) {
  397. let pcim_doctorClient = clientCache.findByIdAndType("pcim_"+targetId,SOCKET_TYPES.PCIM_DOCTOR);
  398. if(pcim_doctorClient) {
  399. let customData = {
  400. session_id: message.session_id||'',
  401. session_type: sessionType,
  402. from: message.sender_id|| '',
  403. data: message.content,
  404. business_type: message.business_type || 1
  405. };
  406. pcim_doctorClient.socket.emit('message', {
  407. session_id: message.session_id||'',
  408. session_type: sessionType,
  409. from: message.sender_id|| '',
  410. data: message.content,
  411. business_type: message.business_type || 1,
  412. sender_name: message.sender_name,
  413. content_type: message.content_type,
  414. content: message.content,
  415. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  416. type: message.content_type, // legacy support
  417. name: message.sender_name,
  418. patient_name:message.patient_name,
  419. patient_age:message.patient_age,
  420. patient_sex:message.patient_sex
  421. });
  422. }
  423. }
  424. }
  425. /**
  426. * 发送socket给居民
  427. * @param patientId
  428. * @param message
  429. */
  430. static sendSocketMessageToPatient(patientId, message) {
  431. let patientClient = clientCache.findByIdAndType(patientId,SOCKET_TYPES.PATIENT);
  432. let pc_patientClient = clientCache.findByIdAndType("pcpatient_"+patientId,SOCKET_TYPES.PC_PATIENT);
  433. if(!patientClient&&!pc_patientClient){
  434. log.warn("target patient is not online!");
  435. return;
  436. }
  437. // let sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);//app医生发送的消息
  438. // if(!sendClient){//pc医生发送的消息
  439. // sendClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
  440. // }
  441. // if(!sendClient){//居民发送的消息
  442. // sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.PATIENT);
  443. // }
  444. var count = 0;
  445. if(patientClient&&message.session_id==patientClient.sessionId){
  446. WechatClient.updateParticipantLastFetchTime(patientClient.sessionId, patientId, ObjectUtil.timestampToLong(message.timestamp));
  447. patientClient.socket.emit('message', {
  448. id: message.id,
  449. session_id: message.session_id,
  450. sender_id: message.sender_id,
  451. sender_name: message.sender_name,
  452. content_type: message.content_type,
  453. content: message.content,
  454. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  455. type: message.content_type, // legacy support
  456. name: message.sender_name,
  457. });
  458. }else{
  459. count++;
  460. }
  461. //发送pc端
  462. if(pc_patientClient&&message.session_id==pc_patientClient.sessionId){
  463. WechatClient.updateParticipantLastFetchTime(pc_patientClient.sessionId, patientId, ObjectUtil.timestampToLong(message.timestamp));
  464. pc_patientClient.socket.emit('message', {
  465. id: message.id,
  466. session_id: message.session_id,
  467. sender_id: message.sender_id,
  468. sender_name: message.sender_name,
  469. content_type: message.content_type,
  470. content: message.content,
  471. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  472. type: message.content_type, // legacy support
  473. name: message.sender_name,
  474. });
  475. }else{
  476. count++;
  477. }
  478. if(count==2){
  479. log.warn("patient is not in the same session or is not online");
  480. }
  481. }
  482. //推送居民、居民PC、医生、医生PC外层推送
  483. static sendSystemSocketMessage(targetUserId, message) {
  484. //居民外层消息推送
  485. let patientClient = clientCache.findByIdAndType("patient_system_"+targetUserId,SOCKET_TYPES.PATIENT_SYSTEM);
  486. let pc_patientClient = clientCache.findByIdAndType("pcpatient_system_"+targetUserId,SOCKET_TYPES.PC_PATIENT_SYSTEM);
  487. if(!patientClient&&!pc_patientClient){
  488. log.warn("target patient systemt is not online!");
  489. // return;
  490. }
  491. var patientcount = 0;
  492. if(patientClient&&message.session_id==patientClient.sessionId){
  493. WechatClient.updateParticipantLastFetchTime(patientClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  494. patientClient.socket.emit('message', {
  495. id: message.id,
  496. session_id: message.session_id,
  497. sender_id: message.sender_id,
  498. sender_name: message.sender_name,
  499. content_type: message.content_type,
  500. content: message.content,
  501. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  502. type: message.content_type, // legacy support
  503. name: message.sender_name,
  504. });
  505. }else{
  506. patientcount++;
  507. }
  508. //发送pc端
  509. if(pc_patientClient&&message.session_id==pc_patientClient.sessionId){
  510. WechatClient.updateParticipantLastFetchTime(pc_patientClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  511. pc_patientClient.socket.emit('message', {
  512. id: message.id,
  513. session_id: message.session_id,
  514. sender_id: message.sender_id,
  515. sender_name: message.sender_name,
  516. content_type: message.content_type,
  517. content: message.content,
  518. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  519. type: message.content_type, // legacy support
  520. name: message.sender_name,
  521. });
  522. }else{
  523. patientcount++;
  524. }
  525. if(patientcount==2){
  526. log.warn("patient system is not in the same session or is not online");
  527. }
  528. //医生外层消息推送
  529. let doctorClient = clientCache.findByIdAndType("doctor_system_"+targetUserId,SOCKET_TYPES.DOCTOR_SYSTEM);
  530. let pc_doctorClient = clientCache.findByIdAndType("pc_system_"+targetUserId,SOCKET_TYPES.PC_DOCTOR_SYSTEM);
  531. if(!doctorClient&&!pc_doctorClient){
  532. log.warn("target doctor system is not online!");
  533. // return;
  534. }
  535. var doctorcount = 0;
  536. if(doctorClient&&message.session_id==doctorClient.sessionId){
  537. WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  538. doctorClient.socket.emit('message', {
  539. id: message.id,
  540. session_id: message.session_id,
  541. sender_id: message.sender_id,
  542. sender_name: message.sender_name,
  543. content_type: message.content_type,
  544. content: message.content,
  545. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  546. type: message.content_type, // legacy support
  547. name: message.sender_name,
  548. });
  549. }else{
  550. doctorcount++;
  551. }
  552. //发送pc端 - PC端消息不做sessionid的判断,前端自己判断消息归属于哪个会话,自行渲染--20191012-huangwenjie
  553. // if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){
  554. if(pc_doctorClient){
  555. WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  556. pc_doctorClient.socket.emit('message', {
  557. id: message.id,
  558. session_id: message.session_id,
  559. sender_id: message.sender_id,
  560. sender_name: message.sender_name,
  561. content_type: message.content_type,
  562. content: message.content,
  563. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  564. type: message.content_type, // legacy support
  565. name: message.sender_name,
  566. });
  567. }else{
  568. doctorcount++;
  569. }
  570. if(doctorcount==2){
  571. log.warn("doctor system is not in the same session or is not online");
  572. }
  573. }
  574. //推送托盘消息
  575. static sendMDTSystemSocketMessage(targetUserId, message) {
  576. //居民外层消息推送
  577. let mdtDcotorClient = clientCache.findByIdAndType("pcim_"+targetUserId,SOCKET_TYPES.PCIM_DOCTOR);
  578. if(!mdtDcotorClient){
  579. log.warn("target mdt doctor is not online!");
  580. }
  581. var mdtDoctorCount = 0;
  582. if(mdtDcotorClient&&message.session_id==mdtDcotorClient.sessionId){
  583. WechatClient.updateParticipantLastFetchTime(mdtDcotorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
  584. mdtDcotorClient.socket.emit('message', {
  585. id: message.id,
  586. session_id: message.session_id,
  587. sender_id: message.sender_id,
  588. sender_name: message.sender_name,
  589. content_type: message.content_type,
  590. content: message.content,
  591. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  592. type: message.content_type, // legacy support
  593. name: message.sender_name,
  594. });
  595. }else{
  596. mdtDoctorCount++;
  597. }
  598. if(mdtDoctorCount==2){
  599. log.warn("doctor system is not in the same session or is not online");
  600. }
  601. }
  602. /**
  603. *
  604. * 发送微信模板消息给居民
  605. *
  606. * @param targetUserId
  607. * @param message
  608. */
  609. static sendViaMessageTemplate(targetUserId, targetUserName, message) {
  610. async.waterfall([
  611. // 获取微信openid
  612. function (callback) {
  613. PatientRepo.findWechatOpenIds(targetUserId, function (err, res) {
  614. if (err) {
  615. ModelUtil.logError("Get wechat openid failed", err);
  616. return;
  617. }
  618. var map = new Map();
  619. res.forEach(function (participant) {
  620. let openid = participant.openid;
  621. if (targetUserId==participant.code) {
  622. if (!openid) {
  623. ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
  624. }
  625. map.set("openid",participant);
  626. }else {
  627. if(!map.has(openid)){
  628. map.set(openid,participant);
  629. }
  630. }
  631. })
  632. //
  633. // let openid = result && result.length > 0 ? result[0].openid : null;
  634. // if (!openid) {
  635. // ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
  636. // return;
  637. // }
  638. //
  639. // log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid);
  640. callback(null, map);
  641. });
  642. },
  643. // 获取议题信息
  644. function (map, callback) {
  645. TopicRepo.findLastTopicStatusAndType(message.session_id, function (err, res) {
  646. if (err) {
  647. ModelUtil.logError("Get topic failed", err);
  648. return;
  649. }
  650. if (!res || res.length == 0) {
  651. ModelUtil.logError("Unable to find session last topic");
  652. return;
  653. }
  654. callback(null, map, message.sender_name, res[0]);
  655. });
  656. },
  657. // 发送消息
  658. function (map, senderName, topic,callback) {
  659. let replyContent = message.content;
  660. switch (Number.parseInt(message.content_type)) {
  661. case CONTENT_TYPES.Image:
  662. replyContent = "[图片]";
  663. break;
  664. case CONTENT_TYPES.Audio:
  665. replyContent = "[语音]";
  666. break;
  667. default:
  668. break;
  669. }
  670. var patient = map.get("openid");
  671. map.delete("openid");
  672. let agent = topic.agent;
  673. let consultTitle = null;
  674. let description = null;
  675. let url = config.wechatConfig.baseUrl;
  676. switch (topic.type) {
  677. case 8:
  678. consultTitle = "续方";
  679. description = "续方咨询";
  680. url = url + "/wx/html/yszx/html/prescription-consulting.html";
  681. case 11:
  682. consultTitle = "上门服务";
  683. description = "上门服务咨询";
  684. url = url + "wx/html/appoint_service/html/appoint-serviceDetail.html";
  685. default:
  686. consultTitle = "健康";
  687. description = topic.description;
  688. url = url + "/wx/html/yszx/html/consulting-doctor.html";
  689. }
  690. if(agent){//代理人发起的议题
  691. var agentOpenid = "";
  692. if(map.size>0){
  693. for(var key of map.keys()){
  694. var member = map.get(key);
  695. if(agent == member.code){
  696. agentOpenid = key;
  697. var openid = key;
  698. var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复";
  699. // 发送模板消息
  700. WechatSDK.sendTemplateMessage({
  701. touser: openid,
  702. name: member.name,
  703. patient: member.code,
  704. template_id: config.wechatConfig.template.consultTemplate,
  705. url: url + "?openid=" + openid + "&type="+topic.type+"&doctor="+message.sender_id+
  706. "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code,
  707. data: {
  708. first: {value: first, color: "#000000"}
  709. , remark: {value: "", color: "#000000"}
  710. , keyword1: {value: description, color: "#000000"}
  711. , keyword2: {value: replyContent, color: "#000000"}
  712. , keyword3: {value: senderName, color: "#000000"}
  713. }
  714. }, function (err, res) {
  715. err ? log.error(err) : log.info(res);
  716. });
  717. }
  718. }
  719. }
  720. if(patient.openid&&patient.openid!=agentOpenid){
  721. var first = "您的"+consultTitle+"咨询有新的回复";
  722. // 发送模板消息
  723. WechatSDK.sendTemplateMessage({
  724. touser: patient.openid,
  725. name: targetUserName,
  726. patient: targetUserId,
  727. template_id: config.wechatConfig.template.consultTemplate,
  728. url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+
  729. "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code,
  730. data: {
  731. first: {value: first, color: "#000000"}
  732. , remark: {value: "", color: "#000000"}
  733. , keyword1: {value: description, color: "#000000"}
  734. , keyword2: {value: replyContent, color: "#000000"}
  735. , keyword3: {value: senderName, color: "#000000"}
  736. }
  737. }, function (err, res) {
  738. err ? log.error(err) : log.info(res);
  739. });
  740. }
  741. }else {//自己发起的议题
  742. // 发送模板消息
  743. if(patient.openid){
  744. WechatSDK.sendTemplateMessage({
  745. touser: patient.openid,
  746. name: targetUserName,
  747. patient: targetUserId,
  748. template_id: config.wechatConfig.template.consultTemplate,
  749. url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+
  750. "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code,
  751. data: {
  752. first: {value: "您的"+consultTitle+"咨询有新的回复", color: "#000000"}
  753. , remark: {value: "", color: "#000000"}
  754. , keyword1: {value: description, color: "#000000"}
  755. , keyword2: {value: replyContent, color: "#000000"}
  756. , keyword3: {value: senderName, color: "#000000"}
  757. }
  758. }, function (err, res) {
  759. err ? log.error(err) : log.info(res);
  760. });
  761. }
  762. if(map.size>0){
  763. for(var key of map.keys()){
  764. if(!patient.openid||key!=patient.openid){
  765. var member = map.get(key);
  766. var openid = key;
  767. var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复";
  768. // 发送模板消息
  769. WechatSDK.sendTemplateMessage({
  770. touser: openid,
  771. name: member.name,
  772. patient: member.code,
  773. template_id: config.wechatConfig.template.consultTemplate,
  774. url: url + "?openid=" + openid +"&type="+topic.type+"&doctor="+message.sender_id+
  775. "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code,
  776. data: {
  777. first: {value: first, color: "#000000"}
  778. , remark: {value: "", color: "#000000"}
  779. , keyword1: {value: description, color: "#000000"}
  780. , keyword2: {value: replyContent, color: "#000000"}
  781. , keyword3: {value: senderName, color: "#000000"}
  782. }
  783. }, function (err, res) {
  784. err ? log.error(err) : log.info(res);
  785. });
  786. }
  787. }
  788. }
  789. }
  790. callback(null, null);
  791. }
  792. ],
  793. function (err, res) {
  794. if (!err) {
  795. log.info("Send via wechat template message, DONE!");
  796. }
  797. });
  798. };
  799. static updateParticipantLastFetchTime(sessionId, userId, score) {
  800. score = score + 1000;
  801. let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
  802. redisConn.zaddAsync(participantsKey, score, userId)
  803. .then(function (res) {
  804. ParticipantRepo.updateLastFetchTime(new Date(score), sessionId, userId, function (err, res) {
  805. if (err) {
  806. log.error("Update participant last fetch time failed: ", err);
  807. }
  808. });
  809. })
  810. .catch(function (err) {
  811. log.error("Update participant last fetch time failed: ", err);
  812. });
  813. };
  814. /**
  815. * 发送第三方接口的微信模版消息
  816. * @param targetUserId
  817. * @param message
  818. */
  819. static sendThirdMessageTemplate(targetUserId, targetUserName, message) {
  820. async.waterfall([
  821. // 获取微信openid
  822. function (callback) {
  823. PatientRepo.findOne(targetUserId, function (err, res) {
  824. if (err) {
  825. ModelUtil.logError("Get wechat openid failed", err);
  826. return;
  827. }
  828. var map = new Map();
  829. res.forEach(function (participant) {
  830. let openid = participant.openid;
  831. let idcard = participant.idcard;
  832. let mobile = participant.mobile;
  833. let name = participant.name;
  834. let id = participant.id;
  835. map.set("openid",openid);
  836. map.set("idcard",idcard);
  837. map.set("mobile",mobile);
  838. map.set("name",name);
  839. map.set("id",id);
  840. })
  841. //
  842. // let openid = result && result.length > 0 ? result[0].openid : null;
  843. // if (!openid) {
  844. // ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
  845. // return;
  846. // }
  847. //
  848. // log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid);
  849. callback(null, map);
  850. });
  851. },
  852. // 获取议题信息
  853. function (map, callback) {
  854. TopicRepo.findLastTopicStatusAndType(message.session_id, function (err, res) {
  855. if (err) {
  856. ModelUtil.logError("Get topic failed", err);
  857. return;
  858. }
  859. if (!res || res.length == 0) {
  860. ModelUtil.logError("Unable to find session last topic");
  861. return;
  862. }
  863. callback(null, map, message.sender_name, res[0]);
  864. });
  865. },
  866. // 发送消息
  867. function (map, senderName, topic,callback) {
  868. let replyContent = message.content;
  869. switch (Number.parseInt(message.content_type)) {
  870. case CONTENT_TYPES.Image:
  871. replyContent = "[图片]";
  872. break;
  873. case CONTENT_TYPES.Audio:
  874. replyContent = "[语音]";
  875. break;
  876. case CONTENT_TYPES.ConsultSuggest:
  877. var tmpContent = JSON.parse(message.content);
  878. var arr = [], consultAdvice = "";
  879. log.error("tmpContent1:"+tmpContent);
  880. tmpContent.forEach(function (v) {
  881. if(v.advice_type==1){
  882. arr.push(v.advice_value);
  883. } else {
  884. consultAdvice = v.advice_value;
  885. }
  886. });
  887. log.error("tmpContent2:"+arr);
  888. replyContent = "参考疾病:"+arr.join("、")+"\r\n"+"咨询建议:"+consultAdvice;
  889. log.error("replyContent:"+replyContent);
  890. break;
  891. default:
  892. break;
  893. }
  894. let consultTitle = null;
  895. let description = null;
  896. let url = null;
  897. switch (topic.type) {
  898. case 8:
  899. consultTitle = "续方";
  900. description = "续方咨询";
  901. url = url + "/wx/html/yszx/html/prescription-consulting.html";
  902. case 11:
  903. consultTitle = "上门服务";
  904. description = "上门服务咨询";
  905. url = url + "wx/html/appoint_service/html/appoint-serviceDetail.html";
  906. default:
  907. consultTitle = "咨询回复提醒";
  908. description = topic.description;
  909. if("xmijk" == config.imClientType.id){
  910. url = "http://zb.xmtyw.cn/ims-wx/index.html#/chatRoom?type=1&consultCode="+topic.id;
  911. }else if("zsyy" == config.imClientType.id){
  912. url = "https://hlwyy.xmzsh.com/ims-wx/index.html#/chatRoom?type=1&consultCode="+topic.id;
  913. }else if("xm_xzzx_wx" == config.imClientType.id){
  914. url = "http://ih.xmheart.com/hlwyy/ims-wx/index.html#/chatRoom?type=1&consultCode="+topic.id;
  915. }else{}
  916. }
  917. log.info("内容类型"+message.content_type);
  918. log.info("内容"+message.content);
  919. //1、2、3、18、19、12、34
  920. // 发送模板消息
  921. if(map != null && (message.content_type==CONTENT_TYPES.PlainText||
  922. message.content_type==CONTENT_TYPES.Image||
  923. message.content_type==CONTENT_TYPES.Audio||
  924. message.content_type==CONTENT_TYPES.Video||
  925. message.content_type==CONTENT_TYPES.PersonalCard||
  926. message.content_type==CONTENT_TYPES.MessageForward||
  927. message.content_type==CONTENT_TYPES.PrescriptionSuggest||
  928. message.content_type==CONTENT_TYPES.ConsultSuggest||
  929. message.content_type==CONTENT_TYPES.Article||
  930. message.content_type==CONTENT_TYPES.surveyMessage)){
  931. log.info("内容类型122:"+message.content_type);
  932. let userName = map.get("name");
  933. let idCard = map.get("idcard");
  934. let phone = map.get("mobile");
  935. let title = consultTitle;
  936. let content = "您的咨询有新的回复";
  937. let contentString = replyContent;
  938. // log.info("推送居民公众号:params:"+params)
  939. let params = 'senderName='+encodeURIComponent(senderName)+'&userName='+encodeURIComponent(userName)+'&idCard='+idCard+"&phone="+phone+'&title='+encodeURIComponent(consultTitle)+'&content='+encodeURIComponent(content)+'&contentString='+encodeURIComponent(contentString)+'&url='+encodeURIComponent(url);
  940. HlwyyWechatAssistantSDK.request(userName,idCard,phone,title,content,contentString,url,params, function (err, res) {
  941. // WlyyAssistantSDK.request('admin', '0a5c5258-8863-4b07-a3f9-88c768528ab4', '', 'admin_imei', '/doctor/feldsher/sendDoctorTemplate', param, function (err, res) {
  942. // WlyySDK.request('admin', '0a5c5258-8863-4b07-a3f9-88c768528ab4', '', 'admin_imei', '/doctor/feldsher/sendDoctorTemplate?' + params, 'GET', function (err, res) {
  943. if(err){
  944. log.error(err);
  945. }else {
  946. log.info(res);
  947. }
  948. });
  949. }
  950. callback(null, null);
  951. }
  952. ],
  953. function (err, res) {
  954. if (!err) {
  955. log.info("Send via wechat template message, DONE!");
  956. }
  957. });
  958. };
  959. }
  960. module.exports = WechatClient;