yeshijie 7 rokov pred
rodič
commit
15529b8110

+ 2 - 2
src/server/app.js

@ -117,5 +117,5 @@ if(!server.address()){
//JobInitializer.init();
pubSub.registerHandlers(config.subChannel,msg=> console.log(msg));
pubSub.subscribe(config.subChannel);
// pubSub.registerHandlers(config.subChannel,msg=> console.log(msg));
// pubSub.subscribe(config.subChannel);

+ 17 - 15
src/server/handlers/socket.handler.js

@ -32,11 +32,11 @@ class SocketHandler {
                if (!data.userId) {
                    socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
                } else {
                    if("pc_doctor"===data.clientType){//新增pc端医生登录
                        data.userId = "pc_"+data.userId;
                    }else if("pcim_doctor"===data.clientType){//用于pcim 消息通知
                        data.userId = "pcim_"+data.userId;
                    }
                    // if("pc_doctor"===data.clientType){//新增pc端医生登录
                    //     data.userId = "pc_"+data.userId;
                    // }else if("pcim_doctor"===data.clientType){//用于pcim 消息通知
                    //     data.userId = "pcim_"+data.userId;
                    // }
                    if(clientCache.removeByUserId(data.userId)){
                        log.info("User " + data.userId + " already login");
@ -53,16 +53,18 @@ class SocketHandler {
                        clientCache.addClient(patientClient);
                        users.login(data.userId, 10, '', '');
                        socket.emit('ack', {});
                    }else if("pcim_doctor"===data.clientType){
                        //用于pcim 消息通知
                        let pcdoctorClient = new PcDoctorClient(socket, socketServer);
                        pcdoctorClient.userId = data.userId;
                        pcdoctorClient.password = data.password;
                        pcdoctorClient.clientType = data.clientType;
                        pcdoctorClient.sessionId =  "";
                        clientCache.addClient(pcdoctorClient);
                        socket.emit('ack', {});
                    }else{
                    }
                    // else if("pcim_doctor"===data.clientType){
                    //     //用于pcim 消息通知
                    //     let pcdoctorClient = new PcDoctorClient(socket, socketServer);
                    //     pcdoctorClient.userId = data.userId;
                    //     pcdoctorClient.password = data.password;
                    //     pcdoctorClient.clientType = data.clientType;
                    //     pcdoctorClient.sessionId =  "";
                    //     clientCache.addClient(pcdoctorClient);
                    //     socket.emit('ack', {});
                    // }
                    else{
                        let doctorClient = new DoctorClient(socket, socketServer);
                        doctorClient.userId = data.userId;
                        doctorClient.password = data.password;

+ 12 - 4
src/server/include/commons.js

@ -10,15 +10,20 @@
"use strict";
let configFile = "config.";
let wlyyDBName = "";
if (process.env.IM_PROFILE === "prod") {
    configFile += "prod";
    wlyyDBName = "wlyy";
} else if (process.env.IM_PROFILE === "local") {
    configFile += "local";
    wlyyDBName = "wlyy";
} else if (process.env.IM_PROFILE === "test") {
    configFile += "test";
    wlyyDBName = "wlyy";
} else {
    configFile += "dev";
    wlyyDBName = "wlyy_sr";
}
exports.CONFIG_FILE = configFile;
@ -208,10 +213,13 @@ const DB_TABLES = {
    Topics: "topics",
    StickySessions: "sticky_sessions",
    WlyyConsult:"wlyy_consults",
    WlyyConsultTeam:"wlyy.wlyy_consult_team",
    WlyyConsultS:"wlyy.wlyy_consult",
    MessageNoticeSetting:"wlyy.wlyy_message_notice_setting",
    SignFamily:"wlyy.wlyy_sign_family",
    WlyyConsultTeam:wlyyDBName+".wlyy_consult_team",
    WlyyConsultS:wlyyDBName+".wlyy_consult",
    WxAccessToken:wlyyDBName+".wx_access_token",
    WlyyWxPushLog:wlyyDBName+".wlyy_wx_push_log",
    WeixinTemplateConfig:wlyyDBName+".weixin_template_config",
    MessageNoticeSetting:wlyyDBName+".wlyy_message_notice_setting",
    SignFamily:wlyyDBName+".wlyy_sign_family",
    sessionTypeToTableName: function (sessionType) {
        if (sessionType == SESSION_TYPES.SYSTEM)

+ 0 - 15
src/server/models/client/app.client.js

@ -185,15 +185,6 @@ class AppClient extends RedisModel {
                            if(master_switch==0||im_switch==0){
                                ModelUtil.logError(targetId+"-关闭im消息,消息id", message.id);
                            }
                            // else if(session_type==SESSION_TYPES.MUC&&family_topic_switch==1){
                            //     SignFamilyRepo.isHealthDoctor(message.session_id,targetId,function (err,res) {
                            //         if(res&&res.length==0){
                            //             ModelUtil.logError("全科医生:"+targetId+"-关闭im消息,消息id", message.id);
                            //         }else{
                            //             AppClient.sendNotice(targetId, message, sessionType,badge,userStatus)
                            //         }
                            //     })
                            // }
                            else{
                                AppClient.sendNotice(targetId, message, sessionType,badge,userStatus)
                            }
@ -203,12 +194,6 @@ class AppClient extends RedisModel {
                    AppClient.sendNotice(targetId, message, sessionType,badge,userStatus)
                }
                // let pc_doctorClient = clientCache.findByIdAndType("pc_"+targetId,SOCKET_TYPES.PC_DOCTOR);
                // if(pc_doctorClient){
                //     log.warn("User's pc is online, user id: " + targetId + ", we cannot send getui.");
                //     return;
                // }
            });
        }
    }

+ 105 - 202
src/server/models/client/wechat.client.js

@ -11,6 +11,7 @@ let WechatSDK = require('../../util/wechat.sdk');
let PatientRepo = require('../../repository/mysql/patient.repo');
let TopicRepo = require("../../repository/mysql/topics.repo.js");
let ParticipantRepo = require("../../repository/mysql/participant.repo");
let WeChatTokenRepo = require("../../repository/mysql/wechat.token.repo");
let redisConn = RedisClient.redisClient().connection;
let clientCache = require('../socket.io/client.cache').clientCache();
let configFile = require('../../include/commons').CONFIG_FILE;
@ -65,7 +66,7 @@ class WechatClient extends RedisModel {
            message.content_type == CONTENT_TYPES.PrescriptionFollowupContent)) {
            let patientClient = clientCache.findById(targetUserId);
            let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
            let pc_doctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
            // let pc_doctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
            var count = 0;
            if (patientClient) {
                log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId);
@ -82,17 +83,17 @@ class WechatClient extends RedisModel {
                }else{
                    count++;
                }
                if(pc_doctorClient){
                    log.error("doctor sessionid "+pc_doctorClient.sessionId);
                    log.error("patient sessionid "+patientClient.sessionId);
                    if(patientClient.sessionId==pc_doctorClient.sessionId){
                        //用户socket在线,推送给用户后,告知医生此消息已读
                        WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
                        WechatClient.sendReadDoctor(pc_doctorClient.socket, message);
                    }
                }else{
                    count++;
                }
                // if(pc_doctorClient){
                //     log.error("doctor sessionid "+pc_doctorClient.sessionId);
                //     log.error("patient sessionid "+patientClient.sessionId);
                //     if(patientClient.sessionId==pc_doctorClient.sessionId){
                //         //用户socket在线,推送给用户后,告知医生此消息已读
                //         WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp));
                //         WechatClient.sendReadDoctor(pc_doctorClient.socket, message);
                //     }
                // }else{
                //     count++;
                // }
                if(count==0){
                    log.error("doctor client not found");
@ -189,8 +190,8 @@ class WechatClient extends RedisModel {
    static sendReadDoctorByDoctorId(doctorId, message) {
        let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
        let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
        if(!doctorClient&&!pc_doctorClient){
        // let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
        if(!doctorClient){
            log.warn("target doctor is not online!");
            return;
        }
@ -217,43 +218,36 @@ class WechatClient extends RedisModel {
            count++;
        }
        //发送pc版医生端
        if(pc_doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==pc_doctorClient.sessionId){
            WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
            pc_doctorClient.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{
            count++;
        }
        // if(pc_doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==pc_doctorClient.sessionId){
        //     WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
        //     pc_doctorClient.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{
        //     count++;
        // }
        if(count==2){
        if(count==1){
            log.warn("doctor is not in the same session or is not online");
        }
    }
    static sendSocketMessageToDoctor(doctorId, message) {
        let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
        let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
        if(!doctorClient&&!pc_doctorClient){
        // let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR);
        if(!doctorClient){
            log.warn("target doctor is not online!");
            return;
        }
        // let sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);//app医生发送的消息
        // if(!sendClient){//pc医生发送的消息
        //     sendClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR);
        // }
        // if(!sendClient){//居民发送的消息
        //     sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.PATIENT);
        // }
        var count = 0;
        if(doctorClient&&message.session_id==doctorClient.sessionId){
@ -275,24 +269,24 @@ class WechatClient extends RedisModel {
        //发送pc端
        if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){
            WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
            pc_doctorClient.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,
            });
        }else{
            count++;
        }
        // if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){
        //     WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp));
        //     pc_doctorClient.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,
        //     });
        // }else{
        //     count++;
        // }
        if(count==2){
        if(count==1){
            log.warn("doctor is not in the same session or is not online");
        }
    }
@ -336,40 +330,25 @@ class WechatClient extends RedisModel {
        async.waterfall([
                // 获取微信openid
                function (callback) {
                    PatientRepo.findWechatOpenIds(targetUserId, function (err, res) {
                    PatientRepo.findWechatOpenId(targetUserId, function (err, res) {
                        if (err) {
                            ModelUtil.logError("Get wechat openid failed", err);
                            return;
                        }
                        var map = new Map();
                        res.forEach(function (participant) {
                            let openid = participant.openid;
                            if (targetUserId==participant.code) {
                                if (!openid) {
                                    ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId);
                                }
                                map.set("openid",participant);
                            }else {
                                if(!map.has(openid)){
                                    map.set(openid,participant);
                                }
                            }
                        })
                        //
                        // 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, map);
                        let openid = res;
                        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 (map, callback) {
                function (openid, callback) {
                    TopicRepo.findLastTopicStatusAndType(message.session_id, function (err, res) {
                        if (err) {
                            ModelUtil.logError("Get topic failed", err);
@ -380,132 +359,56 @@ class WechatClient extends RedisModel {
                            ModelUtil.logError("Unable to find session last topic");
                            return;
                        }
                        callback(null, map, message.sender_name, res[0]);
                        callback(null, openid, message.sender_name, res[0]);
                    });
                },
                // 发送消息
                function (map, 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;
                    }
                function (openid, senderName, topic,callback) {
                    WeChatTokenRepo.findWxTemplateOne(function (err, res) {
                        if (err) {
                            ModelUtil.logError("Get topic failed", err);
                            return;
                        }
                    var patient = map.get("openid");
                    map.delete("openid");
                    let agent = topic.agent;
                    let consultTitle = topic.type==8?"续方":"健康";
                    let description = topic.type==8?"续方咨询":topic.description;
                    let url = config.wechatConfig.baseUrl + (topic.type==8?"/wx/html/yszx/html/prescription-consulting.html":"/wx/html/yszx/html/consulting-doctor.html");
                    if(agent){//代理人发起的议题
                        var agentOpenid = "";
                        if(map.size>0){
                            for(var key of map.keys()){
                                var member = map.get(key);
                                if(agent == member.code){
                                    agentOpenid = key;
                                    var openid = key;
                                    var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复";
                                    // 发送模板消息
                                    WechatSDK.sendTemplateMessage({
                                        touser: openid,
                                        name: member.name,
                                        patient: member.code,
                                        template_id: config.wechatConfig.template.consultTemplate,
                                        url: url + "?openid=" + openid + "&type="+topic.type+"&doctor="+message.sender_id+
                                        "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code,
                                        data: {
                                            first: {value: first, color: "#000000"}
                                            , remark: {value: "", color: "#000000"}
                                            , keyword1: {value: description, color: "#000000"}
                                            , keyword2: {value: replyContent, color: "#000000"}
                                            , keyword3: {value: senderName, color: "#000000"}
                                        }
                                    }, function (err, res) {
                                        err ? log.error(err) : log.info(res);
                                    });
                                }
                            }
                        if (!res || res.length == 0) {
                            ModelUtil.logError("Unable to find session last topic");
                            return;
                        }
                        if(patient.openid&&patient.openid!=agentOpenid){
                            var first = "您的"+consultTitle+"咨询有新的回复";
                            // 发送模板消息
                            WechatSDK.sendTemplateMessage({
                                touser: patient.openid,
                                name: targetUserName,
                                patient: targetUserId,
                                template_id: config.wechatConfig.template.consultTemplate,
                                url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+
                                "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code,
                                data: {
                                    first: {value: first, color: "#000000"}
                                    , remark: {value: "", color: "#000000"}
                                    , keyword1: {value: description, color: "#000000"}
                                    , keyword2: {value: replyContent, color: "#000000"}
                                    , keyword3: {value: senderName, color: "#000000"}
                                }
                            }, function (err, res) {
                                err ? log.error(err) : log.info(res);
                            });
                        let replyContent = message.content;
                        switch (Number.parseInt(message.content_type)) {
                            case CONTENT_TYPES.Image:
                                replyContent = "[图片]";
                                break;
                            case CONTENT_TYPES.Audio:
                                replyContent = "[语音]";
                                break;
                            default:
                                break;
                        }
                    }else {//自己发起的议题
                        // 发送模板消息
                        if(patient.openid){
                            WechatSDK.sendTemplateMessage({
                                touser: patient.openid,
                                name: targetUserName,
                                patient: targetUserId,
                                template_id: config.wechatConfig.template.consultTemplate,
                                url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+
                                "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code,
                                data: {
                                    first: {value: "您的"+consultTitle+"咨询有新的回复", color: "#000000"}
                                    , remark: {value: "", color: "#000000"}
                                    , keyword1: {value: description, color: "#000000"}
                                    , keyword2: {value: replyContent, color: "#000000"}
                                    , keyword3: {value: senderName, color: "#000000"}
                                }
                            }, function (err, res) {
                                err ? log.error(err) : log.info(res);
                            });
                        }
                        if(map.size>0){
                            for(var key of map.keys()){
                                if(!patient.openid||key!=patient.openid){
                                    var member = map.get(key);
                                    var openid = key;
                                    var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复";
                                    // 发送模板消息
                                    WechatSDK.sendTemplateMessage({
                                        touser: openid,
                                        name: member.name,
                                        patient: member.code,
                                        template_id: config.wechatConfig.template.consultTemplate,
                                        url: url + "?openid=" + openid +"&type="+topic.type+"&doctor="+message.sender_id+
                                        "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code,
                                        data: {
                                            first: {value: first, color: "#000000"}
                                            , remark: {value: "", color: "#000000"}
                                            , keyword1: {value: description, color: "#000000"}
                                            , keyword2: {value: replyContent, color: "#000000"}
                                            , keyword3: {value: senderName, color: "#000000"}
                                        }
                                    }, function (err, res) {
                                        err ? log.error(err) : log.info(res);
                                    });
                                }
                        let url = config.wechatConfig.baseUrl + res.url;
                        WechatSDK.sendTemplateMessage({
                            touser: openid,
                            name: targetUserName,
                            patient: targetUserId,
                            template_id: config.wechatConfig.template.consultTemplate,
                            url: url + "?openid=" + openid +"&type="+topic.type+"&doctor="+message.sender_id+
                            "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code,
                            data: {
                                first: {value: res.first, color: "#000000"}
                                , remark: {value: res.remark, 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);
                    });
                    callback(null, null);
                }
            ],
            function (err, res) {

+ 131 - 131
src/server/models/redis/pubSub.js

@ -1,131 +1,131 @@
/*
 * redis发布订阅
 *example:
 * let channel="ryan";
 redis.pubSub.registerHandlers("ryan",msg=> console.log(msg));
 redis.pubSub.subscribe(channel);
 redis.pubSub.publish(channel,"hello from chen");
 */
"use strict";
let configFile = require('../../include/commons').CONFIG_FILE;
let config = require('../../resources/config/' + configFile);
let RedisModel = require('./../redis.model');
let RedisSubClient = require('./redisSubClient');
let RedisPubClient = require('./redisPubClient');
let RedisClient = require('../../repository/redis/redis.client.js');
let redisPubConn = RedisPubClient.redisClient().connection;
let redisSubConn = RedisSubClient.redisClient().connection;
let redis = RedisClient.redisClient().connection;
let Sessions = require('../../models/sessions/sessions');
let WechatClient = require("../client/wechat.client.js");
let WlyySDK = require("../../util/wlyy.sdk");
let AppClient = require("../client/app.client.js");
let Participants = require('../sessions/participants');
let Messages = require('../messages/messages');
const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
let ObjectUtil = require("../../util/object.util.js");
let logger = require('../../util/log.js');
let SessionRepo = require('../../repository/mysql/session.repo');
let ParticipantRepo = require('../../repository/mysql/participant.repo');
const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
const SESSION_BUSINESS_TYPE = require('../../include/commons').SESSION_BUSINESS_TYPE;
class PubSub{
    constructor(){
        this.sub=redisSubConn;
        this.handlers=new Map();
        this.subAction=(channle,message)=>{
            let actions= this.handlers.get(channle)||new Set();
            for(let action of actions)
            {
                console.log("接收消息:"+message);
                message = JSON.parse(message);
                if(config.pubSubSwitch){//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
                    //Sessions.getRedisPushNotification(message);这里不知为什么无法调用这个方法,提示getRedisPushNotification不是方法
                    if (message.targetType=='patient') {
                        if(config.environment!='local'){//pc版接收要发给居民的消息不做处理
                            WechatClient.sendMessage(message.targetUserId, message.targetUserName, message);
                        }
                    } else {
                        if(message.sessionType=="1"){
                            WechatClient.sendReadDoctorByDoctorId(message.targetUserId, message);
                        }
                        //告知医生新消息
                        WechatClient.sendSocketMessageToDoctor(message.targetUserId,message);
                        if(config.environment!='local'){//pc版不推送个推
                            WlyySDK.request(message.targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
                                let count = 0;
                                res =  JSON.parse(res)
                                if (res.status == 200) {
                                    let data = res.data;
                                    count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
                                }
                                AppClient.sendNotification(message.targetUserId, message,message.sessionType,count);
                            });
                        }
                        //外网pcim通过socket推送
                        WechatClient.sendPcImSocket(message.targetUserId,message,message.sessionType);
                    }
                }
                //action(message);
            }
        }
        this.alredyPublishs=[];
        this.subConnected=false;
    }
    publish(channel,message)
    {
        let action=()=>{
            let pub=redisPubConn;
            pub.publish(channel,message);
            console.log("发布消息:channel:"+channel+",message:"+message);
        };
        if(this.subConnected===false)
        {
            this.alredyPublishs.push(action);
        }
        else{
            action();
        }
    }
    registerHandlers(channel,action)
    {
        var actions=this.handlers.get(channel)||new Set();
        actions.add(action);
        this.handlers.set(channel,actions);
    }
    subscribe(channel)
    {
        let self=this;
        this.sub.subscribe(channel,function (err,reply) {
            if(err){
                log.error(err);
            }
            self.subConnected=true;
            for(let publish of self.alredyPublishs){
                publish();
            }
            console.log("订阅成功:"+reply);
        });
        this.sub.on("message", function (channel, message) {
            self.subAction(channel,message);
        });
    }
    tearDown()
    {
        this.sub.quit();
    }
}
// Expose class
module.exports = new PubSub();
// /*
//  * redis发布订阅
//  *example:
//  * let channel="ryan";
//  redis.pubSub.registerHandlers("ryan",msg=> console.log(msg));
//  redis.pubSub.subscribe(channel);
//
//  redis.pubSub.publish(channel,"hello from chen");
//  */
// "use strict";
//
// let configFile = require('../../include/commons').CONFIG_FILE;
// let config = require('../../resources/config/' + configFile);
//
// let RedisModel = require('./../redis.model');
// let RedisSubClient = require('./redisSubClient');
// let RedisPubClient = require('./redisPubClient');
// let RedisClient = require('../../repository/redis/redis.client.js');
// // let redisPubConn = RedisPubClient.redisClient().connection;
// // let redisSubConn = RedisSubClient.redisClient().connection;
// let redis = RedisClient.redisClient().connection;
// let Sessions = require('../../models/sessions/sessions');
// let WechatClient = require("../client/wechat.client.js");
// let WlyySDK = require("../../util/wlyy.sdk");
// let AppClient = require("../client/app.client.js");
// let Participants = require('../sessions/participants');
// let Messages = require('../messages/messages');
// const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
// let ObjectUtil = require("../../util/object.util.js");
// let logger = require('../../util/log.js');
// let SessionRepo = require('../../repository/mysql/session.repo');
// let ParticipantRepo = require('../../repository/mysql/participant.repo');
//
// const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
// const SESSION_BUSINESS_TYPE = require('../../include/commons').SESSION_BUSINESS_TYPE;
//
// class PubSub{
//     constructor(){
//         this.sub=redisSubConn;
//         this.handlers=new Map();
//
//         this.subAction=(channle,message)=>{
//             let actions= this.handlers.get(channle)||new Set();
//             for(let action of actions)
//             {
//                 console.log("接收消息:"+message);
//                 message = JSON.parse(message);
//
//                 // if(config.pubSubSwitch){//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
//                 //     //Sessions.getRedisPushNotification(message);这里不知为什么无法调用这个方法,提示getRedisPushNotification不是方法
//                 //     if (message.targetType=='patient') {
//                 //         if(config.environment!='local'){//pc版接收要发给居民的消息不做处理
//                 //             WechatClient.sendMessage(message.targetUserId, message.targetUserName, message);
//                 //         }
//                 //     } else {
//                 //         if(message.sessionType=="1"){
//                 //             WechatClient.sendReadDoctorByDoctorId(message.targetUserId, message);
//                 //         }
//                 //         //告知医生新消息
//                 //         WechatClient.sendSocketMessageToDoctor(message.targetUserId,message);
//                 //         if(config.environment!='local'){//pc版不推送个推
//                 //             WlyySDK.request(message.targetUserId, '', '', '', '/im/common/message/messages', 'POST', function (err, res) {
//                 //                 let count = 0;
//                 //                 res =  JSON.parse(res)
//                 //                 if (res.status == 200) {
//                 //                     let data = res.data;
//                 //                     count = parseInt(JSON.parse(data.imMsgCount).count) + parseInt(data.system.amount) + parseInt(data.healthIndex.amount) + parseInt(data.sign.amount);
//                 //                 }
//                 //
//                 //                 AppClient.sendNotification(message.targetUserId, message,message.sessionType,count);
//                 //             });
//                 //         }
//                 //         //外网pcim通过socket推送
//                 //         WechatClient.sendPcImSocket(message.targetUserId,message,message.sessionType);
//                 //     }
//                 // }
//                 //action(message);
//             }
//         }
//         this.alredyPublishs=[];
//         this.subConnected=false;
//     }
//
//     publish(channel,message)
//     {
//         let action=()=>{
//             let pub=redisPubConn;
//             pub.publish(channel,message);
//             console.log("发布消息:channel:"+channel+",message:"+message);
//         };
//         if(this.subConnected===false)
//         {
//             this.alredyPublishs.push(action);
//         }
//         else{
//             action();
//         }
//     }
//     registerHandlers(channel,action)
//     {
//         var actions=this.handlers.get(channel)||new Set();
//         actions.add(action);
//         this.handlers.set(channel,actions);
//     }
//     subscribe(channel)
//     {
//         let self=this;
//         this.sub.subscribe(channel,function (err,reply) {
//             if(err){
//                 log.error(err);
//             }
//             self.subConnected=true;
//             for(let publish of self.alredyPublishs){
//                 publish();
//             }
//             console.log("订阅成功:"+reply);
//         });
//
//         this.sub.on("message", function (channel, message) {
//             self.subAction(channel,message);
//         });
//     }
//
//     tearDown()
//     {
//         this.sub.quit();
//     }
// }
//
// // Expose class
// module.exports = new PubSub();

+ 70 - 70
src/server/models/redis/redisPubClient.js

@ -1,70 +1,70 @@
/**
 * Redis客户端封装。
 * Redis客户端封装发布订阅(redis只要使用了发布订阅,这个client不能做其他操作)
 *
 * 注意Redis使用Promises保证调用流程。
 *
 * https://github.com/NodeRedis/node_redis
 *
 * author: linzhuo
 * since: 2016/12/09
 */
"use strict";
let redis = require('redis');
let configFile = require('../../include/commons').CONFIG_FILE;
let config = require('../../resources/config/' + configFile);
let log = require("../../util/log.js");
let redisPubClient = null;
class RedisPubClient {
    constructor() {
        var redisConfig = config.innerRedisConfig;
            redisConfig.retry_strategy = function(options){
                log.info("pub Redis重新连接次数:"+options.times_connected);
                if (options.error.code === 'ECONNREFUSED') {
                    log.error('pub Redis连接被拒绝');
                }
                if (options.times_connected > 10) {
                    log.error('pub Redis重试连接超过十次');
                }
                return Math.max(options.attempt * 100, 3000);
            }
        this._connection = redis.createClient(
            config.innerRedisConfig
        );
        this._connection.auth(config.innerRedisConfig.password||"",function(){
            console.log('pub Redis通过认证');
        });
        this._connection.on('connect', function (res) {
            log.info('pub Redis is connected.');
        });
        this._connection.on('error', function (res) {
            log.error("pub Redis connect failed.");
        })
    }
    get connection() {
        return this._connection;
    }
    static redisClient() {
        if (redisPubClient == null) {
            redisPubClient = new RedisPubClient();
        }
        return redisPubClient;
    }
}
function uncaughtExceptionHandler(err){
    if(err && err.code == 'ECONNREFUSED'){
        //do someting
    }else{
        log.error(err+"exit in pub Redis");
    }
}
process.on('uncaughtException', uncaughtExceptionHandler);
module.exports = RedisPubClient;
// /**
//  * Redis客户端封装。
//  * Redis客户端封装发布订阅(redis只要使用了发布订阅,这个client不能做其他操作)
//  *
//  * 注意Redis使用Promises保证调用流程。
//  *
//  * https://github.com/NodeRedis/node_redis
//  *
//  * author: linzhuo
//  * since: 2016/12/09
//  */
// "use strict";
// let redis = require('redis');
// let configFile = require('../../include/commons').CONFIG_FILE;
// let config = require('../../resources/config/' + configFile);
// let log = require("../../util/log.js");
//
// let redisPubClient = null;
//
// class RedisPubClient {
//     constructor() {
//         var redisConfig = config.innerRedisConfig;
//             redisConfig.retry_strategy = function(options){
//                 log.info("pub Redis重新连接次数:"+options.times_connected);
//                 if (options.error.code === 'ECONNREFUSED') {
//                     log.error('pub Redis连接被拒绝');
//                 }
//                 if (options.times_connected > 10) {
//                     log.error('pub Redis重试连接超过十次');
//                 }
//                 return Math.max(options.attempt * 100, 3000);
//             }
//         this._connection = redis.createClient(
//             config.innerRedisConfig
//         );
//         this._connection.auth(config.innerRedisConfig.password||"",function(){
//             console.log('pub Redis通过认证');
//         });
//
//         this._connection.on('connect', function (res) {
//             log.info('pub Redis is connected.');
//         });
//
//         this._connection.on('error', function (res) {
//             log.error("pub Redis connect failed.");
//         })
//     }
//
//     get connection() {
//         return this._connection;
//     }
//
//     static redisClient() {
//         if (redisPubClient == null) {
//             redisPubClient = new RedisPubClient();
//         }
//         return redisPubClient;
//     }
// }
//
// function uncaughtExceptionHandler(err){
//     if(err && err.code == 'ECONNREFUSED'){
//         //do someting
//     }else{
//         log.error(err+"exit in pub Redis");
//     }
// }
// process.on('uncaughtException', uncaughtExceptionHandler);
//
// module.exports = RedisPubClient;

+ 70 - 70
src/server/models/redis/redisSubClient.js

@ -1,70 +1,70 @@
/**
 * Redis客户端封装。
 * Redis客户端封装发布订阅(redis只要使用了发布订阅,这个client不能做其他操作)
 *
 * 注意Redis使用Promises保证调用流程。
 *
 * https://github.com/NodeRedis/node_redis
 *
 * author: linzhuo
 * since: 2016/12/09
 */
"use strict";
let redis = require('redis');
let configFile = require('../../include/commons').CONFIG_FILE;
let config = require('../../resources/config/' + configFile);
let log = require("../../util/log.js");
let redisSubClient = null;
class RedisSubClient {
    constructor() {
        var redisConfig = config.innerRedisConfig;
            redisConfig.retry_strategy = function(options){
                log.info("sub Redis重新连接次数:"+options.times_connected);
                if (options.error.code === 'ECONNREFUSED') {
                    log.error('sub Redis连接被拒绝');
                }
                if (options.times_connected > 10) {
                    log.error('sub Redis重试连接超过十次');
                }
                return Math.max(options.attempt * 100, 3000);
            }
        this._connection = redis.createClient(
            config.innerRedisConfig
        );
        this._connection.auth(config.innerRedisConfig.password||"",function(){
            console.log('sub Redis通过认证');
        });
        this._connection.on('connect', function (res) {
            log.info('sub Redis is connected.');
        });
        this._connection.on('error', function (res) {
            log.error("sub Redis connect failed.");
        })
    }
    get connection() {
        return this._connection;
    }
    static redisClient() {
        if (redisSubClient == null) {
            redisSubClient = new RedisSubClient();
        }
        return redisSubClient;
    }
}
function uncaughtExceptionHandler(err){
    if(err && err.code == 'ECONNREFUSED'){
        //do someting
    }else{
        log.error(err+"exit in sub Redis");
    }
}
process.on('uncaughtException', uncaughtExceptionHandler);
module.exports = RedisSubClient;
// /**
//  * Redis客户端封装。
//  * Redis客户端封装发布订阅(redis只要使用了发布订阅,这个client不能做其他操作)
//  *
//  * 注意Redis使用Promises保证调用流程。
//  *
//  * https://github.com/NodeRedis/node_redis
//  *
//  * author: linzhuo
//  * since: 2016/12/09
//  */
// "use strict";
// let redis = require('redis');
// let configFile = require('../../include/commons').CONFIG_FILE;
// let config = require('../../resources/config/' + configFile);
// let log = require("../../util/log.js");
//
// let redisSubClient = null;
//
// class RedisSubClient {
//     constructor() {
//         var redisConfig = config.innerRedisConfig;
//             redisConfig.retry_strategy = function(options){
//                 log.info("sub Redis重新连接次数:"+options.times_connected);
//                 if (options.error.code === 'ECONNREFUSED') {
//                     log.error('sub Redis连接被拒绝');
//                 }
//                 if (options.times_connected > 10) {
//                     log.error('sub Redis重试连接超过十次');
//                 }
//                 return Math.max(options.attempt * 100, 3000);
//             }
//         this._connection = redis.createClient(
//             config.innerRedisConfig
//         );
//         this._connection.auth(config.innerRedisConfig.password||"",function(){
//             console.log('sub Redis通过认证');
//         });
//
//         this._connection.on('connect', function (res) {
//             log.info('sub Redis is connected.');
//         });
//
//         this._connection.on('error', function (res) {
//             log.error("sub Redis connect failed.");
//         })
//     }
//
//     get connection() {
//         return this._connection;
//     }
//
//     static redisClient() {
//         if (redisSubClient == null) {
//             redisSubClient = new RedisSubClient();
//         }
//         return redisSubClient;
//     }
// }
//
// function uncaughtExceptionHandler(err){
//     if(err && err.code == 'ECONNREFUSED'){
//         //do someting
//     }else{
//         log.error(err+"exit in sub Redis");
//     }
// }
// process.on('uncaughtException', uncaughtExceptionHandler);
//
// module.exports = RedisSubClient;

+ 4 - 4
src/server/models/sessions/sessions.js

@ -1634,7 +1634,7 @@ class Sessions extends RedisModel {
                        AppClient.sendNotification(targetUserId, message,sessionType,count);
                    }
                    //外网pcim通过socket推送
                    WechatClient.sendPcImSocket(targetUserId,message,sessionType);
                    // WechatClient.sendPcImSocket(targetUserId,message,sessionType);
                });
                message.targetUserId = targetUserId;
@ -1643,9 +1643,9 @@ class Sessions extends RedisModel {
                message.targetType = 'doctor';
            }
            //redis发布消息
            if(config.pubSubSwitch) {//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
                pubSub.publish(config.pubChannel,JSON.stringify(message));
            }
            // if(config.pubSubSwitch) {//接收订阅消息处理开关,本地运行和测试库单独运行时防止用户接收消息2次
            //     pubSub.publish(config.pubChannel,JSON.stringify(message));
            // }
        });
    }

+ 8 - 6
src/server/models/user/users.js

@ -130,12 +130,14 @@ class Users extends RedisModel {
                            'device_token', deviceToken,
                            'last_login_time', lastLoginTime.getTime(),
                            'platform', platform);
                    } else if(loginFromPc){
                        // cache pc status
                        multi = multi.hmset(userStatusKey,
                            'last_login_time', lastLoginTime.getTime(),
                            'platform', platform);
                    }else {
                    }
                    // else if(loginFromPc){
                    //     // cache pc status
                    //     multi = multi.hmset(userStatusKey,
                    //         'last_login_time', lastLoginTime.getTime(),
                    //         'platform', platform);
                    // }
                    else {
                        // cache wechat status
                        multi = multi.hmset(userStatusKey,
                            'last_login_time', lastLoginTime.getTime(),

+ 18 - 3
src/server/repository/mysql/wechat.token.repo.js

@ -8,6 +8,9 @@
let log = require('../../util/log');
let ImDb = require('../mysql/db/im.db');
const DB_TABLES = require('../../include/commons').DB_TABLES;
let configFile = require('../include/commons').CONFIG_FILE;
let config = require('../resources/config/' + configFile);
class WeChatTokenRepo {
    constructor() {
@ -20,7 +23,19 @@ class WeChatTokenRepo {
     */
    static findOne(handler) {
        ImDb.execQuery({
            "sql": "select access_token, expires_in, add_timestamp from wlyy.wx_access_token where acc_id = 'gh_ffd64560fb21' order by add_timestamp desc limit 0, 1"
            "sql": "select access_token, expires_in, add_timestamp from "+DB_TABLES.WxAccessToken+" where acc_id = '"+config.wechatConfig.accId+"' order by add_timestamp desc limit 0, 1"
            , "handler": handler
        });
    };
    /**
     * 获取微信模板
     *
     * @param handler 回调函数
     */
    static findWxTemplateOne(handler) {
        ImDb.execQuery({
            "sql": "SELECT scene_description,`first`,url,remark from "+DB_TABLES.WeixinTemplateConfig+" WHERE `status` = 1 and template_name = 'template_consult_notice' and scene ='zxhf' limit 0, 1"
            , "handler": handler
        });
    };
@ -35,7 +50,7 @@ class WeChatTokenRepo {
     */
    static save(accessToken, expireIn, createTime, handler) {
        ImDb.execQuery({
            "sql": "insert into wlyy.wx_access_token (acc_id,access_token, expires_in, add_timestamp) values ('gh_ffd64560fb21',?,?,?)"
            "sql": "insert into "+DB_TABLES.WxAccessToken+" (acc_id,access_token, expires_in, add_timestamp) values ('"+config.wechatConfig.accId+"',?,?,?)"
            , "args": [accessToken, expireIn, createTime.getTime()]
            , "handler": handler
        });
@ -53,7 +68,7 @@ class WeChatTokenRepo {
     */
    static saveLog(openid,patient,name,request,response,status,createTime,handler){
        ImDb.execQuery({
            "sql": "insert into wlyy.wlyy_wx_push_log (type,openid, patient,name,request,response,status, create_time) values (3,?,?,?,?,?,?,?)"
            "sql": "insert into "+DB_TABLES.WlyyWxPushLog+" (type,openid, patient,name,request,response,status, create_time) values (3,?,?,?,?,?,?,?)"
            , "args": [openid,patient,name,request,response,status, createTime]
            , "handler": handler
        });

+ 13 - 30
src/server/resources/config/config.dev.js

@ -2,10 +2,10 @@
// IM数据库配置
let imDbConfig = {
    host: '172.19.103.85',
    user: 'linzhou',
    password: 'linzhou',
    database: 'im_new',
    host: '172.19.103.77',
    user: 'root',
    password: '123456',
    database: 'im_sr',
    connectionLimit: '50',
    charset: 'utf8mb4'
};
@ -22,13 +22,13 @@ let imDbConfig = {
let redisConfig = {
    host: '172.19.103.88',
    port: 6379,
    db: 1
    db: 2
};
// 内网Redis
let innerRedisConfig = {
    host: '172.19.103.88',
    port: 6379,
    db: 1
    db: 2
};
// 三师后台
@ -39,7 +39,7 @@ let innerRedisConfig = {
// };
let wlyyServerConfig = {
    host: '192.168.131.24',
    port: 8080,
    port: 8082,
    model:"/"
};
@ -53,34 +53,17 @@ let wlyyDAServerConfig = {
// 个推AppStore版参数
let getTuiConfig = {
    HOST: 'https://api.getui.com/apiex.htm',
    APPID: 'qWmRh2X88l7HuE36z3qBe8',
    APPKEY: 'EzERfV8c849lBkZqHWzQG1',
    MASTERSECRET: 'veXiajQrId6iojy7Qv8kZ2'
    APPID: 'NamoCLe9no9pIihdoZ930A',
    APPKEY: 'db7PZsd7TX6JAsLKmWuAT8',
    MASTERSECRET: '5IFJjgxRiI7QpuArMMT3E5'
};
// let getTuiConfig = {
//     HOST: 'https://api.getui.com/apiex.htm',
//     APPID: 'DKgbGvbacm74nJJzen5ilA',
//     APPSECRET: '4kGcL7e7kU6mbSqfEGZFW7',
//     APPKEY: 'ArZfS2qvoA7N3hawOAGVC5',
//     MASTERSECRET: '9lpy5vEss46tVzP1RCJiC4'
// };
// 微信配置
// let wechatConfig = {
//     appId: 'wxd03f859efdf0873d',
//     appSecret: '2935b54b53a957d9516c920a544f2537',
//     token: '27eb3bb24f149a7760cf1bb154b08040',
//     baseUrl: 'weixin.xmtyw.cn/wlyy',
//     template: {
//         consultTemplate: 'qSOW0DBxO3qEBm4ucG0Ial0jxsOyD7_f2TFK5e-mQEc'  // 咨询回复模板
//     }
// };
// 微信配置
let wechatConfig = {
    appId: 'wx1f129f7b51701428',
    appSecret: '988f005d8309ed1795939e0f042431fb',
    appId: 'wxd03f859efdf0873d',
    appSecret: '2935b54b53a957d9516c920a544f2537',
    token: '27eb3bb24f149a7760cf1bb154b08040',
    accId: 'gh_ffd64560fb21',
    baseUrl: 'ehr.yihu.com/wlyy',
    template: {
        consultTemplate: '-dr4QNyFoRvVsf8uWxXMC1dRyjwnbUuJwJ21vBLhf18'  // 咨询回复模板

+ 1 - 0
src/server/resources/config/config.local.js

@ -51,6 +51,7 @@ let wechatConfig = {
    appId: 'wxad04e9c4c5255acf',
    appSecret: 'ae77c48ccf1af5d07069f5153d1ac8d3',
    token: '27eb3bb24f149a7760cf1bb154b08040',
    accId: 'gh_ffd64560fb21',
    baseUrl: 'www.xmtyw.cn/wlyy',
    template: {
        consultTemplate: '0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc'  // 咨询回复模板

+ 4 - 3
src/server/resources/config/config.prod.js

@ -55,12 +55,13 @@ let getTuiConfig = {
// 微信配置
let wechatConfig = {
    appId: 'wxad04e9c4c5255acf',
    appSecret: 'ae77c48ccf1af5d07069f5153d1ac8d3',
    appId: 'wxe627ffaee2d05a40',
    appSecret: '7c29f6b28be7e54b742883a47ff39767',
    token: '27eb3bb24f149a7760cf1bb154b08040',
    accId: 'gh_ffd64560fb21',
    baseUrl: 'www.xmtyw.cn/wlyy',
    template: {
        consultTemplate: '0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc'  // 咨询回复模板
        consultTemplate: '-dr4QNyFoRvVsf8uWxXMC1dRyjwnbUuJwJ21vBLhf18'  // 咨询回复模板
    }
};

+ 1 - 0
src/server/resources/config/config.test.js

@ -53,6 +53,7 @@ let wechatConfig = {
    appId: 'wx1f129f7b51701428',
    appSecret: '988f005d8309ed1795939e0f042431fb',
    token: '27eb3bb24f149a7760cf1bb154b08040',
    accId: 'gh_ffd64560fb21',
    baseUrl: 'ehr.yihu.com/wlyy',
    template: {
        consultTemplate: '-dr4QNyFoRvVsf8uWxXMC1dRyjwnbUuJwJ21vBLhf18'  // 咨询回复模板