-
Notifications
You must be signed in to change notification settings - Fork 5
/
sync-client.js
1685 lines (1554 loc) · 58.1 KB
/
sync-client.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Implements a reactive sync client
// - Reactive mode: client connects to the server automatically, and syncs all reactive tables automatically (at start, or when going online).
// - Non reactive mode: client connects to the server when sync is requested by user, and disconnects when sync finishes.
// User credentials can be set in 2 ways:
// 1°) By using default modal dialog prompt
// 2°) By referencing a custom object/function as an attribute of SyncClient, i.e.: customCredentials="mycredentials()", whose result -typically {login, password}- will be sent as-is to the server.
myalert = function(msg){
alert(msg);
};
Storage.prototype.setItemSTD = Storage.prototype.setItem; // save a copy of standard localStorage.setItem() function, which is monkey-patched when using LocalStorage driver
Storage.prototype.removeItemSTD = Storage.prototype.removeItem; // save a copy of standard localStorage.setItem() function, which is monkey-patched when using LocalStorage driver
function pad(a,b){return(1e15+a+"").slice(-b)}
logMs = function(s){
var prev;
if ( typeof now != "undefined" )
prev = now;
else
prev = new Date();
now = new Date();
var diff = now.getTime()-prev.getTime();
console.log(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + ":" + pad(now.getMilliseconds(),3) + " (" + diff + ") - " + s);
};
// Simple ployfill for Object.values() function
if ( !Object.values )
Object.values = (obj)=>Object.keys(obj).map(key=>obj[key]);
// Save original IndexedDB.open() function before disabling it if necessary
const idb = indexedDB || window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
if ( idb )
idb.openSTD = idb.open;
// Substitute for jquery .ready() function
(function(funcName, baseObj) {
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
function ready() {
if (!readyFired) {
readyFired = true;
for (var i = 0; i < readyList.length; i++)
readyList[i].fn.call(window, readyList[i].ctx);
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else
readyList.push({fn: callback, ctx: context});
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", ready, false);
window.addEventListener("load", ready, false);
} else {
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);
SyncClient.prototype.localStorageItemsPrefix = "syncProxy.";
SyncClient.prototype.setItem = function(key, value){
localStorage.setItemSTD(this.localStorageItemsPrefix + key, value);
};
SyncClient.prototype.getItem = function(key){
return localStorage.getItem(this.localStorageItemsPrefix + key);
};
SyncClient.prototype.removeItem = function(key){
localStorage.removeItemSTD(this.localStorageItemsPrefix + key);
};
SyncClient.prototype.setPrivateItem = function(key, value){
localStorage.setItemSTD(this.localStorageItemsPrefix + this.proxyId + "." + key, value);
};
SyncClient.prototype.getPrivateItem = function(key){
return localStorage.getItem(this.localStorageItemsPrefix + this.proxyId + "." + key);
};
SyncClient.prototype.removePrivateItem = function(key){
localStorage.removeItemSTD(this.localStorageItemsPrefix + this.proxyId + "." + key);
};
SyncClient.prototype.defaultParams = {
"protocol": "wss", // ws / wss
"serverUrl": "my.syncproxy.com", // Default: "my.syncproxy.com";
"serverPort": 4501, // Default: 4501
"proxyId": "", // ID of the server-side sync proxy to sync with. If blank, user's default sync proxy will be retrieved by sync server
"connectorType": "IndexedDB", // Client database connector: IndexedDB / WebSQL / SQLite / LocalStorage / IonicStorage / SQLJS
"dbName": "", // Client databse name
"dbLocation": "default", // Client databse location (used by SQLite driver)
"autoUpgradeDB": "true", // If set to false, database's structure will not be upgraded by sync (in that case, app should manage schema updates by itself).
"physicalSchemaReadDelay": "5000", // Delay after which, if no sync schema was found, the sync client will try to read the schema from the physical data store
"autoInit": true, // If true, sync client will be started automatically. If false, sync client should be created by calling SyncClient.initClient(params)
"reactiveSync": true, // If true, enables reactive sync. Reactivity for each table + direction (server->client and client->server) is configured on server side
"syncButton": true, // If "true" (=draggable) or "fixed", enables reactive sync. Reactivity for each table + direction (server->client and client->server) is configured on server side
"tablesToSync": [], // List of tables to sync with sync profiles (sync direction + reactivity)
"customCredentials": "", // Custom credential function. Typically returns a {login, password} object which will be sent as-is to the server.
"login": "", // Default user login.
"loginSource": "", // User login source for sync server, for instance: "document.getElementById('inputLogin').value"
"passwordSource": "", // User password source for sync server, for instance: "document.getElementById('inputPassword').value"
"zipData": true, // If true, server changes are zipped before being sent
"welcomeMessage": "To begin, please press Sync button",
"onServerChanges": "", // Custom function called after each chunk received from server. Changes are passed as a parameter to the handler function.
"onSyncEnd": function(){console.log('onSyncEnd')}, // Custom function called after sync end
"useSessionStorage": false // Use sessionStorage instead of localStorage
};
function SyncClient(params){
// Script params can be passed directly in <script> tag referring syncclient.js
for ( var p in SyncClient.prototype.scriptParams ){
if ( params && (typeof params[p] != "undefined") )
this[p] = params[p];
else
this[p] = SyncClient.prototype.defaultParams[p];
}
// For testing purpose localStorage can be replaced with volatile sessionStorage (enables browser multi-tabs testing with different sync clients)
if ( this.useSessionStorage && this.useSessionStorage.toString() == "true" ){
delete localStorage;
localStorage = sessionStorage;
}
var reactive = false;
this.lastAuthFailed = false;
this.serverConnection = null;
this.connector = null;
this.showStatus = true;
this.resetSyncsPending();
var self = this;
var textDecoderPolyfill = function(){return Promise.resolve();};
if ( typeof TextDecoder == "undefined" )
textDecoderPolyfill = function(){return includeFile("libs/textencode-decode.js");};
textDecoderPolyfill()
.then(()=>includeFile("libs/pako.min.js")) // zip library
.then(()=>{return includeFile("db-connectors/base.js");})
.then(()=>{
if ( self.connectorType == "IonicStorage" ){
self.dbName = "_ionicstorage"; // name of the database of Ionic Storage key-value pair store when used in IndexedDB (and WebSQL ?)
self.connectorType = DBConnector.getPreferredIonicStorage();
self.tablesToSync = ["_ionickv"];
}
if ( !(self.tablesToSync instanceof Array) )
self.tablesToSync = self.tablesToSync.split(','); // tablesToSync may be passed as a list of tables separated with ","
if ( (self.connectorType == "WebSQL") || (self.connectorType == "SQLite") || (self.connectorType == "SQLJS") )
return includeFile("db-connectors/sql-base.js")
.then(()=>{
if ( (self.connectorType == "WebSQL") || (self.connectorType == "SQLite") )
return includeFile("db-connectors/sqlite-base.js")
});
})
.then(()=>{self.loadSchema(); return self.loadConnector(self.connectorType, self.dbName);})
.then(()=>includeFile("libs/toastada.js"))
.then(()=>includeFile("libs/toastada.css", "link"))
.then(()=>{
// self.loadSchema();
var upgradePromise;
if ( self.upgradeNeeded(self.schema) ){
upgradePromise = self.upgradeDatabase({version:self.schema.version, Tables:self.schema.Tables});
}
else
upgradePromise = Promise.resolve(false); // no recent change in schema
return upgradePromise
.then(()=>includeFile("sync-client-custom.js"))
.then(()=>{ self.loadSyncProfile(); reactive = this.hasReactiveSync();})
.then(()=>{
var tablesToSync = this.getTablesToSync();
if ( (reactive || !tablesToSync || !tablesToSync.length) && self.isOnline() )
return self.connect() // on connected will start a full sync
.catch(err=>self._onConnectionError(err));
});
})
.then(()=>{
if ( self.syncButton ){
docReady(function(){self.createSyncButton();});
}
if (!this.getSyncClientCode() && this.welcomeMessage && (this.welcomeMessage != ""))
this.showToast(this.welcomeMessage)
SyncClient.defaultClient.sendEvent("clientReady");
})
.catch(err=>console.log(err));
// Reactive sync needs to be notified of changes in online status.
//if ( reactive )
{
window.addEventListener('online', function(){self._onOnline();});
window.addEventListener('offline', function(){self._onOffline()});
}
window.addEventListener('syncPending', function(e){self._onSyncPending(e.detail.reactive)});
if ( self.onServerChanges )
window.addEventListener('serverChanges', function(e){eval(self.onServerChanges)(e.detail.changes);}); // call a custom function if any
if ( self.onSyncEnd )
window.addEventListener('syncEnd', function(e){eval(self.onSyncEnd)();}); // call a custom function if any
}
SyncClient.prototype.disableIndexedDBOpen = function(){
// Patch original database open function used by app, to avoid possible database lock conflict with sync client during database upgrade.
var params = SyncClient.prototype.scriptParams;
var syncClientCode = this.getItem(params.proxyId + ".syncClientCode");
var syncClientCode = this.getItem(params.proxyId + ".syncClientCode");
var mustUpgrade = false;
if (params.autoUpgradeDB.toString() != "false")
mustUpgrade = this.getItem(params.dbName + ".mustUpgrade");
if ( (params.connectorType == "IndexedDB") || ((params.connectorType == "IonicStorage") && (DBConnector.getPreferredIonicStorage() == "IndexedDB"))){
if ( (params.autoUpgradeDB.toString() != "false") && (!syncClientCode || (mustUpgrade.toString() == "true")) ){
idb.indexedDBOpenDisabled = true;
idb.open = function(dbName){
console.log("IndexedDB.open() function has been disabled until sync complete and database ready");
idb.restartNeeded = true;
return null;
};
}
}
else if ( idb )
delete idb.openSTD; // backup of IndexedDB.open() function is not needed: reset it
};
SyncClient.prototype.resetIndexedDBOpen = function(){
// Reset original database open function used by app, if it was patched (to prevent database version collision with app), restore original open
var self = this;
if ( (this.connectorType == "IndexedDB") || ((this.connectorType == "IonicStorage") && (DBConnector.getPreferredIonicStorage() == "IndexedDB"))){
if ( !idb )
return;
if (idb && idb.indexedDBOpenDisabled){
delete idb.indexedDBOpenDisabled;
idb.open = function(dbName, version, cb){
idb.restartNeeded = false; // give a chance to app to avoid restart if it calls db.open() again (restart will apply only if app calls db.open() once at launch)
return idb.openSTD(dbName, version, cb);
};
window.setTimeout(function(){
if ( idb.restartNeeded ){
console.log("App attempt to open IndexedDB on start was blocked by sync client's database update. App will restart.");
self.showToast("Application needs to restart", "warning");
window.setTimeout(function(){
self.stopAutoReconnect();
if ( self.serverConnection )
self.serverConnection.close();
}, 100);
window.setTimeout(function(){
location.reload();
}, 3000);
}
else
console.log("IndexedDB.open() was reset to original");
}, 1000);
}
}
};
SyncClient.prototype.saveSchema = function(schema){
this.setItem(this.proxyId + ".schema", JSON.stringify(schema));
};
SyncClient.prototype.loadSchema = function(){
var s = this.getPrivateItem("schema");
if ( s )
this.schema = JSON.parse(s);
return this.schema;
};
// Compare schema version and current DB version to decide wether to upgrade database.
SyncClient.prototype.upgradeNeeded = function(schema){
var needed = ( (this.autoUpgradeDB.toString() != "false") && schema && (schema.version > this.connector.getDBVersion()) );
if ( !needed )
this.saveMustUpgrade(false);
return needed;
};
SyncClient.prototype.saveSyncProfile = function(syncProfile){
this.setItem(this.proxyId + ".syncProfile", JSON.stringify(syncProfile));
};
SyncClient.prototype.loadSyncProfile = function(syncProfile){
var s = this.getItem(this.proxyId + ".syncProfile");
if ( s )
this.syncProfile = JSON.parse(s);
return this.syncProfile;
};
SyncClient.prototype.cacheSyncProfile = function(syncRules){
if ( syncRules != "clientTablesToSync" ){
this.syncProfile = [];
for ( var r in syncRules ){
var table = {};
table[r] = syncRules[r];
this.syncProfile.push(table);
}
this.saveSyncProfile(this.syncProfile);
}
};
///////////////
// Utilities //
///////////////
function includeFile(url, type){
url = url.toLowerCase();
if ( !type )
type = "script";
return new Promise(function(resolve, reject){
var prop = "src";
if ( type == "link" )
prop = "href";
if ( document.querySelector(type + '[' + prop + '$="' + url + '"]') )
return resolve("Already included"); // do not include the same file twice
var root = document.querySelector('script[src$="sync-client.js"]').getAttribute('src').split('/')[0] + "/";
if ( root.indexOf("sync-client") == -1 )
root += "sync-client/";
var script = document.createElement(type);
if ( type == "script" )
script.type = 'text/javascript';
else if ( type == "link" )
script.rel = "stylesheet";
script[prop] = root + url;
script.id = url;
script.onload = function(e){
script.loaded = true;
resolve("OK");
};
document.getElementsByTagName('head')[0].appendChild(script);
});
}
function Translate(message){
return message;
};
SyncClient.prototype.loadConnector = function(connectorType, dbName){
var self = this;
return includeFile("db-connectors/" + connectorType.toLowerCase() + ".js")
.then(function(){
self.connector = eval("new DBConnector" + connectorType + "('" + dbName + "', self)");
console.log("Data connector " + connectorType + " successfully loaded");
});
};
////////////////////////////
// Status change handlers //
////////////////////////////
SyncClient.prototype.sendEvent = function(msg, detail){
if ( CustomEvent )
window.dispatchEvent(new CustomEvent(msg, {detail:detail}));
};
SyncClient.prototype.resetSyncsPending = function(){
this.clientSyncsPending = 0;
this.serverSyncsPending = 0;
}
SyncClient.prototype._onOffline = function(){
this.showToast("Offline", "warning");
this.resetSyncsPending();
this.lastSyncFailed = false;
this.updateSyncButton();
if (this.serverConnection){
this.serverConnection.close();
this.serverConnection = null
}
};
SyncClient.prototype._onOnline = function(){
this.showToast("Online", "success");
this.showNextConnectAttempt = true;
var self = this;
this.updateSyncButton();
window.setTimeout(function(){
if (self.hasReactiveSync()){
console.log("Reactive sync mode...");
self.fullSync();
}
}, 1000);
};
SyncClient.prototype._onConnected = function(){
var self = this;
this.disableAutoReconnect = true;
if ( this.connectInterval )
this.stopAutoReconnect();
this.lastSyncFailed = false;
this.connected = true;
this.updateSyncButton();
if ( this.hasReactiveSync() )
window.setTimeout(function(){self.fullSync();}, 0);
this.sendEvent("connected");
};
SyncClient.prototype._onAuthenticated = function(){
this.lastSyncFailed = false;
this.updateSyncButton();
this.sendEvent("authenticated");
};
SyncClient.prototype._onConnectionError = function(){
this.resetSyncsPending();
this.lastSyncFailed = true;
delete this.serverConnection;
this.connected = false;
if (this.showStatus || this.showNextConnectAttempt)
this.showToastUnique("Could not contact server", "error");
this.showNextConnectAttempt = false;
this.updateSyncButton();
this.autoReconnect();
this.sendEvent("connectionError");
};
SyncClient.prototype._onDisconnected = function(){
this.resetSyncsPending();
this.serverConnection = null;
this.connected = false;
if (this.showStatus)
this.showToast("Disconnected", "warning");
this.updateSyncButton();
this.autoReconnect();
this.sendEvent("disconnected");
};
SyncClient.prototype._onSyncPending = function(reactive){
var self = this;
self.updateSyncButton();
if (!reactive)
this.showToastUnique("Sync started...", "info");
};
SyncClient.prototype._onServerChanges = function(changes){
this.sendEvent("serverChanges", {changes:changes});
};
SyncClient.prototype._onClientChangesReceived = function(){
this.sendEvent("clientChangesReceived");
};
SyncClient.prototype._onSyncEnd = function(reactive){
const self = this;
this.resetChunkNumber();
this.updateSyncButton();
if ( !reactive )
this.showToast("Sync ended successfully", "success");
this.resetIndexedDBOpen(); // reset app's normal database open function
if ( !this.mustUpgrade ){
this.setPrivateItem("firstSyncDone", true);
this.sendEvent("syncEnd", {reactive:reactive, serverModifiedTables:Array.from(self.serverModifiedTables)});
self.serverModifiedTables = new Set();
}
};
SyncClient.prototype._onSyncCancel = function(msg){
this.showToast(msg, "warning");
this.resetSyncsPending();
this.updateSyncButton();
this.sendEvent("syncCancel");
};
SyncClient.prototype._onSyncError = function(err){
// Reset keys of changes being sent.
this.resetSendings();
var self = this;
if ( (err.warning == "SESSION FAILURE") || (err.err == "MISSING FOLDER") )
this.resetChunkNumber();
if ( (err == "Cancel") || (err.err == "AUTH FAILURE") || (err.warning == "SESSION FAILURE") ){
// Will force a new authentication with login/password
if ( this.sessionId )
delete this.sessionId;
this.lastAuthFailed = true;
this.stopAutoReconnect();
this.disableAutoReconnect = true;
if ( this.password )
delete this.password;
}
if ( err.warning && err.message )
this.showToast(err.message, "warning");
else if ( err.warning )
this.showToast(err.warning, "warning");
else if (err != "Cancel"){
this.lastSyncFailed = true;
// if ( err == "Not authenticated" )
// this.showToast("Not authenticated", "error");
if ( err && err.err && err.message && (err.message.toString() != "[object Object]") )
this.showToast(err.err + ": " + err.message, "error");
else if (err && err.err)
this.showToast(err.err, "error");
else if (err && err.message)
this.showToast(err.message);
else if (typeof err == "string")
this.showToast("Sync error: " + err, "error");
else
this.showToast("Sync error", "error");
}
if ( err.warning == "SESSION FAILURE" ){
window.setTimeout(function(){self.showToast("Next sync will start a new session", "info");}, 5000);
}
this.resetSyncsPending();
this.updateSyncButton();
this.sendEvent("syncError");
};
SyncClient.prototype.isOnline = function(){
return navigator.onLine;
};
SyncClient.prototype.isConnected = function(){
if ( !this.connected )
return false;
return true;
};
SyncClient.prototype.isAuthenticated = function(){
if ( this.sessionId )
return true;
else
return false;
};
/////////////////////////////////
// User notification functions //
/////////////////////////////////
SyncClient.prototype.showToastUnique = function(msg, style){
this.removeAllToasts();
this.showToast(msg,style);
};
SyncClient.prototype.showToast = function(msg, style){
// Styles: success, info, warning, error
if ( !style )
style = "warning";
// style = "succe";
switch(style){
case "warning":
toastada.warning(msg);
break;
case "success":
toastada.success(msg);
break;
case "info":
toastada.info(msg);
break;
case "error":
toastada.error(msg);
break;
};
};
SyncClient.prototype.showAlert = function(msg){
var self = this;
var modal = new tingle.modal({
// Show a tingle modal dialog (https://robinparisi.github.io/tingle/)
footer: true,
stickyFooter: false,
closeMethods: ['overlay', 'button', 'escape'],
closeLabel: "Close",
cssClass: ['custom-class-1', 'custom-class-2'],
onOpen: function() {
},
onClose: function() {
}
});
modal.setContent("<p>" + msg + "</p>" );
modal.addFooterBtn('OK', 'tingle-btn tingle-btn--primary tingle-custom-btn', function() {
modal.close();
});
document.addEventListener("keydown", function(evt){
switch ( evt.which ){
case 13: // add missing support for "Enter" key validation.
case 27: // Cancel
modal.close();
}
});
modal.open();
};
///////////////////////////////
// Servers messages handlers //
///////////////////////////////
SyncClient.prototype.onServerMessage = function(msg, synchronousRequestType){
// Types of server messages handled:
// * serverSync => contains a list of modified tables)
var self = this;
return new Promise(function(resolve,reject){
var data, zipped;
var firstChar = msg.substr(0,1);
if ( self.zipData && (self.zipData.toString() == "true") && (['{'].indexOf(firstChar) == -1) ){
console.log("Unzipping received data...");
// The stream doesn't start with a JSON start character: it is supposed to be a zipped JSON string (unless an error was encountered).
try {
var u = pako.inflate(atob(msg));
msg = new TextDecoder().decode(u);
} catch (err) {
console.log(err);
}
}
var continued = "";
if ( msg.length > 100000)
continued = "...";
console.log('Received: ' + msg.substr(0,100000) + continued);
try{data = JSON.parse(msg);}
catch(e){
self.showToast("Bad server data format", "error");
return reject("Bad server data format");
}
if ( data.chunk )
console.log("Receiving server data chunk #" + data.chunk);
if ( data && data.err ){
self._onSyncError(data);
return resolve(data);
// return reject(data);
}
if ( data && data.warning ){
self._onSyncError(data);
// self.handleServerWarning(data);
return resolve(data);
}
if ( synchronousRequestType == "authentication"){
self.sessionId = data.sessionId;
if ( data.clientCode )
self.saveSyncClientCode(data.clientCode);
self.saveUserName(data.userName, data.userLastName)
self._onAuthenticated();
return resolve(data);
}
else if ( synchronousRequestType == "getSchemaUdpate"){
if (self.clientSyncsPending > 0)
self.clientSyncsPending--;
if ( data.schema && data.schema.Tables && data.schema.Tables.length )
self.onSchemaUpdate(data.schema);
return resolve();
}
else if ( synchronousRequestType == "getSyncProfile"){
// User sync profile received
if (self.clientSyncsPending > 0)
self.clientSyncsPending--;
// if ( data.syncRules == {} )
if ( data == {} )
return reject("No tables to sync");
else{
self.cacheSyncProfile(data);
return self.getAndSendClientChanges(self.syncType == 2)
.then(()=>resolve());
}
}
if ( data.serverSync ){
// A server sync has been orderd by server => json.serverSync contains the list of tables to sync.
if ( !self.serverSyncsPending && !self.clientSyncsPending ){
if ( data.serverSync.length && (data.serverSync[0].indexOf(",") >= 0) )
data.serverSync = data.serverSync[0].split(",").map(x=>x.trim());
self.serverSync(true, data.serverSync, true)
.then(res=>resolve(res));
}
else
return resolve();
}
else if ( data.clientChangesReceived ) {
// Server has received client changes
if (self.clientSyncsPending > 0)
self.clientSyncsPending--;
if ( data.clientChangesReceived == -1 ){
console.log("No client changes");
logMs("CLIENT SYNC END");
if (self.syncType == 2)
self._onSyncEnd(true);
else if (!self.serverSyncsPending)
self.serverSync()
.then(()=>resolve());
else
resolve();
}
else{
self._onClientChangesReceived();
console.log("Client changes sent");
if ( data.conflicts )
self.showToast(data.conflicts + " conflicted data");
self.resetSentChanges()
.then(res=>logMs("CLIENT SYNC END"))
.then(()=>{
// If sync pending type was reactive, sync is over after client changes are received. Otherwise (full sync), it will terminate after server sync.
if (self.syncType == 2){
// Sync is over, unless client still has changes to send
if (!self.allChangesSent )
self.clientSync(true);
else
self._onSyncEnd(true);
}
else if ( !self.serverSyncsPending)
self.serverSync()
.then(()=>resolve());
else
resolve();
})
.then(()=>resolve());
}
}
else if ( data.Deletes || data.Updates || data.Inserts ){
// Changes received from server.
self.serverModifiedTables = new Set([ ...self.serverModifiedTables, ...Object.keys(data.Deletes || {}), ...Object.keys(data.Updates || {}), ...Object.keys(data.Inserts || {}) ]);
// If data.chunk is definend: data has been chunked by server to reduce stream size: handle received data, then request the next chunk
self.handleServerChanges(data)
.then(res=>{
if ( data.chunk ){
self.saveChunkNumber(data.chunk); // save chunk for recovery if necessary
return self.requestNextChunk(data.chunk);
}
else{
handledTables = res;
return self.endServerSync(handledTables);
}
})
.then(res=>resolve(res));
}
else if ( data.end ){
// Server sync just ended
logMs("SERVER SYNC END");
if (self.serverSyncsPending > 0)
self.serverSyncsPending--;
self._onSyncEnd(self.syncType == 2);
}
else{
self._onSyncError("Bad server response");
return resolve("Bad server response");
}
});
};
SyncClient.prototype.showMustUpgradeWarning = function(){
this._onSyncCancel("Database initialization... Application will restart", "warning");
var self = this;
window.setTimeout(function(){
self.stopAutoReconnect();
if ( self.serverConnection )
self.serverConnection.close();
}, 1000);
window.setTimeout(function(){
location.reload();
}, 3000);
};
SyncClient.prototype.onSchemaUpdate = function(schema){
// Schema update received
console.log("onSchemaUpdate");
this.saveSchema(schema);
this.mustUpgrade = this.upgradeNeeded(schema);
this.saveMustUpgrade(true);
if (this.mustUpgrade)
this.showMustUpgradeWarning();
};
////////////////////
// Authentication //
////////////////////
SyncClient.prototype.promptUserLogin = function(){
// Open a modal dialog to prompt user's crendentials. The result is returned as a {login, password} object in the promise's resolve().
var self = this;
if ( !self.login )
self.login = "";
return new Promise(function(resolve,reject){
var login = "";
var password = "";
if ( (typeof self.loginModal != "undefined") && self.loginModal.isOpen() )
return;
self.loginModal = new tingle.modal({
// Show a tingle modal dialog (https://robinparisi.github.io/tingle/)
footer: true,
stickyFooter: false,
closeMethods: ['overlay', 'button', 'escape'],
closeLabel: "Close",
cssClass: ['custom-class-1', 'custom-class-2'],
onOpen: function() {
},
onClose: function() {
reject("Cancel");
},
beforeClose: function() {
login = document.getElementById("spLogin").value;
password = document.getElementById("spPassword").value;
if ( !password )
password = "";
self.setItem(self.proxyId + ".lastLogin", login);
return true; // close the dialog
// return false; // nothing happens
}
});
var showFailure = "hidden";
if ( self.lastAuthFailed )
showFailure = "show";
self.loginModal.setContent("<h1 class='tingle-custom-title'>Please enter your sync login</h1>"
+ "<label class='tingle-custom-label'>E-mail:</label> <input id='spLogin' class='tingle-custom-input' onkeydown='document.getElementById(\"lblAuthFailure\").style.visibility=\"hidden\";' value='" + self.login + "' onpaste='return false;'/><br><br>"
+ "<label class='tingle-custom-label'>Password:</label> <input id='spPassword' type='password' class='tingle-custom-input' onkeydown='document.getElementById(\"lblAuthFailure\").style.visibility=\"hidden\";' value=''/><br><br>"
+ "<p class='tingle-custom-text'>If you don't have a login yet, please go to <a href='www.syncproxy.com'>www.syncproxy.com</a> to signup and join or create a sync group.</p>"
+ "<p id='lblAuthFailure' class='tingle-custom-text tingle-red-text' style='visibility:" + showFailure + "'>Authentication failure</p>");
self.loginModal.addFooterBtn('OK', 'tingle-btn tingle-btn--primary tingle-custom-btn', function() {
if ( document.getElementById("spLogin").value == "" )
return;
self.loginModal.close();
resolve({login:login, password:password});
});
self.loginModal.addFooterBtn('Cancel', 'tingle-btn tingle-btn--default tingle-custom-btn', function() {
self.loginModal.close();
reject("Cancel");
});
// document.getElementById("spLogin").parentElement.onkeydown = function(evt){
document.addEventListener("keydown", function(evt){
switch ( evt.which ){
case 13: // add missing support for "Enter" key validation.
self.loginModal.close();
resolve({login:login, password:password});
break;
case 27: // add rejection on Esc pressed (cancel)
reject("Cancel");
}
});
self.loginModal.open();
});
};
SyncClient.prototype.getCredentials = function(){
// Get credential from source objects within application, or using a modal to prompt login/password.
if ( this.loginSource && this.passwordSource ){
this.login = eval(this.loginSource);
this.password = eval(this.loginPassword);
}
if ( this.login && this.password )
return Promise.resolve({login:this.login, password:this.password});
if ( this.getItem(this.proxyId + ".lastLogin") )
this.login = this.getItem(this.proxyId + ".lastLogin");
var self = this;
var cred = this.getCustomCredentials(); // source objects may be defined to get credentials from.
if ( cred )
return Promise.resolve(cred);
else
return includeFile("libs/tingle.js")
.then(()=>includeFile("libs/tingle.css", "link"))
.then(()=>includeFile("libs/tingle-custom.css", "link"))
.then(()=>{return self.promptUserLogin();})
.then(res=>{if (!res.login) return null; self.login = res.login; self.password = res.password; return res;})
};
SyncClient.prototype.getCustomCredentials = function(){
if ( !this.customCredentials || (this.customCredentials == "") )
return null;
return eval(this.customCredentials);
};
////////////////////
// Sync functions //
////////////////////
SyncClient.initClient = function(params){
SyncClient.defaultClient = new SyncClient(SyncClient.prototype.scriptParams);
};
SyncClient.getScriptParams = function() {
var scripts = document.getElementsByTagName('script');
lastScript = scripts[scripts.length-1];
var result = {};
for ( var p in SyncClient.prototype.defaultParams ){
var attr = lastScript.getAttribute(p);
if ( attr )
result[p] = attr;
else
result[p] = SyncClient.prototype.defaultParams[p];
}
return result;
}
SyncClient.prototype.getSyncIcon = function(){
// "offline" = offline (no network)
// "sync" = not authenticated (has a network connection BUT not connected with server OR not authenticated)
// "sync-ok" = connected with server AND authenticated (valide sessionId)
// "auto sync" = connected with server AND authenticated with reactive sync
// "sync error" = last sync failed
if ( this.lastSyncFailed )
return "sync-error";
else if (!this.isOnline() )
return "offline";
else {
// Online
if ( !this.mustUpgrade ){
var reactive = this.hasReactiveSync();
if ( this.isConnected() && this.isAuthenticated() && reactive )
return "sync-auto";
else if ( this.isConnected() && this.isAuthenticated() )
return "sync-ok";
else if ( !reactive || !this.connectInterval )
// Display "sync" button (unless reactive mode and last connect attempt failed)
return "sync";
}
return "online";
}
};
SyncClient.prototype.updateSyncButton = function(pressed){
this.syncIcon = this.getSyncIcon();
if ( !this.syncBtn ){
this.syncBtn = document.createElement("img");
// this.syncBtn = document.createElement("button");
this.syncBtn.alt = "Sync";
}
this.syncBtn.alt = "";
// if ( this.syncBtn.src != "sync-client/libs/" + this.syncIcon + ".png" )
// this.syncBtn.src = "sync-client/libs/" + this.syncIcon + ".png";
this.syncBtn.className = "sync-button " + this.syncIcon;
if ( this.mustUpgrade || !this.isOnline() )
//if ( !this.isOnline() )
this.syncBtn.className += " sync-button-disabled";
else if ( pressed )
this.syncBtn.className += " sync-button-pressed";
if ( this.clientSyncsPending || this.serverSyncsPending )
this.syncBtn.className += " sync-button-rotating";
};
getBodyZoom = function(){
if ( !document.body.style.zoom )
return null;
return window.getComputedStyle(document.body).zoom;
};
getSyncBtnBounds = function(){
};
SyncClient.prototype.initSyncButtonPos = function(){
// Center button horizontally at the bootom
var newLeft = parseInt(parseInt(window.innerWidth)/2 - parseInt(this.syncBtn.offsetWidth)/2);
var newTop = (Math.max(parseInt(document.body.scrollHeight), window.innerHeight || 0) - parseInt(this.syncBtn.offsetHeight));
const zoom = getBodyZoom();
if ( zoom ){
console.log("Zoom: " + zoom);
newLeft = newLeft * zoom;
newTop = newTop * zoom;
}
this.syncBtn.style.left = newLeft + "px";
this.syncBtn.style.top = newTop + "px";
};
SyncClient.prototype.createSyncButton = function(){
includeFile("libs/sync-button.css", "link");
var self = this;
window.onresize = function(e){
self.initSyncButtonPos(e);
};
this.updateSyncButton();
window.setTimeout(function(){
// Set button position, once its height & width are known (therefore we use a timeout)
self.initSyncButtonPos();
}, 1000);
const getPageXY = function(e){
if ( (typeof TouchEvent != "undefined") && (e instanceof TouchEvent) && e.changedTouches[0])
return {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY};
else
return {x: e.pageX, y: e.pageY};
};
if ( this.syncButton == "fixed" ){
this.syncBtn.addEventListener("click", function(){
self.syncButtonPressed();
});
} else {
this.syncBtn.drag = function(e){
e.preventDefault();
self.updateSyncButton(true);
self.syncBtn.moved = false;
self.syncBtn.obj = self.syncBtn;
var pageXY = getPageXY(e);
self.syncBtn.prev_x = pageXY.x - self.syncBtn.obj.offsetLeft;
self.syncBtn.prev_y = pageXY.y - self.syncBtn.obj.offsetTop;
};
this.syncBtn.move = function(e) {
if ( (typeof TouchEvent != "undefined") && (e instanceof TouchEvent) && (e.target != self.syncBtn) )
return;
var pageXY = getPageXY(e);
// If the object specifically is selected, then move it to the X/Y coordinates that are always being tracked.
if (self.syncBtn.obj) {
if ( Math.pow(self.syncBtn.prev_x + self.syncBtn.x - pageXY.x, 2) + Math.pow(self.syncBtn.prev_y + self.syncBtn.y - pageXY.y, 2) > 2 ) // click is tolerant to mini-movements (max 1px on X and 1px on Y)
self.syncBtn.moved = true;