@resolveio/server-lib 9.0.32 → 9.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/client-server-app.js +7 -48
  2. package/client-server-app.js.map +1 -1
  3. package/collections/app-status.collection.js +8 -11
  4. package/collections/app-status.collection.js.map +1 -1
  5. package/collections/app-version.collection.js +8 -11
  6. package/collections/app-version.collection.js.map +1 -1
  7. package/collections/counter.collection.js +8 -11
  8. package/collections/counter.collection.js.map +1 -1
  9. package/collections/cron-job-history.collection.js +9 -12
  10. package/collections/cron-job-history.collection.js.map +1 -1
  11. package/collections/cron-job.collection.js +8 -11
  12. package/collections/cron-job.collection.js.map +1 -1
  13. package/collections/email-history.collection.js +8 -11
  14. package/collections/email-history.collection.js.map +1 -1
  15. package/collections/email-verified.collection.js +9 -12
  16. package/collections/email-verified.collection.js.map +1 -1
  17. package/collections/file.collection.js +8 -11
  18. package/collections/file.collection.js.map +1 -1
  19. package/collections/flag.collection.js +8 -11
  20. package/collections/flag.collection.js.map +1 -1
  21. package/collections/log-method-latency.collection.js +11 -14
  22. package/collections/log-method-latency.collection.js.map +1 -1
  23. package/collections/log-subscription.collection.js +13 -16
  24. package/collections/log-subscription.collection.js.map +1 -1
  25. package/collections/log.collection.js +16 -19
  26. package/collections/log.collection.js.map +1 -1
  27. package/collections/logged-in-users.collection.js +9 -12
  28. package/collections/logged-in-users.collection.js.map +1 -1
  29. package/collections/method-call.collection.js +10 -13
  30. package/collections/method-call.collection.js.map +1 -1
  31. package/collections/method-response.collection.js +10 -13
  32. package/collections/method-response.collection.js.map +1 -1
  33. package/collections/monitor-cpu.collection.js +13 -16
  34. package/collections/monitor-cpu.collection.js.map +1 -1
  35. package/collections/monitor-https-inbound.collection.js +13 -16
  36. package/collections/monitor-https-inbound.collection.js.map +1 -1
  37. package/collections/monitor-https-outbound.collection.js +15 -18
  38. package/collections/monitor-https-outbound.collection.js.map +1 -1
  39. package/collections/monitor-memory.collection.js +12 -15
  40. package/collections/monitor-memory.collection.js.map +1 -1
  41. package/collections/monitor-mongo.collection.js +12 -15
  42. package/collections/monitor-mongo.collection.js.map +1 -1
  43. package/collections/notification.collection.js +8 -11
  44. package/collections/notification.collection.js.map +1 -1
  45. package/collections/queue-flag.collection.js +9 -12
  46. package/collections/queue-flag.collection.js.map +1 -1
  47. package/collections/queue-method.collection.js +9 -12
  48. package/collections/queue-method.collection.js.map +1 -1
  49. package/collections/queue-response.collection.js +9 -12
  50. package/collections/queue-response.collection.js.map +1 -1
  51. package/collections/report-builder-dashboard-builder.collection.js +10 -13
  52. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  53. package/collections/report-builder-library.collection.js +11 -14
  54. package/collections/report-builder-library.collection.js.map +1 -1
  55. package/collections/report-builder-report.collection.js +11 -14
  56. package/collections/report-builder-report.collection.js.map +1 -1
  57. package/collections/user-group.collection.js +11 -14
  58. package/collections/user-group.collection.js.map +1 -1
  59. package/collections/user-guide.collection.js +8 -11
  60. package/collections/user-guide.collection.js.map +1 -1
  61. package/collections/user.collection.js +12 -15
  62. package/collections/user.collection.js.map +1 -1
  63. package/cron/cron.js +25 -25
  64. package/cron/cron.js.map +1 -1
  65. package/fixtures/cron-jobs.js +30 -80
  66. package/fixtures/cron-jobs.js.map +1 -1
  67. package/fixtures/init.js +9 -59
  68. package/fixtures/init.js.map +1 -1
  69. package/http/auth.js +344 -460
  70. package/http/auth.js.map +1 -1
  71. package/http/health.js +1 -5
  72. package/http/health.js.map +1 -1
  73. package/http/home.js +7 -11
  74. package/http/home.js.map +1 -1
  75. package/index.js +36 -98
  76. package/index.js.map +1 -1
  77. package/managers/cron.manager.js +78 -157
  78. package/managers/cron.manager.js.map +1 -1
  79. package/managers/method.manager.js +323 -303
  80. package/managers/method.manager.js.map +1 -1
  81. package/managers/mongo.manager.d.ts +14 -14
  82. package/managers/mongo.manager.js +794 -865
  83. package/managers/mongo.manager.js.map +1 -1
  84. package/managers/monitor.manager.js +171 -254
  85. package/managers/monitor.manager.js.map +1 -1
  86. package/managers/queue-method.manager.js +69 -166
  87. package/managers/queue-method.manager.js.map +1 -1
  88. package/managers/subscription.manager.js +515 -708
  89. package/managers/subscription.manager.js.map +1 -1
  90. package/methods/accounts.js +111 -183
  91. package/methods/accounts.js.map +1 -1
  92. package/methods/aws.js +156 -262
  93. package/methods/aws.js.map +1 -1
  94. package/methods/cloudconvert.js +100 -180
  95. package/methods/cloudconvert.js.map +1 -1
  96. package/methods/collections.js +114 -530
  97. package/methods/collections.js.map +1 -1
  98. package/methods/counters.js +29 -79
  99. package/methods/counters.js.map +1 -1
  100. package/methods/cron-jobs.js +819 -884
  101. package/methods/cron-jobs.js.map +1 -1
  102. package/methods/flags.js +1 -5
  103. package/methods/flags.js.map +1 -1
  104. package/methods/logs.js +258 -313
  105. package/methods/logs.js.map +1 -1
  106. package/methods/monitor.js +289 -348
  107. package/methods/monitor.js.map +1 -1
  108. package/methods/pdf.js +341 -340
  109. package/methods/pdf.js.map +1 -1
  110. package/methods/report-builder.js +565 -657
  111. package/methods/report-builder.js.map +1 -1
  112. package/methods/support.js +67 -185
  113. package/methods/support.js.map +1 -1
  114. package/models/app-status.model.js +1 -2
  115. package/models/app-version.model.js +1 -2
  116. package/models/billing-logged-in-users.model.js +1 -2
  117. package/models/collection-document.model.js +1 -2
  118. package/models/counter.model.js +1 -2
  119. package/models/cron-job-history.model.js +1 -2
  120. package/models/cron-job.model.js +1 -2
  121. package/models/dialog.model.js +1 -2
  122. package/models/email-history.model.js +1 -2
  123. package/models/email-verified.model.js +1 -2
  124. package/models/file.model.js +1 -2
  125. package/models/flag.model.js +1 -2
  126. package/models/log-method-latency.model.js +1 -2
  127. package/models/log-subscription.model.js +1 -2
  128. package/models/log.model.js +1 -2
  129. package/models/logged-in-users.model.js +1 -2
  130. package/models/method-call.model.js +1 -2
  131. package/models/method-response.model.js +1 -2
  132. package/models/method.model.js +1 -2
  133. package/models/monitor-cpu.model.js +1 -2
  134. package/models/monitor-https-inbound.model.js +1 -2
  135. package/models/monitor-https-outbound.model.js +1 -2
  136. package/models/monitor-memory.model.js +1 -2
  137. package/models/monitor-mongo.model.js +1 -2
  138. package/models/notification.model.js +1 -2
  139. package/models/pagination.model.js +2 -5
  140. package/models/pagination.model.js.map +1 -1
  141. package/models/permission.model.js +1 -2
  142. package/models/queue-method.model.js +1 -2
  143. package/models/queue-response.model.js +1 -2
  144. package/models/report-builder-dashboard-builder.model.js +1 -2
  145. package/models/report-builder-library.model.js +1 -2
  146. package/models/report-builder-report.model.js +1 -2
  147. package/models/report-builder.model.js +1 -2
  148. package/models/select-data-label.model.js +1 -2
  149. package/models/server-response.model.js +1 -2
  150. package/models/subscription.model.js +1 -2
  151. package/models/support-ticket.model.js +1 -2
  152. package/models/user-group.model.js +1 -2
  153. package/models/user-guide.model.js +1 -2
  154. package/models/user.model.js +1 -2
  155. package/package.json +1 -1
  156. package/public_api.js +70 -82
  157. package/public_api.js.map +1 -1
  158. package/publications/app-status.js +4 -8
  159. package/publications/app-status.js.map +1 -1
  160. package/publications/app-version.js +4 -8
  161. package/publications/app-version.js.map +1 -1
  162. package/publications/cron-jobs.js +9 -13
  163. package/publications/cron-jobs.js.map +1 -1
  164. package/publications/files.js +11 -15
  165. package/publications/files.js.map +1 -1
  166. package/publications/flags.js +7 -11
  167. package/publications/flags.js.map +1 -1
  168. package/publications/logs.js +31 -35
  169. package/publications/logs.js.map +1 -1
  170. package/publications/method-calls.js +4 -8
  171. package/publications/method-calls.js.map +1 -1
  172. package/publications/method-responses.js +4 -8
  173. package/publications/method-responses.js.map +1 -1
  174. package/publications/notifications.js +4 -8
  175. package/publications/notifications.js.map +1 -1
  176. package/publications/report-builder-dashboard-builders.js +8 -12
  177. package/publications/report-builder-dashboard-builders.js.map +1 -1
  178. package/publications/report-builder-libraries.js +16 -66
  179. package/publications/report-builder-libraries.js.map +1 -1
  180. package/publications/report-builder-reports.js +17 -21
  181. package/publications/report-builder-reports.js.map +1 -1
  182. package/publications/super-admin.js +3 -7
  183. package/publications/super-admin.js.map +1 -1
  184. package/publications/user-groups.js +4 -8
  185. package/publications/user-groups.js.map +1 -1
  186. package/publications/user-guides.js +4 -8
  187. package/publications/user-guides.js.map +1 -1
  188. package/server-app.js +393 -534
  189. package/server-app.js.map +1 -1
  190. package/util/common.js +55 -92
  191. package/util/common.js.map +1 -1
  192. package/util/schema-report-builder.js +76 -134
  193. package/util/schema-report-builder.js.map +1 -1
