瀏覽代碼

增加会话状态

8 年之前
父節點
當前提交
751383406c

+ 20 - 11
src/server/handlers/socket.handler.js

@ -8,7 +8,7 @@ let log = require("../util/log.js");
let clientCache = require('../models/socket.io/client.cache').clientCache();
let PatientClient = require('./../models/socket.io/patient.client');
let DoctorClient  = require('./../models/socket.io/doctor.client');
let Sessions = require('../models/sessions/sessions');
let Users = require('../models/user/users');
@ -37,16 +37,25 @@ class SocketHandler {
                    }
                    log.info('User ' + data.userId + ' login');
                    let patientClient = new PatientClient(socket, socketServer);
                    patientClient.userId = data.userId;
                    patientClient.password = data.password;
                    clientCache.addClient(patientClient);
                    users.login(data.userId, 10, '', '');
                    socket.emit('ack', {});
                    if(!data.clientType||data.clientType=="patient"){
                        let patientClient = new PatientClient(socket, socketServer);
                        patientClient.userId = data.userId;
                        patientClient.password = data.password;
                        patientClient.clientType = data.clientType||"patient";
                        clientCache.addClient(patientClient);
                        users.login(data.userId, 10, '', '');
                        socket.emit('ack', {});
                    }else{
                        let doctorClient = new DoctorClient(socket, socketServer);
                        doctorClient.userId = data.userId;
                        doctorClient.password = data.password;
                        doctorClient.clientType = data.clientType;
                        doctorClient.sessionId = data.sessionId;
                        clientCache.addClient(doctorClient);
                        socket.emit('ack', {});
                    }
                }
            });

+ 7 - 2
src/server/include/commons.js

