socket.handler.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /**
  2. * author: Sand
  3. * since: 2016/11/17
  4. */
  5. "use strict";
  6. let log = require("../util/log.js");
  7. let clientCache = require('../models/socket.io/client.cache').clientCache();
  8. let PatientClient = require('./../models/socket.io/patient.client');
  9. let PcDoctorClient = require('./../models/socket.io/pcDoctor.client');
  10. let DoctorClient = require('./../models/socket.io/doctor.client');
  11. let RtcClient = require('../models/socket.io/rtc.client.js');
  12. let Sessions = require('../models/sessions/sessions');
  13. let Users = require('../models/user/users');
  14. let ModelUtil = require('../util/model.util.js');
  15. let pusher = require('../models/push/pusher.js');
  16. let AppClient = require('../models/client/app.client.js');
  17. let sessions = new Sessions();
  18. let users = new Users();
  19. class SocketHandler {
  20. constructor(socketServer) {
  21. this._socketServer = socketServer;
  22. }
  23. sleep (time) {
  24. return new Promise((resolve) => setTimeout(resolve, time));
  25. }
  26. /**
  27. * 启用事件监听。
  28. */
  29. start() {
  30. let socketServer = this._socketServer;
  31. socketServer.sockets.on('connection', function (socket) {
  32. log.info('one user connection...');
  33. // 客户端注册
  34. socket.on('login', function (data) {
  35. if (!data.userId) {
  36. socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
  37. } else {
  38. if("pc_doctor"===data.clientType){//新增pc端医生登录
  39. data.userId = "pc_"+data.userId;
  40. }else if("pcim_doctor"===data.clientType){//用于pcim 消息通知
  41. data.userId = "pcim_"+data.userId;
  42. }
  43. if(clientCache.removeByUserId(data.userId)){
  44. log.info("User " + data.userId + " already login");
  45. return;
  46. }
  47. log.info('User ' + data.userId + ' login');
  48. if(!data.clientType||data.clientType=="patient"){
  49. let patientClient = new PatientClient(socket, socketServer);
  50. patientClient.userId = data.userId;
  51. patientClient.password = data.password;
  52. patientClient.clientType = data.clientType||"patient";
  53. patientClient.sessionId = data.sessionId||"";
  54. clientCache.addClient(patientClient);
  55. users.login(data.userId, 10, '', '');
  56. socket.emit('ack', {});
  57. }else if("pcim_doctor"===data.clientType){
  58. //用于pcim 消息通知
  59. let pcdoctorClient = new PcDoctorClient(socket, socketServer);
  60. pcdoctorClient.userId = data.userId;
  61. pcdoctorClient.password = data.password;
  62. pcdoctorClient.clientType = data.clientType;
  63. pcdoctorClient.sessionId = "";
  64. clientCache.addClient(pcdoctorClient);
  65. socket.emit('ack', {});
  66. }else{
  67. let doctorClient = new DoctorClient(socket, socketServer);
  68. doctorClient.userId = data.userId;
  69. doctorClient.password = data.password;
  70. doctorClient.clientType = data.clientType;
  71. doctorClient.sessionId = data.sessionId||"";
  72. clientCache.addClient(doctorClient);
  73. socket.emit('ack', {});
  74. }
  75. }
  76. });
  77. // 返回userid的socketid
  78. socket.on('getSid',function(data){
  79. var clientJson = null;
  80. if(!(data instanceof Object)){
  81. clientJson = JSON.parse(data);
  82. }else{
  83. clientJson = data;
  84. }
  85. var userId = clientJson.userId;
  86. var rtcClient = clientCache.findById(userId);
  87. if(rtcClient === undefined){
  88. socketServer.sockets.emit('error', {message: 'this socket client has not ever connect '});
  89. return;
  90. }
  91. var result = {'userId':userId,'sid':rtcClient._socket.id};
  92. log.info('request getSid,userid :'+userId);
  93. socket.emit('getSid',result);
  94. });
  95. // 设置userid的socketid
  96. socket.on('setSid',function(data){
  97. var clientJson = null;
  98. if(!(data instanceof Object)){
  99. clientJson = JSON.parse(data);
  100. }else{
  101. clientJson = data;
  102. }
  103. var userId = clientJson.userId;
  104. let rtcClient = new RtcClient(socket,socketServer);
  105. rtcClient.userId = userId;
  106. clientCache.addClient(rtcClient);
  107. var result = {'userId':userId,'sid':rtcClient._socket.id};
  108. log.info('request setSid,userid :'+userId);
  109. socket.emit('setSid',result);
  110. });
  111. // 接收客户端消息
  112. /**
  113. * 视频消息格式:
  114. * var payload = {
  115. userId: userId,
  116. sid:sid, socket.io 的id
  117. targetId: targetUid,
  118. type: "offer/answer/hang-up/time-out/canidate", 发起视频/接受视频/(拒绝视频|挂断视频)/超时
  119. sdp: myPeerConnection.localDescription
  120. };
  121. */
  122. socket.on('message', function (data) {
  123. var payload = null;
  124. if(!(data instanceof Object)){
  125. payload = JSON.parse(data);
  126. }else{
  127. payload = data;
  128. }
  129. // 视频聊天消息
  130. if(payload !== undefined && payload.type){
  131. if(payload.fromSid === undefined || payload.fromSid === ''){
  132. socket.emit('error', {error: 'Missing fields(s): sid.',"payload":payload});
  133. return;
  134. }
  135. switch (payload.type) {
  136. case 'video-offer':
  137. let title = 'videoCall';
  138. /* var getui = {
  139. from:from_userId,
  140. fromSid:from_sid,
  141. to:to_userId,
  142. msgType: "videoCall",
  143. };*/
  144. AppClient.getAppStatus(payload.targetId, function (err, userStatus) {
  145. if (err) {
  146. ModelUtil.logError("Get user app status failed", err);
  147. socket.emit('error', {error: 'cannot get ClietnId for targetId:' + payload.targetId,"payload":payload});
  148. return;
  149. }
  150. pusher.pushToSingleViaAndroid(title, title, payload, userStatus.client_id, userStatus.app_in_bg, function (err, res) {
  151. if (err) {
  152. ModelUtil.logError("Send notification via Android failed", err);
  153. socket.emit('error', {error: 'Send notification via Android failed for targetId:' + payload.targetId,"payload":payload});
  154. } else {
  155. log.info("offer Send notification via Android succeed: ", JSON.stringify(res));
  156. }
  157. });
  158. });
  159. break;
  160. case 'video-answer':
  161. var rtcClientSocket = clientCache.findById(payload.targetId);
  162. if(rtcClientSocket === undefined){
  163. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when video-answer',"payload":payload});
  164. return
  165. }
  166. rtcClientSocket._socket.send(payload,function(client){
  167. });
  168. break;
  169. case 'candidate':
  170. var rtcClientSocket = clientCache.findById(payload.targetId);
  171. if(rtcClientSocket === undefined){
  172. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when candidate',"payload":payload});
  173. return
  174. }
  175. rtcClientSocket._socket.send(payload,function(client){
  176. });
  177. break;
  178. case 'hang-up':
  179. var rtcClientSocket = clientCache.findById(payload.targetId);
  180. if(rtcClientSocket === undefined){
  181. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when hang-up',"payload":payload});
  182. return
  183. }
  184. rtcClientSocket._socket.send(payload,function(client){
  185. });
  186. case 'time-out':
  187. var rtcClientSocket = clientCache.findById(payload.targetId);
  188. if(rtcClientSocket === undefined){
  189. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when time-out',"payload":payload});
  190. return
  191. }
  192. rtcClientSocket._socket.send(payload,function(client){
  193. });
  194. break;
  195. }
  196. }else{
  197. // 其他类型的消息
  198. log.info('Got message from ' + clientCache.findBySocket(socket).userId);
  199. let sessionId = data.session_id;
  200. let message = data.message;
  201. message.timestamp = new Date();
  202. /*sessions.createSession(sessionId, "Let's talk!", 1, ['504a0bcddb1e4e37a0306b39c51900b5', 'cd92414c-5b06-11e6-8344-fa163e8aee56'], function (err, res) {
  203. sessions.saveMessageBySession(sessionId, message);
  204. });*/
  205. sessions.saveMessageBySession(sessionId, message);
  206. }
  207. });
  208. socket.on('error',function(errMsg){
  209. log.info(JSON.stringify(errMsg));
  210. socket.emit(errMsg);
  211. });
  212. // 客户端退出
  213. socket.on('logout', function (data) {
  214. let client = clientCache.findBySocket(socket);
  215. if (client) {
  216. log.info('User logout: ' + client.userId);
  217. clientCache.removeByUserId(client.userId);
  218. }
  219. });
  220. // 客户端断开
  221. socket.on('disconnect', function (soc) {
  222. let patientClient = clientCache.findBySocket(socket);
  223. if (patientClient) {
  224. log.info("User disconnect: ", patientClient.userId);
  225. clientCache.removeByUserSocket(socket);
  226. }
  227. });
  228. socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
  229. });
  230. }
  231. }
  232. module.exports = SocketHandler;