socket.handler.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. //视频聊天
  78. // 返回userid的socketid
  79. socket.on('getSid',function(data){
  80. var clientJson = null;
  81. if(!(data instanceof Object)){
  82. clientJson = JSON.parse(data);
  83. }else{
  84. clientJson = data;
  85. }
  86. var userId = clientJson.userId;
  87. var rtcClient = clientCache.findById(userId);
  88. if(rtcClient === undefined){
  89. socketServer.sockets.emit('error', {message: 'this socket client has not ever connect '});
  90. return;
  91. }
  92. var result = {'userId':userId,'sid':rtcClient._socket.id};
  93. log.info('request getSid,userid :'+userId);
  94. socket.emit('getSid',result);
  95. });
  96. //视频聊天
  97. // 设置userid的socketid
  98. socket.on('setSid',function(data){
  99. var clientJson = null;
  100. if(!(data instanceof Object)){
  101. clientJson = JSON.parse(data);
  102. }else{
  103. clientJson = data;
  104. }
  105. var userId = clientJson.userId;
  106. let rtcClient = new RtcClient(socket,socketServer);
  107. rtcClient.userId = userId;
  108. clientCache.addClient(rtcClient);
  109. var result = {'userId':userId,'sid':rtcClient._socket.id};
  110. log.info('request setSid,userid :'+userId);
  111. socket.emit('setSid',result);
  112. });
  113. // 接收客户端消息
  114. /**
  115. * 视频消息格式:
  116. * var payload = {
  117. userId: userId,
  118. sid:sid, socket.io 的id
  119. targetId: targetUid,
  120. type: "offer/answer/hang-up/time-out/canidate", 发起视频/接受视频/(拒绝视频|挂断视频)/超时
  121. sdp: myPeerConnection.localDescription
  122. };
  123. */
  124. socket.on('message', function (data) {
  125. var payload = null;
  126. if(!(data instanceof Object)){
  127. payload = JSON.parse(data);
  128. }else{
  129. payload = data;
  130. }
  131. // 视频聊天消息
  132. if(payload !== undefined && payload.type){
  133. if(payload.fromSid === undefined || payload.fromSid === ''){
  134. socket.emit('error', {error: 'Missing fields(s): sid.',"payload":payload});
  135. return;
  136. }
  137. switch (payload.type) {
  138. case 'video-offer':
  139. let title = 'videoCall';
  140. /* var getui = {
  141. from:from_userId,
  142. fromSid:from_sid,
  143. to:to_userId,
  144. msgType: "videoCall",
  145. };*/
  146. AppClient.getAppStatus(payload.targetId, function (err, userStatus) {
  147. if (err) {
  148. ModelUtil.logError("Get user app status failed", err);
  149. socket.emit('error', {error: 'cannot get ClietnId for targetId:' + payload.targetId,"payload":payload});
  150. return;
  151. }
  152. pusher.pushToSingleViaAndroid(title, title, payload, userStatus.client_id, userStatus.app_in_bg, function (err, res) {
  153. if (err) {
  154. ModelUtil.logError("Send notification via Android failed", err);
  155. socket.emit('error', {error: 'Send notification via Android failed for targetId:' + payload.targetId,"payload":payload});
  156. } else {
  157. log.info("offer Send notification via Android succeed: ", JSON.stringify(res));
  158. }
  159. });
  160. });
  161. break;
  162. case 'video-answer':
  163. var rtcClientSocket = clientCache.findById(payload.targetId);
  164. if(rtcClientSocket === undefined){
  165. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when video-answer',"payload":payload});
  166. return
  167. }
  168. rtcClientSocket._socket.send(payload,function(client){
  169. });
  170. break;
  171. case 'candidate':
  172. var rtcClientSocket = clientCache.findById(payload.targetId);
  173. if(rtcClientSocket === undefined){
  174. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when candidate',"payload":payload});
  175. return
  176. }
  177. rtcClientSocket._socket.send(payload,function(client){
  178. });
  179. break;
  180. case 'hang-up':
  181. var rtcClientSocket = clientCache.findById(payload.targetId);
  182. if(rtcClientSocket === undefined){
  183. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when hang-up',"payload":payload});
  184. return
  185. }
  186. rtcClientSocket._socket.send(payload,function(client){
  187. });
  188. case 'time-out':
  189. var rtcClientSocket = clientCache.findById(payload.targetId);
  190. if(rtcClientSocket === undefined){
  191. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when time-out',"payload":payload});
  192. return
  193. }
  194. rtcClientSocket._socket.send(payload,function(client){
  195. });
  196. break;
  197. }
  198. }else{
  199. // 其他类型的消息
  200. log.info('Got message from ' + clientCache.findBySocket(socket).userId);
  201. let sessionId = data.session_id;
  202. let message = data.message;
  203. message.timestamp = new Date();
  204. /*sessions.createSession(sessionId, "Let's talk!", 1, ['504a0bcddb1e4e37a0306b39c51900b5', 'cd92414c-5b06-11e6-8344-fa163e8aee56'], function (err, res) {
  205. sessions.saveMessageBySession(sessionId, message);
  206. });*/
  207. sessions.saveMessageBySession(sessionId, message);
  208. }
  209. });
  210. socket.on('error',function(errMsg){
  211. log.info(JSON.stringify(errMsg));
  212. socket.emit(errMsg);
  213. });
  214. // 客户端退出
  215. socket.on('logout', function (data) {
  216. let client = clientCache.findBySocket(socket);
  217. if (client) {
  218. log.info('User logout: ' + client.userId);
  219. clientCache.removeByUserId(client.userId);
  220. }
  221. });
  222. // 客户端断开
  223. socket.on('disconnect', function (soc) {
  224. let patientClient = clientCache.findBySocket(socket);
  225. if (patientClient) {
  226. log.info("User disconnect: ", patientClient.userId);
  227. clientCache.removeByUserSocket(socket);
  228. }
  229. });
  230. socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
  231. });
  232. }
  233. }
  234. module.exports = SocketHandler;