@resolveio/server-lib 3.2.11 → 3.2.12

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 (177) hide show
  1. package/collections/active-subscription.collection.d.ts +7 -0
  2. package/collections/active-subscription.collection.js +68 -0
  3. package/collections/app-status.collection.d.ts +7 -0
  4. package/collections/app-status.collection.js +43 -0
  5. package/collections/app-version.collection.d.ts +7 -0
  6. package/collections/app-version.collection.js +56 -0
  7. package/collections/billing-logged-in-users.collection.d.ts +7 -0
  8. package/collections/billing-logged-in-users.collection.js +73 -0
  9. package/collections/counter.collection.d.ts +9 -0
  10. package/collections/counter.collection.js +73 -0
  11. package/collections/cron-job-history.collection.d.ts +7 -0
  12. package/collections/cron-job-history.collection.js +86 -0
  13. package/collections/cron-job.collection.d.ts +7 -0
  14. package/collections/cron-job.collection.js +89 -0
  15. package/collections/file.collection.d.ts +9 -0
  16. package/collections/file.collection.js +73 -0
  17. package/collections/flag.collection.d.ts +7 -0
  18. package/collections/flag.collection.js +47 -0
  19. package/collections/log.collection.d.ts +7 -0
  20. package/collections/log.collection.js +65 -0
  21. package/collections/logged-in-users.collection.d.ts +7 -0
  22. package/collections/logged-in-users.collection.js +70 -0
  23. package/collections/method-call.collection.d.ts +6 -0
  24. package/collections/method-call.collection.js +44 -0
  25. package/collections/method-response.collection.d.ts +6 -0
  26. package/collections/method-response.collection.js +48 -0
  27. package/collections/notification.collection.d.ts +7 -0
  28. package/collections/notification.collection.js +43 -0
  29. package/collections/queue-flag.collection.d.ts +7 -0
  30. package/collections/queue-flag.collection.js +41 -0
  31. package/collections/queue-method.collection.d.ts +7 -0
  32. package/collections/queue-method.collection.js +119 -0
  33. package/collections/queue-response.collection.d.ts +7 -0
  34. package/collections/queue-response.collection.js +74 -0
  35. package/collections/support-ticket.collection.d.ts +7 -0
  36. package/collections/support-ticket.collection.js +200 -0
  37. package/collections/user.collection.d.ts +9 -0
  38. package/collections/user.collection.js +153 -0
  39. package/cron/cron.d.ts +5 -0
  40. package/cron/cron.js +160 -0
  41. package/fixtures/cron-jobs.d.ts +1 -0
  42. package/fixtures/cron-jobs.js +90 -0
  43. package/fixtures/init.d.ts +1 -0
  44. package/fixtures/init.js +67 -0
  45. package/http/auth.d.ts +2 -0
  46. package/http/auth.js +468 -0
  47. package/http/health.d.ts +1 -0
  48. package/http/health.js +8 -0
  49. package/index.d.ts +16 -0
  50. package/index.js +125 -0
  51. package/managers/cron.manager.d.ts +16 -0
  52. package/managers/cron.manager.js +202 -0
  53. package/managers/database.manager.d.ts +6 -0
  54. package/managers/database.manager.js +12 -0
  55. package/managers/method.manager.d.ts +28 -0
  56. package/managers/method.manager.js +584 -0
  57. package/managers/queue-method.manager.d.ts +13 -0
  58. package/managers/queue-method.manager.js +240 -0
  59. package/managers/subscription.manager.d.ts +28 -0
  60. package/managers/subscription.manager.js +808 -0
  61. package/managers/support.manager.d.ts +22 -0
  62. package/managers/support.manager.js +320 -0
  63. package/methods/accounts.d.ts +2 -0
  64. package/methods/accounts.js +253 -0
  65. package/methods/aws.d.ts +2 -0
  66. package/methods/aws.js +387 -0
  67. package/methods/cloudconvert.d.ts +2 -0
  68. package/methods/cloudconvert.js +37 -0
  69. package/methods/collections.d.ts +2 -0
  70. package/methods/collections.js +750 -0
  71. package/methods/counters.d.ts +2 -0
  72. package/methods/counters.js +107 -0
  73. package/methods/cron-jobs.d.ts +2 -0
  74. package/methods/cron-jobs.js +132 -0
  75. package/methods/flags.d.ts +2 -0
  76. package/methods/flags.js +6 -0
  77. package/methods/logs.d.ts +2 -0
  78. package/methods/logs.js +29 -0
  79. package/methods/pdf.d.ts +2 -0
  80. package/methods/pdf.js +303 -0
  81. package/models/active-subscription.model.d.ts +13 -0
  82. package/models/active-subscription.model.js +2 -0
  83. package/models/app-status.model.d.ts +4 -0
  84. package/models/app-status.model.js +2 -0
  85. package/models/app-version.model.d.ts +4 -0
  86. package/models/app-version.model.js +2 -0
  87. package/models/billing-logged-in-users.model.d.ts +7 -0
  88. package/models/billing-logged-in-users.model.js +2 -0
  89. package/models/collection-document.model.d.ts +6 -0
  90. package/models/collection-document.model.js +2 -0
  91. package/models/counter.model.d.ts +5 -0
  92. package/models/counter.model.js +2 -0
  93. package/models/cron-job-history.model.d.ts +12 -0
  94. package/models/cron-job-history.model.js +2 -0
  95. package/models/cron-job.model.d.ts +13 -0
  96. package/models/cron-job.model.js +2 -0
  97. package/models/dialog.model.d.ts +23 -0
  98. package/models/dialog.model.js +2 -0
  99. package/models/file.model.d.ts +9 -0
  100. package/models/file.model.js +2 -0
  101. package/models/flag.model.d.ts +5 -0
  102. package/models/flag.model.js +2 -0
  103. package/models/log.model.d.ts +11 -0
  104. package/models/log.model.js +2 -0
  105. package/models/logged-in-users.model.d.ts +9 -0
  106. package/models/logged-in-users.model.js +2 -0
  107. package/models/method-call.model.d.ts +7 -0
  108. package/models/method-call.model.js +2 -0
  109. package/models/method-response.model.d.ts +8 -0
  110. package/models/method-response.model.js +2 -0
  111. package/models/method.model.d.ts +10 -0
  112. package/models/method.model.js +2 -0
  113. package/models/notification.model.d.ts +4 -0
  114. package/models/notification.model.js +2 -0
  115. package/models/pagination.model.d.ts +11 -0
  116. package/models/pagination.model.js +20 -0
  117. package/models/permission.model.d.ts +12 -0
  118. package/models/permission.model.js +2 -0
  119. package/models/queue-method.model.d.ts +10 -0
  120. package/models/queue-method.model.js +2 -0
  121. package/models/queue-response.model.d.ts +10 -0
  122. package/models/queue-response.model.js +2 -0
  123. package/models/select-data-label.model.d.ts +9 -0
  124. package/models/select-data-label.model.js +2 -0
  125. package/models/server-response.model.d.ts +5 -0
  126. package/models/server-response.model.js +2 -0
  127. package/models/subscription.model.d.ts +30 -0
  128. package/models/subscription.model.js +2 -0
  129. package/models/support-method.model.d.ts +9 -0
  130. package/models/support-method.model.js +2 -0
  131. package/models/support-ticket.model.d.ts +61 -0
  132. package/models/support-ticket.model.js +2 -0
  133. package/models/user.model.d.ts +14 -0
  134. package/models/user.model.js +2 -0
  135. package/package.json +1 -1
  136. package/private/email-templates/enrollment.html +12 -0
  137. package/private/email-templates/forgot-password.html +12 -0
  138. package/private/email-templates/support-ticket-deleted.html +40 -0
  139. package/private/email-templates/support-ticket-modified.html +71 -0
  140. package/private/email-templates/support-ticket.html +71 -0
  141. package/private/images/ResolveIO.png +0 -0
  142. package/publications/app-status.d.ts +2 -0
  143. package/publications/app-status.js +14 -0
  144. package/publications/app-version.d.ts +2 -0
  145. package/publications/app-version.js +14 -0
  146. package/publications/billing-logged-in-users.d.ts +1 -0
  147. package/publications/billing-logged-in-users.js +63 -0
  148. package/publications/cron-jobs.d.ts +2 -0
  149. package/publications/cron-jobs.js +14 -0
  150. package/publications/files.d.ts +2 -0
  151. package/publications/files.js +71 -0
  152. package/publications/flags.d.ts +2 -0
  153. package/publications/flags.js +23 -0
  154. package/publications/logs.d.ts +2 -0
  155. package/publications/logs.js +26 -0
  156. package/publications/method-calls.d.ts +2 -0
  157. package/publications/method-calls.js +14 -0
  158. package/publications/method-responses.d.ts +2 -0
  159. package/publications/method-responses.js +14 -0
  160. package/publications/notifications.d.ts +2 -0
  161. package/publications/notifications.js +14 -0
  162. package/publications/super-admin.d.ts +2 -0
  163. package/publications/super-admin.js +21 -0
  164. package/publications/support-tickets.d.ts +1 -0
  165. package/publications/support-tickets.js +200 -0
  166. package/server-app.d.ts +35 -0
  167. package/server-app.js +638 -0
  168. package/support-methods/aws.d.ts +2 -0
  169. package/support-methods/aws.js +276 -0
  170. package/support-methods/collections.d.ts +2 -0
  171. package/support-methods/collections.js +471 -0
  172. package/support-methods/counters.d.ts +2 -0
  173. package/support-methods/counters.js +189 -0
  174. package/support-methods/support.d.ts +2 -0
  175. package/support-methods/support.js +236 -0
  176. package/util/common.d.ts +14 -0
  177. package/util/common.js +341 -0
