about summary refs log tree commit diff stats
path: root/src/app.ts
blob: a446ea3aee67411e70d3f92ddcdb8db7f526822f (plain) (blame)
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
'use strict';

class Cookie {

    /**
     * Set a cookie.
     * @param name - The cookie name.
     * @param value - The cookie value.
     * @param lifetime - Lifetime in seconds.
     */
    static set(name: string, value: string | number | boolean, lifetime: number): void {
        const d = new Date();
        d.setTime(d.getTime() + lifetime * 1000);
        const expires = "expires=" + d.toUTCString();
        document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires;
    }

    /**
     * Get a cookie value by name.
     * @param name - The cookie name.
     */
    static get(name: string): string {
        name = name + "=";
        const ca = document.cookie.split(';');
        for (let i=0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length));
        }
        return "";
    }

    /**
     * Delete a cookie by name.
     * @param name - The cookie name.
     */
    static delete(name: string): void {
        const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT";
        document.cookie = name + "=; " + expires;
    }
}

class AppCommon {
    /**
     * Extract a URL query parameter.
     * @param name - The parameter name.
     */
    urlParam(name: string): string{
        try {
            const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
            if (!results) return "";
            return decodeURIComponent(results[1].replace(/\+/g, " ")) || "";
        } catch (e) {
            return "";
        }
    }

    isOnline() {
        if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined")
            return EpubeApp.isOnline();
        else
            return navigator.onLine;
    }

    async getActiveCacheName(timeoutMs = 1000) {
        const registration = await navigator.serviceWorker.ready;
        const worker = registration.active;

        // Fast exit if no worker is active
        if (!worker) return null;

        return new Promise<string | null>((resolve, reject) => {
            const channel = new MessageChannel();
            let timeoutId = -1;

            channel.port1.onmessage = (event) => {
                clearTimeout(timeoutId); // Clean up the timeout
                resolve(event.data?.cacheName || null);
            };

            // 1. Set a timeout so it never gets stuck forever
            timeoutId = window.setTimeout(() => {
                channel.port1.onmessage = null; // Clean up listener
                console.warn('Service worker did not respond to GET_CACHE_NAME');
                resolve(null);
            }, timeoutMs);

            // 2. Send the message and transfer the port
            worker.postMessage({ type: 'GET_CACHE_NAME' }, [channel.port2]);
        });
    }

    async getActiveCacheVersion(timeoutMs = 1000) {
        const registration = await navigator.serviceWorker.ready;
        const worker = registration.active;

        // Fast exit if no worker is active
        if (!worker) return null;

        return new Promise<string | null>((resolve, reject) => {
            const channel = new MessageChannel();
            let timeoutId = -1;

            channel.port1.onmessage = (event) => {
                clearTimeout(timeoutId); // Clean up the timeout
                resolve(event.data?.cacheName || null);
            };

            // 1. Set a timeout so it never gets stuck forever
            timeoutId = window.setTimeout(() => {
                channel.port1.onmessage = null; // Clean up listener
                console.warn('Service worker did not respond to GET_CACHE_VERSION');
                resolve(null);
            }, timeoutMs);

            // 2. Send the message and transfer the port
            worker.postMessage({ type: 'GET_CACHE_VERSION' }, [channel.port2]);
        });
    }

    initNightMode() {
        if (typeof EpubeApp != "undefined") {
            this.applyNightMode(EpubeApp.isNightMode());
            return;
        }

        if (window.matchMedia) {
            const mql = window.matchMedia('(prefers-color-scheme: dark)');

            mql.addEventListener("change", () => {
                this.applyNightMode(mql.matches);
            });

            this.applyNightMode(mql.matches);
        }
    }

    /** Apply night/dark mode styling. */
    applyNightMode(is_night: boolean): void {
        console.log("night mode changed to", is_night);

        $("#theme_css").attr("href",
            "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css"));
    }

    /** htmlspecialchars()-alike for headlines data-content attribute. */
    escapeHtml(p: string | number | boolean): string {
        if (p === null || p === undefined) {
            return '';
        }

        if (typeof p !== "string") {
            return String(p);
        } else {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                '/': '&#x2F;',
                "'": '&#039;',
                '`': '&#x60;'
            };

            return p.replace(/[&<>"'`/]/g, function(m) { return map[m]; });
        }
    }
}

