-
Notifications
You must be signed in to change notification settings - Fork 3
/
shared.js
2493 lines (2211 loc) · 89.1 KB
/
shared.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 IDTEAM_UNKNOWN = "//"; //reserved idTeam. note that idTeam can also be null for boards without team
var IDBOARD_UNKNOWN = "//"; //board shortLink/idLong reserved for unknown boards. saved into db. for cases where user does not have permission for a board (for example when moving a card there)
var IDLIST_UNKNOWN = "//"; //list idLong. deals with missing idList in convertToCardFromCheckItem board action. saved to db
//review: dummy labels were initially used as a hacky way to get certain queries with "NOT" (!) working on labels.
//however it was limited and a similar effect can be achieved using idCard NOT in (list)
var IDLABEL_DUMMY = "//"; //the one dummy label cards share.
var g_bDummyLabel = false; //not used. just kept to keep the code as it inserts itself in interesting spots
const ROWID_REPORT_CARD = -1; // "fake" rowid on reports that join card with history. use -1 as rowid so when doing a "new s/e rows" report and a group is used, this union wont appear.
var PREFIX_COMMAND_SE_RESETCOMMAND = "[^resetsync";
var g_msFetchTimeout = 15000; //ms to wait on urlFetches. update copy on plus.js
var g_cchTruncateDefault = 50;
var g_cchTruncateShort = 20;
var g_cchTruncateChartDlabel = 35;
var g_regexpHashtags = /#([\S-]+)/g;
var g_colorTrelloBlack = "#4D4D4D";
const IDNOTIFICATION_FIRSTSYNCPRORESS = "firstSyncProgress";
var OPT_SHOWSPENTINICON_NORMAL = 0;
var OPT_SHOWSPENTINICON_ALWAYS = 1;
var OPT_SHOWSPENTINICON_NEVER = 2;
var g_optAlwaysShowSpentChromeIcon = OPT_SHOWSPENTINICON_NORMAL; //review zig these 3 need initialization.
var g_bDontShowTimerPopups = false;
var g_bIncreaseLogging = false;
var g_lsKeyDisablePlus = "plus_agile_disable_page_changes"; //in page localStorage (of trello.com content script) so it survives plus reset sync
var g_language = "en";
var g_bNoSE = false; //true -> hide S/E features
var g_bNoEst = false; //true -> hide E features
var g_bProVersion = false;
var g_msStartPro = 0; //together with g_bProVersion
var g_bFromBackground = false;
var g_msStartPlusUsage = null; //ms of date when plus started being used.
var g_bReportsUseSystemNumberFormat = true; //review: should parametrize but wasnt easy. Callers must set this before calling report format functions.
const URLPART_PLUSLICENSE = "plus-license";
const LOCALPROP_NEEDSHOWPRO = "keyNeedShowProInfo";
const LOCALPROP_DONTSHOWSYNCWARN = "bDontShowAgainSyncWarn";
const LOCALPROP_NEEDSHOWHELPPANE = "keyNeedShowHelpPane";
const ID_PLUSBOARDCOMMAND = "/PLUSCOMMAND"; //review zig: remnant from undocumented boardmarkers feature. newer commands do not use this.
//thanks http://stackoverflow.com/a/12034334
var g_entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function numToPlusLocaleString(val) {
if (g_bReportsUseSystemNumberFormat && typeof(val)=="number")
val = val.toLocaleString();
return val;
}
//replace can be a string, or a map function
//for performace, returns same string when there is no match
function replaceString(string, regex, replace) {
if (typeof (string) != "string")
string = String(string);
regex.lastIndex = 0;
return string.replace(regex, replace);
}
//much faster than localeCompare for many strings to sort
function cmpString(a, b) {
return a > b ? 1 : a < b ? -1 : 0;
}
function commonBuildUrlFromParams(params, doc) {
var url = chrome.extension.getURL(doc);
var val = null;
var bPasQ = (doc.indexOf("?")>=0);
for (var i in params) {
val = params[i];
if (val == "")
continue;
if (!bPasQ) {
url += "?";
bPasQ = true;
}
else
url += "&";
url += (i + "=" + encodeURIComponent(val));
}
return url;
}
var g_regexEscapeHtml = /[&<>"'\/]/g;
function escapeHtml(string) {
if (!string)
return "";
return replaceString(string, g_regexEscapeHtml, function (s) {
return g_entityMap[s];
});
}
function getDialogParent(bForceBody) {
if (!bForceBody) {
var par = $('[data-testid="card-back-name"]');
if (par.length > 0)
return par;
}
return $("body");
}
function bHandledDeletedOrNoAccess(status, objRet, statusRetCustom) {
var bDeleted = bStatusXhrDeleted(status);
if (bStatusXhrNoAccess(status) || bDeleted) {
if (typeof (statusRetCustom) == "undefined")
statusRetCustom = STATUS_OK;
objRet.hasPermission = false;
objRet.status = statusRetCustom;
if (bDeleted)
objRet.bDeleted = true;
return true;
}
return false;
}
function bStatusXhrNoAccess(status) {
if (status == 400 || status == 401 || status == 403)
return true;
return false;
}
function bStatusXhrDeleted(status) {
return (status == 404);
}
var g_regexParserFormat = /<.*?>/;
function addTableSorterParsers() {
$.tablesorter.addParser({
// set a unique id
id: 'links',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
// format your data for normalization
return replaceString(s, g_regexParserFormat, "");
},
// set type, either numeric or text
type: 'text'
});
$.tablesorter.addParser({
// set a unique id
id: 'digitWithParen',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
// format your data for normalization
return s.split("(")[0].trim(); //remove possible (E 1st)
},
// set type, either numeric or text
type: 'numeric'
});
$.tablesorter.addParser({
id: 'dateDue',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
// format your data for normalization
if (s.length > 2) //hackish: empty dates show as a spasish char. this detects it.
return s;
return "3000-01-01 00:00";
},
// set type, either numeric or text
type: 'text'
});
}
function isTestVersion() {
//return false;
return (chrome.runtime.id != "gjjpophepkbhejnglcmkdnncmaanojkf");
}
function getHashtagsFromTitle(title, bFirstOnly) {
var hashtags = [];
g_regexpHashtags.lastIndex = 0; //needed because of /g in global regex
var result = g_regexpHashtags.exec(title);
while (result != null) {
hashtags.push(result[1]);
if (bFirstOnly)
break;
result = g_regexpHashtags.exec(title);
}
return hashtags;
}
function setOptAlwaysShowSpentChromeIcon(opt) {
//note old versions used to store boolean
if (typeof (opt) === "undefined")
opt=OPT_SHOWSPENTINICON_NORMAL;
else if (opt === true)
opt = OPT_SHOWSPENTINICON_ALWAYS;
else if (opt === false)
opt = OPT_SHOWSPENTINICON_NORMAL;
g_optAlwaysShowSpentChromeIcon = opt;
}
var STATUS_OK = "OK"; //for messaging status with background page. all responses should have response.status=STATUS_OK when ok
var STATUS_CANCEL = "cancelled";
var COLOR_ERROR = "#D16C6C";
var MS_TRELLOAPI_WAIT = (1000 / 2); //its really 10 per second but we dont abuse https://help.trello.com/article/838-api-rate-limits
var CMAX_THREADS = 4;
var g_callbackOnAssert = null;
var g_bDebuggingInfo = false;
var g_bAcceptSFT = true;
var g_bAcceptPFTLegacy = true;
var g_regexExcludeList = /\[\s*exclude\s*\]/;
var g_userTrelloBackground = null;
var g_regexWords = /\S+/g; //parse words from an s/e comment. kept global in hopes of increasing perf by not having to parse the regex every time
var PROP_TRELLOUSER = "plustrellouser";
var PROP_SHOWBOARDMARKERS = "showboardmarkers";
var COLUMNNAME_ETYPE = "E. type";
var g_bPopupMode = false; //running as popup? (chrome browse action popup) REVIEW zig: cleanup, only reports need this?
var SYNCPROP_CARDPOPUPTYPE = "cardPopupType"; //one of CARDPOPUPTYPE
var SYNCPROP_ACTIVETIMER = "cardTimerActive";
var SYNCPROP_optAlwaysShowSpentChromeIcon = "bAlwaysShowSpentChromeIcon"; //"b" because it used to be a boolean
var SYNCPROP_bShowedFeatureSEButton = "bShowedFeatureSEButton";
var SYNCPROP_bStealthSEMode = "bStealthSEMode";
var SYNCPROP_language = "language";
var SYNCPROP_BOARD_DIMENSION = "board_dimension";
var SYNCPROP_GLOBALUSER = "global_user";
var SYNCPROP_KEYWORDS_HOME = "keywords_home";
var LOCALPROP_PRO_VERSION = "pro_enabled";
var LOCALPROP_PRO_MSDATEENABLED = "pro_datestart"; //only used for prompting, not the actual date the user enabled it, only the local date as of v5.1.2
var SYNCPROP_MSLICHECK = "msLiCheck";
var SYNCPROP_LIDATA = "LiData"; //for chrome store { msLastCheck, msCreated, li}
var SYNCPROP_LIDATA_STRIPE = "striLiData"; //for stripe { msLastCheck, msCreated, li, userTrello, emailOwner, quantity, nameCardOwner}
var SYNCPROP_SERVIEWS = "SERViews"; // see g_serViews
var SYNCPROP_MSSTARTPLUSUSAGE = "msStartPlusUsage";
var SYNCPROP_USERSEBAR_LAST = "userSEBarLast";
var SYNCPROP_NO_SE = "dontUseSE";
var SYNCPROP_NO_EST = "dontUseEst";
var LOCALPROP_EXTENSION_VERSIONSTORE = "chromeStoreExtensionVersion";
var LOCALPROP_bHiliteTimerOnOpenCard = "bHiliteTimerOnOpenCard";
var g_bStealthSEMode = false; //stealth mode. Only applies when using google spreadsheet sync. use IsStealthMode()
var g_strServiceUrl = null; //null while not loaded. set to empty string or url NOTE initialized separately in content vs background
var SEKEYWORD_DEFAULT = "plus!";
var SEKEYWORD_LEGACY = "plus s/e";
var g_bEnableTrelloSync = false; //review zig this and g_bDisableSync must be initialized by caller (like loadSharedOptions)
var g_bDisableSync = false; // 'bDisabledSync' sync prop. note this takes precedence over bEnableTrelloSync or g_strServiceUrl 'serviceUrl'
var g_bCheckedTrelloSyncEnable = false; //review zig must be initialized by caller
var g_hackPaddingTableSorter = " "; //because we remove many tablesorter css styles, appending spaces to header text was the easiest way to avoid overlap with sort arrow
var g_dateMinCommentSELegacy = new Date(2014, 11, 12);
function IsStealthMode() {
return (!g_bDisableSync && g_bStealthSEMode && !g_optEnterSEByComment.IsEnabled() && g_strServiceUrl);
}
function MsWaitRetry() {
return (Math.floor(12000 + Math.random() * 8000));
}
const g_msWaitMax = 200000;
var g_optEnterSEByComment = {
bInitialized: false,
IsEnabled: function () { //note this doesnt take into account g_bDisableSync
assert(this.bInitialized);
assert(typeof g_bEnableTrelloSync !== "undefined");
return (g_bEnableTrelloSync && this.bEnabled && this.rgKeywords.length > 0);
},
bEnabled: false, //review zig: some use this directly because its not always equivalent to IsEnabled. clean up with another method or param in IsEnabled
rgKeywords: [SEKEYWORD_DEFAULT],
getAllKeywordsExceptLegacy: function () {
var ret=[];
var iMax=this.rgKeywords.length;
for (var i = 0; i < iMax; i++) {
var kw=this.rgKeywords[i];
if (kw.toLowerCase() == SEKEYWORD_LEGACY)
continue;
ret.push(kw);
}
if (ret.length == 0)
ret.push(SEKEYWORD_DEFAULT);
return ret;
},
getDefaultKeyword: function() {
assert(this.bInitialized);
var ret = this.rgKeywords[0];
if (!ret)
ret = SEKEYWORD_DEFAULT;
return ret.toLowerCase();
},
hasLegacyKeyword: function () {
assert(this.bInitialized);
var bFound = false;
this.rgKeywords.every(function (keyword) {
if (keyword.toLowerCase() == SEKEYWORD_LEGACY) {
bFound = true;
return false; //stop
}
return true; //continue
});
return bFound;
},
loadFromStrings: function (bEnabled, strKW) {
this.bEnabled = bEnabled || false;
this.rgKeywords = JSON.parse(strKW || "[]");
if (this.rgKeywords.constructor !== Array || this.rgKeywords.length == 0)
this.rgKeywords = [SEKEYWORD_DEFAULT]; //force always the default. array cant be empty.
this.bInitialized = true;
}
};
Array.prototype.appendArray = function (other_array) {
other_array.forEach(function (v) { this.push(v); }, this);
};
//var g_rgiDayName = ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'];
var g_rgiDayName = [null, null, null, null, null, null, null];
var g_rgiDayNameLong = [null, null, null, null, null, null, null];
function getWeekdayName(num, bLong) {
var dateKnown;
if (bLong) {
if (!g_rgiDayNameLong[num]) {
assert(num >= 0 && num <= 6);
dateKnown = new Date(2016, 10, 6 + num, 12, 0, 0, 0); //midday of known sunday + delta, to avoid daylight-saving issues
g_rgiDayNameLong[num] = dateKnown.toLocaleString(window.navigator.language, { weekday: 'long' });
}
return g_rgiDayNameLong[num];
}
if (!g_rgiDayName[num]) {
assert(num >= 0 && num <= 6);
dateKnown = new Date(2016, 10, 6+num, 12, 0, 0, 0); //midday of known sunday + delta, to avoid daylight-saving issues
g_rgiDayName[num]=dateKnown.toLocaleString(window.navigator.language, { weekday: 'short' });
}
return g_rgiDayName[num];
}
var EVENTS = {
NEW_ROWS: "newrows",
START_SYNC: "startsync",
DB_CHANGED: "dbchanged",
FIRST_SYNC_RUNNING: "firstsyncrunning",
EXTENSION_RESTARTING: "extensionRestarting"
};
var CARDPOPUPTYPE = {
POPUP_NOACTIONS: "noactions",
POPUP_SOMEACTIONS: "someactions",
NO_POPUP: "nopopup",
DEFAULT: "nopopup"
};
/* DowMapper
*
* handles mapping betwen a dow (day of week, 0=sunday, 1=monday, etc) to/from an ordering position (0 to 6)
* the week starts with the day at position 0.
*
* getDowStart()
* setDowStart(dow,delta)
* posWeekFromDow(dow)
* dowFromPosWeek(pos)
*
* Plus strategy for dealing with week numbers:
* each HISTORY stores its week number, so its easier to query without worrying about producing the right week query. Without it its hard to deal correctly
* with boundary weeks, for example week 53 of a given year might fall into the next year thus a query by year would crop the results.
* Once the week number is stored, we need a way to know what standard was used (week's start day) for the row. We dont keep that standard in browser storage because it wouldnt
* be possible to atomically change a row and setting. Thus the setting is saved in a table GLOBALS which has a single row and a column 'dowStart'
* Additionally, we keep in storage.sync the last dowStart the user configured, and during openDb it checks if the db needs converting.
* By convension, only openDb from the content script will cause conversion. the other callers just use the db setting. In practice, unless there is a rare case of failure,
* the sync setting and the db setting will be in sync. The sync setting has precedence and will continue attempting to make them in sync at the next openDb call (window refresh or new tab)
*
**/
var DowMapper = {
//public:
DOWSTART_DEFAULT:0, //sunday default
getDowStart: function () { return this.m_dowStart; }, //set dow with position 0
getDowDelta: function () { return this.m_dowDelta; },
setDowStart: function (dow, delta) {
assert(typeof(delta) !== "undefined");
this.m_dowStart = dow;
this.m_dowDelta = delta;
}, //get dow with position 0
posWeekFromDow: function (dow) { //position for a given dow
var pos = dow - this.m_dowStart - this.m_dowDelta;
if (pos < 0)
pos = 14 + pos;
pos = pos % 7;
return pos;
},
dowFromPosWeek: function (pos) { //dow in given position
var dowNew = pos + this.m_dowStart + this.m_dowDelta;
if (dowNew < 0)
dowNew = 14 + dowNew;
dowNew = dowNew % 7;
return dowNew;
},
//------------------------------------------
//private:
init: function () {
//initialize the object. see http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations
this.m_dowStart = this.DOWSTART_DEFAULT;
this.m_dowDelta = 0;
delete this.init; //dont call me back again
return this;
}
}.init();
function loadSharedOptions(callback) {
var keyAcceptSFT = "bAcceptSFT";
var keyAcceptPFTLegacy = "bAcceptPFTLegacy";
var keybEnableTrelloSync = "bEnableTrelloSync";
var keybDisabledSync = "bDisabledSync"; //note this takes precedence over bEnableTrelloSync or g_strServiceUrl 'serviceUrl'
var keybEnterSEByCardComments = "bEnterSEByCardComments";
var keyrgKeywordsforSECardComment = "rgKWFCC";
var keyUnits = "units";
var keybDontShowTimerPopups = "bDontShowTimerPopups";
var keyServiceUrl = 'serviceUrl';
assert(typeof SYNCPROP_optAlwaysShowSpentChromeIcon !== "undefined");
//review zig: app.js has duplicate code for this
chrome.storage.sync.get([SYNCPROP_NO_EST, SYNCPROP_NO_SE, SYNCPROP_MSSTARTPLUSUSAGE, keyServiceUrl, SYNCPROP_bStealthSEMode, SYNCPROP_language, keybDontShowTimerPopups, keyUnits, SYNCPROP_optAlwaysShowSpentChromeIcon, keyAcceptSFT, keybEnableTrelloSync, keybEnterSEByCardComments,
keyrgKeywordsforSECardComment, keybDisabledSync],
function (objSync) {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
g_strServiceUrl = objSync[keyServiceUrl]; //note: its still called serviceUrl even though now stores a sheet url (used to store a backend url in 2011)
if (g_strServiceUrl === undefined || g_strServiceUrl == null)
g_strServiceUrl = ""; //means simple trello. (do the same as in content script)
g_msStartPlusUsage = objSync[SYNCPROP_MSSTARTPLUSUSAGE] || null;
if (g_msStartPlusUsage == null) {
g_msStartPlusUsage = Date.now();
chrome.storage.sync.set({ [SYNCPROP_MSSTARTPLUSUSAGE]: g_msStartPlusUsage });
}
g_bDontShowTimerPopups = objSync[keybDontShowTimerPopups] || false;
UNITS.current = objSync[keyUnits] || UNITS.current;
setOptAlwaysShowSpentChromeIcon(objSync[SYNCPROP_optAlwaysShowSpentChromeIcon]);
g_bAcceptSFT = objSync[keyAcceptSFT];
if (g_bAcceptSFT === undefined)
g_bAcceptSFT = true;
g_bAcceptPFTLegacy = objSync[keyAcceptPFTLegacy];
if (g_bAcceptPFTLegacy === undefined)
g_bAcceptPFTLegacy = true; //defaults to true to not break legacy users
g_bEnableTrelloSync = objSync[keybEnableTrelloSync] || false;
g_optEnterSEByComment.loadFromStrings(objSync[keybEnterSEByCardComments], objSync[keyrgKeywordsforSECardComment]);
g_bDisableSync = objSync[keybDisabledSync] || false;
g_bStealthSEMode = (objSync[SYNCPROP_bStealthSEMode] && g_strServiceUrl && !g_bDisableSync) ? true : false;
g_language = objSync[SYNCPROP_language] || "en";
g_bNoSE = objSync[SYNCPROP_NO_SE] || false;
g_bNoEst = objSync[SYNCPROP_NO_EST] || false;
chrome.storage.local.get([PROP_TRELLOUSER, LOCALPROP_PRO_VERSION], function (obj) {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
g_userTrelloBackground = (obj[PROP_TRELLOUSER] || null);
g_bProVersion = obj[LOCALPROP_PRO_VERSION] || false; //does not update g_msStartPro
callback();
});
});
}
function errFromXhr(xhr) {
var errText = "error: " + xhr.status;
if (xhr.statusText || xhr.responseText) {
g_bIncreaseLogging = true;
errText = errText + "\n" + xhr.statusText + "\n" + xhr.responseText;
}
else if (xhr.status == 0)
errText = Language.NOINTERNETCONNECTION;
console.log(errText);
return errText;
}
function assert(condition, message) {
if (!condition) {
g_bIncreaseLogging = true;
var log = "Assertion failed. ";
if (message)
log += message;
logPlusError(log);
debugger;
if (g_callbackOnAssert)
g_callbackOnAssert(log);
throw new Error(log);
}
}
function saveAsFile(data, filename, bForceSave) {
if (!bForceSave && !g_bDebuggingInfo)
return;
if (!filename)
filename = 'console.json';
if (typeof data === "object") {
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], { type: 'text/json' }),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
// ETYPE
// stored in HISTORY.eType
// indicates the estimate action on the card (by card by user)
var ETYPE_NONE = 0;
var ETYPE_INCR = 1;
var ETYPE_DECR = -1;
var ETYPE_NEW = 2;
function nameFromEType(eType) {
if (eType == ETYPE_NONE)
return "";
if (eType == ETYPE_INCR)
return "+E";
if (eType == ETYPE_DECR)
return "-E";
if (eType == ETYPE_NEW)
return "NEW";
}
function buildSyncErrorTooltip(status) {
var ret = "";
if (status) {
if (status.statusRead && status.statusRead != STATUS_OK)
ret = ret + "\nLast sync read error:\n" + status.statusRead;
if (status.statusWrite && status.statusWrite != STATUS_OK)
ret = ret + "\nLast sync write error:\n" + status.statusWrite;
}
if (ret.length > 0)
ret = ret + "\n";
return ret;
}
//openPlusDb
//
//wrapper for openDB message. initializes global options
function openPlusDb(sendResponse, options) {
sendExtensionMessage({ method: "openDB", options: options },
function (response) {
if (response.dowStart !== undefined) {
assert(response.dowDelta !== undefined);
DowMapper.setDowStart(response.dowStart, response.dowDelta);
}
sendResponse(response);
});
}
function CreateWaiter(cTasks, callback) {
var waiter = {
Init: function (cTasks, callback) {
assert(this.cTasksPending == 0);
this.cTasksPending = cTasks;
this.OnFinish = callback;
return this;
},
Increase: function (prop) { //prop: optional to prevent multiple calls with the same prop from increasing
if (prop) {
if (this.mapProps[prop])
return;
this.mapProps[prop] = true;
}
this.cTasksPending++;
},
SetCount: function (cTasks) {
assert(this.cTasksPending == 0);
this.cTasksPending = cTasks;
},
Decrease: function (prop) { //prop: optional to prevent multiple calls with the same prop from decreasing
if (prop) {
if (this.mapProps[prop])
return;
this.mapProps[prop] = true;
}
this.cTasksPending--;
if (this.bWaiting && this.cTasksPending == 0)
this.OnFinish();
},
SetWaiting: function (bWaiting) {
this.bWaiting = bWaiting;
if (this.bWaiting && this.cTasksPending == 0)
this.OnFinish();
},
bWaiting: false,
cTasksPending: 0,
mapProps: {}
}.Init(cTasks, callback);
return waiter;
}
function getUrlParams(href) {
if (!href)
href = window.location.href;
var iParams = href.indexOf("?");
var objRet = {};
if (iParams < 0)
return objRet;
var strParams = href.substring(iParams + 1);
var params = strParams.split("&");
var i = 0;
for (i = 0; i < params.length; i++) {
var pair = params[i].split("=");
objRet[pair[0]] = decodeURIComponent(pair[1]);
}
return objRet;
}
/* strTruncate
*
* truncates a string if larger than length, returns a string at most of length+3
**/
function strTruncate(str, length) {
if (length === undefined)
length = g_cchTruncateDefault;
if (typeof (str) != 'string')
str = "" + str;
if (str.length > length)
str = str.substr(0, length) + "...";
return str;
}
function sendExtensionMessage(obj, responseParam, bRethrow) {
function preResponse(response) {
try {
if (response && response.bExtensionNotLoadedOK)
return; //safer to not respond
if (chrome.runtime.lastError) //could happen on error connecting to the extension. that case response can even be undefined https://developer.chrome.com/extensions/runtime#method-sendMessage
throw new Error(chrome.runtime.lastError.message);
if (responseParam)
responseParam(response);
} catch (e) {
logException(e);
}
}
try {
//sending a message from bk to bk doesnt work, so do it manually
if (g_bFromBackground && chrome.runtime && chrome.runtime.getBackgroundPage) {
chrome.runtime.getBackgroundPage(function (bkPage) {
try {
bkPage.handleExtensionMessage(obj, preResponse);
} catch (e) {
logException(e);
}
});
return;
}
chrome.runtime.sendMessage(obj, preResponse);
} catch (e) {
logException(e);
if (bRethrow)
throw e;
}
}
function logException(e, str) {
if (str && str != e.message)
str = str + "," + e.message;
else
str = e.message;
logPlusError(str + " :: " + e.stack, false);
}
function sendDesktopNotification(strNotif, timeout, idUse) {
if (timeout === undefined)
timeout = 7000;
sendExtensionMessage({ method: "showDesktopNotification", notification: strNotif, timeout: timeout, idUse: idUse }, function (response) { });
}
var g_plusLogMessages = []; //queues an error log which is regularly purged
var g_lastLogPush = null;
var g_lastLogError = "";
function bIgnoreError(str) {
return (str.indexOf("Error connecting to extension") >= 0 || str.indexOf("Invocation of form runtime")>=0);
}
//logPlusError
// bAddStackTrace: defaults to true.
//
function logPlusError(str, bAddStackTrace) {
str = str || ""; //handle possible undefined
if (bIgnoreError(str))
return;
if (str.indexOf("disconnected port") >= 0 || str.indexOf("port closed") >= 0)
return; //sometimes we dont return from a received message. that seems ok
g_bIncreaseLogging = true;
var strStack = null;
var date = new Date();
if (bAddStackTrace === undefined)
bAddStackTrace = true;
if (bAddStackTrace) {
try {
throw new Error();
} catch (e) {
str = str + " :: " + e.stack;
//remove self/known callstack elements, and remove column from each line number
str = str.replace(/\n\s*(at logPlusError).*\n/, "\n").replace(/\n\s*(at assert).*\n/, "\n").replace(/:\d\)/g, ")");
//remove absolute paths
str = str.replace(/chrome-extension:\/\/.*\//g, "");
}
}
g_lastLogError = str;
console.log(str);
if (typeof g_userTrelloCurrent != "undefined") {
if (g_userTrelloCurrent && (g_userTrelloCurrent == "zmandel" || g_userTrelloCurrent == "zigmandel")) {
if (typeof document != "undefined" && typeof PLUS_BACKGROUND_CALLER == "undefined")
console.dir(document.body);
//hi to me
if (str)
alert(str);
}
}
var pushData = { date: date.getTime(), message: str };
if (!(g_lastLogPush != null && (pushData.date - g_lastLogPush.date < 1000 * 60) && pushData.message == g_lastLogPush.message)) {
g_lastLogPush = pushData;
g_plusLogMessages.push(pushData);
setTimeout(function () { //get out of the current callstack which could be inside a db transaction etc
if (g_callbackPostLogMessage)
g_callbackPostLogMessage();
}, 2000);
}
}
/* setCallbackPostLogMessage
* must be called once if you want to commit messages to the db
* will cause a commit one call to push a message (errors etc), plus will attempt commit every minute
**/
var g_intervalCallbackPostLogMessage = null;
var g_callbackPostLogMessage = null;
function setCallbackPostLogMessage(callback) {
g_callbackPostLogMessage = callback;
if (g_intervalCallbackPostLogMessage)
clearInterval(g_intervalCallbackPostLogMessage);
//note: callers expect this interval, dont change it.
g_intervalCallbackPostLogMessage = setInterval(function () {
callback();
}, 60000);
}
/* getSQLReportShared supports Promises or callbacks
* when okCallback is not set, it will use promises (ignoring errorCallback even if set)
* when okCallback is set, it uses callbacks (okCallback and errorCallback if set)
**/
function getSQLReportShared(sql, values, okCallback, errorCallback) {
var promise = null;
var resolveFn = null; //these are used so we can use promises or callbacks
var rejectFn = null;
function sendResponse(response) {
if (response.status != STATUS_OK) {
if (rejectFn) {
rejectFn(new Error(response.status));
return;
}
if (errorCallback && !resolveFn)
errorCallback(response.status);
return; //dont call okCallback
}
if (resolveFn) {
resolveFn(response);
return;
}
okCallback(response);
}
if (!okCallback) {
assert(window.Promise);
promise = new Promise(doit);
return promise;
}
function doit(resolve, reject) {
resolveFn = resolve;
rejectFn = reject;
var obj = { method: "getReport", sql: sql, values: values };
if (chrome && chrome.runtime && chrome.runtime.getBackgroundPage) { //calling directly background (vs using a message) should be more efficient and allow bigger returned tables
chrome.runtime.getBackgroundPage(function (bkPage) {
bkPage.handleGetReport(obj, sendResponse);
});
}
else {
sendExtensionMessage(obj, sendResponse);
}
}
doit();
return null; //happy lint
}
function selectElementContents(el) {
if (window.getSelection && document.createRange) {
//select it just for visual purposes. Extension background will do the actual copy
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
sendExtensionMessage({ method: "copyToClipboard", html: el.innerHTML }, function (response) {
if (response.status != STATUS_OK) {
sendDesktopNotification(response.status || "Error");
return;
}
setTimeout(function () {
removeSelection();
sendDesktopNotification("Copied to the clipboard.\nPaste anywhere like excel or email.");
}, 100); //delay is for user visuals only
});
}
}
function removeSelection() {
if (window.getSelection && document.createRange) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
function prependZero(num) {
assert(typeof num == "number");
return (num < 10 ? "0" + num : num);
}
function parseColonFormatSE(val, bExact) {
assert(val.indexOf(":") >= 0);
if (val.indexOf(".") >= 0)
return null; //invalid
var rg = val.split(":");
if (rg.length != 2)
return null; //invalid
var h = parseInt(rg[0], 10) || 0;
var sign = (h < 0 ? -1 : 1);
h = Math.abs(h);
var m = parseInt(rg[1], 10) || 0;
var retVal = sign * (h + (m / UNITS.ColonFactor()));
if (bExact)
return retVal;
return parseFixedFloat(retVal);
}
//parseFixedFloat
//round to two decimals.
//input can be string or number
//if text contains colon, will assume units:subunits format
//returns a float
function parseFixedFloat(text, bDontZeroNan, bOneDecimal) {
var val = null;
if (typeof text == "number")
val = text;
else {
if (typeof (text) == 'string' && text.indexOf(":") >= 0) {
val = parseColonFormatSE(text, false);
if (val === null)
val = 0;
}
else {
val = parseFloat(text);
}
}
if (isNaN(val)) {
if (bDontZeroNan)
return val;
return 0;
}
var roundNum = (bOneDecimal ? 10 : 100);
return Math.round(val * roundNum) / roundNum;
}
function addSumToRows(bModifyRows, rows, prefix) {
prefix = prefix || "";
var mapRet = {};
var iRow = 0;
for (; iRow < rows.length; iRow++) {
var sum = 0;
var row = rows[iRow];
var iCol = 1;
for (; iCol < row.length; iCol++)
sum += row[iCol];
sum = parseFixedFloat(sum);
if (bModifyRows)
row[0] = prefix + sum + " " + row[0];
else
mapRet[row[0]] = sum;
}
return mapRet;
}
function getDrilldownTopButtons(bNoClose, title) {
bNoClose = bNoClose || false;
var ret = '<div style="padding-bottom:3px;"><p class="agile_drilldown_h"><span>' + title + "</span><span class='agile_selection_totals'></span></p>";
if (!bNoClose)
ret += '<img class="agile_help_close_drilldown"></img>';
ret += '<img class="agile_drilldown_select"></img></div>';
return ret;
}
function getHtmlBurndownTooltipFromRows(bShowTotals, rows, bReverse, header, callbackGetRowData, bOnlyTable, title, bSEColumns) {
bOnlyTable = bOnlyTable || false;
if (title === undefined)
title = "Plus Drill-down";
var iColComment = -1;
function th(val, bExtend) {
return "<th class='agile_drill_th" + (bExtend ? " agile_drill_th_extend" : "") + "'>" + val + "</th>";
}
function htmlRow(row) {
function td(val, bNoTruncate, type) {
var classesTd = "agile_cell_drilldown";
if (type) {
classesTd += " agile_cell_drilldown" + type; //used for agile_cell_drilldownS and agile_cell_drilldownE classes
if (val === 0) {
//review zig: assumes type is always an s/e type
classesTd += " agile_reportSECellZero";
}
}
if (val === "")
val = " "; //prevent tables with all empty fields (Bad height)
if (typeof(val)=="number")
val = numToPlusLocaleString(val);
return "<td class='"+classesTd+ "'>" + (bNoTruncate ? val : strTruncate(val)) + "</td>";
}