This repository has been archived by the owner on Jan 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
bzdeck.js
1910 lines (1518 loc) · 52.6 KB
/
bzdeck.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
/**
* BzDeck Application Logic
* Copyright © 2014 Kohei Yoshino. All rights reserved.
*/
'use strict';
let BzDeck = BzDeck || {};
/* ----------------------------------------------------------------------------------------------
* Data
* ---------------------------------------------------------------------------------------------- */
BzDeck.data = {};
/* ----------------------------------------------------------------------------------------------
* Options
* ---------------------------------------------------------------------------------------------- */
BzDeck.options = {
api: {
endpoints: {
rest: 'https://api-dev.bugzilla.mozilla.org/latest/',
websocket: 'ws://bugzfeed.mozilla.org/'
},
extra_fields: [
'attachments', 'blocks', 'cc', 'comments', 'depends_on', 'dupe_of', 'flags', 'groups',
'history', 'is_cc_accessible', 'is_confirmed', 'is_creator_accessible', 'see_also',
'update_token'
]
},
app: {
manifest: location.origin + '/manifest.webapp'
},
grid: {
default_columns: [
// Custom
{ id: '_starred', type: 'boolean' },
{ id: '_unread', type: 'boolean', hidden: true },
// Name
{ id: 'id', type: 'integer' },
{ id: 'alias', hidden: true },
{ id: 'summary' },
// Status
{ id: 'status', hidden: true },
{ id: 'resolution', hidden: true },
{ id: 'target_milestone', hidden: true },
// Affected
{ id: 'classification', hidden: true },
{ id: 'product' },
{ id: 'component' },
{ id: 'version', hidden: true },
{ id: 'platform', hidden: true },
{ id: 'op_sys', hidden: true },
// Importance
{ id: 'severity', hidden: true },
{ id: 'priority', hidden: true },
// Notes
{ id: 'whiteboard', hidden: true },
{ id: 'keywords', hidden: true },
{ id: 'url', hidden: true },
// People
{ id: 'creator', type: 'person', hidden: true },
{ id: 'assigned_to', type: 'person', hidden: true },
{ id: 'qa_contact', type: 'person', hidden: true },
// Dates
{ id: 'creation_time', type: 'time', hidden: true },
{ id: 'last_change_time', type: 'time' },
]
}
};
/* ----------------------------------------------------------------------------------------------
* Bootstrap
* ---------------------------------------------------------------------------------------------- */
BzDeck.bootstrap = {};
BzDeck.bootstrap.start = function () {
this.$form = document.querySelector('#app-login form');
this.$input = this.$form.querySelector('[role="textbox"]');
this.$button = this.$form.querySelector('[role="button"]');
BzDeck.global.$statusbar = document.querySelector('#app-login [role="status"]');
this.open_database();
};
BzDeck.bootstrap.open_database = function () {
let req = indexedDB.open('BzDeck'); // Version 1
req.addEventListener('error', event => {
BzDeck.global.show_status('ERROR: Cannot open the database.'); // l10n
});
// The database is created or upgraded
req.addEventListener('upgradeneeded', event => {
let db = BzDeck.model.db = event.target.result,
stores = {
// Bugzilla data
bugs: { keyPath: 'id' },
attachments: { keyPath: 'id' },
users: { keyPath: 'id' },
bugzilla: { keyPath: 'key' },
// BzDeck data
accounts: { keyPath: 'id' }, // the key is Bugzilla account ID
subscriptions: { keyPath: 'id' },
prefs: { keyPath: 'key' }
};
for (let [name, option] of Iterator(stores)) if (!db.objectStoreNames.contains(name)) {
db.createObjectStore(name, option);
}
});
req.addEventListener('success', event => {
BzDeck.model.db = event.target.result;
this.load_config();
this.load_account();
this.load_prefs();
});
};
BzDeck.bootstrap.load_config = function () {
BzDeck.model.db.transaction('bugzilla').objectStore('bugzilla').get('config')
.addEventListener('success', event => {
let result = event.target.result;
if (result) {
// Cache found
BzDeck.data.bugzilla_config = result.value;
return;
}
if (!navigator.onLine) {
// Offline; give up
BzDeck.global.show_status('You have to go online to load data.'); // l10n
return;
}
// Load the Bugzilla config in background
BzDeck.core.request('GET', 'configuration', new URLSearchParams('cached_ok=1'), null, data => {
if (!data || !data.version) {
// Give up
BzDeck.global.show_status('ERROR: Bugzilla configuration could not be loaded. \
The instance might be offline.'); // l10n
this.$input.disabled = this.$button.disabled = true;
return;
}
// The config is loaded successfully
BzDeck.data.bugzilla_config = data;
BzDeck.model.db.transaction('bugzilla', 'readwrite').objectStore('bugzilla')
.add({ key: 'config', value: data });
});
});
};
BzDeck.bootstrap.load_account = function () {
BzDeck.model.db.transaction('accounts').objectStore('accounts').openCursor()
.addEventListener('success', event => {
let cursor = event.target.result;
if (cursor) {
// Cache found (the first entry)
BzDeck.data.account = cursor.value;
BzDeck.core.load_subscriptions();
return;
}
this.show_login_form();
});
};
BzDeck.bootstrap.load_prefs = function () {
let db = BzDeck.model.db,
prefs = {};
db.transaction('prefs').objectStore('prefs').mozGetAll()
.addEventListener('success', event => {
for (let { key, value } of event.target.result) {
prefs[key] = value;
}
BzDeck.data.prefs = new Proxy(prefs, {
set: (obj, key, value) => {
obj[key] = value;
db.transaction('prefs', 'readwrite').objectStore('prefs').put({ key: key, value: value });
}
});
});
};
BzDeck.bootstrap.show_login_form = function (firstrun = true) {
this.$form.setAttribute('aria-hidden', 'false');
this.$input.disabled = this.$button.disabled = false;
this.$input.focus();
if (!firstrun) {
return;
}
this.$form.addEventListener('submit', event => {
if (!this.processing) {
// User is trying to re-login
this.relogin = true;
this.processing = true;
}
navigator.onLine ? this.validate_account()
: BzDeck.global.show_status('You have to go online to sign in.'); // l10n
event.preventDefault();
return false;
});
BzDeck.global.show_status('');
};
BzDeck.bootstrap.validate_account = function () {
BzDeck.global.show_status('Confirming account...'); // l10n
this.$input.disabled = this.$button.disabled = true;
BzDeck.core.request('GET', 'user/' + encodeURIComponent(this.$input.value), null, null, data => {
let status;
if (!data) {
// Network error?
status = 'ERROR: Failed to sign in.'; // l10n
}
if (data.error || !data.name) {
// User not found
status = 'ERROR: ' + (data.message || 'The user could not be found. \
Please check your email adress and try again.'); // l10n
}
if (status) {
BzDeck.global.show_status(status); // l10n
this.$input.disabled = this.$button.disabled = false;
return;
}
// User found, now load his/her data
BzDeck.data.account = data;
BzDeck.model.db.transaction('accounts', 'readwrite').objectStore('accounts').add(data);
BzDeck.core.load_subscriptions();
});
};
BzDeck.bootstrap.setup_ui = function () {
if (this.relogin) {
// UI has already been set up, skip this process
this.finish();
return;
}
BzDeck.global.show_status('Loading UI...'); // l10n
let datetime = FlareTail.util.datetime,
prefs = BzDeck.data.prefs,
theme = prefs['ui.theme.selected'],
FTut = FlareTail.util.theme,
$root = document.documentElement;
// Automatically update relative dates on the app
datetime.options.updater_enabled = true;
// Date format
{
let value = prefs['ui.date.relative'];
datetime.options.relative = value !== undefined ? value : true;
}
// Date timezone
{
let value = prefs['ui.date.timezone'];
datetime.options.timezone = value || 'local';
}
// Timeline: Font
{
let value = prefs['ui.timeline.font.family'];
$root.setAttribute('data-timeline-font-family', value || 'proportional');
}
// Timeline: Sort order
{
let value = prefs['ui.timeline.sort.order'];
$root.setAttribute('data-timeline-sort-order', value || 'ascending');
}
// Timeline: Changes
{
let value = prefs['ui.timeline.show_cc_changes'];
$root.setAttribute('data-timeline-show-cc-changes', value !== undefined ? value : false);
}
// Timeline: Attachments
{
let value = prefs['ui.timeline.display_attachments_inline'];
$root.setAttribute('data-timeline-display-attachments-inline', value !== undefined ? value : true);
}
// Activate widgets
BzDeck.homepage = new BzDeck.HomePage();
BzDeck.toolbar.setup();
BzDeck.sidebar.setup();
BzDeck.DetailsPage.swipe.init();
// Check the requested URL to open the specific folder or tab if needed
FlareTail.util.event.dispatch(window, 'popstate');
// Change the theme
if (theme && FTut.list.contains(theme)) {
FTut.selected = theme;
}
// Preload images from CSS
FTut.preload_images(() => {});
// Authorize a notification
FlareTail.util.app.auth_notification();
// Update UI & Show a notification
BzDeck.core.toggle_unread_ui(true);
window.addEventListener('UI:toggle_unread', event => {
let bugs = [...event.detail.bugs];
if ($root.getAttribute('data-current-tab') === 'home') {
let unread_num = [for (bug of BzDeck.homepage.data.bug_list) if (bug._unread) bug].length;
BzDeck.homepage.change_window_title(
document.title.replace(/(\s\(\d+\))?$/, unread_num ? ' (' + unread_num + ')' : '')
);
}
if (!event.detail.loaded) {
return;
}
if (bugs.length === 0) {
BzDeck.global.show_status('No new bugs to download'); // l10n
return;
}
bugs.sort((a, b) => new Date(b.last_change_time) - new Date(a.last_change_time));
let status = bugs.length > 1 ? 'You have %d unread bugs'.replace('%d', bugs.length)
: 'You have 1 unread bug', // l10n
extract = [for (bug of bugs.slice(0, 3)) bug.id + ' - ' + bug.summary].join('\n');
BzDeck.global.show_status(status);
BzDeck.global.show_notification(status, extract);
});
// Notify requests
BzDeck.model.get_subscription_by_id('requests', sub => {
let len = sub.bugs.length;
if (!len) {
return;
}
let title = len > 1 ? 'You have %d requests'.replace('%d', len)
: 'You have 1 request'; // l10n
let body = len > 1 ? 'Select the Requests folder to browse those bugs.'
: 'Select the Requests folder to browse the bug.'; // l10n
// TODO: Improve the notification body to describe more about the requests,
// e.g. There are 2 bugs awaiting your information, 3 patches awaiting your review.
BzDeck.global.show_notification(title, body, event => {
// Select the Requests folder when the notification is clicked
$root.setAttribute('data-current-tab', 'home');
BzDeck.toolbar.tablist.view.selected = document.querySelector('#tab-home');
BzDeck.sidebar.folders.view.selected = document.querySelector('#sidebar-folders--requests');
});
});
this.finish();
};
BzDeck.bootstrap.finish = function () {
// Timer to check for updates
BzDeck.core.timers.load_subscriptions = window.setInterval(() => {
BzDeck.core.load_subscriptions();
}, 600000); // Call every 10 minutes
// Register the app for an activity on Firefox OS
BzDeck.global.register_activity_handler();
// Connect to the push notification server
BzDeck.bugzfeed.connect();
BzDeck.global.show_status('Loading complete.'); // l10n
BzDeck.session.login();
this.processing = false;
};
/* ----------------------------------------------------------------------------------------------
* Core
* ---------------------------------------------------------------------------------------------- */
BzDeck.core = {};
BzDeck.core.timers = {};
BzDeck.core.load_subscriptions = function () {
this.firstrun = false;
BzDeck.global.show_status('Checking for new bugs...'); // l10n
BzDeck.model.get_all_subscriptions(subscriptions => {
let email = BzDeck.data.account.name,
_query = { email1: email, email1_type: 'equals_any', resolution: '---' },
fields = { cc: 'cc', reported: 'creator', assigned: 'assigned_to', qa: 'qa_contact' },
requests_sub = { id: 'requests', query: { quicksearch: 'requestee:' + email }};
if (subscriptions.length) {
BzDeck.model.get_all_bugs(bugs => {
// List all starred bugs to check the last modified dates
let ids = [for (bug of bugs) if (bug._starred) bug.id];
if (ids.length) {
subscriptions.push({ query: { id: ids.join() } });
}
// [Migration] Remove Need Info
{
let index = [for (sub of subscriptions) sub.id].indexOf('needinfo');
if (index > -1) {
subscriptions.splice(index, 1);
}
}
// [Migration] Add Request Queue
{
let index = [for (sub of subscriptions) sub.id].indexOf('requests');
if (index === -1) {
subscriptions.push(requests_sub);
}
}
this.fetch_subscriptions(subscriptions);
});
// Hide the app intro copy from existing users
document.querySelector('#app-intro').style.display = 'none';
return;
}
this.firstrun = true;
// No cache available; try to create the default store
if (!navigator.onLine) {
// Offline; give up
BzDeck.global.show_status('You have to go online to load data.'); // l10n
return;
}
for (let [name, field] of Iterator(fields)) {
let query = FlareTail.util.object.clone(_query);
query['email1_' + field] = 1;
subscriptions.push({ id: name, query: query });
}
subscriptions.push(requests_sub);
this.fetch_subscriptions(subscriptions);
});
};
BzDeck.core.fetch_subscriptions = function (subscriptions) {
if (!navigator.onLine) {
// Skip loading the latest subscription data
this.load_bugs(subscriptions);
return;
}
let _fetch = sub => new Promise((resolve, reject) => {
let params = new URLSearchParams();
for (let [key, value] of Iterator(sub.query)) {
params.append(key, value);
}
params.append('include_fields', 'id,last_change_time');
this.request('GET', 'bug', params, null, data => {
if (!data || !Array.isArray(data.bugs)) {
reject(new Error('No data'));
return;
}
sub.bugs = data.bugs;
resolve(sub);
});
});
// Load bug list from Bugzilla
Promise.all([for (sub of subscriptions) _fetch(sub)]).then(subscriptions => {
BzDeck.model.save_subscriptions(subscriptions);
this.load_bugs(subscriptions);
}).catch(error => {
BzDeck.global.show_status('ERROR: Failed to load data.'); // l10n
});
};
BzDeck.core.load_bugs = function (subscriptions) {
let boot = BzDeck.bootstrap.processing,
cached_time = {},
requesting_bugs = new Map();
BzDeck.global.show_status('Loading bugs...'); // l10n
// Step 1: look for bugs in the local storage
let _get = () => {
BzDeck.model.get_all_bugs(bugs => {
for (let bug of bugs) {
cached_time[bug.id] = bug.last_change_time;
}
if (Object.keys(cached_time).length > 0) {
if (navigator.onLine) {
_list();
} else if (boot) {
// Skip loading the latest bug data
BzDeck.bootstrap.setup_ui();
}
return;
}
if (!navigator.onLine) {
// Offline; give up
BzDeck.global.show_status('You have to go online to load data.'); // l10n
}
// No cache available; try to retrieve bugs anyway
_list();
});
};
// Step 2: determine which bugs should be loaded from Bugzilla
let _list = () => {
for (let sub of subscriptions) {
for (let bug of sub.bugs) {
let cache = cached_time[bug.id];
if (!cache || bug.last_change_time > cache) {
requesting_bugs.set(bug.id, bug);
}
}
}
if (requesting_bugs.size > 0) {
_retrieve();
} else if (boot) {
BzDeck.bootstrap.setup_ui();
} else {
BzDeck.global.show_status('No new bugs to download'); // l10n
}
};
let opt = BzDeck.options,
default_fields = opt.api.default_fields
= [for (column of opt.grid.default_columns)
if (!column.id.startsWith('_')) column.id],
extra_fields = opt.api.extra_fields,
params = new URLSearchParams(),
ignore_cc_changes = BzDeck.data.prefs['notifications.ignore_cc_changes'] !== false;
// Fetch only the default fields for firstrun to load faster
params.append('include_fields', this.firstrun ? default_fields.join()
: [...default_fields, ...extra_fields].join());
// Step 3: load the listed bugs from Bugzilla
let _retrieve = () => {
let _fetch = bug_ids => new Promise((resolve, reject) => {
let _params = new URLSearchParams(params);
_params.append('id', bug_ids.join());
this.request('GET', 'bug', _params, null, data => {
if (!data || !Array.isArray(data.bugs)) {
reject(new Error('No data'));
return;
}
for (let bug of data.bugs) {
if (this.firstrun) {
bug._unread = false; // Mark all bugs read if the session is firstrun
bug._update_needed = true; // Flag to update details
continue;
}
let cache = requesting_bugs.get(bug.id);
bug._starred = cache._starred || false; // Copy the annotation
bug._update_needed = false;
// Mark the bug unread if the user subscribes CC changes or the bug is already unread
if (!ignore_cc_changes || cache._unread || !cache._last_viewed) {
bug._unread = true;
continue;
}
// Mark the bug unread if there are unread comments
if ([for (c of bug.comments) if (c.creation_time > cache.last_change_time) c].length) {
bug._unread = true;
continue;
}
// Mark the bug unread if there are unread attachments
if (bug.attachments &&
[for (a of bug.attachments) if (a.creation_time > cache.last_change_time) a].length) {
bug._unread = true;
continue;
}
// Mark the bug unread if there are unread non-CC changes
if (bug.history &&
[for (h of bug.history) if (history.change_time > cache.last_change_time &&
[for (c of history.changes) if (c.field_name !== 'cc') c].length) h].length) {
bug._unread = true;
continue;
}
// Looks like there are only CC changes, so mark the bug read
bug._unread = false;
}
resolve(data.bugs);
});
});
let bug_ids = [...requesting_bugs.keys()],
bug_ids_chunk = [];
// Load 50 bugs each
while (bug_ids.length) {
bug_ids_chunk.push(_fetch(bug_ids.splice(0, 50)));
}
Promise.all(bug_ids_chunk).then(bug_arrays => {
// Finally load the UI modules
if (boot) {
BzDeck.model.save_bugs(Array.concat(...bug_arrays), bugs => {
BzDeck.bootstrap.setup_ui();
});
}
}).catch(error => {
BzDeck.global.show_status('ERROR: Failed to load data.'); // l10n
});
};
// Start processing
_get();
};
BzDeck.core.load_bug_details = function (ids, callback = null) {
let params = new URLSearchParams();
params.append('id', ids.join());
params.append('include_fields', 'id,' + BzDeck.options.api.extra_fields.join());
params.append('exclude_fields', 'attachments.data');
this.request('GET', 'bug', params, null, data => {
if (!data) {
// Give up
BzDeck.global.show_status('ERROR: Failed to load data.'); // l10n
return;
}
for (let _bug of data.bugs) {
BzDeck.model.get_bug_by_id(_bug.id, bug => {
for (let [field, value] of Iterator(_bug)) {
bug[field] = value;
}
bug._update_needed = false;
BzDeck.model.save_bug(bug);
if (callback) {
callback(bug);
}
});
}
});
};
BzDeck.core.toggle_star = function (id, value) {
// Save in DB
BzDeck.model.get_bug_by_id(id, bug => {
if (bug) {
bug._starred = value;
BzDeck.model.save_bug(bug);
this.toggle_star_ui();
}
});
};
BzDeck.core.toggle_star_ui = function () {
BzDeck.model.get_all_bugs(bugs => {
FlareTail.util.event.dispatch(window, 'UI:toggle_star', { detail: {
bugs: new Set([for (bug of bugs) if (bug._starred) bug]),
ids: new Set([for (bug of bugs) if (bug._starred) bug.id])
}});
});
};
BzDeck.core.toggle_unread = function (id, value) {
// Save in DB
BzDeck.model.get_bug_by_id(id, bug => {
if (bug && bug._unread !== value) {
bug._unread = value;
BzDeck.model.save_bug(bug);
this.toggle_unread_ui();
}
});
};
BzDeck.core.toggle_unread_ui = function (loaded = false) {
BzDeck.model.get_all_bugs(bugs => {
FlareTail.util.event.dispatch(window, 'UI:toggle_unread', { detail: {
loaded: loaded,
bugs: new Set([for (bug of bugs) if (bug._unread) bug]),
ids: new Set([for (bug of bugs) if (bug._unread) bug.id])
}});
});
};
BzDeck.core.request = function (method, path, params, data, callback, auth = false) {
if (!navigator.onLine) {
BzDeck.global.show_status('You have to go online to load data.'); // l10n
return;
}
let xhr = new XMLHttpRequest(),
url = new URL(BzDeck.options.api.endpoints.rest);
params = params || new URLSearchParams();
if (auth) {
params.append('userid', BzDeck.data.account.id);
params.append('cookie', BzDeck.data.account.token);
}
url.pathname += path;
url.searchParams = params;
xhr.open(method, url.toString(), true);
xhr.setRequestHeader('Accept', 'application/json');
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.addEventListener('load', event => {
let text = event.target.responseText;
callback(text ? JSON.parse(text) : null);
});
xhr.addEventListener('error', event => {
callback(null);
});
xhr.send(data);
};
/* ----------------------------------------------------------------------------------------------
* Model
* ---------------------------------------------------------------------------------------------- */
BzDeck.model = {};
BzDeck.model.cache = {};
BzDeck.model.get_bug_by_id = function (id, callback, record_time = true) {
let cache = this.cache.bugs,
store = this.db.transaction('bugs', 'readwrite').objectStore('bugs');
if (cache) {
let bug = cache.get(id);
if (bug) {
callback(bug);
if (record_time) {
bug._last_viewed = Date.now();
cache.set(id, bug);
store.put(bug);
}
return;
}
}
store.get(id).addEventListener('success', event => {
let bug = event.target.result;
callback(bug);
if (bug && record_time) {
bug._last_viewed = Date.now();
if (cache) {
cache.set(id, bug);
}
store.put(bug); // Save
}
});
};
BzDeck.model.get_bugs_by_ids = function (ids, callback) {
let cache = this.cache.bugs,
ids = [...ids]; // Accept both an Array and a Set as the first argument
if (cache) {
callback([for (c of [...cache]) if (ids.indexOf(c[0]) > -1) c[1]]);
return;
}
this.db.transaction('bugs').objectStore('bugs')
.mozGetAll().addEventListener('success', event => {
callback([for (bug of event.target.result) if (ids.indexOf(bug.id) > -1) bug]);
});
};
BzDeck.model.get_all_bugs = function (callback) {
let cache = this.cache.bugs;
if (cache) {
callback([for (c of [...cache]) c[1]]); // Convert Map to Array
return;
}
this.db.transaction('bugs').objectStore('bugs')
.mozGetAll().addEventListener('success', event => {
let bugs = event.target.result; // array of Bug
callback(bugs);
if (bugs && !cache) {
this.cache.bugs = new Map([for (bug of bugs) [bug.id, bug]]);
}
});
};
BzDeck.model.save_bug = function (bug, callback) {
this.save_bugs([bug], callback);
};
BzDeck.model.save_bugs = function (bugs, callback = () => {}) {
let cache = this.cache.bugs,
transaction = this.db.transaction('bugs', 'readwrite'),
store = transaction.objectStore('bugs');
transaction.addEventListener('complete', () => {
callback(bugs);
});
if (!cache) {
cache = this.cache.bugs = new Map();
}
for (let bug of bugs) if (bug.id) {
cache.set(bug.id, bug);
store.put(bug);
}
};
BzDeck.model.fetch_bugs_by_ids = function (ids, callback) {
let params = new URLSearchParams();
if (![...ids].length) {
return;
}
params.append('id', [...ids].join());
params.append('include_fields', BzDeck.options.api.default_fields.join());
BzDeck.core.request('GET', 'bug', params, null, data => {
if (data && Array.isArray(data.bugs)) {
this.save_bugs(data.bugs);
callback(data.bugs);
} else {
callback([]);
}
});
};
BzDeck.model.get_subscription_by_id = function (id, callback) {
let cache = this.cache.subscriptions;
if (cache) {
callback(cache.get(id));
return;
}
this.db.transaction('subscriptions').objectStore('subscriptions').get(id)
.addEventListener('success', event => {
callback(event.target.result);
});
};
BzDeck.model.get_all_subscriptions = function (callback) {
let cache = this.cache.subscriptions;
if (cache) {
callback([for (c of [...cache]) c[1]]); // Convert Map to Array
return;
}
this.db.transaction('subscriptions').objectStore('subscriptions').mozGetAll()
.addEventListener('success', event => {
callback(event.target.result);
});
};
BzDeck.model.save_subscriptions = function (subscriptions) {
let store = this.db.transaction('subscriptions', 'readwrite').objectStore('subscriptions'),
cache = this.cache.subscriptions;
if (!cache) {
cache = this.cache.subscriptions = new Map();
}
for (let sub of subscriptions) if (sub.id) {
store.put(sub);
cache.set(sub.id, sub);
}
};
/* ----------------------------------------------------------------------------------------------
* Session
* ---------------------------------------------------------------------------------------------- */
BzDeck.session = {};
BzDeck.session.login = function () {
let $app_login = document.querySelector('#app-login'),
$app_body = document.querySelector('#app-body');
BzDeck.global.$statusbar = document.querySelector('#statusbar');
$app_login.setAttribute('aria-hidden', 'true');
$app_body.removeAttribute('aria-hidden');
// TODO: focus handling
// GA
if (_gaq) {
_gaq.push(['_trackEvent', 'Session', 'Login'], ['_setCustomVar', 1, 'Login', 'true', 2]);
}
};
BzDeck.session.logout = function () {
let $app_login = document.querySelector('#app-login'),
$app_body = document.querySelector('#app-body');
BzDeck.global.$statusbar = $app_login.querySelector('[role="status"]');
BzDeck.global.show_status('You have logged out.'); // l10n
$app_login.removeAttribute('aria-hidden');
$app_body.setAttribute('aria-hidden', 'true');
BzDeck.bootstrap.show_login_form(false);
// Terminate timers
for (let [key, timer] of Iterator(BzDeck.core.timers)) {
window.clearInterval(timer);
}
// Delete the account data