class AppClass extends AppCommon {
    _dl_progress_timeout: number = -1;

    index_mode: string = "";
    index_query: string = "";
    index_offset: number = 0;

    cached_urls: string[] = [];

    cacheVersion = BUILD_CACHE_VERSION as string;
    cosmeticVersion = BUILD_VERSION as string;
    csrf_token: string = "";

    async init(): Promise<void> {
        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());

        // Read URL params for mode/query/offset
        // Whitelist known modes: never let an arbitrary URL value flow into
        // generated hrefs or backend requests (DOM XSS hardening).
        this.index_mode = this.urlParam("mode") === "favorites" ? "favorites" : "";
        this.index_query = this.urlParam("query") || "";
        const offsetParam = parseInt(this.urlParam("offset"));
        this.index_offset = isNaN(offsetParam) ? 0 : offsetParam;

        // Update navbar active states
        if (this.index_mode === "favorites") {
            $(".index_favorites").addClass("active");
            $(".download_all_link").show();
            $(".logout_link").hide();
        } else {
            $(".index_all").addClass("active");
            $(".download_all_link").hide();
        }

        $(".search_query").val(this.index_query);

        // Auth check: call backend with a minimal request; 401 means unauthorized
        try {
            const checkParams = new URLSearchParams({op: "list", limit: "1"});
            await Http.get("backend.php?" + checkParams.toString());
            // If we get here without error, we're authenticated
        } catch (e) {
            const err = e as HttpError;
            // 401 Unauthorized — redirect to login
            if ((err as any).status === 401) {
                window.location.href = "login.php";
                return;
            }
            throw e;
        }

        this.csrf_token = Cookie.get('epube_csrf_token');

        Http.setCsrfToken(this.csrf_token);

        if (typeof EpubeApp != "undefined") {
            $(".navbar").hide();
            $(".epube-app-filler").show();
            $(".separate-search").show();
            $("body").addClass("is-epube-app");

            if (this.index_mode == "favorites")
                EpubeApp.setPage("PAGE_FAVORITES");
            else
                EpubeApp.setPage("PAGE_LIBRARY");
        }

        this.initNightMode();
        this.initCommonEventHandlers();

        this.populateList();

