'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((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((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 = { '&': '&', '<': '<', '>': '>', '"': '"', '/': '/', "'": ''', '`': '`' }; 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 { 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 { 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 { 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 = $("") .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 { 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 { 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 { 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 { 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[] = []; 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 " + this.escapeHtml(data.title) + ""); 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[] = []; 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 { 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 `
  • Download: ${fmt.format}
  • `; }) .join(""); const menuItems = [ `
  • Summary
  • `, `
  • ${book.is_fav ? "Remove from favorites" : "Add to favorites"}
  • `, ]; if (book.epub_id) { menuItems.push(`
  • `); menuItems.push('
  • '); } 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
  • menu item HTML strings. * @param opts.seriesUrl - Search by series override * @param opts.authorUrl - Search by author override * @returns {JQuery} The created cell element. */ renderBookCell(book: BookInfo, opts: { menuItems: string[], seriesUrl?: string, authorUrl?: string }): JQuery { //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 ? `${this.escapeHtml(book.title)}` : this.escapeHtml(book.title); const authorHtml = ` ${this.escapeHtml(book.author_sort)} `; const seriesHtml = book.series_name ? `` : ''; const cell = $(`
    ${isOpenable ? `` : ``} ${isOpenable ? "" : ""}
    ${titleHtml}
    ${seriesHtml}
    ${authorHtml}
    `); 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 { const query = $(".search_query").val() as string | undefined; await localforage.setItem("epube.search-query", query); this.populateOfflineList(); return false; } async removeAll(): Promise { if (confirm("Remove all downloaded books?")) { const promises: Promise[] = []; 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 { if (!confirm("Remove downloaded books marked as read?")) { return; } const suffixes = ["", ".book", ".cover", ".locations", ".lastread"]; const promises: Promise[] = []; 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: [ `
  • Summary
  • `, `
  • Remove offline data
  • `, ], authorUrl: authorUrl, seriesUrl: seriesUrl, }); if (cover) { cell.find("img") .css("background-image", "url(" + cover + ")") .fadeIn(); } else { cell.fadeIn(); } books.append(cell); } }); } }); } }