socket.handler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 PcPatientClient = require('./../models/socket.io/pcPatient.client');
  10. let PcDoctorClient = require('./../models/socket.io/pcDoctor.client');
  11. let DoctorClient = require('./../models/socket.io/doctor.client');
  12. let RtcClient = require('../models/socket.io/rtc.client.js');
  13. let Sessions = require('../models/sessions/sessions');
  14. let Users = require('../models/user/users');
  15. let ModelUtil = require('../util/model.util.js');
  16. let pusher = require('../models/push/pusher.js');
  17. let AppClient = require('../models/client/app.client.js');
  18. let sessions = new Sessions();
  19. let users = new Users();
  20. class SocketHandler {
  21. constructor(socketServer) {
  22. this._socketServer = socketServer;
  23. }
  24. sleep (time) {
  25. return new Promise((resolve) => setTimeout(resolve, time));
  26. }
  27. /**
  28. * 启用事件监听。
  29. */
  30. start() {
  31. let socketServer = this._socketServer;
  32. socketServer.sockets.on('connection', function (socket) {
  33. log.info('one user connection...');
  34. // 客户端注册
  35. socket.on('login', function (data) {
  36. if (!data.userId) {
  37. socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
  38. } else {
  39. let mdt_login_tag = data.SYSTEM_TYPE;
  40. //MDT 托盘登陆
  41. if(mdt_login_tag && "MDT" == mdt_login_tag){
  42. //传入手机号,转换成医生CODE
  43. sessions.conversionAarticipant(data.userId, (doctorid) => {
  44. data.userId = "pcim_"+doctorid;
  45. if(clientCache.removeByUserId(data.userId)){
  46. log.info("User " + data.userId + " already loginMDT");
  47. return;
  48. }
  49. log.info('User ' + data.userId + ' loginMDT');
  50. // if("pcim_doctor"===data.clientType){
  51. //用于pcim 消息通知
  52. let pcdoctorClient = new PcDoctorClient(socket, socketServer);
  53. pcdoctorClient.userId = data.userId;
  54. pcdoctorClient.password = data.password;
  55. pcdoctorClient.clientType = data.clientType;
  56. pcdoctorClient.sessionId = "";
  57. clientCache.addClient(pcdoctorClient);
  58. socket.emit('ack', {});
  59. });
  60. }else{
  61. //原始登陆者ID
  62. let original_login_userid = data.userId;
  63. if("pc_doctor"===data.clientType){//新增pc端医生登录
  64. data.userId = "pc_"+data.userId;
  65. }else if("pc_doctor_system"===data.clientType){//新增pc端医生外层-登录类型-20191012-huangnwenjie
  66. data.userId= "pc_system_"+data.userId;
  67. // }else if("pcim_doctor"===data.clientType){//用于pcim 消息通知 MDT-登陆类型已迁移到上面的分支-20191012-huangnwenjie
  68. // data.userId = "pcim_"+data.userId;
  69. }else if("pc_patient"===data.clientType){//新增居民PC登陆类型
  70. data.userId= "pcpatient_"+data.userId;
  71. }else if("pc_patient_system"===data.clientType){//新增居民PC外层-登陆类型-20191012-huangnwenjie
  72. data.userId= "pcpatient_system_"+data.userId;
  73. }else if("patient_system"===data.clientType){//新增居民微信端外层-登陆类型-20191012-huangnwenjie
  74. data.userId= "patient_system_"+data.userId;
  75. }else if("doctor_system"===data.clientType){//新增医生APP外层-登陆类型-20191012-huangnwenjie
  76. data.userId= "doctor_system_"+data.userId;
  77. }
  78. if(clientCache.removeByUserId(data.userId)){
  79. log.info("User " + data.userId + " already login");
  80. return;
  81. }
  82. log.info('User ' + data.userId + ' login');
  83. if(!data.clientType||data.clientType=="patient"||data.clientType=="patient_system"){//新增居民微信端外层-登陆类型-20191012-huangnwenjie
  84. let patientClient = new PatientClient(socket, socketServer);
  85. patientClient.userId = data.userId;
  86. patientClient.password = data.password;
  87. patientClient.clientType = data.clientType||"patient";
  88. patientClient.sessionId = data.sessionId||"";
  89. clientCache.addClient(patientClient);
  90. users.login(data.userId, 10, '', '');
  91. //修改居民在线状态
  92. users.changUserRedisLoginStatus(original_login_userid,data.clientType,1);
  93. socket.emit('ack', {});
  94. }else if("pc_patient"===data.clientType || "pc_patient_system"===data.clientType){////新增居民PC外层-登陆类型-20191012-huangnwenjie
  95. //用于pcpatient 消息通知
  96. let pcpatientClient = new PcPatientClient(socket, socketServer);
  97. pcpatientClient.userId = data.userId;
  98. pcpatientClient.password = data.password;
  99. pcpatientClient.clientType = data.clientType;
  100. pcpatientClient.sessionId = data.sessionId||"";
  101. clientCache.addClient(pcpatientClient);
  102. users.login(data.userId, 10, '', '');
  103. //修改居民在线状态
  104. users.changUserRedisLoginStatus(original_login_userid,data.clientType,1);
  105. socket.emit('ack', {});
  106. //MDT 登陆类型已迁移到上面的分支-20191012-huangnwenjie
  107. // }else if("pcim_doctor"===data.clientType){ 登
  108. // //用于pcim 消息通知
  109. // let pcdoctorClient = new PcDoctorClient(socket, socketServer);
  110. // pcdoctorClient.userId = data.userId;
  111. // pcdoctorClient.password = data.password;
  112. // pcdoctorClient.clientType = data.clientType;
  113. // pcdoctorClient.sessionId = "";
  114. // clientCache.addClient(pcdoctorClient);
  115. // socket.emit('ack', {});
  116. }else{
  117. let doctorClient = new DoctorClient(socket, socketServer);
  118. doctorClient.userId = data.userId;
  119. doctorClient.password = data.password;
  120. doctorClient.clientType = data.clientType;
  121. doctorClient.sessionId = data.sessionId||"";
  122. clientCache.addClient(doctorClient);
  123. //修改医生在线状态
  124. users.changUserRedisLoginStatus(original_login_userid,data.clientType,1);
  125. socket.emit('ack', {});
  126. }
  127. }
  128. }
  129. });
  130. // 客户端注册
  131. socket.on('loginMDT', function (data) {
  132. if (!data.userId) {
  133. socketServer.sockets.emit('error', {message: 'Missing fields(s): userId.'});
  134. } else {
  135. sessions.conversionAarticipant(j, (doctorid) => {
  136. data.userId = "pcim_"+doctorid;
  137. if(clientCache.removeByUserId(data.userId)){
  138. log.info("User " + data.userId + " already loginMDT");
  139. return;
  140. }
  141. log.info('User ' + data.userId + ' loginMDT');
  142. // if("pcim_doctor"===data.clientType){
  143. //用于pcim 消息通知
  144. let pcdoctorClient = new PcDoctorClient(socket, socketServer);
  145. pcdoctorClient.userId = data.userId;
  146. pcdoctorClient.password = data.password;
  147. pcdoctorClient.clientType = data.clientType;
  148. pcdoctorClient.sessionId = "";
  149. clientCache.addClient(pcdoctorClient);
  150. socket.emit('ack', {});
  151. // }
  152. });
  153. }
  154. });
  155. //视频聊天
  156. // 返回userid的socketid
  157. socket.on('getSid',function(data){
  158. var clientJson = null;
  159. if(!(data instanceof Object)){
  160. clientJson = JSON.parse(data);
  161. }else{
  162. clientJson = data;
  163. }
  164. var userId = clientJson.userId;
  165. var rtcClient = clientCache.findById(userId);
  166. if(rtcClient === undefined){
  167. socketServer.sockets.emit('error', {message: 'this socket client has not ever connect '});
  168. return;
  169. }
  170. var result = {'userId':userId,'sid':rtcClient._socket.id};
  171. log.info('request getSid,userid :'+userId);
  172. socket.emit('getSid',result);
  173. });
  174. //视频聊天
  175. // 设置userid的socketid
  176. socket.on('setSid',function(data){
  177. var clientJson = null;
  178. if(!(data instanceof Object)){
  179. clientJson = JSON.parse(data);
  180. }else{
  181. clientJson = data;
  182. }
  183. var userId = clientJson.userId;
  184. let rtcClient = new RtcClient(socket,socketServer);
  185. rtcClient.userId = userId;
  186. clientCache.addClient(rtcClient);
  187. var result = {'userId':userId,'sid':rtcClient._socket.id};
  188. log.info('request setSid,userid :'+userId);
  189. socket.emit('setSid',result);
  190. });
  191. // 接收客户端消息
  192. /**
  193. * 视频消息格式:
  194. * var payload = {
  195. userId: userId,
  196. sid:sid, socket.io 的id
  197. targetId: targetUid,
  198. type: "offer/answer/hang-up/time-out/canidate", 发起视频/接受视频/(拒绝视频|挂断视频)/超时
  199. sdp: myPeerConnection.localDescription
  200. };
  201. */
  202. socket.on('message', function (data) {
  203. var payload = null;
  204. if(!(data instanceof Object)){
  205. payload = JSON.parse(data);
  206. }else{
  207. payload = data;
  208. }
  209. // 视频聊天消息
  210. if(payload !== undefined && payload.type){
  211. if(payload.fromSid === undefined || payload.fromSid === ''){
  212. socket.emit('error', {error: 'Missing fields(s): sid.',"payload":payload});
  213. return;
  214. }
  215. switch (payload.type) {
  216. case 'video-offer':
  217. let title = 'videoCall';
  218. /* var getui = {
  219. from:from_userId,
  220. fromSid:from_sid,
  221. to:to_userId,
  222. msgType: "videoCall",
  223. };*/
  224. AppClient.getAppStatus(payload.targetId, function (err, userStatus) {
  225. if (err) {
  226. ModelUtil.logError("Get user app status failed", err);
  227. socket.emit('error', {error: 'cannot get ClietnId for targetId:' + payload.targetId,"payload":payload});
  228. return;
  229. }
  230. pusher.pushToSingleViaAndroid(title, title, payload, userStatus.client_id, userStatus.app_in_bg, function (err, res) {
  231. if (err) {
  232. ModelUtil.logError("Send notification via Android failed", err);
  233. socket.emit('error', {error: 'Send notification via Android failed for targetId:' + payload.targetId,"payload":payload});
  234. } else {
  235. log.info("offer Send notification via Android succeed: ", JSON.stringify(res));
  236. }
  237. });
  238. });
  239. break;
  240. case 'video-answer':
  241. var rtcClientSocket = clientCache.findById(payload.targetId);
  242. if(rtcClientSocket === undefined){
  243. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when video-answer',"payload":payload});
  244. return
  245. }
  246. rtcClientSocket._socket.send(payload,function(client){
  247. });
  248. break;
  249. case 'candidate':
  250. var rtcClientSocket = clientCache.findById(payload.targetId);
  251. if(rtcClientSocket === undefined){
  252. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when candidate',"payload":payload});
  253. return
  254. }
  255. rtcClientSocket._socket.send(payload,function(client){
  256. });
  257. break;
  258. case 'hang-up':
  259. var rtcClientSocket = clientCache.findById(payload.targetId);
  260. if(rtcClientSocket === undefined){
  261. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when hang-up',"payload":payload});
  262. return
  263. }
  264. rtcClientSocket._socket.send(payload,function(client){
  265. });
  266. case 'time-out':
  267. var rtcClientSocket = clientCache.findById(payload.targetId);
  268. if(rtcClientSocket === undefined){
  269. socket.emit('error',{error: 'cannot find this socket client for userid:'+ payload.targetId + ' when time-out',"payload":payload});
  270. return
  271. }
  272. rtcClientSocket._socket.send(payload,function(client){
  273. });
  274. break;
  275. }
  276. }else{
  277. // 其他类型的消息
  278. log.info('Got message from ' + clientCache.findBySocket(socket).userId);
  279. let sessionId = data.session_id;
  280. let message = data.message;
  281. message.timestamp = new Date();
  282. /*sessions.createSession(sessionId, "Let's talk!", 1, ['504a0bcddb1e4e37a0306b39c51900b5', 'cd92414c-5b06-11e6-8344-fa163e8aee56'], function (err, res) {
  283. sessions.saveMessageBySession(sessionId, message);
  284. });*/
  285. sessions.saveMessageBySession(sessionId, message);
  286. }
  287. });
  288. socket.on('error',function(errMsg){
  289. let client = clientCache.findBySocket(socket);
  290. if (client) {
  291. //修改居民在线状态
  292. // users.changUserRedisLoginStatus(original_login_userid,client.clientType,0);
  293. }
  294. log.info(JSON.stringify(errMsg));
  295. socket.emit(errMsg);
  296. });
  297. // 客户端退出
  298. socket.on('logout', function (data) {
  299. let client = clientCache.findBySocket(socket);
  300. if (client) {
  301. //修改居民在线状态
  302. // users.changUserRedisLoginStatus(original_login_userid,client.clientType,0);
  303. log.info('User logout: ' + client.userId);
  304. clientCache.removeByUserId(client.userId);
  305. }
  306. });
  307. // 客户端断开
  308. socket.on('disconnect', function (soc) {
  309. let patientClient = clientCache.findBySocket(socket);
  310. if (patientClient) {
  311. //修改居民在线状态
  312. // users.changUserRedisLoginStatus(original_login_userid,client.clientType,0);
  313. log.info("User disconnect: ", patientClient.userId);
  314. clientCache.removeByUserSocket(socket);
  315. }
  316. });
  317. socket.emit('welcome', {message: 'Welcome to connect IM server, please login.'});
  318. });
  319. }
  320. }
  321. module.exports = SocketHandler;