فهرست منبع

合并 代码

Sand 8 سال پیش
والد
کامیت
d5da9ecf43

+ 1 - 1
src/server/endpoints/url.initializer.js

@ -53,7 +53,7 @@ class UrlInitializer {
        app.use(APIv2.Management.Base, management);
        app.use(APIv2.Users.Base, users);
        app.use(APIv2.Sessions.Base, sessions);
        app.use(APIv2.Sessions.Topics, topics);
        app.use(APIv2.Sessions.Base, topics);
    }
    static initWebPages(app) {

+ 11 - 10
src/server/endpoints/v2/session.endpoint.js

@ -197,26 +197,27 @@ router.post(APIv2.Sessions.Messages, function (req, res) {
 *  /sessions/:session_id/messages?session_id=blabla&user_id=abc&start_message_id=100&end_message_id=20
 */
router.get(APIv2.Sessions.Messages, function (req, res) {
    let start_msg_id = req.query.start_msg_id;
    let end_msg_id = req.query.end_msg_id;
    let pagesize = req.query.pagesize;
    let page = req.query.page;
    let size = req.query.size;
    let user = req.query.user;
    let sessionId = req.query.sessionId;
    if (!page) {
        throw {httpStatus: 406, message: 'Missing page.'};
    }
    if (!size) {
        throw {httpStatus: 406, message: 'Missing size.'};
    }
    let sessionId = req.query.session_id;
    if (!user) {
        throw {httpStatus: 406, message: 'Missing user.'};
    }
    if (!sessionId) {
        throw {httpStatus: 406, message: 'Missing sessionId.'};
    }
    if(!pagesize){
        pagesize = 20;
    }
    if(!page){
        page = 1;
    }
    let sessions = new Sessions();
    ControllerUtil.regModelEventHandler(sessions, res);
    sessions.getMessages(sessionId, user, page, size);
    sessions.getMessages(sessionId, user, start_msg_id,end_msg_id,page,pagesize);
});
router.get(APIv2.Sessions.SessionUnreadMessages, function (req, res) {

+ 19 - 13
src/server/endpoints/v2/topic.endpoint.js

@ -9,7 +9,7 @@
let express = require('express');
let router = express.Router();
let log = require('../../util/log.js');
let ObjectUtil = require("../../util/object.util.js");
let ControllerUtil = require('../../util/controller.util');
let Topics = require('../../models/sessions/topics');
@ -26,28 +26,34 @@ router.get(APIv2.Sessions.Topics, function (req, res) {
});
router.post(APIv2.Sessions.Topics, function (req, res) {
    let data = req.body;
    //    data.topicName ="topicstest1";
    //    data.topicId ="12132312";
    //    data.healthDoctor ="1";
    //    data.doctor ="2";
    //    data.message ={description:"咨询:猥琐大叔大",title:"测试咨询",img:"img/sada.jpg",patient:"topicpatient",patientName:"甘宁"};
    //let testing = ObjectUtil.fieldsCheck(data.message, "description", "title", "img", "patient","patientName");
    //if (!testing.description) {
    /**
     * //    data.topicName ="topicstest1";
     //    data.topicId ="12132312";
     //    data.healthDoctor ="1";
     //    data.doctor ="2";
     //    data.message ={description:"咨询:猥琐大叔大",title:"测试咨询",img:"img/sada.jpg",patient:"topicpatient",patientName:"甘宁"};
     //let testing = ObjectUtil.fieldsCheck(data.message, "description", "title", "img", "patient","patientName");
     //if (!testing.description) {
    //    throw {httpStatus: 406, message: "miss message.description"};
    //}
    //if (!testing.title) {
     //if (!testing.title) {
    //    throw {httpStatus: 406, message:"miss message.title"};
    //}
    //if (!testing.patient) {
     //if (!testing.patient) {
    //    throw {httpStatus: 406, message:"miss message.patient"};
    //}
    //if (!testing.patientName) {
     //if (!testing.patientName) {
    //    throw {httpStatus: 406, message:"miss message.patientName"};
    //}
     */
    let payload = req.body;
    let testing = ObjectUtil.fieldsCheck(payload, "topicId", "topicName", "participants", "messages", "sessionId");
    if (!testing.pass) {
        throw {httpStatus: 406, message: testing.message}
    }
    let topic = new Topics();
    ControllerUtil.regModelEventHandler(topic, res);
    topic.createTopics(data.topicName, data.topicId, data.message.patient, data.healthDoctor, data.doctor, data.message);
    topic.createTopics(payload.topicName, payload.topicId,payload.sessionId,JSON.parse(payload.participants), JSON.parse(payload.messages));
});
router.get(APIv2.Sessions.TopicEnded, function (req, res) {

+ 1 - 1
src/server/models/messages/messages.js

@ -101,7 +101,7 @@ class Messages extends RedisModel {
     */
    static updateLastContent(sessionKey, sessionType, name, message) {
        redis.hmsetAsync(sessionKey,
            "create_date", message.timestamp,
            "create_date", message.timestamp.getTime(),
            "last_content", message.content,
            "last_content_type", message.content_type,
            "sender_id", message.sender_id,

+ 102 - 42
src/server/models/sessions/sessions.js

@ -243,58 +243,118 @@ class Sessions extends RedisModel {
     * @param page 第几页
     * @param pagesize 分页数量
     */
    getMessages(sessionId, userId, page, pagesize) {
    getMessages(sessionId, user, start_msg_id, end_msg_id, page, pagesize) {
        let self = this;
        let message_timestamp_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
        let message_key = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
        let participants_key = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
        //超过最大限制后从mysql获取数据
        if (page * pagesize >= config.sessionConfig.maxMessageCount) {
            self.getMessageFromMySQL(sessionId, page, pagesize, function (err, res) {
                if (!err) {
                    ModelUtil.emitOK(self.eventEmitter, {"status": 200, "data": res});
                } else {
                    ModelUtil.emitOK(self.eventEmitter, {"status": -1, "data": err});
                }
        if (!start_msg_id && !end_msg_id) {
            redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
                start_msg_id = res[0];
                redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
                    end_msg_id = res[0];
                    self.getMessagesByPage(sessionId, user, start_msg_id, end_msg_id, page, pagesize, function (err, res) {
                        if (err) {
                            logger.error("getMessagesByPage error" + err);
                            ModelUtil.emitError(self.eventEmitter,err,err);
                        } else {
                            ModelUtil.emitOK(self.eventEmitter, res);
                        }
                    })
                })
            })
        } else if (!start_msg_id) {
            redis.zrevrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
                start_msg_id = res[0];
                self.getMessagesByPage(sessionId, user, startMsgId, endMsgId, page, pagesize, function (err, res) {
                    if (err) {
                        logger.error("getMessagesByPage error" + err);
                        ModelUtil.emitError(self.eventEmitter,err,err);
                    } else {
                        ModelUtil.emitOK(self.eventEmitter, res);
                    }
                })
            })
        } else if (!end_msg_id) {
            redis.zrangeAsync(message_timestamp_key, 0, 0).then(function (res) {
                end_msg_id = res[0];
                self.getMessagesByPage(sessionId, user, start_msg_id, end_msg_id, page, pagesize, function (err, res) {
                    if (err) {
                        logger.error("getMessagesByPage error" + err);
                        ModelUtil.emitError(self.eventEmitter,err,err);
                    } else {
                        ModelUtil.emitOK(self.eventEmitter, res);
                    }
                })
            })
        } else {
            if (page > 0) {
                page = page * pagesize;
                pagesize = pagesize + page;
            }
            let participants = new Participants();
            participants.existsParticipant(sessionId, userId, function (res) {
                if (!res) {
                    ModelUtil.emitOK(self.eventEmitter, {"status": -1, "msg": "用户不在此会话中!"});
            self.getMessagesByPage(sessionId, user, start_msg_id, end_msg_id, page, pagesize, function (err, res) {
                if (err) {
                    logger.error("getMessagesByPage error" + err);
                    ModelUtil.emitError(self.eventEmitter,err,err);
                } else {
                    //倒序取出最后N条消息
                    redis.zrevrangeAsync(message_timestamp_key, page, pagesize).then(function (res) {
                        //取出消息实体
                        if (res.length == 0) {
                            ModelUtil.emitOK(self.eventEmitter, {"status": 200, "data": []});
                            return;
                        }
                        redis.hmgetAsync(message_key, res).then(function (messages) {
                            console.log(messages)
                            //将取到的消息返回给前端
                            ModelUtil.emitOK(self.eventEmitter, {"status": 200, "data": messages});
                        }).then(function () {
                            //更新患者最后一次获取消息的日期
                            redis.zaddAsync(participants_key, (new Date().getTime()), userId).then(function (res) {
                                console.log(res);
                            }).catch(function (res) {
                                throw res;
                            })
                        })
                    }).catch(function (res) {
                        ModelUtil.emitOK(self.eventEmitter, {message: res});
                    })
                    ModelUtil.emitOK(self.eventEmitter, res);
                }
            })
        }
    }
    /**
     * 分页获取会话消息。
     *
     * @param sessionId     必选。会话ID
     * @param user          必选。用户ID
     * @param startMsgId    必选。会话的的起始消息ID,作为检索的起始依据
     * @param endMsgId      必选。会话中的结束消息ID
     * @param offset        必选。页码
     * @param count         必选。页面大小
     * @param handler       必选。回调
     */
    getMessagesByPage(sessionId, user, startMsgId, endMsgId, page, size, handler) {
        let self = this;
        let message_timestamp_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
        let message_key = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
        let participants_key = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
        let participants = new Participants();
        let offset = (page - 1 < 0 ? 0 : page - 1) * size;
        let count = 20;
        participants.existsParticipant(sessionId, user, function (err,res) {
            if (!res) {
                handler("用户不在此会话中!", false);
            } else {
                //将消息ID转换成分值
                redis.zscoreAsync(message_timestamp_key, startMsgId).then(function (res) {
                    let startMsgScore = res;
                    redis.zscoreAsync(message_timestamp_key, endMsgId).then(function (res) {
                        let endMsgScore = res;
                        //倒序取出最后N条消息
                        redis.zrevrangebyscoreAsync(message_timestamp_key, startMsgScore, endMsgScore, "limit", offset, count).then(function (res) {
                            //取出消息实体
                            if (res.length == 0) {
                                handler(null, res);
                                return;
                            }
                            redis.hmgetAsync(message_key, res).then(function (messages) {
                                console.log(messages)
                                //将取到的消息返回给前端
                                handler(null, messages);
                            }).then(function () {
                                //更新患者最后一次获取消息的日期
                                redis.zaddAsync(participants_key, (new Date().getTime()), user).then(function (res) {
                                    console.log(res);
                                }).catch(function (res) {
                                    throw res;
                                })
                            })
                        }).catch(function (res) {
                            handler(res, false);
                        })
                    })
                })
            }
        })
    }
    /**
     * 获取所有会话的未读消息数。
     */

+ 31 - 30
src/server/models/sessions/topics.js

@ -17,6 +17,7 @@ let config = require('../../resources/config/' + configFile);
const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
const SESSION_USER_STATUS = require('../../include/commons').SESSION_USER_STATUS;
const SESSION_TYPES = require('../../include/commons').SESSION_TYPES;
class Topics extends RedisModel {
    constructor() {
@ -29,7 +30,7 @@ class Topics extends RedisModel {
     * @param page
     * @param size
     */
    getTopicMessages(topicId, page, size) {
    getTopicMessages(topicId) {
        let self = this;
        let topic_key = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        let _super = RedisModel.makeRedisKey;
@ -57,35 +58,35 @@ class Topics extends RedisModel {
     *
     * @param topicName 发起议题的名称
     * @param topicId
     * @param patient 发起议题的患者
     * @param healthDoctor
     * @param doctor 参与的医生
     * @param users 发起议题的患者{"userId1:role", "userId2:role"}
     * @param messages 发送的消息对象{description:"",title:"",img:"",patient:"",patientName:""}图片多个用逗号隔开
     */
    createTopics(topicName, topicId, patient, healthDoctor, doctor, messages) {
    createTopics(topicName, topicId,sessionId,users, messages) {
        let self = this;
        
        //MUC模式中sessionID就是患者ID
        let topics_key = RedisModel.makeRedisKey(REDIS_KEYS.Topics, patient);
        let topics_key = RedisModel.makeRedisKey(REDIS_KEYS.Topics, sessionId);
        let topic_key = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        let sessions = new Sessions();
        let participants = new Participants();
        
        //从数据库中获取sessionId
        let date = new Date();
        var pars=[];
        redis.zaddAsync(topics_key, date.getTime(), topicId).then(function (res) {
            redis.hmsetAsync(topic_key, "name", topicName, "end_by", "", "session_id", patient, "create_time", date.getTime(), "end_time", "", "description", messages.description).then(function (res) {
                sessions.getSessions(patient, function (err, res) {
            redis.hmsetAsync(topic_key, "name", topicName, "end_by", "", "session_id", sessionId, "create_time", date.getTime(), "end_time", "", "description", messages.description).then(function (res) {
                sessions.getSessions(sessionId, function (err, res) {
                    //已经存在对应的会话更新全科为旁听
                    if (res && res.length > 0) {
                        participants.updateUser(patient, doctor, SESSION_USER_STATUS.OTHER);
                        for(var j in users){
                           participants.updateUser(sessionId, j, users[j]);
                        }
                        callbegin();
                    } else {//不存在创建SESSION
                        var users = {};
                        users[patient] = SESSION_USER_STATUS.ONLINE;
                        users[healthDoctor] = SESSION_USER_STATUS.ONLINE;
                        users[doctor] = SESSION_USER_STATUS.OTHER;
                        sessions.createSession(patient, messages.patientName, config.sessionConfig.MUC, JSON.stringify(users), function (res) {
                        for(var j in users){
                            pars.push(j+":"+users[j]);
                        }
                        sessions.createSession(sessionId, messages.patientName, SESSION_TYPES.MUC, pars, function (res) {
                            if (res) {
                                callbegin();
                            }
@ -100,17 +101,17 @@ class Topics extends RedisModel {
         */
        function callbegin() {
            let msg = {};
            msg.senderId = messages.patient;
            msg.senderName = messages.patientName;
            msg.contentType = 6;
            msg.sender_id = messages.patient;
            msg.sender_name = messages.patientName;
            msg.content_type = 6;
            msg.content = "开始咨询"
            msg.timestamp = date;
            sessions.saveMessageByTopic(msg, patient, function (err, msgId) {
            sessions.saveMessageByTopic(msg, sessionId, function (err, msgId) {
                if (err) {
                    ModelUtil.emitOK(self.eventEmitter, err);
                } else {
                    self.saveTopicsToSql(topicName, topicId, patient, msgId, date);
                    callBeginMsg();
                    self.saveTopicsToSql(topicName, topicId, sessionId, msgId, date);
                    callBeginMsg(msgId);
                }
            })
        }
@ -118,14 +119,14 @@ class Topics extends RedisModel {
        /**
         * 发送求助内容
         */
        function callBeginMsg() {
        function callBeginMsg(startMsgId) {
            let msg = {};
            msg.senderId = messages.patient;
            msg.senderName = messages.patientName;
            msg.contentType = 1;
            msg.sender_id = messages.patient;
            msg.sender_name = messages.patientName;
            msg.content_type = 1;
            msg.content = messages.description;
            msg.timestamp = new Date();
            sessions.saveMessageByTopic(msg, patient, function (err, msgId) {
            sessions.saveMessageByTopic(msg,  sessionId, function (err, msgId) {
                log.info("begin send" + messages.description);
            });
            
@ -133,17 +134,17 @@ class Topics extends RedisModel {
                let imgs = messages.img.split(",");
                for (var j in imgs) {
                    let msgimg = {};
                    msgimg.senderId = messages.patient;
                    msgimg.senderName = messages.patientName;
                    msgimg.contentType = 2;
                    msgimg.sender_id = messages.patient;
                    msgimg.sender_name = messages.patientName;
                    msgimg.content_type = 2;
                    msgimg.content = imgs[j];
                    msgimg.timestamp = new Date();
                    sessions.saveMessageByTopic(msgimg, patient, function (err, msgId) {
                    sessions.saveMessageByTopic(msgimg, sessionId, function (err, msgId) {
                        log.info("begin send" + imgs[j]);
                    })
                }
            }
            ModelUtil.emitOK(self.eventEmitter, "创建成功!");
            ModelUtil.emitOK(self.eventEmitter, startMsgId);
        }
    }