wechat.client.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. });
  86. }
  87. static sendAllRead(doctorId,sessionId){
  88. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  89. if(doctorClient){
  90. if(doctorClient.sessionId==sessionId){
  91. doctorClient.socket.emit('message',{ read:"all"});
  92. }else{
  93. log.warn(" doctor not in the same session ");
  94. }
  95. }else{
  96. log.warn(doctorId+" target doctor is not online!");
  97. }
  98. }
  99. static sendReadDoctor(socket, message) {
  100. socket.emit('message', {
  101. id: message.id,
  102. session_id: message.session_id,
  103. sender_id: message.sender_id,
  104. sender_name: message.sender_name,
  105. content_type: message.content_type,
  106. content: message.content,
  107. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  108. type: message.content_type, // legacy support
  109. name: message.sender_name,
  110. read:"one"
  111. });
  112. }
  113. static sendReadDoctorByDoctorId(doctorId, message) {
  114. let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
  115. if(!doctorClient){
  116. log.warn("target doctor is not online!");
  117. return;
  118. }
  119. let sendDoctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
  120. if(sendDoctorClient.sessionId==doctorClient.sessionId){
  121. sendDoctorClient.socket.emit('message', {
  122. id: message.id,
  123. session_id: message.session_id,
  124. sender_id: message.sender_id,
  125. sender_name: message.sender_name,
  126. content_type: message.content_type,
  127. content: message.content,
  128. timestamp: ObjectUtil.timestampToLong(message.timestamp),
  129. type: message.content_type, // legacy support
  130. name: message.sender_name,
  131. read:"one"
  132. });
  133. }else{
  134. log.warn("doctor is not in the same session");
  135. }
  136. }
  137. /**
  138. * 发送微信模板消息给居民
  139. *
  140. * @param targetUserId
  141. * @param message
  142. */
  143. static sendViaMessageTemplate(targetUserId, targetUserName, message) {
  144. async.waterfall([
  145. // 获取微信openid
  146. function (callback) {
  147. PatientRepo.findWechatOpenId(targetUserId, function (err, result) {
  148. if (err) {
  149. ModelUtil.logError("Get wechat openid failed", err);
  150. return;
  151. }
  152. let openid = result && result.length > 0 ? result[0].openid : null;
  153. if (!openid) {
  154. ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
  155. return;
  156. }
  157. log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid);
  158. callback(null, openid);
  159. });
  160. },
  161. // 获取议题信息
  162. function (openid, callback) {
  163. TopicRepo.findLastTopicStatus(message.session_id, function (err, res) {
  164. if (err) {
  165. ModelUtil.logError("Get topic failed", err);
  166. return;
  167. }
  168. if (!res || res.length == 0) {
  169. ModelUtil.logError("Unable to find session last topic");
  170. return;
  171. }
  172. callback(null, openid, message.sender_name, res[0]);
  173. });
  174. },
  175. // 发送消息
  176. function (openid, senderName, topic, callback) {
  177. let replyContent = message.content;
  178. switch (Number.parseInt(message.content_type)) {
  179. case CONTENT_TYPES.Image:
  180. replyContent = "[图片]";
  181. break;
  182. case CONTENT_TYPES.Audio:
  183. replyContent = "[语音]";
  184. break;
  185. default:
  186. break;
  187. }
  188. // 发送模板消息
  189. WechatSDK.sendTemplateMessage({
  190. touser: openid,
  191. template_id: config.wechatConfig.template.consultTemplate,
  192. url: config.wechatConfig.baseUrl + "/wx/html/yszx/html/consulting-doctor.html?openid=" + openid +
  193. "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName,
  194. data: {
  195. first: {value: "您的健康咨询有新的回复", color: "#000000"}
  196. , remark: {value: "", color: "#000000"}
  197. , keyword1: {value: topic.description, color: "#000000"}
  198. , keyword2: {value: replyContent, color: "#000000"}
  199. , keyword3: {value: senderName, color: "#000000"}
  200. }
  201. }, function (err, res) {
  202. err ? log.error(err) : log.info(res);
  203. });
  204. callback(null, null);
  205. }
  206. ],
  207. function (err, res) {
  208. if (!err) {
  209. log.info("Send via wechat template message, DONE!");
  210. }
  211. });
  212. };
  213. }
  214. module.exports = WechatClient;