package/server-app.js CHANGED
@@ -1,77 +1,31 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __spreadArrays = (this && this.__spreadArrays) || function () {
39
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
40
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
41
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
42
- r[k] = a[j];
43
- return r;
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- var http_1 = require("http");
47
- var express = require("express");
48
- var bodyParser = require("body-parser");
49
- var xmlParser = require("express-xml-bodyparser");
50
- var passport = require("passport");
51
- var passportlocal = require("passport-local");
52
- var WebSocket = require("ws");
53
- var jwt = require("jsonwebtoken");
54
- var uuid = require("uuid/v4");
55
- var SegfaultHandler = require("segfault-handler");
56
- var moment = require("moment");
57
- var common_1 = require("./util/common");
58
- var mongo_manager_1 = require("./managers/mongo.manager");
59
- var cron_manager_1 = require("./managers/cron.manager");
60
- var method_manager_1 = require("./managers/method.manager");
61
- var subscription_manager_1 = require("./managers/subscription.manager");
62
- var queue_method_manager_1 = require("./managers/queue-method.manager");
63
- var monitor_manager_1 = require("./managers/monitor.manager");
64
- var method_call_collection_1 = require("./collections/method-call.collection");
65
- var method_response_collection_1 = require("./collections/method-response.collection");
66
- var log_collection_1 = require("./collections/log.collection");
67
- var log_method_latency_collection_1 = require("./collections/log-method-latency.collection");
68
- var user_collection_1 = require("./collections/user.collection");
69
- var home_1 = require("./http/home");
70
- var auth_1 = require("./http/auth");
71
- var health_1 = require("./http/health");
72
- var ResolveIOMainServer = /** @class */ (function () {
73
- function ResolveIOMainServer(mainServer, monitorAgent, serverConfig, clientRoutes, clientDir, sesMail, standardProgram) {
74
- var _this = this;
1
+ import { createServer } from 'http';
2
+ import * as express from 'express';
3
+ import * as bodyParser from 'body-parser';
4
+ import * as xmlParser from 'express-xml-bodyparser';
5
+ import * as passport from 'passport';
6
+ import * as passportlocal from 'passport-local';
7
+ import * as WebSocket from 'ws';
8
+ import * as jwt from 'jsonwebtoken';
9
+ import * as uuid from 'uuid/v4';
10
+ import * as SegfaultHandler from 'segfault-handler';
11
+ import * as moment from 'moment';
12
+ import { dateReviver, getBinarySize, deepCopy } from './util/common';
13
+ import { objectIdHexString } from './managers/mongo.manager';
14
+ import { CronManager } from './managers/cron.manager';
15
+ import { MethodManager } from './managers/method.manager';
16
+ import { SubscriptionManager } from './managers/subscription.manager';
17
+ import { QueueMethodManager } from './managers/queue-method.manager';
18
+ import { MonitorManager } from './managers/monitor.manager';
19
+ import { MethodCalls } from './collections/method-call.collection';
20
+ import { MethodResponses } from './collections/method-response.collection';
21
+ import { Logs } from './collections/log.collection';
22
+ import { LogMethodLatencies } from './collections/log-method-latency.collection';
23
+ import { Users } from './collections/user.collection';
24
+ import { setupHomeRoutes } from './http/home';
25
+ import { setupAuthRoutes } from './http/auth';
26
+ import { setupHealthRoutes } from './http/health';
27
+ export default class ResolveIOMainServer {
28
+ constructor(mainServer, monitorAgent, serverConfig, clientRoutes, clientDir, sesMail, standardProgram) {
75
29
  this._msgQueue = [];
76
30
  this._msgQueueRunning = false;
77
31
  this.sesMail = false;
@@ -87,105 +41,68 @@ var ResolveIOMainServer = /** @class */ (function () {
87
41
  this._serverStartTime = new Date();
88
42
  this._lastErrorMsg = null;
89
43
  if (serverConfig['ROOT_URL'] !== 'http://localhost:4200') {
90
- this._monitorManager = new monitor_manager_1.MonitorManager(mainServer, monitorAgent, serverConfig);
44
+ this._monitorManager = new MonitorManager(mainServer, monitorAgent, serverConfig);
91
45
  }
92
- process.on('unhandledRejection', function (error, rej) { return __awaiter(_this, void 0, void 0, function () {
93
- var diffTimeSec;
94
- var _this = this;
95
- return __generator(this, function (_a) {
96
- switch (_a.label) {
97
- case 0:
98
- diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
99
- if (!(error && error['name'] === 'MongoError' && error['message'] === 'not master')) return [3 /*break*/, 3];
100
- if (!(diffTimeSec > 60 && !this._lastErrorMsg)) return [3 /*break*/, 2];
101
- this._lastErrorMsg = new Date();
102
- setTimeout(function () {
103
- _this._lastErrorMsg = null;
104
- }, 60000);
105
- return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2))];
106
- case 1:
107
- _a.sent();
108
- _a.label = 2;
109
- case 2:
110
- process.exit(1);
111
- return [3 /*break*/, 7];
112
- case 3:
113
- if (!(error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false')) return [3 /*break*/, 6];
114
- if (!(diffTimeSec > 60 && !this._lastErrorMsg)) return [3 /*break*/, 5];
115
- this._lastErrorMsg = new Date();
116
- setTimeout(function () {
117
- _this._lastErrorMsg = null;
118
- }, 60000);
119
- return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2))];
120
- case 4:
121
- _a.sent();
122
- _a.label = 5;
123
- case 5:
124
- process.exit(1);
125
- return [3 /*break*/, 7];
126
- case 6:
127
- if (error) {
128
- if (error['name'] !== 'StatusError' && error['message'] !== '') {
129
- if (diffTimeSec > 60 && !this._lastErrorMsg) {
130
- this._lastErrorMsg = new Date();
131
- setTimeout(function () {
132
- _this._lastErrorMsg = null;
133
- }, 60000);
134
- this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));
135
- }
136
- }
137
- }
138
- _a.label = 7;
139
- case 7: return [2 /*return*/];
46
+ process.on('unhandledRejection', async (error, rej) => {
47
+ // console.error('Unhandled Rejection at Promise', [error, rej]);
48
+ let diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
49
+ if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {
50
+ if (diffTimeSec > 60 && !this._lastErrorMsg) {
51
+ this._lastErrorMsg = new Date();
52
+ setTimeout(() => {
53
+ this._lastErrorMsg = null;
54
+ }, 60000);
55
+ await this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));
140
56
  }
141
- });
142
- }); });
143
- process.on('uncaughtException', function (error) { return __awaiter(_this, void 0, void 0, function () {
144
- var diffTimeSec;
145
- var _this = this;
146
- return __generator(this, function (_a) {
147
- switch (_a.label) {
148
- case 0:
149
- console.error(error, 'Uncaught Exception thrown');
150
- diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
151
- if (!(diffTimeSec > 60 && !this._lastErrorMsg)) return [3 /*break*/, 2];
57
+ process.exit(1);
58
+ }
59
+ else if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {
60
+ if (diffTimeSec > 60 && !this._lastErrorMsg) {
61
+ this._lastErrorMsg = new Date();
62
+ setTimeout(() => {
63
+ this._lastErrorMsg = null;
64
+ }, 60000);
65
+ await this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));
66
+ }
67
+ process.exit(1);
68
+ }
69
+ else if (error) {
70
+ if (error['name'] !== 'StatusError' && error['message'] !== '') {
71
+ if (diffTimeSec > 60 && !this._lastErrorMsg) {
152
72
  this._lastErrorMsg = new Date();
153
- setTimeout(function () {
154
- _this._lastErrorMsg = null;
73
+ setTimeout(() => {
74
+ this._lastErrorMsg = null;
155
75
  }, 60000);
156
- return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2))];
157
- case 1:
158
- _a.sent();
159
- _a.label = 2;
160
- case 2:
161
- process.exit(1);
162
- return [2 /*return*/];
163
- }
164
- });
165
- }); });
166
- SegfaultHandler.registerHandler('crash.log', function (signal, address, stack) { return __awaiter(_this, void 0, void 0, function () {
167
- var diffTimeSec;
168
- return __generator(this, function (_a) {
169
- switch (_a.label) {
170
- case 0:
171
- // Do what you want with the signal, address, or stack (array)
172
- // This callback will execute before the signal is forwarded on.
173
- console.log('Segment Fault Detected');
174
- console.log('Signal', JSON.stringify(signal, null, 2));
175
- console.log('Address', JSON.stringify(address, null, 2));
176
- console.log('Stack', JSON.stringify(stack, null, 2));
177
- diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
178
- if (!(diffTimeSec > 60 && !this._lastErrorMsg)) return [3 /*break*/, 2];
179
- return [4 /*yield*/, this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Segfault - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([signal, address, stack], null, 2))];
180
- case 1:
181
- _a.sent();
182
- _a.label = 2;
183
- case 2:
184
- process.exit(1);
185
- return [2 /*return*/];
76
+ this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));
77
+ }
186
78
  }
187
- });
188
- }); });
79
+ }
80
+ });
81
+ process.on('uncaughtException', async (error) => {
82
+ console.error(error, 'Uncaught Exception thrown');
83
+ let diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
84
+ if (diffTimeSec > 60 && !this._lastErrorMsg) {
85
+ this._lastErrorMsg = new Date();
86
+ setTimeout(() => {
87
+ this._lastErrorMsg = null;
88
+ }, 60000);
89
+ await this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));
90
+ }
91
+ process.exit(1);
92
+ });
93
+ SegfaultHandler.registerHandler('crash.log', async (signal, address, stack) => {
94
+ // Do what you want with the signal, address, or stack (array)
95
+ // This callback will execute before the signal is forwarded on.
96
+ console.log('Segment Fault Detected');
97
+ console.log('Signal', JSON.stringify(signal, null, 2));
98
+ console.log('Address', JSON.stringify(address, null, 2));
99
+ console.log('Stack', JSON.stringify(stack, null, 2));
100
+ let diffTimeSec = moment().diff(this._serverStartTime, 'seconds');
101
+ if (diffTimeSec > 60 && !this._lastErrorMsg) {
102
+ await this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Segfault - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([signal, address, stack], null, 2));
103
+ }
104
+ process.exit(1);
105
+ });
189
106
  //SegfaultHandler.causeSegfault(); // simulates a buggy native module that dereferences NULL
