wechat.client.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 redisConn = RedisClient.redisClient().connection;
  13. let clientCache = require('../socket.io/client.cache').clientCache();
  14. let configFile = require('../../include/commons').CONFIG_FILE;
  15. let config = require('../../resources/config/' + configFile);
  16. let log = require("../../util/log.js");
  17. let https = require('https');
  18. let async = require('async');
  19. const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES;
  20. const SOCKET_TYPES = require('../../include/commons').SOCKET_TYPES;
  21. const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
  22. class WechatClient extends RedisModel {
  23. constructor() {
  24. super();
  25. }
  26. /**
  27. * 取得用户微信端状态。若Redis中找不到,则从MySQL中查找。
  28. *
  29. * @param userId
  30. * @param handler
  31. */
  32. static getWechatStatus(userId, handler) {
  33. redisConn.hgetallAsync(RedisModel.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId))
  34. .then(function (status) {
  35. if (status == null) {
  36. PatientRepo.findWechatOpenId(userId, handler);
  37. } else {
  38. handler(null, {openid: status.openid});
  39. }
  40. })
  41. .catch(function (err) {
  42. handler(err, null);
  43. });
  44. }
  45. /**
  46. * 向微信端用户发送消息。若用户微信端在线,通过Web Socket推送给患者,如果不在线则通过微信的模板消息。
  47. *
  48. * 只推送文本、图片及语音消息
  49. *
  50. * @param targetUserId
  51. * @param message 消息体
  52. */
  53. static sendMessage(targetUserId, targetUserName, message) {
  54. if (message&&(message.content_type == CONTENT_TYPES.PlainText ||
  55. message.content_type == CONTENT_TYPES.Image ||
  56. message.content_type == CONTENT_TYPES.Audio)) {
  57. let patientClient = clientCache.findById(targetUserId);
  58. let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
  59. if (patientClient) {
  60. log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId);
  61. WechatClient.sendViaWebSocket(patientClient.socket, message);
  62. if(doctorClient){
  63. if(patientClient.sessionId==doctorClient.sessionId){
  64. //用户socket在线,推送给用户后,告知医生此消息已读
  65. WechatClient.sendReadDoctor(doctorClient.socket, message);
  66. }
  67. }
  68. } else {
  69. log.info("User's wechat endpoint is not online, sending via wechat template message. User id: ", targetUserId);
  70. WechatClient.sendViaMessageTemplate(targetUserId, targetUserName, message);
  71. }
  72. }
  73. };
  74. static sendViaWebSocket(socket, message) {
  75. socket.emit('message', {
  76. id: message.id,
  77. session_id: message.session_id,
  78. sender_id: message.sender_id,
  79. sender_name: message.sender_name,
  80. content_type: message.content_type,
  81. content: message.content,
  82. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  83. type: message.content_type, // legacy support
  84. name: message.sender_name,
  85. sender_img : message.sender_img
  86. });
  87. }
  88. static sendAllRead(doctorId,sessionId){
  89. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  90. if(doctorClient){
  91. if(doctorClient.sessionId==sessionId){
  92. doctorClient.socket.emit('message',{ read:"all"});
  93. }else{
  94. log.warn(" doctor not in the same session ");
  95. }
  96. }else{
  97. log.warn(doctorId+" target doctor is not online!");
  98. }
  99. }
  100. static sendReadDoctor(socket, message) {
  101. socket.emit('message', {
  102. id: message.id,
  103. session_id: message.session_id,
  104. sender_id: message.sender_id,
  105. sender_name: message.sender_name,
  106. content_type: message.content_type,
  107. content: message.content,
  108. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  109. type: message.content_type, // legacy support
  110. name: message.sender_name,
  111. read:"one"
  112. });
  113. }
  114. static sendReadDoctorByDoctorId(doctorId, message) {
  115. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  116. if(!doctorClient){
  117. log.warn("target doctor is not online!");
  118. return;
  119. }
  120. let sendDoctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
  121. if(sendDoctorClient&&sendDoctorClient.sessionId==doctorClient.sessionId){
  122. sendDoctorClient.socket.emit('message', {
  123. id: message.id,
  124. session_id: message.session_id,
  125. sender_id: message.sender_id,
  126. sender_name: message.sender_name,
  127. content_type: message.content_type,
  128. content: message.content,
  129. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  130. type: message.content_type, // legacy support
  131. name: message.sender_name,
  132. read:"one"
  133. });
  134. }else{
  135. log.warn("doctor is not in the same session");
  136. }
  137. }
  138. /**
  139. * 发送微信模板消息给居民
  140. *
  141. * @param targetUserId
  142. * @param message
  143. */
  144. static sendViaMessageTemplate(targetUserId, targetUserName, message) {
  145. async.waterfall([
  146. // 获取微信openid
  147. function (callback) {
  148. PatientRepo.findWechatOpenId(targetUserId, function (err, result) {
  149. if (err) {
  150. ModelUtil.logError("Get wechat openid failed", err);
  151. return;
  152. }
  153. let openid = result && result.length > 0 ? result[0].openid : null;
  154. if (!openid) {
  155. ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
  156. return;
  157. }
  158. log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid);
  159. callback(null, openid);
  160. });
  161. },
  162. // 获取议题信息
  163. function (openid, callback) {
  164. TopicRepo.findLastTopicStatus(message.session_id, function (err, res) {
  165. if (err) {
  166. ModelUtil.logError("Get topic failed", err);
  167. return;
  168. }
  169. if (!res || res.length == 0) {
  170. ModelUtil.logError("Unable to find session last topic");
  171. return;
  172. }
  173. callback(null, openid, message.sender_name, res[0]);
  174. });
  175. },
  176. // 发送消息
  177. function (openid, senderName, topic, callback) {
  178. let replyContent = message.content;
  179. switch (Number.parseInt(message.content_type)) {
  180. case CONTENT_TYPES.Image:
  181. replyContent = "[图片]";
  182. break;
  183. case CONTENT_TYPES.Audio:
  184. replyContent = "[语音]";
  185. break;
  186. default:
  187. break;
  188. }
  189. // 发送模板消息
  190. WechatSDK.sendTemplateMessage({
  191. touser: openid,
  192. template_id: config.wechatConfig.template.consultTemplate,
  193. url: config.wechatConfig.baseUrl + "/wx/html/yszx/html/consulting-doctor.html?openid=" + openid +
  194. "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName,
  195. data: {
  196. first: {value: "您的健康咨询有新的回复", color: "#000000"}
  197. , remark: {value: "", color: "#000000"}
  198. , keyword1: {value: topic.description, color: "#000000"}
  199. , keyword2: {value: replyContent, color: "#000000"}
  200. , keyword3: {value: senderName, color: "#000000"}
  201. }
  202. }, function (err, res) {
  203. err ? log.error(err) : log.info(res);
  204. });
  205. callback(null, null);
  206. }
  207. ],
  208. function (err, res) {
  209. if (!err) {
  210. log.info("Send via wechat template message, DONE!");
  211. }
  212. });
  213. };
  214. }
  215. module.exports = WechatClient;