        if ('serviceWorker' in navigator) {
            this.showCovers();
            this.updateOfflinePrompts();
        } else {
            $(".container-main")
                .addClass("alert alert-danger")
                .html("Service worker support missing in browser (are you using plain HTTP?).");
        }
    }

    initCommonEventHandlers() {
        $(".remove_all_downloads").on('click', () => {
            this.removeAll();
        });

        $(".remove_read_downloads").on('click', () => {
            this.removeRead();
        });

        $(".logout_link").on('click', () => {
            this.logout();
        });

        $(".download_all_link").on('click', (e: JQuery.Event) => {
            e.preventDefault();
            this.getAll();
        });

        $(".update_link").on('click', (e: JQuery.Event) => {
            e.preventDefault();
            window.location.reload();
        });

        $(".cosmetic_version").attr('title', this.cosmeticVersion);

    }

    async logout(): Promise<void> {
        try {
            await Http.post("backend.php", {op: "logout"});
        } catch (e) {
            console.warn('logout request failed', e);
        }
        window.location.reload();
    }

    /**
     * Show the book summary modal.
     * @param elem - The trigger element with data-book-id.
     */
    async showSummary(elem: HTMLElement): Promise<boolean> {
        const bookId = elem.getAttribute("data-book-id");

        if (!bookId)
            return false;

        if (this.isOnline()) {

            const reply = await Http.post("backend.php", {op: 'list', ids: bookId}) as HttpResponse;

            const data = reply.data['books'][0] as BookInfo;

            const comment = data.comment ? data.comment : 'No description available';

            $("#summary-modal .modal-title").text(data.title);
            $("#summary-modal .book-summary").html(comment);

            $("#summary-modal").modal();

        } else {
            const data = await localforage.getItem("epube-book." + bookId) as BookInfo;
            const comment = data.comment ? data.comment : 'No description available';

            $("#summary-modal .modal-title").text(data.title);
            $("#summary-modal .book-summary").html(comment);

            $("#summary-modal").modal();
        }

        return false;
    }

    showCovers() {
        $("img[data-book-id]").each((i: number, elem: HTMLElement) => {
            const e = $(elem);

            if (e.attr('data-cover-link')) {
                const img = $("<img>")
                    .on("load", () => {
                        e.css("background-image", "url(" + e.attr('data-cover-link') + ")")
                            .fadeIn();

                        img.attr("src", null);
                    })
                    .attr("src", e.attr('data-cover-link') ?? "");
            }
        });
    }

    /**
     * Update the favorite prompt text on an element.
     * @param elem - The element to update.
     * @param is_fav - Whether the book is a favorite.
     */
    updateFavoritePrompt(elem: HTMLElement, is_fav: boolean): void {
        $(elem)
            .text(is_fav ? "Remove from favorites" : "Add to favorites")
            .attr('data-is-fav', is_fav ? 1 : 0);
    }

    /**
     * Toggle a book's favorite status.
     * @param elem - The trigger element with data-book-id.
     */
    async toggleFavorite(elem: HTMLElement): Promise<boolean> {
        const bookId = elem.getAttribute("data-book-id");

        if (!bookId)
            return false;

        if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {

            try {
                const resp = await Http.post("backend.php", {op: "togglefav", id: bookId}) as HttpResponse;
                if (resp.data) {
                    this.updateFavoritePrompt(elem, resp.data.status == "1");

                    if (this.index_mode == "favorites" && resp.data.status == 0) {
                        $("#cell-" + bookId).remove();
                    }
                }
            } catch (e) {
                console.warn('toggleFavorite failed', e);
            }
        }

        return false;
    }

    updateOfflinePrompts() {
        const elems = $(".offline_dropitem");

        $.each(elems, (i: number, elem: HTMLElement) => {
            this.updateOfflinePrompt(elem);
        });
    }

    /**
     * Update the offline prompt for a single book element.
     * @param elem - The element to update.
     */
    async updateOfflinePrompt(elem: HTMLElement): Promise<void> {
        const bookId = elem.getAttribute("data-book-id");

        if (!bookId)
            return;

        const cacheId = "epube-book." + bookId;

        const book = await localforage.getItem(cacheId);

        if (book) {
            elem.onclick = () => {
                this.remove(bookId, () => {
                    this.updateOfflinePrompt(elem);
                });

                return false;
            };

            elem.innerHTML = "Remove offline data";

        } else {
            elem.onclick = () => {
                this.get(bookId, () => {
                    this.updateOfflinePrompt(elem);
                });
                return false;
            };

            elem.innerHTML = "Make available offline";
        }
    }

    async offlineInit(): Promise<void> {
        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());

        if (typeof EpubeApp != "undefined") {
            $(".navbar").hide();
            $(".epube-app-filler").show();
            $("body").addClass("is-epube-app");

            EpubeApp.setPage("PAGE_OFFLINE");
        }

        this.initNightMode();
        this.initCommonEventHandlers();

        $(".search_query").val(this.urlParam("query"));

        this.populateOfflineList();
    }

     /**
     * Download a single book for offline reading.
     * @param bookId - The book ID to download.
     * @param callback - Callback invoked after download completes.
     */
    async get(bookId: string, callback: () => void): Promise<void> {
        console.log("offline cache: " + bookId);

        const reply = await Http.post("backend.php", {op: "list", ids: bookId}) as HttpResponse;

        const data = reply.data['books'][0] as BookInfo;

        if (data) {
            const cacheId = 'epube-book.' + bookId;

            await localforage.setItem(cacheId, data);
            console.log(cacheId + ' got data');

            const promises: Promise<void|Blob>[] = [];

            promises.push(Http.blob('backend.php?op=download&id=' + data.epub_id).then((resp) => {
                console.log(cacheId + ' got book');
                return localforage.setItem(cacheId + '.book', resp.blob);
            }).catch((e) => console.warn('failed to download book', e)));

            promises.push(Http.text("backend.php?op=getpagination&id=" + data.epub_id).then((resp) => {
                console.log(cacheId + ' got pagination');
                return localforage.setItem(cacheId + '.locations', JSON.parse(resp.text));
            }).catch((e) => console.warn('failed to download pagination', e)));

            promises.push(Http.text("backend.php?op=getlastread&id=" + data.epub_id).then((resp) => {
                console.log(cacheId + ' got lastread');
                return localforage.setItem(cacheId + '.lastread', JSON.parse(resp.text));
            }).catch((e) => console.warn('failed to download lastread', e)));

            if (data.has_cover) {
                promises.push(Http.blob("backend.php?op=cover&id=" + bookId).then((resp) => {
                    console.log(cacheId + ' got cover');
                    return localforage.setItem(cacheId + '.cover', resp.blob);
                }).catch((e) => console.warn('failed to download cover', e)));
            }

            await Promise.all(promises);
            console.log('download done, running callback', callback);

            callback();

            $(".dl-progress")
                .show()
                .html("Finished downloading <b>" + this.escapeHtml(data.title) + "</b>");

            window.clearTimeout(this._dl_progress_timeout);

            this._dl_progress_timeout = window.setTimeout(() => {
                $(".dl-progress").fadeOut();
            }, 5*1000);
        }
    }

    getAll(): void {
        if (confirm("Download all books on this page?")) {

            $(".row > div").each((i: number, row: HTMLElement) => {
                const bookId = ($(row).attr("id") ?? "").replace("cell-", "");
                const dropitem = $(row).find(".offline_dropitem")[0] ?? null;

                if (bookId) {
                    const cacheId = 'epube-book.' + bookId;

                    localforage.getItem(cacheId).then((book) => {
                        if (!book) {
                            this.get(bookId, () => {
                                this.updateOfflinePrompt(dropitem as HTMLElement);
                            });
                        }
                    });
                }
            });
        }
    }

    /**
     * Remove a book from the list UI.
     * @param elem - The element with data-book-id.
     */
    removeFromList(elem: HTMLElement): void {
        const bookId = elem.getAttribute("data-book-id");

        if (bookId) {
            this.remove(bookId, () => {
                $("#cell-" + bookId).remove();
            });
        }
    }

    remove(id: string, callback: () => void): void {
        if (confirm("Remove download?")) {

            const cacheId = "epube-book." + id;
            const promises: Promise<void>[] = [];

            console.log("offline remove: " + id);

            localforage.iterate(function(value: unknown, key: string /*, i */) {
                if (key.match(cacheId)) {
                    promises.push(localforage.removeItem(key));
                }
            });

            Promise.all(promises).then(() => {
                console.log('remove done, running callback', callback);

                // just promise.all is not enough, need to wait a bit for localforage to actually delete item (?)
                window.setTimeout(() => {
                    callback();
                }, 250);
            });
        }
    }

    async populateList(): Promise<void> {
        const params = new URLSearchParams({
            op: "list",
            mode: this.index_mode,
            query: this.index_query,
            offset: String(this.index_offset),
            limit: String(60),
        });

        let resp: HttpResponse;
        try {
            resp = await Http.get("backend.php?" + params.toString());
        } catch (e) {
            const err = e as HttpError;
            if ((err as any).status === 401) {
                window.location.href = "login.php";
            }
            return;
        }

        const data = resp.data as BookList;
        const books = $("#books_container");
        books.html("");

        if (data) {
            data.books.forEach((book: BookInfo) => {
                const download_html = book.download_formats
                    .map((fmt: { id: number, format: string }) => {
                        const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary";
                        return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`;
                    })
                    .join("");

                const menuItems = [
                    `<li><a href="#" class="summary_link" data-book-id="${book.id}">Summary</a></li>`,
                    `<li><a href="#" class="fav_item" data-is-fav="${book.is_fav ? "1" : "0"}"
                        data-book-id="${book.id}">${book.is_fav ? "Remove from favorites" : "Add to favorites"}</a></li>`,
                ];

                if (book.epub_id) {
                    menuItems.push(`<li><a href="#" data-book-id="${book.id}" class="offline_dropitem"></a></li>`);
                    menuItems.push('<li class="divider"></li>');
                }

                menuItems.push(download_html);

                const cell = this.renderBookCell(book, {
                    menuItems: menuItems,
                });

                books.append(cell);
            });

            this.showCovers();
            this.updateOfflinePrompts();
        }

        this.updateIndexPagination(data);
    }

    /**
     * Update the index pagination UI.
     * @param data - The book list response containing pagination info.
     */
    updateIndexPagination(data: BookList): void {
        const prevLi = $(".pager .previous");
        const nextLi = $(".pager .next");
        const pagerInfo = $(".pager .pager-info");

        const prevParams = new URLSearchParams({
            mode: this.index_mode,
            query: this.index_query,
            offset: String(this.index_offset - 60),
        });
        const nextParams = new URLSearchParams({
            mode: this.index_mode,
            query: this.index_query,
            offset: String(this.index_offset + 60),
        });

        if (this.index_offset > 0) {
            prevLi.removeClass("disabled");
            prevLi.find("a").attr("href", "?" + prevParams.toString());
        } else {
            prevLi.addClass("disabled");
            prevLi.find("a").attr("href", "#");
        }

        if (data.books && data.books.length >= 60) {
            nextLi.removeClass("disabled");
            nextLi.find("a").attr("href", "?" + nextParams.toString());
        } else {
            nextLi.addClass("disabled");
            nextLi.find("a").attr("href", "#");
        }

        const limit = data.limit || 60;
        const total = data.total || 0;
        const currentPage = Math.floor(this.index_offset / limit) + 1;
        const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;

        pagerInfo.find("span").text(`Page ${currentPage} of ${totalPages}`);
    }

    /**
     * Render a book cell DOM element.
     * @param book - Book data object.
     * @param opts - Rendering options.
     * @param opts.menuItems - Array of <li> menu item HTML strings.
     * @param opts.seriesUrl - Search by series override
     * @param opts.authorUrl - Search by author override
     * @returns {JQuery<HTMLElement>} The created cell element.
     */
    renderBookCell(book: BookInfo, opts: { menuItems: string[], seriesUrl?: string, authorUrl?: string }): JQuery<HTMLElement> {
        //console.log('renderBookCell', book, opts);

        const cellThumbClass = book.is_read ? "read" : "";
        const cellTitleClass = book.in_progress ? "in_progress" : "";

        const isOpenable = book.epub_id != 0;

        const authorUrl = opts.authorUrl ?? "?" + new URLSearchParams({"query": book.author_sort, "mode": this.index_mode}).toString();
        const seriesUrl = opts.seriesUrl ?? "?" + new URLSearchParams({"query": book.series_name, "mode": this.index_mode}).toString();

        const readUrl = `read.html?id=${book.epub_id}&b=${book.id}&rt=${this.index_mode}`;

        const titleHtml = isOpenable ?
            `<a href="${readUrl}">${this.escapeHtml(book.title)}</a>` :
            this.escapeHtml(book.title);

        const authorHtml = `<a title="${this.escapeHtml(book.author_sort)}" href="${authorUrl}">
                ${this.escapeHtml(book.author_sort)}
            </a>`;

        const seriesHtml = book.series_name ?
            `<div><a class="series_link" href="${seriesUrl}">
                ${this.escapeHtml(book.series_name) + " [" + book.series_index + "]"}
            </a></div>` : '';

        const cell = $(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${book.id}">
            ${isOpenable ?
                `<a class="thumbnail ${cellThumbClass}" href="${readUrl}">` :
                    `<span class="thumbnail ${cellThumbClass}">`}
                <img style="display : none" data-book-id="${book.id}" data-cover-link="${book.cover_link || ''}">
            ${isOpenable ? "</a>" : "</span>"}
            <div class="caption">
                <div title="${this.escapeHtml(book.title)}" class="${cellTitleClass}">
                    ${titleHtml}
                </div>
                ${seriesHtml}
                <div>${authorHtml}</div>
            </div>
            <div class="dropdown" style="white-space : nowrap">
                <a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
                <ul class="dropdown-menu" aria-labelledby="dLabel">
                    ${opts.menuItems.join('\n')}
                </ul>
            </div>
        </div>`);

        cell.find('.summary_link').on('click', (evt: JQuery.ClickEvent) => {
            evt.preventDefault();
            this.showSummary(evt.currentTarget);
        });

        cell.find('.fav_item').on('click', (evt: JQuery.ClickEvent) => {
            evt.preventDefault();
            this.toggleFavorite(evt.currentTarget);
        });

        // specific to offline index
        cell.find('.remove_offline_data').on('click', (evt: JQuery.ClickEvent) => {
            evt.preventDefault();
            this.removeFromList(evt.currentTarget);
        });

        return cell;
    }

    async search(): Promise<boolean> {
        const query = $(".search_query").val() as string | undefined;

        await localforage.setItem("epube.search-query", query);

        this.populateOfflineList();

        return false;
    }

    async removeAll(): Promise<void> {
        if (confirm("Remove all downloaded books?")) {

            const promises: Promise<void>[] = [];

            localforage.iterate(function(value: unknown, key: string/*, i*/) {
                if (key.match("epube-book")) {
                    promises.push(localforage.removeItem(key));
                }
            });

            await Promise.all(promises);

            this.populateOfflineList();
        }
    }

    /**
     * Remove downloaded books whose stored reading progress marks them as read
     * (same heuristic as the rendered list: fewer than 5 pages left).
     */
    async removeRead(): Promise<void> {
        if (!confirm("Remove downloaded books marked as read?")) {
            return;
        }

        const suffixes = ["", ".book", ".cover", ".locations", ".lastread"];
        const promises: Promise<void>[] = [];
        const keysToRemove: string[] = [];

        // Gather all individual asynchronous check operations
        await localforage.iterate((value: unknown, key: string) => {
            const match = key.match(/^epube-book\.(\d+)$/);

            if (!match) {
                return;
            }

            const cacheId = match[0];

            // Push the pending getItem promise into our tracker array
            const checkPromise = localforage.getItem(cacheId + ".lastread").then((raw) => {
                if (!raw) {
                    return;
                }

                const lastread = (typeof raw === "string" ? JSON.parse(raw) : raw) as LastRead;
                const isRead = lastread.total > 0 && lastread.total - lastread.page < 5;

                if (isRead) {
                    console.log("offline remove read: " + cacheId);
                    for (const suffix of suffixes) {
                        keysToRemove.push(cacheId + suffix);
                    }
                }
            });

            promises.push(checkPromise);
        });

        // Wait for ALL database lookups to completely finish evaluation
        await Promise.all(promises);

        // Perform the actual removal of the compiled keys
        if (keysToRemove.length > 0) {
            await Promise.all(keysToRemove.map((key) => localforage.removeItem(key)));
        }

        this.populateOfflineList();
    }

   populateOfflineList(): void {
        let query = this.urlParam("query");
        if (query) query = String(query).toLowerCase();

        const books = $("#books_container");
        books.html("");

        localforage.iterate((value: unknown, key: string) => {
            if (key.match(/epube-book\.\d{1,}$/)) {

                Promise.all([
                    localforage.getItem(key),
                    localforage.getItem(key + ".cover"),
                    localforage.getItem(key + ".lastread"),
                    localforage.getItem(key + ".book")
                ]).then((results) => {

                    if (results[0] && results[3]) {

                        const info = results[0] as BookInfo;

                        if (query) {
                            const match =
                                (info.series_name && info.series_name.toLowerCase().match(query)) ||
                                (info.title && info.title.toLowerCase().match(query)) ||
                                (info.author_sort && info.author_sort.toLowerCase().match(query));

                            if (!match) return;
                        }

                        let cover = "";
                        if (results[1]) {
                            cover = URL.createObjectURL(results[1] as Blob);
                        }

                        const lastread = results[2] as LastRead | null;
                        info.in_progress = lastread ? lastread.page > 0 : false;
                        info.is_read = lastread ? (lastread.total > 0 && lastread.total - lastread.page < 5) : false;

                        const authorUrl = `offline.html?query=${encodeURIComponent(info.author_sort)}`;
                        const seriesUrl = `offline.html?query=${encodeURIComponent(info.series_name)}`;

                        const cell = this.renderBookCell(info, {
                            menuItems: [
                                `<li><a href="#" class="summary_link" data-book-id="${info.id}">Summary</a></li>`,
                                `<li><a href="#" class="remove_offline_data" data-book-id="${info.id}">Remove offline data</a></li>`,
                            ],
                            authorUrl: authorUrl,
                            seriesUrl: seriesUrl,
                        });

                        if (cover) {
                            cell.find("img")
                                .css("background-image", "url(" + cover + ")")
                                .fadeIn();
                        } else {
                            cell.fadeIn();
                        }

                        books.append(cell);
                    }
                });
            }
        });
    }

}