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
|
/*
* This file is part of TbSync.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
"use strict";
/**
*
*/
var StatusData = class {
/**
* A StatusData instance must be used as return value by
* :class:`Base.syncFolderList` and :class:`Base.syncFolder`.
*
* StatusData also defines the possible StatusDataTypes used by the
* :ref:`TbSyncEventLog`.
*
* @param {StatusDataType} type Status type (see const definitions below)
* @param {string} message ``Optional`` A message, which will be used as
* sync status. If this is not a success, it will be
* used also in the :ref:`TbSyncEventLog` as well.
* @param {string} details ``Optional`` If this is not a success, it will
* be used as description in the
* :ref:`TbSyncEventLog`.
*
*/
constructor(type = "success", message = "", details = "") {
this.type = type; //success, info, warning, error
this.message = message;
this.details = details;
}
/**
* Successfull sync.
*/
static get SUCCESS() {return "success"};
/**
* Sync of the entire account will be aborted.
*/
static get ERROR() {return "error"};
/**
* Sync of this resource will be aborted and continued with next resource.
*/
static get WARNING() {return "warning"};
/**
* Successfull sync, but message and details
* provided will be added to the event log.
*/
static get INFO() {return "info"};
/**
* Sync of the entire account will be aborted and restarted completely.
*/
static get ACCOUNT_RERUN() {return "account_rerun"};
/**
* Sync of the current folder/resource will be restarted.
*/
static get FOLDER_RERUN() {return "folder_rerun"};
}
/**
* ProgressData to manage a ``done`` and a ``todo`` counter.
*
* Each :class:`SyncData` instance has an associated ProgressData instance. See
* :class:`SyncData.progressData`. The information of that ProgressData
* instance is used, when the current syncstate is prefixed by ``send.``,
* ``eval.`` or ``prepare.``. See :class:`SyncData.setSyncState`.
*
*/
var ProgressData = class {
/**
*
*/
constructor() {
this._todo = 0;
this._done = 0;
}
/**
* Reset ``done`` and ``todo`` counter.
*
* @param {integer} done ``Optional`` Set a value for the ``done`` counter.
* @param {integer} todo ``Optional`` Set a value for the ``todo`` counter.
*
*/
reset(done = 0, todo = 0) {
this._todo = todo;
this._done = done;
}
/**
* Increment the ``done`` counter.
*
* @param {integer} value ``Optional`` Set incrementation value.
*
*/
inc(value = 1) {
this._done += value;
}
/**
* Getter for the ``todo`` counter.
*
*/
get todo() {
return this._todo;
}
/**
* Getter for the ``done`` counter.
*
*/
get done() {
return this._done;
}
}
/**
* ProviderData
*
*/
var ProviderData = class {
/**
* Constructor
*
* @param {FolderData} folderData FolderData of the folder for which the
* display name is requested.
*
*/
constructor(provider) {
if (!TbSync.providers.hasOwnProperty(provider)) {
throw new Error("Provider <" + provider + "> has not been loaded. Failed to create ProviderData.");
}
this.provider = provider;
}
/**
* Getter for an :class:`EventLogInfo` instance with all the information
* regarding this ProviderData instance.
*
*/
get eventLogInfo() {
return new EventLogInfo(
this.getAccountProperty("provider"));
}
getVersion() {
return TbSync.providers.loadedProviders[this.provider].version;
}
get extension() {
return TbSync.providers.loadedProviders[this.provider].extension;
}
getAllAccounts() {
let accounts = TbSync.db.getAccounts();
let allAccounts = [];
for (let i=0; i<accounts.IDs.length; i++) {
let accountID = accounts.IDs[i];
if (accounts.data[accountID].provider == this.provider) {
allAccounts.push(new TbSync.AccountData(accountID));
}
}
return allAccounts;
}
getFolders(aFolderSearchCriteria = {}) {
let allFolders = [];
let folderSearchCriteria = {};
Object.assign(folderSearchCriteria, aFolderSearchCriteria);
folderSearchCriteria.cached = false;
let folders = TbSync.db.findFolders(folderSearchCriteria, {"provider": this.provider});
for (let i=0; i < folders.length; i++) {
allFolders.push(new TbSync.FolderData(new TbSync.AccountData(folders[i].accountID), folders[i].folderID));
}
return allFolders;
}
getDefaultAccountEntries() {
return TbSync.providers.getDefaultAccountEntries(this.provider)
}
addAccount(accountName, accountOptions) {
let newAccountID = TbSync.db.addAccount(accountName, accountOptions);
Services.obs.notifyObservers(null, "tbsync.observer.manager.updateAccountsList", newAccountID);
return new TbSync.AccountData(newAccountID);
}
}
/**
* AccountData
*
*/
var AccountData = class {
/**
*
*/
constructor(accountID) {
this._accountID = accountID;
if (!TbSync.db.accounts.data.hasOwnProperty(accountID)) {
throw new Error("An account with ID <" + accountID + "> does not exist. Failed to create AccountData.");
}
}
/**
* Getter for an :class:`EventLogInfo` instance with all the information
* regarding this AccountData instance.
*
*/
get eventLogInfo() {
return new EventLogInfo(
this.getAccountProperty("provider"),
this.getAccountProperty("accountname"),
this.accountID);
}
get accountID() {
return this._accountID;
}
getAllFolders() {
let allFolders = [];
let folders = TbSync.db.findFolders({"cached": false}, {"accountID": this.accountID});
for (let i=0; i < folders.length; i++) {
allFolders.push(new TbSync.FolderData(this, folders[i].folderID));
}
return allFolders;
}
getAllFoldersIncludingCache() {
let allFolders = [];
let folders = TbSync.db.findFolders({}, {"accountID": this.accountID});
for (let i=0; i < folders.length; i++) {
allFolders.push(new TbSync.FolderData(this, folders[i].folderID));
}
return allFolders;
}
getFolder(setting, value) {
// ES6 supports variable keys by putting it into brackets
let folders = TbSync.db.findFolders({[setting]: value, "cached": false}, {"accountID": this.accountID});
if (folders.length > 0) return new TbSync.FolderData(this, folders[0].folderID);
return null;
}
getFolderFromCache(setting, value) {
// ES6 supports variable keys by putting it into brackets
let folders = TbSync.db.findFolders({[setting]: value, "cached": true}, {"accountID": this.accountID});
if (folders.length > 0) return new TbSync.FolderData(this, folders[0].folderID);
return null;
}
createNewFolder() {
return new TbSync.FolderData(this, TbSync.db.addFolder(this.accountID));
}
// get data objects
get providerData() {
return new TbSync.ProviderData(
this.getAccountProperty("provider"),
);
}
get syncData() {
return TbSync.core.getSyncDataObject(this.accountID);
}
/**
* Initiate a sync of this entire account by calling
* :class:`Base.syncFolderList`. If that succeeded, :class:`Base.syncFolder`
* will be called for each available folder / resource found on the server.
*
* @param {Object} syncDescription ``Optional``
*/
sync(syncDescription = {}) {
TbSync.core.syncAccount(this.accountID, syncDescription);
}
isSyncing() {
return TbSync.core.isSyncing(this.accountID);
}
isEnabled() {
return TbSync.core.isEnabled(this.accountID);
}
isConnected() {
return TbSync.core.isConnected(this.accountID);
}
getAccountProperty(field) {
return TbSync.db.getAccountProperty(this.accountID, field);
}
setAccountProperty(field, value) {
TbSync.db.setAccountProperty(this.accountID, field, value);
Services.obs.notifyObservers(null, "tbsync.observer.manager.reloadAccountSetting", JSON.stringify({accountID: this.accountID, setting: field}));
}
resetAccountProperty(field) {
TbSync.db.resetAccountProperty(this.accountID, field);
Services.obs.notifyObservers(null, "tbsync.observer.manager.reloadAccountSetting", JSON.stringify({accountID: this.accountID, setting: field}));
}
}
/**
* FolderData
*
*/
var FolderData = class {
/**
*
*/
constructor(accountData, folderID) {
this._accountData = accountData;
this._folderID = folderID;
this._target = null;
if (!TbSync.db.folders[accountData.accountID].hasOwnProperty(folderID)) {
throw new Error("A folder with ID <" + folderID + "> does not exist for the given account. Failed to create FolderData.");
}
}
/**
* Getter for an :class:`EventLogInfo` instance with all the information
* regarding this FolderData instance.
*
*/
get eventLogInfo() {
return new EventLogInfo(
this.accountData.getAccountProperty("provider"),
this.accountData.getAccountProperty("accountname"),
this.accountData.accountID,
this.getFolderProperty("foldername"),
);
}
get folderID() {
return this._folderID;
}
get accountID() {
return this._accountData.accountID;
}
getDefaultFolderEntries() { // remove
return TbSync.providers.getDefaultFolderEntries(this.accountID);
}
getFolderProperty(field) {
return TbSync.db.getFolderProperty(this.accountID, this.folderID, field);
}
setFolderProperty(field, value) {
TbSync.db.setFolderProperty(this.accountID, this.folderID, field, value);
}
resetFolderProperty(field) {
TbSync.db.resetFolderProperty(this.accountID, this.folderID, field);
}
/**
* Initiate a sync of this folder only by calling
* :class:`Base.syncFolderList` and than :class:`Base.syncFolder` for this
* folder / resource only.
*
* @param {Object} syncDescription ``Optional``
*/
sync(aSyncDescription = {}) {
let syncDescription = {};
Object.assign(syncDescription, aSyncDescription);
syncDescription.syncFolders = [this];
this.accountData.sync(syncDescription);
}
isSyncing() {
let syncdata = this.accountData.syncData;
return (syncdata.currentFolderData && syncdata.currentFolderData.folderID == this.folderID);
}
getFolderStatus() {
let status = "";
if (this.getFolderProperty("selected")) {
//default
status = TbSync.getString("status." + this.getFolderProperty("status"), this.accountData.getAccountProperty("provider")).split("||")[0];
switch (this.getFolderProperty("status").split(".")[0]) { //the status may have a sub-decleration
case "modified":
//trigger periodic sync (TbSync.syncTimer, tbsync.jsm)
if (!this.isSyncing()) {
this.accountData.setAccountProperty("lastsynctime", 0);
}
case "success":
try {
status = status + ": " + this.targetData.targetName;
} catch (e) {
this.resetFolderProperty("target");
this.setFolderProperty("status","notsyncronized");
return TbSync.getString("status.notsyncronized");
}
break;
case "pending":
//add extra info if this folder is beeing synced
if (this.isSyncing()) {
let syncdata = this.accountData.syncData;
status = TbSync.getString("status.syncing", this.accountData.getAccountProperty("provider"));
if (["send","eval","prepare"].includes(syncdata.getSyncState().state.split(".")[0]) && (syncdata.progressData.todo + syncdata.progressData.done) > 0) {
//add progress information
status = status + " (" + syncdata.progressData.done + (syncdata.progressData.todo > 0 ? "/" + syncdata.progressData.todo : "") + ")";
}
}
break;
}
} else {
//remain empty if not selected
}
return status;
}
// get data objects
get accountData() {
return this._accountData;
}
/**
* Getter for the :class:`TargetData` instance associated with this
* FolderData. See :ref:`TbSyncTargets` for more details.
*
* @returns {TargetData}
*
*/
get targetData() {
// targetData is created on demand
if (!this._target) {
let provider = this.accountData.getAccountProperty("provider");
let targetType = this.getFolderProperty("targetType");
if (!targetType)
throw new Error("Provider <"+provider+"> has not set a proper target type for this folder.");
if (!TbSync.providers[provider].hasOwnProperty("TargetData_" + targetType))
throw new Error("Provider <"+provider+"> is missing a TargetData implementation for <"+targetType+">.");
this._target = new TbSync.providers[provider]["TargetData_" + targetType](this);
if (!this._target)
throw new Error("notargets");
}
return this._target;
}
// Removes the folder and its target. If the target should be
// kept as a stale/unconnected item, provide a suffix, which
// will be added to its name, to indicate, that it is no longer
// managed by TbSync.
remove(keepStaleTargetSuffix = "") {
// hasTarget() can throw an error, ignore that here
try {
if (this.targetData.hasTarget()) {
if (keepStaleTargetSuffix) {
let oldName = this.targetData.targetName;
this.targetData.targetName = TbSync.getString("target.orphaned") + ": " + oldName + " " + keepStaleTargetSuffix;
this.targetData.disconnectTarget();
} else {
this.targetData.removeTarget();
}
}
} catch (e) {
Components.utils.reportError(e);
}
this.setFolderProperty("cached", true);
}
}
/**
* There is only one SyncData instance per account which contains all
* relevant information regarding an ongoing sync.
*
*/
var SyncData = class {
/**
*
*/
constructor(accountID) {
//internal (private, not to be touched by provider)
this._syncstate = {
state: "accountdone",
timestamp: Date.now(),
}
this._accountData = new TbSync.AccountData(accountID);
this._progressData = new TbSync.ProgressData();
this._currentFolderData = null;
}
//all functions provider should use should be in here
//providers should not modify properties directly
//when getSyncDataObj is used never change the folder id as a sync may be going on!
_setCurrentFolderData(folderData) {
this._currentFolderData = folderData;
}
_clearCurrentFolderData() {
this._currentFolderData = null;
}
/**
* Getter for an :class:`EventLogInfo` instance with all the information
* regarding this SyncData instance.
*
*/
get eventLogInfo() {
return new EventLogInfo(
this.accountData.getAccountProperty("provider"),
this.accountData.getAccountProperty("accountname"),
this.accountData.accountID,
this.currentFolderData ? this.currentFolderData.getFolderProperty("foldername") : "",
);
}
/**
* Getter for the :class:`FolderData` instance of the folder being currently
* synced. Can be ``null`` if no folder is being synced.
*
*/
get currentFolderData() {
return this._currentFolderData;
}
/**
* Getter for the :class:`AccountData` instance of the account being
* currently synced.
*
*/
get accountData() {
return this._accountData;
}
/**
* Getter for the :class:`ProgressData` instance of the ongoing sync.
*
*/
get progressData() {
return this._progressData;
}
/**
* Sets the syncstate of the ongoing sync, to provide feedback to the user.
* The selected state can trigger special UI features, if it starts with one
* of the following prefixes:
*
* * ``send.``, ``eval.``, ``prepare.`` :
* The status message in the UI will be appended with the current progress
* stored in the :class:`ProgressData` associated with this SyncData
* instance. See :class:`SyncData.progressData`.
*
* * ``send.`` :
* The status message in the UI will be appended by a timeout countdown
* with the timeout being defined by :class:`Base.getConnectionTimeout`.
*
* @param {string} state A short syncstate identifier. The actual
* message to be displayed in the UI will be
* looked up in the locales of the provider
* by looking for ``syncstate.<state>``.
* The lookup is done via :func:`getString`,
* so the same fallback rules apply.
*
*/
setSyncState(state) {
//set new syncstate
let msg = "State: " + state + ", Account: " + this.accountData.getAccountProperty("accountname");
if (this.currentFolderData) msg += ", Folder: " + this.currentFolderData.getFolderProperty("foldername");
let syncstate = {};
syncstate.state = state;
syncstate.timestamp = Date.now();
this._syncstate = syncstate;
TbSync.dump("setSyncState", msg);
Services.obs.notifyObservers(null, "tbsync.observer.manager.updateSyncstate", this.accountData.accountID);
}
/**
* Gets the current syncstate and its timestamp of the ongoing sync. The
* returned Object has the following attributes:
*
* * ``state`` : the current syncstate
* * ``timestamp`` : its timestamp
*
* @returns {Object} The syncstate and its timestamp.
*
*/
getSyncState() {
return this._syncstate;
}
}
// Simple dumper, who can dump to file or console
// It is suggested to use the event log instead of dumping directly.
var dump = function (what, aMessage) {
if (TbSync.prefs.getBoolPref("log.toconsole")) {
Services.console.logStringMessage("[TbSync] " + what + " : " + aMessage);
}
if (TbSync.prefs.getIntPref("log.userdatalevel") > 0) {
let now = new Date();
TbSync.io.appendToFile("debug.log", "** " + now.toString() + " **\n[" + what + "] : " + aMessage + "\n\n");
}
}
/**
* Get a localized string.
*
* TODO: Explain placeholder and :: notation.
*
* @param {string} key The key of the message to look up
* @param {string} provider ``Optional`` The provider the key belongs to.
*
* @returns {string} The message belonging to the key of the specified provider.
* If that key is not found in the in the specified provider
* or if no provider has been specified, the messages of
* TbSync itself we be used as fallback. If the key could not
* be found there as well, the key itself is returned.
*
*/
var getString = function (key, provider) {
let localized = null;
//spezial treatment of strings with :: like status.httperror::403
let parts = key.split("::");
// if a provider is given, try to get the string from the provider
if (provider && TbSync.providers.loadedProviders.hasOwnProperty(provider)) {
let localeData = TbSync.providers.loadedProviders[provider].extension.localeData;
if (localeData.messages.get(localeData.selectedLocale).has(parts[0].toLowerCase())) {
localized = TbSync.providers.loadedProviders[provider].extension.localeData.localizeMessage(parts[0]);
}
}
// if we did not yet succeed, check the locales of tbsync itself
if (!localized) {
localized = TbSync.extension.localeData.localizeMessage(parts[0]);
}
if (!localized) {
localized = key;
} else {
//replace placeholders in returned string
for (let i = 0; i<parts.length; i++) {
let regex = new RegExp( "##replace\."+i+"##", "g");
localized = localized.replace(regex, parts[i]);
}
}
return localized;
}
var localizeNow = function (window, provider) {
let document = window.document;
let keyPrefix = "__" + (provider ? provider.toUpperCase() + "4" : "") + "TBSYNCMSG_";
let localization = {
i18n: null,
updateString(string) {
let re = new RegExp(keyPrefix + "(.+?)__", "g");
return string.replace(re, matched => {
const key = matched.slice(keyPrefix.length, -2);
return TbSync.getString(key, provider) || matched;
});
},
updateDocument(node) {
const texts = document.evaluate(
'descendant::text()[contains(self::text(), "' + keyPrefix + '")]',
node,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
for (let i = 0, maxi = texts.snapshotLength; i < maxi; i++) {
const text = texts.snapshotItem(i);
if (text.nodeValue.includes(keyPrefix)) text.nodeValue = this.updateString(text.nodeValue);
}
const attributes = document.evaluate(
'descendant::*/attribute::*[contains(., "' + keyPrefix + '")]',
node,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
for (let i = 0, maxi = attributes.snapshotLength; i < maxi; i++) {
const attribute = attributes.snapshotItem(i);
if (attribute.value.includes(keyPrefix)) attribute.value = this.updateString(attribute.value);
}
}
};
localization.updateDocument(document);
}
var localizeOnLoad = function (window, provider) {
// standard event if loaded by a standard window
window.document.addEventListener('DOMContentLoaded', () => {
this.localizeNow(window, provider);
}, { once: true });
// custom event, fired by the overlay loader after it has finished loading
// the editAccount dialog is never called as a provider, but from tbsync itself
let eventId = "DOMOverlayLoaded_"
+ (!provider || window.location.href.startsWith("chrome://tbsync/content/manager/editAccount.") ? "" : provider + "4")
+ "tbsync@jobisoft.de";
window.document.addEventListener(eventId, () => {
TbSync.localizeNow(window, provider);
}, { once: true });
}
var generateUUID = function () {
const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
return uuidGenerator.generateUUID().toString().replace(/[{}]/g, '');
}
|