@ -74,8 +74,8 @@ const CONTENT_TYPES = {
    Article: 4,     // 文章信息
    GoTo: 5,        // 跳转信息
    TopicBegin: 6,  // 议题开始
    TopicEnd: 7,    // 议题结束
    TopicEnd: 7,    // 议题结束 10 11 系统发送的会话消息
    Video:12,//视频
    typeToDescription: function (type, defaultDescription) {
        if (CONTENT_TYPES.Image === type) {
            return '[图片]';
@ -91,6 +91,11 @@ const CONTENT_TYPES = {
exports.CONTENT_TYPES = CONTENT_TYPES;
exports.SOCKET_TYPES={
    PATIENT:"patient",
    DOCTOR:"doctor"
}
/**
 * 客户端平台。
 */

+ 29 - 2
src/server/models/client/wechat.client.js

@ -20,6 +20,7 @@ let https = require('https');
let async = require('async');
const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES;
const SOCKET_TYPES = require('../../include/commons').SOCKET_TYPES;
const REDIS_KEYS = require('../../include/commons').REDIS_KEYS;
class WechatClient extends RedisModel {
@ -60,11 +61,14 @@ class WechatClient extends RedisModel {
            message.content_type == CONTENT_TYPES.Image ||
            message.content_type == CONTENT_TYPES.Audio)) {
            let patientClient = clientCache.findById(targetUserId);
            let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);
            if (patientClient) {
                log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId);
                WechatClient.sendViaWebSocket(patientClient.socket, message);
                if(doctorClient){
                    //用户socket在线,推送给用户后,告知医生此消息已读
                    WechatClient.sendReadDoctor(doctorClient.socket, message);
                }
            } else {
                log.info("User's wechat endpoint is not online, sending via wechat template message. User id: ", targetUserId);
@ -88,6 +92,29 @@ class WechatClient extends RedisModel {
        });
    }
    static sendAllRead(doctorId,sessionId){
        let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR);
        if(doctorClient){
            if(doctorClient.sessionId==sessionId)
                socket.emit('read',{ read:"all"});
        }
    }
    static sendReadDoctor(socket, message) {
        socket.emit('read', {
            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"
        });
    }
    /**
     * 发送微信模板消息给居民
     *

+ 21 - 9
src/server/models/sessions/sessions.js

@ -102,14 +102,16 @@ class Sessions extends RedisModel {
                callBusinessType(sessionId);
                return;
            }
            if (participantIdArray.length != 2) {
            else if (participantIdArray.length != 2) {
                handler("P2P session only allow 2 participants.", null);
                return false;
            }else{
                ParticipantRepo.findSessionIdByParticipantIds(participantIdArray[0], participantIdArray[1], function (err, res) {
                    sessionId = res;
                    callBusinessType(sessionId);
                    return;
                });
            }
            ParticipantRepo.findSessionIdByParticipantIds(participantIdArray[0], participantIdArray[1], function (err, res) {
                sessionId = res;
                callBusinessType(sessionId);
            });
        } else {
            if (!sessionId) {
                handler("MUC OR GROUP session sessionId is not  allow null .", null);
@ -350,12 +352,11 @@ class Sessions extends RedisModel {
                        let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
                        let participantsRoleKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipantsRole, sessionId);
                        let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
                        let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
                        redis.multi()
                            .hgetall(sessionKey)                       // 会话实体
                            .hget(participantsRoleKey, userId)         // 用户在此会话中的角色
                            .zscore(sessionParticipantsKey, userId)    // 用户在此会话中最后一次获取未读消息的时间
                            .zrange(participantsKey, 0, -1)
                            .zrange(sessionParticipantsKey, 0, -1)
                            .zrange(sessionParticipantsKey, 0,-1,'withscores')  // 所有用户在此会话中最后一次获取未读消息的时间
                            .execAsync()
                            .then(function (res) {
@ -583,7 +584,8 @@ class Sessions extends RedisModel {
    getMessagesByPage(sessionId, userId, startMsgId, endMsgId, page, size, isoffset, handler) {
        let messagesTimestampKey = RedisModel.makeRedisKey(REDIS_KEYS.MessagesByTimestamp, sessionId);
        let messagesKey = RedisModel.makeRedisKey(REDIS_KEYS.Messages, sessionId);
        let sessionKey = RedisModel.makeRedisKey(REDIS_KEYS.Session, sessionId);
        let sessionParticipantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId);
        let participants = new Participants();
        let offset = (page - 1 < 0 ? 0 : page - 1) * size;
        let count = size;
@ -599,11 +601,14 @@ class Sessions extends RedisModel {
                redis.multi()
                    .zscore(messagesTimestampKey, startMsgId)
                    .zscore(messagesTimestampKey, endMsgId)
                    .hgetall(sessionKey)
                    .zrange(sessionParticipantsKey, 0, -1)
                    .execAsync()
                    .then(function (res) {
                        let startMsgScore = res[1];
                        let endMsgScore = res[0];
                        let session = res[2];
                        let users = res[3];
                        if (startMsgScore == null || endMsgScore == null || (startMsgScore == endMsgScore && isoffset == 1)) {
                            handler(null, []);
                            return;
@ -620,6 +625,13 @@ class Sessions extends RedisModel {
                                        handler(null, messages);
                                    }).then(function () {
                                        Sessions.updateParticipantLastFetchTime(sessionId, userId, new Date().getTime());
                                        if(session.type != SESSION_TYPES.GROUP){
                                            for(var j in users){
                                                if(users[j]==userId)continue;
                                                 WechatClient.sendAllRead(users[j]);
                                            }
                                        }
                                    })
                                })
                                .catch(function (err) {

+ 10 - 5
src/server/models/socket.io/client.cache.js

@ -14,6 +14,7 @@ class ClientCache {
    constructor() {
        this._clientsBySocket = new Map();
        this._clientsByUserId = new Map();
        this._clientsByTypeAndUserId = new Map();
    }
    get clients() {
@ -23,23 +24,23 @@ class ClientCache {
    addClient(client) {
        this._clientsByUserId.set(client.userId, client);
        this._clientsBySocket.set(client.socket, client);
        this._clientsByTypeAndUserId.set(client.userId+":"+client.clientType,client);
        //log.info('Current clients: ', this.clients);
    }
    removeByUserId(userId) {
        var socket = this.findById(userId);
        var client = this.findById(userId);
        this._clientsByUserId.delete(userId);
        this._clientsBySocket.delete(socket);
        this._clientsBySocket.delete(client.socket);
        this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType)
    }
    removeByUserSocket(socket) {
        var client = this.findBySocket(socket);
        if (client) {
            this._clientsByUserId.delete(client.userId);
            this._clientsBySocket.delete(socket);
            this._clientsByTypeAndUserId.delete(client.userId+":"+client.clientType)
        }
    }
@ -47,6 +48,10 @@ class ClientCache {
        return this._clientsByUserId.get(userId);
    }
    findByIdAndType(userId,type){
        this._clientsByTypeAndUserId.get(userId+":"+type);
    }
    findBySocket(socket) {
        return this._clientsBySocket.get(socket);
    }

+ 19 - 0
src/server/models/socket.io/doctor.client.js

@ -0,0 +1,19 @@
/**
 * 患者端socket.
 *
 * author: Sand
 * since: 2016/11/18
 */
"use strict";
var util = require('util');
var Client = require('./client');
class DoctorClient extends Client{
    constructor(socket, socketServer){
        super(socket, socketServer);
    }
}
module.exports = DoctorClient;