socket.io
Thu Nov 28 2024 02:27:42 GMT+0000 (Coordinated Universal Time)
Saved by @khainguyenhm
/* eslint-disable class-methods-use-this */ /* eslint no-console:0 */ // import logHandler from './logHandler'; import { Auth } from '@aws-amplify/auth'; import _ from 'lodash'; import io from 'socket.io-client'; import { EMITTER_CONSTANTS } from '../ConstantsV2'; import AppConstant from '../ConstantsV2/appFlowActions'; import { logError } from '../LayoutV2/Reports/AiEditReport/handler'; import CONFIG from '../config/config'; import auth from './auth'; import emitter from './eventEmitter'; class SocketClient { constructor() { this.isConnected = false; this.isLazyLoading = false; this.rooms = []; this.intervalRoom = null; this.queueECGEvent = []; this.queueNewEvent = []; this.queueReportUpdate = []; this.roomUsersEvent = []; this.timeOutRoomEvent = undefined; this.intervalJoinRoomEvent = null; this.queueRoomEvent = []; this.roomUsersReport = []; this.timeOutRoomReport = undefined; this.intervalJoinRoomReport = null; this.queueRoomReport = []; this.timeOutOverviewtUpdate = undefined; this.queueOverviewUpdate = []; } getAuth = async () => { const accessToken = auth.isLoginWithMicrosoftAccount() ? (await Auth.currentSession()).getAccessToken().getJwtToken() : auth.token(); auth.setOriginalToken(accessToken); return { accessToken, }; }; connectToServer = async () => { try { if (!this.socket) { this.socket = io(CONFIG.SOCKET, { forceNew: true, transports: ['websocket'], auth: async cb => cb(await this.getAuth()), // Prevent disconnect socket before unload to send close event to server closeOnBeforeunload: false, }); this.socket.on('connect', this.connectListener); } } catch (error) { logError('Failed to connect socket: ', error); this.disconnectSocket(); } }; connectListener = () => { this.isConnected = true; auth.setSocketId(this.socket?.id); this.socket.off('reconnect'); this.socket.on('disconnect', this.disconnectListener); // this.socket.on('studyEvent', this.studyEventListener); // this.socket.on('deviceEvent', this.deviceEventListener); // this.socket.on('lastSync', this.lastSyncListener); // this.socket.on('studyUpdated', this.studyUpdatedListener); // this.socket.on('studyDeleted', this.studyDeletedListener); // this.socket.on('inbox', this.inboxListener); this.socket.on('roomUsers', this.roomUsersListener); this.socket.on('KickClientsByToken', this.kickClientsByTokenListener); this.socket.on('KickClientsByUsername', this.kickClientsByUsernameListener); this.socket.on('newSession', this.newSessionListener); if (auth.isCallCenter()) { // this.socket.on('isPreparingFullData', this.isPreparingFullDataListener); // this.socket.on('newEvent', this.newEventListener); // this.socket.on('multipleEventsClosed', this.multipleEventsClosedListener); // this.socket.on('facilityUpdated', this.facilityUpdatedListener); // this.socket.on('bucketChanged', this.bucketChangedListener); // this.socket.on('moreStudies', this.moreStudiesListener); this.socket.on('eventUpdated', this.eventUpdatedListener); this.socket.on('reportUpdated', this.reportUpdatedListener); this.socket.on('groupUpdated', this.groupUpdatedListener); this.socket.on('profileReady', this.profileReadyListener); this.socket.on('beatsUpdated', this.beatsUpdatedListener); this.socket.on('eventsUpdated', this.eventsUpdatedListener); this.socket.on('dailySummaryUpdated', this.dailySummaryUpdatedListener); this.socket.on('afibHrSummaryUpdated', this.afibHrSummaryUpdatedListener); this.socket.on('holterProfileUpdated', this.holterProfileUpdatedListener); this.socket.on('technicianCommentsUpdated', this.technicianCommentsUpdatedListener); this.socket.on('rrCellsReviewed', this.rrCellsReviewedListener); this.socket.on('commandProgressUpdated', this.commandProgressUpdatedListener); this.socket.on('commandExecuted', this.commandExecutedListener); this.socket.on('commandPending', this.commandPendingListener); this.socket.on('rrHeatMapUpdated', this.rrHeatMapUpdatedListener); this.socket.on('aiProcessSaved', this.aiProcessSavedListener); this.socket.on('migrateAiData', this.migrateAiDataListener); this.socket.on('reCapturedEvents', this.reCapturedEventsListener); } //* Test socket // setTimeout(() => { // emitter.emit(EMITTER_CONSTANTS.COMMAND_PENDING, { // messageId: '65857578925735af4701e5ad', // command: 'update-beats', // }); // }, 10000); // setTimeout(() => { // emitter.emit(EMITTER_CONSTANTS.COMMAND_EXECUTED, { // messageId: '65857578925735af4701e5ad', // command: 'update-beats', // isSuccess: true, // }); // }, 11000); }; disconnectListener = (error) => { console.log('socket io - on disconnect:', error); // emitter.emit(EMITTER_CONSTANTS.LOST_CONNECTION, CONNECTION_TYPE.SOCKET); // alert('Sorry for the inconvenience!\nThe system ran into a problem and needs to reload a page.'); // window.location.reload(); this.isConnected = false; this.socket.io.on('reconnect', this.reconnectListener); this.socket.off('connect'); this.socket.off('disconnect'); // this.socket.off('studyEvent'); // this.socket.off('deviceEvent'); // this.socket.off('lastSync'); // this.socket.off('studyUpdated'); // this.socket.off('studyDeleted'); // this.socket.off('inbox'); this.socket.off('roomUsers'); this.socket.off('KickClientsByToken'); this.socket.off('KickClientsByUsername'); this.socket.off('newSession'); if (auth.isCallCenter()) { // this.socket.off('isPreparingFullData'); // this.socket.off('newEvent'); // this.socket.off('multipleEventsClosed'); // this.socket.off('facilityUpdated'); // this.socket.off('bucketChanged'); // this.socket.off('moreStudies'); this.socket.off('eventUpdated'); this.socket.off('reportUpdated'); this.socket.off('groupUpdated'); this.socket.off('profileReady'); this.socket.off('beatsUpdated'); this.socket.off('eventsUpdated'); this.socket.off('dailySummaryUpdated'); this.socket.off('afibHrSummaryUpdated'); this.socket.off('holterProfileUpdated'); this.socket.off('technicianCommentsUpdated'); this.socket.off('rrCellsReviewed'); this.socket.off('commandProgressUpdated'); this.socket.off('commandExecuted'); this.socket.off('commandPending'); this.socket.off('rrHeatMapUpdated'); this.socket.off('aiProcessSaved'); this.socket.off('migrateAiData'); } if (error && error.trim() === 'io server disconnect') { window.isSessionExpired = true; emitter.emit(EMITTER_CONSTANTS.EXPIRED_TOKEN, 'request'); this.socket = null; } // if (error && error.trim() === 'ping timeout' && !auth.token()) { // this.disconnectSocket(); // this.socket = null; // } // if (error && error.trim() === 'io server disconnect') { // emitter.emit(EMITTER_CONSTANTS.EXPIRED_TOKEN, 'request'); // this.socket = null; // } }; reconnectListener = () => { console.log('on reconnect'); this.socket.on('connect', this.connectListener); // window.location.reload(); // Remove duplicate data const uniqRooms = _.uniqWith(this.rooms, _.isEqual); console.log('uniqRooms', uniqRooms); _.forEach(uniqRooms, (room) => { const { name, id } = room; switch (name) { case 'joinReportRoom': { this.sendJoinReportRoom(id); break; } default: { this.emitIntervalEvent(name, id); break; } } }); }; eventUpdatedListener = (msg) => { console.log('socket io - eventUpdatedListener', msg); if (msg.study?._id) { this.addQueueECGEventUpdate(msg.study?._id); } emitter.emit(EMITTER_CONSTANTS.UPDATE_EVENT_ECG, msg); if (auth.isCallCenter()) { this.addQueueHandleUpdateReport({ type: 'eventUpdated', data: msg }); } }; reportUpdatedListener = (msg) => { console.log('socket io - reportUpdatedListener', msg); emitter.emit(EMITTER_CONSTANTS.REPORT_UPDATED, msg); if (auth.isCallCenter()) { this.addQueueHandleUpdateReport({ type: 'reportUpdated', data: msg }); if (auth.isCallCenterSupervisor() || auth.isCallCenterQaLeader()) { this.addQueueHandleUpdateOverview({ type: 'reportUpdated', data: msg }); } } }; migrateAiDataListener = (msg) => { console.log('socket io - migrateAiDataListener', msg); emitter.emit(EMITTER_CONSTANTS.MIGRATE_AI_DATA_VER1_TO_VER2, msg); }; newSessionListener = (msg) => { console.log('socket io - newSessionListener', msg); emitter.emit(EMITTER_CONSTANTS.NEW_SESSION, msg); }; groupUpdatedListener = (msg) => { console.log('socket io - groupUpdatedListener', msg); emitter.emit(EMITTER_CONSTANTS.GROUP_UPDATED, msg); }; profileReadyListener = (msg) => { console.log('socket io - profileReadyListener', msg); emitter.emit(EMITTER_CONSTANTS.PROFILE_READY, msg); }; beatsUpdatedListener = (msg) => { console.log('socket io - beatsUpdatedListener', msg); // logHandler.addLog('beatsUpdated', msg); emitter.emit(EMITTER_CONSTANTS.BEATSUPDATED_EVENT, msg); }; eventsUpdatedListener = (msg) => { console.log('socket io - eventsUpdatedListener', msg); // logHandler.addLog('eventsUpdated', msg); emitter.emit(EMITTER_CONSTANTS.EVENTSUPDATED_EVENT, msg); }; afibHrSummaryUpdatedListener = (msg) => { console.log('socket io - afibHrSummaryUpdatedListener', msg); // logHandler.addLog('afibHrSummaryUpdated', msg); emitter.emit(EMITTER_CONSTANTS.AFIB_HR_SUMMARY_UPDATED, msg); }; dailySummaryUpdatedListener = (msg) => { console.log('socket io - dailySummaryUpdatedListener', msg); // logHandler.addLog('dailySummaryUpdated', msg); emitter.emit(EMITTER_CONSTANTS.DAILY_SUMMARY_UPDATED, msg); }; holterProfileUpdatedListener = (msg) => { console.log('socket io - holterProfileUpdatedListener', msg); emitter.emit(EMITTER_CONSTANTS.HOLTER_PROFILE_UPDATED, msg); }; technicianCommentsUpdatedListener = (msg) => { console.log('socket io - technicianCommentsUpdatedListener', msg); emitter.emit(EMITTER_CONSTANTS.TECHNICIAN_COMMENT_UPDATED, msg); }; rrCellsReviewedListener = (msg) => { console.log('socket io - rrCellsReviewedListener', msg); // logHandler.addLog('rrCellsReviewed', msg); emitter.emit(EMITTER_CONSTANTS.RR_CELL_REVIEWED, msg); }; commandProgressUpdatedListener = (msg) => { console.log('socket io - commandProgressUpdatedListener', msg); emitter.emit(EMITTER_CONSTANTS.COMMAND_PROGRESS_UPDATED, msg); }; commandExecutedListener = (msg) => { console.log('socket io - commandExecutedListener', msg); // logHandler.addLog('commandExecuted', msg); // logHandler.sendLog(); emitter.emit(EMITTER_CONSTANTS.COMMAND_EXECUTED, msg); }; commandPendingListener = (msg) => { console.log('socket io - commandPendingListener', msg); // logHandler.addLog('commandPending', msg); emitter.emit(EMITTER_CONSTANTS.COMMAND_PENDING, msg); }; rrHeatMapUpdatedListener = (msg) => { console.log('socket io - rrHeatMapUpdatedListener', msg); // logHandler.addLog('rrHeatMapUpdated', msg); emitter.emit(EMITTER_CONSTANTS.RR_HEATMAP_UPDATED, msg); }; aiProcessSavedListener = (msg) => { console.log('socket io - aiProcessSavedListener', msg); // logHandler.addLog('aiProcessSaved', msg); // logHandler.sendLog(); emitter.emit(EMITTER_CONSTANTS.AI_PROCESS_SAVED, msg); }; reCapturedEventsListener = async (msg) => { console.log('socket io - reCapturedEventsListener', msg); emitter.emit(EMITTER_CONSTANTS.RE_CAPTURE_EVENTS, msg); }; roomUsersListener = (msg) => { console.log('socket io - roomUsersListener', msg); // logHandler.addLog('roomUsers', msg); if (msg.roomType === 'Event') { this.roomUsersEvent.push(msg); } else if (msg.roomType === 'Report') { this.roomUsersReport.push(msg); } if (!this.timeOutRoomEvent) { this.timeOutRoomEvent = setTimeout(() => { if (this.roomUsersEvent.length > 0) { emitter.emit(EMITTER_CONSTANTS.EVENT_ROOM_USER, this.roomUsersEvent.splice(0, this.roomUsersEvent.length)); } if (this.roomUsersReport.length > 0) { emitter.emit(EMITTER_CONSTANTS.REPORT_ROOM_USER, this.roomUsersReport.splice(0, this.roomUsersReport.length)); } this.timeOutRoomEvent = undefined; }, 1000); } }; kickClientsByTokenListener = (msg) => { console.log('socket io - kickClientsByTokenListener', msg); emitter.emit(AppConstant.LOGOUT_REQUEST, 'request'); }; kickClientsByUsernameListener = (msg) => { console.log('socket io - kickClientsByUsernameListener', msg); emitter.emit(AppConstant.LOGOUT_REQUEST, 'request'); }; emitIntervalEvent = (status, id) => { console.log('EMITEVENT', status, id, this.isConnected); if (this.isConnected) { // console.log(`${this.TAG} ${status} `, id); this.socket.emit(status, id); } else { const interval = setInterval(() => { // console.log(`${this.TAG} ${status} `, id); if (this.isConnected) { this.socket.emit(status, id); clearInterval(interval); } if (!auth.token()) { clearInterval(interval); } }, 1000); } }; handleStoreRooms = (name, id) => { if (!_.some(this.rooms, x => x.id === id)) { this.rooms.push({ name, id }); } }; emitRoom = (id) => { if (id && id !== 'undefined') { this.handleStoreRooms('room', id); this.emitIntervalEvent('room', id); } }; addQueueECGEventUpdate = (studyId, msg = {}) => { this.queueECGEvent.push(studyId); if (!_.isEmpty(msg)) { this.queueNewEvent.push({ id: msg.id, stripImgs: msg.stripImgs }); } if (!this.timeOutEventUpdate) { this.timeOutEventUpdate = setTimeout(() => { this.timeOutEventUpdate = undefined; emitter.emit(EMITTER_CONSTANTS.UPDATE_TOTAL_EVENTS, this.queueECGEvent.splice(0, this.queueECGEvent.length)); if (this.queueNewEvent.length > 0) { emitter.emit(EMITTER_CONSTANTS.UPDATE_NEW_EVENT_ECG, this.queueNewEvent.splice(0, this.queueNewEvent.length)); } }, 5000); } }; addQueueHandleUpdateReport = (msg) => { this.queueReportUpdate.push(msg); if (!this.timeOutReportUpdate) { this.timeOutReportUpdate = setTimeout(() => { this.timeOutReportUpdate = undefined; if (this.updateReportReminder) { console.log('this.queueReportUpdate', this.queueReportUpdate); this.updateReportReminder(this.queueReportUpdate.splice(0, this.queueReportUpdate.length)); } }, 1000); } }; addQueueHandleUpdateOverview = (msg) => { this.queueOverviewUpdate.push(msg); if (!this.timeOutOverviewtUpdate) { this.timeOutOverviewtUpdate = setTimeout(() => { this.timeOutOverviewtUpdate = undefined; emitter.emit(EMITTER_CONSTANTS.UPDATE_OVERVIEW, this.queueOverviewUpdate.splice(0, this.queueOverviewUpdate.length)); }, 15000); } }; sendMessageToServer(event, data) { console.log('sendMessageToServer ', event, data); this.socket.emit(event, data); } // send join event room sendJoinEventRoom(room, isPreview = false) { const msg = { room, isPreview, }; this.queueRoomEvent.push(msg); if (this.isConnected) { this.socket.emit('joinEventRoom', msg); } else if (!this.intervalJoinRoomEvent) { this.intervalJoinRoomEvent = setInterval(() => { if (this.isConnected) { const datas = _.assign([], this.queueRoomEvent); this.queueRoomEvent.splice(0, datas.length); _.forEach(datas, (e) => { this.socket.emit('joinEventRoom', e); }); clearInterval(this.intervalJoinRoomEvent); this.intervalJoinRoomEvent = null; } }, 1000); } } // send join report room sendJoinReportRoom(room, isPreview = false) { const msg = { room, isPreview, }; this.queueRoomReport.push(msg); if (this.isConnected) { console.log('[ ==> ] sendJoinReportRoom connected', msg); this.handleStoreRooms('joinReportRoom', msg.room); this.socket.emit('joinReportRoom', msg); } else if (!this.intervalJoinRoomReport) { this.intervalJoinRoomReport = setInterval(() => { if (this.isConnected) { const datas = _.assign([], this.queueRoomReport); this.queueRoomReport.splice(0, datas.length); // Remove duplicate data const uniqDatas = _.uniqWith(datas, _.isEqual); _.forEach(uniqDatas, (e) => { console.log('[ ==> ] sendJoinReportRoom', e); this.handleStoreRooms('joinReportRoom', e.room); this.socket.emit('joinReportRoom', e); }); clearInterval(this.intervalJoinRoomReport); this.intervalJoinRoomReport = null; } }, 1000); } } sendLeaveReportRoom(room, isPreview = false) { const msg = { room, isPreview, }; // *: Only use interval for emiting room // this.emitIntervalEvent('leaveReportRoom', msg); if (this.socket && this.isConnected) { console.log('[ ==> ] sendLeaveReportRoom', msg); _.remove(this.rooms, x => x.id === msg.room); this.socket.emit('leaveReportRoom', msg); } } sendLeaveEventRoom(room, isPreview = false) { const msg = { room, isPreview, }; if (this.socket && this.isConnected) { _.remove(this.rooms, x => x.id === msg.room); this.socket.emit('leaveEventRoom', msg); } } disconnectSocket() { console.log('socket io disconnect', this.socket); if (this.socket) { this.socket.disconnect(); } this.socket = null; this.rooms.length = 0; } } const staticSocket = new SocketClient(); export default staticSocket;
socket old
Comments