-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
477 lines (429 loc) · 16.8 KB
/
index.js
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
var JsonDB = require('node-json-db');
var FCM = require('fcm-push');
var diff = require('rus-diff').diff;
var log4js = require('log4js');
var SN = require('sync-node');
var sha1 = require('sha1');
const TAG = "Flamebase Database";
var logger = log4js.getLogger(TAG);
JSON.stringifyAligned = require('json-align');
var ACTION_SIMPLE_UPDATE = "simple_update";
var ACTION_SLICE_UPDATE = "slice_update";
var ACTION_NO_UPDATE = "no_update";
function FlamebaseDatabase(database, path) {
// object reference
var object = this;
// debug
this.debugVal = false;
// os
this.OS = {};
this.OS.ANDROID = "android";
this.OS.IOS = "ios";
var lengthMargin = 400; // supposed length of additional info to send
this.lengthLimit = {};
this.lengthLimit.ANDROID = (4096 - lengthMargin);
this.lengthLimit.IOS = (2048 - lengthMargin);
this.queue = SN.createQueue();
// database
this.db = new JsonDB(database, true, true);
// db reference
this.ref = {};
// last db string reference
this.lastStringReference = JSON.stringify({});
this.pushConfig = null;
this.fcm = null;
/**
* sync from database
*/
this.syncFromDatabase = function() {
try {
object.ref = object.db.getData(path);
this.lastStringReference = JSON.stringify(object.ref);
if (this.debugVal) {
logger.debug("ref: " + path);
logger.debug("len: " + this.lastStringReference.length);
}
} catch(e) {
console.log("####################### error: " + e);
console.log("####################### generating {} ");
object.ref = {};
this.lastStringReference = JSON.stringify(object.ref);
}
};
/**
* sync to database
*/
this.syncToDatabase = function(restart, callback) {
if (restart !== undefined && restart) {
this.lastStringReference = JSON.stringify({});
if (this.debugVal) {
logger.debug("cleaning last reference on " + path);
}
}
object.db.push(path, object.ref);
object.syncNotifications(callback);
};
/**
* config for real time synchronization
* @param config
*/
this.setSyncConfig = function(config) {
this.pushConfig = config;
// push notifications
if (this.fcm === null) {
this.fcm = (this.pushConfig.APIKey() === null || this.pushConfig.APIKey() === 0 ? null : new FCM(this.pushConfig.APIKey()));
}
this.lastStringReference = JSON.stringify({});
};
/**
* debug logs
* @param callback
*/
this.debug = function(value) {
this.debugVal = value;
};
/**
* fired if fcm is defined and DB changes or reloads
*/
this.syncNotifications = function(callback) {
if (this.pushConfig !== null) {
try {
this.sendDetailPushMessage(callback);
} catch (e) {
logger.error("error: " + e);
}
}
};
/**
*
*/
this.sendDetailPushMessage = function(callback) {
if (this.fcm === null) {
logger.error("# no fcm detected, set an API key")
return;
}
var ios_tokens = [];
var android_tokens = [];
var id = this.pushConfig.referenceId();
var notification = this.pushConfig.notification();
var devices = this.pushConfig.devices();
for (var t = 0; t < devices.length; t++) {
var device = devices[t];
if (device.os.indexOf(this.OS.IOS) !== -1) {
ios_tokens.push(device.token);
} else {
android_tokens.push(device.token);
}
}
this.lastStringReference = JSON.stringify(this.ref);
if (android_tokens.length > 0) {
var data_android = this.getPartsFor(this.OS.ANDROID, JSON.parse(this.lastStringReference), this.ref);
if (object.debugVal) {
logger.debug("android_tokens_size: " + android_tokens.length);
logger.debug("data_android_size: " + data_android.parts.length);
}
if (data_android.parts.length === 1) {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.reference = data_android.parts[0];
data.action = ACTION_SIMPLE_UPDATE;
data.size = data_android.parts.length;
data.index = 0;
var send = {};
send.data = data;
send.tokens = android_tokens;
send.notification = notification;
if (ios_tokens.length === 0) {
this.sendPushMessage(send, callback);
} else {
this.sendPushMessage(send);
}
} else if (data_android.parts.length > 1) {
for (var i = 0; i < data_android.parts.length; i++) {
var dat = {};
dat.id = id;
dat.tag = this.pushConfig.tag();
dat.reference = data_android.parts[i];
dat.action = ACTION_SLICE_UPDATE;
dat.index = i;
dat.size = data_android.parts.length;
var sen = {};
sen.data = dat;
sen.tokens = android_tokens;
sen.notification = notification;
if (ios_tokens.length === 0 && i === data_android.parts.length - 1) {
this.sendPushMessage(sen, callback);
} else {
this.sendPushMessage(sen);
}
}
} else {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.action = ACTION_NO_UPDATE;
var send = {};
send.data = data;
send.tokens = android_tokens;
send.notification = notification;
if (ios_tokens.length === 0) {
this.sendPushMessage(send, callback);
} else {
this.sendPushMessage(send);
}
}
}
if (ios_tokens.length > 0) {
var data_ios = this.getPartsFor(this.OS.IOS, JSON.parse(this.lastStringReference), this.ref);
if (object.debugVal) {
logger.debug("ios_tokens_size: " + ios_tokens.length);
logger.debug("data_ios_size: " + data_ios.parts.length);
}
if (data_ios.parts.length === 1) {
var da = {};
da.id = id;
da.tag = this.pushConfig.tag();
da.reference = data_ios.parts[0];
da.action = ACTION_SIMPLE_UPDATE;
da.size = data_ios.parts.length;
da.index = 0;
var se = {};
se.data = da;
se.tokens = ios_tokens;
se.notification = notification;
this.sendPushMessage(se, callback);
} else if (data_ios.parts.length > 1) {
for (var i = 0; i < data_ios.parts.length; i++) {
var d = {};
d.id = id;
d.tag = this.pushConfig.tag();
d.reference = data_ios.parts[i];
d.action = ACTION_SLICE_UPDATE;
d.index = i;
d.size = data_ios.parts.length;
var s = {};
s.data = d;
s.tokens = ios_tokens;
s.notification = notification;
if (i === data_ios.parts.length - 1) {
this.sendPushMessage(s, callback);
} else {
this.sendPushMessage(s);
}
}
} else {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.action = ACTION_NO_UPDATE;
var s = {};
s.data = data;
s.tokens = ios_tokens;
s.notification = notification;
this.sendPushMessage(s, callback);
}
}
};
this.sendDifferencesForClient = function(before, device, callback) {
if (this.fcm === null) {
logger.error("# no fcm detected, set an API key")
return;
}
var ios_tokens = [];
var android_tokens = [];
var id = this.pushConfig.referenceId();
var notification = this.pushConfig.notification();
if (device.os.indexOf(this.OS.IOS) !== -1) {
ios_tokens.push(device.token);
} else {
android_tokens.push(device.token);
}
if (android_tokens.length > 0) {
var data_android = this.getPartsFor(this.OS.ANDROID, JSON.parse(before), this.ref);
if (object.debugVal) {
logger.debug("android_tokens_size: " + android_tokens.length);
logger.debug("data_android_size: " + data_android.parts.length);
}
if (data_android.parts.length === 1) {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.reference = data_android.parts[0];
data.action = ACTION_SIMPLE_UPDATE;
data.size = data_android.parts.length;
data.index = 0;
var send = {};
send.data = data;
send.tokens = android_tokens;
send.notification = notification;
if (ios_tokens.length === 0) {
this.sendPushMessage(send, callback);
} else {
this.sendPushMessage(send);
}
} else if (data_android.parts.length > 1) {
for (var i = 0; i < data_android.parts.length; i++) {
var dat = {};
dat.id = id;
dat.tag = this.pushConfig.tag();
dat.reference = data_android.parts[i];
dat.action = ACTION_SLICE_UPDATE;
dat.index = i;
dat.size = data_android.parts.length;
var sen = {};
sen.data = dat;
sen.tokens = android_tokens;
sen.notification = notification;
if (ios_tokens.length === 0 && i === data_android.parts.length - 1) {
this.sendPushMessage(sen, callback);
} else {
this.sendPushMessage(sen);
}
}
} else {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.action = ACTION_NO_UPDATE;
var send = {};
send.data = data;
send.tokens = android_tokens;
send.notification = notification;
if (ios_tokens.length === 0) {
this.sendPushMessage(send, callback);
} else {
this.sendPushMessage(send);
}
}
}
if (ios_tokens.length > 0) {
var data_ios = this.getPartsFor(this.OS.IOS, JSON.parse(before), this.ref);
if (object.debugVal) {
logger.debug("ios_tokens_size: " + ios_tokens.length);
logger.debug("data_ios_size: " + data_ios.parts.length);
}
if (data_ios.parts.length === 1) {
var da = {};
da.id = id;
da.tag = this.pushConfig.tag();
da.reference = data_ios.parts[0];
da.action = ACTION_SIMPLE_UPDATE;
da.size = data_ios.parts.length;
da.index = 0;
var se = {};
se.data = da;
se.tokens = ios_tokens;
se.notification = notification;
this.sendPushMessage(se, callback);
} else if (data_ios.parts.length > 1) {
for (var i = 0; i < data_ios.parts.length; i++) {
var d = {};
d.id = id;
d.tag = this.pushConfig.tag();
d.reference = data_ios.parts[i];
d.action = ACTION_SLICE_UPDATE;
d.index = i;
d.size = data_ios.parts.length;
var s = {};
s.data = d;
s.tokens = ios_tokens;
s.notification = notification;
if (i === data_ios.parts.length - 1) {
this.sendPushMessage(s, callback);
} else {
this.sendPushMessage(s);
}
}
} else {
var data = {};
data.id = id;
data.tag = this.pushConfig.tag();
data.action = ACTION_NO_UPDATE;
var send = {};
send.data = data;
send.tokens = ios_tokens;
send.notification = notification;
this.sendPushMessage(send, callback);
}
}
this.lastStringReference = JSON.stringify(this.ref);
};
this.sendPushMessage = function(send, callback) {
this.queue.pushJob(function() {
return new Promise(function (resolve, reject) {
var message = {
registration_ids: send.tokens, // required fill with device token or topics
data: send.data,
notification: send.notification
};
if (object.debugVal) {
logger.debug("Sending to: " + JSON.stringifyAligned(message.registration_ids));
}
object.fcm.send(message)
.then(function (response) {
if (object.debugVal) {
logger.debug("Successfully sent with response: " + JSON.stringifyAligned(JSON.parse(response)));
}
if (callback != undefined) {
callback();
}
resolve();
})
.catch(function (err) {
logger.error("error: " + JSON.stringifyAligned(err));
resolve();
})
});
});
};
this.getPartsFor = function(os, before, after) {
var notification = this.pushConfig.notification();
var notificationLength = JSON.stringify(notification).length;
//var differences = JSON.stringify(diff(JSON.parse(this.lastStringReference), this.ref));
var differences = JSON.stringify(diff(before, after));
var partsToSend = [];
if (this.debugVal) {
logger.debug("diff: " + differences);
}
if (differences === "false") {
var currentStringAfter = JSON.stringify(after);
var currentStringBefore = JSON.stringify(before);
if (currentStringBefore.length !== currentStringAfter.length) {
logger.error("something went wrong; sha1 diff: " + currentStringBefore.length + " - " + currentStringAfter.length);
}
if (this.debugVal) {
logger.debug("no differences");
}
} else {
differences = this.string2Hex(differences);
var limit = os.indexOf(this.OS.IOS) !== -1 ? this.lengthLimit.IOS - notificationLength : this.lengthLimit.ANDROID - notificationLength;
if (differences.length > limit) {
var index = -1;
var pendingChars = differences.length;
while (pendingChars > 0) {
index++;
var part = differences.slice(index * limit, (pendingChars < limit ? index * limit + pendingChars : (index + 1) * limit));
pendingChars = pendingChars - part.length;
partsToSend.push(part);
}
} else {
partsToSend.push(differences);
}
}
var result = {};
result.parts = partsToSend;
return result;
};
this.exist = function() {
return !(this.ref === null || this.ref === undefined)
};
this.string2Hex = function (tmp) {
var str = '';
for (var i = 0; i < tmp.length; i++) {
str += tmp[i].charCodeAt(0).toString(16);
}
return str;
};
}
module.exports = FlamebaseDatabase;