diff options
Diffstat (limited to 'src/app.ts')
| -rw-r--r-- | src/app.ts | 842 |
1 files changed, 842 insertions, 0 deletions
diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..03aefd1 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,842 @@ +// @ts-check + +'use strict'; + +class Cookie { + + /** + * @param {string} name + * @param {string | number | boolean} value + * @param {number} lifetime + */ + static set(name, value, lifetime) { + const d = new Date(); + d.setTime(d.getTime() + lifetime * 1000); + const expires = "expires=" + d.toUTCString(); + document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires; + } + + /** + * @param {string} name + */ + static get(name) { + 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 ""; + } + + /** + * @param {string} name + */ + static delete(name) { + const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT"; + document.cookie = name + "=; " + expires; + } +} + +class AppCommon { + /** + * @param {string} name + */ + urlParam(name){ + 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((resolve, reject) => { + const channel = new MessageChannel(); + let timeoutId = null; + + 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 = 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((resolve, reject) => { + const channel = new MessageChannel(); + let timeoutId = null; + + 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 = 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); + } + } + + /** @param {boolean} is_night */ + applyNightMode(is_night) { + 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 + * @param {string | number | boolean} p + * + * @return {string} + */ + escapeHtml(p) { + if (p === null || p === undefined) { + return ''; + } + + if (typeof p !== "string") { + return String(p); + } else { + const map = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + '/': '/', + "'": ''', + '`': '`' + }; + + return p.replace(/[&<>"'`/]/g, function(m) { return map[m]; }); + } + } +} + +/* eslint-disable-next-line no-unused-vars */ +class AppClass extends AppCommon { + _dl_progress_timeout; + + /** @type{string} */ + index_mode = ""; + + /** @type{string} */ + index_query = ""; + + /** @type{number} */ + index_offset = 0; + + cached_urls = []; + + /** @type{string} */ + cacheVersion = BUILD_CACHE_VERSION; + + /** @type{string} */ + cosmeticVersion = BUILD_VERSION; + + /** @type{string} */ + csrf_token = ""; + + async init() { + console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion()); + + // Read URL params for mode/query/offset + this.index_mode = this.urlParam("mode") || ""; + 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 = /** @type {HttpError} */(e); + // 401 Unauthorized — redirect to login + if (err.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(); + }); + + $(".logout_link").on('click', () => { + this.logout(); + }); + + $(".download_all_link").on('click', (e) => { + e.preventDefault(); + this.getAll(); + }); + + $(".update_link").on('click', (e) => { + e.preventDefault(); + window.location.reload(); + }); + + $(".cosmetic_version").attr('title', this.cosmeticVersion); + + } + + async logout() { + try { + await Http.post("backend.php", {op: "logout"}); + } catch (e) { + console.warn('logout request failed', e); + } + window.location.reload(); + } + + /** + * @param {HTMLElement} elem + */ + async showSummary(elem) { + const bookId = elem.getAttribute("data-book-id"); + + if (!bookId) + return; + + if (this.isOnline()) { + + /** @type{HttpResponse} */ + const reply = await Http.post("backend.php", {op: 'list', ids: bookId}); + + /** @type{BookInfo} */ + const data = reply.data['books'][0]; + + 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); + 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, 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') ?? ""); + } + }); + } + + /** + * @param {HTMLElement} elem + * @param {boolean} is_fav + */ + updateFavoritePrompt(elem, is_fav) { + $(elem) + .text(is_fav ? "Remove from favorites" : "Add to favorites") + .attr('data-is-fav', is_fav ? 1 : 0); + } + + /** + * @param {HTMLElement} elem + */ + async toggleFavorite(elem) { + const bookId = elem.getAttribute("data-book-id"); + + if (!bookId) + return; + + if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) { + + try { + const resp = await Http.post("backend.php", {op: "togglefav", id: bookId}); + 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, elem) => { + this.updateOfflinePrompt(elem); + }); + } + + /** + * @param {HTMLElement} elem + */ + async updateOfflinePrompt(elem) { + 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() { + 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(); + } + + /** + * @param {string} bookId + * @param {Function} callback + */ + async get(bookId, callback) { + console.log("offline cache: " + bookId); + + /** @type {HttpResponse} */ + const reply = await Http.post("backend.php", {op: "list", ids: bookId}); + + /** @type{BookInfo} */ + const data = reply.data['books'][0]; + + if (data) { + const cacheId = 'epube-book.' + bookId; + + await localforage.setItem(cacheId, data); + console.log(cacheId + ' got data'); + + const promises = []; + + 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() { + 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] ?? null; + + if (bookId) { + const cacheId = 'epube-book.' + bookId; + + localforage.getItem(cacheId).then((book) => { + if (!book) { + this.get(bookId, () => { + this.updateOfflinePrompt(dropitem); + }); + } + }); + } + }); + } + } + + /** + * @param {HTMLElement} elem + */ + 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 populateList() { + const params = new URLSearchParams({ + op: "list", + mode: this.index_mode, + query: this.index_query, + offset: String(this.index_offset), + limit: String(60), + }); + + /** @type {HttpResponse} */ + let resp; + try { + resp = await Http.get("backend.php?" + params.toString()); + } catch (e) { + const err = /** @type {HttpError} */(e); + if (err.status === 401) { + window.location.href = "login.php"; + } + return; + } + + /** @type{BookList} */ + const data = resp.data; + const books = $("#books_container"); + books.html(""); + + if (data) { + data.books.forEach((book) => { + const download_html = book.download_formats + .map((fmt) => { + 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); + } + + /** + * @param {BookList} data + */ + updateIndexPagination(data) { + 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 {BookInfo} book - Book data object. + * @param {Object} opts - Rendering options. + * @param {string[]} opts.menuItems - Array of <li> menu item HTML strings. + * @param {String} [opts.seriesUrl] - Search by series override + * @param {String} [opts.authorUrl] - Search by author override + * @returns {JQuery<HTMLElement>} The created cell element. + */ + renderBookCell(book, opts) { + //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) => { + evt.preventDefault(); + this.showSummary(evt.currentTarget); + }); + + cell.find('.fav_item').on('click', (evt) => { + evt.preventDefault(); + this.toggleFavorite(evt.currentTarget); + }); + + // specific to offline index + cell.find('.remove_offline_data').on('click', (evt) => { + evt.preventDefault(); + this.removeFromList(evt.currentTarget); + }); + + return cell; + } + + async search() { + const query = $(".search_query").val(); + + await localforage.setItem("epube.search-query", query); + + this.populateOfflineList(); + + 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.populateOfflineList(); + } + } + + populateOfflineList() { + let query = this.urlParam("query"); + if (query) query = String(query).toLowerCase(); + + const books = $("#books_container"); + books.html(""); + + localforage.iterate((value, key) => { + 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]) { + + /** @type BookInfo */ + 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[1]) { + cover = URL.createObjectURL(results[1]); + } + + const lastread = results[2]; + 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); + } + }); + } + }); + } + +} |
