diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-05-24 20:16:56 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-05-24 20:16:56 +0300 |
| commit | a578fa50b2fc2d11ff5a0d45c2cd4d390409739a (patch) | |
| tree | fa502e64c2afdf90063a53d82bd9d3c80d0616af | |
| parent | 9942c9e5c5863fd66c945ec96125779cd382d611 (diff) | |
| download | the-epube-a578fa50b2fc2d11ff5a0d45c2cd4d390409739a.tar.gz the-epube-a578fa50b2fc2d11ff5a0d45c2cd4d390409739a.tar.xz | |
deal with remaining tsc errors
| -rw-r--r-- | dist/app.min.js | 6 | ||||
| -rw-r--r-- | src/app.js | 1 | ||||
| -rw-r--r-- | src/reader.js | 18 |
3 files changed, 16 insertions, 9 deletions
diff --git a/dist/app.min.js b/dist/app.min.js index ecb6b4d..a44bc31 100644 --- a/dist/app.min.js +++ b/dist/app.min.js @@ -1,4 +1,4 @@ -"use strict";function setupCsrfPrefilter(d){console.log("setting prefilter for token",d),$.ajaxPrefilter((e,t,o)=>{if(t.type!=="post"||e.type!=="post")return;const a=typeof t.data;a=="object"?e.data=$.param($.extend(t.data,{csrf_token:d})):a=="string"&&(e.data=t.data+"&csrf_token="+encodeURIComponent(d)),console.log(">>>",e)})}class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const s="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+s}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}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="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";init(){let e=0;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(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",t=>{t.data=="refresh-started"&&(console.log("cache refresh started"),e=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),t.data&&t.data.indexOf("refreshed:")==0&&(++e,$(".dl-progress").fadeIn().text("Updated "+e+" files...")),t.data=="refresh-finished"&&(localforage.setItem("epube.cache-version",this.version),localforage.setItem("epube.cache-timestamp",this.buildTimestamp),window.location.reload())}),this.showCovers(),this.updateOfflinePrompts(),this.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")}initCommonEventHandlers(){$(".refresh_cache_link").on("click",()=>{this.refreshCache(!0)}),$(".remove_all_downloads").on("click",()=>{this.removeAll()}),$(".logout_link").on("click",()=>{this.logout()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const t=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:t}),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+t),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,t)=>{const o=$(t);if(o.attr("data-cover-link")){const a=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),a.attr("src",null)}).attr("src",o.attr("data-cover-link")??"")}})}toggleFavorite(e){const t=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:t},o=>{if(o){let a="[Error]";o.status==0?a="Add to favorites":o.status==1&&(a="Remove from favorites"),$(e).html(a).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+t).remove()}}),!1}async refreshCache(e){if("serviceWorker"in navigator){const t=await localforage.getItem("epube.cache-version");if(console.log("local version",t,"remote version",this.version),e||t!=this.version)if(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller)navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:this.cached_urls});else{const o=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",o),o?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):(await localforage.setItem("epube.initial-load-done",!0),$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout(function(){window.location.reload()},3*1e3))}}else $(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(t,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const t=e.getAttribute("data-book-id"),o="epube-book."+t;await localforage.getItem(o)?(e.onclick=()=>(this.remove(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}offlineInit(){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.populateList()}get(e,t){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const a="epube-book."+e;localforage.setItem(a,o).then(s=>{console.log(a+" got data");const i=[];i.push(fetch("backend.php?op=download&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),i.push(fetch("backend.php?op=getpagination&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got pagination"),n.text().then(function(l){localforage.setItem(a+".locations",JSON.parse(l))}))})),i.push(fetch("backend.php?op=getlastread&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got lastread"),n.text().then(function(l){localforage.setItem(a+".lastread",JSON.parse(l))}))})),s.has_cover&&i.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got cover"),localforage.setItem(a+".cover",n.blob()))})),Promise.all(i).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+s.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,t)=>{const o=($(t).attr("id")??"").replace("cell-",""),a=$(t).find(".offline_dropitem")[0]??null;if(o){const s="epube-book."+o;localforage.getItem(s).then(i=>{i||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(e){const t=e.getAttribute("data-book-id");this.remove(t,()=>{$("#cell-"+t).remove()})}remove(e,t){if(confirm("Remove download?")){const o="epube-book."+e,a=[];console.log("offline remove: "+e),localforage.iterate(function(s,i){i.match(o)&&a.push(localforage.removeItem(i))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(t,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateList()}}populateList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate(function(o,a){a.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(a),localforage.getItem(a+".cover"),localforage.getItem(a+".lastread"),localforage.getItem(a+".book")]).then(function(s){if(s[0]&&s[3]){const i=s[0];if(e&&!(i.series_name&&i.series_name.toLowerCase().match(e)||i.title&&i.title.toLowerCase().match(e)||i.author_sort&&i.author_sort.toLowerCase().match(e)))return;let n="";s&&s[1]&&(n=URL.createObjectURL(s[1]));let l=!1,r=!1;const c=s[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const f=r?"read":"",p=l?"in_progress":"",g=i.series_name?`<div><a class="series_link" href="#">${i.series_name+" ["+i.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${i.id}"> +"use strict";function setupCsrfPrefilter(d){console.log("setting prefilter for token",d),$.ajaxPrefilter((e,t,o)=>{if(t.type!=="post"||e.type!=="post")return;const a=typeof t.data;a=="object"?e.data=$.param($.extend(t.data,{csrf_token:d})):a=="string"&&(e.data=t.data+"&csrf_token="+encodeURIComponent(d)),console.log(">>>",e)})}class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const s="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+s}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return t&&decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}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="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";init(){let e=0;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(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",t=>{t.data=="refresh-started"&&(console.log("cache refresh started"),e=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),t.data&&t.data.indexOf("refreshed:")==0&&(++e,$(".dl-progress").fadeIn().text("Updated "+e+" files...")),t.data=="refresh-finished"&&(localforage.setItem("epube.cache-version",this.version),localforage.setItem("epube.cache-timestamp",this.buildTimestamp),window.location.reload())}),this.showCovers(),this.updateOfflinePrompts(),this.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")}initCommonEventHandlers(){$(".refresh_cache_link").on("click",()=>{this.refreshCache(!0)}),$(".remove_all_downloads").on("click",()=>{this.removeAll()}),$(".logout_link").on("click",()=>{this.logout()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const t=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:t}),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+t),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,t)=>{const o=$(t);if(o.attr("data-cover-link")){const a=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),a.attr("src",null)}).attr("src",o.attr("data-cover-link")??"")}})}toggleFavorite(e){const t=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:t},o=>{if(o){let a="[Error]";o.status==0?a="Add to favorites":o.status==1&&(a="Remove from favorites"),$(e).html(a).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+t).remove()}}),!1}async refreshCache(e){if("serviceWorker"in navigator){const t=await localforage.getItem("epube.cache-version");if(console.log("local version",t,"remote version",this.version),e||t!=this.version)if(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller)navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:this.cached_urls});else{const o=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",o),o?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):(await localforage.setItem("epube.initial-load-done",!0),$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout(function(){window.location.reload()},3*1e3))}}else $(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(t,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const t=e.getAttribute("data-book-id"),o="epube-book."+t;await localforage.getItem(o)?(e.onclick=()=>(this.remove(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}offlineInit(){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.populateList()}get(e,t){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const a="epube-book."+e;localforage.setItem(a,o).then(s=>{console.log(a+" got data");const i=[];i.push(fetch("backend.php?op=download&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),i.push(fetch("backend.php?op=getpagination&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got pagination"),n.text().then(function(l){localforage.setItem(a+".locations",JSON.parse(l))}))})),i.push(fetch("backend.php?op=getlastread&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got lastread"),n.text().then(function(l){localforage.setItem(a+".lastread",JSON.parse(l))}))})),s.has_cover&&i.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got cover"),localforage.setItem(a+".cover",n.blob()))})),Promise.all(i).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+s.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,t)=>{const o=($(t).attr("id")??"").replace("cell-",""),a=$(t).find(".offline_dropitem")[0]??null;if(o){const s="epube-book."+o;localforage.getItem(s).then(i=>{i||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(e){const t=e.getAttribute("data-book-id");this.remove(t,()=>{$("#cell-"+t).remove()})}remove(e,t){if(confirm("Remove download?")){const o="epube-book."+e,a=[];console.log("offline remove: "+e),localforage.iterate(function(s,i){i.match(o)&&a.push(localforage.removeItem(i))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(t,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateList()}}populateList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate(function(o,a){a.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(a),localforage.getItem(a+".cover"),localforage.getItem(a+".lastread"),localforage.getItem(a+".book")]).then(function(s){if(s[0]&&s[3]){const i=s[0];if(e&&!(i.series_name&&i.series_name.toLowerCase().match(e)||i.title&&i.title.toLowerCase().match(e)||i.author_sort&&i.author_sort.toLowerCase().match(e)))return;let n="";s&&s[1]&&(n=URL.createObjectURL(s[1]));let l=!1,r=!1;const c=s[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const f=r?"read":"",p=l?"in_progress":"",g=i.series_name?`<div><a class="series_link" href="#">${i.series_name+" ["+i.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${i.id}"> <a class="thumbnail ${f}" href="read.html?id=${i.epub_id}&b=${i.id}"> <img style="display : none"> </a> @@ -14,7 +14,7 @@ <li><a href="#" data-book-id="${i.id}" onclick="App.removeFromList(this)">Remove offline data</a></li> </ul> </div> - </div>`);n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",i.series_name+" ["+i.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(i.series_name)),h.find(".author_link").attr("title",i.author_sort).attr("href","offline.html?query="+encodeURIComponent(i.author_sort)),t.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;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 t=e.touches[0]||e.changedTouches[0];this._swipeState={active:!0,startX:t.clientX,startY:t.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,a=Date.now()-this._swipeState.startTime,s=a>0?Math.abs(o)/a:0,i=Math.abs(o)>=this._swipeConfig.minDistance&&s>=this._swipeConfig.velocityThreshold,n=this._swipeState.direction=="left",l=n?o<0:o>0;i&&l&&(e.preventDefault(),e.stopPropagation(),n?this.nextPage():this.prevPage())}onTouchMove(e){if(!this._swipeState.active)return;const t=e.touches[0]||e.changedTouches[0];if(Math.abs(t.clientY-this._swipeState.startY)>this._swipeConfig.verticalDistanceThreshold){this._swipeState.active=!1;return}}async init(){this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",t=>{this.openPrevious(t.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),$("#left, #right").on("touchstart",t=>{this.onTouchStart(t)}),$("#left, #right").on("touchmove",t=>{this.onTouchMove(t)}),$("#left, #right").on("touchend",t=>{this.onTouchEnd(t)});const e=await this.loader.init();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 t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:new Date().getTime()},function(){}).fail(function(a){a&&a.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 s=this.urlParam("b");console.log("requesting bookinfo for book",s);try{const i=await $.post("backend.php",{op:"getinfo",id:s});if(i.has_cover){const n=await fetch("backend.php?op=cover&id="+s);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),i),console.log("bookinfo saved")}catch(i){const n=i;console.error(n),$(".loading-message").html(`Unable to load book info.<br/><small>${n.responseText}</small>`);return}}console.log("trying to load book...");let t=await localforage.getItem(this.cacheId("book"));if(!t){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const s=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(s.ok)if(t=await s.blob(),t)await localforage.setItem(this.cacheId("book"),t),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: ${s.status}`);return}}const o=new FileReader,a=this;o.onload=function(){try{a.openBookData(this.result)}catch(s){console.error(s),$(".loading-message").html("Unable to load book blob: "+s)}},o.onerror=s=>{console.log("filereader error",s),$(".loading-message").html("Unable to open book.<br/><small>"+s+"</small>")},o.readAsArrayBuffer(t)}async openBookData(e){try{await this.book.open(e)}catch(a){console.error(a),$(".loading-message").html(`Unable to open book.<br/><small>${a instanceof Error?a.message:a}</small>`);return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const t=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const a=Math.floor(t.currentLocation().start.location/LOCATION_DIVISOR),s=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),i=prompt("Jump to location [1-"+s+"]",String(a));i&&await t.display(this.book.locations._locations[parseInt(i)*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,t),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await t.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const t=await localforage.getItem(this.cacheId());let o,a;if(t)o=t.title,a=t.author_sort;else{const s=e.packaging.metadata;o=s.title,a=s.creator}document.title=o+" \u2013 "+a+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+a),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let t=await localforage.getItem(this.cacheId("locations"));if(t&&typeof t[0]=="string"){console.log("loading local locations...");try{await e.locations.load(t);return}catch(a){console.warn(a)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const a=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(a.ok){console.log("got locations from server");try{t=await a.json()}catch(s){console.warn(s)}if(t&&typeof t[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),t);try{e.locations.load(t);return}catch(s){console.warn(s)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;t=await e.locations.generate(100,a=>{if(o||(o=a.length()),o>0){const s=Math.round((1-a.length()/o)*100);$(".loading-message").html(`Preparing locations (${s}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(t),total:100}),await localforage.setItem(this.cacheId("locations"),t)}initRenditionHooks(e,t){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),t.hooks.content.register(async o=>{o.on("linkClicked",i=>{console.log("linkClicked",i),this.blockLastReadUpdate(),i.indexOf("://")==-1&&($(".prev_location_btn").attr("data-location-cfi",t.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async i=>{if(this.isOnline()){const n=await e.getRange(i),l=n.endContainer.data.substring(n.startOffset,n.endOffset);console.log("selected",i,l),l.match(/^[\w]+$/)&&this.lookupWord(l,()=>{typeof EpubeApp<"u"&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const a=window.location.href.match(/^.*\//)[0];$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[a+"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",i=>{if(i.button==0){if($(".modal").is(":visible"))return;typeof EpubeApp<"u"?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async i=>{await localforage.getItem("epube.enable-wheel")&&((i.originalEvent?.deltaY??0)>0?this.nextPage():(i.originalEvent?.deltaY??0)<0&&this.prevPage())})}),t.on("keyup",o=>{this.hotkeyHandler(o)}),t.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),t.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=t.currentLocation();if(o.start){const a=e.canonical(o.start.href);let s={};$.each(this.flattenToc(e),function(i,n){if(e.spine.get(n.href).canonical==a){s=n;return}}),s&&s.label&&$(".chapter_title").html(s.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())}),t.on("displayed",function(){console.log("rendition displayed")}),t.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")},i=>{$(".lastread_input").val(i.page+"%").attr("title",`[remote] ${i.cfi}`)}),$(".font_family").off("change").on("change",i=>{this.onFontChanged(i.target)}),$(".font_size").off("change").on("change",i=>{this.onTextSizeChanged(i.target)}),$(".line_height").off("change").on("change",i=>{this.onLineHeightChanged(i.target)}),$(".theme_name").off("change").on("change",i=>{this.onThemeChanged(i.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",i=>{localforage.setItem("epube.enable-hyphens",i.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",i=>{localforage.setItem("epube.enable-wheel",i.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",i=>{localforage.setItem("epube.keep-ui-visible",i.target.checked)});const t=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o} + </div>`);n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",i.series_name+" ["+i.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(i.series_name)),h.find(".author_link").attr("title",i.author_sort).attr("href","offline.html?query="+encodeURIComponent(i.author_sort)),t.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;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 t=e.touches[0]||e.changedTouches[0];this._swipeState={active:!0,startX:t.clientX,startY:t.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,a=Date.now()-this._swipeState.startTime,s=a>0?Math.abs(o)/a:0,i=Math.abs(o)>=this._swipeConfig.minDistance&&s>=this._swipeConfig.velocityThreshold,n=this._swipeState.direction=="left",l=n?o<0:o>0;i&&l&&(e.preventDefault(),e.stopPropagation(),n?this.nextPage():this.prevPage())}onTouchMove(e){if(!this._swipeState.active)return;const t=e.touches[0]||e.changedTouches[0];if(Math.abs(t.clientY-this._swipeState.startY)>this._swipeConfig.verticalDistanceThreshold){this._swipeState.active=!1;return}}async init(){this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",t=>{this.openPrevious(t.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),$("#left, #right").on("touchstart",t=>{this.onTouchStart(t)}),$("#left, #right").on("touchmove",t=>{this.onTouchMove(t)}),$("#left, #right").on("touchend",t=>{this.onTouchEnd(t)});const e=await this.loader.init();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 t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:new Date().getTime()},function(){}).fail(function(a){a&&a.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 s=this.urlParam("b");console.log("requesting bookinfo for book",s);try{const i=await $.post("backend.php",{op:"getinfo",id:s});if(i.has_cover){const n=await fetch("backend.php?op=cover&id="+s);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),i),console.log("bookinfo saved")}catch(i){const n=i;console.error(n),$(".loading-message").html(`Unable to load book info.<br/><small>${n.responseText}</small>`);return}}console.log("trying to load book...");let t=await localforage.getItem(this.cacheId("book"));if(!t){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const s=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(s.ok)if(t=await s.blob(),t)await localforage.setItem(this.cacheId("book"),t),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: ${s.status}`);return}}const o=new FileReader,a=this;o.onload=function(){try{a.openBookData(this.result)}catch(s){console.error(s),$(".loading-message").html("Unable to load book blob: "+s)}},o.onerror=s=>{console.log("filereader error",s),$(".loading-message").html("Unable to open book.<br/><small>"+s+"</small>")},o.readAsArrayBuffer(t)}async openBookData(e){try{await this.book.open(e)}catch(a){console.error(a),$(".loading-message").html(`Unable to open book.<br/><small>${a instanceof Error?a.message:a}</small>`);return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const t=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const a=Math.floor(t.currentLocation().start.location/LOCATION_DIVISOR),s=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),i=prompt("Jump to location [1-"+s+"]",String(a));i&&await t.display(this.book.locations._locations[parseInt(i)*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,t),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await t.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const t=await localforage.getItem(this.cacheId());let o,a;if(t)o=t.title,a=t.author_sort;else{const s=e.packaging.metadata;o=s.title,a=s.creator}document.title=o+" \u2013 "+a+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+a),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let t=await localforage.getItem(this.cacheId("locations"));if(t&&typeof t[0]=="string"){console.log("loading local locations...");try{await e.locations.load(t);return}catch(a){console.warn(a)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const a=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(a.ok){console.log("got locations from server");try{t=await a.json()}catch(s){console.warn(s)}if(t&&typeof t[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),t);try{e.locations.load(t);return}catch(s){console.warn(s)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;t=await e.locations.generate(100,a=>{if(o||(o=a.length()),o>0){const s=Math.round((1-a.length()/o)*100);$(".loading-message").html(`Preparing locations (${s}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(t),total:100}),await localforage.setItem(this.cacheId("locations"),t)}initRenditionHooks(e,t){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),t.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",t.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 a=window.location.href.match(/^.*\//),s=a?a[0]:window.location.href;$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(s))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[s+"dist/reader_iframe.min.css"]));const i=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+i),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())})}),t.on("keyup",o=>{this.hotkeyHandler(o)}),t.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),t.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=t.currentLocation();if(o.start){const a=e.canonical(o.start.href);let s={};$.each(this.flattenToc(e),function(i,n){if(e.spine.get(n.href).canonical==a){s=n;return}}),s&&s.label&&$(".chapter_title").html(s.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())}),t.on("displayed",function(){console.log("rendition displayed")}),t.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")},i=>{$(".lastread_input").val(i.page+"%").attr("title",`[remote] ${i.cfi}`)}),$(".font_family").off("change").on("change",i=>{this.onFontChanged(i.target)}),$(".font_size").off("change").on("change",i=>{this.onTextSizeChanged(i.target)}),$(".line_height").off("change").on("change",i=>{this.onLineHeightChanged(i.target)}),$(".theme_name").off("change").on("change",i=>{this.onThemeChanged(i.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",i=>{localforage.setItem("epube.enable-hyphens",i.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",i=>{localforage.setItem("epube.enable-wheel",i.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",i=>{localforage.setItem("epube.keep-ui-visible",i.target.checked)});const t=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o} — ${parseInt(t)?new Date(t*1e3).toLocaleString("en-GB"):"Unknown"} (${this.isOnline()?"<span class='text-success'>Online</span>":"<span class='text-danger'>Offline</span>"}) `),$(".font_family").val(await localforage.getItem("epube.fontFamily")||DEFAULT_FONT_FAMILY),$(".theme_name").val(await localforage.getItem("epube.theme")||"default");const a=$(".font_size").html("");for(let i=10;i<=32;i++){const n=$("<option>").val(i).html(i+" px");a.append(n)}a.val(await localforage.getItem("epube.fontSize")||DEFAULT_FONT_SIZE);const s=$(".line_height").html("");for(let i=100;i<=220;i+=10){const n=$("<option>").val(i).html(i+"%");s.append(n)}s.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 t=this;function o(s){try{const i=e.spine.get(s).cfiBase,n=e.locations._locations.find(function(l){return l.indexOf(i)!=-1});return Math.round(t.book.locations.locationFromCfi(n)/LOCATION_DIVISOR)}catch(i){console.warn(i)}return""}function a(s,i,n){if(n==3)return!1;if(s.subitems){const l=$("<ul class='toc_sublist list-unstyled'>");$.each(s.subitems,function(r,c){const f=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(c.href)+"</b>"+c.label).attr("data-href",c.href).click(function(){e.rendition.display(f.attr("data-href"))});l.append($("<li>").append(f)),a(c,l,n+1)}),i.append(l)}}$("#toc-modal").on("shown.bs.modal",function(){const s=e.navigation.toc,i=$(".toc_list");i.html(""),$.each(s,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"))});i.append($("<li>").append(r)),a(l,i,0)}catch(r){console.warn(r)}}),i.children().length<=1&&(i.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"))});i.append($("<li>").append(r))}))})}cleanupEmbeddedStyles(e){$(e).find("p").filter((t,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((t,o)=>{const a=$(o);a.html(this.hyphenate.en(a.html())),a.html(this.hyphenate.ru(a.html()))})}generateFontsCss(e){return` @@ -187,4 +187,4 @@ font-style: normal; font-weight : 400; } - `}flattenTocSubItems(e,t){let o=[];return t==3?!1:(e.subitems&&$.each(e.subitems,(a,s)=>{s._nest=t,o.push(s),o=o.concat(this.flattenTocSubItems(s,t+1))}),o)}flattenToc(e){if(this._flattened_toc)return this._flattened_toc;{let t=[];return $.each(e.navigation.toc,(o,a)=>{a._nest=0,t.push(a),t=t.concat(this.flattenTocSubItems(a,1))}),this._flattened_toc=t,t}}generateTocBar(e,t){$(".spacer").html(""),$.each(t,function(o,a){try{const s=e.spine.get(a.href).cfiBase,i=e.locations._locations.find(function(n){return n.indexOf(s)!=-1});if(i){const n=Math.round(e.locations.percentageFromCfi(i)*100);$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",a._nest).css("left",n+"%").css("_width",3-a._nest+"px").attr("title",a.label))}}catch(s){console.warn(s)}}),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(e,e.rendition.currentLocation())}updateTocBarPosition(e,t){const o=Math.round(t.start.location/e.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let e=await localforage.getItem("epube.fontSize"),t=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");e=e?e+"px":DEFAULT_FONT_SIZE+"px",t=t||DEFAULT_FONT_FAMILY,o=o?o+"%":DEFAULT_LINE_HEIGHT+"%",console.log("style",t,e,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":e,"font-family":"'"+t+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let a=await localforage.getItem("epube.theme")||"default";console.log("called for theme",a),a=="default"&&typeof EpubeApp<"u"&&EpubeApp.isNightMode()&&(a="night"),console.log("setting main UI theme",a),$("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("epube-reader theme-"+a).attr("data-is-loading","false"),typeof EpubeApp<"u"&&window.setTimeout(function(){let i=window.getComputedStyle(document.querySelector("body"),null).getPropertyValue("background-color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);i&&(console.log("sending bgcolor",i),EpubeApp.setStatusBarColor(parseInt(i[1]),parseInt(i[2]),parseInt(i[3]))),i=window.getComputedStyle(document.querySelector(".header .title"),null).getPropertyValue("color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),i&&(console.log("sending accent_color",i),EpubeApp.setAccentColor(parseInt(i[1]),parseInt(i[2]),parseInt(i[3])))},250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(s=>{console.log(`applying styles and theme ${a} to `,s),s.css("font-size",e),s.css("font-family","'"+t+"'"),s.css("line-height",o),s.css("text-align","justify"),$(s.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+a)})}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(t){console.warn(t)}}resizeSideColumns(){let e=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(t=>{e+=parseInt(t.window.getComputedStyle(t.document.querySelector("body")).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,t=this.book.locations.cfiFromPercentage(1),o=new Date().getTime();if(this.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:e,cfi:t,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:e,total:e,timestamp:o}),await this.openLastRead()}}async close(){const t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100),a=100,s=new Date().getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:o,total:a,timestamp:s}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:s},()=>{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,t,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 a=await $.post("backend.php",{op:"define",word:e});a&&($(".dict_result").html(a.result.join("<br/>")),$(".dict_query").val(e),t&&t())}catch(a){const s=a;console.error(s),$(".dict_result").html(`Network error while looking up word: ${s.responseText}.`)}}search(){const e=$(".search_input").val(),t=$(".search_results");t.html(""),e&&(t.html("<li>Loading, please wait...</li>"),Promise.all(this.book.spine.spineItems.map(o=>o.load(this.book.load.bind(this.book)).then(o.find.bind(o,e)).finally(o.unload.bind(o)))).then(o=>Promise.resolve([].concat.apply([],o))).then(o=>{t.html(""),$.each(o,(a,s)=>{const i=$("<a>").attr("href","#").html("<b class='pull-right'>"+this.book.locations.locationFromCfi(s.cfi)+"</b>"+s.excerpt).attr("data-cfi",s.cfi).attr("data-id",s.id).on("click",()=>{this.book.rendition.display(i.attr("data-cfi"))});t.append($("<li>").append(i))})}))}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 t=$(e).attr("data-location-cfi");t&&await this.book.rendition.display(t),$(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,t){if(e.locations.length()==0)return;const o=t.start.cfi,a=Math.round(e.locations.percentageFromCfi(o)*100);$("#cur_page").text(Math.floor(t.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,t);const s=t.start.displayed;if(s&&($("#chapter_cur_page").text(s.page),$("#chapter_total_pages").text(s.total),s.total>0&&$("#chapter_pct").text(Math.round(s.page/s.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const i=new Date().getTime();console.log("storing lastread",a,o,i),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:i}),this.isOnline()&&(console.log("updating remote lastread",o),this.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:a,cfi:o,timestamp:i}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const e=this.book.locations.length(),t=new Date().getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:PAGE_RESET_PROGRESS,cfi:"",id:this.urlParam("id"),timestamp:t}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:e,timestamp:t}),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 t=!1;const o=await localforage.getItem(this.cacheId("lastread"))||{};if(console.log("got local lastread",o),this.isOnline())try{const a=await $.post("backend.php",{op:"getlastread",id:this.urlParam("id")});console.log("got remote lastread",a),a&&a.cfi&&o.cfi!=a.cfi&&a.page>=(o.page||0)&&(console.log(`using remote lastread cfi ${a.cfi}: cfi is different and remote pct ${a.page}% is further than local pct ${o.page}%`),await localforage.setItem(this.cacheId("lastread"),{cfi:a.cfi,page:a.page,total:a.total,timestamp:a.timestamp}),t=await this.moveToCfiVerify(e,a.cfi))}catch(a){console.log("unable to get remote lastread, continuing..."),console.warn(a)}if(!t&&o&&o.cfi){console.log(`using local lastread cfi: ${o.cfi}`);try{await this.moveToCfiVerify(e,o.cfi)}catch(a){console.warn(a)}}$(".loading").fadeOut()}calculateCfiDelta(e,t){if(!e||!t)return-1;const o=new ePub.CFI(e),a=new ePub.CFI(t);if(console.log("calculateCfiDelta",o,a),o.path.steps.length!=a.path.steps.length)return-1;let s=0;for(let i=0;i<o.path.steps.length;i++){if(o.path.steps[i].type!=a.path.steps[i].type||o.path.steps[i].id!=a.path.steps[i].id)return-1;o.path.steps[i].id===null&&o.path.steps[i].type==="element"&&(s+=Math.abs(o.path.steps[i].index-a.path.steps[i].index))}return s}async moveToCfiVerify(e,t,o=5,a=5){for(let s=1;s<o;s++){this.blockLastReadUpdate(),console.log(`trying to open ${t}: attempt ${s} of ${o}...`),await e.display(t);let i;try{i=e.currentLocation().start.cfi}catch(n){console.warn("location not yet available, will retry:",n)}try{const n=this.calculateCfiDelta(t,i??null);if(console.log(`opened cfi ${i} expected ${t}; delta: ${n}`),i==t||n!=-1&&n<=a)return console.log("cfi move verified!"),!0}catch(n){console.warn("exception while parsing cfi, will retry: ",n)}}return!1}async onThemeChanged(e){const t=$(e).val();await localforage.setItem("epube.theme",t),this.applyTheme()}async onLineHeightChanged(e){const t=$(e).val();await localforage.setItem("epube.lineHeight",t),this.applyTheme()}async onTextSizeChanged(e){const t=$(e).val();await localforage.setItem("epube.fontSize",t),this.applyTheme()}async onFontChanged(e){const t=$(e).val();await localforage.setItem("epube.fontFamily",t),this.applyTheme()}}class ReaderLoader{_res_data=[];CACHE_NAME="epube-v3";async init(){typeof EpubeApp<"u"&&$("body").addClass("epube-app");const e=[];let t=!1;return(await(await caches.open(this.CACHE_NAME)).keys()).forEach(s=>{if(!s.url.match("backend.php")){console.log("[loader] loading resource",s.url);const i=fetch(s.url).then(async n=>{if(n.ok){const l=new URL(n.url);if(l.searchParams.delete("ts"),n.url.match("\\.ttf|\\.otf")){const r=await n.blob();console.log("[loader] storing blob",l.href),this._res_data[l.toString()]=URL.createObjectURL(r)}else{const r=await n.text();console.log("[loader] storing text",l.href),this._res_data[l.toString()]=r}}else console.warn("[loader] failed for resource",s.url,n),$(".loading-message").html(`Unable to load resource.<br/><small>${s.url}</small>`),t=!0});e.push(i)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",t),t}} + `}flattenTocSubItems(e,t){let o=[];return t==3?!1:(e.subitems&&$.each(e.subitems,(a,s)=>{s._nest=t,o.push(s),o=o.concat(this.flattenTocSubItems(s,t+1))}),o)}flattenToc(e){if(this._flattened_toc)return this._flattened_toc;{let t=[];return $.each(e.navigation.toc,(o,a)=>{a._nest=0,t.push(a),t=t.concat(this.flattenTocSubItems(a,1))}),this._flattened_toc=t,t}}generateTocBar(e,t){$(".spacer").html(""),$.each(t,function(o,a){try{const s=e.spine.get(a.href).cfiBase,i=e.locations._locations.find(function(n){return n.indexOf(s)!=-1});if(i){const n=Math.round(e.locations.percentageFromCfi(i)*100);$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",a._nest).css("left",n+"%").css("_width",3-a._nest+"px").attr("title",a.label))}}catch(s){console.warn(s)}}),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(e,e.rendition.currentLocation())}updateTocBarPosition(e,t){const o=Math.round(t.start.location/e.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let e=await localforage.getItem("epube.fontSize"),t=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");e=e?e+"px":DEFAULT_FONT_SIZE+"px",t=t||DEFAULT_FONT_FAMILY,o=o?o+"%":DEFAULT_LINE_HEIGHT+"%",console.log("style",t,e,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":e,"font-family":"'"+t+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let a=await localforage.getItem("epube.theme")||"default";console.log("called for theme",a),a=="default"&&typeof EpubeApp<"u"&&EpubeApp.isNightMode()&&(a="night"),console.log("setting main UI theme",a),$("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("epube-reader theme-"+a).attr("data-is-loading","false"),typeof EpubeApp<"u"&&window.setTimeout(function(){const s=document.querySelector("body");let n=(s?window.getComputedStyle(s,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(s=>{console.log(`applying styles and theme ${a} to `,s),s.css("font-size",e),s.css("font-family","'"+t+"'"),s.css("line-height",o),s.css("text-align","justify"),$(s.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+a)})}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(t){console.warn(t)}}resizeSideColumns(){let e=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(t=>{const o=t.document.querySelector("body");o&&(e+=parseInt(t.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,t=this.book.locations.cfiFromPercentage(1),o=new Date().getTime();if(this.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:e,cfi:t,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:e,total:e,timestamp:o}),await this.openLastRead()}}async close(){const t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100),a=100,s=new Date().getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:o,total:a,timestamp:s}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:s},()=>{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,t,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 a=await $.post("backend.php",{op:"define",word:e});a&&($(".dict_result").html(a.result.join("<br/>")),$(".dict_query").val(e),t&&t())}catch(a){const s=a;console.error(s),$(".dict_result").html(`Network error while looking up word: ${s.responseText}.`)}}search(){const e=$(".search_input").val(),t=$(".search_results");t.html(""),e&&(t.html("<li>Loading, please wait...</li>"),Promise.all(this.book.spine.spineItems.map(o=>o.load(this.book.load.bind(this.book)).then(o.find.bind(o,e)).finally(o.unload.bind(o)))).then(o=>Promise.resolve([].concat.apply([],o))).then(o=>{t.html(""),$.each(o,(a,s)=>{const i=$("<a>").attr("href","#").html("<b class='pull-right'>"+this.book.locations.locationFromCfi(s.cfi)+"</b>"+s.excerpt).attr("data-cfi",s.cfi).attr("data-id",s.id).on("click",()=>{this.book.rendition.display(i.attr("data-cfi"))});t.append($("<li>").append(i))})}))}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 t=$(e).attr("data-location-cfi");t&&await this.book.rendition.display(t),$(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,t){if(e.locations.length()==0)return;const o=t.start.cfi,a=Math.round(e.locations.percentageFromCfi(o)*100);$("#cur_page").text(Math.floor(t.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,t);const s=t.start.displayed;if(s&&($("#chapter_cur_page").text(s.page),$("#chapter_total_pages").text(s.total),s.total>0&&$("#chapter_pct").text(Math.round(s.page/s.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const i=new Date().getTime();console.log("storing lastread",a,o,i),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:i}),this.isOnline()&&(console.log("updating remote lastread",o),this.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:a,cfi:o,timestamp:i}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const e=this.book.locations.length(),t=new Date().getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:PAGE_RESET_PROGRESS,cfi:"",id:this.urlParam("id"),timestamp:t}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:e,timestamp:t}),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 t=!1;const o=await localforage.getItem(this.cacheId("lastread"))||{};if(console.log("got local lastread",o),this.isOnline())try{const a=await $.post("backend.php",{op:"getlastread",id:this.urlParam("id")});console.log("got remote lastread",a),a&&a.cfi&&o.cfi!=a.cfi&&a.page>=(o.page||0)&&(console.log(`using remote lastread cfi ${a.cfi}: cfi is different and remote pct ${a.page}% is further than local pct ${o.page}%`),await localforage.setItem(this.cacheId("lastread"),{cfi:a.cfi,page:a.page,total:a.total,timestamp:a.timestamp}),t=await this.moveToCfiVerify(e,a.cfi))}catch(a){console.log("unable to get remote lastread, continuing..."),console.warn(a)}if(!t&&o&&o.cfi){console.log(`using local lastread cfi: ${o.cfi}`);try{await this.moveToCfiVerify(e,o.cfi)}catch(a){console.warn(a)}}$(".loading").fadeOut()}calculateCfiDelta(e,t){if(!e||!t)return-1;const o=new ePub.CFI(e),a=new ePub.CFI(t);if(console.log("calculateCfiDelta",o,a),o.path.steps.length!=a.path.steps.length)return-1;let s=0;for(let i=0;i<o.path.steps.length;i++){if(o.path.steps[i].type!=a.path.steps[i].type||o.path.steps[i].id!=a.path.steps[i].id)return-1;o.path.steps[i].id===null&&o.path.steps[i].type==="element"&&(s+=Math.abs(o.path.steps[i].index-a.path.steps[i].index))}return s}async moveToCfiVerify(e,t,o=5,a=5){for(let s=1;s<o;s++){this.blockLastReadUpdate(),console.log(`trying to open ${t}: attempt ${s} of ${o}...`),await e.display(t);let i;try{i=e.currentLocation().start.cfi}catch(n){console.warn("location not yet available, will retry:",n)}try{const n=this.calculateCfiDelta(t,i??null);if(console.log(`opened cfi ${i} expected ${t}; delta: ${n}`),i==t||n!=-1&&n<=a)return console.log("cfi move verified!"),!0}catch(n){console.warn("exception while parsing cfi, will retry: ",n)}}return!1}async onThemeChanged(e){const t=$(e).val();await localforage.setItem("epube.theme",t),this.applyTheme()}async onLineHeightChanged(e){const t=$(e).val();await localforage.setItem("epube.lineHeight",t),this.applyTheme()}async onTextSizeChanged(e){const t=$(e).val();await localforage.setItem("epube.fontSize",t),this.applyTheme()}async onFontChanged(e){const t=$(e).val();await localforage.setItem("epube.fontFamily",t),this.applyTheme()}}class ReaderLoader{_res_data=[];CACHE_NAME="epube-v3";async init(){typeof EpubeApp<"u"&&$("body").addClass("epube-app");const e=[];let t=!1;return(await(await caches.open(this.CACHE_NAME)).keys()).forEach(s=>{if(!s.url.match("backend.php")){console.log("[loader] loading resource",s.url);const i=fetch(s.url).then(async n=>{if(n.ok){const l=new URL(n.url);if(l.searchParams.delete("ts"),n.url.match("\\.ttf|\\.otf")){const r=await n.blob();console.log("[loader] storing blob",l.href),this._res_data[l.toString()]=URL.createObjectURL(r)}else{const r=await n.text();console.log("[loader] storing text",l.href),this._res_data[l.toString()]=r}}else console.warn("[loader] failed for resource",s.url,n),$(".loading-message").html(`Unable to load resource.<br/><small>${s.url}</small>`),t=!0});e.push(i)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",t),t}} diff --git a/src/app.js b/src/app.js index 2bed544..ef29043 100644 --- a/src/app.js +++ b/src/app.js @@ -33,6 +33,7 @@ class AppCommon { urlParam(name){ try { const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); + if (!results) return 0; return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0; } catch (e) { return 0; diff --git a/src/reader.js b/src/reader.js index 3340203..aa9f103 100644 --- a/src/reader.js +++ b/src/reader.js @@ -498,7 +498,8 @@ class ReaderClass extends AppCommon { // get our stuff from resource loader and inject into iframe content - const base_url = window.location.href.match(/^.*\//)[0]; + const match = window.location.href.match(/^.*\//); + const base_url = match ? match[0] : window.location.href; $(contents.document.head) .append($("<style type='text/css'>") @@ -1186,8 +1187,9 @@ class ReaderClass extends AppCommon { if (typeof EpubeApp != "undefined") { window.setTimeout(function() { - const bg_color = window.getComputedStyle(document.querySelector("body"), null) - .getPropertyValue("background-color"); + const body = document.querySelector("body"); + const bg_color = body ? window.getComputedStyle(body, null) + .getPropertyValue("background-color") : ""; let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); @@ -1197,8 +1199,9 @@ class ReaderClass extends AppCommon { EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3])); } - const accent_color = window.getComputedStyle(document.querySelector(".header .title"), null) - .getPropertyValue("color"); + const title = document.querySelector(".header .title"); + const accent_color = title ? window.getComputedStyle(title, null) + .getPropertyValue("color") : ""; match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); @@ -1260,7 +1263,10 @@ class ReaderClass extends AppCommon { if (this.book && this.book.rendition) this.book.rendition.getContents().forEach((rendition) => { - width += parseInt(rendition.window.getComputedStyle(rendition.document.querySelector('body')).getPropertyValue('padding-left')); + const body = rendition.document.querySelector('body'); + + if (body) + width += parseInt(rendition.window.getComputedStyle(body).getPropertyValue('padding-left')); }); console.log(`resizing side columns to ${width} px`); |
