-
Notifications
You must be signed in to change notification settings - Fork 3
/
background.js
2753 lines (2434 loc) · 106 KB
/
background.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
/// <reference path="intellisense.js" />
var g_dataTotalSpentThisWeek = { str: null, weeknum: null };
var g_msSyncRateLimit = 1000 * 1; //1 second (used to be larger and more relevant back when syncing on spreadsheets with my developer key
var MSDELAY_FIRSTSYNC = 500;
var g_bOffline = false;
var g_cErrorSync = 0; //errors during sync period. hack alert: it is set to specific values, does not really reflect a real count but a state
var g_strTimerLast = "";
var g_idTimeoutTimer = null;
var PLUS_BACKGROUND_CALLER = true; //allows us to tell shared.js we are calling
var g_bInstalledNetworkDetection = false;
var g_bDetectTrelloNetworkActivity = false;
var g_cTrelloActivitiesDetected = 0;
var g_bLastPlusMenuIconError = false; //remembers if the icon last drew the red error X
var g_mapTimerWindows = {}; // {idWindow, can be undefined or invalid }
const PROP_LS_cViewedBuyDialog = "plus_viewed_buy_dialog"; //count stored as string
var g_msUpdateNotificationReceived = 0; //0 means not received
const g_nameMinimizeTimer = "Min";
chrome.runtime.onInstalled.addListener(function (details) {
if (details && details.reason && details.reason == "install") {
handleShowDesktopNotification({
notification: "Welcome!\nRefresh or open a trello.com page to start.",
timeout: 8000
});
}
});
chrome.declarativeNetRequest.updateDynamicRules({
addRules: [
{
id: 1,
priority: 1,
action: {
type: "modifyHeaders",
requestHeaders: [{ header: "Referer", operation: "set", value: "https://trello.com/search" }],
},
condition: {
urlFilter: "https://trello.com/1/search",
resourceTypes: ["xmlhttprequest"],
},
},
],
});
function handleUpdateExtension(details) {
var versionNew = (details || { version: "" }).version || "";
if (!versionNew)
return;
var pair = {};
pair[LOCALPROP_EXTENSION_VERSIONSTORE] = versionNew;
chrome.storage.local.set(pair, function () {
if (chrome.runtime.lastError)
console.log(chrome.runtime.lastError.message);
else
g_msUpdateNotificationReceived = Date.now();
});
}
chrome.runtime.onUpdateAvailable.addListener(function (details) {
handleUpdateExtension(details);
});
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
var message;
if (string.indexOf(substring) > -1) {
message = 'Script Error: See background browser console for details. ' + msg;
} else {
message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
}
logPlusError(message, false);
return false;
};
function getConfigData(urlService, userTrello, callback, bSkipCache) {
var data = null;
//review zig: assumes g_optEnterSEByComment is loaded. should be. assert in IsEnabled ensures it wont continue if not.
if (g_optEnterSEByComment.IsEnabled())
urlService = ""; //to be more consistent with trello sync when no google user was configured
if (bSkipCache === undefined || bSkipCache === false)
data = localStorage.getItem("plus_config_data");
if (data !== undefined && data != null)
data = JSON.parse(data);
if (data === undefined)
data = null;
if (data != null)
callback(data);
else {
doCallUrlConfig(urlService, userTrello, callback);
}
}
function doCallUrlConfig(urlConfig, userTrello, callback) {
if (!urlConfig) {
callback(null);
return;
}
if (urlConfig.indexOf("https://docs.google.com/") == 0) {
//this is hacky, but it was the easiest way to enable the simple Plus case (without spent backend)
//pretend urlConfig is the gas script url until the last minute (here) where we build the config object
var config = doGetJsonConfigSimplePlus(urlConfig, userTrello);
localStorage.setItem("plus_config_data", JSON.stringify(config));
callback(config);
return;
}
handleShowDesktopNotification({
notification: "Incorrect google sync url",
timeout: 10000
});
callback(null);
return;
}
var DATAVERSION_SIMPLEPLUS = 1;
function doGetJsonConfigSimplePlus(url, user) {
var objRet = { version: DATAVERSION_SIMPLEPLUS, bSimplePlus: true };
var strFindKey = "key=";
var iKey = url.indexOf(strFindKey);
var bNewSheet = false;
if (iKey <= 0) {
strFindKey = "/d/";
iKey = url.indexOf(strFindKey);
if (iKey <= 0) {
objRet.status = "No spreadsheet key.";
return objRet;
}
bNewSheet = true;
}
var strRight = url.substr(iKey + strFindKey.length);
var parts = strRight.split("#gid=");
objRet.userTrello = user;
objRet.urlSsUser = url;
var partLeft = parts[0];
if (partLeft.indexOf("&") >=0)
partLeft = (partLeft.split("&"))[0];
if (bNewSheet && partLeft.indexOf("/") >= 0) //new sheets have "/edit"
partLeft = (partLeft.split("/"))[0];
objRet.idSsUser = partLeft;
objRet.idUserSheetTrello = gid_to_wid(parts[1]);
objRet.status = STATUS_OK;
return objRet;
}
// number to string
function gid_to_wid(gid) {
//thanks for new sheets support to http://stackoverflow.com/a/26893526/2213940
var idIsNewStyle = gid > 31578;
var xorValue = idIsNewStyle ? 474 : 31578;
var postValue = parseInt((gid ^ xorValue), 10).toString(36);
if (idIsNewStyle) {
return 'o' + postValue;
} else {
return postValue;
}
}
function standarizeSpreadsheetValue(value) {
if (value == "#VALUE!" || value == "--")
value = "";
if (typeof (value) == 'string' && value.indexOf("'") == 0)
value = value.substr(1);
return value;
}
function handleRawSync(bFromAuto, sendResponseParam) {
var PROP_SERVICEURL = 'serviceUrl';
function sendResponse(response) {
if (sendResponseParam)
sendResponseParam(response);
}
chrome.storage.local.get([PROP_TRELLOUSER], function (obj) {
var userTrello = (obj[PROP_TRELLOUSER] || null);
if (userTrello == null) {
sendResponse({ status: "error: no user yet. Enter a trello.com page first." });
return;
}
chrome.storage.sync.get([PROP_SERVICEURL], function (obj) {
var urlSync = obj[PROP_SERVICEURL] || null;
getConfigData(urlSync, userTrello, function (responseConfig) {
//responseConfig can be null (when no urlSync). review zig: remnant from v1. once we stop using internal backend, a lot of this code can be simplified
if (responseConfig && responseConfig.status != STATUS_OK) {
sendResponse(responseConfig);
return;
}
handleOpenDB(null, function (responseOpen) {
if (responseOpen.status != STATUS_OK) {
sendResponse(responseOpen);
return;
}
//g_optEnterSEByComment initialized while inside handleOpenDb
if (g_bDisableSync || (!g_optEnterSEByComment.IsEnabled() && (urlSync == null || urlSync.length == 0))) {
sendResponse({ status: "sync not configured or off" });
return;
}
handleSyncDB({ config: responseConfig, bUserInitiated: !bFromAuto }, function (responseSync) {
sendResponse(responseSync);
}, true);
});
});
});
});
}
var g_strBadgeText = "";
var PLUS_COLOR_SPENTBADGE = "#B10013";
function getFormattedSpentBadgeText() {
var l = g_strBadgeText.length;
if (l>0 && l<4)
return g_strBadgeText + UNITS.current;
return g_strBadgeText;
}
function setIconBadgeText(text, bAsTimer) {
text = "" + text; //in case its not string yet
if (!bAsTimer) {
g_strBadgeText = text;
}
if (g_strTimerLast.length > 0) {
chrome.browserAction.setBadgeBackgroundColor({ color: "#2A88BE" });
chrome.browserAction.setBadgeText({ text: g_strTimerLast });
}
else {
assert(!bAsTimer);
chrome.browserAction.setBadgeBackgroundColor({ color: PLUS_COLOR_SPENTBADGE });
var textSet = "";
if (g_optAlwaysShowSpentChromeIcon != OPT_SHOWSPENTINICON_NEVER)
textSet = getFormattedSpentBadgeText(text);
chrome.browserAction.setBadgeText({ text: textSet });
}
}
function calculateSyncDelay(callback) {
var keyPlusDateSyncLast = "plus_datesync_last";
chrome.storage.local.get(keyPlusDateSyncLast, function (obj) {
var msDateSyncLast = obj[keyPlusDateSyncLast];
var delay = 0;
if (msDateSyncLast !== undefined) {
var dateNow = new Date();
var deltaCur = (dateNow.getTime() - msDateSyncLast);
if (deltaCur < g_msSyncRateLimit)
delay = g_msSyncRateLimit - deltaCur;
}
setTimeout(function () {
callback();
}, delay);
});
}
//review: cache this list globally, patch it as cards get renamed (hard to tell when an entry goes away)
function handleGetAllHashtags(sendResponse) {
var request = { sql: "SELECT name FROM cards WHERE name LIKE '%#%' AND bDeleted=0 AND bArchived=0 AND idBoard <> ? AND idBoard in (SELECT idBoard from Boards where bArchived=0)", values: [IDBOARD_UNKNOWN] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK) {
sendResponse(responseReport);
return;
}
var mapHashtags = {};
responseReport.rows.forEach(function (row) {
var h = getHashtagsFromTitle(row.name);
h.forEach(function (hItem) {
mapHashtags[hItem] = true;
});
});
var result = [];
for (var hItem in mapHashtags) {
result.push(hItem);
}
result.sort(function doSort(a, b) {
return (a.toLowerCase().localeCompare(b.toLowerCase()));
});
var hLast = null;
var resultUnique = [];
for (var iResult = 0; iResult < result.length; iResult++) {
var hCur = result[iResult];
if (hLast && hCur.toLowerCase() == hLast.toLowerCase())
continue;
resultUnique.push(hCur);
hLast = hCur;
}
responseReport.list = resultUnique;
sendResponse(responseReport);
});
}
function handlePlusMenuSync(sendResponse) {
loadBackgroundOptions(function () {
handleRawSync(false, sendResponse);
});
}
function handleRequestProPermission(sendResponse) {
//review: handleCheckChromeStoreToken not used anymore here. we used to check for webstore permissions here
g_bProVersion = true; //this global is only for background. caller will update storage
//g_msStartPro unused in background contexts
sendResponse({ status: STATUS_OK });
}
function handleGoogleSyncPermission(sendResponse) {
chrome.permissions.request({
permissions: [],
origins: ['https://spreadsheets.google.com/', 'https://www.googleapis.com/']
}, function (granted) {
if (chrome.runtime.lastError) {
sendResponse({ status: chrome.runtime.lastError.message || "Error", granted:false });
return;
}
sendResponse({ status: STATUS_OK, granted: granted || false });
});
}
var g_idCardTimerLast = null;
function handleShowAllActiveTimers() {
findAllActiveTimers(function (rgIdCards) {
var cTotal = rgIdCards.length;
var cProcessed = 0;
var cMinimized = 0;
var cExisting = 0;
function onFinishedAll() {
var strNotification = null;
if (cExisting == cTotal) {
strNotification = "No more active timers to show.";
}
if (strNotification) {
handleShowDesktopNotification({
notification: strNotification,
timeout: 5000
});
}
}
if (rgIdCards.length == 0)
onFinishedAll(); //edge or impossible case
else {
rgIdCards.forEach(function (idCard) {
doShowTimerWindow(idCard, function (status, properties) {
cProcessed++;
if (status == STATUS_OK && properties && properties.bExisted) {
cExisting++;
if (properties.bMinimized)
cMinimized++;
}
if (cProcessed == cTotal)
onFinishedAll();
});
});
}
});
}
function processTimerCounter(bLoadingExtension) {
var bChangedIdCard = false;
function getTimerText(response) {
assert(typeof SYNCPROP_optAlwaysShowSpentChromeIcon !== "undefined");
var keyUnits = "units";
chrome.storage.sync.get([keyUnits, SYNCPROP_ACTIVETIMER, SYNCPROP_optAlwaysShowSpentChromeIcon], function (obj) {
var idCardTimer = null;
UNITS.current = obj[keyUnits] || UNITS.current; //reload
setOptAlwaysShowSpentChromeIcon(obj[SYNCPROP_optAlwaysShowSpentChromeIcon]);
if (obj[SYNCPROP_ACTIVETIMER] !== undefined)
idCardTimer = obj[SYNCPROP_ACTIVETIMER];
if (idCardTimer != g_idCardTimerLast) {
bChangedIdCard = true;
if (g_idCardTimerLast == null && bLoadingExtension) {
//done only when bLoadingExtension as other times will be taken care from content.
//otherwise, if the user closes the popup, it would come back again
//open the last active timer. do it a little later since chrome is just starting up
setTimeout(function () {
//show the active timer. wait for it otherwise timing issues can cause rare paths as db is being opened while the other timers are reached below.
doShowTimerWindow(idCardTimer, function (status) {
if (status != STATUS_OK)
return;
findAllActiveTimers(function (rgIdCards) {
rgIdCards.forEach(function (idCard) {
if (idCard != idCardTimer)
doShowTimerWindow(idCard);
});
});
});
}, 2000);
}
g_idCardTimerLast = idCardTimer;
}
if (idCardTimer) {
var hash = getCardTimerSyncHash(idCardTimer);
getCardTimerData(hash, function (objTimer) {
var stored = objTimer.stored;
if (stored === undefined || stored.msStart == null || stored.msEnd != null) {
response("");
return;
}
var msStart = stored.msStart;
var msEnd = Date.now();
var minutesDelta= (msEnd - msStart) / 1000 / 60;
var msRemain = (minutesDelta - Math.floor(minutesDelta)) * 60 * 1000;
var time=getTimerElemText(msStart, msEnd,true);
var text = "";
var unit = UNITS.current;
if (unit == UNITS.hours) {
if (time.hours > 9)
text = "" + Math.round(UNITS.TimeToUnits(msEnd - msStart) * 10) / 10;
else {
if (time.hours == 0)
text = "0:" + time.minutes; //cleaner
else
text = "" + time.hours + ":" + prependZero(time.minutes);
}
}
else if (unit == UNITS.minutes) {
if (time.minutes > 9999)
text = "+9999";
else
text = "" + time.minutes;
}
else {
assert(unit == UNITS.days);
text = "" + Math.round(UNITS.TimeToUnits(msEnd - msStart) * 10) / 10;
}
response(text, msRemain);
});
}
else {
response("");
}
});
}
getTimerText(function responseTimer(strTimer, msRemain) {
var bChanged = (g_strTimerLast != strTimer);
var bWasEmpty = (g_strTimerLast.length==0);
g_strTimerLast = strTimer;
if (g_idTimeoutTimer) {
clearTimeout(g_idTimeoutTimer);
g_idTimeoutTimer = null;
}
if (strTimer.length == 0) { //stopped timer
if (bChanged) {
setIconBadgeText(g_strBadgeText); //restore last badge
updatePlusIcon(false);
animateFlip();
}
}
else {
updatePlusIcon(false);
g_idTimeoutTimer = setTimeout(processTimerCounter, (1000 * 60 - msRemain + 500));
if ((bChanged && bWasEmpty) || bChangedIdCard)
animateFlip();
}
});
}
function doInstallNetworkDetection() {
if (g_bInstalledNetworkDetection)
return;
g_bInstalledNetworkDetection = true;
var rgIgnore = ["/checklist/", "/markAsViewed", "/1/members"];
chrome.webRequest.onCompleted.addListener(
function (details) {
if (details.statusCode == 200 && g_bDetectTrelloNetworkActivity && details.method != "GET") {
// && details.url.indexOf("/1/members") < 0
var bHandleIt=rgIgnore.every(function (str) {
if (details.url.indexOf(str) >= 0)
return false; //stop
return true;
});
if (bHandleIt)
handleDetectedTrelloActivity();
}
},
{ urls: ["https://trello.com/1/*"] },
[]);
chrome.webRequest.onErrorOccurred.addListener(function (details) {
if (details && details.type == "main_frame" && details.parentFrameId == -1 && details.method == "GET" && !details.fromCache &&
(!navigator.onLine || details.error.indexOf("_DISCONNECT") >= 0)) {
var url = details.url;
chrome.tabs.get(details.tabId, function (tab) {
if (tab && tab.highlighted) { //highlighted reduces chances we show the message for a tab that chrome is retrying in the background
doShowBoardCardOfflineNotification(url);
}
});
}
}, { urls: ["https://trello.com/b/*", "https://trello.com/c/*"] });
}
function doShowBoardCardOfflineNotification(url) {
var idBoard = null;
var idCard = null;
if (url.toLowerCase().indexOf("/b/") >= 0)
idBoard = url.split("/")[4];
else if (url.toLowerCase().indexOf("/c/") >= 0)
idCard = url.split("/")[4];
if (idBoard || idCard) {
handleOpenDB(null, function (responseOpen) {
if (responseOpen.status != STATUS_OK) {
return;
}
var request = null;
if (idBoard) {
request = { sql: "SELECT idBoard,name FROM boards WHERE idBoard=?", values: [idBoard] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status == STATUS_OK && responseReport.rows.length > 0) {
handleShowDesktopNotification({ timeout: 10000, idUse: g_prefixOfflineBoardNotification + idBoard, notification: "Chrome is offline. Click to open a card report for this board: " + responseReport.rows[0].name });
}
});
}
else if (idCard) {
request = { sql: "SELECT idBoard,name FROM cards WHERE idCard=?", values: [idCard] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status == STATUS_OK && responseReport.rows.length > 0) {
idBoard = responseReport.rows[0].idBoard;
handleShowDesktopNotification({ timeout: 10000, idUse: g_prefixOfflineCardNotification + idBoard + ":" + idCard, notification: "Chrome is offline. Click to open a card report for this card and board: " + responseReport.rows[0].name });
}
});
}
});
}
}
function handleDetectedTrelloActivity() {
//the idea is to do the bare minimum here as it can happen often and we also dont want to risk errors happening on this system callback.
//later, a setTimeout detects this change and acts
g_cTrelloActivitiesDetected++;
}
function handleQueryTrelloDetectionCount(sendResponse) {
var cRet = g_cTrelloActivitiesDetected;
g_cTrelloActivitiesDetected = 0;
sendResponse({ status: STATUS_OK, count: cRet });
}
var g_bPlusExtensionLoadedOK = false;
var g_bRetryWhenNotLoadedOK = true;
function setUninstallURLCustom() {
//review zig: modify to include &pro=true when g_bProVersion. First requires to keep g_bProVersion up to date (its not in many cases)
if (chrome.runtime.setUninstallURL) //none in some ubuntu
chrome.runtime.setUninstallURL("http://www.plusfortrello.com/p/goodbye.html?from=uninstall", function () { });
}
var g_loaderDetector = {
initLoader: function () {
var thisLocal = this;
g_bFromBackground = true; //from shared
setUninstallURLCustom();
//prevent too old Chrome versions.
//Must support at least Promises (Chrome 33) http://caniuse.com/#feat=promises
//<dialog>: polyfilled so we dont check. http://caniuse.com/#feat=dialog (native since Chrome 37)
//your ticket to the Promised land
if (!window.Promise) {
g_bRetryWhenNotLoadedOK = false;
setTimeout(function () {
handleShowDesktopNotification({
notification: "Sorry, your Chrome browser is outdated. Plus for Trello requires Chrome 33 or later.\nUpdate Chrome or remove Plus from the Chrome Menu + More Tools + Extensions.",
timeout: 30000
});
}, 1000);
//g_bPlusExtensionLoadedOK remains false
return this;
}
setTimeout(function () { //avoid global dependencies. however, this timeout could cause content script to call before we are ready. in messaging we handle it.
g_analytics.init();
loadBackgroundOptions(function () {
thisLocal.init();
g_bPlusExtensionLoadedOK = true;
});
}, 1); //to force-test timing-related issues, change this 1 to a larger number so that other places will retry. those places also need larger setTimeouts to test.
return this;
},
init: function () {
g_bOffline = !navigator.onLine;
updatePlusIcon();
//unpause sync
setInterval(function () {
if (g_msRequestedSyncPause==0)
return;
var msNow = Date.now();
if (msNow - g_msRequestedSyncPause > 6000) {
handleUnpause();
}
}, 2000);
//update icon tooltip and active timer
setInterval(function () {
updatePlusIcon(true); //just the tooltip
if (g_cErrorSync == 1) {
g_cErrorSync = 2; //not 1
//attempt to recover from the first error wihin the sync period.
setTimeout(function () {
checkNeedsSync(true);
}, 5000);
}
}, 1000 * 5);
var intervalNetDetect = null;
function doNetDetect() {
if (g_bInstalledNetworkDetection) {
if (intervalNetDetect)
clearInterval(intervalNetDetect);
intervalNetDetect = null;
return;
}
var keyTrelloSync = 'bEnableTrelloSync';
chrome.storage.sync.get(keyTrelloSync, function (obj) {
g_bDetectTrelloNetworkActivity = obj[keyTrelloSync] || false;
if (g_bDetectTrelloNetworkActivity && !g_bInstalledNetworkDetection) {
doInstallNetworkDetection();
}
});
}
setTimeout(function () {
doNetDetect();
//install network detection
intervalNetDetect = setInterval(doNetDetect, 4000);
}, 2500);
hookNotificationActions();
processTimerCounter(true);
function updateOnlineState(bOnline) {
console.log("Plus online: " + bOnline);
g_bOffline = !bOnline;
updatePlusIcon(false);
if (bOnline)
setTimeout(function () { checkNeedsSync(true); }, 2000);
}
window.addEventListener("online", function () { updateOnlineState(true); }, false);
window.addEventListener("offline", function () { updateOnlineState(false); }, false);
//do sync
function checkNeedsSync(bForce) {
var keySyncOutsideTrello = "bSyncOutsideTrello";
var keyPlusDateSyncLast = "plus_datesync_last";
if (g_bOffline)
return;
chrome.storage.sync.get([keySyncOutsideTrello], function (obj) {
var bSyncOutsideTrello = obj[keySyncOutsideTrello];
if (g_bDisableSync)
return;
//if we already did at least one sync during this chrome session, and the last error was "offline", do try to sync again (bypassing bSyncOutsideTrello)
var bLastErrorWasOffline = (g_lastStatusSyncCache &&
((g_lastStatusSyncCache.statusRead && g_lastStatusSyncCache.statusRead.indexOf(Language.NOINTERNETCONNECTION)>=0) ||
(g_lastStatusSyncCache.statusWrite && g_lastStatusSyncCache.statusWrite.indexOf(Language.NOINTERNETCONNECTION) >= 0)));
if (!bSyncOutsideTrello && !bLastErrorWasOffline)
return;
if (g_optEnterSEByComment.IsEnabled() && (localStorage.getItem("plus_first_trello_sync_completed") || "") != "true")
return; //dont make the first sync from background-sync
chrome.storage.local.get(keyPlusDateSyncLast, function (obj) {
var msDateSyncLast = obj[keyPlusDateSyncLast];
var dateNow = new Date();
if (!bForce && msDateSyncLast !== undefined && dateNow.getTime() - msDateSyncLast < g_msSyncRateLimit)
return;
handleRawSync(true);
});
});
}
//check right away
setTimeout(function () {
checkNeedsSync(true);
}, MSDELAY_FIRSTSYNC);
//every 10 minutes
setInterval(function () {
checkAnalyticsActive();
checkNeedsSync(false);
g_cErrorSync = 0; //reset counter
}, 1000 * 60 * 10);
}
}.initLoader();
function checkAnalyticsActive() {
if (!g_db) //active only if at least opened the db
return;
var dateNow = new Date();
var msShift = (dateNow.getTimezoneOffset() - 60 * 5) * 60000; //GMT-5 aprox standarization
var msNow = dateNow.getTime() + msShift;
var msLast = parseInt(localStorage.getItem("plus_ms_last_usage" || "0"), 10);
dateNow = new Date(msNow); //overwrite
var dateLast = new Date(msLast);
var strNow = makeDateCustomString(dateNow);
var strLast = makeDateCustomString(dateLast);
if (strNow != strLast) {
handleHitAnalyticsEvent("ActiveDay", "active", true, true);
localStorage.setItem("plus_ms_last_usage", "" + msNow);
}
}
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined") {
stroke = true;
}
if (typeof radius == "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (fill) {
ctx.fill();
}
if (stroke) {
ctx.stroke();
}
}
var g_dataSyncLast = { stage: "", ms: 0 }; //to avoid spamming tooltip update
var g_animationFrames = 18;
var g_msAnimationSpeed = 17;
var g_rotation = 0;
var g_bHilitePlusIcon = false;
function ease(x) {
return (1 - Math.sin(Math.PI / 2 + x * Math.PI)) / 2;
}
function animateFlip() {
if (true) { //review zig: temporarily stopped until rotation is fixed
g_bHilitePlusIcon = true;
updatePlusIcon(false);
setTimeout(function () {
g_bHilitePlusIcon = false;
updatePlusIcon(false);
}, 600);
return;
}
if (g_rotation != 0)
return;
function worker() {
var bQueue = false;
if (g_rotation <= 1) {
g_rotation += (1 / g_animationFrames);
bQueue = true;
} else {
g_rotation = 0;
}
updatePlusIcon(false);
if (bQueue) {
setTimeout(function () {
worker();
}, g_msAnimationSpeed);
}
}
worker();
}
function updatePlusIcon(bTooltipOnly) {
setTimeout(function () {
updatePlusIconWorker(bTooltipOnly); //review zig: ugly workarround because code sets storage props and immediately calls updatePlusIcon
}, 100);
}
function updatePlusIconWorker(bTooltipOnly) {
bTooltipOnly = bTooltipOnly || false;
if (g_bLastPlusMenuIconError)
bTooltipOnly = false; //force it
var keyLastSync = "rowidLastHistorySynced";
var keyLastSyncViewed = "rowidLastHistorySyncedViewed";
var key_plus_datesync_last = "plus_datesync_last";
var keyplusSyncLastStatus = "plusSyncLastStatus";
var msNow = Date.now();
//prevent changing tooltip too often
//note: checks typeof as this could be called from within a global constructor.
if (bTooltipOnly && typeof g_syncStatus != "undefined" && typeof g_dataSyncLast != "undefined" && g_syncStatus.bSyncing) {
if (g_dataSyncLast.stage != g_syncStatus.stage) {
g_dataSyncLast.stage = g_syncStatus.stage;
}
else {
if (msNow - g_dataSyncLast.ms < 200)
return;
}
g_dataSyncLast.ms = msNow;
}
chrome.storage.local.get([keyLastSync, keyLastSyncViewed, key_plus_datesync_last, keyplusSyncLastStatus], function (obj) {
var rowidLastSync = obj[keyLastSync];
var rowidLastSyncViewed = obj[keyLastSyncViewed];
var msplus_datesync_last = obj[key_plus_datesync_last];
var statusLastSync = obj[keyplusSyncLastStatus]; //can be undefined the first time or after reset sync
var bNew = false;
if (rowidLastSync != null && (rowidLastSyncViewed == null || rowidLastSyncViewed < rowidLastSync))
bNew = true;
var strBase = "images/icon19";
if (bNew) {
strBase += "new";
}
if (g_bHilitePlusIcon)
strBase = "images/icon19hilite";
//returns false if there is no sync error
function setTooltipSyncStatus() {
var tooltipPre = "Plus for Trello\n";
var tooltip = "";
if (bNew)
tooltipPre = tooltipPre + "New S/E rows\n";
if (g_dataTotalSpentThisWeek.str == null || g_strTimerLast.length>0)
setIconBadgeText("", g_strTimerLast.length > 0);
if (g_dataTotalSpentThisWeek.str)
tooltipPre = tooltipPre + g_dataTotalSpentThisWeek.weeknum + ": " + g_dataTotalSpentThisWeek.str + " Spent \n\n";
if (msplus_datesync_last !== undefined)
tooltipPre = tooltipPre + "Last sync " + getTimeDifferenceAsString(msplus_datesync_last, true) + "\n";
var syncStatus = "";
if (g_cWriteSyncLock == 0 && g_cReadSyncLock == 0 && !g_syncStatus.bSyncing) {
if (g_msRequestedSyncPause > 0) {
tooltipPre = tooltipPre + "Sync is paused until help is closed.\n";
}
if (statusLastSync)
syncStatus = buildSyncErrorTooltip(statusLastSync);
tooltipPre = tooltipPre + syncStatus;
}
if (g_cWriteSyncLock > 0)
tooltip = tooltip + "Writting S/E to spreadsheet...\n";
if (g_cReadSyncLock > 0)
tooltip = tooltip + "Reading S/E from spreadsheet...\n" + g_cRowsRead + " rows read.\n";
if (g_syncStatus.bSyncing) {
tooltip = tooltip + "Reading from Trello..."+ g_syncStatus.postfixStage+"\n";
tooltip = tooltip + g_syncStatus.stage + "\n";
if (!g_syncStatus.bSingleStep)
tooltip = tooltip + (g_syncStatus.cProcessed + " of " + g_syncStatus.cSteps + "\n");
}
if (g_bUpdateSyncNotificationProgress) {
if (g_cWriteSyncLock == 0 && g_cReadSyncLock == 0 && !g_syncStatus.bSyncing) {
g_bUpdateSyncNotificationProgress = false; //reset
chrome.notifications.clear(IDNOTIFICATION_FIRSTSYNCPRORESS, function (bWasCleared) { });
} else {
chrome.notifications.update(IDNOTIFICATION_FIRSTSYNCPRORESS,
{
message: Language.FIRSTSYNC_PRE + tooltip
}, function (notificationId) {});
}
}
if (g_bOffline)
tooltip = tooltip + "\nChrome is offline.";
chrome.browserAction.setTitle({ title: tooltipPre + tooltip });
var dateLastStatus = (statusLastSync && statusLastSync.date) || msNow;
return { statusStr: syncStatus, msDelta: msNow - dateLastStatus };
}
var statusTooltip = setTooltipSyncStatus();
var bErrorSync = (statusTooltip.statusStr.length > 0 && statusTooltip.msDelta < 1000 * 60 * 60); //pretend there wasnt a sync error if its old (over 60 min)
var ctx = null;
var canvas = null;
var dxCanvas = 0;
var dyCanvas = 0;
var rotation = g_rotation;
if (bErrorSync && statusTooltip.statusStr && statusTooltip.statusStr.indexOf(Language.NOINTERNETCONNECTION) >= 0) {
bErrorSync = false;
}
if (bTooltipOnly && bErrorSync)
bTooltipOnly = false;
if (!bTooltipOnly) {
var img = document.getElementById("imgPlusMenu");
img.setAttribute("width", "19");
img.setAttribute("height", "19");
img.setAttribute("src", chrome.extension.getURL(strBase + ".png"));
canvas = document.getElementById("canvasPlusMenu");
canvas.setAttribute("width", "19");
canvas.setAttribute("height", "19");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (rotation != 0) {
dxCanvas = Math.ceil(canvas.width / 2);
dyCanvas = Math.ceil(canvas.height / 2);
ctx.translate(dxCanvas, dyCanvas);
}
//review zig if (rotation != 0) ctx.rotate(2 * Math.PI * ease(rotation));
if (img.complete) { //check if image was already loaded by the browser
img.onload = null; //anyone waiting should be cancelled as they have stale data
callbackPaint();
} else {
img.onload = callbackPaint;
}
}
function callbackPaint() {
ctx.drawImage(img, -dxCanvas, -dyCanvas);
if (rotation != 0) {
ctx.translate(-dxCanvas, -dyCanvas);
ctx.rotate(-2 * Math.PI * ease(rotation));
}
var colorTrelloSync = "#FFFFFF";
var colorErrorSync = "#FF5050";
var colorOffline = "#BBBBBB";
var colorBackground = "#FFFFFF";
var colorCircleStroke = '#000000';
if (bErrorSync)
colorBackground = colorErrorSync;
else if (g_bOffline)
colorBackground = colorOffline;
g_bLastPlusMenuIconError = false; //reset
var nameFontSmall = "bold 8px Tahoma, Arial, sans-serif"; //tahoma is very readable at small sizes
//draw spent counter on top of chrome badge
if (g_optAlwaysShowSpentChromeIcon == OPT_SHOWSPENTINICON_ALWAYS && g_strTimerLast.length > 0 && g_strBadgeText.length > 0) {
//review zig: doesnt show offline/error visual status
ctx.fillStyle = PLUS_COLOR_SPENTBADGE;
ctx.strokeStyle = PLUS_COLOR_SPENTBADGE;
ctx.font = nameFontSmall;
var textBadgeSpent = getFormattedSpentBadgeText();
var width = ctx.measureText(textBadgeSpent).width;
var xStart = Math.max(16 - width, 1);
ctx.fillRect(xStart, 4, 19, 9);
ctx.fillStyle = "#FFFFFF";
ctx.fillText(textBadgeSpent, xStart + 2, 12);