diff options
| -rw-r--r-- | .eslintrc.js | 1 | ||||
| -rw-r--r-- | build.js | 20 | ||||
| -rw-r--r-- | classes/Config.php | 91 | ||||
| -rw-r--r-- | dist/app.min.js | 418 | ||||
| -rw-r--r-- | docs/Config.md | 58 | ||||
| -rw-r--r-- | index.php | 6 | ||||
| -rw-r--r-- | src/app.js | 4 | ||||
| -rw-r--r-- | src/index.d.ts | 2 | ||||
| -rw-r--r-- | src/reader.js | 4 | ||||
| -rw-r--r-- | tests/ConfigTest.php | 15 | ||||
| -rw-r--r-- | worker.js | 2 |
11 files changed, 300 insertions, 321 deletions
diff --git a/.eslintrc.js b/.eslintrc.js index 83c32a1..8bf9969 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,6 +12,7 @@ module.exports = { }, "globals": { "BUILD_CACHE_VERSION": "readonly", + "BUILD_VERSION": "readonly", "BUILD_MANIFEST_ASSETS": "readonly", }, "rules": { diff --git a/build.js b/build.js index 624d71b..4c3b0da 100644 --- a/build.js +++ b/build.js @@ -6,6 +6,21 @@ import { writeFile } from 'fs/promises'; import less from 'less'; import chokidar from 'chokidar'; import path from 'path'; +import { execSync } from 'child_process'; + +function getBuildVersion() { + try { + const output = execSync('git --no-pager log --pretty=%ct-%h -n1 HEAD', { encoding: 'utf8' }).trim(); + const [ts, shortHash] = output.split('-'); + const commitTs = parseInt(ts, 10); + const date = new Date(commitTs * 1000); + const yy = date.getUTCFullYear().toString().slice(-2); + const mm = String(date.getUTCMonth() + 1).padStart(2, '0'); + return `v${yy}.${mm}-${shortHash}`; + } catch { + return 'v00.00-unknown'; + } +} const LIB_FILES = [ 'lib/bootstrap/v3/js/jquery.js', @@ -65,6 +80,9 @@ async function buildApp() { const content = JS_FILES.map(f => readFileSync(f, 'utf8')).join('\n'); const CACHE_VERSION = `v${Date.now()}`; + const BUILD_VERSION = getBuildVersion(); + + console.log(`build version: ${BUILD_VERSION}`); await esbuild.build({ stdin: { contents: content, resolveDir: process.cwd(), loader: 'js' }, @@ -73,6 +91,7 @@ async function buildApp() { outfile: 'dist/app.min.js', define: { 'BUILD_CACHE_VERSION': JSON.stringify(CACHE_VERSION), + 'BUILD_VERSION': JSON.stringify(BUILD_VERSION), } }); @@ -102,6 +121,7 @@ async function buildApp() { define: { 'BUILD_CACHE_VERSION': JSON.stringify(CACHE_VERSION), 'BUILD_MANIFEST_ASSETS': JSON.stringify(MANIFEST_ASSETS), + 'BUILD_VERSION': JSON.stringify(BUILD_VERSION), } }); diff --git a/classes/Config.php b/classes/Config.php index b0a6e12..3898503 100644 --- a/classes/Config.php +++ b/classes/Config.php @@ -104,97 +104,6 @@ class Config { $this->reload(); } - /* package maintainers who don't use git: if version_static.txt exists in tt-rss root - directory, its contents are displayed instead of git commit-based version, this could be generated - based on source git tree commit used when creating the package */ - - /** @return string|array<string, mixed> */ - static function get_version(bool $as_string = true) : mixed { - return self::get_instance()->_get_version($as_string); - } - - /** @return string|array<string, mixed> */ - private function _get_version(bool $as_string = true) : mixed { - $root_dir = dirname(__DIR__); - - if (empty($this->version)) { - $this->version["status"] = -1; - - if (getenv("CI_COMMIT_SHORT_SHA") && getenv("CI_COMMIT_TIMESTAMP")) { - - $this->version["branch"] = getenv("CI_COMMIT_BRANCH"); - $this->version["timestamp"] = strtotime(getenv("CI_COMMIT_TIMESTAMP")); - $this->version["version"] = sprintf("%s-%s", date("y.m", $this->version["timestamp"]), getenv("CI_COMMIT_SHORT_SHA")); - $this->version["commit"] = getenv("CI_COMMIT_SHORT_SHA"); - $this->version["status"] = 0; - - } else if (PHP_OS === "Darwin") { - $this->version["version"] = "UNKNOWN (Unsupported, Darwin)"; - } else if (file_exists("$root_dir/version_static.txt")) { - $this->version["version"] = trim(file_get_contents("$root_dir/version_static.txt")) . " (Unsupported)"; - } else if (is_dir("$root_dir/.git")) { - $this->version = self::get_version_from_git($root_dir); - - if ($this->version["status"] != 0) { - user_error("Unable to determine version: " . $this->version["version"], E_USER_WARNING); - - $this->version["version"] = "UNKNOWN (Unsupported, Git error)"; - } - } else { - $this->version["version"] = "UNKNOWN (Unsupported)"; - } - } - - return $as_string ? $this->version["version"] : $this->version; - } - - /** @return array<string, mixed> */ - static function get_version_from_git(string $dir) : array { - $descriptorspec = [ - 1 => ["pipe", "w"], // STDOUT - 2 => ["pipe", "w"], // STDERR - ]; - - $rv = [ - "status" => -1, - "version" => "", - "commit" => "", - "branch" => "", - "timestamp" => 0, - ]; - - $proc = proc_open("git --no-pager log --pretty=\"version-%ct-%h\" -n1 HEAD", - $descriptorspec, $pipes, $dir); - - if (is_resource($proc)) { - $stdout = trim(stream_get_contents($pipes[1])); - $stderr = trim(stream_get_contents($pipes[2])); - $status = proc_close($proc); - - $rv["status"] = $status; - - list($check, $timestamp, $commit) = explode("-", $stdout); - - if ($check == "version") { - - $rv["version"] = strftime("%y.%m", (int)$timestamp) . "-$commit"; - $rv["commit"] = $commit; - $rv["timestamp"] = $timestamp; - - // proc_close() may return -1 even if command completed successfully - // so if it looks like we got valid data, we ignore it - - if ($rv["status"] == -1) - $rv["status"] = 0; - - } else { - $rv["version"] = T_sprintf("Git error [RC=%d]: %s", $status, $stderr); - } - } - - return $rv; - } - static function get_migrations() : Db_Migrations { return self::get_instance()->_get_migrations(); } diff --git a/dist/app.min.js b/dist/app.min.js index 1a1b681..5e87eb3 100644 --- a/dist/app.min.js +++ b/dist/app.min.js @@ -1,209 +1,209 @@ -"use strict";function setupCsrfPrefilter(p){console.log("setting prefilter for token",p),$.ajaxPrefilter((e,a,o)=>{if(a.type!=="post"||e.type!=="post")return;const t=typeof a.data;t=="object"?e.data=$.param($.extend(a.data,{csrf_token:p})):t=="string"&&(e.data=a.data+"&csrf_token="+encodeURIComponent(p)),console.log(">>>",e)})}class Cookie{static set(e,a,o){const t=new Date;t.setTime(t.getTime()+o*1e3);const i="expires="+t.toUTCString();document.cookie=e+"="+encodeURIComponent(a)+"; "+i}static get(e){e=e+"=";const a=document.cookie.split(";");for(let o=0;o<a.length;o++){let t=a[o];for(;t.charAt(0)==" ";)t=t.substring(1);if(t.indexOf(e)==0)return decodeURIComponent(t.substring(e.length,t.length))}return""}static delete(e){const a="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+a}}class AppCommon{urlParam(e){try{const a=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return a&&decodeURIComponent(a[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}async getActiveCacheName(){const a=(await navigator.serviceWorker.ready).active;return a?new Promise(o=>{const t=new MessageChannel;t.port1.onmessage=i=>{o(i.data.cacheName)},a.postMessage({type:"GET_CACHE_NAME"},[t.port2])}):null}async getActiveCacheVersion(){const a=(await navigator.serviceWorker.ready).active;return a?new Promise(o=>{const t=new MessageChannel;t.port1.onmessage=i=>{o(i.data.cacheName)},a.postMessage({type:"GET_CACHE_VERSION"},[t.port2])}):null}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";index_query="";index_offset=0;cached_urls=[];version="v1780151390364";csrf_token="";async init(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),this.urlParam("mode")=="favorites"?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),this.initCommonEventHandlers(),this.populateList(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",()=>{}),this.showCovers(),this.updateOfflinePrompts()):$(".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()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const a=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:a}),t=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").text(o.title),$("#summary-modal .book-summary").html(t),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+a),t=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").text(o.title),$("#summary-modal .book-summary").html(t),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,a)=>{const o=$(a);if(o.attr("data-cover-link")){const t=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),t.attr("src",null)}).attr("src",o.attr("data-cover-link")??"")}})}toggleFavorite(e){const a=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:a},o=>{if(o){let t="[Error]";o.status==0?t="Add to favorites":o.status==1&&(t="Remove from favorites"),$(e).html(t).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+a).remove()}}),!1}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(a,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const a=e.getAttribute("data-book-id"),o="epube-book."+a;await localforage.getItem(o)?(e.onclick=()=>(this.remove(a,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(a,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}async offlineInit(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode(),this.initCommonEventHandlers();const e=this.urlParam("query");e&&$(".search_query").val(e),this.populateOfflineList()}get(e,a){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const t="epube-book."+e;localforage.setItem(t,o).then(i=>{console.log(t+" got data");const s=[];s.push(fetch("backend.php?op=download&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got book"),localforage.setItem(t+".book",n.blob()))})),s.push(fetch("backend.php?op=getpagination&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got pagination"),n.text().then(function(l){localforage.setItem(t+".locations",JSON.parse(l))}))})),s.push(fetch("backend.php?op=getlastread&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got lastread"),n.text().then(function(l){localforage.setItem(t+".lastread",JSON.parse(l))}))})),i.has_cover&&s.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got cover"),localforage.setItem(t+".cover",n.blob()))})),Promise.all(s).then(()=>{console.log("download done, running callback",a),a(),$(".dl-progress").show().html("Finished downloading <b>"+i.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,a)=>{const o=($(a).attr("id")??"").replace("cell-",""),t=$(a).find(".offline_dropitem")[0]??null;if(o){const i="epube-book."+o;localforage.getItem(i).then(s=>{s||this.get(o,()=>{this.updateOfflinePrompt(t)})})}})}removeFromList(e){const a=e.getAttribute("data-book-id");this.remove(a,()=>{$("#cell-"+a).remove()})}remove(e,a){if(confirm("Remove download?")){const o="epube-book."+e,t=[];console.log("offline remove: "+e),localforage.iterate(function(i,s){s.match(o)&&t.push(localforage.removeItem(s))}),Promise.all(t).then(()=>{console.log("remove done, running callback",a),window.setTimeout(()=>{a()},250)})}}populateList(){const e=new URLSearchParams({op:"list",mode:this.index_mode,query:this.index_query,offset:String(this.index_offset),limit:String(60)});$.get("backend.php?"+e.toString()).done(a=>{const o=$("#books_container");o.html(""),a.books&&a.books.length>0&&(a.books.forEach(t=>{const i=t.is_read?"read":"",s=t.in_progress?"in_progress":"",n=t.is_fav?"1":"0",l=t.is_fav?"Remove from favorites":"Add to favorites",r=t.series_name?`<div><a title="${this.escapeHtml(t.series_full)}" href="${this.escapeHtml(t.series_link)}">${this.escapeHtml(t.series_full)}</a></div>`:"",c=t.author_sort?`?${new URLSearchParams({query:t.author_sort}).toString()}`:"",d=t.download_formats.map(u=>{const h=u.format==="EPUB"?"label-success":"label-primary";return`<li><a target="_blank" href="backend.php?op=download&id=${u.id}">Download: <span class="label ${h}">${u.format}</span></a></li>`}).join(""),f=$(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${t.id}"> - ${t.read_link?`<a class="thumbnail ${i}" href="${t.read_link}">`:`<span class="thumbnail ${i}">`} - <img style="display : none" data-book-id="${t.id}" data-cover-link="${t.cover_link}"> - ${t.read_link?"</a>":"</span>"} - <div class="caption"> - <div title="${this.escapeHtml(t.title)}" class="${s}"> - ${t.read_link?`<a href="${t.read_link}">${this.escapeHtml(t.title)}</a>`:this.escapeHtml(t.title)} - </div> - ${r} - <div><a title="${this.escapeHtml(t.author_sort)}" href="${this.escapeHtml(c)}">${this.escapeHtml(t.author_sort)}</a></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"> - <li><a href="#" class="summary_link" data-book-id="${t.id}">Summary</a></li> - <li><a href="#" class="fav_item" data-is-fav="${n}" data-book-id="${t.id}">${l}</a></li> - ${t.epub_id?`<li><a href="#" data-book-id="${t.id}" class="offline_dropitem"></a></li><li class="divider"></li>`:""} - ${d} - </ul> - </div> - </div>`);o.append(f)}),this.showCovers(),this.updateOfflinePrompts(),$(".summary_link").on("click",t=>{t.preventDefault(),this.showSummary(t.currentTarget)}),$(".fav_item").on("click",t=>{t.preventDefault(),this.toggleFavorite(t.currentTarget)}),$(".offline_dropitem").on("click",async t=>{t.preventDefault();const i=t.currentTarget.getAttribute("data-book-id"),s="epube-book."+i;await localforage.getItem(s)?this.remove(i,()=>{this.updateOfflinePrompt(t.currentTarget)}):this.get(i,()=>{this.updateOfflinePrompt(t.currentTarget)})})),this.updateIndexPagination(a)})}updateIndexPagination(e){const a=$(".pager .previous"),o=$(".pager .next"),t=$(".pager .pager-info"),i=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset-60)}),s=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset+60)});this.index_offset>0?(a.removeClass("disabled"),a.find("a").attr("href","?"+i.toString())):(a.addClass("disabled"),a.find("a").attr("href","#")),e.books&&e.books.length>=60?(o.removeClass("disabled"),o.find("a").attr("href","?"+s.toString())):(o.addClass("disabled"),o.find("a").attr("href","#"));const n=e.limit||60,l=e.total||0,r=Math.floor(this.index_offset/n)+1,c=n>0?Math.ceil(l/n):1;t.find("span").text(`Page ${r} of ${c}`)}escapeHtml(e){if(!e)return"";const a=document.createElement("div");return a.appendChild(document.createTextNode(e)),a.innerHTML}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateOfflineList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(a,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateOfflineList()}}populateOfflineList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const a=$("#books_container");a.html(""),localforage.iterate((o,t)=>{t.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(t),localforage.getItem(t+".cover"),localforage.getItem(t+".lastread"),localforage.getItem(t+".book")]).then(i=>{if(i[0]&&i[3]){const s=i[0];if(e&&!(s.series_name&&s.series_name.toLowerCase().match(e)||s.title&&s.title.toLowerCase().match(e)||s.author_sort&&s.author_sort.toLowerCase().match(e)))return;let n="";i&&i[1]&&(n=URL.createObjectURL(i[1]));let l=!1,r=!1;const c=i[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const d=r?"read":"",f=l?"in_progress":"",u=s.series_name?`<div><a class="series_link" href="#">${s.series_name+" ["+s.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${s.id}"> - <a class="thumbnail ${d}" href="read.html?id=${s.epub_id}&b=${s.id}"> - <img style="display : none"> - </a> - <div class="caption"> - <div><a class="${f}" href="read.html?id=${s.epub_id}&b=${s.id}">${s.title}</a></div> - <div><a class="author_link" href="#">${s.author_sort}</a></div> - ${u} - </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="#" class="offline_summary" data-book-id="${s.id}">Summary</a></li> - <li><a href="#" class="remove_offline_data" data-book-id="${s.id}">Remove offline data</a></li> - </ul> - </div> - </div>`);$(h).find(".offline_summary").on("click",m=>{m.preventDefault(),this.showSummary(m.currentTarget)}),$(h).find(".remove_offline_data").on("click",m=>{m.preventDefault(),this.removeFromList(m.currentTarget)}),n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",s.series_name+" ["+s.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(s.series_name)),h.find(".author_link").attr("title",s.author_sort).attr("href","offline.html?query="+encodeURIComponent(s.author_sort)),a.append(h)}})})}}const DEFAULT_FONT_SIZE=16,DEFAULT_FONT_FAMILY="Arial",DEFAULT_LINE_HEIGHT=140,MIN_LENGTH_TO_JUSTIFY=32,LOCATION_DIVISOR=10,PAGE_RESET_PROGRESS=-1;class ReaderClass extends AppCommon{csrf_token="";last_stored_cfi="";startup_finished=!1;open_last_read_when_displayed=!0;hyphenate={};_prevent_lastread_timeout;_prevent_lastread;version="v1780151390364";book;_swipeState={active:!1,startX:0,startY:0,startTime:0,direction:null};_swipeConfig={minDistance:50,velocityThreshold:.3,verticalDistanceThreshold:80};constructor(){super(),this.book=new ePub.Book,this.loader=new ReaderLoader}onTouchStart(e){const a=e.touches[0]||e.changedTouches[0];this._swipeState={active:!0,startX:a.clientX,startY:a.clientY,startTime:Date.now(),direction:e.target.id=="right"?"left":"right"}}onTouchEnd(e){if(!this._swipeState.active)return;const o=(e.changedTouches[0]||e.changedTouches[e.changedTouches.length-1]).clientX-this._swipeState.startX,t=Date.now()-this._swipeState.startTime,i=t>0?Math.abs(o)/t:0,s=Math.abs(o)>=this._swipeConfig.minDistance&&i>=this._swipeConfig.velocityThreshold,n=this._swipeState.direction=="left",l=n?o<0:o>0;s&&l&&(e.preventDefault(),e.stopPropagation(),n?this.nextPage():this.prevPage())}onTouchMove(e){if(!this._swipeState.active)return;const a=e.touches[0]||e.changedTouches[0];if(Math.abs(a.clientY-this._swipeState.startY)>this._swipeConfig.verticalDistanceThreshold){this._swipeState.active=!1;return}}async init(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),$(document).on("keyup",a=>{this.hotkeyHandler(a)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",a=>{this.openPrevious(a.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),$("#left, #right").on("touchstart",a=>{this.onTouchStart(a)}),$("#left, #right").on("touchmove",a=>{this.onTouchMove(a)}),$("#left, #right").on("touchend",a=>{this.onTouchEnd(a)});const e=await this.loader.init(this);console.log("[init] load failed",e),e?(this.applyTheme(),$(".loading-message").text("Resource loader failed to initialize.")):this.initSecondStage()}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(e){if(console.log("onOfflineModeChanged",e),!e&&this.book){console.log("we're online, storing lastread");const a=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(a)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:a,timestamp:new Date().getTime()},function(){}).fail(function(t){t&&t.status==401&&(window.location.href="index.php")})}}async initSecondStage(){if(typeof EpubeApp<"u"?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme(),!await localforage.getItem(this.cacheId())){const i=this.urlParam("b");console.log("requesting bookinfo for book",i);try{const s=await $.post("backend.php",{op:"getinfo",id:i});if(s.has_cover){const n=await fetch("backend.php?op=cover&id="+i);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),s),console.log("bookinfo saved")}catch(s){const n=s;console.error(n),$(".loading-message").html(`Unable to load book info.<br/><small>${n.responseText}</small>`);return}}console.log("trying to load book...");let a=await localforage.getItem(this.cacheId("book"));if(!a){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const i=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(i.ok)if(a=await i.blob(),a)await localforage.setItem(this.cacheId("book"),a),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: ${i.status}`);return}}const o=new FileReader,t=this;o.onload=function(){try{t.openBookData(this.result)}catch(i){console.error(i),$(".loading-message").html("Unable to load book blob: "+i)}},o.onerror=i=>{console.log("filereader error",i),$(".loading-message").html("Unable to open book.<br/><small>"+i+"</small>")},o.readAsArrayBuffer(a)}async openBookData(e){try{await this.book.open(e)}catch(t){console.error(t),$(".loading-message").html(`Unable to open book.<br/><small>${t instanceof Error?t.message:t}</small>`);return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const a=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(a.currentLocation().start.location/LOCATION_DIVISOR),i=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),s=prompt("Jump to location [1-"+i+"]",String(t));s&&await a.display(this.book.locations._locations[parseInt(s)*LOCATION_DIVISOR])}),await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(this.book,a),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await a.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const a=await localforage.getItem(this.cacheId());let o,t;if(a)o=a.title,t=a.author_sort;else{const i=e.packaging.metadata;o=i.title,t=i.creator}document.title=o+" \u2013 "+t+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+t),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let a=await localforage.getItem(this.cacheId("locations"));if(a&&typeof a[0]=="string"){console.log("loading local locations...");try{await e.locations.load(a);return}catch(t){console.warn(t)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const t=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(t.ok){console.log("got locations from server");try{a=await t.json()}catch(i){console.warn(i)}if(a&&typeof a[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),a);try{e.locations.load(a);return}catch(i){console.warn(i)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;a=await e.locations.generate(100,t=>{if(o||(o=t.length()),o>0){const i=Math.round((1-t.length()/o)*100);$(".loading-message").html(`Preparing locations (${i}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(a),total:100}),await localforage.setItem(this.cacheId("locations"),a)}initRenditionHooks(e,a){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),a.hooks.content.register(async o=>{o.on("linkClicked",n=>{console.log("linkClicked",n),this.blockLastReadUpdate(),n.indexOf("://")==-1&&($(".prev_location_btn").attr("data-location-cfi",a.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async n=>{if(this.isOnline()){const l=await e.getRange(n),r=l.endContainer.data.substring(l.startOffset,l.endOffset);console.log("selected",n,r),r.match(/^[\w]+$/)&&this.lookupWord(r,()=>{typeof EpubeApp<"u"&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const t=window.location.href.match(/^.*\//),i=t?t[0]:window.location.href;$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(i))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[i+"dist/reader_iframe.min.css"]));const s=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+s),console.log("contents",o),$(o.window).on("click tap",n=>{if(n.button==0){if($(".modal").is(":visible"))return;typeof EpubeApp<"u"?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async n=>{await localforage.getItem("epube.enable-wheel")&&((n.originalEvent?.deltaY??0)>0?this.nextPage():(n.originalEvent?.deltaY??0)<0&&this.prevPage())})}),a.on("keyup",o=>{this.hotkeyHandler(o)}),a.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),a.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=a.currentLocation();if(o.start){const t=e.canonical(o.start.href);let i={};$.each(this.flattenToc(e),function(s,n){if(e.spine.get(n.href).canonical==t){i=n;return}}),i&&i.label&&$(".chapter_title").html(i.label.trim()+" | "),this.generateTocBar(e,this.flattenToc(e))}}catch(o){console.warn(o)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),a.on("displayed",function(){console.log("rendition displayed")}),a.on("relocated",o=>this.onRelocated(e,o))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const e=await localforage.getItem(this.cacheId("lastread"));e&&e.cfi&&$(".lastread_input").val(e.page+"%").attr("title",`[local] ${e.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()}),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title",`[remote] ${t.cfi}`)}),$(".font_family").off("change").on("change",t=>{this.onFontChanged(t.target)}),$(".font_size").off("change").on("change",t=>{this.onTextSizeChanged(t.target)}),$(".line_height").off("change").on("change",t=>{this.onLineHeightChanged(t.target)}),$(".theme_name").off("change").on("change",t=>{this.onThemeChanged(t.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",t=>{localforage.setItem("epube.enable-hyphens",t.target.checked),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",t=>{localforage.setItem("epube.enable-wheel",t.target.checked)}),typeof EpubeApp<"u"?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",t=>{localforage.setItem("epube.keep-ui-visible",t.target.checked)}),$(".last-mod-timestamp").html(`${this.version} - (${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 a=$(".font_size").html("");for(let t=10;t<=32;t++){const i=$("<option>").val(t).html(t+" px");a.append(i)}a.val(await localforage.getItem("epube.fontSize")||DEFAULT_FONT_SIZE);const o=$(".line_height").html("");for(let t=100;t<=220;t+=10){const i=$("<option>").val(t).html(t+"%");o.append(i)}o.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)}),$(".dict_search_btn").on("click",function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})}initToc(e){const a=this;function o(i){try{const s=e.spine.get(i).cfiBase,n=e.locations._locations.find(function(l){return l.indexOf(s)!=-1});return Math.round(a.book.locations.locationFromCfi(n)/LOCATION_DIVISOR)}catch(s){console.warn(s)}return""}function t(i,s,n){if(n==3)return!1;if(i.subitems){const l=$("<ul class='toc_sublist list-unstyled'>");$.each(i.subitems,function(r,c){const d=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(c.href)+"</b>"+c.label).attr("data-href",c.href).click(function(){e.rendition.display(d.attr("data-href"))});l.append($("<li>").append(d)),t(c,l,n+1)}),s.append(l)}}$("#toc-modal").on("shown.bs.modal",function(){const i=e.navigation.toc,s=$(".toc_list");s.html(""),$.each(i,function(n,l){try{const r=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(l.href)+"</b>"+l.label).attr("data-href",l.href).click(function(){e.rendition.display(r.attr("data-href"))});s.append($("<li>").append(r)),t(l,s,0)}catch(r){console.warn(r)}}),s.children().length<=1&&(s.html(""),$.each(e.spine.items,function(n,l){const r=$("<a>").attr("href","#").attr("title",l.url).html(`Section ${n+1}`).attr("data-href",l.href).on("click",()=>{e.rendition.display(r.attr("data-href"))});s.append($("<li>").append(r))}))})}cleanupEmbeddedStyles(e){$(e).find("p").filter((a,o)=>$(o).text().length>=MIN_LENGTH_TO_JUSTIFY?o:null).css("text-align","justify"),$(e).find("html").attr("class",""),$(e).find("pre").css("white-space","pre-wrap"),$(e).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",""),$(e).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),typeof this.hyphenate.en<"u"&&$(e).find("p, div").each((a,o)=>{const t=$(o);t.html(this.hyphenate.en(t.html())),t.html(this.hyphenate.ru(t.html()))})}generateFontsCss(e){return` - /** Calibri */ - - @font-face { - font-family: 'Calibri'; - src: url(${this.loader._res_data[e+"lib/fonts/calibriz.ttf"]}); - font-style: italic; - font-weight : 700; - } - - @font-face { - font-family: 'Calibri'; - src: url(${this.loader._res_data[e+"lib/fonts/calibrib.ttf"]}); - font-style: normal; - font-weight : 700; - } - - @font-face { - font-family: 'Calibri'; - src: url(${this.loader._res_data[e+"lib/fonts/calibrii.ttf"]}); - font-style: italic; - font-weight : 400; - } - - @font-face { - font-family: 'Calibri'; - src: url(${this.loader._res_data[e+"lib/fonts/calibri.ttf"]}); - font-style: normal; - font-weight : 400; - } - - /** Cambria */ - - @font-face { - font-family: 'Cambria'; - src: url(${this.loader._res_data[e+"lib/fonts/cambriab.ttf"]}); - font-style: normal; - font-weight : 700; - } - - @font-face { - font-family: 'Cambria'; - src: url(${this.loader._res_data[e+"lib/fonts/cambriaz.ttf"]}); - font-style: italic; - font-weight : 700; - } - - @font-face { - font-family: 'Cambria'; - src: url(${this.loader._res_data[e+"lib/fonts/cambriai.ttf"]}); - font-style: italic; - font-weight : 400; - } - - @font-face { - font-family: 'Cambria'; - src: url(${this.loader._res_data[e+"lib/fonts/cambria.ttf"]}); - font-style: normal; - font-weight : 400; - } - - /** Caecilia */ - - @font-face { - font-family: Caecilia; - src: url(${this.loader._res_data[e+"lib/fonts/caecilia.ttf"]}); - font-weight : normal; - } - - @font-face { - font-family: Caecilia; - src: url(${this.loader._res_data[e+"lib/fonts/caeciliab.ttf"]}); - font-weight : bold; - } - - @font-face { - font-family: Caecilia; - src: url(${this.loader._res_data[e+"lib/fonts/caeciliai.ttf"]}); - font-style : italic; - } - - /** Palatino */ - - @font-face { - font-family: 'Palatino'; - src: url(${this.loader._res_data[e+"lib/fonts/palab.ttf"]}); - font-style: normal; - font-weight : 700; - } - - @font-face { - font-family: 'Palatino'; - src: url(${this.loader._res_data[e+"lib/fonts/palabi.ttf"]}); - font-style: italic; - font-weight : 700; - } - - @font-face { - font-family: 'Palatino'; - src: url(${this.loader._res_data[e+"lib/fonts/palai.ttf"]}); - font-style: italic; - font-weight : 400; - } - - @font-face { - font-family: 'Palatino'; - src: url(${this.loader._res_data[e+"lib/fonts/pala.ttf"]}); - font-style: normal; - font-weight : 400; - } - - /** Consolas */ - - @font-face { - font-family: 'Consolas'; - src: url(${this.loader._res_data[e+"lib/fonts/consolab.ttf"]}); - font-style: normal; - font-weight : 700; - } - - @font-face { - font-family: 'Consolas'; - src: url(${this.loader._res_data[e+"lib/fonts/consolaz.ttf"]}); - font-style: italic; - font-weight : 700; - } - - @font-face { - font-family: 'Consolas'; - src: url(${this.loader._res_data[e+"lib/fonts/consolai.ttf"]}); - font-style: italic; - font-weight : 400; - } - - @font-face { - font-family: 'Consolas'; - src: url(${this.loader._res_data[e+"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[e+"lib/fonts/IBMPlexMono-Bold.otf"]}); - font-style: normal; - font-weight : 700; - } - - @font-face { - font-family: 'IBM Plex Mono'; - src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-BoldItalic.otf"]}); - font-style: italic; - font-weight : 700; - } - - @font-face { - font-family: 'IBM Plex Mono'; - src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-TextItalic.otf"]}); - font-style: italic; - font-weight : 400; - } - - @font-face { - font-family: 'IBM Plex Mono'; - src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-Text.otf"]}); - font-style: normal; - font-weight : 400; - } - `}flattenTocSubItems(e,a){let o=[];return a==3?!1:(e.subitems&&$.each(e.subitems,(t,i)=>{i._nest=a,o.push(i),o=o.concat(this.flattenTocSubItems(i,a+1))}),o)}flattenToc(e){if(this._flattened_toc)return this._flattened_toc;{let a=[];return $.each(e.navigation.toc,(o,t)=>{t._nest=0,a.push(t),a=a.concat(this.flattenTocSubItems(t,1))}),this._flattened_toc=a,a}}generateTocBar(e,a){$(".spacer").html(""),$.each(a,function(o,t){try{const i=e.spine.get(t.href).cfiBase,s=e.locations._locations.find(function(n){return n.indexOf(i)!=-1});if(s){const n=Math.round(e.locations.percentageFromCfi(s)*100);$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",t._nest).css("left",n+"%").css("_width",3-t._nest+"px").attr("title",t.label))}}catch(i){console.warn(i)}}),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(e,e.rendition.currentLocation())}updateTocBarPosition(e,a){const o=Math.round(a.start.location/e.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let e=await localforage.getItem("epube.fontSize"),a=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");e=e?e+"px":DEFAULT_FONT_SIZE+"px",a=a||DEFAULT_FONT_FAMILY,o=o?o+"%":DEFAULT_LINE_HEIGHT+"%",console.log("style",a,e,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":e,"font-family":"'"+a+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let t=await localforage.getItem("epube.theme")||"default";console.log("called for theme",t),t=="default"&&typeof EpubeApp<"u"&&EpubeApp.isNightMode()&&(t="night"),console.log("setting main UI theme",t),$("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("epube-reader theme-"+t).attr("data-is-loading","false"),typeof EpubeApp<"u"&&window.setTimeout(function(){const i=document.querySelector("body");let n=(i?window.getComputedStyle(i,null).getPropertyValue("background-color"):"").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);n&&(console.log("sending bgcolor",n),EpubeApp.setStatusBarColor(parseInt(n[1]),parseInt(n[2]),parseInt(n[3])));const l=document.querySelector(".header .title");n=(l?window.getComputedStyle(l,null).getPropertyValue("color"):"").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),n&&(console.log("sending accent_color",n),EpubeApp.setAccentColor(parseInt(n[1]),parseInt(n[2]),parseInt(n[3])))},250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(i=>{console.log(`applying styles and theme ${t} to `,i),i.css("font-size",e),i.css("font-family","'"+a+"'"),i.css("line-height",o),i.css("text-align","justify"),$(i.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+t)})}hotkeyHandler(e){try{if($(".modal").is(":visible"))return;(e.which==39||e.which==32||e.which==34)&&(e.preventDefault(),this.nextPage()),(e.which==37||e.which==33)&&(e.preventDefault(),this.prevPage()),e.which==27&&(e.preventDefault(),this.showUI(!0))}catch(a){console.warn(a)}}resizeSideColumns(){let e=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(a=>{const o=a.document.querySelector("body");o&&(e+=parseInt(a.window.getComputedStyle(o).getPropertyValue("padding-left")))}),console.log(`resizing side columns to ${e} px`),$("#left, #right").width(e)}async markAsRead(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const e=100,a=this.book.locations.cfiFromPercentage(1),o=new Date().getTime();if(this.isOnline()){const t=await $.post("backend.php",{op:"storelastread",page:e,cfi:a,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(t.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:a,page:e,total:e,timestamp:o}),await this.openLastRead()}}async close(){const a=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(a)*100),t=100,i=new Date().getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:a,page:o,total:t,timestamp:i}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:a,timestamp:i},()=>{window.location.href=this.urlParam("rt")?"index.php?mode="+this.urlParam("rt"):"index.php"}).fail(()=>{window.location.href="index.php"}):window.location.href="index.php"}cacheId(e){return"epube-book."+this.urlParam("b")+(e?"."+e:"")}showUI(e){e?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()}toggleUI(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()}async lookupWord(e,a,o){o&&(e=$(o).val()),e=e.replace(//g,""),console.log("lookupWord",e),$(".dict_result").html("Loading, please wait..."),$("#dict-modal").modal("show");try{const t=await $.post("backend.php",{op:"define",word:e});t&&($(".dict_result").html(t.result.join("<br/>")),$(".dict_query").val(e),a&&a())}catch(t){const i=t;console.error(i),$(".dict_result").html(`Network error while looking up word: ${i.responseText}.`)}}async search(){const e=$(".search_input").val(),a=$(".search_results");if(a.html(""),!!e){a.html("<li>Loading, please wait...</li>");try{const o=await Promise.all(this.book.spine.spineItems.map(async t=>{try{return await t.load(this.book.load.bind(this.book)),await t.find(`${e}`)}finally{await t.unload()}}));a.html(""),o.flat().forEach(t=>{console.log("sr",t);const i=$("<a>").attr("href","#").html(`<b class='pull-right'>${this.book.locations.locationFromCfi(t.cfi)}</b>${t.excerpt}`).attr("data-cfi",t.cfi).on("click",()=>{this.book.rendition.display($(i).attr("data-cfi"))});a.append($("<li>").append(i))})}catch(o){console.error("Search failed:",o)}}}nextPage(){this.book.rendition.next(),typeof EpubeApp<"u"?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(e=>{e||this.showUI(!1)})}prevPage(){this.book.rendition.prev(),typeof EpubeApp<"u"?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(e=>{e||this.showUI(!1)})}async openPrevious(e){const a=$(e).attr("data-location-cfi");a&&await this.book.rendition.display(a),$(e).fadeOut()}blockLastReadUpdate(){console.log("blocking last read updates..."),this._prevent_lastread_timeout&&window.clearTimeout(this._prevent_lastread_timeout),this._prevent_lastread_timeout=window.setTimeout(()=>{this._prevent_lastread=!1,this._prevent_lastread_timeout=!1,console.log("unblocked last read updates")},1e3),this._prevent_lastread=!0}async onRelocated(e,a){if(e.locations.length()==0)return;const o=a.start.cfi,t=Math.round(e.locations.percentageFromCfi(o)*100);$("#cur_page").text(Math.floor(a.start.location/LOCATION_DIVISOR)),$("#total_pages").text(Math.floor(e.locations.length()/LOCATION_DIVISOR)),$("#page_pct").text(Math.round(e.locations.percentageFromCfi(o)*100)+"%"),this.updateTocBarPosition(e,a);const i=a.start.displayed;if(i&&($("#chapter_cur_page").text(i.page),$("#chapter_total_pages").text(i.total),i.total>0&&$("#chapter_pct").text(Math.round(i.page/i.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const s=new Date().getTime();console.log("storing lastread",t,o,s),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:t,total:100,timestamp:s}),this.isOnline()&&(console.log("updating remote lastread",o),this.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:t,cfi:o,timestamp:s}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const e=this.book.locations.length(),a=new Date().getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:PAGE_RESET_PROGRESS,cfi:"",id:this.urlParam("id"),timestamp:a}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:e,timestamp:a}),await this.book.rendition.display(this.book.locations.cfiFromPercentage(0)),$(".lastread_input").val("0%")}}async resetLocations(){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()}),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\u2026"),$("#settings-modal").modal("hide");const e=this.book.rendition;if(!e){console.error("no rendition to work on");return}let a=!1;const o=await localforage.getItem(this.cacheId("lastread"))||{};if(console.log("got local lastread",o),this.isOnline())try{const t=await $.post("backend.php",{op:"getlastread",id:this.urlParam("id")});console.log("got remote lastread",t),t&&t.cfi&&o.cfi!=t.cfi&&t.page>=(o.page||0)&&(console.log(`using remote lastread cfi ${t.cfi}: cfi is different and remote pct ${t.page}% is further than local pct ${o.page}%`),await localforage.setItem(this.cacheId("lastread"),{cfi:t.cfi,page:t.page,total:t.total,timestamp:t.timestamp}),a=await this.moveToCfiVerify(e,t.cfi))}catch(t){console.log("unable to get remote lastread, continuing..."),console.warn(t)}if(!a&&o&&o.cfi){console.log(`using local lastread cfi: ${o.cfi}`);try{await this.moveToCfiVerify(e,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()}calculateCfiDelta(e,a){if(!e||!a)return-1;const o=new ePub.CFI(e),t=new ePub.CFI(a);if(console.log("calculateCfiDelta",o,t),o.path.steps.length!=t.path.steps.length)return-1;let i=0;for(let s=0;s<o.path.steps.length;s++){if(o.path.steps[s].type!=t.path.steps[s].type||o.path.steps[s].id!=t.path.steps[s].id)return-1;o.path.steps[s].id===null&&o.path.steps[s].type==="element"&&(i+=Math.abs(o.path.steps[s].index-t.path.steps[s].index))}return i}async moveToCfiVerify(e,a,o=5,t=5){for(let i=1;i<o;i++){this.blockLastReadUpdate(),console.log(`trying to open ${a}: attempt ${i} of ${o}...`),await e.display(a);let s;try{s=e.currentLocation().start.cfi}catch(n){console.warn("location not yet available, will retry:",n)}try{const n=this.calculateCfiDelta(a,s??null);if(console.log(`opened cfi ${s} expected ${a}; delta: ${n}`),s==a||n!=-1&&n<=t)return console.log("cfi move verified!"),!0}catch(n){console.warn("exception while parsing cfi, will retry: ",n)}}return!1}async onThemeChanged(e){const a=$(e).val();await localforage.setItem("epube.theme",a),this.applyTheme()}async onLineHeightChanged(e){const a=$(e).val();await localforage.setItem("epube.lineHeight",a),this.applyTheme()}async onTextSizeChanged(e){const a=$(e).val();await localforage.setItem("epube.fontSize",a),this.applyTheme()}async onFontChanged(e){const a=$(e).val();await localforage.setItem("epube.fontFamily",a),this.applyTheme()}}class ReaderLoader{_res_data={};async init(e){const a=await e.getActiveCacheName();console.log("loader init for cache:",a),typeof EpubeApp<"u"&&$("body").addClass("epube-app");const o=await caches.open(a),t=await o.keys(),i=[];let s=!1;for(const n of t){if(n.url.match(/backend\.php/))continue;const l=await o.match(n.url);if(!l){console.warn("[loader] cache miss for",n.url),s=!0;continue}const r=new URL(n.url);r.searchParams.delete("ts");const c=r.toString();let d;n.url.match(/\.(ttf|otf)$/)?d=l.blob().then(f=>{this._res_data[c]=URL.createObjectURL(f)}):d=l.text().then(f=>{this._res_data[c]=f}),i.push(d.catch(f=>{console.warn("[loader] failed to read",n.url,f),s=!0}))}return await Promise.allSettled(i),Object.keys(this._res_data).length===0&&(s=!0),console.log("[loader] loaded",Object.keys(this._res_data).length,"resources, failed:",s),s}} +"use strict";function setupCsrfPrefilter(p){console.log("setting prefilter for token",p),$.ajaxPrefilter((e,a,o)=>{if(a.type!=="post"||e.type!=="post")return;const t=typeof a.data;t=="object"?e.data=$.param($.extend(a.data,{csrf_token:p})):t=="string"&&(e.data=a.data+"&csrf_token="+encodeURIComponent(p)),console.log(">>>",e)})}class Cookie{static set(e,a,o){const t=new Date;t.setTime(t.getTime()+o*1e3);const i="expires="+t.toUTCString();document.cookie=e+"="+encodeURIComponent(a)+"; "+i}static get(e){e=e+"=";const a=document.cookie.split(";");for(let o=0;o<a.length;o++){let t=a[o];for(;t.charAt(0)==" ";)t=t.substring(1);if(t.indexOf(e)==0)return decodeURIComponent(t.substring(e.length,t.length))}return""}static delete(e){const a="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+a}}class AppCommon{urlParam(e){try{const a=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return a&&decodeURIComponent(a[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}async getActiveCacheName(){const a=(await navigator.serviceWorker.ready).active;return a?new Promise(o=>{const t=new MessageChannel;t.port1.onmessage=i=>{o(i.data.cacheName)},a.postMessage({type:"GET_CACHE_NAME"},[t.port2])}):null}async getActiveCacheVersion(){const a=(await navigator.serviceWorker.ready).active;return a?new Promise(o=>{const t=new MessageChannel;t.port1.onmessage=i=>{o(i.data.cacheName)},a.postMessage({type:"GET_CACHE_VERSION"},[t.port2])}):null}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";index_query="";index_offset=0;cached_urls=[];version="v1781200872189";cosmeticVersion="v26.06-24187f2";csrf_token="";async init(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),this.urlParam("mode")=="favorites"?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),this.initCommonEventHandlers(),this.populateList(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",()=>{}),this.showCovers(),this.updateOfflinePrompts()):$(".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()}),$(".cosmetic_version").attr("title",this.cosmeticVersion)}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const a=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:a}),t=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").text(o.title),$("#summary-modal .book-summary").html(t),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+a),t=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").text(o.title),$("#summary-modal .book-summary").html(t),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,a)=>{const o=$(a);if(o.attr("data-cover-link")){const t=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),t.attr("src",null)}).attr("src",o.attr("data-cover-link")??"")}})}toggleFavorite(e){const a=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:a},o=>{if(o){let t="[Error]";o.status==0?t="Add to favorites":o.status==1&&(t="Remove from favorites"),$(e).html(t).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+a).remove()}}),!1}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(a,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const a=e.getAttribute("data-book-id"),o="epube-book."+a;await localforage.getItem(o)?(e.onclick=()=>(this.remove(a,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(a,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}async offlineInit(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode(),this.initCommonEventHandlers();const e=this.urlParam("query");e&&$(".search_query").val(e),this.populateOfflineList()}get(e,a){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const t="epube-book."+e;localforage.setItem(t,o).then(i=>{console.log(t+" got data");const s=[];s.push(fetch("backend.php?op=download&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got book"),localforage.setItem(t+".book",n.blob()))})),s.push(fetch("backend.php?op=getpagination&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got pagination"),n.text().then(function(l){localforage.setItem(t+".locations",JSON.parse(l))}))})),s.push(fetch("backend.php?op=getlastread&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got lastread"),n.text().then(function(l){localforage.setItem(t+".lastread",JSON.parse(l))}))})),i.has_cover&&s.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(t+" got cover"),localforage.setItem(t+".cover",n.blob()))})),Promise.all(s).then(()=>{console.log("download done, running callback",a),a(),$(".dl-progress").show().html("Finished downloading <b>"+i.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,a)=>{const o=($(a).attr("id")??"").replace("cell-",""),t=$(a).find(".offline_dropitem")[0]??null;if(o){const i="epube-book."+o;localforage.getItem(i).then(s=>{s||this.get(o,()=>{this.updateOfflinePrompt(t)})})}})}removeFromList(e){const a=e.getAttribute("data-book-id");this.remove(a,()=>{$("#cell-"+a).remove()})}remove(e,a){if(confirm("Remove download?")){const o="epube-book."+e,t=[];console.log("offline remove: "+e),localforage.iterate(function(i,s){s.match(o)&&t.push(localforage.removeItem(s))}),Promise.all(t).then(()=>{console.log("remove done, running callback",a),window.setTimeout(()=>{a()},250)})}}populateList(){const e=new URLSearchParams({op:"list",mode:this.index_mode,query:this.index_query,offset:String(this.index_offset),limit:String(60)});$.get("backend.php?"+e.toString()).done(a=>{const o=$("#books_container");o.html(""),a.books&&a.books.length>0&&(a.books.forEach(t=>{const i=t.is_read?"read":"",s=t.in_progress?"in_progress":"",n=t.is_fav?"1":"0",l=t.is_fav?"Remove from favorites":"Add to favorites",r=t.series_name?`<div><a title="${this.escapeHtml(t.series_full)}" href="${this.escapeHtml(t.series_link)}">${this.escapeHtml(t.series_full)}</a></div>`:"",c=t.author_sort?`?${new URLSearchParams({query:t.author_sort}).toString()}`:"",d=t.download_formats.map(u=>{const h=u.format==="EPUB"?"label-success":"label-primary";return`<li><a target="_blank" href="backend.php?op=download&id=${u.id}">Download: <span class="label ${h}">${u.format}</span></a></li>`}).join(""),f=$(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${t.id}"> + ${t.read_link?`<a class="thumbnail ${i}" href="${t.read_link}">`:`<span class="thumbnail ${i}">`} + <img style="display : none" data-book-id="${t.id}" data-cover-link="${t.cover_link}"> + ${t.read_link?"</a>":"</span>"} + <div class="caption"> + <div title="${this.escapeHtml(t.title)}" class="${s}"> + ${t.read_link?`<a href="${t.read_link}">${this.escapeHtml(t.title)}</a>`:this.escapeHtml(t.title)} + </div> + ${r} + <div><a title="${this.escapeHtml(t.author_sort)}" href="${this.escapeHtml(c)}">${this.escapeHtml(t.author_sort)}</a></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"> + <li><a href="#" class="summary_link" data-book-id="${t.id}">Summary</a></li> + <li><a href="#" class="fav_item" data-is-fav="${n}" data-book-id="${t.id}">${l}</a></li> + ${t.epub_id?`<li><a href="#" data-book-id="${t.id}" class="offline_dropitem"></a></li><li class="divider"></li>`:""} + ${d} + </ul> + </div> + </div>`);o.append(f)}),this.showCovers(),this.updateOfflinePrompts(),$(".summary_link").on("click",t=>{t.preventDefault(),this.showSummary(t.currentTarget)}),$(".fav_item").on("click",t=>{t.preventDefault(),this.toggleFavorite(t.currentTarget)}),$(".offline_dropitem").on("click",async t=>{t.preventDefault();const i=t.currentTarget.getAttribute("data-book-id"),s="epube-book."+i;await localforage.getItem(s)?this.remove(i,()=>{this.updateOfflinePrompt(t.currentTarget)}):this.get(i,()=>{this.updateOfflinePrompt(t.currentTarget)})})),this.updateIndexPagination(a)})}updateIndexPagination(e){const a=$(".pager .previous"),o=$(".pager .next"),t=$(".pager .pager-info"),i=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset-60)}),s=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset+60)});this.index_offset>0?(a.removeClass("disabled"),a.find("a").attr("href","?"+i.toString())):(a.addClass("disabled"),a.find("a").attr("href","#")),e.books&&e.books.length>=60?(o.removeClass("disabled"),o.find("a").attr("href","?"+s.toString())):(o.addClass("disabled"),o.find("a").attr("href","#"));const n=e.limit||60,l=e.total||0,r=Math.floor(this.index_offset/n)+1,c=n>0?Math.ceil(l/n):1;t.find("span").text(`Page ${r} of ${c}`)}escapeHtml(e){if(!e)return"";const a=document.createElement("div");return a.appendChild(document.createTextNode(e)),a.innerHTML}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateOfflineList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(a,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateOfflineList()}}populateOfflineList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const a=$("#books_container");a.html(""),localforage.iterate((o,t)=>{t.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(t),localforage.getItem(t+".cover"),localforage.getItem(t+".lastread"),localforage.getItem(t+".book")]).then(i=>{if(i[0]&&i[3]){const s=i[0];if(e&&!(s.series_name&&s.series_name.toLowerCase().match(e)||s.title&&s.title.toLowerCase().match(e)||s.author_sort&&s.author_sort.toLowerCase().match(e)))return;let n="";i&&i[1]&&(n=URL.createObjectURL(i[1]));let l=!1,r=!1;const c=i[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const d=r?"read":"",f=l?"in_progress":"",u=s.series_name?`<div><a class="series_link" href="#">${s.series_name+" ["+s.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${s.id}"> + <a class="thumbnail ${d}" href="read.html?id=${s.epub_id}&b=${s.id}"> + <img style="display : none"> + </a> + <div class="caption"> + <div><a class="${f}" href="read.html?id=${s.epub_id}&b=${s.id}">${s.title}</a></div> + <div><a class="author_link" href="#">${s.author_sort}</a></div> + ${u} + </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="#" class="offline_summary" data-book-id="${s.id}">Summary</a></li> + <li><a href="#" class="remove_offline_data" data-book-id="${s.id}">Remove offline data</a></li> + </ul> + </div> + </div>`);$(h).find(".offline_summary").on("click",m=>{m.preventDefault(),this.showSummary(m.currentTarget)}),$(h).find(".remove_offline_data").on("click",m=>{m.preventDefault(),this.removeFromList(m.currentTarget)}),n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",s.series_name+" ["+s.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(s.series_name)),h.find(".author_link").attr("title",s.author_sort).attr("href","offline.html?query="+encodeURIComponent(s.author_sort)),a.append(h)}})})}}const DEFAULT_FONT_SIZE=16,DEFAULT_FONT_FAMILY="Arial",DEFAULT_LINE_HEIGHT=140,MIN_LENGTH_TO_JUSTIFY=32,LOCATION_DIVISOR=10,PAGE_RESET_PROGRESS=-1;class ReaderClass extends AppCommon{csrf_token="";last_stored_cfi="";startup_finished=!1;open_last_read_when_displayed=!0;hyphenate={};_prevent_lastread_timeout;_prevent_lastread;version="v1781200872189";cosmeticVersion="v26.06-24187f2";book;_swipeState={active:!1,startX:0,startY:0,startTime:0,direction:null};_swipeConfig={minDistance:50,velocityThreshold:.3,verticalDistanceThreshold:80};constructor(){super(),this.book=new ePub.Book,this.loader=new ReaderLoader}onTouchStart(e){const a=e.touches[0]||e.changedTouches[0];this._swipeState={active:!0,startX:a.clientX,startY:a.clientY,startTime:Date.now(),direction:e.target.id=="right"?"left":"right"}}onTouchEnd(e){if(!this._swipeState.active)return;const o=(e.changedTouches[0]||e.changedTouches[e.changedTouches.length-1]).clientX-this._swipeState.startX,t=Date.now()-this._swipeState.startTime,i=t>0?Math.abs(o)/t:0,s=Math.abs(o)>=this._swipeConfig.minDistance&&i>=this._swipeConfig.velocityThreshold,n=this._swipeState.direction=="left",l=n?o<0:o>0;s&&l&&(e.preventDefault(),e.stopPropagation(),n?this.nextPage():this.prevPage())}onTouchMove(e){if(!this._swipeState.active)return;const a=e.touches[0]||e.changedTouches[0];if(Math.abs(a.clientY-this._swipeState.startY)>this._swipeConfig.verticalDistanceThreshold){this._swipeState.active=!1;return}}async init(){console.log("version",this.version,"current, worker",await this.getActiveCacheVersion()),this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),$(document).on("keyup",a=>{this.hotkeyHandler(a)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",a=>{this.openPrevious(a.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),$("#left, #right").on("touchstart",a=>{this.onTouchStart(a)}),$("#left, #right").on("touchmove",a=>{this.onTouchMove(a)}),$("#left, #right").on("touchend",a=>{this.onTouchEnd(a)});const e=await this.loader.init(this);console.log("[init] load failed",e),e?(this.applyTheme(),$(".loading-message").text("Resource loader failed to initialize.")):this.initSecondStage()}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(e){if(console.log("onOfflineModeChanged",e),!e&&this.book){console.log("we're online, storing lastread");const a=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(a)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:a,timestamp:new Date().getTime()},function(){}).fail(function(t){t&&t.status==401&&(window.location.href="index.php")})}}async initSecondStage(){if(typeof EpubeApp<"u"?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme(),!await localforage.getItem(this.cacheId())){const i=this.urlParam("b");console.log("requesting bookinfo for book",i);try{const s=await $.post("backend.php",{op:"getinfo",id:i});if(s.has_cover){const n=await fetch("backend.php?op=cover&id="+i);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),s),console.log("bookinfo saved")}catch(s){const n=s;console.error(n),$(".loading-message").html(`Unable to load book info.<br/><small>${n.responseText}</small>`);return}}console.log("trying to load book...");let a=await localforage.getItem(this.cacheId("book"));if(!a){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const i=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(i.ok)if(a=await i.blob(),a)await localforage.setItem(this.cacheId("book"),a),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: ${i.status}`);return}}const o=new FileReader,t=this;o.onload=function(){try{t.openBookData(this.result)}catch(i){console.error(i),$(".loading-message").html("Unable to load book blob: "+i)}},o.onerror=i=>{console.log("filereader error",i),$(".loading-message").html("Unable to open book.<br/><small>"+i+"</small>")},o.readAsArrayBuffer(a)}async openBookData(e){try{await this.book.open(e)}catch(t){console.error(t),$(".loading-message").html(`Unable to open book.<br/><small>${t instanceof Error?t.message:t}</small>`);return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const a=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(a.currentLocation().start.location/LOCATION_DIVISOR),i=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),s=prompt("Jump to location [1-"+i+"]",String(t));s&&await a.display(this.book.locations._locations[parseInt(s)*LOCATION_DIVISOR])}),await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(this.book,a),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await a.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const a=await localforage.getItem(this.cacheId());let o,t;if(a)o=a.title,t=a.author_sort;else{const i=e.packaging.metadata;o=i.title,t=i.creator}document.title=o+" \u2013 "+t+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+t),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let a=await localforage.getItem(this.cacheId("locations"));if(a&&typeof a[0]=="string"){console.log("loading local locations...");try{await e.locations.load(a);return}catch(t){console.warn(t)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const t=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(t.ok){console.log("got locations from server");try{a=await t.json()}catch(i){console.warn(i)}if(a&&typeof a[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),a);try{e.locations.load(a);return}catch(i){console.warn(i)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;a=await e.locations.generate(100,t=>{if(o||(o=t.length()),o>0){const i=Math.round((1-t.length()/o)*100);$(".loading-message").html(`Preparing locations (${i}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(a),total:100}),await localforage.setItem(this.cacheId("locations"),a)}initRenditionHooks(e,a){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),a.hooks.content.register(async o=>{o.on("linkClicked",n=>{console.log("linkClicked",n),this.blockLastReadUpdate(),n.indexOf("://")==-1&&($(".prev_location_btn").attr("data-location-cfi",a.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async n=>{if(this.isOnline()){const l=await e.getRange(n),r=l.endContainer.data.substring(l.startOffset,l.endOffset);console.log("selected",n,r),r.match(/^[\w]+$/)&&this.lookupWord(r,()=>{typeof EpubeApp<"u"&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const t=window.location.href.match(/^.*\//),i=t?t[0]:window.location.href;$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(i))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[i+"dist/reader_iframe.min.css"]));const s=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+s),console.log("contents",o),$(o.window).on("click tap",n=>{if(n.button==0){if($(".modal").is(":visible"))return;typeof EpubeApp<"u"?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async n=>{await localforage.getItem("epube.enable-wheel")&&((n.originalEvent?.deltaY??0)>0?this.nextPage():(n.originalEvent?.deltaY??0)<0&&this.prevPage())})}),a.on("keyup",o=>{this.hotkeyHandler(o)}),a.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),a.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=a.currentLocation();if(o.start){const t=e.canonical(o.start.href);let i={};$.each(this.flattenToc(e),function(s,n){if(e.spine.get(n.href).canonical==t){i=n;return}}),i&&i.label&&$(".chapter_title").html(i.label.trim()+" | "),this.generateTocBar(e,this.flattenToc(e))}}catch(o){console.warn(o)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),a.on("displayed",function(){console.log("rendition displayed")}),a.on("relocated",o=>this.onRelocated(e,o))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const e=await localforage.getItem(this.cacheId("lastread"));e&&e.cfi&&$(".lastread_input").val(e.page+"%").attr("title",`[local] ${e.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()}),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title",`[remote] ${t.cfi}`)}),$(".font_family").off("change").on("change",t=>{this.onFontChanged(t.target)}),$(".font_size").off("change").on("change",t=>{this.onTextSizeChanged(t.target)}),$(".line_height").off("change").on("change",t=>{this.onLineHeightChanged(t.target)}),$(".theme_name").off("change").on("change",t=>{this.onThemeChanged(t.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",t=>{localforage.setItem("epube.enable-hyphens",t.target.checked),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",t=>{localforage.setItem("epube.enable-wheel",t.target.checked)}),typeof EpubeApp<"u"?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",t=>{localforage.setItem("epube.keep-ui-visible",t.target.checked)}),$(".last-mod-timestamp").html(`${this.cosmeticVersion} — ${this.version} + (${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 a=$(".font_size").html("");for(let t=10;t<=32;t++){const i=$("<option>").val(t).html(t+" px");a.append(i)}a.val(await localforage.getItem("epube.fontSize")||DEFAULT_FONT_SIZE);const o=$(".line_height").html("");for(let t=100;t<=220;t+=10){const i=$("<option>").val(t).html(t+"%");o.append(i)}o.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)}),$(".dict_search_btn").on("click",function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})}initToc(e){const a=this;function o(i){try{const s=e.spine.get(i).cfiBase,n=e.locations._locations.find(function(l){return l.indexOf(s)!=-1});return Math.round(a.book.locations.locationFromCfi(n)/LOCATION_DIVISOR)}catch(s){console.warn(s)}return""}function t(i,s,n){if(n==3)return!1;if(i.subitems){const l=$("<ul class='toc_sublist list-unstyled'>");$.each(i.subitems,function(r,c){const d=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(c.href)+"</b>"+c.label).attr("data-href",c.href).click(function(){e.rendition.display(d.attr("data-href"))});l.append($("<li>").append(d)),t(c,l,n+1)}),s.append(l)}}$("#toc-modal").on("shown.bs.modal",function(){const i=e.navigation.toc,s=$(".toc_list");s.html(""),$.each(i,function(n,l){try{const r=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(l.href)+"</b>"+l.label).attr("data-href",l.href).click(function(){e.rendition.display(r.attr("data-href"))});s.append($("<li>").append(r)),t(l,s,0)}catch(r){console.warn(r)}}),s.children().length<=1&&(s.html(""),$.each(e.spine.items,function(n,l){const r=$("<a>").attr("href","#").attr("title",l.url).html(`Section ${n+1}`).attr("data-href",l.href).on("click",()=>{e.rendition.display(r.attr("data-href"))});s.append($("<li>").append(r))}))})}cleanupEmbeddedStyles(e){$(e).find("p").filter((a,o)=>$(o).text().length>=MIN_LENGTH_TO_JUSTIFY?o:null).css("text-align","justify"),$(e).find("html").attr("class",""),$(e).find("pre").css("white-space","pre-wrap"),$(e).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",""),$(e).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),typeof this.hyphenate.en<"u"&&$(e).find("p, div").each((a,o)=>{const t=$(o);t.html(this.hyphenate.en(t.html())),t.html(this.hyphenate.ru(t.html()))})}generateFontsCss(e){return` + /** Calibri */ + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[e+"lib/fonts/calibriz.ttf"]}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[e+"lib/fonts/calibrib.ttf"]}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[e+"lib/fonts/calibrii.ttf"]}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[e+"lib/fonts/calibri.ttf"]}); + font-style: normal; + font-weight : 400; + } + + /** Cambria */ + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[e+"lib/fonts/cambriab.ttf"]}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[e+"lib/fonts/cambriaz.ttf"]}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[e+"lib/fonts/cambriai.ttf"]}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[e+"lib/fonts/cambria.ttf"]}); + font-style: normal; + font-weight : 400; + } + + /** Caecilia */ + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[e+"lib/fonts/caecilia.ttf"]}); + font-weight : normal; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[e+"lib/fonts/caeciliab.ttf"]}); + font-weight : bold; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[e+"lib/fonts/caeciliai.ttf"]}); + font-style : italic; + } + + /** Palatino */ + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[e+"lib/fonts/palab.ttf"]}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[e+"lib/fonts/palabi.ttf"]}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[e+"lib/fonts/palai.ttf"]}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[e+"lib/fonts/pala.ttf"]}); + font-style: normal; + font-weight : 400; + } + + /** Consolas */ + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[e+"lib/fonts/consolab.ttf"]}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[e+"lib/fonts/consolaz.ttf"]}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[e+"lib/fonts/consolai.ttf"]}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[e+"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[e+"lib/fonts/IBMPlexMono-Bold.otf"]}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-BoldItalic.otf"]}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-TextItalic.otf"]}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[e+"lib/fonts/IBMPlexMono-Text.otf"]}); + font-style: normal; + font-weight : 400; + } + `}flattenTocSubItems(e,a){let o=[];return a==3?!1:(e.subitems&&$.each(e.subitems,(t,i)=>{i._nest=a,o.push(i),o=o.concat(this.flattenTocSubItems(i,a+1))}),o)}flattenToc(e){if(this._flattened_toc)return this._flattened_toc;{let a=[];return $.each(e.navigation.toc,(o,t)=>{t._nest=0,a.push(t),a=a.concat(this.flattenTocSubItems(t,1))}),this._flattened_toc=a,a}}generateTocBar(e,a){$(".spacer").html(""),$.each(a,function(o,t){try{const i=e.spine.get(t.href).cfiBase,s=e.locations._locations.find(function(n){return n.indexOf(i)!=-1});if(s){const n=Math.round(e.locations.percentageFromCfi(s)*100);$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",t._nest).css("left",n+"%").css("_width",3-t._nest+"px").attr("title",t.label))}}catch(i){console.warn(i)}}),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(e,e.rendition.currentLocation())}updateTocBarPosition(e,a){const o=Math.round(a.start.location/e.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let e=await localforage.getItem("epube.fontSize"),a=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");e=e?e+"px":DEFAULT_FONT_SIZE+"px",a=a||DEFAULT_FONT_FAMILY,o=o?o+"%":DEFAULT_LINE_HEIGHT+"%",console.log("style",a,e,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":e,"font-family":"'"+a+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let t=await localforage.getItem("epube.theme")||"default";console.log("called for theme",t),t=="default"&&typeof EpubeApp<"u"&&EpubeApp.isNightMode()&&(t="night"),console.log("setting main UI theme",t),$("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("epube-reader theme-"+t).attr("data-is-loading","false"),typeof EpubeApp<"u"&&window.setTimeout(function(){const i=document.querySelector("body");let n=(i?window.getComputedStyle(i,null).getPropertyValue("background-color"):"").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);n&&(console.log("sending bgcolor",n),EpubeApp.setStatusBarColor(parseInt(n[1]),parseInt(n[2]),parseInt(n[3])));const l=document.querySelector(".header .title");n=(l?window.getComputedStyle(l,null).getPropertyValue("color"):"").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),n&&(console.log("sending accent_color",n),EpubeApp.setAccentColor(parseInt(n[1]),parseInt(n[2]),parseInt(n[3])))},250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(i=>{console.log(`applying styles and theme ${t} to `,i),i.css("font-size",e),i.css("font-family","'"+a+"'"),i.css("line-height",o),i.css("text-align","justify"),$(i.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+t)})}hotkeyHandler(e){try{if($(".modal").is(":visible"))return;(e.which==39||e.which==32||e.which==34)&&(e.preventDefault(),this.nextPage()),(e.which==37||e.which==33)&&(e.preventDefault(),this.prevPage()),e.which==27&&(e.preventDefault(),this.showUI(!0))}catch(a){console.warn(a)}}resizeSideColumns(){let e=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(a=>{const o=a.document.querySelector("body");o&&(e+=parseInt(a.window.getComputedStyle(o).getPropertyValue("padding-left")))}),console.log(`resizing side columns to ${e} px`),$("#left, #right").width(e)}async markAsRead(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const e=100,a=this.book.locations.cfiFromPercentage(1),o=new Date().getTime();if(this.isOnline()){const t=await $.post("backend.php",{op:"storelastread",page:e,cfi:a,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(t.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:a,page:e,total:e,timestamp:o}),await this.openLastRead()}}async close(){const a=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(a)*100),t=100,i=new Date().getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:a,page:o,total:t,timestamp:i}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:a,timestamp:i},()=>{window.location.href=this.urlParam("rt")?"index.php?mode="+this.urlParam("rt"):"index.php"}).fail(()=>{window.location.href="index.php"}):window.location.href="index.php"}cacheId(e){return"epube-book."+this.urlParam("b")+(e?"."+e:"")}showUI(e){e?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()}toggleUI(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()}async lookupWord(e,a,o){o&&(e=$(o).val()),e=e.replace(//g,""),console.log("lookupWord",e),$(".dict_result").html("Loading, please wait..."),$("#dict-modal").modal("show");try{const t=await $.post("backend.php",{op:"define",word:e});t&&($(".dict_result").html(t.result.join("<br/>")),$(".dict_query").val(e),a&&a())}catch(t){const i=t;console.error(i),$(".dict_result").html(`Network error while looking up word: ${i.responseText}.`)}}async search(){const e=$(".search_input").val(),a=$(".search_results");if(a.html(""),!!e){a.html("<li>Loading, please wait...</li>");try{const o=await Promise.all(this.book.spine.spineItems.map(async t=>{try{return await t.load(this.book.load.bind(this.book)),await t.find(`${e}`)}finally{await t.unload()}}));a.html(""),o.flat().forEach(t=>{console.log("sr",t);const i=$("<a>").attr("href","#").html(`<b class='pull-right'>${this.book.locations.locationFromCfi(t.cfi)}</b>${t.excerpt}`).attr("data-cfi",t.cfi).on("click",()=>{this.book.rendition.display($(i).attr("data-cfi"))});a.append($("<li>").append(i))})}catch(o){console.error("Search failed:",o)}}}nextPage(){this.book.rendition.next(),typeof EpubeApp<"u"?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(e=>{e||this.showUI(!1)})}prevPage(){this.book.rendition.prev(),typeof EpubeApp<"u"?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(e=>{e||this.showUI(!1)})}async openPrevious(e){const a=$(e).attr("data-location-cfi");a&&await this.book.rendition.display(a),$(e).fadeOut()}blockLastReadUpdate(){console.log("blocking last read updates..."),this._prevent_lastread_timeout&&window.clearTimeout(this._prevent_lastread_timeout),this._prevent_lastread_timeout=window.setTimeout(()=>{this._prevent_lastread=!1,this._prevent_lastread_timeout=!1,console.log("unblocked last read updates")},1e3),this._prevent_lastread=!0}async onRelocated(e,a){if(e.locations.length()==0)return;const o=a.start.cfi,t=Math.round(e.locations.percentageFromCfi(o)*100);$("#cur_page").text(Math.floor(a.start.location/LOCATION_DIVISOR)),$("#total_pages").text(Math.floor(e.locations.length()/LOCATION_DIVISOR)),$("#page_pct").text(Math.round(e.locations.percentageFromCfi(o)*100)+"%"),this.updateTocBarPosition(e,a);const i=a.start.displayed;if(i&&($("#chapter_cur_page").text(i.page),$("#chapter_total_pages").text(i.total),i.total>0&&$("#chapter_pct").text(Math.round(i.page/i.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const s=new Date().getTime();console.log("storing lastread",t,o,s),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:t,total:100,timestamp:s}),this.isOnline()&&(console.log("updating remote lastread",o),this.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:t,cfi:o,timestamp:s}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const e=this.book.locations.length(),a=new Date().getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:PAGE_RESET_PROGRESS,cfi:"",id:this.urlParam("id"),timestamp:a}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:e,timestamp:a}),await this.book.rendition.display(this.book.locations.cfiFromPercentage(0)),$(".lastread_input").val("0%")}}async resetLocations(){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()}),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\u2026"),$("#settings-modal").modal("hide");const e=this.book.rendition;if(!e){console.error("no rendition to work on");return}let a=!1;const o=await localforage.getItem(this.cacheId("lastread"))||{};if(console.log("got local lastread",o),this.isOnline())try{const t=await $.post("backend.php",{op:"getlastread",id:this.urlParam("id")});console.log("got remote lastread",t),t&&t.cfi&&o.cfi!=t.cfi&&t.page>=(o.page||0)&&(console.log(`using remote lastread cfi ${t.cfi}: cfi is different and remote pct ${t.page}% is further than local pct ${o.page}%`),await localforage.setItem(this.cacheId("lastread"),{cfi:t.cfi,page:t.page,total:t.total,timestamp:t.timestamp}),a=await this.moveToCfiVerify(e,t.cfi))}catch(t){console.log("unable to get remote lastread, continuing..."),console.warn(t)}if(!a&&o&&o.cfi){console.log(`using local lastread cfi: ${o.cfi}`);try{await this.moveToCfiVerify(e,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()}calculateCfiDelta(e,a){if(!e||!a)return-1;const o=new ePub.CFI(e),t=new ePub.CFI(a);if(console.log("calculateCfiDelta",o,t),o.path.steps.length!=t.path.steps.length)return-1;let i=0;for(let s=0;s<o.path.steps.length;s++){if(o.path.steps[s].type!=t.path.steps[s].type||o.path.steps[s].id!=t.path.steps[s].id)return-1;o.path.steps[s].id===null&&o.path.steps[s].type==="element"&&(i+=Math.abs(o.path.steps[s].index-t.path.steps[s].index))}return i}async moveToCfiVerify(e,a,o=5,t=5){for(let i=1;i<o;i++){this.blockLastReadUpdate(),console.log(`trying to open ${a}: attempt ${i} of ${o}...`),await e.display(a);let s;try{s=e.currentLocation().start.cfi}catch(n){console.warn("location not yet available, will retry:",n)}try{const n=this.calculateCfiDelta(a,s??null);if(console.log(`opened cfi ${s} expected ${a}; delta: ${n}`),s==a||n!=-1&&n<=t)return console.log("cfi move verified!"),!0}catch(n){console.warn("exception while parsing cfi, will retry: ",n)}}return!1}async onThemeChanged(e){const a=$(e).val();await localforage.setItem("epube.theme",a),this.applyTheme()}async onLineHeightChanged(e){const a=$(e).val();await localforage.setItem("epube.lineHeight",a),this.applyTheme()}async onTextSizeChanged(e){const a=$(e).val();await localforage.setItem("epube.fontSize",a),this.applyTheme()}async onFontChanged(e){const a=$(e).val();await localforage.setItem("epube.fontFamily",a),this.applyTheme()}}class ReaderLoader{_res_data={};async init(e){const a=await e.getActiveCacheName();console.log("loader init for cache:",a),typeof EpubeApp<"u"&&$("body").addClass("epube-app");const o=await caches.open(a),t=await o.keys(),i=[];let s=!1;for(const n of t){if(n.url.match(/backend\.php/))continue;const l=await o.match(n.url);if(!l){console.warn("[loader] cache miss for",n.url),s=!0;continue}const r=new URL(n.url);r.searchParams.delete("ts");const c=r.toString();let d;n.url.match(/\.(ttf|otf)$/)?d=l.blob().then(f=>{this._res_data[c]=URL.createObjectURL(f)}):d=l.text().then(f=>{this._res_data[c]=f}),i.push(d.catch(f=>{console.warn("[loader] failed to read",n.url,f),s=!0}))}return await Promise.allSettled(i),Object.keys(this._res_data).length===0&&(s=!0),console.log("[loader] loaded",Object.keys(this._res_data).length,"resources, failed:",s),s}} diff --git a/docs/Config.md b/docs/Config.md new file mode 100644 index 0000000..9e62afb --- /dev/null +++ b/docs/Config.md @@ -0,0 +1,58 @@ +# Config + +Singleton configuration manager. Loads settings from environment variables (prefixed with `EPUBE_`), falls back to built-in defaults, and provides runtime accessors. + +## Type system + +| Constant | Value | Meaning | +|--------------|-------|-----------| +| `T_BOOL` | `1` | Boolean | +| `T_STRING` | `2` | String | +| `T_INT` | `3` | Integer | + +Values are cast on retrieval via `cast_to()`. + +## Configuration keys & defaults + +All keys are class constants. At runtime they are read from environment variables with the `EPUBE_` prefix (e.g. `EPUBE_DB_HOST`). + +| Key | Default | Type | +|--------------------|--------------------|--------| +| `DB_TYPE` | `sqlite` | string | +| `DB_HOST` | `db` | string | +| `DB_USER` | _(empty)_ | string | +| `DB_NAME` | _(empty)_ | string | +| `DB_PASS` | _(empty)_ | string | +| `DB_PORT` | `5432` | string | +| `SCRATCH_DB` | `db/scratch.db` | string | +| `CALIBRE_DB` | _(empty)_ | string | +| `BOOKS_DIR` | _(empty)_ | string | +| `DICT_SERVER` | _(empty)_ | string | +| `SESSION_LIFETIME` | `2592000` (30 days)| int | +| `SESSION_NAME` | `epube_sid` | string | +| `OIDC_NAME` | `OIDC` | string | +| `OIDC_URL` | _(empty)_ | string | +| `OIDC_CLIENT_ID` | _(empty)_ | string | +| `OIDC_CLIENT_SECRET`| _(empty)_ | string | + +## Public API + +| Method | Returns | Description | +|------------------------------|--------------------|-----------------------------------------------| +| `get_instance()` | `Config` | Singleton accessor | +| `get(string $param)` | `int\|bool\|string`| Read a config value (cast to declared type) | +| `add(string $param, string $default, int $type_hint)` | `void` | Register a new config key at runtime | +| `set(string $key, mixed $value)` | `bool` | Write a config value (**test-only**) | +| `reload()` | `void` | Reload all values from environment | +| `get_migrations()` | `Db_Migrations` | Lazily initialised migration handler | +| `is_migration_needed()` | `bool` | Whether pending migrations exist | +| `get_schema_version()` | `int` | Current database schema version | +| `is_server_https()` | `bool` | Detect HTTPS via `$_SERVER` | +| `get_self_url()` | `string` | Base URL of the current request (no trailing slash) | +| `sanity_check()` | `void` | Validate runtime environment; halt with error page or CLI output on failure | + +## Internal notes + +- `__clone()` is private — the class is non-clonable. +- `set()` emits an `E_USER_WARNING` and returns `false` outside test environments. +- `sanity_check()` boots `Db::pdo()` eagerly so ORM-dependent checks work. diff --git a/index.php b/index.php index a2aaf86..f4d72be 100644 --- a/index.php +++ b/index.php @@ -71,7 +71,7 @@ <div class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> - <span class="navbar-brand"><a title="v<?= Config::get_version(true) ?>" href="?">The Epube</a></span> + <span class="navbar-brand"><a href="?" class="cosmetic_version">The Epube</a></span> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav-collapse" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> @@ -107,9 +107,6 @@ </form> <ul class="nav navbar-nav navbar-right"> - <!-- <li><a href="#" title="Refresh script cache" class="refresh_cache_link"> - <span class="glyphicon glyphicon-refresh"></span> <span class='hidden-sm hidden-md hidden-lg'>Refresh script cache</span></a></li> - </li> --> <?php if ($mode !== "favorites") { ?> <li><a href="#" class="logout_link" title="Log out"> <span class="glyphicon glyphicon-log-out"></span> <span class='hidden-sm hidden-md hidden-lg'>Log out</span> @@ -167,6 +164,7 @@ <li class="pager-info"><span>Loading, please wait...</span></li> <li class="next"><a href="#">→ Next</a></li> </ul> + </div> </body> </html> diff --git a/src/app.js b/src/app.js index fd02999..095df1c 100644 --- a/src/app.js +++ b/src/app.js @@ -124,6 +124,8 @@ class AppClass extends AppCommon { version = BUILD_CACHE_VERSION; + cosmeticVersion = BUILD_VERSION; + // cacheManifest = []; csrf_token = ""; @@ -186,6 +188,8 @@ class AppClass extends AppCommon { this.getAll(); }); + $(".cosmetic_version").attr('title', this.cosmeticVersion); + } logout() { diff --git a/src/index.d.ts b/src/index.d.ts index d84c22a..4bf1153 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -16,3 +16,5 @@ declare var localforage: LocalForage; declare const BUILD_CACHE_VERSION: string; declare const BUILD_MANIFEST_ASSETS: []; + +declare const BUILD_VERSION: string; diff --git a/src/reader.js b/src/reader.js index 259e66d..e1b2ab1 100644 --- a/src/reader.js +++ b/src/reader.js @@ -30,6 +30,8 @@ class ReaderClass extends AppCommon { version = BUILD_CACHE_VERSION; + cosmeticVersion = BUILD_VERSION; + /** * @type {ePub.Book} */ @@ -696,7 +698,7 @@ class ReaderClass extends AppCommon { }); } - $(".last-mod-timestamp").html(`${this.version} + $(".last-mod-timestamp").html(`${this.cosmeticVersion} — ${this.version} (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`}) `); diff --git a/tests/ConfigTest.php b/tests/ConfigTest.php index 74503bc..a62e6e2 100644 --- a/tests/ConfigTest.php +++ b/tests/ConfigTest.php @@ -179,19 +179,4 @@ final class ConfigTest extends TestCase $this->assertStringNotContainsString('///', $url); } - // ── get_version() ──────────────────────────────────────────────────────── - - public function test_get_version_returns_string(): void - { - $version = Config::get_version(); - $this->assertIsString($version); - } - - public function test_get_version_as_array(): void - { - $version = Config::get_version(false); - $this->assertIsArray($version); - $this->assertArrayHasKey('status', $version); - $this->assertArrayHasKey('version', $version); - } } diff --git a/worker.js b/worker.js index 1dd1766..d4572af 100644 --- a/worker.js +++ b/worker.js @@ -1 +1 @@ -var i=["dist/app-libs.min.js","dist/app.min.js","dist/app.min.css","dist/reader_iframe.min.css","manifest.json","worker.js","offline.html","read.html","lib/fonts/palai.ttf","lib/fonts/palabi.ttf","lib/fonts/palab.ttf","lib/fonts/pala.ttf","lib/fonts/consolaz.ttf","lib/fonts/consolai.ttf","lib/fonts/consolab.ttf","lib/fonts/consola.ttf","lib/fonts/cambriaz.ttf","lib/fonts/cambriai.ttf","lib/fonts/cambriab.ttf","lib/fonts/cambria.ttf","lib/fonts/calibriz.ttf","lib/fonts/calibrii.ttf","lib/fonts/calibrib.ttf","lib/fonts/calibri.ttf","lib/fonts/caeciliai.ttf","lib/fonts/caeciliab.ttf","lib/fonts/caecilia.ttf","lib/fonts/IBMPlexMono-TextItalic.otf","lib/fonts/IBMPlexMono-Text.otf","lib/fonts/IBMPlexMono-BoldItalic.otf","lib/fonts/IBMPlexMono-Bold.otf","img/ic_launcher_web.png","img/favicon.png"];const sw=self,CACHE_PREFIX="epube",CACHE_VERSION="v1780151390364",CACHE_NAME=CACHE_PREFIX+"-"+CACHE_VERSION,MANIFEST_ASSETS=i;sw.addEventListener("install",t=>{t.waitUntil((async()=>{console.log("[worker] install started",CACHE_NAME);const s=await caches.open(CACHE_NAME),a=MANIFEST_ASSETS.map(e=>new Request(e,{cache:"reload"}));try{await s.addAll(a),console.log("[worker] all assets cached successfully"),sw.skipWaiting()}catch(e){console.error("[worker] Critical precache failed! Critical asset missing:",e)}})())}),sw.addEventListener("message",t=>{t.data&&t.data.type==="GET_CACHE_NAME"?t.ports[0].postMessage({cacheName:CACHE_NAME}):t.data&&t.data.type==="GET_CACHE_VERSION"&&t.ports[0].postMessage({cacheName:CACHE_VERSION})}),sw.addEventListener("activate",t=>{console.log("[worker] activate");const s=async()=>{const a=await caches.keys();for(const e of a)e.includes(CACHE_PREFIX)&&e!==CACHE_NAME&&await caches.delete(e);await sw.clients.claim()};t.waitUntil(s())}),sw.addEventListener("fetch",t=>{const s=new URL(t.request.url);if(!s.pathname.startsWith("/assets/")){if(s.pathname.match("backend.php\\?op=(cover|getinfo)")){t.respondWith((async()=>{try{const a=await fetch(t.request);return a.ok&&await(await caches.open(CACHE_NAME)).put(a.url,a.clone()),a}catch{const e=await caches.match(t.request);if(e)return e}})());return}if(s.pathname=="/"||s.pathname.match("index.php|offline.html|read.html")){t.respondWith((async()=>{try{const a=await fetch(t.request);return a.ok&&await(await caches.open(CACHE_NAME)).put(a.url,a.clone()),a}catch{return s.pathname.includes("read.html")?caches.match("read.html"):caches.match("/offline.html")}})());return}t.respondWith((async()=>{const a=await caches.open(CACHE_NAME),e=await a.match(t.request);return e?(fetch(t.request).then(c=>{c.ok&&a.put(t.request,c.clone())}).catch(c=>console.warn("[worker] Background update failed:",c)),e):await fetch(t.request)})())}}); +var i=["dist/app-libs.min.js","dist/app.min.js","dist/app.min.css","dist/reader_iframe.min.css","manifest.json","worker.js","offline.html","read.html","lib/fonts/palai.ttf","lib/fonts/palabi.ttf","lib/fonts/palab.ttf","lib/fonts/pala.ttf","lib/fonts/consolaz.ttf","lib/fonts/consolai.ttf","lib/fonts/consolab.ttf","lib/fonts/consola.ttf","lib/fonts/cambriaz.ttf","lib/fonts/cambriai.ttf","lib/fonts/cambriab.ttf","lib/fonts/cambria.ttf","lib/fonts/calibriz.ttf","lib/fonts/calibrii.ttf","lib/fonts/calibrib.ttf","lib/fonts/calibri.ttf","lib/fonts/caeciliai.ttf","lib/fonts/caeciliab.ttf","lib/fonts/caecilia.ttf","lib/fonts/IBMPlexMono-TextItalic.otf","lib/fonts/IBMPlexMono-Text.otf","lib/fonts/IBMPlexMono-BoldItalic.otf","lib/fonts/IBMPlexMono-Bold.otf","img/ic_launcher_web.png","img/favicon.png"];const sw=self,CACHE_PREFIX="epube",CACHE_VERSION="v1781200872189",CACHE_NAME=CACHE_PREFIX+"-"+CACHE_VERSION,MANIFEST_ASSETS=i;sw.addEventListener("install",t=>{t.waitUntil((async()=>{console.log("[worker] install started",CACHE_NAME);const s=await caches.open(CACHE_NAME),a=MANIFEST_ASSETS.map(e=>new Request(e,{cache:"reload"}));try{await s.addAll(a),console.log("[worker] all assets cached successfully"),sw.skipWaiting()}catch(e){console.error("[worker] Critical precache failed! Critical asset missing:",e)}})())}),sw.addEventListener("message",t=>{t.data&&t.data.type==="GET_CACHE_NAME"?t.ports[0].postMessage({cacheName:CACHE_NAME}):t.data&&t.data.type==="GET_CACHE_VERSION"&&t.ports[0].postMessage({cacheName:CACHE_VERSION})}),sw.addEventListener("activate",t=>{console.log("[worker] activate");const s=async()=>{const a=await caches.keys();for(const e of a)e.includes(CACHE_PREFIX)&&e!==CACHE_NAME&&await caches.delete(e);await sw.clients.claim()};t.waitUntil(s())}),sw.addEventListener("fetch",t=>{const s=new URL(t.request.url);if(!s.pathname.startsWith("/assets/")){if(s.pathname.match("backend.php\\?op=(cover|getinfo)")){t.respondWith((async()=>{try{const a=await fetch(t.request);return a.ok&&await(await caches.open(CACHE_NAME)).put(a.url,a.clone()),a}catch{const e=await caches.match(t.request);if(e)return e}})());return}if(s.pathname=="/"||s.pathname.match("index.php|offline.html|read.html")){t.respondWith((async()=>{try{const a=await fetch(t.request);return a.ok&&await(await caches.open(CACHE_NAME)).put(a.url,a.clone()),a}catch{return s.pathname.includes("read.html")?caches.match("read.html"):caches.match("/offline.html")}})());return}t.respondWith((async()=>{const a=await caches.open(CACHE_NAME),e=await a.match(t.request);return e?(fetch(t.request).then(c=>{c.ok&&a.put(t.request,c.clone())}).catch(c=>console.warn("[worker] Background update failed:",c)),e):await fetch(t.request)})())}}); |