190
107
  if (this.LOGGER === 'DEBUG') {
191
108
  console.log('Starting ResolveIO Server');
@@ -193,7 +110,7 @@ var ResolveIOMainServer = /** @class */ (function () {
193
110
  // Start express app
194
111
  this._app = express();
195
112
  // Use body parser for http call (login)
196
- this._app.use(bodyParser.json({ limit: '50mb', reviver: common_1.dateReviver }));
113
+ this._app.use(bodyParser.json({ limit: '50mb', reviver: dateReviver }));
197
114
  this._app.use(bodyParser.urlencoded({ limit: '50mb', extended: true, parameterLimit: 1000000 }));
198
115
  this._app.use(xmlParser());
199
116
  // Set port
@@ -226,170 +143,151 @@ var ResolveIOMainServer = /** @class */ (function () {
226
143
  console.log('Setup cors');
227
144
  }
228
145
  // Set up http login route
229
- auth_1.setupAuthRoutes(this, this._app, serverConfig);
230
- health_1.setupHealthRoutes(this._app, serverConfig);
146
+ setupAuthRoutes(this, this._app, serverConfig);
147
+ setupHealthRoutes(this._app, serverConfig);
231
148
  if (serverConfig['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {
232
- home_1.setupHomeRoutes(this, this._app, serverConfig);
149
+ setupHomeRoutes(this, this._app, serverConfig);
233
150
  }
234
151
  if (this.LOGGER === 'DEBUG') {
235
152
  console.log('Setup express routes');
236
153
  }
237
154
  }
238
- ResolveIOMainServer.prototype.getWS = function (id_ws) {
239
- var res = null;
240
- this._wss.clients.forEach(function (ws) {
155
+ getWS(id_ws) {
156
+ let res = null;
157
+ this._wss.clients.forEach((ws) => {
241
158
  if (ws['id_socket'] === id_ws) {
242
159
  res = ws;
243
160
  }
244
161
  });
245
162
  return res;
246
- };
247
- ResolveIOMainServer.prototype.getWSList = function () {
248
- var res = [];
249
- this._wss.clients.forEach(function (ws) {
163
+ }
164
+ getWSList() {
165
+ let res = [];
166
+ this._wss.clients.forEach((ws) => {
250
167
  res.push(ws['id_socket']);
251
168
  });
252
169
  return res;
253
- };
254
- ResolveIOMainServer.prototype.getWSUserList = function () {
255
- var res = [];
256
- this._wss.clients.forEach(function (ws) {
170
+ }
171
+ getWSUserList() {
172
+ let res = [];
173
+ this._wss.clients.forEach((ws) => {
257
174
  res.push(ws['id_user']);
258
175
  });
259
176
  return res;
260
- };
261
- ResolveIOMainServer.prototype.getHTTPServer = function () {
177
+ }
178
+ getHTTPServer() {
262
179
  return this._server;
263
- };
264
- ResolveIOMainServer.prototype.getCronManager = function () {
180
+ }
181
+ getCronManager() {
265
182
  return this._cronManager;
266
- };
267
- ResolveIOMainServer.prototype.getMethodManager = function () {
183
+ }
184
+ getMethodManager() {
268
185
  return this._methodManager;
269
- };
270
- ResolveIOMainServer.prototype.getSubscriptionManager = function () {
186
+ }
187
+ getSubscriptionManager() {
271
188
  return this._subscriptionManager;
272
- };
273
- ResolveIOMainServer.prototype.getQueueManager = function () {
189
+ }
190
+ getQueueManager() {
274
191
  return this._queueManager;
275
- };
276
- ResolveIOMainServer.prototype.getMonitorManager = function () {
192
+ }
193
+ getMonitorManager() {
277
194
  return this._monitorManager;
278
- };
279
- ResolveIOMainServer.prototype.createServer = function () {
280
- var _this = this;
195
+ }
196
+ createServer() {
281
197
  // Start express server
282
- this._server = http_1.createServer(this._app);
198
+ this._server = createServer(this._app);
283
199
  this._server.keepAliveTimeout = 65000;
284
200
  this._server.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`
285
201
  // Start websocket server
286
202
  // Verify client with token before opening socket
287
203
  this._wss = new WebSocket.Server({
288
204
  server: this._server,
289
- verifyClient: function (info, cb) { return __awaiter(_this, void 0, void 0, function () {
290
- var infoData, token;
291
- var _this = this;
292
- return __generator(this, function (_a) {
293
- if (this.LOGGER === 'DEBUG') {
294
- console.log('Verify Client', info, cb);
295
- }
296
- infoData = info.req.headers['sec-websocket-protocol'].split(/,/);
297
- if (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {
298
- cb(false, 401, 'Unauthorized');
299
- }
300
- else {
301
- if (infoData[1]) { //app version
302
- token = infoData[0];
303
- if (!token) {
304
- cb(false, 401, 'Unauthorized');
305
- }
306
- else {
307
- jwt.verify(token, this._serverConfig['JWT_SECRET'], function (err, decoded) { return __awaiter(_this, void 0, void 0, function () {
308
- var user, err_1;
309
- return __generator(this, function (_a) {
310
- switch (_a.label) {
311
- case 0:
312
- if (!err) return [3 /*break*/, 1];
313
- cb(false, 401, 'Unauthorized');
314
- return [3 /*break*/, 5];
315
- case 1:
316
- info.req['id_user'] = decoded['id_user'];
317
- _a.label = 2;
318
- case 2:
319
- _a.trys.push([2, 4, , 5]);
320
- return [4 /*yield*/, user_collection_1.Users.findById(decoded['id_user'])];
321
- case 3:
322
- user = _a.sent();
323
- if (user) {
324
- info.req['user'] = user.fullname;
325
- info.req['user_readonly'] = user.readonly || false;
326
- info.req['doc_user'] = user;
327
- cb(true);
328
- }
329
- else {
330
- cb(false);
331
- }
332
- return [3 /*break*/, 5];
333
- case 4:
334
- err_1 = _a.sent();
335
- cb(false);
336
- return [3 /*break*/, 5];
337
- case 5: return [2 /*return*/];
338
- }
339
- });
340
- }); });
341
- }
205
+ verifyClient: async (info, cb) => {
206
+ if (this.LOGGER === 'DEBUG') {
207
+ console.log('Verify Client', info, cb);
208
+ }
209
+ let infoData = info.req.headers['sec-websocket-protocol'].split(/,/);
210
+ if (info.origin !== this._serverConfig['ROOT_URL'] && info.origin !== this._serverConfig['SEC_ROOT_URL'] && info.origin !== this._serverConfig['RESOLVEIO_URL'] && info.origin !== this._serverConfig['RESOLVEIO_SECONDARY_URL']) {
211
+ cb(false, 401, 'Unauthorized');
212
+ }
213
+ else {
214
+ if (infoData[1]) { //app version
215
+ let token = infoData[0];
216
+ if (!token) {
217
+ cb(false, 401, 'Unauthorized');
342
218
  }
343
219
  else {
344
- cb(false, 401, 'Invalid Version');
220
+ jwt.verify(token, this._serverConfig['JWT_SECRET'], async (err, decoded) => {
221
+ if (err) {
222
+ cb(false, 401, 'Unauthorized');
223
+ }
224
+ else {
225
+ info.req['id_user'] = decoded['id_user'];
226
+ try {
227
+ let user = await Users.findById(decoded['id_user']);
228
+ if (user) {
229
+ info.req['user'] = user.fullname;
230
+ info.req['user_readonly'] = user.readonly || false;
231
+ info.req['doc_user'] = user;
232
+ cb(true);
233
+ }
234
+ else {
235
+ cb(false);
236
+ }
237
+ }
238
+ catch (err) {
239
+ cb(false);
240
+ }
241
+ }
242
+ });
345
243
  }
346
244
  }
347
- return [2 /*return*/];
348
- });
349
- }); }
245
+ else {
246
+ cb(false, 401, 'Invalid Version');
247
+ }
248
+ }
249
+ }
350
250
  });
351
251
  // Start MongoDB Connection
352
252
  this.setUpMongo();
353
- };
354
- ResolveIOMainServer.prototype.setUpMongo = function () {
253
+ }
254
+ setUpMongo() {
355
255
  this.setUpPassport();
356
256
  if (this.LOGGER === 'DEBUG') {
357
257
  console.log('Start Managers');
358
258
  }
359
259
  // Start Managers
360
- this._subscriptionManager = new subscription_manager_1.SubscriptionManager(this, this._wss, this._serverConfig);
361
- this._methodManager = new method_manager_1.MethodManager(this, this._serverConfig, this._clientDir);
362
- this._cronManager = new cron_manager_1.CronManager(this);
363
- this._queueManager = new queue_method_manager_1.QueueMethodManager(this);
260
+ this._subscriptionManager = new SubscriptionManager(this, this._wss, this._serverConfig);
261
+ this._methodManager = new MethodManager(this, this._serverConfig, this._clientDir);
262
+ this._cronManager = new CronManager(this);
263
+ this._queueManager = new QueueMethodManager(this);
364
264
  if (this.LOGGER === 'DEBUG') {
365
265
  console.log('End Managers');
366
266
  }
367
267
  this.listen();
368
- };
369
- ResolveIOMainServer.prototype.setUpPassport = function () {
370
- var _this = this;
371
- if (user_collection_1.Users) {
268
+ }
269
+ setUpPassport() {
270
+ if (Users) {
372
271
  // Set up login passort
373
272
  this._app.use(passport.initialize());
374
273
  // Start user authentication
375
- passport.use(new passportlocal.Strategy(user_collection_1.Users.authenticateStrategy()));
376
- passport.serializeUser(user_collection_1.Users.serializeUser());
377
- passport.deserializeUser(user_collection_1.Users.deserializeUser());
274
+ passport.use(new passportlocal.Strategy(Users.authenticateStrategy()));
275
+ passport.serializeUser(Users.serializeUser());
276
+ passport.deserializeUser(Users.deserializeUser());
378
277
  }
379
278
  else {
380
- setTimeout(function () {
381
- _this.setUpPassport();
279
+ setTimeout(() => {
280
+ this.setUpPassport();
382
281
  }, 1);
383
282
  }
384
- };
283
+ }
385
284
  // Listen to port for websocket
386
- ResolveIOMainServer.prototype.listen = function () {
387
- var _this = this;
388
- this._server.listen(this._port, function () {
389
- console.log('Running server on port %s', _this._port);
285
+ listen() {
286
+ this._server.listen(this._port, () => {
287
+ console.log('Running server on port %s', this._port);
390
288
  });
391
289
  // On websocket connection (already verified)
392
- this._wss.on('connection', function (ws, req) {
290
+ this._wss.on('connection', (ws, req) => {
393
291
  // Get user from token
394
292
  ws['id_user'] = req.id_user;
395
293
  ws['user'] = req.user;
@@ -397,309 +295,270 @@ var ResolveIOMainServer = /** @class */ (function () {
397
295
  ws['doc_user'] = req.doc_user;
398
296
  ws['id_socket'] = uuid();
399
297
  ws['retryCnt'] = 0;
400
- if (_this.LOGGER === 'DEBUG') {
298
+ if (this.LOGGER === 'DEBUG') {
401
299
  console.log('Connection from: ' + req.user);
402
300
  }
403
301
  // Use for keeping connection alive (ping/pong)
404
302
  ws['isAlive'] = true;
405
- ws.on('pong', function () {
303
+ ws.on('pong', () => {
406
304
  ws['isAlive'] = true;
407
305
  ws['pongTime'] = new Date();
408
306
  ws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();
409
- _this._subscriptionManager.loggedInLatency(ws);
307
+ this._subscriptionManager.loggedInLatency(ws);
410
308
  });
411
- ws['versionTimer'] = setTimeout(function () {
412
- _this.unsubscribeWS(ws);
309
+ ws['versionTimer'] = setTimeout(() => {
310
+ this.unsubscribeWS(ws);
413
311
  }, 10000);
414
312
  // On data received (message)
415
- ws.on('message', function (message) { return __awaiter(_this, void 0, void 0, function () {
416
- var parseErrorFound, socketData, data, messageRoute_1, messageDate, messageId, type, subType, pub;
417
- var _a, _b;
418
- var _this = this;
419
- return __generator(this, function (_c) {
420
- if (this.LOGGER === 'DEBUG') {
421
- console.log('Message from: ' + ws['user'], message);
422
- }
423
- parseErrorFound = false;
424
- socketData = null;
425
- try {
426
- socketData = JSON.parse(message, common_1.dateReviver);
313
+ ws.on('message', async (message) => {
314
+ if (this.LOGGER === 'DEBUG') {
315
+ console.log('Message from: ' + ws['user'], message);
316
+ }
317
+ let parseErrorFound = false;
318
+ let socketData = null;
319
+ try {
320
+ socketData = JSON.parse(message, dateReviver);
321
+ }
322
+ catch (e) {
323
+ console.log('Error - JSON.parse', message);
324
+ this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));
325
+ parseErrorFound = true;
326
+ }
327
+ if (!parseErrorFound) {
328
+ let data = deepCopy(socketData);
329
+ if (data[0] === 'ping') {
330
+ if (ws && ws.readyState === ws.OPEN) {
331
+ ws.send('pong', (error) => {
332
+ if (error) {
333
+ console.log('Error on WS: ', error);
334
+ this.unsubscribeWS(ws);
335
+ }
336
+ });
337
+ }
338
+ return;
427
339
  }
428
- catch (e) {
429
- console.log('Error - JSON.parse', message);
430
- this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + this._serverConfig['CLIENT_NAME'], JSON.stringify([message, e]));
431
- parseErrorFound = true;
340
+ let messageRoute = data.shift();
341
+ if (this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b))) && !ws['doc_user'].roles.super_admin) {
342
+ return;
432
343
  }
433
- if (!parseErrorFound) {
434
- data = common_1.deepCopy(socketData);
435
- if (data[0] === 'ping') {
436
- if (ws && ws.readyState === ws.OPEN) {
437
- ws.send('pong', function (error) {
438
- if (error) {
439
- console.log('Error on WS: ', error);
440
- _this.unsubscribeWS(ws);
441
- }
442
- });
443
- }
444
- return [2 /*return*/];
445
- }
446
- messageRoute_1 = data.shift();
447
- if (this._clientRoutes.some(function (a) { return messageRoute_1.includes(a); }) && !ws['doc_user'].roles.groups.some(function (a) { return a.views.some(function (b) { return messageRoute_1.includes(b); }); }) && !ws['doc_user'].roles.super_admin) {
448
- return [2 /*return*/];
449
- }
450
- messageDate = data.shift();
451
- messageId = data.shift();
452
- type = data.shift();
453
- if (type === 'subscription') {
454
- subType = data.shift();
455
- pub = data.shift();
456
- // Subscribe
457
- if (subType === 'sub') {
458
- (_a = this._subscriptionManager).subscribe.apply(_a, __spreadArrays([messageDate, ws, messageId, pub], data));
459
- }
460
- // Unsubscribe
461
- else {
462
- (_b = this._subscriptionManager).unsubscribe.apply(_b, __spreadArrays([messageDate, ws, messageId, pub], data));
463
- }
344
+ let messageDate = data.shift();
345
+ let messageId = data.shift();
346
+ let type = data.shift();
347
+ if (type === 'subscription') {
348
+ let subType = data.shift();
349
+ let pub = data.shift();
350
+ // Subscribe
351
+ if (subType === 'sub') {
352
+ this._subscriptionManager.subscribe(messageDate, ws, messageId, pub, ...data);
464
353
  }
354
+ // Unsubscribe
465
355
  else {
466
- this._msgQueue.splice(0, 0, {
467
- ws: ws,
468
- data: socketData
469
- });
356
+ this._subscriptionManager.unsubscribe(messageDate, ws, messageId, pub, ...data);
470
357
  }
471
358
  }
472
- return [2 /*return*/];
473
- });
474
- }); });
475
- ws.on('close', function () {
476
- _this.unsubscribeWS(ws);
359
+ else {
360
+ this._msgQueue.splice(0, 0, {
361
+ ws: ws,
362
+ data: socketData
363
+ });
364
+ }
365
+ }
477
366
  });
478
- ws.on('error', function (error) {
367
+ ws.on('close', () => {
368
+ this.unsubscribeWS(ws);
369
+ });
370
+ ws.on('error', error => {
479
371
  console.log(error);
480
- _this.unsubscribeWS(ws);
372
+ this.unsubscribeWS(ws);
481
373
  });
482
374
  });
483
375
  // Keep alive timer to ping/pong
484
- setInterval(function () {
485
- _this._wss.clients.forEach(function (ws) {
376
+ setInterval(() => {
377
+ this._wss.clients.forEach((ws) => {
486
378
  if (ws['isAlive'] === false) {
487
379
  ws['retryCnt']++;
488
380
  if (ws['retryCnt'] >= 60) {
489
- _this.unsubscribeWS(ws);
381
+ this.unsubscribeWS(ws);
490
382
  }
491
383
  else {
492
384
  ws['pingTime'] = new Date();
493
- ws.ping(function () { });
385
+ ws.ping(() => { });
494
386
  }
495
387
  }
496
388
  else {
497
389
  ws['retryCnt'] = 0;
498
390
  ws['isAlive'] = false;
499
391
  ws['pingTime'] = new Date();
500
- ws.ping(function () { });
392
+ ws.ping(() => { });
501
393
  }
502
394
  });
503
395
  }, 5000);
504
- setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
505
- var _loop_1, this_1, i;
506
- var _this = this;
507
- return __generator(this, function (_a) {
508
- switch (_a.label) {
509
- case 0:
510
- if (!!this._msgQueueRunning) return [3 /*break*/, 5];
511
- this._msgQueueRunning = true;
512
- _loop_1 = function (i) {
513
- var msg, data, ws, messageRoute, messageDate, messageId, type, method, methodLatencyId, serverRes, query, methodCall, method;
514
- var _a;
515
- return __generator(this, function (_b) {
516
- switch (_b.label) {
517
- case 0:
518
- msg = this_1._msgQueue.pop();
519
- data = msg.data;
520
- ws = msg.ws;
521
- messageRoute = data.shift();
522
- messageDate = data.shift();
523
- messageId = data.shift();
524
- type = data.shift();
525
- if (!(type === 'method')) return [3 /*break*/, 4];
526
- method = data.shift();
527
- if (method === 'setWSAppVersion') {
528
- clearTimeout(ws['versionTimer']);
529
- }
530
- if (method === 'disconnectWSCommand') {
531
- setTimeout(function () {
532
- _this.unsubscribeWS(ws);
533
- }, 1000);
534
- }
535
- if (ws['user_readonly']) {
536
- return [2 /*return*/, "continue"];
537
- }
538
- methodLatencyId = mongo_manager_1.objectIdHexString();
539
- log_method_latency_collection_1.LogMethodLatencies.create({
540
- _id: methodLatencyId,
541
- __v: 0,
542
- date_start: new Date(),
543
- date_end: null,
544
- latency_ms: 0,
545
- method: method
546
- });
547
- if (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'setWSAppVersion' && method !== 'getDrivers') {
548
- log_collection_1.Logs.create({
549
- _id: mongo_manager_1.objectIdHexString(),
550
- type: 'client-request',
551
- collection: '',
552
- id_document: '',
553
- payload: common_1.getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',
554
- method: method,
555
- id_user: ws['id_user'],
556
- user: ws['user'],
557
- messageId: messageId.toString(),
558
- route: messageRoute
559
- });
560
- }
561
- serverRes = {
562
- messageId: messageId,
563
- hasError: false,
564
- data: 'ACK'
565
- };
396
+ setInterval(async () => {
397
+ // console.log(data);
398
+ if (!this._msgQueueRunning) {
399
+ this._msgQueueRunning = true;
400
+ for (let i = this._msgQueue.length - 1; i >= 0; i--) {
401
+ let msg = this._msgQueue.pop();
402
+ let data = msg.data;
403
+ let ws = msg.ws;
404
+ let messageRoute = data.shift();
405
+ let messageDate = data.shift();
406
+ let messageId = data.shift();
407
+ let type = data.shift();
408
+ // Method call
409
+ if (type === 'method') {
410
+ let method = data.shift();
411
+ if (method === 'setWSAppVersion') {
412
+ clearTimeout(ws['versionTimer']);
413
+ }
414
+ if (method === 'disconnectWSCommand') {
415
+ setTimeout(() => {
416
+ this.unsubscribeWS(ws);
417
+ }, 1000);
418
+ }
419
+ if (ws['user_readonly']) {
420
+ continue;
421
+ }
422
+ let methodLatencyId = objectIdHexString();
423
+ LogMethodLatencies.create({
424
+ _id: methodLatencyId,
425
+ __v: 0,
426
+ date_start: new Date(),
427
+ date_end: null,
428
+ latency_ms: 0,
429
+ method: method
430
+ });
431
+ if (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'setWSAppVersion' && method !== 'getDrivers') {
432
+ Logs.create({
433
+ _id: objectIdHexString(),
434
+ type: 'client-request',
435
+ collection: '',
436
+ id_document: '',
437
+ payload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',
438
+ method: method,
439
+ id_user: ws['id_user'],
440
+ user: ws['user'],
441
+ messageId: messageId.toString(),
442
+ route: messageRoute
443
+ });
444
+ }
445
+ let serverRes = {
446
+ messageId: messageId,
447
+ hasError: false,
448
+ data: 'ACK'
449
+ };
450
+ if (ws && ws.readyState === ws.OPEN) {
451
+ ws.send(JSON.stringify(serverRes), (error) => {
452
+ if (error) {
453
+ console.log('Error on WS: ', error);
454
+ this.unsubscribeWS(ws);
455
+ }
456
+ });
457
+ }
458
+ if (this._methodManager._methods[method]) {
459
+ let query = { $and: [
460
+ { id_user: ws['id_user'] },
461
+ { message_id: messageId },
462
+ { date: messageDate }
463
+ ] };
464
+ if (method !== 'updateDocumentOffline' && method !== 'updateDocumentPropsOffline') {
465
+ query.$and.push({ method: method });
466
+ }
467
+ else {
468
+ if (method === 'updateDocumentOffline') {
469
+ query.$and.push({
470
+ $or: [
471
+ { method: method },
472
+ { method: 'updateDocument' }
473
+ ]
474
+ });
475
+ }
476
+ else if (method === 'updateDocumentPropsOffline') {
477
+ query.$and.push({
478
+ $or: [
479
+ { method: method },
480
+ { method: 'updateDocumentProps' }
481
+ ]
482
+ });
483
+ }
484
+ }
485
+ let methodCall = await MethodCalls.findOne(query);
486
+ if (!methodCall) {
487
+ MethodCalls.create({
488
+ _id: objectIdHexString(),
489
+ __v: 0,
490
+ id_user: ws['id_user'],
491
+ message_id: messageId.toString(),
492
+ method: method,
493
+ date: messageDate
494
+ });
495
+ if (this._methodManager._methods[method]) {
496
+ if (this._methodManager._methods[method].skipQueue) {
497
+ this._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);
498
+ }
499
+ else {
500
+ this._queueManager.addMethodToQueue(methodLatencyId, ws['id_socket'], ws['id_user'], ws['user'], messageDate, messageId, method, data);
501
+ }
502
+ }
503
+ else {
504
+ console.log('Could not find method: ' + method);
505
+ }
506
+ }
507
+ else {
508
+ MethodResponses.findOne({ $and: [
509
+ { id_user: ws['id_user'] },
510
+ { message_id: messageId.toString() },
511
+ { method: method },
512
+ { date: messageDate }
513
+ ] }).then(res => {
514
+ if (res) {
566
515
  if (ws && ws.readyState === ws.OPEN) {
567
- ws.send(JSON.stringify(serverRes), function (error) {
516
+ ws.send(JSON.stringify(res.response), (error) => {
568
517
  if (error) {
569
518
  console.log('Error on WS: ', error);
570
- _this.unsubscribeWS(ws);
519
+ this.unsubscribeWS(ws);
571
520
  }
572
521
  });
573
522
  }
574
- if (!this_1._methodManager._methods[method]) return [3 /*break*/, 2];
575
- query = { $and: [
576
- { id_user: ws['id_user'] },
577
- { message_id: messageId },
578
- { date: messageDate }
579
- ] };
580
- if (method !== 'updateDocumentOffline' && method !== 'updateDocumentPropsOffline') {
581
- query.$and.push({ method: method });
582
- }
583
- else {
584
- if (method === 'updateDocumentOffline') {
585
- query.$and.push({
586
- $or: [
587
- { method: method },
588
- { method: 'updateDocument' }
589
- ]
590
- });
591
- }
592
- else if (method === 'updateDocumentPropsOffline') {
593
- query.$and.push({
594
- $or: [
595
- { method: method },
596
- { method: 'updateDocumentProps' }
597
- ]
598
- });
599
- }
600
- }
601
- return [4 /*yield*/, method_call_collection_1.MethodCalls.findOne(query)];
602
- case 1:
603
- methodCall = _b.sent();
604
- if (!methodCall) {
605
- method_call_collection_1.MethodCalls.create({
606
- _id: mongo_manager_1.objectIdHexString(),
607
- __v: 0,
608
- id_user: ws['id_user'],
609
- message_id: messageId.toString(),
610
- method: method,
611
- date: messageDate
612
- });
613
- if (this_1._methodManager._methods[method]) {
614
- if (this_1._methodManager._methods[method].skipQueue) {
615
- (_a = this_1._methodManager).callMethod.apply(_a, __spreadArrays([methodLatencyId, ws, messageDate, messageId, method], data));
616
- }
617
- else {
618
- this_1._queueManager.addMethodToQueue(methodLatencyId, ws['id_socket'], ws['id_user'], ws['user'], messageDate, messageId, method, data);
619
- }
620
- }
621
- else {
622
- console.log('Could not find method: ' + method);
623
- }
624
- }
625
- else {
626
- method_response_collection_1.MethodResponses.findOne({ $and: [
627
- { id_user: ws['id_user'] },
628
- { message_id: messageId.toString() },
629
- { method: method },
630
- { date: messageDate }
631
- ] }).then(function (res) {
632
- if (res) {
633
- if (ws && ws.readyState === ws.OPEN) {
634
- ws.send(JSON.stringify(res.response), function (error) {
635
- if (error) {
636
- console.log('Error on WS: ', error);
637
- _this.unsubscribeWS(ws);
638
- }
639
- });
640
- }
641
- }
642
- }, function (err) { });
643
- }
644
- return [3 /*break*/, 3];
645
- case 2:
646
- console.log('Could not find method: ' + method);
647
- _b.label = 3;
648
- case 3: return [3 /*break*/, 5];
649
- case 4:
650
- if (type === 'methodResponse') {
651
- method = data.shift();
652
- method_response_collection_1.MethodResponses.findOne({ $and: [
653
- { id_user: ws['id_user'] },
654
- { message_id: messageId.toString() },
655
- { method: method },
656
- { date: messageDate }
657
- ] }).then(function (res) {
658
- if (res) {
659
- if (ws && ws.readyState === ws.OPEN) {
660
- ws.send(JSON.stringify(res.response), function (error) {
661
- if (error) {
662
- console.log('Error on WS: ', error);
663
- _this.unsubscribeWS(ws);
664
- }
665
- });
666
- }
667
- }
668
- }, function (err) { });
523
+ }
524
+ }, err => { });
525
+ }
526
+ }
527
+ else {
528
+ console.log('Could not find method: ' + method);
529
+ }
530
+ }
531
+ else if (type === 'methodResponse') {
532
+ let method = data.shift();
533
+ MethodResponses.findOne({ $and: [
534
+ { id_user: ws['id_user'] },
535
+ { message_id: messageId.toString() },
536
+ { method: method },
537
+ { date: messageDate }
538
+ ] }).then(res => {
539
+ if (res) {
540
+ if (ws && ws.readyState === ws.OPEN) {
541
+ ws.send(JSON.stringify(res.response), (error) => {
542
+ if (error) {
543
+ console.log('Error on WS: ', error);
544
+ this.unsubscribeWS(ws);
669
545
  }
670
- _b.label = 5;
671
- case 5: return [2 /*return*/];
546
+ });
672
547
  }
673
- });
674
- };
675
- this_1 = this;
676
- i = this._msgQueue.length - 1;
677
- _a.label = 1;
678
- case 1:
679
- if (!(i >= 0)) return [3 /*break*/, 4];
680
- return [5 /*yield**/, _loop_1(i)];
681
- case 2:
682
- _a.sent();
683
- _a.label = 3;
684
- case 3:
685
- i--;
686
- return [3 /*break*/, 1];
687
- case 4:
688
- this._msgQueueRunning = false;
689
- _a.label = 5;
690
- case 5: return [2 /*return*/];
548
+ }
549
+ }, err => { });
550
+ }
691
551
  }
692
- });
693
- }); }, 10);
694
- };
695
- ResolveIOMainServer.prototype.unsubscribeWS = function (ws) {
552
+ this._msgQueueRunning = false;
553
+ }
554
+ }, 10);
555
+ }
556
+ unsubscribeWS(ws) {
696
557
  this._subscriptionManager.unsubscribeAll(ws);
697
- };
698
- ResolveIOMainServer.prototype.getApp = function () {
558
+ }
559
+ getApp() {
699
560
  return this._app;
700
- };
701
- return ResolveIOMainServer;
702
- }());
703
- exports.default = ResolveIOMainServer;
561
+ }
562
+ }
704
563
 
705
564
  //# sourceMappingURL=server-app.js.map