Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x | /* eslint-disable no-constant-condition */ /* eslint-disable no-console */ /* eslint-disable no-param-reassign */ import crypto from 'crypto'; import APIError from '../../helpers/error'; import { t } from '../../helpers/i18n'; const DEBUG = true; let agentsIo; let agentModel; // Global queue const queueError = {}; const STATUS = { CONNECTED: 'connected', DISCONNECTED: 'disconnected', }; const TIMEOUT_SEND_EVENT = 10000; // 10 seconds const TIMEOUT_QUEUE_PROCESS = 5000; // 5 seconds // Get Sockets const getSockets = async () => { if (agentsIo) { const sockets = await agentsIo.fetchSockets(); return sockets; } return []; }; const getAgentByCode = async (code) => { if (code) { const sockets = await getSockets(); return sockets.find( (socket) => socket.data.dataModel && socket.data.dataModel.code === code ); } return null; }; const sleep = (time = 100) => new Promise((resolve) => { setTimeout(() => resolve(), time); }); const generateUniqueId = () => crypto.randomBytes(16).toString('hex'); // Adiciona na fila para tratar erros de conexao const queueMessage = (socket, data) => { try { const uniqueMessageId = generateUniqueId(); queueError[uniqueMessageId] = { hasError: false, id: uniqueMessageId, socket, data, }; const timeoutError = setTimeout(() => { if (queueError[uniqueMessageId]) { queueError[uniqueMessageId].hasError = true; } }, TIMEOUT_SEND_EVENT); return { timeoutError, uniqueMessageId }; } catch (e) { console.log('queueMessageError', e.message); } return {}; }; // Remove da fila pois recebeu mensagem de retorno callback const queueRemoveMessage = (queueMessageObj = {}) => { try { const { timeoutError, uniqueMessageId } = queueMessageObj; if (timeoutError) clearTimeout(timeoutError); if (uniqueMessageId && queueError[uniqueMessageId]) { delete queueError[uniqueMessageId]; } } catch (e) { console.log('queueRemoveMessageError', e.message); } }; const sendPrinterEvent = (socket, data) => { if (!socket) throw new APIError('', t('BEE3509' /* Agente não localizado! */)); return new Promise((resolve, reject) => { // Adiciona na queue para tratar erros de conexao e reenvio da mensagem const queueMessageObject = queueMessage(socket, data); socket .timeout(TIMEOUT_SEND_EVENT) .emit('printer-event', data, (err, response) => { // Remove da fila pois recebeu retorno queueRemoveMessage(queueMessageObject); if (err) { reject(err); } else { resolve(response); } }); }); }; const disconnectAgent = async (code) => { try { if (code) { const sockets = await getSockets(); const socketFinded = sockets.find( (socket) => socket.data.dataModel && socket.data.dataModel.code === code ); if (socketFinded) socketFinded.disconnect(true); } } catch (e) { console.log('SOCKET AGENT ERROR disconnectAgent => ', e); } return null; }; // Processa a fila de impressao que contem erros const queueProcessLoop = async () => { while (true) { try { Object.entries(queueError).forEach((itemQueue) => { if (itemQueue.hasError) { const { socket, data, id } = itemQueue; // Remove da fila para nao ser reprocessado delete queueError[id]; sendPrinterEvent(socket, data); } }); } catch (e) { console.log('queueProcessLoop', e.message); } await sleep(TIMEOUT_QUEUE_PROCESS); } }; const initialize = async (io, models) => { agentModel = models.Agent; // Initialize disconnect all sockets await agentModel.update( { status: STATUS.DISCONNECTED }, { where: { status: STATUS.CONNECTED } } ); agentModel.afterDestroy((agent) => { disconnectAgent(agent.code); }); agentModel.afterUpdate((agent) => { let bDisconnectAgent = false; if (agent.changed('active') && !agent.active) bDisconnectAgent = true; else if (agent.changed('token')) bDisconnectAgent = true; if (bDisconnectAgent) disconnectAgent(agent.code); }); if (io) { agentsIo = io.of('/agents'); // Authorization Bearer Middleware agentsIo.use(async (socket, next) => { try { const authHeader = socket.handshake.headers.authorization; const code = socket.handshake.headers.appcode || ''; let token = authHeader && authHeader.startsWith('Bearer ') && authHeader.substring(7).trim(); if (token) { const agentModelToken = await agentModel.findOne({ attributes: ['token'], where: { code, token, active: true }, raw: true, }); token = agentModelToken && agentModelToken.token ? agentModelToken.token : null; } if (token) { socket.data.token = token; next(); } else { next(new Error('Invalid token Or Agent Inactived')); } } catch (e) { console.log('SOCKET AGENT ERROR auth => ', e); next(new Error('Invalid token Or Agent Inactived')); } }); // ############################### // Listeners agentsIo.on('connection', (socket) => { if (DEBUG) console.log( '[Agent connected] ', (socket.data && socket.data.dataModel && socket.data.dataModel.code) || socket.id ); socket.on('disconnect', async (/* reason */) => { try { if (DEBUG) console.log( '[Agent disconnected] ', (socket.data && socket.data.dataModel && socket.data.dataModel.code) || socket.id ); await agentModel.update( { status: STATUS.DISCONNECTED }, { where: { token: socket.data.token } } ); } catch (e) { console.log('SOCKET AGENT ERROR disconnect => ', e); } }); socket.on('initialized', async (data) => { try { if (data) { const agentModelToken = await agentModel.findOne({ where: { token: socket.data.token, active: true }, }); await agentModelToken.update({ osData: data, status: STATUS.CONNECTED, }); socket.data.dataModel = agentModelToken.toJSON(); } } catch (e) { console.log('SOCKET AGENT ERROR initialized => ', e); } }); socket.emit('initialized'); }); // Loop de processo para fila com erro de impressao queueProcessLoop(); // ######### } }; export default { initialize, getAgentByCode, sendPrinterEvent, STATUS, }; |