about summary refs log tree commit diff stats
path: root/dist/app.js
diff options
context:
space:
mode:
Diffstat (limited to 'dist/app.js')
-rw-r--r--dist/app.js417
1 files changed, 417 insertions, 0 deletions
diff --git a/dist/app.js b/dist/app.js
new file mode 100644
index 0000000..5950757
--- /dev/null
+++ b/dist/app.js
@@ -0,0 +1,417 @@
+'use strict';
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.AppClass = void 0;
+const appcommon_1 = require("./appcommon");
+const cookie_1 = require("./cookie");
+class AppClass extends appcommon_1.AppCommon {
+    constructor() {
+        super(...arguments);
+        this.index_mode = "";
+        this.cached_urls = [];
+        this.version = "UNKNOWN";
+        this.buildTimestamp = 0;
+        this.csrf_token = "";
+    }
+    init() {
+        let refreshed_files = 0;
+        this.csrf_token = cookie_1.Cookie.get('epube_csrf_token');
+        console.log('setting prefilter for token', this.csrf_token);
+        /* eslint-disable no-unused-vars */
+        $.ajaxPrefilter((options, originalOptions, jqXHR) => {
+            if (originalOptions.type !== 'post' || options.type !== 'post') {
+                return;
+            }
+            const datatype = typeof originalOptions.data;
+            if (datatype == 'object')
+                options.data = $.param($.extend(originalOptions.data, { "csrf_token": this.csrf_token }));
+            else if (datatype == 'string')
+                options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token);
+            console.log('>>>', options);
+        });
+        if (typeof EpubeApp != "undefined") {
+            $(".navbar").hide();
+            $(".epube-app-filler").show();
+            $(".separate-search").show();
+            $("body").addClass("is-epube-app");
+            if (this.urlParam("mode") == "favorites")
+                EpubeApp.setPage("PAGE_FAVORITES");
+            else
+                EpubeApp.setPage("PAGE_LIBRARY");
+        }
+        this.initNightMode();
+        this.initCommonEventHandlers();
+        if ('serviceWorker' in navigator) {
+            navigator.serviceWorker.addEventListener('message', (event) => {
+                if (event.data == 'refresh-started') {
+                    console.log('cache refresh started');
+                    refreshed_files = 0;
+                    $(".dl-progress")
+                        .fadeIn()
+                        .text("Loading, please wait...");
+                }
+                if (event.data && event.data.indexOf("refreshed:") == 0) {
+                    ++refreshed_files;
+                    $(".dl-progress")
+                        .fadeIn()
+                        .text("Updated " + refreshed_files + " files...");
+                }
+                if (event.data == 'refresh-finished') {
+                    localforage.setItem("epube.cache-version", this.version);
+                    localforage.setItem("epube.cache-timestamp", this.buildTimestamp);
+                    window.location.reload();
+                }
+            });
+            this.showCovers();
+            this.updateOfflinePrompts();
+            this.refreshCache(false);
+        }
+        else {
+            $(".container-main")
+                .addClass("alert alert-danger")
+                .html("Service worker support missing in browser (are you using plain HTTP?).");
+        }
+    }
+    initCommonEventHandlers() {
+        $(".refresh_cache_link").on('click', () => {
+            this.refreshCache(true);
+        });
+        $(".remove_all_downloads").on('click', () => {
+            this.removeAll();
+        });
+        $(".logout_link").on('click', () => {
+            this.logout();
+        });
+    }
+    logout() {
+        $.post("backend.php", { op: "logout" }).then(() => {
+            window.location.reload();
+        });
+    }
+    async showSummary(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+        if (this.isOnline()) {
+            const data = await $.post("backend.php", { op: 'getinfo', id: bookId });
+            const comment = data.comment ? data.comment : 'No description available';
+            $("#summary-modal .modal-title").html(data.title);
+            $("#summary-modal .book-summary").html(comment);
+            $("#summary-modal").modal();
+        }
+        else {
+            const data = await localforage.getItem("epube-book." + bookId);
+            const comment = data.comment ? data.comment : 'No description available';
+            $("#summary-modal .modal-title").html(data.title);
+            $("#summary-modal .book-summary").html(comment);
+            $("#summary-modal").modal();
+        }
+        return false;
+    }
+    showCovers() {
+        $("img[data-book-id]").each((i, elem) => {
+            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'));
+            }
+        });
+    }
+    toggleFavorite(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+        if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {
+            $.post("backend.php", { op: "togglefav", id: bookId }, (data) => {
+                if (data) {
+                    let msg = "[Error]";
+                    if (data.status == 0) {
+                        msg = "Add to favorites";
+                    }
+                    else if (data.status == 1) {
+                        msg = "Remove from favorites";
+                    }
+                    $(elem).html(msg).attr('data-is-fav', data.status);
+                    if (this.index_mode == "favorites" && data.status == 0) {
+                        $("#cell-" + bookId).remove();
+                    }
+                }
+            });
+        }
+        return false;
+    }
+    async refreshCache(force) {
+        if ('serviceWorker' in navigator) {
+            const version = await localforage.getItem("epube.cache-version");
+            console.log('local version', version, 'remote version', this.version);
+            if (force || version != this.version) {
+                console.log('asking worker to refresh cache');
+                if (navigator.serviceWorker.controller) {
+                    navigator.serviceWorker.controller.postMessage({ msg: "refresh-cache", urls: this.cached_urls });
+                }
+                else {
+                    const done = await localforage.getItem("epube.initial-load-done");
+                    console.log("initial load done?", done);
+                    if (done) {
+                        $(".dl-progress")
+                            .show()
+                            .addClass("alert-danger")
+                            .html("Could not communicate with service worker. Try reloading the page.");
+                    }
+                    else {
+                        await localforage.setItem("epube.initial-load-done", true);
+                        $(".dl-progress")
+                            .show()
+                            .addClass("alert-info")
+                            .html("Page will reload to activate service worker...");
+                        window.setTimeout(function () {
+                            window.location.reload();
+                        }, 3 * 1000);
+                    }
+                }
+            }
+        }
+        else {
+            $(".dl-progress")
+                .show()
+                .addClass("alert-danger")
+                .html("Could not communicate with service worker. Try reloading the page.");
+        }
+    }
+    appCheckOffline() {
+        EpubeApp.setOffline(!this.isOnline);
+    }
+    updateOfflinePrompts() {
+        const elems = $(".offline_dropitem");
+        $.each(elems, (i, elem) => {
+            this.updateOfflinePrompt(elem);
+        });
+    }
+    async updateOfflinePrompt(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+        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";
+        }
+    }
+    offlineInit() {
+        if (typeof EpubeApp != "undefined") {
+            $(".navbar").hide();
+            $(".epube-app-filler").show();
+            $("body").addClass("is-epube-app");
+            EpubeApp.setPage("PAGE_OFFLINE");
+        }
+        this.initNightMode();
+        this.initCommonEventHandlers();
+        const query = this.urlParam("query");
+        if (query)
+            $(".search_query").val(query);
+        this.populateList();
+    }
+    get(bookId, callback) {
+        console.log("offline cache: " + bookId);
+        $.post("backend.php", { op: "getinfo", id: bookId }, (data) => {
+            if (data) {
+                const cacheId = 'epube-book.' + bookId;
+                localforage.setItem(cacheId, data).then((data) => {
+                    console.log(cacheId + ' got data');
+                    const promises = [];
+                    promises.push(fetch('backend.php?op=download&id=' + data.epub_id, { credentials: 'same-origin' }).then(function (resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got book');
+                            localforage.setItem(cacheId + '.book', resp.blob());
+                        }
+                    }));
+                    promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, { credentials: 'same-origin' }).then(function (resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got pagination');
+                            resp.text().then(function (text) {
+                                localforage.setItem(cacheId + '.locations', JSON.parse(text));
+                            });
+                        }
+                    }));
+                    promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, { credentials: 'same-origin' }).then(function (resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got lastread');
+                            resp.text().then(function (text) {
+                                localforage.setItem(cacheId + '.lastread', JSON.parse(text));
+                            });
+                        }
+                    }));
+                    if (data.has_cover) {
+                        promises.push(fetch("backend.php?op=cover&id=" + bookId, { credentials: 'same-origin' }).then(function (resp) {
+                            if (resp.status == 200) {
+                                console.log(cacheId + ' got cover');
+                                localforage.setItem(cacheId + '.cover', resp.blob());
+                            }
+                        }));
+                    }
+                    Promise.all(promises).then(() => {
+                        console.log('download done, running callback', callback);
+                        callback();
+                        $(".dl-progress")
+                            .show()
+                            .html("Finished downloading <b>" + data.title + "</b>");
+                        window.clearTimeout(this._dl_progress_timeout);
+                        this._dl_progress_timeout = window.setTimeout(function () {
+                            $(".dl-progress").fadeOut();
+                        }, 5 * 1000);
+                    });
+                });
+            }
+        });
+    }
+    getAll() {
+        if (confirm("Download all books on this page?")) {
+            $(".row > div").each((i, row) => {
+                const bookId = $(row).attr("id").replace("cell-", "");
+                const dropitem = $(row).find(".offline_dropitem")[0];
+                if (bookId) {
+                    const cacheId = 'epube-book.' + bookId;
+                    localforage.getItem(cacheId).then((book) => {
+                        if (!book) {
+                            this.get(bookId, () => {
+                                this.updateOfflinePrompt(dropitem);
+                            });
+                        }
+                    });
+                }
+            });
+        }
+    }
+    removeFromList(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+        this.remove(bookId, () => {
+            $("#cell-" + bookId).remove();
+        });
+    }
+    remove(id, callback) {
+        if (confirm("Remove download?")) {
+            const cacheId = "epube-book." + id;
+            const promises = [];
+            console.log("offline remove: " + id);
+            localforage.iterate(function (value, key /*, 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 search() {
+        const query = $(".search_query").val();
+        await localforage.setItem("epube.search-query", query);
+        this.populateList();
+        return false;
+    }
+    async removeAll() {
+        if (confirm("Remove all downloaded books?")) {
+            const promises = [];
+            localforage.iterate(function (value, key /*, i*/) {
+                if (key.match("epube-book")) {
+                    promises.push(localforage.removeItem(key));
+                }
+            });
+            await Promise.all(promises);
+            this.populateList();
+        }
+    }
+    populateList() {
+        let query = this.urlParam("query");
+        if (query)
+            query = String(query).toLowerCase();
+        const books = $("#books_container");
+        books.html("");
+        localforage.iterate(function (value, key /*, i*/) {
+            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(function (results) {
+                    if (results[0] && results[3]) {
+                        const info = results[0];
+                        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 && results[1]) {
+                            cover = URL.createObjectURL(results[1]);
+                        }
+                        let in_progress = false;
+                        let is_read = false;
+                        const lastread = results[2];
+                        if (lastread) {
+                            in_progress = lastread.page > 0;
+                            is_read = lastread.total > 0 && lastread.total - lastread.page < 5;
+                        }
+                        const thumb_class = is_read ? "read" : "";
+                        const title_class = in_progress ? "in_progress" : "";
+                        const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : "";
+                        const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}">
+						<a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}">
+							<img style="display : none">
+						</a>
+						<div class="caption">
+							<div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div>
+							<div><a class="author_link" href="#">${info.author_sort}</a></div>
+							${series_link}
+						</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">
+								<li><a href="#" data-book-id="${info.id}" onclick="return App.showSummary(this)">Summary</a></li>
+								<li><a href="#" data-book-id="${info.id}" onclick="App.removeFromList(this)">Remove offline data</a></li>
+							</ul>
+						</div>
+					</div>`);
+                        if (cover) {
+                            cell.find("img")
+                                .css("background-image", "url(" + cover + ")")
+                                .fadeIn();
+                        }
+                        else {
+                            cell
+                                .fadeIn();
+                        }
+                        cell.find(".series_link")
+                            .attr("title", info.series_name + " [" + info.series_index + "]")
+                            .attr("href", "offline.html?query=" + encodeURIComponent(info.series_name));
+                        cell.find(".author_link")
+                            .attr("title", info.author_sort)
+                            .attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort));
+                        books.append(cell);
+                    }
+                });
+            }
+        });
+    }
+}
+exports.AppClass = AppClass;