diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-03-29 09:54:51 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-03-29 09:54:51 +0300 |
| commit | 7d1f357a5e263567707b8f018da17f74c44c6d50 (patch) | |
| tree | faefd91113c180f3591002a8fdf291dbfdf6e692 /src | |
| parent | d2ea17abf815b6cd754511e27f4853045e0b3ca2 (diff) | |
| download | the-epube-ts.tar.gz the-epube-ts.tar.xz | |
horrors of ts ts
Diffstat (limited to 'src')
| -rw-r--r-- | src/app.ts | 540 | ||||
| -rw-r--r-- | src/appcommon.ts | 43 | ||||
| -rw-r--r-- | src/cookie.ts | 24 | ||||
| -rw-r--r-- | src/reader.ts | 1709 |
4 files changed, 2316 insertions, 0 deletions
diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..8c6df78 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,540 @@ +'use strict' + +declare var EpubeApp: any; +declare var localforage: LocalForage; + +import { AppCommon } from "./appcommon"; +import { Cookie } from "./cookie"; + +export class AppClass extends AppCommon { + _dl_progress_timeout; + + index_mode = ""; + + cached_urls = []; + + version = "UNKNOWN"; + + buildTimestamp = 0; + + csrf_token = ""; + + init() { + let refreshed_files = 0; + + this.csrf_token = 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 = <any> 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 = <any> 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] as Blob); + + } + let in_progress = false; + let is_read = false; + + const lastread = <any> 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); + } + }); + } + }); + } + +} diff --git a/src/appcommon.ts b/src/appcommon.ts new file mode 100644 index 0000000..393b781 --- /dev/null +++ b/src/appcommon.ts @@ -0,0 +1,43 @@ +declare var EpubeApp: any; + +export class AppCommon { + urlParam(name){ + try { + const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); + return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0; + } catch (e) { + return 0; + } + } + + isOnline() { + if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined") + return EpubeApp.isOnline(); + else + return navigator.onLine; + } + + 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); + } + } + + 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")); + } +} diff --git a/src/cookie.ts b/src/cookie.ts new file mode 100644 index 0000000..c38a1ac --- /dev/null +++ b/src/cookie.ts @@ -0,0 +1,24 @@ +export class Cookie { + 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; + } + + 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 ""; + } + + static delete(name) { + const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT"; + document.cookie = name + "=; " + expires; + } +} diff --git a/src/reader.ts b/src/reader.ts new file mode 100644 index 0000000..1758a74 --- /dev/null +++ b/src/reader.ts @@ -0,0 +1,1709 @@ +'use strict'; + +declare var EpubeApp: any; +declare var localforage: LocalForage; + +declare var createHyphenator: any; +declare var hyphenationPatternsEnUs: any; +declare var hyphenationPatternsRu: any; + +const DEFAULT_FONT_SIZE = 16; +const DEFAULT_FONT_FAMILY = "Arial"; +const DEFAULT_LINE_HEIGHT = 140; +const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */ + +const LOCATION_DIVISOR = 10; +const PAGE_RESET_PROGRESS = -1; + +import { AppCommon } from "./appcommon"; +import { Cookie } from "./cookie"; + +export class ReaderClass extends AppCommon { + csrf_token = ""; + + last_stored_cfi = ""; + + startup_finished = false; + + open_last_read_when_displayed = true; + + hyphenate = {en: null, ru: null}; + + _prevent_lastread_timeout; + + _prevent_lastread; + + _flattened_toc; + + loader; + + /** + * @type {ePub.Book} + */ + book; + + async init() { + this.csrf_token = Cookie.get('epube_csrf_token'); + + console.log('setting prefilter for token', this.csrf_token); + + $.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); + }); + + $(document).on("keyup", (e) => { + this.hotkeyHandler(e); + }); + + $(".close_book").on("click", () => { + this.close(); + }); + + $("#left").on("mouseup", () => { + this.prevPage(); + }); + + $(".search_input").on("change", () => { + this.search(); + }); + + $(".prev_location_btn").on("click", (evt) => { + this.openPrevious(evt.target); + }); + + $("#right").on("mouseup", () => { + this.nextPage(); + }); + + this.loader = new ReaderLoader(); + + const load_failed = await this.loader.init(); + + console.log('[init] load failed', load_failed); + + if (!load_failed) { + this.initSecondStage(); + } else { + this.applyTheme(); + + $(".loading-message").text('Resource loader failed to initialize.'); + } + } + + // another method, maybe use this: window.matchMedia("(pointer: coarse)").matches + // https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas + isTouchDevice() { + return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0); + } + + /** + * @param {boolean} offline + */ + onOfflineModeChanged(offline) { + console.log('onOfflineModeChanged', offline); + + if (!offline && this.book) { + console.log("we're online, storing lastread"); + + const currentCfi = this.book.rendition.currentLocation().start.cfi; + const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf + + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, + cfi: currentCfi, timestamp: new Date().getTime() }, function() { + // + }) + .fail(function(e) { + if (e && e.status == 401) { + window.location.href = "index.php"; + } + }); + } + } + + async initSecondStage() { + + if (typeof EpubeApp != "undefined") { + EpubeApp.setPage("PAGE_READER"); + } else { + $(window).on('online', () => { + this.onOfflineModeChanged(false); + }); + + $(window).on('offline', () => { + this.onOfflineModeChanged(true); + }); + } + + this.applyTheme(); + + const bookinfo = await localforage.getItem(this.cacheId()); + + if (!bookinfo) { + const bookId = this.urlParam("b"); + + console.log('requesting bookinfo for book', bookId) + + try { + const resp = await $.post("backend.php", {op: "getinfo", id: bookId }); + + if (resp.has_cover) { + const cover = await fetch("backend.php?op=cover&id=" + bookId); + + if (cover.ok) + await localforage.setItem(this.cacheId('cover'), cover.blob()); + } + + await localforage.setItem(this.cacheId(), resp); + + console.log('bookinfo saved'); + + } catch (e) { + $(".loading-message").html(`Unable to load book info.<br/><small>${e.responseText}</small>`); + return; + } + } + + console.log('trying to load book...'); + + let book_data = await localforage.getItem(this.cacheId("book")); + + if (!book_data) { + console.log("local data not found, loading from network..."); + + $(".loading-message").html("Downloading book…"); + + const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id")); + + if (book_resp.ok) { + book_data = await book_resp.blob(); + + if (book_data) { + await localforage.setItem(this.cacheId('book'), book_data); + console.log('saved local data for book'); + } else { + $(".loading-message").html("Unable to get book blob data."); + return; + } + + } else { + $(".loading-message").html(`Unable to download book: ${book_resp.status}`); + return; + } + } + + const fileReader = new FileReader(); + const _reader = this; + + fileReader.onload = function() { + try { + _reader.openBookData(this.result); + } catch (e) { + console.error(e); + $(".loading-message").html("Unable to load book blob: " + e); + } + }; + + fileReader.onerror = (e) => { + console.log('filereader error', e); + $(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>"); + }; + + fileReader.readAsArrayBuffer(book_data as Blob); + } + + async openBookData(book_data) { + // @ts-ignore + this.book = new ePub.Book(); + + try { + await this.book.open(book_data); + } catch (e) { + console.error(e); + $(".loading-message").html("Unable to open book.<br/><small>" + e.message + "</small>"); + return; + } + + await this.book.ready; + + console.log('book is ready'); + + await this.showBookInfo(this.book); + await this.loadLocations(this.book); + + const rendition = this.book.renderTo("reader", { + width: '100%', + height: '100%', + allowScriptedContent: false, + minSpreadWidth: 961 + }); + + $(".location").on('click', async () => { + const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR); + const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR); + + const page = prompt("Jump to location [1-" + total + "]", String(current)); + + if (page) + await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]); + }); + + const enable_hyphens = await localforage.getItem("epube.enable-hyphens"); + + if (enable_hyphens) { + /* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */ + this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true }); + this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true }); + } + + this.initRenditionHooks(this.book, rendition); + this.initModals(); + this.initToc(this.book); + + // open first page at startup, lastread will open when it is rendered + this.blockLastReadUpdate(); + await rendition.display(); + + console.log('startup finished'); + this.startup_finished = true; + } + + /** + * @param {ePub.Book} book + */ + async showBookInfo(book) { + const bookinfo = <any> await localforage.getItem(this.cacheId()); + + let title; + let author; + + if (bookinfo) { + title = bookinfo.title; + author = bookinfo.author_sort; + } else { + const metadata = book.packaging.metadata; + + title = metadata.title; + author = metadata.creator; + } + + document.title = title + " – " + author + " – The Epube"; + + $(".title") + .text(title) + .attr("title", title + " – " + author); + + if (typeof EpubeApp != "undefined") { + EpubeApp.setTitle(title); + EpubeApp.showActionBar(false); + } + } + + /** + * @param {ePub.Book} book + */ + async loadLocations(book) { + let locations = await localforage.getItem(this.cacheId("locations")); + + // legacy format is array of objects {cfi: ..., page: ...} + if (locations && typeof locations[0] == "string") { + console.log('loading local locations...'); + try { + await book.locations.load(locations); + return; + } catch (e) { + console.warn(e); + } + } + + if (this.isOnline()) { + console.log("downloading locations..."); + + $(".loading-message").html("Downloading locations…"); + + const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id")); + + if (resp.ok) { + console.log("got locations from server"); + + // if this doesn't load, we'll generate locations and save them + try { + locations = await resp.json(); + } catch (e) { + console.warn(e); + } + + if (locations && typeof locations[0] == "string") { + console.log('saving locations locally...'); + + await localforage.setItem(this.cacheId("locations"), locations); + + try { + book.locations.load(locations); + + return; + } catch (e) { + console.warn(e); + } + } + } + } + + $(".loading-message").html("Preparing locations…"); + + let generate_queue_max = 0; + + locations = await book.locations.generate(100, (queue) => { + if (!generate_queue_max) + generate_queue_max = queue.length(); + + // what if there's only one section or something and queue is already zero + if (generate_queue_max > 0) { + const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf + + $(".loading-message").html(`Preparing locations (${queue_pct}%)…`); + } + }); + + $.post("backend.php", { op: "storepagination", id: this.urlParam("id"), + payload: JSON.stringify(locations), total: 100}); + + await localforage.setItem(this.cacheId("locations"), locations); + } + + /** + * @param {ePub.Book} book + * @param {ePub.Rendition} rendition + */ + initRenditionHooks(book, rendition) { + console.log('initRenditionHooks'); + + book.spine.hooks.content.register((doc/*, section */) => { + this.cleanupEmbeddedStyles(doc); + }); + + rendition.hooks.content.register(async (contents) => { + + contents.on("linkClicked", (href) => { + console.log('linkClicked', href); + + this.blockLastReadUpdate(); + + if (href.indexOf("://") == -1) { + $(".prev_location_btn") + .attr("data-location-cfi", rendition.currentLocation().start.cfi) + .show(); + + window.requestAnimationFrame(() => { + this.showUI(true); + }); + } + }); + + contents.on("selected", async (cfiRange) => { + if (this.isOnline()) { + const range = await book.getRange(cfiRange); + + const selection = range.endContainer.data.substring(range.startOffset, range.endOffset); + + console.log('selected', cfiRange, selection); + + if (selection.match(/^[\w]+$/)) { + this.lookupWord(selection, () => { + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + + contents.window.requestAnimationFrame(() => { + contents.window.getSelection().removeAllRanges(); + }); + }); + } + } + }); + + // get our stuff from resource loader and inject into iframe content + + const base_url = window.location.href.match(/^.*\//)[0]; + + $(contents.document.head) + .append($("<style type='text/css'>") + .text(this.generateFontsCss(base_url))); + + $(contents.document.head) + .append($("<style type='text/css'>") + .text(this.loader._res_data[base_url + 'dist/reader_iframe.min.css'])); + + const theme = await localforage.getItem("epube.theme") || 'default'; + + $(contents.document).find("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("theme-" + theme); + + console.log('contents', contents); + + $(contents.window).on("click tap", (evt) => { + if (evt.button == 0) { + if ($(".modal").is(":visible")) + return; + + if (typeof EpubeApp != "undefined") + EpubeApp.toggleActionBar(); + else + this.showUI(true); + } + }); + + $(contents.window).on("wheel", async (evt) => { + if (await localforage.getItem("epube.enable-wheel")) { + if ((evt.originalEvent as WheelEvent).deltaY > 0) { + this.nextPage(); + } else if ((evt.originalEvent as WheelEvent).deltaY < 0) { + this.prevPage(); + } + } + }); + + // need to figure out how to do swipes safely (invisible overlay which passes text selection?) + + /* if (typeof EpubeApp != "undefined" || Reader.isTouchDevice()) { + $(window).on("swipeleft", function() { + console.log('swipe left'); + + this.nextPage(); + }); + + $(window).on("swiperight", function() { + console.log('swipe right'); + + this.prevPage(); + }); + } */ + + }); + + rendition.on("keyup", (e) => { + this.hotkeyHandler(e); + }); + + rendition.on('resized', (/*chapter*/) => { + console.log('rendition resized'); + + this.blockLastReadUpdate(); + this.open_last_read_when_displayed = true; + }); + + rendition.on('rendered', async (/* section */) => { + console.log('rendition rendered'); + + this.applyTheme(); + this.resizeSideColumns(); + + try { + const location = rendition.currentLocation(); + + if (location.start) { + const cur_href = book.canonical(location.start.href); + let toc_entry = {label: ""}; + + $.each(this.flattenToc(book), function(i, r) { + + if (book.spine.get(r.href).canonical == cur_href) { + toc_entry = r; + return; + } + }); + + if (toc_entry && toc_entry.label) + $(".chapter_title").html(toc_entry.label.trim() + " | "); + + this.generateTocBar(book, this.flattenToc(book)); + } + + } catch (e) { + console.warn(e); + } + + if (this.open_last_read_when_displayed) { + this.open_last_read_when_displayed = false; + + await this.openLastRead(); + } + }); + + // this seems to be called a lot more than rendered + rendition.on('displayed', function(/*chapter*/) { + console.log('rendition displayed'); + }); + + rendition.on('relocated', (/** @type {ePub.Location} */ location) => this.onRelocated(book, location)); + } + + initModals() { + $('#settings-modal').on('shown.bs.modal', async () => { + + const last_read = <any> await localforage.getItem(this.cacheId("lastread")); + + if (last_read && last_read.cfi) { + $(".lastread_input") + .val(last_read.page + '%') + .attr('title', `[local] ${last_read.cfi}`); + } + + $(".clear_last_read") + .off("click") + .on("click", () => { + this.clearLastRead(); + }); + + $(".open_last_read") + .off("click") + .on("click", () => { + this.openLastRead(); + }); + + $(".mark_as_read") + .off("click") + .on("click", () => { + this.markAsRead(); + }); + + $(".reset_locations") + .off("click") + .on("click", () => { + this.resetLocations(); + }); + + if (navigator.onLine) + $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => { + $(".lastread_input") + .val(data.page + '%') + .attr('title', `[remote] ${data.cfi}`); + }); + + $(".font_family") + .off("change") + .on("change", (evt) => { + this.onFontChanged(evt.target); + }); + + $(".font_size") + .off("change") + .on("change", (evt) => { + this.onTextSizeChanged(evt.target); + }); + + $(".line_height") + .off("change") + .on("change", (evt) => { + this.onLineHeightChanged(evt.target); + }); + + $(".theme_name") + .off("change") + .on("change", (evt) => { + this.onThemeChanged(evt.target); + }); + + $(".enable_hyphens_checkbox") + .attr("checked", await localforage.getItem("epube.enable-hyphens")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.enable-hyphens", (evt.target as HTMLInputElement).checked); + + if (confirm("Toggling hyphens requires page reload. Reload now?")) { + window.location.reload(); + } + }); + + $(".enable_wheel_checkbox") + .attr("checked", await localforage.getItem("epube.enable-wheel")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.enable-wheel", (evt.target as HTMLInputElement).checked); + }); + + if (typeof EpubeApp != "undefined") { + $(".keep_ui_checkbox").parent().parent().hide(); + } else { + $(".keep_ui_checkbox") + .attr("checked", await localforage.getItem("epube.keep-ui-visible")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.keep-ui-visible", (evt.target as HTMLInputElement).checked); + }); + } + + const stamp = String(await localforage.getItem("epube.cache-timestamp")); + const version = await localforage.getItem("epube.cache-version"); + + $(".last-mod-timestamp").html(`${version} + — ${parseInt(stamp) ? new Date(parseInt(stamp) * 1000).toLocaleString("en-GB") : "Unknown"} + (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`}) + `); + + $(".font_family").val(await localforage.getItem("epube.fontFamily") || DEFAULT_FONT_FAMILY); + $(".theme_name").val(await localforage.getItem("epube.theme") || 'default'); + + const zoom = $(".font_size").html(""); + + for (let i = 10; i <= 32; i++) { + const opt = $("<option>").val(i).html(i + " px"); + zoom.append(opt); + } + + zoom.val(await localforage.getItem("epube.fontSize") || DEFAULT_FONT_SIZE); + + const line_height = $(".line_height").html(""); + + for (let i = 100; i <= 220; i += 10) { + const opt = $("<option>").val(i).html(i + "%"); + line_height.append(opt); + } + + line_height.val(await localforage.getItem("epube.lineHeight") || DEFAULT_LINE_HEIGHT); + + }); + + $('#dict-modal').on('shown.bs.modal', () => { + $(".dict_query") + .off("change") + .on("change", () => { + this.lookupWord(null, null, '.dict_query'); + }); + + $(".dict_result").scrollTop(0); + }); + + // TODO: make configurable + $(".dict_search_btn").on("click", function() { + $("#dict-modal").modal('hide'); + window.open("https://duckduckgo.com/?q=" + $(".dict_query").val()); + }); + + } + + initToc(book) { + const _reader = this; + + function toc_loc_msg(href) { + try { + const cfiBase = book.spine.get(href).cfiBase; + + const loc = book.locations._locations.find(function(k) { + return k.indexOf(cfiBase) != -1 + }); + + return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR); + + } catch (e) { + console.warn(e); + } + + return ""; + } + + function process_toc_sublist(row, list, nest) { + + if (nest == 3) return false; + + if (row.subitems) { + + const sublist = $("<ul class='toc_sublist list-unstyled'>"); + + $.each(row.subitems, function(i, row) { + + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label) + .attr('data-href', row.href) + .click(function() { + book.rendition.display(a.attr('data-href')); + }); + + sublist.append($("<li>").append(a)); + + process_toc_sublist(row, sublist, nest + 1); + + }); + + list.append(sublist); + } + } + + $('#toc-modal').on('shown.bs.modal', function() { + + const toc = book.navigation.toc; + + const list = $(".toc_list"); + list.html(""); + + $.each(toc, function(i, row) { + + // if anything fails here the toc entry is likely useless anyway (i.e. no cfi) + try { + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label) + .attr('data-href', row.href) + .click(function() { + book.rendition.display(a.attr('data-href')); + }); + + list.append($("<li>").append(a)); + + process_toc_sublist(row, list, 0); + + } catch (e) { + console.warn(e); + } + }); + + // well the toc didn't work out, might as well generate one + if (list.children().length <= 1) { + + list.html(""); + + $.each(book.spine.items, function (i, row) { + + const a = $("<a>") + .attr('href', '#') + .attr('title', row.url) + // @ts-ignore + .html(`Section ${i+1}`) + .attr('data-href', row.href) + .on('click', () => { + book.rendition.display(a.attr('data-href')); + }); + + list.append($("<li>").append(a)); + + }); + } + + }); + } + + /* embedded styles may conflict with our font sizes, etc */ + cleanupEmbeddedStyles(doc) { + $(doc).find("p") + // @ts-ignore + .filter((i, e) => (($(e).text().length >= MIN_LENGTH_TO_JUSTIFY) ? e : null)) + .css("text-align", "justify"); + + $(doc).find("html") + .attr("class", ""); + + $(doc).find("pre") + .css("white-space", "pre-wrap"); + + $(doc).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li") + .attr("class", "") + .css("font-family", "inherit") + .css("font-size", "inherit") + .css("line-height", "inherit") + .css("color", "") + .css("border", "none ! important") + .css("background", "") + .css("background-color", "") + .attr("width", "") + .attr("height", ""); + + // same as above except for allowed font-size + $(doc).find("h1, h2, h3, h4, h5") + .attr("class", "") + .css("font-family", "inherit") + .css("color", "") + .css("border", "none ! important") + .css("background", "") + .css("background-color", ""); + + if (typeof this.hyphenate.en != "undefined") { + $(doc).find('p, div').each((i, elem) => { + const p = $(elem); + + p.html(this.hyphenate.en(p.html())); + p.html(this.hyphenate.ru(p.html())); + }); + } + } + + generateFontsCss(base_url) { + return ` + /** Calibri */ + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibriz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrib.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrii.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibri.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Cambria */ + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriaz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambria.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Caecilia */ + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caecilia.ttf']}); + font-weight : normal; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliab.ttf']}); + font-weight : bold; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliai.ttf']}); + font-style : italic; + } + + /** Palatino */ + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palabi.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/pala.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Consolas */ + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolaz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consola.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** IBM Plex Mono */ + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Bold.otf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-BoldItalic.otf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-TextItalic.otf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Text.otf']}); + font-style: normal; + font-weight : 400; + } + `; + } + + flattenTocSubItems(entry, nest) { + let rv = []; + + if (nest == 3) return false; + + if (entry.subitems) { + $.each(entry.subitems, (i, r) => { + r._nest = nest; + + rv.push(r); + rv = rv.concat(this.flattenTocSubItems(r, nest+1)); + }); + } + + return rv; + } + + /** + * @param { ePub.Book } book + * + * @returns { ePub.NavItem[] } + */ + flattenToc(book) { + if (this._flattened_toc) { + return this._flattened_toc; + } else { + let rv = []; + + $.each(book.navigation.toc, (i, r) => { + // @ts-ignore + r._nest = 0; + + rv.push(r); + rv = rv.concat(this.flattenTocSubItems(r, 1)); + }); + + this._flattened_toc = rv; + + return rv; + } + } + + /** + * @param { ePub.Book } book + * @param { any[] } toc + */ + generateTocBar(book, toc) { + $(".spacer") + .html(""); + + $.each(toc, function(i, te) { + try { + const cfiBase = book.spine.get(te.href).cfiBase; + const loc = book.locations._locations.find(function(k) { + return k.indexOf(cfiBase) != -1 + }); + + if (loc) { + const pct = Math.round(book.locations.percentageFromCfi(loc) * 100); + + $(".spacer").append( + $("<div class='toc-bar-entry'>") + .attr('data-nest-level', te._nest) + .css('left', pct + '%') + .css('_width', (3 - te._nest) + "px") + .attr("title", te.label) + ) + + } + + } catch (e) { + console.warn(e); + } + }); + + $(".spacer").append($("<div class='toc-bar-entry current-position'>")); + + this.updateTocBarPosition(book, book.rendition.currentLocation()) + } + + updateTocBarPosition(book, location) { + const cur_pct = Math.round(location.start.location / book.locations.length() * 100); + + $(".toc-bar-entry.current-position") + .css('left', cur_pct + '%'); + } + + async applyTheme() { + let fontSize = await localforage.getItem("epube.fontSize"); + let fontFamily = await localforage.getItem("epube.fontFamily"); + let lineHeight = await localforage.getItem("epube.lineHeight"); + + fontSize = fontSize ? fontSize + "px" : DEFAULT_FONT_SIZE + "px"; + fontFamily = fontFamily ? fontFamily : DEFAULT_FONT_FAMILY; + lineHeight = lineHeight ? lineHeight + "%" : DEFAULT_LINE_HEIGHT + "%"; + + console.log('style', fontFamily, fontSize, lineHeight); + console.log('applying default theme styles...'); + + if (this.book && this.book.rendition) + this.book.rendition.themes.default({ + html: { + 'font-size': fontSize, + 'font-family': "'" + fontFamily + "'", + 'line-height': lineHeight, + 'text-align': 'justify', + 'text-indent': '1em' + } + }); + + let theme = await localforage.getItem("epube.theme") || "default"; + + console.log('called for theme', theme); + + if (theme == "default" && typeof EpubeApp != "undefined") + if (EpubeApp.isNightMode()) + theme = "night"; + + console.log('setting main UI theme', theme); + + $("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("epube-reader theme-" + theme) + .attr("data-is-loading", "false"); + + if (typeof EpubeApp != "undefined") { + window.setTimeout(function() { + const bg_color = window.getComputedStyle(document.querySelector("body"), null) + .getPropertyValue("background-color"); + + let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); + + if (match) { + console.log("sending bgcolor", match); + + EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3])); + } + + const accent_color = window.getComputedStyle(document.querySelector(".header .title"), null) + .getPropertyValue("color"); + + match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); + + if (match) { + console.log("sending accent_color", match); + + EpubeApp.setAccentColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3])); + } + + }, 250); + } + + if (this.book && this.book.rendition) + this.book.rendition.getContents().forEach((rendition) => { + console.log(`applying styles and theme ${theme} to `, rendition); + + rendition.css("font-size", fontSize); + rendition.css("font-family", "'" + fontFamily + "'"); + rendition.css("line-height", lineHeight); + rendition.css("text-align", 'justify'); + + $(rendition.document).find("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("theme-" + theme); + }); + } + + hotkeyHandler(e) { + try { + //console.log('K3:' + e.which, e); + + if ($(".modal").is(":visible")) + return; + + // right or space or pagedown + if (e.which == 39 || e.which == 32 || e.which == 34) { + e.preventDefault(); + this.nextPage(); + } + + // left or pageup + if (e.which == 37 || e.which == 33) { + e.preventDefault(); + this.prevPage(); + } + + // esc + if (e.which == 27) { + e.preventDefault(); + this.showUI(true); + } + } catch (e) { + console.warn(e); + } + } + + resizeSideColumns() { + let width = $("#reader").position().left; + + if (this.book && this.book.rendition) + this.book.rendition.getContents().forEach((rendition) => { + width += parseInt(rendition.window.getComputedStyle(rendition.document.querySelector('body')).getPropertyValue('padding-left')); + }); + + console.log(`resizing side columns to ${width} px`); + + $("#left, #right").width(width); + } + + async markAsRead() { + if (confirm("Mark book as read?")) { + $("#settings-modal").modal('hide'); + + const total = 100; + const lastCfi = this.book.locations.cfiFromPercentage(1); + const lastread_timestamp = new Date().getTime(); + + if (this.isOnline()) { + const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp }); + $(".lastread_input").val(data.page + '%'); + } + + await localforage.setItem(this.cacheId("lastread"), + {cfi: lastCfi, page: total, total: total, timestamp: lastread_timestamp}); + + await this.openLastRead(); + } + } + + async close() { + const location = this.book.rendition.currentLocation(); + + const currentCfi = location.start.cfi; + const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); + const totalPages = 100; + const lastread_timestamp = new Date().getTime(); + + await localforage.setItem(this.cacheId("lastread"), + {cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp}); + + if (this.isOnline()) { + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, + cfi: currentCfi, timestamp: lastread_timestamp }, () => { + window.location.href = this.urlParam("rt") ? "index.php?mode=" + this.urlParam("rt") : "index.php"; + }) + .fail(() => { + window.location.href = "index.php"; + }); + } else { + window.location.href = "index.php"; + } + } + + cacheId(suffix = "") { + return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : ""); + } + + showUI(show) { + if (show) + $(".header,.footer").fadeIn(); + else + $(".header,.footer").fadeOut(); + } + + toggleUI() { + if ($(".header").is(":visible")) + $(".header,.footer").fadeOut(); + else + $(".header,.footer").fadeIn(); + } + + async lookupWord(word, callback, elem = null) { + if (elem) + word = $(elem).val(); + + word = word.replace(//g, ""); + + console.log('lookupWord', word); + + $(".dict_result").html('Loading, please wait...'); + + $("#dict-modal").modal('show'); + + try { + const data = await $.post("backend.php", {op: 'define', word: word}); + + if (data) { + + $(".dict_result").html(data.result.join("<br/>")); + $(".dict_query").val(word); + + if (callback) callback(); + } + } catch (e) { + console.error(e); + + $(".dict_result").html(`Network error while looking up word: ${e.responseText}.`); + } + } + + search() { + const query = $(".search_input").val(); + const list = $(".search_results"); + + list.html(""); + + if (query) { + list.html("<li>Loading, please wait...</li>"); + + /* eslint-disable prefer-spread */ + Promise.all( + this.book.spine.spineItems.map( + (item) => item.load(this.book.load.bind(this.book)) + // @ts-ignore TODO something wrong with the types (?) + .then(item.find.bind(item, query)) + .finally(item.unload.bind(item))) + ) + .then((results) => Promise.resolve([].concat.apply([], results))) + .then((results) => { + list.html(""); + + $.each(results, (i, row) => { + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + this.book.locations.locationFromCfi(row.cfi) + "</b>" + row.excerpt) + .attr('data-cfi', row.cfi) + .attr('data-id', row.id) + .on('click', () => { + this.book.rendition.display(a.attr('data-cfi')); + }); + + list.append($("<li>").append(a)); + }); + }); + } + } + + nextPage() { + this.book.rendition.next(); + + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + else + localforage.getItem("epube.keep-ui-visible").then((keep) => { + if (!keep) this.showUI(false); + }); + } + + prevPage() { + this.book.rendition.prev(); + + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + else + localforage.getItem("epube.keep-ui-visible").then((keep) => { + if (!keep) this.showUI(false); + }); + } + + /** + * @param {HTMLElement} elem + */ + async openPrevious(elem) { + const cfi = $(elem).attr("data-location-cfi"); + + if (cfi) + await this.book.rendition.display(cfi); + + $(elem).fadeOut(); + } + + blockLastReadUpdate() { + console.log('blocking last read updates...'); + + if (this._prevent_lastread_timeout) + window.clearTimeout(this._prevent_lastread_timeout); + + this._prevent_lastread_timeout = window.setTimeout(() => { + this._prevent_lastread = false; + this._prevent_lastread_timeout = false; + console.log('unblocked last read updates'); + }, 1000); + + this._prevent_lastread = true; + } + + /** + * @param { ePub.Book } book + * @param { ePub.Location } location + */ + async onRelocated(book, location) { + // locations not generated yet + if (book.locations.length() == 0) + return; + + const currentCfi = location.start.cfi; + const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100); + + $("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR)); + $("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR)); + $("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi)*100) + '%'); + + this.updateTocBarPosition(book, location); + + const displayed = location.start.displayed; + + if (displayed) { + $("#chapter_cur_page").text(displayed.page); + $("#chapter_total_pages").text(displayed.total); + + if (displayed.total > 0) + $("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%') + } + + if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) { + const lastread_timestamp = new Date().getTime(); + + console.log("storing lastread", currentPct, currentCfi, lastread_timestamp); + + await localforage.setItem(this.cacheId("lastread"), + {cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp}); + + if (this.isOnline()) { + console.log("updating remote lastread", currentCfi); + this.last_stored_cfi = currentCfi; + + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct, + cfi: currentCfi, timestamp: lastread_timestamp }); + } + } + } + + async clearLastRead() { + if (confirm("Reset reading progress for this book?")) { + $("#settings-modal").modal('hide'); + + const total = this.book.locations.length(); + const lastread_timestamp = new Date().getTime(); + + if (this.isOnline()) + await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp }); + + await localforage.setItem(this.cacheId("lastread"), + {cfi: "", page: 0, total: total, timestamp: lastread_timestamp}); + + await this.book.rendition.display(this.book.locations.cfiFromPercentage(0)); + + $(".lastread_input").val('0%'); + } + } + + async resetLocations() { + if (confirm("Reset stored pagination data? This will also reset reading progress.")) { + $("#settings-modal").modal('hide'); + + await localforage.removeItem(this.cacheId("lastread")); + await localforage.removeItem(this.cacheId("locations")); + + await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() }) + + // this might return 404 and its okay + await $.post("backend.php", + { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e)) + + window.location.reload(); + } + } + + async openLastRead() { + $(".loading").show(); + $(".loading-message").html("Opening last read page…"); + + $("#settings-modal").modal('hide'); + + const rendition = this.book.rendition; + + if (!rendition) { + console.error('no rendition to work on'); + return; + } + + let location_found = false; + + const lr_local = <any> await localforage.getItem(this.cacheId("lastread")) || {}; + console.log('got local lastread', lr_local); + + if (this.isOnline()) { + try { + const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }); + + console.log('got remote lastread', lr_remote); + + if (lr_remote) { + if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) { + console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`); + + await localforage.setItem(this.cacheId("lastread"), + {cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp}); + + location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi); + } + } + } catch (e) { + console.log('unable to get remote lastread, continuing...'); + console.warn(e); + } + } + + // for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts, + // that's why we no longer reset to page 1 after trying local CFI + if (!location_found) { + if (lr_local && lr_local.cfi) { + console.log(`using local lastread cfi: ${lr_local.cfi}`); + try { + await this.moveToCfiVerify(rendition, lr_local.cfi); + } catch (e) { + console.warn(e); + } + } + } + + $(".loading").fadeOut(); + } + + /** + * @param {string} a + * @param {string} b + */ + calculateCfiDelta(a, b) { + // @ts-ignore + const acfi = new ePub.CFI(a); + // @ts-ignore + const bcfi = new ePub.CFI(b); + + console.log('calculateCfiDelta', acfi, bcfi); + + if (acfi.path.steps.length != bcfi.path.steps.length) + return -1; + + let delta = 0; + + // this is about as ad-hoc as it gets... + for (let i = 0; i < acfi.path.steps.length; i++) { + + // is this possible? who knows! + if (acfi.path.steps[i].type != bcfi.path.steps[i].type) + return -1; + + // different "filepos" or w/e + if (acfi.path.steps[i].id != bcfi.path.steps[i].id) + return -1; + + if (acfi.path.steps[i].id === null && acfi.path.steps[i].type === 'element') + delta += Math.abs(acfi.path.steps[i].index - bcfi.path.steps[i].index); + } + + return delta; + } + + /** + * @param {ePub.Rendition} rendition + * @param {string} cfi + */ + async moveToCfiVerify(rendition, cfi, attempts = 5, maxDelta = 5) { + for (let att = 1; att < attempts; att++) { + this.blockLastReadUpdate(); + + console.log(`trying to open ${cfi}: attempt ${att} of ${attempts}...`); + + /* eslint-disable no-await-in-loop */ + await rendition.display(cfi); // we need to be synchronous here + + let moved_to; + + try { + moved_to = rendition.currentLocation().start.cfi; + } catch (e) { + console.warn('location not yet available, will retry:', e); + } + + try { + const delta = this.calculateCfiDelta(cfi, moved_to); + + console.log(`opened cfi ${moved_to} expected ${cfi}; delta: ${delta}`); + + if (moved_to == cfi || (delta != -1 && delta <= maxDelta)) { + console.log("cfi move verified!"); + return true; + } + } catch (e) { + console.warn('exception while parsing cfi, will retry: ', e); + } + } + + return false; + } + + /** + * @param {HTMLElement} elem + */ + async onThemeChanged(elem) { + const theme = $(elem).val(); + + await localforage.setItem("epube.theme", theme); + this.applyTheme(); + } + + /** + * @param {HTMLElement} elem + */ + async onLineHeightChanged(elem) { + const height = $(elem).val(); + + await localforage.setItem("epube.lineHeight", height); + this.applyTheme(); + } + + /** + * @param {HTMLElement} elem + */ + async onTextSizeChanged(elem) { + const size = $(elem).val(); + + await localforage.setItem("epube.fontSize", size); + this.applyTheme(); + } + + /** + * @param {HTMLElement} elem + */ + async onFontChanged(elem) { + const font = $(elem).val(); + + await localforage.setItem("epube.fontFamily", font); + this.applyTheme(); + } +} + +class ReaderLoader { + _res_data = []; + + CACHE_NAME = 'epube-v3'; + + async init() { + if (typeof EpubeApp != "undefined") { + $("body").addClass("epube-app"); + } + + // we need to manually provide resources for reader iframe because service worker fetch() handler doesn't work inside iframes (chrome bug?) + + const promises = []; + let load_failed = false; + + const cache = await caches.open(this.CACHE_NAME); + const cache_keys = await cache.keys(); + + cache_keys.forEach((req) => { + if (!req.url.match('backend\.php')) { + console.log('[loader] loading resource', req.url); + const promise = fetch(req.url).then(async (resp) => { + if (resp.ok) { + const url = new URL(resp.url); + url.searchParams.delete("ts"); + + if (resp.url.match('\\.ttf|\\.otf')) { + const blob = await resp.blob(); + console.log('[loader] storing blob', url.href); + + this._res_data[url.toString()] = URL.createObjectURL(blob); + } else { + const text = await resp.text(); + console.log('[loader] storing text', url.href); + + this._res_data[url.toString()] = text; + } + } else { + console.warn('[loader] failed for resource', req.url, resp); + + $(".loading-message").html(`Unable to load resource.<br/><small>${req.url}</small>`); + + load_failed = true; + } + }); + + promises.push(promise); + } + }); + + await Promise.allSettled(promises); + + console.log('[loader] resource load complete, failed: ', load_failed); + + return load_failed; + } +} |
