forked from men232/plus-for-trello
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplus.js
3336 lines (2946 loc) · 128 KB
/
plus.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_msSyncPeriod = 3 * (60 * 1000); //3 minutes
var g_tipUserTopReport = "Sync";
var g_marginLabelChart = 35;
var g_heightBarUser = 30;
var g_bShowBoardMarkers = false;
var g_portBackground = null; //plus engine notifications to this tab
var g_bCheckedbSumFiltered = null; //null means not yet initialized (From sync storage)
var DELAY_FIRST_SYNC = 2000;
var g_cRetryingSync = 0;
var g_cRowsWeekByUser = 0; //gets set after making the chart. Used by the tour
var g_bShowHomePlusSections = true;
var g_bSkipUpdateSsLinks = false; //used by dimensions dropdown to hack arround legacy way to start sync
var g_bInsertedStripeScript = false;
var g_fnCallbackStripeMessage=null;
const PROP_LS_MSLASTNOSYNCWARN = "plus_ms_last_sync_warn"; //warning: can be in the future. date since last time we showed the configure warning.
const PROP_LS_MSLAST_IGNORE_EXTUPGRADE = "plus_msLastIgnoreExtUpg";
const PROP_LS_ASKEDNOTUSINGSE = "plus_asked_not_usingse";
//board dimensions combo
//sync see SYNCPROP_BOARD_DIMENSION
var VAL_COMBOVIEWKW_PREFIX = "~#^*()-"; //use weird value as cheap way to avoid collision with keywords
var VAL_COMBOVIEWKW_ALL = VAL_COMBOVIEWKW_PREFIX + "all";
var VAL_COMBOVIEWKW_KWONLY = VAL_COMBOVIEWKW_PREFIX + "kwonly";
var VAL_COMBOVIEWKW_CARDTITLES = VAL_COMBOVIEWKW_PREFIX + "cardtitles";
var VAL_COMBOVIEWKW_HELP = VAL_COMBOVIEWKW_PREFIX + "help";
var VAL_COMBOVIEWKW_REPORTKW = VAL_COMBOVIEWKW_PREFIX + "reportkw";
var VAL_COMBOVIEWKW_HEADER = VAL_COMBOVIEWKW_PREFIX + "header";
var VAL_COMBOVIEWKW_SEP = VAL_COMBOVIEWKW_PREFIX + "sep";
var g_globalUser = ""; //saved in sync storage
var g_rgKeywordsHome = [];
//for sync performance, we keep the preference as a single string
//it can be one of the special values above, or a keyword string
var g_dimension = VAL_COMBOVIEWKW_ALL;
//review zig: this was the easy way to prevent charts from rendering until their container is attached to the dom.
// in the home page case, we dont attach the plus 2x2 table until all its cells have loaded, so that its full height
// is known, thus preventing page jumps as its height grows until all 4 cells are loaded.
// if we dont do this, the charts draw smaller, probably are not picking up some font-size/type that makes them paint smaller.
// task: investigate if changing css attributes to match body, like font type/size will make the chart draw right.
//end-review
var g_bPreventChartDraw = true;
var g_delayedActions = {
bPendingWeeklyReport: false
};
function isSpecialPayTestUser() {
getCurrentTrelloUser();
if (!g_userTrelloCurrent)
return false;
if (g_userTrelloCurrent == "zmandel")
return true;
var prop="plus_rand_user_pay_stage1";
var randUser = localStorage.getItem(prop);
if (!randUser) {
randUser = Math.round(Math.random()*1000);
localStorage.setItem(prop, ""+randUser);
} else
randUser = parseInt(randUser, 10);
return true;
}
var g_waiterLi = CreateWaiter(2, function () {
if (document.URL.indexOf("/trello.com/" + URLPART_PLUSLICENSE + "/") >= 0)
return;
assert(g_userTrelloCurrent); //waiters ensure user and db are loaded at this point
checkFirstTimeUse(function (bShowedDialog) {
if (bShowedDialog)
return;
checkDownWarning();
checkNeedsExtensionUpdate(function (bShowedDialog) { //review: should also check regularly for users that never close the trello tab
if (bShowedDialog)
return;
sendExtensionMessage({ method: "completedFirstSync" }, function (response) {
if (response && response.status == STATUS_OK && response.bCompletedFirstSync) {
//setTimeout(checkLi, 2000);
}
});
});
});
});
function checkNeedsExtensionUpdate(callback) {
sendExtensionMessage({ method: "getDateUpdateNotificationReceived" }, function (response) {
if (response && response.status == STATUS_OK) {
var msNow = Date.now();
var bShowUpdateNeeded = false;
var bUrgent = false;
if (response.msDate > 0 && msNow - response.msDate > 1000 *60 *60 * 8) { //8 hours of pending update. so we dont bother users right away (give a chance for chrome to autoupdate)
bShowUpdateNeeded = true;
if (msNow - response.msDate > 1000 * 60 * 60 * 24 * 3) // 3 days old
bUrgent = true;
}
if (newerStoreVersion(true)) {
bShowUpdateNeeded = true;
bUrgent = true;
}
callback(bShowUpdateNeeded); //return it, even if later here we dont end up showing a dialog
if (!bShowUpdateNeeded)
return;
var msDateLastWarn = parseInt(localStorage.getItem(PROP_LS_MSLAST_IGNORE_EXTUPGRADE) || "0", 10) || 0;
if (msDateLastWarn > 0) {
var msDelta = Date.now() - msDateLastWarn;
var msLimit = (bUrgent ? 1000 * 60 * 40 : 1000 * 60 * 60 * 8); //40 minutes or 8 hours
if (msDelta < msLimit)
bShowUpdateNeeded = false;
}
if (bShowUpdateNeeded)
showExtensionUpgradedError(null, true);
}
});
}
function resizeHelp(container) {
if (!container)
container = $('#agile_help_container');
if (container.length == 0)
return;
container.height($(window).innerHeight() - 20); //-20 prevents trello from adding a vertical scrollbar
}
function resizeMain() {
resizeHelp();
checkTrelloLogo();
}
window.addEventListener('resize', resizeMain);
var g_optIsPlusDisplayDisabled = null; //null means uninitialized. dont use directly. private to below
function isPlusDisplayDisabled() {
if (g_optIsPlusDisplayDisabled === null)
g_optIsPlusDisplayDisabled = localStorage.getItem(g_lsKeyDisablePlus); //we want to read it once so its consistent for future calls. user must refresh page if changed
if (g_optIsPlusDisplayDisabled == "true")
return true;
return false;
}
/* isBackendMode
*
* REVIEW zig: warning: must be called only if g_bReadGlobalConfig, else caller should wait until later
* all callers were verified on mar-11-2014
**/
function isBackendMode(configData) {
if (configData === undefined) {
if (!g_bReadGlobalConfig)
return false;
configData = g_configData;
}
return (configData && configData.spentSpecialUser != null);
}
var g_bReadGlobalConfig = false;
function showAproveGoogleSyncPermissions(callback) {
//the main purpose of showing the dialog is to generate a user action (OK click)
//to ask for new permissions (allowed only during a user action)
//also, it lets us warn the user about what is about to be asked and why.
var divDialog = $(".agile_dialog_showAproveGSP");
if (divDialog.length == 0) {
divDialog = $('\
<dialog class="agile_dialog_showAproveGSP agile_dialog_DefaultStyle"> \
<h2>Plus for Trello - Google Sync permissions</h2><br> \
<p>Your configuration was synced to this device. Plus may ask</p>\
<p>you to approve Google permissions after pressing OK.</p>\
<br>\
<button style="float:right;" id="agile_dialog_GSP_OK">OK</button> \
</dialog>');
getDialogParent().append(divDialog);
divDialog = $(".agile_dialog_showAproveGSP");
}
divDialog.find("#agile_dialog_GSP_OK").off("click.plusForTrello").on("click.plusForTrello", function (e) {
divDialog[0].close();
callback();
});
showModalDialog(divDialog[0]);
}
function handleProAproval(callback) {
sendExtensionMessage({ method: "requestProPermission" }, function (response) {
callback(response.status);
});
}
//REVIEW: remove dialog
function showApproveProTrialDialog(callback) {
var divDialog = $(".agile_dialog_showAprovePro");
if (divDialog.length == 0) {
//note: tabindex="1" will set focus to the title. this is to prevent focus to other elements that may cause a scroll down of the dialog on small screens.
divDialog = $('\
<dialog class="agile_dialog_showAprovePro agile_dialog_DefaultStyle"> \
<h2 tabindex="1" id="agile_dialog_showAprovePro_Top" style="outline: none;" align="center">Plus for Trello - "Pro" version</h2>\
<p align="justify">\
<p align="justify">\
By Pressing "Approve" you agree to later purchase the "Pro" license for $9.⁹⁹ a year (*).<br>\
You also accept our <A target="_blank" href="http://www.plusfortrello.com/p/eula-plus-for-trello-end-user-license.html">End-user license agreement</A>.<br>\
<\p>\
<br>\
* We won\'t ask for payment information right now. Plus will remind you later.<br>Amount may vary slightly per country.<br>\
<br>\
<button id="agile_dialog_showAprovePro_OK">Approve</button> \
<button id="agile_dialog_showAprovePro_Cancel">Cancel</button>\
\
<a style="float:right;margin-top:2em;" target="_blank" href="http://www.plusfortrello.com/p/plus-for-trello-pro-version.html">Read more</a>.\
</dialog>');
getDialogParent().append(divDialog);
divDialog = $(".agile_dialog_showAprovePro");
} else {
$("#agile-scrolldown-alert-pro").hide(); //possible leftover
}
function doFinish(bOK) {
divDialog[0].close();
callback(bOK);
}
divDialog.find("#agile_dialog_showAprovePro_Cancel").off("click.plusForTrello").on("click.plusForTrello", function (e) {
doFinish(false);
});
divDialog.find("#agile_dialog_showAprovePro_OK").off("click.plusForTrello").on("click.plusForTrello", function (e) {
doFinish(true);
});
showModalDialog(divDialog[0]);
setTimeout(function () {
if (!elementInViewport($("#agile_dialog_showAprovePro_OK")[0]))
$("#agile-scrolldown-alert-pro").slideDown();
}, 200);
}
function configureSsLinks(bParam) {
if (g_strServiceUrl != null) {
configureSsLinksWorker(bParam, g_strServiceUrl);
}
else {
chrome.storage.sync.get('serviceUrl', function (obj) {
var strUrlNew = obj['serviceUrl']; //note: its still called serviceUrl even though now stores a sheet url (used to store a backend url in 2011)
if (strUrlNew === undefined || strUrlNew == null)
strUrlNew = ""; //means simple trello
strUrlNew = strUrlNew.trim();
var keyUrlLast = "serviceUrlLast";
chrome.storage.local.get(keyUrlLast, function (obj) { //must be local as we are comparing local configuration. each devices does the same
var strUrlOld = obj[keyUrlLast];
if (strUrlOld)
strUrlOld = strUrlOld.trim();
else
strUrlOld = "";
function continueConfig() {
g_strServiceUrl = strUrlNew;
configureSsLinksWorker(bParam, strUrlNew);
}
function saveLocalUrl(callback) {
var pairUrlOld = {};
pairUrlOld[keyUrlLast] = strUrlNew;
chrome.storage.local.set(pairUrlOld, function () {
if (chrome.runtime.lastError != undefined) {
alert("Plus for Trello:"+chrome.runtime.lastError.message);
return;
}
callback();
});
}
if (strUrlOld != strUrlNew && !g_bDisableSync && !g_optEnterSEByComment.IsEnabled()) {
//config changed from another device.
if (strUrlOld && strUrlOld != "") {
function saveLocalAndRestart() {
saveLocalUrl(function () {
restartPlus("Refreshing with updated sync setting.");
});
}
var promiseClearStorage = DeleteOrMergeNewSyncSource("Google sync spreadsheet changed. ");
promiseClearStorage.then(function (bClearStorage) {
g_strServiceUrl = strUrlNew;
if (!bClearStorage) {
reloadConfigData(strUrlNew, function () {
saveLocalAndRestart();
});
} else {
clearAllStorage(function () {
saveLocalAndRestart();
});
}
});
}
else {
//possibly first time it has a sync url. must ask for extension permissions
//review zig multiple calls to continueConfig can be simplified with promises (need to add polyfill for older chromes)
showAproveGoogleSyncPermissions(function () {
sendExtensionMessage({ method: "requestGoogleSyncPermission" }, function (response) {
if (response.status != STATUS_OK) {
alert(response.status);
return;
}
if (!response.granted) {
//here so user doesnt get stuck in a loop if no longer wants to use google sync
if (confirm("Remove the Google sync url? Only press OK if you want to turn off Google sync.")) {
chrome.storage.sync.set({ "serviceUrl": "" }, function () {
if (chrome.runtime.lastError != undefined) {
alert(chrome.runtime.lastError.message);
return;
}
strUrlNew = "";
saveLocalUrl(function () {
continueConfig();
});
});
}
else {
alert("You may continue using Plus but sync features may not work correctly.");
continueConfig();
}
}
else {
saveLocalUrl(function () {
continueConfig();
});
}
});
});
}
}
else {
continueConfig();
}
});
});
}
}
var g_userTrelloCurrent = null;
function getCurrentUserByApi(callback, waitRetry) {
//https://trello.com/members/me/
var url = "https://trello.com/1/members/me?fields=username&token=";
url = url + $.cookie("token"); //trello requires the extra token besides the cookie to prevent accidental errors from extensions
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
handleFinishRequest();
function handleFinishRequest() {
var objRet = { status: "unknown error", hasPermission: false };
var bReturned = false;
if (xhr.status == 200) {
try {
objRet.hasPermission = true;
objRet.obj = JSON.parse(xhr.responseText);
objRet.status = STATUS_OK;
bReturned = true;
callback(objRet);
} catch (ex) {
objRet.status = "error: " + ex.message;
logException(ex);
}
} else {
if (bHandledDeletedOrNoAccess(xhr.status, objRet, "error: permission error or deleted")) { //no permission or deleted
null; //avoid lint
}
else if (xhr.status == 429) { //too many request, reached quota.
var waitNew = (waitRetry || MsWaitRetry()) * 2;
if (waitNew < g_msWaitMax) {
bReturned = true;
setTimeout(function () {
getCurrentUserByApi(callback, waitNew);
}, waitNew);
}
else {
objRet.status = errFromXhr(xhr);
}
}
else {
objRet.status = errFromXhr(xhr);
}
}
if (!bReturned)
callback(objRet);
}
}
};
xhr.open("GET", url);
xhr.send();
}
var g_bMakingUserApiCall = false;
/* getCurrentTrelloUser
*
* returns null if user not logged in, or not yet loaded
* else returns user (without @)
**/
function getCurrentTrelloUser() {
var user=getCurrentTrelloUserWorker();
if (user)
return user;
if (g_bMakingUserApiCall)
return null;
var header = $('#header');
if (header.length == 0)
return null;
g_bMakingUserApiCall = true;
getCurrentUserByApi(function (response) {
g_bMakingUserApiCall = false;
if (response.status == STATUS_OK && response.obj && response.obj.username) {
g_userTrelloCurrent=response.obj.username;
}
});
}
function getCurrentTrelloUserWorker() {
if (g_userTrelloCurrent != null)
return g_userTrelloCurrent;
var header = $('#header');
if (header.length==0)
return null;
var elemUserMenu = header.find('[data-testid="header-member-menu-button"]');
var userElem = null;
if (elemUserMenu.length == 0) {
return null;
}
elemUserMenu = elemUserMenu.children("div");
if (elemUserMenu.length==0)
return null;
userElem = elemUserMenu.first().attr("title");
//search for the last () pair because the user long name could also have parenthesis
//this happens a lot in users with non-western names, where trello adds the western name in parenthesis,
//as in "%$#& &%948# (peter chang) (peterchang)"
var iParenOpen = userElem.lastIndexOf("(");
if (iParenOpen < 0)
return null;
userElem = userElem.substring(iParenOpen+1);
var iParenClose = userElem.lastIndexOf(")");
if (iParenClose < 0 || iParenClose != userElem.length-1)
return null;
userElem = userElem.substring(0,iParenClose);
if (userElem.length == 0)
return null; //not needed, but might help when trello suddenly changes DOM
g_userTrelloCurrent = userElem;
g_waiterLi.Decrease("user");
//save the user
chrome.storage.local.get([PROP_TRELLOUSER], function (obj) {
var userTrelloLast = (obj[PROP_TRELLOUSER] || null);
if (userTrelloLast != userElem) {
if (userTrelloLast)
sendDesktopNotification("Warning: Trello user changed. Reset Sync from Plus help" , 30000);
var pairUser = {};
pairUser[PROP_TRELLOUSER] = userElem;
chrome.storage.local.set(pairUser, function () {
if (chrome.runtime.lastError != undefined)
alert("Plus for Trello:" + chrome.runtime.lastError.message);
});
}
});
return userElem;
}
var g_configData = null; //set to non-null when sync is configured
//returns true iff progress set. false when progress was already set
function setWeekSummaryProgress(elem) {
var strClass = "agile_sync_state";
var elemTable = elem.children("table"); //review zig cleanup table find all over
if (elemTable.hasClass(strClass))
return false;
elemTable.addClass(strClass);
elem.attr("title", "Syncing...\nTo see progress hover Chrome's Plus icon ↗");
return true;
}
function removeWeekSummaryProgress(elem) {
var strClass = "agile_sync_state";
elem.children("table").removeClass(strClass);
}
var g_bCreatedPlusHeader = false; //review zig: get rid of this by always creating 'new' icon hidden when #urlUser is created.
function configureSsLinksWorker(b, url, bSkipConfigCache) {
var userElem = getCurrentTrelloUser();
if (userElem == null) {
//try later. most likely user not logged-in
setTimeout(function () { configureSsLinksWorker(b, url, bSkipConfigCache); }, 500);
return;
}
var urlUserElem = $('#urlUser');
if (urlUserElem.length == 0) {
g_bCreatedPlusHeader = true;
urlUserElem = $('<span id="urlUser"></span>').css("margin-left", "0px").css("margin-right", "2px");
urlUserElem.addClass('agile_urlUser');
urlUserElem.appendTo(b);
if (!isPlusDisplayDisabled()) {
if (g_bNoSE)
urlUserElem.hide();
getRecentWeeksList().appendTo(b);
}
}
if (!isPlusDisplayDisabled())
checkCreateRecentFilter(b);
urlUserElem.attr("title", g_tipUserTopReport); //reset
if (url == "") {
g_configData = null;
g_bReadGlobalConfig = true;
onReadGlobalConfig(g_configData, userElem);
return;
}
function part2() {
sendExtensionMessage({ method: "getConfigData", userTrello: userElem, urlService: url, bSkipCache: bSkipConfigCache },
function (respConfig) {
//note: here we used to check for trello user changed. worked for google sync but not for trello sync. that has now moved
//to a warning at the time we detect that we change PROP_TRELLOUSER (independent of configData now)
//respConfig.config is null in the non-spreadsheet-sync case
if (respConfig.config && respConfig.config.status != STATUS_OK) {
setTimeout(function () {
//set error text later, to avoid cases when user navigates back/away while on this xhr call.
setSyncErrorStatus(urlUserElem, respConfig.config.status);
}, 500);
return;
}
g_configData = respConfig.config; //cached. can be null
g_bReadGlobalConfig = true;
onReadGlobalConfig(g_configData, userElem);
});
}
//review zig remove g_bCheckedTrelloSyncEnable and just force-enable sync
if (!g_bCheckedTrelloSyncEnable && !g_bEnableTrelloSync) {
g_bCheckedTrelloSyncEnable = true;
chrome.storage.sync.set({ "bCheckedTrelloSyncEnable": g_bCheckedTrelloSyncEnable }, function () { });
if (!g_bDisableSync) {
//used to be that spreadsheet sync could be used without trellosync. no more.
var pairTrelloSync = {};
pairTrelloSync["bEnableTrelloSync"] = true;
chrome.storage.sync.set(pairTrelloSync, function () {
if (chrome.runtime.lastError != undefined)
alert("Plus for Trello:" + chrome.runtime.lastError.message);
else
g_bEnableTrelloSync = true; //note: this is a safe place to init this global. be careful if init code changes.
part2();
});
return; //dont continue and call part2 again
}
}
part2();
}
var g_bDidInitialIntervalsSetup = false;
function initialIntervalsSetup() {
g_spentTotal = InfoBoxFactory.makeTotalInfoBox(SPENT,true).hide();
g_estimationTotal = InfoBoxFactory.makeTotalInfoBox(ESTIMATION, true).hide();
g_remainingTotal = InfoBoxFactory.makeTotalInfoBox(REMAINING, true).hide();
doAllUpdates(false);
chrome.storage.local.get([LOCALPROP_NEEDSHOWHELPPANE], function (obj) {
if (obj && obj[LOCALPROP_NEEDSHOWHELPPANE]) {
var pair = {};
pair[LOCALPROP_NEEDSHOWHELPPANE] = false;
chrome.storage.local.set(pair, function () {
Help.display();
});
}
});
setInterval(function () {
doAllUpdates(true);
}, UPDATE_STEP);
if (isPlusDisplayDisabled())
return;
setTimeout(function () {
update(false); //first update
}, 20);
detectMovedCards();
var oldLocation = location.href;
setInterval(function () {
if (location.href != oldLocation) {
oldLocation = location.href;
removeAllGrumbleBubbles();
if (g_tour.bAutoShowTour && getIdBoardFromUrl(oldLocation))
setTimeout(function () { handleTourStart(false); }, 2500);
//this might not be strictly needed. for safety clean this cache. it contains jquery elements inside and might confuse code.
//needed because trello plays with navigation and we can end up with the cache even though we are on another page (like a board page)
if (!bAtTrelloHome()) {
g_chartsCache = {};
cancelZoomin(null, true); //review zig: find a better way that is not timing-related, like a chrome url-changed notif, or change the href of recent/remaining to handlers
}
setTimeout(function () { doAllUpdates(false); }, 100); //breathe
}
}, 400); //check often, its important to prevent a big layout jump (so you can click on boards right away on home without them jumping (used to be more important before new trello 2014-01)
var msLastDetectedActivity = 0; //zero means nothing detected yet.
setInterval(function () {
if (!g_bEnableTrelloSync)
return;
//detect trello network activity and initiate sync
//in case of multiple trello windows open, note that the extension message will only return the same count to only one of the windows and the rest will receive zero.
//its still possible that several consecutive changes cause more than one window to receive a non-zero modification count. its not a big deal as one will fail with busy.
//this method also protects us from performance issues with many trello tabs open. it should not use "isTabVisible" because if all tabs are hidden it would not do the sync.
sendExtensionMessage(
{ method: "queryTrelloDetectionCount" },
function (response) {
if (response.status != STATUS_OK)
return;
var msNow = Date.now();
if (response.count == 0) {
if (msLastDetectedActivity == 0)
return;
if (msNow - msLastDetectedActivity > 500) { //this prevents many consecutive change detections from triggering many syncs
msLastDetectedActivity = 0; //reset
doSyncDB(null, true, true, true,true);
}
}
else {
msLastDetectedActivity = msNow;
}
});
}, 1000);
setInterval(function () {
testExtensionAndcommitPendingPlusMessages();
}, 20000);
}
function onReadGlobalConfig(configData, user) {
g_bShowBoardMarkers = false;
if (isBackendMode(configData))
g_bShowBoardMarkers = true;
var pair = {};
pair[PROP_SHOWBOARDMARKERS] = g_bShowBoardMarkers;
chrome.storage.local.set(pair, function () { });
//REVIEW zig: need a new way to notify of new service url/spreadsheet archiving (like a row with special meaning)
startOpenDB(configData, user);
}
function setSyncErrorStatus(urlUser, status, statusLastTrelloSync) {
removeWeekSummaryProgress(urlUser);
statusLastTrelloSync = statusLastTrelloSync || STATUS_OK;
if (statusLastTrelloSync == "busy")
statusLastTrelloSync = STATUS_OK; //dont bother the user when busy
if (status == STATUS_OK && statusLastTrelloSync == STATUS_OK) {
var dateNow = new Date();
var strTip = g_tipUserTopReport;
urlUser.children("table").removeClass("agile_plus_header_error");
if (g_bDisableSync || (g_strServiceUrl == "" && !g_optEnterSEByComment.IsEnabled()))
strTip = "";
urlUser.attr("title", strTip);
return;
}
urlUser.children("table").addClass("agile_plus_header_error");
var statusSet = "";
if (status != STATUS_OK) {
if (status && status.indexOf("error:") >= 0)
statusSet = status;
else
statusSet = "error: " + (status?status: "unknown error");
}
if (statusLastTrelloSync != STATUS_OK) {
if (statusSet != "")
statusSet = statusSet + "\n";
statusSet = statusSet+ "sync error: " + statusLastTrelloSync;
}
urlUser.attr("title", statusSet);
console.log(statusSet);
}
var g_intervalSync = null;
var g_dbOpened = false;
var g_idTimeoutReportHover = null;
function startOpenDB(config, user) {
g_dbOpened = false;
openPlusDb(
function (response) {
if (response.status != STATUS_OK) {
showFatalError(response.status);
return;
}
g_cRowsHistoryLast = response.cRowsTotal; //review: only this caller uses cRowsTotal. that and 'dateMin' could be an option of handleOpenDB
g_dbOpened = true;
onDbOpened();
doWeeklyReport(config, user, true, false, false); //bRefreshCardReport=false because onDbOpened already does so REVIEW zig detect it in a cleaner way
setTimeout(function () {
doSyncDB(user, true, false, true);
}, DELAY_FIRST_SYNC); //wait a little so trello itself can load fully. Not needed but may speed up loading trello page.
if (g_intervalSync != null) {
clearInterval(g_intervalSync);
g_intervalSync = null;
}
var urlUser = $("#urlUser");
//Note: why use javascript handlers instead of css hover?
//we want to cover a common case that css hover cant do: if a user using the mouse aiming towards the Plus help icon,
//and she hovers over the weekly report on her way, as soon as she hover out of the report it will shrink and the plus icon will
//keep moving away. Thus, here we delay the mouseout by 2 seconds so it gives her time to reach the plus icon.
function handlerIn(event) {
zoomTopReport(urlUser);
}
function handlerOut(event) {
programUnZoom(urlUser);
}
urlUser.unbind("hover");
urlUser.hover(handlerIn, handlerOut);
if (!isPlusDisplayDisabled()) {
g_intervalSync = setInterval(function () { doSyncDB(user, true, false, false); }, g_msSyncPeriod);
//review zig: these all should be at urlUser creation time to avoid the unbinds and such
urlUser.unbind("click");
urlUser.click(function () {
doSyncDB(user, false, false, false);
});
}
}, { dowStart: DowMapper.getDowStart(), dowDelta: DowMapper.getDowDelta() });
}
function zoomTopReport(userElem) {
if (g_idTimeoutReportHover) {
//cancel ongoing. will be recreated on Out
clearTimeout(g_idTimeoutReportHover);
g_idTimeoutReportHover = null;
}
userElem.children("table").addClass("agile_plus_header_link_zoomhoverActive");
}
function programUnZoom(userElem) {
if (g_idTimeoutReportHover == null) { //note: !=null can actually happen in rare cases involving switching windows while on the hover timeout wait
g_idTimeoutReportHover = setTimeout(function () {
userElem.children("table").removeClass("agile_plus_header_link_zoomhoverActive");
g_idTimeoutReportHover = null;
}, 8000);
}
}
var g_cRowsHistoryLast = 0;
var g_bFirstTimeUse = false;
var g_bDisplayPointUnits = false;
var g_bAllowNegativeRemaining = false;
var g_bPreventIncreasedE = false;
var g_bDontWarnParallelTimers = false;
var g_bUserDonated = false; //review: remove
var g_bHidePendingCards = false;
var g_bAlwaysShowSEBar = false;
var g_bHideLessMore = false;
var g_bSyncOutsideTrello = false; //allow sync outside trello
var g_bChangeCardColor = false; //change card background color based on its first label
var g_bHideTour = false;
function checkFirstTimeUse(callback) { //callback(bShowedDialog)
var keyDateLastSetupCheck = "dateLastSetupCheck";
var bShowedDialog = false;
var msDateNow = Date.now();
var bShowHelp = false;
var totalDbRowsHistory = 0;
sendExtensionMessage({ method: "getTotalDBRows" }, function (response) {
if (response.status == STATUS_OK) {
totalDbRowsHistory = response.cRowsTotal;
if (g_msStartPlusUsage === null && response.dateMin) {
g_msStartPlusUsage = response.dateMin;
chrome.storage.sync.set({ 'msStartPlusUsage': response.dateMin }, function () {
if (chrome.runtime.lastError)
console.log(chrome.runtime.lastError.message);
});
}
}
chrome.storage.local.get([LOCALPROP_NEEDSHOWPRO, keyDateLastSetupCheck, LOCALPROP_DONTSHOWSYNCWARN], function (obj) {
var bSyncDontWarn = obj[LOCALPROP_DONTSHOWSYNCWARN] || false;
var bForceShowHelp = false;
var msDateLastSetupCheck = obj[keyDateLastSetupCheck];
g_bNeedShowPro = obj[LOCALPROP_NEEDSHOWPRO];
if (g_bNeedShowPro) {
bShowHelp = true;
bForceShowHelp = true;
}
var bSyncNotEnabled = (g_bDisableSync || (g_strServiceUrl == "" && !g_optEnterSEByComment.IsEnabled()));
if (bSyncNotEnabled && !g_bDisableSync) { //sync not set up ever
if (msDateLastSetupCheck !== undefined) {
if (totalDbRowsHistory > 0) {
if (msDateNow - msDateLastSetupCheck > 1000 * 60 * 60 * 24) //nag once a day
bShowHelp = true;
}
}
else {
bShowHelp = true;
g_bFirstTimeUse = true;
}
}
function showHelp(msDelay) {
setTimeout(function () {
hiliteOnce($(".agile-main-plus-help-icon"), 2000);
}, msDelay);
setTimeout(function () { Help.display(); }, msDelay+500);
}
if (bShowHelp) {
if (!bSyncDontWarn || bForceShowHelp) {
bShowedDialog = true;
var pair = {};
pair[keyDateLastSetupCheck] = msDateNow;
pair[LOCALPROP_NEEDSHOWPRO] = "";
chrome.storage.local.set(pair, function () {
showHelp(1500);
});
}
} else if (bSyncNotEnabled && !bSyncDontWarn) {
var boardCurrent = getCurrentBoard();
if (!boardCurrent || boardCurrent.toLowerCase().indexOf("plus for trello") < 0) { //skip the plus for trello help board
var msNow = Date.now();
var msLastHiliteNoSync = localStorage.getItem(PROP_LS_MSLASTNOSYNCWARN) || 0;
hiliteOnce($(".agile-main-plus-help-icon"), 500, "agile_box_input_hilite_red", 3);
if (msNow - msLastHiliteNoSync > 1000 * 60 * 5) { //can be negative
bShowedDialog = true;
localStorage.setItem(PROP_LS_MSLASTNOSYNCWARN, msNow);
setTimeout(function () {
showEnableSyncDialog(function (status) {
//STATUS_OK, dontask, cancel (later)
if (status == "dontask") {
var pair = {};
pair[LOCALPROP_DONTSHOWSYNCWARN] = true;
chrome.storage.local.set(pair, function () {
});
}
else if (status == STATUS_OK) {
showHelp(0);
} else if (status == "cancel") {
//later
localStorage.setItem(PROP_LS_MSLASTNOSYNCWARN, Date.now() + 1000 * 60 * 60 * 1);
}
});
}, 2000);
g_msLastHiliteNoSync = msNow;
}
}
}
callback(bShowedDialog);
});
});
}
function updateCRowsTotalState(cRowsTotal, config, user) {
var cRowsOld = g_cRowsHistoryLast;
g_cRowsHistoryLast = cRowsTotal;
var bNewRows = (cRowsOld != g_cRowsHistoryLast);
//review zig: the hack below causes the side-effect that users not using S/E will have cRowsTotal==0 and make the empty
//home charts refresh more than once.
if (bNewRows || cRowsTotal == 0) { //cRowsTotal==0 is a hack so the "first sync" status text gets updated after a first sync with no rows
g_bForceUpdate = true;
g_seCardCur = null; //mark as uninitialized. will be set on the refresh below
if (!isTabVisible())
g_delayedActions.bPendingWeeklyReport = true;
else
doWeeklyReport(config, user, false, true);
}
}
function onDbOpened() {
if (!g_bDidInitialIntervalsSetup) {
initialIntervalsSetup(); //also calls doAllUpdates
g_bDidInitialIntervalsSetup = true;
g_waiterLi.Decrease("dbOpened");
}
if (g_portBackground == null) {
g_portBackground = chrome.runtime.connect({ name: "registerForChanges" });
g_portBackground.onMessage.addListener(function (msg) {
var urlUser = $('#urlUser');
if (msg.status)
setSyncErrorStatus(urlUser, msg.status, msg.statusLastTrelloSync);
if (msg.status != STATUS_OK)
return;
if (msg.event == EVENTS.FIRST_SYNC_RUNNING) {
urlUser.html(buildDailyTable("<tr><td>Running</td></tr><tr><td>first sync</td></tr>"));
setWeekSummaryProgress(urlUser);
setTimeout(function () {
if (g_bNeedStartTourBubble)
showTourBubble();
}, 1000);
}
else if (msg.event == EVENTS.NEW_ROWS) {
//this avoids refreshing the UI if no rows were added since last time
sendExtensionMessage({ method: "getTotalDBRows" },
function (response) {
if (response.status != STATUS_OK)
return;
var user = getCurrentTrelloUser();
if (g_bReadGlobalConfig && user) {
updateCRowsTotalState(response.cRowsTotal, g_configData, user);
}
});
} else if (msg.event == EVENTS.DB_CHANGED) {
checkCardRecurringCheckbox();
//EVENTS.DB_CHANGED not handled for home/daily reports as we care about new rows only (otherwise it gets complicated to prevent double refreshing on new rows and other changes
//review zig" ideally refresh on this only if NEW_ROWS was not just received. then chart labels will rename when renamed in trello and so on (no new rows cases)
//important so we update card report then changing [R] status
if (!msg.bNewHistoryRows) { //NEW_ROWS is already handled above
var user = getCurrentTrelloUser();
if (user) {
g_bForceUpdate = true;
if (!isTabVisible())
g_delayedActions.bPendingWeeklyReport = true;
else
doWeeklyReport(g_configData, user, false, true);
}
}
} else if (msg.event == EVENTS.EXTENSION_RESTARTING) {
setTimeout(function () {
location.reload();
}, 1500);
}
});
}
}
//REVIEW zig: workarround for Trello auth "dsc" issue
function AuthAndsendExtensionMessage(obj, responseParam, bRethrow) {
setTrelloAuth(function () {
sendExtensionMessage(obj, responseParam, bRethrow);
});
}
function doSyncDB(userUnusedParam, bFromAuto, bOnlyTrelloSync, bRetry, bForce) {
if (Help.isVisible() || isPlusDisplayDisabled())
return;
bOnlyTrelloSync = bOnlyTrelloSync || false;
if (bRetry === undefined)
bRetry = true;
var config = g_configData;
var urlUser = null;
var dateNow = new Date();
var bSetStatus = false;
var cRetries = (bRetry? 3 : 1); //try this many times to start google sync
var bDidTrelloSync=false;
var bEnterSEByComments = g_optEnterSEByComment.IsEnabled();
var tokenTrello = $.cookie("token");