123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233 |
- /**
- * 用户微信客户端。
- */
- "use strict";
- let RedisClient = require('../../repository/redis/redis.client');
- let RedisModel = require('../redis.model');
- let ObjectUtil = require("../../util/object.util.js");
- let ModelUtil = require('../../util/model.util');
- let WechatSDK = require('../../util/wechat.sdk');
- let PatientRepo = require('../../repository/mysql/patient.repo');
- let TopicRepo = require("../../repository/mysql/topics.repo.js");
- let redisConn = RedisClient.redisClient().connection;
- let clientCache = require('../socket.io/client.cache').clientCache();
- let configFile = require('../../include/commons').CONFIG_FILE;
- let config = require('../../resources/config/' + configFile);
- let log = require("../../util/log.js");
- let https = require('https');
- let async = require('async');
- const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES;
- const SOCKET_TYPES = require('../../include/commons').SOCKET_TYPES;
- const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
- class WechatClient extends RedisModel {
- constructor() {
- super();
- }
- /**
- * 取得用户微信端状态。若Redis中找不到,则从MySQL中查找。
- *
- * @param userId
- * @param handler
- */
- static getWechatStatus(userId, handler) {
- redisConn.hgetallAsync(RedisModel.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId))
- .then(function (status) {
- if (status == null) {
- PatientRepo.findWechatOpenId(userId, handler);
- } else {
- handler(null, {openid: status.openid});
- }
- })
- .catch(function (err) {
- handler(err, null);
- });
- }
- /**
- * 向微信端用户发送消息。若用户微信端在线,通过Web Socket推送给患者,如果不在线则通过微信的模板消息。
- *
- * 只推送文本、图片及语音消息
- *
- * @param targetUserId
- * @param message 消息体
- */
- static sendMessage(targetUserId, targetUserName, message) {
- if (message&&(message.content_type == CONTENT_TYPES.PlainText ||
- message.content_type == CONTENT_TYPES.Image ||
- message.content_type == CONTENT_TYPES.Audio)) {
- let patientClient = clientCache.findById(targetUserId);
- let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
- if (patientClient) {
- log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId);
- WechatClient.sendViaWebSocket(patientClient.socket, message);
- if(doctorClient){
- if(patientClient.sessionId==doctorClient.sessionId){
- //用户socket在线,推送给用户后,告知医生此消息已读
- WechatClient.sendReadDoctor(doctorClient.socket, message);
- }
- }
- } else {
- log.info("User's wechat endpoint is not online, sending via wechat template message. User id: ", targetUserId);
- WechatClient.sendViaMessageTemplate(targetUserId, targetUserName, message);
- }
- }
- };
- static sendViaWebSocket(socket, message) {
- socket.emit('message', {
- id: message.id,
- session_id: message.session_id,
- sender_id: message.sender_id,
- sender_name: message.sender_name,
- content_type: message.content_type,
- content: message.content,
- timestamp: ObjectUtil.timestampToLong(message.timestamp),
- type: message.content_type, // legacy support
- name: message.sender_name
- });
- }
- static sendAllRead(doctorId,sessionId){
- let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
- if(doctorClient){
- if(doctorClient.sessionId==sessionId){
- doctorClient.socket.emit('message',{ read:"all"});
- }else{
- log.warn(" doctor not in the same session ");
- }
- }else{
- log.warn(doctorId+" target doctor is not online!");
- }
- }
- static sendReadDoctor(socket, message) {
- socket.emit('message', {
- id: message.id,
- session_id: message.session_id,
- sender_id: message.sender_id,
- sender_name: message.sender_name,
- content_type: message.content_type,
- content: message.content,
- timestamp: ObjectUtil.timestampToLong(message.timestamp),
- type: message.content_type, // legacy support
- name: message.sender_name,
- read:"one"
- });
- }
- static sendReadDoctorByDoctorId(doctorId, message) {
- let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
- if(!doctorClient){
- log.warn("target doctor is not online!");
- return;
- }
- let sendDoctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
- if(sendDoctorClient.sessionId==doctorClient.sessionId){
- sendDoctorClient.socket.emit('message', {
- id: message.id,
- session_id: message.session_id,
- sender_id: message.sender_id,
- sender_name: message.sender_name,
- content_type: message.content_type,
- content: message.content,
- timestamp: ObjectUtil.timestampToLong(message.timestamp),
- type: message.content_type, // legacy support
- name: message.sender_name,
- read:"one"
- });
- }else{
- log.warn("doctor is not in the same session");
- }
- }
- /**
- * 发送微信模板消息给居民
- *
- * @param targetUserId
- * @param message
- */
- static sendViaMessageTemplate(targetUserId, targetUserName, message) {
- async.waterfall([
- // 获取微信openid
- function (callback) {
- PatientRepo.findWechatOpenId(targetUserId, function (err, result) {
- if (err) {
- ModelUtil.logError("Get wechat openid failed", err);
- return;
- }
- let openid = result && result.length > 0 ? result[0].openid : null;
- if (!openid) {
- ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
- return;
- }
- log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid);
- callback(null, openid);
- });
- },
- // 获取议题信息
- function (openid, callback) {
- TopicRepo.findLastTopicStatus(message.session_id, function (err, res) {
- if (err) {
- ModelUtil.logError("Get topic failed", err);
- return;
- }
- if (!res || res.length == 0) {
- ModelUtil.logError("Unable to find session last topic");
- return;
- }
- callback(null, openid, message.sender_name, res[0]);
- });
- },
- // 发送消息
- function (openid, senderName, topic, callback) {
- let replyContent = message.content;
- switch (Number.parseInt(message.content_type)) {
- case CONTENT_TYPES.Image:
- replyContent = "[图片]";
- break;
- case CONTENT_TYPES.Audio:
- replyContent = "[语音]";
- break;
- default:
- break;
- }
- // 发送模板消息
- WechatSDK.sendTemplateMessage({
- touser: openid,
- template_id: config.wechatConfig.template.consultTemplate,
- url: config.wechatConfig.baseUrl + "/wx/html/yszx/html/consulting-doctor.html?openid=" + openid +
- "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName,
- data: {
- first: {value: "您的健康咨询有新的回复", color: "#000000"}
- , remark: {value: "", color: "#000000"}
- , keyword1: {value: topic.description, color: "#000000"}
- , keyword2: {value: replyContent, color: "#000000"}
- , keyword3: {value: senderName, color: "#000000"}
- }
- }, function (err, res) {
- err ? log.error(err) : log.info(res);
- });
- callback(null, null);
- }
- ],
- function (err, res) {
- if (!err) {
- log.info("Send via wechat template message, DONE!");
- }
- });
- };
- }
- module.exports = WechatClient;
|