-
Notifications
You must be signed in to change notification settings - Fork 3
/
trellosync.js
3027 lines (2633 loc) · 144 KB
/
trellosync.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_cMaxCallstack = 400; //400 is a safe size. Larger could cause stack overflow. must be large else is too slow in chrome canary.
var g_cLimitActionsPerPage = 900; //the larger the better to avoid many round-trips and consuming more quota. trello allows up to 1000 but I feel safer with a little less.
var g_bProcessCardCommentCopies = false; //Trello optionally copies card comment when making a card copy REVIEW must handle in comment parser. blocking: these dont appear inside board.actions so we would need a full rewrite of the sync algorithm.
var g_bUpdateSyncNotificationProgress = false;
var SQLQUERY_PREFIX_CARDDATA = "select dateCreated, dateDue, idBoard, name, dateSzLastTrello, idList, idLong, idCard, idShort, bArchived, bDeleted ";
var SQLQUERY_PREFIX_LISTDATA = "select idBoard, name, dateSzLastTrello, idList, bArchived, pos ";
var SQLQUERY_PREFIX_BOARDDATA = "select idBoard,idLong, name, dateSzLastTrello, idActionLast, bArchived, verDeepSync, idTeam, dateLastActivity ";
var SQLQUERY_PREFIX_LABELDATA = "select idLabel,name, idBoardShort, color ";
var SQLQUERY_PREFIX_LABELCARDDATA = "select idCardShort, idLabel ";
var g_msDelayTrelloSearch = (1000 * 60 * 5); //trello takes sometimes over a minute to show changed cards in search, so use 5min as a safe delay
var g_lastStatusSyncCache = {}; //needed for later checking if the last sync had errors easily (not async) statusRead, statusWrite, date could all be undefined)
var g_strKeyTokenTrelloLast = "plus_token_trello_last";
/* array of cards where card = {
status: "OK", //ignore it
shortLink: "H8gGOqNk",
nameOld: "(4) bb [5]",
nameNew: "bb"
}; */
var g_rgUndoCardRename = null;
//REVIEW zig: idCardShort is a bad name, its really shortLink, and NOT idShort.
function checkMaxCallStack(iLoop) {
return (((iLoop+1) % g_cMaxCallstack) == 0);
}
function logTrelloSync(message) {
if (g_bIncreaseLogging)
console.log(message);
}
var TOTAL_SYNC_STAGES = 9;
var g_syncStatus = {
postfixStage: "",
strLastStatus: STATUS_OK,
bSyncing: false,
cSteps: 0,
cProcessed: 0,
stage: "",
cTotalStages: TOTAL_SYNC_STAGES,
stageNum: 0,
rgStepHistory: [], //review zig: for debugging errors in steps
msStart: 0,
msLast: Date.now(),
bSingleStep: false,
bExtraRenameStep:false,
setStage: function (name, cSteps, bSingleStep, bFirstStep) { //bSingleStep indicates this stage always has one step
//review zig: a rare bug causes stageNum to be != cTotalStages when sync finishes ok. I have reviewed the flow many times but havent
//found the cause. Seems that it would need two sync at the same time but a global prevents that already.
//since its very rare, I suspect it happens when a specific step fails an ajax call (no interenet etc) and plus doesnt recover properly.
//I have reviewed the error handlers and they seem ok. eventually should use bFirstStep as safety but
//not done yet so rgStepHistory in error logs can tell me when this bug happens.
assert(name=="" || this.bSyncing || this.stage == ""); //first stage or already syncing. first stage is special because bSyncing isnt yet set (so progress wouldnt read a bad stage)
this.bSingleStep = bSingleStep || false;
var bSyncingOld = this.bSyncing;
var bFinished = (name == "");
if (bFinished) {
this.stageNum = 0;
this.bSyncing = false;
this.bExtraRenameStep = false;
this.rgUndoCardRename = null;
this.cTotalStages = TOTAL_SYNC_STAGES;
}
else {
if (!bSyncingOld) {
this.stageNum = 0; //reset
}
if (this.stageNum == 0 && bFirstStep)
this.rgStepHistory = [];
this.stageNum++;
this.bSyncing = true;
name = "Stage " + this.stageNum + " of " + this.cTotalStages + ": " + name;
this.rgStepHistory.push(name);
}
this.stage = name;
this.postfixStage = ""; //reset
this.cProcessed = 0;
this.cSteps = cSteps;
var msNow = Date.now();
if (this.bSyncing && !bSyncingOld) {
this.msStart = msNow;
this.msLast = msNow;
this.cTotalStages = TOTAL_SYNC_STAGES;
this.bExtraRenameStep = false;
this.rgUndoCardRename = null;
var strOptionrenameCardsPendingData = localStorage.getItem("plus_rename_cards_pending_data");
if (strOptionrenameCardsPendingData) {
localStorage.removeItem("plus_rename_cards_pending_data"); //remove right away, so in case the following code gets stuck in a loop, we wont continue attempting rename
var optRename = JSON.parse(strOptionrenameCardsPendingData);
if (optRename.pending) {
this.cTotalStages++;
this.bExtraRenameStep = true;
this.bOnlyRenameCardsWithHistory = optRename.bOnlyCardsWithHistory;
if (typeof (this.bOnlyRenameCardsWithHistory) == "undefined")
this.bOnlyRenameCardsWithHistory = true; //safer
}
} else if (g_rgUndoCardRename) {
this.cTotalStages++;
this.bExtraRenameStep = true;
this.rgUndoCardRename = g_rgUndoCardRename;
g_rgUndoCardRename = null;
}
}
var segDelta = " delta prev:" + Math.round((msNow - (bFinished ? this.msStart : this.msLast)) / 10) / 100 + "s";
if (!(bFinished && !bSyncingOld))
this.msLast = msNow;
updatePlusIcon(bSyncingOld == this.bSyncing);
if (!bFinished)
logTrelloSync("sync: " + this.stage + " total:" + this.cSteps + segDelta);
else {
if (g_bEnableTrelloSync && bSyncingOld)
logTrelloSync("sync: finished." + segDelta);
}
}
};
//review zig: tokenTrello is not used. some callers already pass null
function processThreadedItemsSync(tokenTrello, items, onPreProcessItem, onProcessItem, onFinishedAll, bDontUpdateSyncStatus, needsProcessItemDelay) {
function onFinishedEach(status) {
if (status == STATUS_OK) {
if (!bDontUpdateSyncStatus) {
g_syncStatus.cProcessed++;
updatePlusIcon(true);
}
}
}
processThreadedItems(tokenTrello, items, onPreProcessItem, onProcessItem, onFinishedAll, onFinishedEach, needsProcessItemDelay);
}
function handleGetTrelloCardData(request, sendResponseParam) {
var response = { status: "error" };
getCardData(request.tokenTrello, request.idCard, request.fields, request.bBoardShortLink, callbackCard);
function callbackCard(cardData) {
response.status = cardData.status;
response.card = cardData.card;
sendResponseParam(response);
}
}
function handleGetTrelloBoardData(request, sendResponseParam) {
var response = { status: "error" };
getBoardData(request.tokenTrello, false, request.idBoard, "fields=" + request.fields, callback);
function callback(data) {
response.status = data.status;
response.board = data.board;
sendResponseParam(response);
}
}
function makeLastStatusSync(statusRead, statusWrite, date) {
if (!date)
date = Date.now();
g_lastStatusSyncCache = { statusRead: statusRead, statusWrite: statusWrite, date: date };
return g_lastStatusSyncCache;
}
/* handleSyncBoards
*
* Entry point to trello sync
*
* See sync diagram on how this can be reached:
* https://docs.google.com/drawings/d/1C6SaEjejg1e_NzfqhMpno5B5RyugtwCzdfH4XTyZmuw/edit?usp=sharing
*
**/
function handleSyncBoards(request, sendResponseParam) {
loadBackgroundOptions(function () {
function sendResponse(response) {
g_syncStatus.strLastStatus = response.status;
if (g_optEnterSEByComment.IsEnabled()) {
var pairDateLast = {};
var pairLastStatus = {};
var dateNow = Date.now();
if (response.status == STATUS_OK)
pairDateLast["plus_datesync_last"] = dateNow;
chrome.storage.local.set(pairDateLast, function () {
pairLastStatus["plusSyncLastStatus"] = makeLastStatusSync(response.status, STATUS_OK, dateNow);
chrome.storage.local.set(pairLastStatus, function () {
sendResponseParam(response);
});
});
}
else
sendResponseParam(response);
}
if (g_bDisableSync) {
sendResponseParam({ status: "sync is off" });
return;
}
if (!isDbOpened() || g_syncStatus.bSyncing || g_cReadSyncLock != 0 || g_cFullSyncLock != 0 || g_cWriteSyncLock != 0) {
sendResponseParam({ status: "busy" });
return;
}
//first stage
g_syncStatus.setStage("", 0); //reset in case somehow a previous one was pending
g_syncStatus.setStage("Starting sync", 1, true, true); //note that this will cause g_syncStatus.bSyncing=true
//if there are pending rows, we must commit them before because they reference board/card names/ids that could change during sync
//and sync only maintains the history table, not the queuehistory
insertPendingSERows(function (responseInsertSE) {
if (responseInsertSE.status != STATUS_OK) {
g_syncStatus.setStage("", 0);
sendResponseParam({ status: responseInsertSE.status });
return;
}
handleSyncBoardsWorker(request.tokenTrello, request.bUserInitiated, sendResponse);
});
});
}
function handleSyncBoardsWorker(tokenTrello, bUserInitiated, sendResponseParam) {
var tokenTrelloStored = localStorage.getItem(g_strKeyTokenTrelloLast);
g_bUpdateSyncNotificationProgress = false; //reset
if (!tokenTrello) {
if (!tokenTrelloStored) {
//note: currently the token is not actually used during sync, but might be used in the future
//its also safer to do the background calls only after we've made calls from the content script (which sets the token)
sendResponseParam({ status: "busy" }); //happens if called from offline sync and weve never done an online sync yet (rare)
return;
}
tokenTrello = tokenTrelloStored;
}
if (!tokenTrelloStored)
localStorage.setItem(g_strKeyTokenTrelloLast, tokenTrello);
var boardsTrello = []; //boards the user has access. This list is later intersected with the db boards list.
var boardsReport = [];
//Arquitecture note about rgCardResetData: see http://sqlite.org/autoinc.html regarding deleting rows and rowid behaviour. some plus features rely on an always-incrementing rowid,
//(like etype for E1st, and boardmarkers). We could use autoincrement on history, but requires an upgrade of the table and decreases performace.
//that sqlite link in our case says that you cant ever delete the row with the largest rowid, which could be of a card in this array.
//to avoid the issue, and to maintain a record of the original values being modified, I instead make the existing card history rows 0/0,
//and include in the note the [details] of the original S/E in the row.
//this does not break 1st estimates, because they ignore 0/0 when calculating min(rowid) see updateCardRecurringStatusInHistory, handleMakeNonRecurring
//CARDBALANCE and BOARDMARKER tables are reset for the cards, and are re-generated.
var alldata = {
bForceDeepSyncOnRecentBoards: bUserInitiated,
labels: {}, //hash by idLabel (name,idBoardShort,color)
teams: {}, //hash by idTeam (name, dateSzLastTrello, nameShort)
boards: {}, //hash by shortLink. (name, dateSzLastTrello, idActionLast, bArchived, idTeam ...) **NOTE** dateSzLastTrello is 1ms behind (see note in sql)
lists: {}, //hash by idLong. (name, idBoard, dateSzLastTrello, bArchived, pos)
cards: {}, //hash by shortLink. (name, idBoard, dateSzLastTrello, idList, bArchived, listCards[] (idList,dateSzIn,dateSzOut,userIn,userOut) )
//if cards.idLabels, contains an array of idLabels
cardsByLong: {}, //hash idLong -> shortLink.
boardsByLong: {}, //hash idLong -> shortLink.
hasBoardAccessDirect: {}, //hash by shortLink -> true iff user has access to that board (note: means user has no direct access, but may still have access throigh team membership)
hasNoBoardAccess: {}, //hash by shortLink -> true iff user has NO board access.
hasBoardAccess : {}, //hash by shortLink -> true iff user has access to that board. Not here does not mean user has no access.
rgCommentsSE: [], //all possible S/E comments
rgCardResetData: [], //array of {idCard: shortLink, idBoard: shortLink, dateSzBefore, idActionReset: action with resetsync command } of cards needing reset
dateLastLabelsSyncStrOrig: null, //when not null, indicates original value from GLOBALS
dateLastLabelsSyncStrNew: null //when not null, indicates new value from GLOBALS
};
g_lastLogError = ""; //reset
updatePlusIcon(false);
startSyncProcess();
function startSyncProcess() {
var request = { sql: "select idTeam, name, dateSzLastTrello, nameShort FROM TEAMS where idTeam<>?", values: [IDTEAM_UNKNOWN] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK) {
sendResponse(responseReport);
return;
}
responseReport.rows.forEach(function (row) {
assert(row.idTeam);
var teamCur = cloneObject(row); //to modify it
teamCur.orig = cloneObject(teamCur); //keep original values for comparison
alldata.teams[row.idTeam] = teamCur;
});
var request = { sql: SQLQUERY_PREFIX_BOARDDATA+"FROM BOARDS where idBoard<>?", values: [IDBOARD_UNKNOWN] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK) {
sendResponse(responseReport);
return;
}
boardsReport = cloneObject(responseReport.rows || []); //clone so rows can be modified.
assert(boardsReport);
getBoardsLastInfo(tokenTrello, callbackBoardsLastInfo);
});
});
}
function callbackBoardsLastInfo(responseBoardsLastInfo) {
if (responseBoardsLastInfo.status != STATUS_OK) {
sendResponse(responseBoardsLastInfo);
return;
}
boardsTrello = responseBoardsLastInfo.items;
var bFirstSync = (boardsTrello.length > 0 && ((localStorage.getItem("plus_first_trello_sync_completed") || "") != "true"));
if (bFirstSync) {
animateFlip();
for (var iAnim = 1; iAnim < 10; iAnim++)
doAnim(1000 * iAnim);
function doAnim(ms) {
setTimeout(function () {
if (g_syncStatus.bSyncing)
animateFlip();
}, ms);
}
broadcastMessage({ event: EVENTS.FIRST_SYNC_RUNNING, status: STATUS_OK });
g_bUpdateSyncNotificationProgress = true;
handleShowDesktopNotification({
notification: Language.FIRSTSYNC_PRE,
timeout: 15000,
idUse: IDNOTIFICATION_FIRSTSYNCPRORESS,
dontClose: true
});
}
completeMissingCardDateCreated(tokenTrello, alldata, function (response) {
if (response.status != STATUS_OK)
sendResponse(response);
else
getAllTrelloBoardActions(tokenTrello, alldata, boardsReport, boardsTrello, process, bUserInitiated);
});
}
function sendResponse(response) {
if (response.status == STATUS_OK) {
if (g_syncStatus.cTotalStages != g_syncStatus.stageNum)
logPlusError("Finished with stageNum != cTotalStages " + g_syncStatus.stageNum + "/" + g_syncStatus.cTotalStages + ":"+JSON.stringify(g_syncStatus.rgStepHistory));
}
g_syncStatus.setStage("", 0);
sendResponseParam(response);
}
function process(responseGetActions) {
if (responseGetActions.status != STATUS_OK)
sendResponse({ status: responseGetActions.status });
else {
function processAllCardsRename(response) {
if (response.status == STATUS_OK && g_syncStatus.bExtraRenameStep) {
if (g_syncStatus.rgUndoCardRename)
processUndoAllCardsNameCleanup(tokenTrello, g_syncStatus.rgUndoCardRename, sendResponse);
else
processAllCardsNameCleanup(tokenTrello, g_syncStatus.bOnlyRenameCardsWithHistory, sendResponse);
}
else
sendResponse(response);
}
processTrelloActions(tokenTrello, alldata, responseGetActions.actions, responseGetActions.boards, responseGetActions.hasBoardAccessDirect, processAllCardsRename);
}
}
}
function populateTeams(teamsDb, boardsTrello) {
boardsTrello.forEach(function (board) {
var team = board.organization;
var bChanged = false;
if (!team)
return;
var teamDb = teamsDb[team.id];
assert(board.dateLastActivity);
var teamNew = {
idTeam: team.id,
name: team.displayName,
dateSzLastTrello: board.dateLastActivity,
nameShort: team.name || ""
};
if (!teamDb) {
teamsDb[team.id] = teamNew;
}
else {
if (teamDb.dateSzLastTrello < teamNew.dateSzLastTrello)
teamDb.dateSzLastTrello = teamNew.dateSzLastTrello;
//dateSzLastTrello comes from the board, not the team. so update name and nameShort which is always fresh data
teamDb.name = teamNew.name;
teamDb.nameShort = teamNew.nameShort;
}
});
}
function processUndoAllCardsNameCleanup(tokenTrello, rgUndoCardRename, sendResponse) {
handleShowDesktopNotification({
notification: "Starting to UNDO card title renames.\nWatch progress by hovering the Chrome Plus icon.",
timeout: 15000
});
var rgErrorRenamedCards = [];
g_syncStatus.setStage("Undoing card renames.", rgUndoCardRename.length);
processThreadedItemsSync(tokenTrello, rgUndoCardRename, null, onProcessItem, onFinishedAll);
/* a card contains: cardSample = {
status: "OK", //ignore it
shortLink: "H8gGOqNk",
nameOld: "(4) bb [5]",
nameNew: "bb"
}; */
function onProcessItem(tokenTrello, card, iitem, postProcessItem) {
function callPost(status) {
postProcessItem(status, card, iitem);
}
if (!card.status || card.status != STATUS_OK) {
rgErrorRenamedCards.push("Ignoring card with previous failed rename or missing status. shortLink: " + (card.shortLink || "missing too!"));
callPost(STATUS_OK);
return;
}
var shortLink = card.shortLink;
if (!shortLink || !card.nameOld) {
rgErrorRenamedCards.push("Ignoring card with missing shortLink/nameOld");
callPost(STATUS_OK);
return;
}
renameCard(tokenTrello, shortLink, card.nameOld, function (cardData) {
if (cardData.status != STATUS_OK)
rgErrorRenamedCards.push("Error during card rename. shortLink: " + shortLink + ". " + cardData.status);
else {
if (!cardData.hasPermission) {
rgErrorRenamedCards.push("No permission to rename card. shortLink: " + shortLink);
cardData.status = STATUS_OK;
}
}
callPost(cardData.status);
}, STATUS_OK); //STATUS_OK means a failure from lack of permission will still be OK (with hasPemission=false)
}
function onFinishedAll(status) {
if (rgErrorRenamedCards.length > 0) {
saveAsFile(rgErrorRenamedCards.join("\r\n"), "error log - plus for trello undo renamed cards.txt", true);
handleShowDesktopNotification({
notification: "Finished undo operation of " + rgUndoCardRename.length + " cards with errors (see downloaded file).",
timeout: 8000
});
} else {
handleShowDesktopNotification({
notification: "Finished undo operation of " + rgUndoCardRename.length + " cards OK.",
timeout: 8000
});
}
sendResponse({ status: status });
}
}
function processAllCardsNameCleanup(tokenTrello, bOnlyRenameCardsWithHistory, sendResponse) {
handleShowDesktopNotification({
notification: "Starting to cleanup S/E from card titles.\nWatch progress by hovering the Chrome Plus icon.",
timeout: 15000
});
var sql = "select idCard FROM CARDS WHERE bDeleted=0";
if (bOnlyRenameCardsWithHistory)
sql = "select c.idCard FROM CARDS c JOIN CARDBALANCE cb ON c.idCard=cb.idCard WHERE c.bDeleted=0";
var request = { sql: sql, values: [] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK || responseReport.rows.length == 0) {
if (responseReport.status == STATUS_OK)
g_syncStatus.setStage("Removing S/E from card titles", 1, true); //pretent step happened anyway (as status could be OK so caller expects all steps to finish)
sendResponse(responseReport);
return;
}
g_syncStatus.setStage("Removing S/E from card titles", responseReport.rows.length);
var rgRenamedCards = [];
var rgErrorsRename = [];
processThreadedItemsSync(tokenTrello, responseReport.rows, null, onProcessItem, onFinishedAll);
function onProcessItem(tokenTrello, card, iitem, postProcessItem) {
function callPost(status) {
postProcessItem(status, card, iitem);
}
function callbackCard(cardData) {
if (cardData.status != STATUS_OK) {
callPost(cardData.status);
return;
}
if (!cardData.hasPermission) {
rgErrorsRename.push("No permission to get card with shortLink: " + card.idCard);
callPost(STATUS_OK);
return;
}
var nameNew = parseSE(cardData.card.name, true).titleNoSE;
if (cardData.card.name != nameNew) {
var shortLinkSaved = cardData.card.shortLink;
var nameOld = cardData.card.name;
renameCard(tokenTrello, shortLinkSaved, nameNew, function (cardData) {
rgRenamedCards.push({ status: cardData.status, shortLink: shortLinkSaved, nameOld: nameOld, nameNew: nameNew });
if (cardData.status == STATUS_OK && !cardData.hasPermission) {
rgErrorsRename.push("No permission to rename card with shortLink: " + shortLinkSaved);
cardData.status = STATUS_OK;
}
callPost(cardData.status);
}, STATUS_OK); //STATUS_OK means a failure from lack of permission will still be OK (with hasPemission=false)
}
else
callPost(STATUS_OK);
}
assert(card.idCard);
getCardData(tokenTrello, card.idCard, "shortLink,name", false, callbackCard);
}
function onFinishedAll(status) {
if (rgErrorsRename.length > 0)
saveAsFile(rgErrorsRename.join("\r\n"), "error log - plus for trello renamed cards.txt", true, true);
saveAsFile({ totalCards: rgRenamedCards.length, cards: rgRenamedCards }, "plus for trello renamed cards json.txt", true);
var strNotify;
if (rgErrorsRename.length==0)
strNotify = "Finished renaming " + rgRenamedCards.length + " cards.\nAs a backup, all renamed cards are in the file just downloaded.";
else
strNotify = "Finished renaming with errors (see downloaded errors file)." + rgRenamedCards.length + " cards.\nAs a backup, all renamed cards are in the file just downloaded.";
handleShowDesktopNotification({
notification: strNotify,
timeout: 15000
});
sendResponse({ status: status });
}
});
}
function completeMissingCardDateCreated(tokenTrello, alldata, sendResponse) {
var request = { sql: SQLQUERY_PREFIX_CARDDATA + "FROM CARDS where dateCreated is NULL AND idLong is not NULL", values: [] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK) {
sendResponse(responseReport);
return;
}
responseReport.rows.forEach(function (row) {
var cardCur = alldata.cards[row.idCard];
if (!cardCur) {
cardCur = cloneObject(row);
cardCur.orig = cloneObject(cardCur); //keep original values for comparison
alldata.cards[row.idCard] = cardCur;
if (row.idLong)
alldata.cardsByLong[row.idLong] = row.idCard;
}
if (!cardCur.dateCreated && row.idLong) {
var cSeconds = parseInt(row.idLong.substring(0, 8), 16); //http://help.trello.com/article/759-getting-the-time-a-card-or-board-was-created
if (cSeconds && cSeconds > 0)
cardCur.dateCreated = cSeconds;
}
});
sendResponse({ status: STATUS_OK });
});
}
function completeMissingListCardData(tokenTrello, alldata, sendResponse) {
var shortLinkCard = null;
var cardsToFix=[];
for (shortLinkCard in alldata.cards) {
var cardCur = alldata.cards[shortLinkCard];
if (!cardCur.bDeleted && (cardCur.idList == IDLIST_UNKNOWN || cardCur.idList == null))
cardsToFix.push(cardCur);
}
g_syncStatus.setStage("Completing card's lists", cardsToFix.length);
processThreadedItemsSync(tokenTrello, cardsToFix, null, onProcessItem, onFinishedAll, false, needsProcessItemDelay);
function needsProcessItemDelay(card, iitem) {
return (!(card.idBoard && alldata.hasNoBoardAccess[card.idBoard]));
}
function onProcessItem(tokenTrello, card, iitem, postProcessItem) {
function callPost(status) {
postProcessItem(status, card, iitem);
}
function callbackCard(cardData) {
if (cardData.status != STATUS_OK) {
callPost(cardData.status);
return;
}
if (!card.dateSzLastTrello)
card.dateSzLastTrello = earliest_trello_date(); //set it to simplify code that assumes cards from trello api always have it set
if (cardData.hasPermission) {
card.idList = cardData.card.idList;
card.idLong = cardData.card.id; //cards that came from db might be missing it
}
else {
card.idList = IDLIST_UNKNOWN;
card.bArchived = true; //not really true but this prevents later attempts at completing card data.
//not setting card.idBoard = IDBOARD_UNKNOWN; //review zig: this would be good for consistency, but may not be a good idea when a card was deleted or loses permission we dont want to lose the board it beloged to
//thus, because of this currently its not always true that a card's list belongs to the same board as the card in the db
if (cardData.bDeleted) {
card.bDeleted = true;
card.bArchived = true;
}
if (!cardData.bForced) {
if (card.idBoard && card.idBoard != IDBOARD_UNKNOWN && !alldata.hasNoBoardAccess[card.idBoard] && !alldata.hasBoardAccessDirect[card.idBoard] && !alldata.hasBoardAccess[card.idBoard]) {
//optimization: check board status so later we dont have to keep checking all board cards
getBoardData(tokenTrello, false, card.idBoard, "fields=dateLastActivity", function (boardData) {
if (!boardData.hasPermission)
alldata.hasNoBoardAccess[card.idBoard] = true;
else
alldata.hasBoardAccess[card.idBoard] = true;
callPost(cardData.status);
});
return;
}
}
}
callPost(cardData.status);
}
assert(card.idLong || card.idCard);
if (!needsProcessItemDelay(card, iitem))
callbackCard({status:STATUS_OK, hasPermission:false, bForced:true}); //optimization
else
getCardData(tokenTrello, card.idLong || card.idCard, "id,idList", false, callbackCard);
}
function onFinishedAll(status) {
sendResponse({ status: status });
}
}
function completeMissingListData(tokenTrello, alldata, sendResponse) {
var listsToFix = [];
var mapHandled = {};
for (var shortLinkCard in alldata.cards) {
var idList=alldata.cards[shortLinkCard].idList;
if (idList == IDLIST_UNKNOWN)
continue;
if (!mapHandled[idList] && !alldata.lists[idList]) {
listsToFix.push({ idList: idList });
mapHandled[idList] = true;
//idBoard: IDBOARD_UNKNOWN is later used to know this one is missing in local db
alldata.lists[idList] = { name: STR_UNKNOWN_LIST, idBoard: IDBOARD_UNKNOWN, dateSzLastTrello: null, bArchived: false, pos:null }; //set a default
}
}
for (var idListMissing in alldata.lists) {
if (mapHandled[idListMissing])
continue;
if (alldata.lists[idListMissing].pos)
continue;
listsToFix.push({ idList: idListMissing });
mapHandled[idListMissing] = true;
}
g_syncStatus.setStage("Completing list details", listsToFix.length);
processThreadedItemsSync(tokenTrello, listsToFix, null, onProcessItem, onFinishedAll);
function onProcessItem(tokenTrello, item, iitem, postProcessItem) {
var idListCur = item.idList;
assert(idListCur);
var listDb = alldata.lists[idListCur];
function finish() {
if (listDb.idBoard != IDBOARD_UNKNOWN && !alldata.hasBoardAccessDirect[listDb.idBoard] && !alldata.hasBoardAccess[listDb.idBoard]) {
if (alldata.hasNoBoardAccess[listDb.idBoard]) {
callbackList({ status: STATUS_OK, hasPermission :false, bForced: true}); //optimize trello calls
return;
}
}
getListData(tokenTrello, idListCur, "name,idBoard,closed,pos", callbackList);
}
if (listDb.idBoard == IDBOARD_UNKNOWN) {
//could be in db. if not, get it with the trello api
getThisListFromDb(alldata, idListCur, function () {
listDb = alldata.lists[idListCur];
if (listDb.idBoard == IDBOARD_UNKNOWN)
finish();
else
callPost(STATUS_OK);
}, function onError(status) {
callPost(status);
});
}
else {
finish();
}
function callPost(status) {
postProcessItem(status, item, iitem);
}
function callbackList(listData) {
if (listData.status != STATUS_OK) {
callPost(listData.status);
return;
}
if (!listDb.dateSzLastTrello)
listDb.dateSzLastTrello = earliest_trello_date(); //fill a valid date. code later is simplified as it expects that it came from an "action"
//note there isnt a "delete list" action, so dont archive it here. different than cards where we assume the card was deleted
if (listData.hasPermission) {
assert(listData.list.name);
listDb.name = listData.list.name;
//note: in the case of upgrading from data without list "pos", we can end up here early without boardsByLong but with a vali idBoard already
listDb.idBoard = listDb.idBoard || alldata.boardsByLong[listData.list.idBoard] || IDBOARD_UNKNOWN;
listDb.bArchived = listData.list.closed || false;
listDb.pos = listData.list.pos || null;
}
else {
listDb.pos = -1; //fake pos. this prevents from continuing to attempt getting pos from lists with "null" pos during upgrade to this pos feature
listDb.bArchived = true; //this might not be really true but prevents certain repeated queries to update the list
if (!listData.bForced && listDb.idBoard && listDb.idBoard != IDBOARD_UNKNOWN && !alldata.hasNoBoardAccess[listDb.idBoard] && !alldata.hasBoardAccessDirect[listDb.idBoard] && !alldata.hasBoardAccess[listDb.idBoard]) {
//optimization: check board status so later we dont have to keep checking all board cards
getBoardData(tokenTrello, false, listDb.idBoard, "fields=dateLastActivity", function (boardData) {
if (!boardData.hasPermission)
alldata.hasNoBoardAccess[listDb.idBoard] = true;
else
alldata.hasBoardAccess[listDb.idBoard] = true;
callPost(listData.status);
});
return;
}
}
callPost(listData.status);
}
}
function onFinishedAll(status) {
sendResponse({ status: status });
}
}
function matchesCardShortLinkFromTrelloWelcomeBoard(shortLink) {
var rg = [
//all cards from both "welcome board" in https://trello.com/examples
//1: https://trello.com/b/bKbdmCKB/welcome-board
"YdSxoGcc",
"XNItoCqd",
"B5h0PIBw",
"tVOKKKJS",
"1FzNqM9E",
"jOERTc2e",
"3MOoOZAk",
"FUKG6oiY",
"3E8uiAEk",
"LrrmgFyd",
"HMWuGKCb",
"kn935e6l",
"TFHJb9F2",
"uoe6rcDL",
"Tek4fCNQ",
"bVlkHq2d",
"JSccv2Cq",
"sfAshneN",
"xa7yvDpA",
//2: https://trello.com/b/HF8XAoZd/welcome-board
"QB1UIzwU",
"TqE553J6",
"rlJzoJEd",
"UlhkFUUd",
"OR0JbMVP",
"ZQK0l0oa",
"AgCyecMP"
];
for (var i = 0; i < rg.length; i++) {
if (rg[i] == shortLink)
return true;
}
return false;
}
function preProcessActionsCaches(tokenTrello, actions, alldata, nextAction) {
for (var i = 0; i < actions.length; i++) {
var action = actions[i];
var card = action.data.card;
if (card && card.shortLink) {
if (matchesCardShortLinkFromTrelloWelcomeBoard(card.shortLink))
card.shortLink = undefined; //trello bug. see note below.
else
alldata.cardsByLong[card.id] = card.shortLink; //populate cache. needed later for cards missing shortLink
}
function preProcessBoardSourceTarget(board) {
if (board) {
var shortLink = alldata.boardsByLong[board.id];
if (!shortLink) {
//set temporarily to unknown. Might remain unknown if we dont recover it from later history
alldata.boardsByLong[board.id] = IDBOARD_UNKNOWN;
}
}
}
preProcessBoardSourceTarget(action.data.boardSource);
preProcessBoardSourceTarget(action.data.boardTarget);
var board = action.data.board;
if (board) {
//in .com.pe https://mail.google.com/mail/ca/u/0/#apps/to%3Asupport%40trello.com+shortlink/148d1f65e49605b2
//NOTE: confirmed trello bug where board.shortLink != action.idBoardSrc
//Ive seen it happen on a customer, where an updateList action had board.shortLink be the trello welcome board, but idBoardSrc was the copy that trello makes.
//WARNING: this means that code elsewhere cant trust board.shortLink unless it came from the db :(
//there is code that currently identifies cards from trello sample boards, where this often happens, to ignore those shortLinks
if (board.shortLink && board.shortLink != action.idBoardSrc) {
console.log("Plus unusual: board.shortLink != action.idBoardSrc. shortLink:" + board.shortLink + " idBoardSrc:" + action.idBoardSrc+" .Full action:");
console.log(JSON.stringify(action, undefined, 4));
}
var shortLink=alldata.boardsByLong[board.id];
if (!shortLink || shortLink == IDBOARD_UNKNOWN)
alldata.boardsByLong[board.id] = action.idBoardSrc;//dont use board.shortLink, could be incorrect (see note above)
}
}
getAllItemsFromDb(actions, alldata, getAllMissingCardShortlinks);
function getAllMissingCardShortlinks(status) {
if (status != STATUS_OK) {
nextAction(status);
return;
}
var cardIds = listMissingCardShortlinks(actions, alldata);
var cardsIgnore = {}; //cardsIgnore[idCardLong] true. review zig: doesnt seem necessary as cardIds has unique values
g_syncStatus.setStage("Completing card details", cardIds.length);
processThreadedItemsSync(tokenTrello, cardIds, null, onProcessItem, nextAction);
function onProcessItem(tokenTrello, item, iitem, postProcessItem) {
var idLong = item.idLong;
if (cardsIgnore[idLong])
callPost(STATUS_OK);
else
getCardData(tokenTrello, idLong, "shortLink", false, callbackCard);
function callPost(status) {
postProcessItem(status, item, iitem);
}
function callbackCard(cardData) {
if (cardData.status != STATUS_OK) {
callPost(cardData.status);
return;
}
if (!cardData.hasPermission || cardData.bDeleted) {
cardsIgnore[idLong] = true;
callPost(cardData.status);
return;
}
alldata.cardsByLong[idLong] = cardData.card.shortLink;
var cardsNotFound = {};
populateDataCardFromDb(cardsNotFound, alldata, cardData.card, callPost); //there might be new cards now that we have the shortLink
}
}
}
}
function listMissingCardShortlinks(actions, alldata) {
var cardIds = [];
var mapHandled = {};
for (var i = 0; i < actions.length; i++) {
var action = actions[i];
if (action.ignore)
continue;
var card = action.data.card;
if (!card || card.shortLink || mapHandled[card.id])
continue;
mapHandled[card.id] = true;
if (alldata.cardsByLong[card.id])
continue;
cardIds.push({ idLong: card.id });
}
return cardIds;
}
function getAllItemsFromDb(actions, alldata, sendStatus) {
var iAction = -1;
var cardsNotFound = {};
g_syncStatus.setStage("Pre-processing history", actions.length);
nextAction(STATUS_OK);
function nextAction(status) {
iAction++;
if (status != STATUS_OK) {
sendStatus(status);
return;
}
g_syncStatus.cProcessed = iAction;
if ((iAction % 500) == 0)
updatePlusIcon(true);
if (iAction == actions.length) {
sendStatus(STATUS_OK);
return;
}
var action = actions[iAction];
var card = action.data.card;
var bCheckMaxCallstack = checkMaxCallStack(iAction);
if (card) {
populateDataCardFromDb(cardsNotFound, alldata, card, nextAction, bCheckMaxCallstack);
}
else {
if (bCheckMaxCallstack) { //reduce long callstacks. must be large else is slow in canary
setTimeout(function () {
nextAction(STATUS_OK);
}); //undefined timeout is faster and still clears callstack
}
else
nextAction(STATUS_OK);
}
}
}
function populateDataCardFromDb(cardsNotFound, alldata, card, sendStatus, bAsync) {
assert(card);
var idShortCard = card.shortLink;
var idLongCard = card.id;
var cardDb = null;
function earlyFinish() {
if (bAsync) {
setTimeout(function () {
sendStatus(STATUS_OK);
});
}
else
sendStatus(STATUS_OK);
}
assert(idLongCard);
if (cardsNotFound[idLongCard]) {
earlyFinish();
return;
}
if (idShortCard)
cardDb = alldata.cards[idShortCard];
else {
assert(idLongCard);
idShortCard = alldata.cardsByLong[idLongCard];
if (idShortCard)
cardDb = alldata.cards[idShortCard];
}
if (cardDb) {
earlyFinish();
return;
}
var request = { sql: SQLQUERY_PREFIX_CARDDATA+"FROM CARDS where (idCard=? OR idLong=?)", values: [idShortCard, idLongCard] };
handleGetReport(request,
function (responseReport) {
if (responseReport.status != STATUS_OK) {
sendStatus(responseReport.status);
return;
}
if (responseReport.rows.length > 0) {
if (responseReport.rows.length != 1) {