Browse Source

merge code

Sand 8 năm trước cách đây
mục cha
commit
2b883fff2e

+ 22 - 16
src/client/im.client.js

@ -5,6 +5,7 @@
// Node.js模拟jQuery及ajax请求所需要的环境:document及XMLHttpRequest。
// 这些环境仅用于模拟,客户端在使用时候不需要真正引入
if (typeof process !== 'undefined') {
    module.exports = imClient;
    var jsdom = require('jsdom').jsdom;
    var document = jsdom('<html></html>', {});
    var window = document.defaultView;
@ -24,7 +25,7 @@ var LocalStorageKey = {
};
// 服务器
var APIPrefix = "http://127.0.0.1:3008/api/v2";
var imServer = "http://192.168.131.109:3008/api/v2";
// 资源实体在URL中的占位符
var UserPath = ":user_id";
@ -80,7 +81,7 @@ var httpClient = {
    get: function (endpoint, data, successCallback, errorCallback) {
        $.ajax({
            type: "get",
            url: APIPrefix + endpoint,
            url: imServer + endpoint,
            data: data,
            async: true,
            dataType: "json",
@ -88,14 +89,14 @@ var httpClient = {
                successCallback(data);
            },
            error: function (xhr, status, error) {
                errorCallback(xhr, status, error);
                errorCallback ? errorCallback(xhr, status, error) : "";
            }
        });
    },
    post: function (endpoint, data, successCallback, errorCallback) {
        $.ajax({
            type: "post",
            url: APIPrefix + endpoint,
            url: imServer + endpoint,
            data: data,
            async: true,
            dataType: "json",
@ -110,7 +111,7 @@ var httpClient = {
    put: function (endpoint, data, successCallback, errorCallback) {
        $.ajax({
            type: "post",
            url: APIPrefix + endpoint,
            url: imServer + endpoint,
            data: data,
            async: true,
            dataType: "json",
@ -128,7 +129,7 @@ var httpClient = {
    delete: function (endpoint, data, successCallback, errorCallback) {
        $.ajax({
            type: "get",
            url: APIPrefix + endpoint,
            url: imServer + endpoint,
            data: data,
            async: true,
            dataType: "json",
@ -165,6 +166,7 @@ var imClient = {
                failure);
        }
    },
    // TEST!PASS
    Management: {
        getDbStatus: function (success, failure) {
            httpClient.get(ENDPOINTS.Management.DbStatus,
@ -173,6 +175,7 @@ var imClient = {
                failure);
        }
    },
    // TEST!PASS
    Users: {
        // 登录
        login: function (userId, token, client_id, platform, success, failure) {
@ -277,17 +280,17 @@ var imClient = {
        },
        // 创建咨询
        createTopic: function (sessionId, topicId, success, failure) {
        createTopic: function (sessionId, userId, success, failure) {
            httpClient.post(ENDPOINTS.Sessions.Topics.replace(SessionPath, sessionId),
                {topic_id: topicId},
                {user_id: userId},
                success,
                failure);
        },
        // 结束咨询
        endTopic: function (sessionId, topicId, success, failure) {
        endTopic: function (sessionId, userId, success, failure) {
            httpClient.put(ENDPOINTS.Sessions.Topics.replace(SessionPath, sessionId),
                {topic_id: topicId},
                {user_id: userId},
                success,
                failure);
        },
@ -309,9 +312,16 @@ var imClient = {
        },
        // 按会话获取消息
        getMessagesBySession: function (sessionId, startMessageId, count, success, failure) {
        getMessagesBySession: function (sessionId, userId, page, pagesize, startMsgId, endMsgId, success, failure) {
            httpClient.get(ENDPOINTS.Sessions.Messages.replace(SessionPath, sessionId),
                {start_message_id: startMessageId, count: count},
                {
                    page: page || 1,
                    pagesize: pagesize || 20,
                    end_msg_id: endMsgId || "",
                    start_msg_id: startMsgId || "",
                    user: userId,
                    session_id: sessionId
                },
                success,
                failure);
        },
@ -382,7 +392,3 @@ var imClient = {
    },
    Search: {}
};
if (typeof process !== 'undefined') {
    module.exports = imClient;
}

+ 27 - 30
src/server/endpoints/v2/topic.endpoint.js

@ -9,6 +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');
@ -20,61 +21,57 @@ const APIv2 = require('../../include/endpoints').APIv2;
 */
router.get(APIv2.Sessions.Topics, function (req, res) {
    let topicId = req.query.topicId;
    let topic = new Topics();
    ControllerUtil.regModelEventHandler(topic, res);
    topic.getTopicMessages(topicId);
});
router.post(APIv2.Sessions.Topics, function (req, res) {
    /**
     * //    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) {
    //    throw {httpStatus: 406, message:"miss message.title"};
    //}
     //if (!testing.patient) {
    //    throw {httpStatus: 406, message:"miss message.patient"};
    //}
     //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(payload.topicName, payload.topicId,payload.sessionId,JSON.parse(payload.participants), JSON.parse(payload.messages));
    topic.createTopic(payload.topicName, payload.topicId, payload.sessionId, JSON.parse(payload.participants), JSON.parse(payload.messages));
});
router.put(APIv2.Sessions.Topics, function (req, res) {
    let data = req.body;
    let topicId = data.topic_id;
    let jsonValue = data.data;
    let payload = req.body;
    let topicId = payload.topic_id;
    let jsonValue = payload.data;
    let topic = new Topics();
    ControllerUtil.regModelEventHandler(topic, res);
    topic.updateTopic(topicId,jsonValue);
    topic.updateTopic(topicId, jsonValue);
});
router.get(APIv2.Sessions.TopicEnded, function (req, res) {
    let sessionId = req.session_id;
    let topicId = req.topic_id;
    let topic = new Topics();
    ControllerUtil.regModelEventHandler(topic, res);
    topic.isTopicEnded(sessionId, topicId, null);
});
router.post(APIv2.Sessions.TopicEnded, function (req, res) {
    let data = req.body;
    let endUser = data.end_user;
    let endUserName = data.end_user_name;
    let topicId = data.topic_id;
    let payload = req.body;
    let endUser = payload.end_user;
    let endUserName = payload.end_user_name;
    let topicId = payload.topic_id;
    let topic = new Topics();
    ControllerUtil.regModelEventHandler(topic, res);
    topic.endTopic(topicId, endUser, endUserName);
});
module.exports = router;

+ 1 - 1
src/server/include/commons.js

@ -40,7 +40,7 @@ exports.SESSION_TYPES = SESSION_TYPES;
const TOPIC_STATUS = {
    NEW: 0,             // 新建
    PROCEEDINGS: 1,     // 进行中
    FINISHED: 10        // 结束
    ENDED: 10        // 结束
};
exports.TOPIC_STATUS = TOPIC_STATUS;

+ 0 - 1
src/server/include/endpoints.js

@ -31,7 +31,6 @@ const APIv2 = {
        RecentSessions: '/recent',                                      // 最近会话,使用类型过滤出'患者'或'医生'会话
        Topics: '/:session_id/topics',
        Topic: '/:session_id/topics/:topic_id',
        Topic: '/:session_id/topics/:topic_id',                          // 议题,指定ID的议题将返回其信息
        TopicEnded: '/:session_id/topics/:topic_id/ended',              // 议题是否已结束,若top_id为current,则检查最后一个议题的状态

+ 101 - 63
src/server/models/sessions/topics.js

@ -27,26 +27,22 @@ class Topics extends RedisModel {
    /**
     * 根据topicId获取对应的消息
     * @param topicId
     * @param page
     * @param size
     */
    getTopicMessages(topicId) {
        let self = this;
        let topic_key = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        let _super = RedisModel.makeRedisKey;
        redis.hgetallAsync(topic_key).then(function (topic) {
            let message_time_key = _super(REDIS_KEYS.MessagesByTimestamp, topic.session_id);
            let message_key = _super(REDIS_KEYS.Messages, topic.session_id);
        let topicKey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        redis.hgetallAsync(topicKey).then(function (topic) {
            let message_time_key = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, topic.session_id);
            let message_key = RedisModel.makeRedisKey(REDIS_KEYS.Messages, topic.session_id);
            //倒序取出所有的消息ID
            let create_time = topic.create_time;
            let end_time = topic.end_time;
            if (!end_time) {
                end_time = new Date().getTime();
            let createTime = topic.create_time;
            let endTime = topic.end_time;
            if (!endTime) {
                endTime = new Date().getTime();
            }
            redis.zrevrangebyscoreAsync(message_time_key, end_time, create_time).then(function (messages) {
                //取出消息实例
            redis.zrevrangebyscoreAsync(message_time_key, endTime, createTime).then(function (messages) {
                redis.hmgetAsync(message_key, messages).then(function (res) {
                    ModelUtil.emitOK(self.eventEmitter, res);
                });
@ -55,49 +51,59 @@ class Topics extends RedisModel {
    }
    /**
     * 创建议题。
     *
     * @param topicName 发起议题的名称
     * @param topicId
     * @param users 发起议题的患者{"userId1:role", "userId2:role"}
     * @param messages 发送的消息对象{description:"",title:"",img:"",senderId:"",senderName:""}图片多个用逗号隔开
     * @param sessionId
     * @param users 发起议题的患者,格式:{"userId1:role", "userId2:role"}
     * @param messages 发送的消息对象,格式:{description:"",title:"",img:"image1,image2",senderId:"",senderName:""},多个图片用逗号隔开
     */
    createTopics(topicName, topicId,sessionId,users, messages) {
    createTopic(topicName, topicId, sessionId, users, messages) {
        let self = this;
        
        //MUC模式中sessionID就是患者ID
        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=[];
        var pars = [];
        redis.zaddAsync(topics_key, date.getTime(), topicId).then(function (res) {
            redis.hmsetAsync(topic_key, "name", topicName, "end_by", "", "session_id", sessionId, "create_time", date.getTime(), "end_time", "", "description", messages.description, "status", TOPIC_STATUS.NEW).then(function (res) {
                sessions.getSessions(sessionId, function (err, res) {
                    //已经存在对应的会话更新全科为旁听
                    if (res && res.length > 0) {
                        for(var j in users){
                           participants.updateUser(sessionId, j, users[j]);
                        }
                        callbegin();
                    } else {//不存在创建SESSION
                        for(var j in users){
                            pars.push(j+":"+users[j]);
                        }
                        sessions.createSession(sessionId, messages.senderName, SESSION_TYPES.MUC, pars, function (res) {
                            if (res) {
                                callbegin();
            redis.hmsetAsync(topic_key,
                "name", topicName,
                "end_by", "",
                "session_id", sessionId,
                "create_time", date.getTime(),
                "end_time", "",
                "description", messages.description,
                "status", TOPIC_STATUS.NEW)
                .then(function (res) {
                    sessions.getSessions(sessionId, function (err, res) {
                        // 已经存在对应的会话更新全科为旁听
                        if (res && res.length > 0) {
                            for (var j in users) {
                                participants.updateUser(sessionId, j, users[j]);
                            }
                        });
                    }
                            callbegin();
                        } else {
                            // 不存在创建SESSION
                            for (var j in users) {
                                pars.push(j + ":" + users[j]);
                            }
                            sessions.createSession(sessionId, messages.senderName, SESSION_TYPES.MUC, pars, function (res) {
                                if (res) {
                                    callbegin();
                                }
                            });
                        }
                    })
                })
            })
        }).catch(function(e){
            log.info("line 7")
        });
        
        }).catch();
        /**
         * 开始消息发送
         */
@ -112,7 +118,7 @@ class Topics extends RedisModel {
                if (err) {
                    ModelUtil.emitOK(self.eventEmitter, err);
                } else {
                    self.saveTopicsToSql(topicName, topicId, sessionId, msgId, date,messages.description,TOPIC_STATUS.NEW);
                    self.saveTopicToMySQL(topicName, topicId, sessionId, msgId, date, messages.description, TOPIC_STATUS.NEW);
                    callBeginMsg(msgId);
                }
            })
@ -128,10 +134,10 @@ class Topics extends RedisModel {
            msg.content_type = 1;
            msg.content = messages.description;
            msg.timestamp = new Date();
            sessions.saveMessageByTopic(msg,  sessionId, function (err, msgId) {
            sessions.saveMessageByTopic(msg, sessionId, function (err, msgId) {
                log.info("begin send" + messages.description);
            });
            
            if (messages.img) {
                let imgs = messages.img.split(",");
                for (var j in imgs) {
@ -146,62 +152,94 @@ class Topics extends RedisModel {
                    })
                }
            }
            ModelUtil.emitOK(self.eventEmitter, {"id":startMsgId});
            ModelUtil.emitOK(self.eventEmitter, {"id": startMsgId});
        }
    }
    saveTopicsToSql(topicName, topicId, sessionId, messageId, date,description) {
        TopicsRepo.saveTopic(topicName, topicId, sessionId, messageId, date,description);
    saveTopicToMySQL(topicName, topicId, sessionId, messageId, date, description) {
        TopicsRepo.saveTopic(topicName, topicId, sessionId, messageId, date, description);
    }
    /**
     * 议题是否已结束。
     *
     * @param sessionId
     * @param topicId
     * @param handler
     */
    isTopicEnded(sessionId, topicId, handler) {
        let self = this;
        if (topicId === "current") {
            TopicsRepo.findLastTopicStatus(sessionId, callback);
        } else {
            TopicsRepo.findTopicStatus(topicId, callback);
        }
        function callback(err, res) {
            if (err) {
                handler != null ? handler(err, res) : ModelUtil.emitError(self.eventEmitter, err);
            } else {
                if (null == res) {
                    handler != null ? handler(err, res) : ModelUtil.emitDataNotFound(self.eventEmitter, "Topic not found.");
                } else {
                    let ended = res[0].status == TOPIC_STATUS.ENDED;
                    handler != null ? handler(err, res) : ModelUtil.emitOK(self.eventEmitter, ended);
                }
            }
        }
    }
    /**
     * 结束议题
     * @param topicId
     * @param endUser
     * @param endUserName
     */
    endTopic(topicId, endUser, endUserName) {
        let endDate = new Date();
        let self = this;
        let topic_key = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        redis.hmsetAsync(topic_key, "end_time", endDate.getTime(), "end_by", endUser,"status",TOPIC_STATUS.FINISHED).then(function (res) {
        redis.hmsetAsync(topic_key, "end_time", endDate.getTime(), "end_by", endUser, "status", TOPIC_STATUS.ENDED).then(function (res) {
            redis.hgetallAsync(topic_key).then(function (topic) {
                callEnd(topic.session_id);
            })
        });
        
        /**
         * 结束消息发送
         */
        function callEnd(sessionId) {
            let msg = {};
            msg.sender_id = endUser;
            msg.sender_name = endUserName;
            msg.content_type = 7;
            msg.content = endUserName + "结束了咨询"
            msg.timestamp = new Date();
            let msg = {
                sender_id: endUser,
                sender_name: endUserName,
                content_type: 7,
                content: endUserName + "结束了咨询",
                timestamp: new Date()
            };
            let sessions = new Sessions();
            sessions.saveMessageByTopic(msg, sessionId, function (err, msgId) {
                if (err) {
                    ModelUtil.emitOK(self.eventEmitter, err);
                } else {
                    ModelUtil.emitOK(self.eventEmitter,  {"id":msgId});
                    ModelUtil.emitOK(self.eventEmitter, {"id": msgId});
                    TopicsRepo.endTopic(topicId, endUser, msg.date, msgId);
                }
            })
        }
    }
    updateTopic(topicId,valueJson){
        let self = this;
        let topic_key = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
    updateTopic(topicId, valueJson) {
        let topickey = RedisModel.makeRedisKey(REDIS_KEYS.Topic, topicId);
        var dataArray = [];
        for(var j in valueJson){
        for (var j in valueJson) {
            dataArray.push(j);
            dataArray.push(valueJson[j]);
        }
        redis.hmsetAsync(topic_key, dataArray).then(function (res) {
            TopicsRepo.updateTopis(topicId,valueJson);
        redis.hmsetAsync(topickey, dataArray).then(function (res) {
        });
        TopicsRepo.updateTopics(topicId, valueJson);
    }
}

+ 0 - 50
src/server/repository/mysql/topic.repo.js

@ -1,50 +0,0 @@
/**
 * 会话议题库。
 *
 * author: Sand
 * since: 12/21/2016
 */
"use strict";
let ImDb = require('./db/im.db');
class TopicsRepo {
    constructor(){}
    /**
     * 查找议题.
     *
     * @param topicId
     * @param handler
     */
    static findOne(topicId, handler){
        let sql = "select id, session_id, name, create_time, end_by, end_time," +
            " start_message_id, end_message_id, description, status from topics where id = ?";
        ImDb.execQuery({
            sql: sql,
            args: [topicId],
            handler: handler
        });
    }
    /**
     * 获取会话中的议题。
     *
     * @param sessionId
     * @param handler
     */
    static findAllBySessionId(sessionId, handler){
        let sql = "select id, session_id, name, create_time, end_by, end_time," +
            " start_message_id, end_message_id, description, status from topics where session_id = ? order by id";
        ImDb.execQuery({
            sql: sql,
            args: [sessionId],
            handler: handler
        });
    }
}
module.exports = TopicsRepo;

+ 88 - 18
src/server/repository/mysql/topics.repo.js

@ -4,28 +4,95 @@
"use strict";
let ImDb = require('../mysql/db/im.db');
let DbUtil = require('../../util/db.util');
let log = require('../../util/log.js');
const DB_TABLES = require('../../include/commons').DB_TABLES;
class TopicRepo {
    constructor() {
    }
    /**
     * 查找议题.
     *
     * @param topicId
     * @param handler
     */
    static findOne(topicId, handler) {
        let sql = "select id, session_id, name, create_time, end_by, end_time," +
            " start_message_id, end_message_id, description, status from " + DB_TABLES.Topics + " where id = ?";
        ImDb.execQuery({
            sql: sql,
            args: [topicId],
            handler: handler
        });
    }
    static findLastTopicStatus(sessionId, handler) {
        let sql = "select id from " + DB_TABLES.Topics + " where session_id = ? order by id desc limit 0, 1";
        ImDb.execQuery({
            sql: sql,
            args: [sessionId],
            handler: function (err, res) {
                if (res.length == 0) {
                    handler(null, null);
                } else {
                    TopicRepo.findTopicStatus(res[0].id, handler);
                }
            }
        });
    }
    static findTopicStatus(topicId, handler) {
        let sql = "select status from " + DB_TABLES.Topics + " where id = ?";
        ImDb.execQuery({
            sql: sql,
            args: [topicId],
            handler: handler
        });
    }
    /**
     * 获取会话中的议题。
     *
     * @param sessionId
     * @param handler
     */
    static findAllBySessionId(sessionId, handler) {
        let sql = "select id, session_id, name, create_time, end_by, end_time," +
            " start_message_id, end_message_id, description, status from " + DB_TABLES.Topics + " where session_id = ? order by id";
        ImDb.execQuery({
            sql: sql,
            args: [sessionId],
            handler: handler
        });
    }
    /**
     * 保存议题
     *
     * @param topicName
     * @param topicId
     * @param sessionId
     * @param messageId
     * @param date
     * @param description
     * @param status
     */
    static saveTopic(topicName,topicId,sessionId,messageId,date,description,status) {
        let sql = "insert into topics (id,session_id,name,create_time,start_message_id,description,status) VALUES (?,?,?,?,?,?,?)";
    static saveTopic(topicName, topicId, sessionId, messageId, date, description, status) {
        let sql = "insert into " + DB_TABLES.Topics + " (id,session_id,name,create_time,start_message_id,description,status) VALUES (?,?,?,?,?,?,?)";
        ImDb.execQuery({
            "sql": sql,
            "args": [topicId,sessionId,topicName,date,messageId,description,status],
            "args": [topicId, sessionId, topicName, date, messageId, description, status],
            "handler": function (err, res) {
                if (err) {
                    log.error("saveTopic is fail error: " + err+"messageId:"+messageId);
                }else{
                    log.info("saveTopic is success" );
                    log.error("saveTopic is fail error: " + err + "messageId:" + messageId);
                } else {
                    log.info("saveTopic is success");
                }
            }
        });
@ -34,26 +101,29 @@ class TopicRepo {
    /**
     * 结束议题
     *
     * @param sessionId
     * @param handler
     * @param topicId
     * @param endUser
     * @param date
     * @param messageId
     * @param status
     */
    static endTopic(topicId,endUser,date,messageId,status) {
        let sql = "update topics set end_by = ?,end_time=?,end_message_id=?,status = ? where  id = ?";
    static endTopic(topicId, endUser, date, messageId, status) {
        let sql = "update " + DB_TABLES.Topics + " set end_by = ?,end_time=?,end_message_id=?,status = ? where  id = ?";
        ImDb.execQuery({
            "sql": sql,
            "args": [endUser,date,messageId,status ,topicId],
            "args": [endUser, date, messageId, status, topicId],
            "handler": function (err, res) {
                if (err) {
                    log.error("endTopic is fail error: " + err);
                }else{
                    log.info("endTopic is success" );
                } else {
                    log.info("endTopic is success");
                }
            }
        });
    }
    static updateTopis(topicId,jsonValue){
        var values=[];
    static updateTopics(topicId, jsonValue) {
        var values = [];
        let sql = "update topics set ";
        var key =[];
        for(var j in jsonValue){
@ -69,8 +139,8 @@ class TopicRepo {
            "handler": function (err, res) {
                if (err) {
                    log.error("updateTopis is fail error: " + err);
                }else{
                    log.info("updateTopis is success" );
                } else {
                    log.info("updateTopis is success");
                }
            }
        });

+ 0 - 4
src/server/repository/redis/redis.client.js

@ -30,10 +30,6 @@ class RedisClient {
        this._connection.on('ready', function (res) {
            log.info('Redis is ready.');
        });
        this._connection.on('connect', function (res) {
            log.info('Redis connected.');
        });
    }
    get connection() {