@@ -0,0 +1,808 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __generator = (this && this.__generator) || function (thisArg, body) {
11
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
+ function verb(n) { return function (v) { return step([n, v]); }; }
14
+ function step(op) {
15
+ if (f) throw new TypeError("Generator is already executing.");
16
+ while (_) try {
17
+ 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;
18
+ if (y = 0, t) op = [op[0] & 2, t.value];
19
+ switch (op[0]) {
20
+ case 0: case 1: t = op; break;
21
+ case 4: _.label++; return { value: op[1], done: false };
22
+ case 5: _.label++; y = op[1]; op = [0]; continue;
23
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
+ default:
25
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
+ if (t[2]) _.ops.pop();
30
+ _.trys.pop(); continue;
31
+ }
32
+ op = body.call(thisArg, _);
33
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
+ }
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ var MongoOplog = require("mongo-oplog");
39
+ var logs_1 = require("../publications/logs");
40
+ var app_status_1 = require("../publications/app-status");
41
+ var app_version_1 = require("../publications/app-version");
42
+ var mongoose_1 = require("mongoose");
43
+ var files_1 = require("../publications/files");
44
+ var super_admin_1 = require("../publications/super-admin");
45
+ var active_subscription_collection_1 = require("../collections/active-subscription.collection");
46
+ var logged_in_users_collection_1 = require("../collections/logged-in-users.collection");
47
+ var cron_jobs_1 = require("../publications/cron-jobs");
48
+ var flags_1 = require("../publications/flags");
49
+ var method_calls_1 = require("../publications/method-calls");
50
+ var method_responses_1 = require("../publications/method-responses");
51
+ var support_tickets_1 = require("../publications/support-tickets");
52
+ var index_1 = require("../index");
53
+ var notifications_1 = require("../publications/notifications");
54
+ var common_1 = require("../util/common");
55
+ var billing_logged_in_users_collection_1 = require("../collections/billing-logged-in-users.collection");
56
+ var moment = require("moment");
57
+ var billing_logged_in_users_1 = require("../publications/billing-logged-in-users");
58
+ var SubscriptionManager = /** @class */ (function () {
59
+ function SubscriptionManager(mainServer, wss, serverConfig) {
60
+ var _this = this;
61
+ this._publications = {};
62
+ this._subscriptions = [];
63
+ this._oplogQueue = [];
64
+ this._sendQueue = [];
65
+ this._runningQueue = false;
66
+ this._mainServer = mainServer;
67
+ this.serverConfig = serverConfig;
68
+ this._wss = wss;
69
+ // Publications
70
+ super_admin_1.loadSuperAdminPublications(this);
71
+ app_version_1.loadAppVersionPublications(this);
72
+ app_status_1.loadAppStatusPublications(this);
73
+ logs_1.loadLogPublications(this);
74
+ files_1.loadFilePublications(this);
75
+ cron_jobs_1.loadCronJobPublications(this);
76
+ flags_1.loadFlagsPublications(this);
77
+ method_calls_1.loadMethodCallsPublications(this);
78
+ method_responses_1.loadMethodResponsePublications(this);
79
+ support_tickets_1.loadSupportTicketPublications(this);
80
+ billing_logged_in_users_1.loadBillingLoggedInUsersPublications(this);
81
+ notifications_1.loadNotificationPublications(this);
82
+ this.tailOpLog();
83
+ this.runOpLogQueue();
84
+ if (index_1.ResolveIOServer.getSupportDB()) {
85
+ this.tailOpLogSupport();
86
+ }
87
+ setInterval(function () {
88
+ if (!_this._runningQueue) {
89
+ if (_this._sendQueue.length) {
90
+ _this._runningQueue = true;
91
+ var _loop_1 = function (i) {
92
+ var ws = _this._mainServer.getWS(_this._sendQueue[i].id_ws);
93
+ if (ws && ws.readyState === ws.OPEN) {
94
+ if (ws.bufferedAmount < 20480) {
95
+ var sendItem = _this._sendQueue.pop();
96
+ ws.send(JSON.stringify(sendItem.data), function (error) {
97
+ if (error) {
98
+ console.log('Error on WS: ', error);
99
+ _this._mainServer.unsubscribeWS(ws);
100
+ }
101
+ });
102
+ }
103
+ }
104
+ else {
105
+ _this._sendQueue.splice(i, 1);
106
+ }
107
+ };
108
+ for (var i = _this._sendQueue.length - 1; i >= 0; i--) {
109
+ _loop_1(i);
110
+ }
111
+ _this._runningQueue = false;
112
+ }
113
+ }
114
+ }, 25);
115
+ }
116
+ // Add all files to publications private object
117
+ SubscriptionManager.prototype.publications = function (method) {
118
+ this._publications = Object.assign(this._publications, method);
119
+ };
120
+ SubscriptionManager.prototype.loggedInLatency = function (ws) {
121
+ return __awaiter(this, void 0, void 0, function () {
122
+ var _this = this;
123
+ return __generator(this, function (_a) {
124
+ logged_in_users_collection_1.LoggedInUsers.findOneAndUpdate({ id_ws: ws['id_socket'] }, { $set: { latency: ws['latency'] } }).exec(function (err, res) {
125
+ if (err) {
126
+ _this.unsubscribeAll(ws);
127
+ }
128
+ });
129
+ return [2 /*return*/];
130
+ });
131
+ });
132
+ };
133
+ // Subscribe to publication
134
+ SubscriptionManager.prototype.subscribe = function (ws, messageId, publication) {
135
+ var subscriptionData = [];
136
+ for (var _i = 3; _i < arguments.length; _i++) {
137
+ subscriptionData[_i - 3] = arguments[_i];
138
+ }
139
+ return __awaiter(this, void 0, void 0, function () {
140
+ var that, pub, valObj, valKeys, rootKeys, i, sub, _a, newActiveSub, begDate, endDate, billUser;
141
+ var _b;
142
+ return __generator(this, function (_c) {
143
+ switch (_c.label) {
144
+ case 0:
145
+ that = this;
146
+ pub = that._publications[publication];
147
+ if (!!pub) return [3 /*break*/, 1];
148
+ console.error('No Publication: ' + publication);
149
+ return [2 /*return*/];
150
+ case 1:
151
+ if (subscriptionData.length > 1 || subscriptionData[0]) {
152
+ if (!pub.check) {
153
+ console.error('No Check Function For Pub ' + publication);
154
+ return [2 /*return*/];
155
+ }
156
+ else if (!pub.check._schema) {
157
+ console.error('No Check Schema For Pub ' + publication);
158
+ return [2 /*return*/];
159
+ }
160
+ else {
161
+ valObj = {};
162
+ valKeys = Object.keys(pub.check._schema);
163
+ rootKeys = valKeys.filter(function (a) { return !a.includes('.'); });
164
+ for (i = 0; i < subscriptionData.length; i++) {
165
+ valObj[rootKeys[i]] = subscriptionData[i];
166
+ }
167
+ try {
168
+ pub.check.validate(valObj);
169
+ }
170
+ catch (errors) {
171
+ if (errors) {
172
+ console.error('Error in Pub Check (' + publication + ')', errors);
173
+ return [2 /*return*/];
174
+ }
175
+ }
176
+ }
177
+ }
178
+ sub = that._subscriptions.filter(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); })[0];
179
+ // If sub found (another user watching same data), add client to same sub
180
+ if (sub) {
181
+ sub.clients.push({
182
+ id_user: ws['id_user'],
183
+ messageId: messageId,
184
+ id_socket: ws['id_socket']
185
+ });
186
+ }
187
+ // If sub not found, create new sub
188
+ else {
189
+ that._subscriptions.push({
190
+ publication: publication,
191
+ subscriptionData: subscriptionData,
192
+ collections: that.getPublicationCollections(publication),
193
+ clients: [{
194
+ id_user: ws['id_user'],
195
+ messageId: messageId,
196
+ id_socket: ws['id_socket']
197
+ }]
198
+ });
199
+ }
200
+ if (!sub) {
201
+ sub = that._subscriptions.filter(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); })[0];
202
+ }
203
+ // Send pub data to client who just subscribed only, don't want to send to existing clients since nothing has changed
204
+ that.sendPubDataOnce(ws, messageId, sub);
205
+ if (!(that._publications[sub.publication].preFunction && !sub.preSubscriptionData)) return [3 /*break*/, 3];
206
+ _a = sub;
207
+ return [4 /*yield*/, (_b = that._publications[sub.publication]).preFunction.apply(_b, sub.subscriptionData)];
208
+ case 2:
209
+ _a.preSubscriptionData = _c.sent();
210
+ _c.label = 3;
211
+ case 3:
212
+ newActiveSub = new active_subscription_collection_1.ActiveSubscriptions({
213
+ date: new Date(),
214
+ publication: publication,
215
+ subData: JSON.stringify(subscriptionData),
216
+ collections: pub.collections,
217
+ clients: sub.clients
218
+ });
219
+ active_subscription_collection_1.ActiveSubscriptions.findOneAndUpdate({
220
+ $and: [
221
+ { publication: publication },
222
+ { subData: JSON.stringify(subscriptionData) }
223
+ ]
224
+ }, { $setOnInsert: { _id: mongoose_1.Types.ObjectId().toHexString(), __v: 0 }, $set: newActiveSub }, { upsert: true }).exec();
225
+ _c.label = 4;
226
+ case 4:
227
+ if (!(publication === 'appversion')) return [3 /*break*/, 6];
228
+ logged_in_users_collection_1.LoggedInUsers.create({
229
+ _id: mongoose_1.Types.ObjectId().toHexString(),
230
+ __v: 0,
231
+ date: new Date(),
232
+ id_user: ws['id_user'],
233
+ user: ws['user'],
234
+ id_ws: ws['id_socket']
235
+ });
236
+ if (!(ws['user'] !== 'Admin' && index_1.ResolveIOServer.getSupportDB())) return [3 /*break*/, 6];
237
+ begDate = moment().startOf('month');
238
+ endDate = moment().endOf('month');
239
+ return [4 /*yield*/, billing_logged_in_users_collection_1.BillingLoggedInUsers.findOne({
240
+ $and: [
241
+ {
242
+ client: index_1.ResolveIOServer.getClientName()
243
+ },
244
+ {
245
+ id_user: ws['id_user']
246
+ },
247
+ {
248
+ date: { $gte: begDate }
249
+ },
250
+ {
251
+ date: { $lte: endDate }
252
+ }
253
+ ]
254
+ })];
255
+ case 5:
256
+ billUser = _c.sent();
257
+ if (!billUser) {
258
+ billing_logged_in_users_collection_1.BillingLoggedInUsers.create({
259
+ _id: mongoose_1.Types.ObjectId().toHexString(),
260
+ __v: 0,
261
+ id_user: ws['id_user'],
262
+ user: ws['user'],
263
+ date: new Date(),
264
+ client: index_1.ResolveIOServer.getClientName()
265
+ });
266
+ }
267
+ _c.label = 6;
268
+ case 6: return [2 /*return*/];
269
+ }
270
+ });
271
+ });
272
+ };
273
+ // Unsubscribe from publication
274
+ SubscriptionManager.prototype.unsubscribe = function (ws, messageId, publication) {
275
+ var subscriptionData = [];
276
+ for (var _i = 3; _i < arguments.length; _i++) {
277
+ subscriptionData[_i - 3] = arguments[_i];
278
+ }
279
+ return __awaiter(this, void 0, void 0, function () {
280
+ var that, sub, i, activeSub;
281
+ return __generator(this, function (_a) {
282
+ switch (_a.label) {
283
+ case 0:
284
+ that = this;
285
+ if (!!that._publications[publication]) return [3 /*break*/, 1];
286
+ console.log('No Publication: ' + publication);
287
+ return [2 /*return*/];
288
+ case 1:
289
+ sub = that._subscriptions.filter(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); })[0];
290
+ if (!sub) return [3 /*break*/, 5];
291
+ for (i = sub.clients.length - 1; i >= 0; i--) {
292
+ if (sub.clients[i].id_user === ws['id_user'] && sub.clients[i].messageId === messageId && sub.clients[i].id_socket === ws['id_socket']) {
293
+ sub.clients.splice(i, 1);
294
+ }
295
+ }
296
+ if (!!sub.clients.length) return [3 /*break*/, 2];
297
+ that._subscriptions.splice(that._subscriptions.findIndex(function (a) { return a.publication === publication && JSON.stringify(a.subscriptionData) === JSON.stringify(subscriptionData); }), 1);
298
+ active_subscription_collection_1.ActiveSubscriptions.deleteOne({
299
+ $and: [
300
+ { publication: publication },
301
+ { subData: JSON.stringify(subscriptionData) }
302
+ ]
303
+ }).exec();
304
+ return [3 /*break*/, 4];
305
+ case 2: return [4 /*yield*/, active_subscription_collection_1.ActiveSubscriptions.findOne({
306
+ $and: [
307
+ { publication: publication },
308
+ { subData: JSON.stringify(subscriptionData) }
309
+ ]
310
+ })];
311
+ case 3:
312
+ activeSub = _a.sent();
313
+ if (activeSub) {
314
+ active_subscription_collection_1.ActiveSubscriptions.updateOne({ _id: activeSub._id }, { $set: { clients: sub.clients } }).exec();
315
+ }
316
+ _a.label = 4;
317
+ case 4: return [3 /*break*/, 6];
318
+ case 5:
319
+ console.log('Did not sub on unsubscribe');
320
+ _a.label = 6;
321
+ case 6: return [2 /*return*/];
322
+ }
323
+ });
324
+ });
325
+ };
326
+ // Unsubscribe from publication
327
+ SubscriptionManager.prototype.unsubscribeAll = function (ws) {
328
+ return __awaiter(this, void 0, void 0, function () {
329
+ var that, loggedInUser, userSubs, _loop_2, i, activeSubs;
330
+ return __generator(this, function (_a) {
331
+ switch (_a.label) {
332
+ case 0:
333
+ that = this;
334
+ return [4 /*yield*/, logged_in_users_collection_1.LoggedInUsers.findOne({ id_ws: ws['id_socket'] })];
335
+ case 1:
336
+ loggedInUser = _a.sent();
337
+ if (loggedInUser) {
338
+ logged_in_users_collection_1.LoggedInUsers.deleteOne({ _id: loggedInUser._id }).exec();
339
+ }
340
+ userSubs = that._subscriptions.filter(function (a) { return a.clients.some(function (b) { return b.id_user === ws['id_user'] && b.id_socket === ws['id_socket']; }); });
341
+ _loop_2 = function (i) {
342
+ var sub = userSubs[i];
343
+ for (var j = sub.clients.length - 1; j >= 0; j--) {
344
+ if (sub.clients[j].id_socket === ws['id_socket']) {
345
+ sub.clients.splice(j, 1);
346
+ }
347
+ }
348
+ if (!sub.clients.length) {
349
+ that._subscriptions.splice(that._subscriptions.findIndex(function (a) { return a.publication === sub.publication && JSON.stringify(a.subscriptionData) === JSON.stringify(sub.subscriptionData); }), 1);
350
+ }
351
+ };
352
+ for (i = userSubs.length - 1; i >= 0; i--) {
353
+ _loop_2(i);
354
+ }
355
+ return [4 /*yield*/, active_subscription_collection_1.ActiveSubscriptions.find({ 'clients.id_socket': ws['id_socket'] })];
356
+ case 2:
357
+ activeSubs = _a.sent();
358
+ activeSubs.forEach(function (sub) {
359
+ for (var j = sub.clients.length - 1; j >= 0; j--) {
360
+ if (sub.clients[j].id_socket === ws['id_socket']) {
361
+ sub.clients.splice(j, 1);
362
+ }
363
+ }
364
+ if (!sub.clients.length) {
365
+ active_subscription_collection_1.ActiveSubscriptions.deleteOne({ _id: sub._id }).exec();
366
+ }
367
+ else {
368
+ for (var j = sub.clients.length - 1; j >= 0; j--) {
369
+ if (sub.clients[j].id_socket === ws['id_socket']) {
370
+ sub.clients.splice(j, 1);
371
+ }
372
+ }
373
+ active_subscription_collection_1.ActiveSubscriptions.updateOne({ _id: sub._id }, { $set: { clients: sub.clients } }).exec();
374
+ }
375
+ });
376
+ return [2 /*return*/];
377
+ }
378
+ });
379
+ });
380
+ };
381
+ // Get publication collection
382
+ SubscriptionManager.prototype.getPublicationCollections = function (publication) {
383
+ return this._publications[publication].collections;
384
+ };
385
+ // Watch (tail) Mongo's operation log on the entire database (all insert/modify/delete will trigger this function)
386
+ SubscriptionManager.prototype.tailOpLog = function () {
387
+ var _this = this;
388
+ var that = this;
389
+ var oplog = MongoOplog(that.serverConfig['OPLOG_URL']);
390
+ oplog.tail().then(function () {
391
+ console.log('tail started');
392
+ });
393
+ oplog.on('insert', function (doc) {
394
+ var nsArray = doc.ns.split('.');
395
+ var collection = nsArray[1];
396
+ if (nsArray[2]) {
397
+ collection += '.' + nsArray[2];
398
+ }
399
+ if (collection === 'cron-jobs') {
400
+ _this._mainServer.getCronManager().checkCronJobsForUpdates();
401
+ }
402
+ else if (collection === 'queue-methods') {
403
+ _this._mainServer.getQueueManager().runMethodQueue();
404
+ }
405
+ else if (collection === 'queue-responses') {
406
+ _this._mainServer.getQueueManager().runMethodResponse();
407
+ }
408
+ else if (collection === 'support-tickets') {
409
+ _this._mainServer.getMethodManager().callMethodInternal('sendSupportTicketEmail', doc.o._id);
410
+ }
411
+ _this._oplogQueue.push({
412
+ type: 'insert',
413
+ collection: collection,
414
+ doc: doc.o
415
+ });
416
+ });
417
+ oplog.on('update', function (doc) {
418
+ var nsArray = doc.ns.split('.');
419
+ var collection = nsArray[1];
420
+ if (nsArray[2]) {
421
+ collection += '.' + nsArray[2];
422
+ }
423
+ doc.o['_id'] = doc.o2['_id'];
424
+ if (collection === 'cron-jobs') {
425
+ _this._mainServer.getCronManager().checkCronJobsForUpdates();
426
+ }
427
+ _this._oplogQueue.push({
428
+ type: 'update',
429
+ collection: collection,
430
+ doc: doc.o
431
+ });
432
+ });
433
+ oplog.on('delete', function (doc) {
434
+ var nsArray = doc.ns.split('.');
435
+ var collection = nsArray[1];
436
+ if (nsArray[2]) {
437
+ collection += '.' + nsArray[2];
438
+ }
439
+ that.resendPubsForDelete(collection);
440
+ if (collection === 'cron-jobs') {
441
+ _this._mainServer.getCronManager().checkCronJobsForUpdates();
442
+ }
443
+ });
444
+ oplog.on('error', function (error) {
445
+ console.log('Error', error);
446
+ });
447
+ oplog.on('end', function () {
448
+ console.log('oplog ended');
449
+ process.exit();
450
+ });
451
+ oplog.stop(function () {
452
+ console.log('oplog stopped');
453
+ });
454
+ };
455
+ SubscriptionManager.prototype.tailOpLogSupport = function () {
456
+ var that = this;
457
+ var oplog = MongoOplog(that.serverConfig['RESOLVEIO_SUPPORT_OPLOG_URL']);
458
+ oplog.tail().then(function () {
459
+ console.log('tail started support');
460
+ });
461
+ oplog.on('insert', function (doc) {
462
+ var nsArray = doc.ns.split('.');
463
+ var collection = nsArray[1];
464
+ if (nsArray[2]) {
465
+ collection += '.' + nsArray[2];
466
+ }
467
+ if (collection === 'support-tickets') {
468
+ that.checkSupportPubsForChanges(collection, doc.o);
469
+ }
470
+ });
471
+ oplog.on('update', function (doc) {
472
+ var nsArray = doc.ns.split('.');
473
+ var collection = nsArray[1];
474
+ if (nsArray[2]) {
475
+ collection += '.' + nsArray[2];
476
+ }
477
+ doc.o['_id'] = doc.o2['_id'];
478
+ if (collection === 'support-tickets') {
479
+ that.checkSupportPubsForChanges(collection, doc.o);
480
+ }
481
+ });
482
+ oplog.on('delete', function (doc) {
483
+ var nsArray = doc.ns.split('.');
484
+ var collection = nsArray[1];
485
+ if (nsArray[2]) {
486
+ collection += '.' + nsArray[2];
487
+ }
488
+ if (collection === 'support-tickets') {
489
+ that.resendPubsForDelete(collection);
490
+ }
491
+ });
492
+ oplog.on('error', function (error) {
493
+ console.log('Error support', error);
494
+ });
495
+ oplog.on('end', function () {
496
+ console.log('oplog ended support');
497
+ process.exit();
498
+ });
499
+ oplog.stop(function () {
500
+ console.log('oplog stopped support');
501
+ });
502
+ };
503
+ SubscriptionManager.prototype.runOpLogQueue = function () {
504
+ var _this = this;
505
+ setInterval(function () {
506
+ var oplogQueue = common_1.deepCopy(_this._oplogQueue);
507
+ var uniqueCollectionOplogQueue = oplogQueue.map(function (a) { return a.collection; }).filter(function (elem, index, self) {
508
+ return index === self.indexOf(elem);
509
+ });
510
+ uniqueCollectionOplogQueue.forEach(function (collection) {
511
+ var oplogQueueFiltered = oplogQueue.filter(function (a) { return a.collection === collection; });
512
+ if (oplogQueueFiltered.length === 1) {
513
+ _this.checkPubsForChanges(oplogQueueFiltered[0].collection, oplogQueueFiltered[0].doc);
514
+ _this._oplogQueue.splice(_this._oplogQueue.map(function (a) { return a.collection; }).indexOf(collection), 1);
515
+ }
516
+ else {
517
+ oplogQueueFiltered.forEach(function (item) {
518
+ _this.checkPubsForChanges(item.collection, item.doc, true);
519
+ });
520
+ _this.checkPubsForChanges(oplogQueueFiltered[oplogQueueFiltered.length - 1].collection, oplogQueueFiltered[oplogQueueFiltered.length - 1].doc, false, true);
521
+ for (var i = _this._oplogQueue.length - 1; i >= 0; i--) {
522
+ var item = _this._oplogQueue[i];
523
+ if (item.collection === collection) {
524
+ _this._oplogQueue.splice(i, 1);
525
+ }
526
+ }
527
+ }
528
+ });
529
+ }, 25);
530
+ };
531
+ SubscriptionManager.prototype.resendPubsForDelete = function (collection) {
532
+ var that = this;
533
+ that._subscriptions.filter(function (a) { return a.collections.includes(collection); }).forEach(function (sub) {
534
+ if (that._publications[sub.publication].ws_specific) {
535
+ sub.clients.forEach(function (client) {
536
+ that._wss.clients.forEach(function (ws) {
537
+ if (ws['id_socket'] === client.id_socket) {
538
+ that.sendPubDataOnce(ws, client.messageId, sub);
539
+ }
540
+ });
541
+ });
542
+ }
543
+ else {
544
+ that.sendPubData(sub);
545
+ }
546
+ });
547
+ };
548
+ // Document: Inserted/Modified/Deleted Document
549
+ // Collection: Collection Document Lives In
550
+ // Check to see if any pubs need to refetch due to Mongo operation
551
+ SubscriptionManager.prototype.checkPubsForChanges = function (collection, document, fetchFunctionOnly, noFetchFunction) {
552
+ var _this = this;
553
+ if (fetchFunctionOnly === void 0) { fetchFunctionOnly = false; }
554
+ if (noFetchFunction === void 0) { noFetchFunction = false; }
555
+ var that = this;
556
+ that._subscriptions.filter(function (a) { return a.collections.includes(collection); }).forEach(function (sub) { return __awaiter(_this, void 0, void 0, function () {
557
+ var schemaErrors, _a, _b;
558
+ var _c, _d;
559
+ return __generator(this, function (_e) {
560
+ switch (_e.label) {
561
+ case 0:
562
+ schemaErrors = null;
563
+ try {
564
+ index_1.ResolveIOServer.getMainDB().model(collection)['simplschema'].validate(document);
565
+ }
566
+ catch (errors) {
567
+ schemaErrors = errors;
568
+ }
569
+ if (!schemaErrors) return [3 /*break*/, 2];
570
+ return [4 /*yield*/, index_1.ResolveIOServer.getMainDB().model(collection).findById(document['_id'])];
571
+ case 1:
572
+ document = _e.sent();
573
+ _e.label = 2;
574
+ case 2:
575
+ if (!sub.preSubscriptionData) return [3 /*break*/, 4];
576
+ if (!that._publications[sub.publication].fetchFunction(document, sub.preSubscriptionData)) return [3 /*break*/, 4];
577
+ that.sendPubData(sub);
578
+ _a = sub;
579
+ return [4 /*yield*/, (_c = that._publications[sub.publication]).preFunction.apply(_c, sub.subscriptionData)];
580
+ case 3:
581
+ _a.preSubscriptionData = _e.sent();
582
+ return [2 /*return*/];
583
+ case 4:
584
+ if (!that._publications[sub.publication].preFunction) return [3 /*break*/, 7];
585
+ if (!!noFetchFunction) return [3 /*break*/, 6];
586
+ _b = sub;
587
+ return [4 /*yield*/, that._publications[sub.publication].preFunction(sub.subscriptionData)];
588
+ case 5:
589
+ _b.preSubscriptionData = _e.sent();
590
+ if (that._publications[sub.publication].fetchFunction(document, sub.preSubscriptionData)) {
591
+ that.sendPubData(sub);
592
+ }
593
+ _e.label = 6;
594
+ case 6: return [3 /*break*/, 8];
595
+ case 7:
596
+ if (that._publications[sub.publication].ws_specific) {
597
+ sub.clients.forEach(function (client) {
598
+ var _a;
599
+ if (that._publications[sub.publication].fetchFunction) {
600
+ if (!noFetchFunction) {
601
+ if ((_a = that._publications[sub.publication]).fetchFunction.apply(_a, [document, client.id_user].concat(sub.subscriptionData))) {
602
+ that._wss.clients.forEach(function (ws) {
603
+ if (ws['id_socket'] === client.id_socket) {
604
+ that.sendPubDataOnce(ws, client.messageId, sub);
605
+ }
606
+ });
607
+ }
608
+ }
609
+ }
610
+ else if (!fetchFunctionOnly) {
611
+ that._wss.clients.forEach(function (ws) {
612
+ if (ws['id_socket'] === client.id_socket) {
613
+ that.sendPubDataOnce(ws, client.messageId, sub);
614
+ }
615
+ });
616
+ }
617
+ });
618
+ }
619
+ else {
620
+ if (that._publications[sub.publication].fetchFunction) {
621
+ if (!noFetchFunction) {
622
+ if ((_d = that._publications[sub.publication]).fetchFunction.apply(_d, [document].concat(sub.subscriptionData))) {
623
+ that.sendPubData(sub);
624
+ }
625
+ }
626
+ }
627
+ else if (!fetchFunctionOnly) {
628
+ that.sendPubData(sub);
629
+ }
630
+ }
631
+ _e.label = 8;
632
+ case 8: return [2 /*return*/];
633
+ }
634
+ });
635
+ }); });
636
+ };
637
+ SubscriptionManager.prototype.checkSupportPubsForChanges = function (collection, document) {
638
+ var _this = this;
639
+ var that = this;
640
+ that._subscriptions.filter(function (a) { return a.collections.includes(collection); }).forEach(function (sub) { return __awaiter(_this, void 0, void 0, function () {
641
+ var schemaErrors, _a, _b;
642
+ var _c, _d, _e;
643
+ return __generator(this, function (_f) {
644
+ switch (_f.label) {
645
+ case 0:
646
+ schemaErrors = null;
647
+ try {
648
+ index_1.ResolveIOServer.getSupportDB().model(collection)['simplschema'].validate(document);
649
+ }
650
+ catch (errors) {
651
+ schemaErrors = errors;
652
+ }
653
+ if (!schemaErrors) return [3 /*break*/, 2];
654
+ return [4 /*yield*/, index_1.ResolveIOServer.getSupportDB().model(collection).findById(document['_id'])];
655
+ case 1:
656
+ document = _f.sent();
657
+ _f.label = 2;
658
+ case 2:
659
+ if (!sub.preSubscriptionData) return [3 /*break*/, 4];
660
+ if (!that._publications[sub.publication].fetchFunction(document, sub.preSubscriptionData)) return [3 /*break*/, 4];
661
+ that.sendPubData(sub);
662
+ _a = sub;
663
+ return [4 /*yield*/, (_c = that._publications[sub.publication]).preFunction.apply(_c, sub.subscriptionData)];
664
+ case 3:
665
+ _a.preSubscriptionData = _f.sent();
666
+ return [2 /*return*/];
667
+ case 4:
668
+ if (!that._publications[sub.publication].preFunction) return [3 /*break*/, 6];
669
+ _b = sub;
670
+ return [4 /*yield*/, (_d = that._publications[sub.publication]).preFunction.apply(_d, sub.subscriptionData)];
671
+ case 5:
672
+ _b.preSubscriptionData = _f.sent();
673
+ if (that._publications[sub.publication].fetchFunction(document, sub.preSubscriptionData)) {
674
+ that.sendPubData(sub);
675
+ }
676
+ return [3 /*break*/, 7];
677
+ case 6:
678
+ if (that._publications[sub.publication].ws_specific) {
679
+ sub.clients.forEach(function (client) {
680
+ var _a;
681
+ if (that._publications[sub.publication].fetchFunction) {
682
+ if ((_a = that._publications[sub.publication]).fetchFunction.apply(_a, [document, client.id_user].concat(sub.subscriptionData))) {
683
+ that._wss.clients.forEach(function (ws) {
684
+ if (ws['id_socket'] === client.id_socket) {
685
+ that.sendPubDataOnce(ws, client.messageId, sub);
686
+ }
687
+ });
688
+ }
689
+ }
690
+ else {
691
+ that._wss.clients.forEach(function (ws) {
692
+ if (ws['id_socket'] === client.id_socket) {
693
+ that.sendPubDataOnce(ws, client.messageId, sub);
694
+ }
695
+ });
696
+ }
697
+ });
698
+ }
699
+ else {
700
+ if (that._publications[sub.publication].fetchFunction) {
701
+ if ((_e = that._publications[sub.publication]).fetchFunction.apply(_e, [document].concat(sub.subscriptionData))) {
702
+ that.sendPubData(sub);
703
+ }
704
+ }
705
+ else {
706
+ that.sendPubData(sub);
707
+ }
708
+ }
709
+ _f.label = 7;
710
+ case 7: return [2 /*return*/];
711
+ }
712
+ });
713
+ }); });
714
+ };
715
+ // Fetch pub once, send to all clients linked to this pub
716
+ SubscriptionManager.prototype.sendPubDataOnce = function (ws, messageId, subscription) {
717
+ return __awaiter(this, void 0, void 0, function () {
718
+ var that;
719
+ var _a, _b;
720
+ var _this = this;
721
+ return __generator(this, function (_c) {
722
+ that = this;
723
+ if (!that._publications[subscription.publication].ws_specific) { // Same pub for all users
724
+ (_a = that._publications[subscription.publication].function).call.apply(_a, [Object.assign({}, that, SubscriptionManager.prototype)].concat(subscription.subscriptionData)).then(function (res) {
725
+ var serverRes = {
726
+ messageId: messageId,
727
+ hasError: false,
728
+ data: res
729
+ };
730
+ _this.sendWS(ws, serverRes);
731
+ }, function (err) {
732
+ var serverRes = {
733
+ messageId: messageId,
734
+ hasError: true,
735
+ data: err
736
+ };
737
+ _this.sendWS(ws, serverRes);
738
+ });
739
+ }
740
+ else { // Pub is different for each user (Look at users publication) [MUCH SLOWER, RE-RUNS FOR EACH USER]
741
+ (_b = that._publications[subscription.publication].function).call.apply(_b, [Object.assign({}, that, SubscriptionManager.prototype), ws['id_user']].concat(subscription.subscriptionData)).then(function (res) {
742
+ var serverRes = {
743
+ messageId: messageId,
744
+ hasError: false,
745
+ data: res
746
+ };
747
+ _this.sendWS(ws, serverRes);
748
+ }, function (err) {
749
+ var serverRes = {
750
+ messageId: messageId,
751
+ hasError: true,
752
+ data: err
753
+ };
754
+ _this.sendWS(ws, serverRes);
755
+ });
756
+ }
757
+ return [2 /*return*/];
758
+ });
759
+ });
760
+ };
761
+ // Fetch pub once, send to all clients linked to this pub
762
+ SubscriptionManager.prototype.sendPubData = function (subscription) {
763
+ return __awaiter(this, void 0, void 0, function () {
764
+ var that;
765
+ var _a;
766
+ var _this = this;
767
+ return __generator(this, function (_b) {
768
+ that = this;
769
+ (_a = that._publications[subscription.publication].function).call.apply(_a, [Object.assign({}, that, SubscriptionManager.prototype)].concat(subscription.subscriptionData)).then(function (res) {
770
+ subscription.clients.forEach(function (client) {
771
+ that._wss.clients.forEach(function (ws) {
772
+ if (ws['id_socket'] === client.id_socket) {
773
+ var serverRes = {
774
+ messageId: client.messageId,
775
+ hasError: false,
776
+ data: res
777
+ };
778
+ _this.sendWS(ws, serverRes);
779
+ }
780
+ });
781
+ });
782
+ }, function (err) {
783
+ subscription.clients.forEach(function (client) {
784
+ that._wss.clients.forEach(function (ws) {
785
+ if (ws['id_socket'] === client.id_socket) {
786
+ var serverRes = {
787
+ messageId: client.messageId,
788
+ hasError: true,
789
+ data: err
790
+ };
791
+ _this.sendWS(ws, serverRes);
792
+ }
793
+ });
794
+ });
795
+ });
796
+ return [2 /*return*/];
797
+ });
798
+ });
799
+ };
800
+ SubscriptionManager.prototype.sendWS = function (ws, data) {
801
+ this._sendQueue.splice(0, 0, {
802
+ id_ws: ws['id_socket'],
803
+ data: data
804
+ });
805
+ };
806
+ return SubscriptionManager;
807
+ }());
808
+ exports.SubscriptionManager = SubscriptionManager;