about summary refs log tree commit diff stats
path: root/dist/app.min.js
diff options
context:
space:
mode:
Diffstat (limited to 'dist/app.min.js')
-rw-r--r--dist/app.min.js2
1 files changed, 1 insertions, 1 deletions
diff --git a/dist/app.min.js b/dist/app.min.js
index 57ed9d2..5c1eb1f 100644
--- a/dist/app.min.js
+++ b/dist/app.min.js
@@ -1 +1 @@
-"use strict";class Cookie{static set(t,e,o){const a=new Date;a.setTime(a.getTime()+1e3*o);const n="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+"; "+n}static get(t){t+="=";const e=document.cookie.split(";");for(let o=0;o<e.length;o++){let a=e[o];for(;" "==a.charAt(0);)a=a.substring(1);if(0==a.indexOf(t))return decodeURIComponent(a.substring(t.length,a.length))}return""}static delete(t){document.cookie=t+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT"}}class AppCommon{urlParam(t){try{const e=new RegExp("[?&]"+t+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(e[1].replace(/\+/g," "))||0}catch(t){return 0}}isOnline(){return"undefined"!=typeof EpubeApp&&void 0!==EpubeApp.isOnline?EpubeApp.isOnline():navigator.onLine}initNightMode(){if("undefined"==typeof EpubeApp){if(window.matchMedia){const t=window.matchMedia("(prefers-color-scheme: dark)");t.addEventListener("change",()=>{this.applyNightMode(t.matches)}),this.applyNightMode(t.matches)}}else this.applyNightMode(EpubeApp.isNightMode())}applyNightMode(t){console.log("night mode changed to",t),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(t?"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 t=0;this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e,o)=>{if("post"!==e.type||"post"!==t.type)return;const a=typeof e.data;"object"==a?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==a&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),"favorites"==this.urlParam("mode")?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",e=>{"refresh-started"==e.data&&(console.log("cache refresh started"),t=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),e.data&&0==e.data.indexOf("refreshed:")&&(++t,$(".dl-progress").fadeIn().text("Updated "+t+" files...")),"refresh-finished"==e.data&&(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?).")}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(t){const e=t.getAttribute("data-book-id");if(this.isOnline()){const t=await $.post("backend.php",{op:"getinfo",id:e}),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}else{const t=await localforage.getItem("epube-book."+e),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((t,e)=>{const o=$(e);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(t){const e=t.getAttribute("data-book-id");return("0"==t.getAttribute("data-is-fav")||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:e},o=>{if(o){let a="[Error]";0==o.status?a="Add to favorites":1==o.status&&(a="Remove from favorites"),$(t).html(a).attr("data-is-fav",o.status),"favorites"==this.index_mode&&0==o.status&&$("#cell-"+e).remove()}}),!1}async refreshCache(t){if("serviceWorker"in navigator){const e=await localforage.getItem("epube.cache-version");if(console.log("local version",e,"remote version",this.version),t||e!=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 t=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",t),t?$(".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()}),3e3))}}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 t=$(".offline_dropitem");$.each(t,(t,e)=>{this.updateOfflinePrompt(e)})}async updateOfflinePrompt(t){const e=t.getAttribute("data-book-id"),o="epube-book."+e;await localforage.getItem(o)?(t.onclick=()=>(this.remove(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Remove offline data"):(t.onclick=()=>(this.get(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Make available offline")}offlineInit(){"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode();const t=this.urlParam("query");t&&$(".search_query").val(t),this.populateList()}get(t,e){console.log("offline cache: "+t),$.post("backend.php",{op:"getinfo",id:t},o=>{if(o){const a="epube-book."+t;localforage.setItem(a,o).then(o=>{console.log(a+" got data");const n=[];n.push(fetch("backend.php?op=download&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got book"),localforage.setItem(a+".book",t.blob()))}))),n.push(fetch("backend.php?op=getpagination&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got pagination"),t.text().then((function(t){localforage.setItem(a+".locations",JSON.parse(t))})))}))),n.push(fetch("backend.php?op=getlastread&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got lastread"),t.text().then((function(t){localforage.setItem(a+".lastread",JSON.parse(t))})))}))),o.has_cover&&n.push(fetch("backend.php?op=cover&id="+t,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got cover"),localforage.setItem(a+".cover",t.blob()))}))),Promise.all(n).then(()=>{console.log("download done, running callback",e),e(),$(".dl-progress").show().html("Finished downloading <b>"+o.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout((function(){$(".dl-progress").fadeOut()}),5e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((t,e)=>{const o=$(e).attr("id").replace("cell-",""),a=$(e).find(".offline_dropitem")[0];if(o){const t="epube-book."+o;localforage.getItem(t).then(t=>{t||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(t){const e=t.getAttribute("data-book-id");this.remove(e,()=>{$("#cell-"+e).remove()})}remove(t,e){if(confirm("Remove download?")){const o="epube-book."+t,a=[];console.log("offline remove: "+t),localforage.iterate((function(t,e){e.match(o)&&a.push(localforage.removeItem(e))})),Promise.all(a).then(()=>{console.log("remove done, running callback",e),window.setTimeout(()=>{e()},250)})}}async search(){const t=$(".search_query").val();return await localforage.setItem("epube.search-query",t),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const t=[];localforage.iterate((function(e,o){o.match("epube-book")&&t.push(localforage.removeItem(o))})),await Promise.all(t),this.populateList()}}populateList(){let t=this.urlParam("query");t&&(t=String(t).toLowerCase());const e=$("#books_container");e.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(o){if(o[0]&&o[3]){const a=o[0];if(t){if(!(a.series_name&&a.series_name.toLowerCase().match(t)||a.title&&a.title.toLowerCase().match(t)||a.author_sort&&a.author_sort.toLowerCase().match(t)))return}let n="";o&&o[1]&&(n=URL.createObjectURL(o[1]));let i=!1,s=!1;const l=o[2];l&&(i=l.page>0,s=l.total>0&&l.total-l.page<5);const r=s?"read":"",c=i?"in_progress":"",d=a.series_name?`<div><a class="series_link" href="#">${a.series_name+" ["+a.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${a.id}">\n\t\t\t\t\t\t<a class="thumbnail ${r}" href="read.html?id=${a.epub_id}&b=${a.id}">\n\t\t\t\t\t\t\t<img style="display : none">\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div class="caption">\n\t\t\t\t\t\t\t<div><a class="${c}" href="read.html?id=${a.epub_id}&b=${a.id}">${a.title}</a></div>\n\t\t\t\t\t\t\t<div><a class="author_link" href="#">${a.author_sort}</a></div>\n\t\t\t\t\t\t\t${d}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="dropdown" style="white-space : nowrap">\n\t\t\t\t\t\t\t<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>\n\t\t\t\t\t\t\t<ul class="dropdown-menu">\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="return App.showSummary(this)">Summary</a></li>\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="App.removeFromList(this)">Remove offline data</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>`);n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",a.series_name+" ["+a.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(a.series_name)),h.find(".author_link").attr("title",a.author_sort).attr("href","offline.html?query="+encodeURIComponent(a.author_sort)),e.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;init(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e)=>{if("post"!==e.type||"post"!==t.type)return;const o=typeof e.data;"object"==o?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==o&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$("#left").on("mouseup",()=>{this.prevPage()}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader,this.loader.init(t=>{t?this.applyTheme():this.initSecondStage()})}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(t){if(console.log("onOfflineModeChanged",t),!t&&this.book){const t=this.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=Math.round(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:e,timestamp:(new Date).getTime()},(function(){})).fail((function(t){t&&401==t.status&&(window.location.href="index.php")}))}}async initSecondStage(){"undefined"!=typeof EpubeApp?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme();if(!await localforage.getItem(this.cacheId())){const t=this.urlParam("b");console.log("requesting bookinfo for book",t);try{const e=await $.post("backend.php",{op:"getinfo",id:t});if(e.has_cover){const e=await fetch("backend.php?op=cover&id="+t);e.ok&&await localforage.setItem(this.cacheId("cover"),e.blob())}await localforage.setItem(this.cacheId(),e),console.log("bookinfo saved")}catch(t){return void $(".loading-message").html(`Unable to load book info.<br/><small>${t.responseText}</small>`)}}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…");const e=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(!e.ok)return void $(".loading-message").html("Unable to download book: "+e.status);if(t=await e.blob(),!t)return void $(".loading-message").html("Unable to get book blob data.");await localforage.setItem(this.cacheId("book"),t),console.log("saved local data for book")}const e=new FileReader,o=this;e.onload=function(){try{o.openBookData(this.result)}catch(t){console.error(t),$(".loading-message").html("Unable to load book blob: "+t)}},e.onerror=t=>{console.log("filereader error",t),$(".loading-message").html("Unable to open book.<br/><small>"+t+"</small>")},e.readAsArrayBuffer(t)}async openBookData(t){const e=ePub();this.book=e;try{await e.open(t)}catch(t){return console.error(t),void $(".loading-message").html("Unable to open book.<br/><small>"+t.message+"</small>")}await e.ready,console.log("book is ready"),await this.showBookInfo(e),await this.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",String(t));n&&await o.display(e.locations._locations[10*parseInt(n)])});await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(e,o),this.initModals(),this.initToc(e),this.blockLastReadUpdate(),await o.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(t){const e=await localforage.getItem(this.cacheId());let o,a;if(e)o=e.title,a=e.author_sort;else{const e=t.package.metadata;o=e.title,a=e.creator}document.title=o+" – "+a+" – The Epube",$(".title").text(o).attr("title",o+" – "+a),"undefined"!=typeof EpubeApp&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(t){let e=await localforage.getItem(this.cacheId("locations"));if(e&&"string"==typeof e[0]){console.log("loading local locations...");try{return void await t.locations.load(e)}catch(t){console.warn(t)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations…");const o=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(o.ok){console.log("got locations from server");try{e=await o.json()}catch(t){console.warn(t)}if(e&&"string"==typeof e[0]){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),e);try{return void t.locations.load(e)}catch(t){console.warn(t)}}}}$(".loading-message").html("Preparing locations…");let o=0;e=await t.locations.generate(100,t=>{if(o||(o=t.length()),o>0){const e=Math.round(100*(1-t.length()/o));$(".loading-message").html(`Preparing locations (${e}%)…`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(e),total:100}),await localforage.setItem(this.cacheId("locations"),e)}initRenditionHooks(t,e){console.log("initRenditionHooks"),t.spine.hooks.content.register(t=>{this.cleanupEmbeddedStyles(t)}),e.hooks.content.register(async o=>{o.on("linkClicked",t=>{console.log("linkClicked",t),this.blockLastReadUpdate(),-1==t.indexOf("://")&&($(".prev_location_btn").attr("data-location-cfi",e.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async e=>{if(this.isOnline()){const a=await t.getRange(e),n=a.endContainer.data.substring(a.startOffset,a.endOffset);console.log("selected",e,n),n.match(/^[\w­]+$/)&&this.lookupWord(n,()=>{"undefined"!=typeof EpubeApp&&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 n=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+n),console.log("contents",o),$(o.window).on("click tap",t=>{if(0==t.button){if($(".modal").is(":visible"))return;"undefined"!=typeof EpubeApp?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async t=>{await localforage.getItem("epube.enable-wheel")&&(t.originalEvent.deltaY>0?this.nextPage():t.originalEvent.deltaY<0&&this.prevPage())})}),e.on("keyup",t=>{this.hotkeyHandler(t)}),e.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),e.on("rendered",async o=>{console.log("rendition rendered section",o),this.applyTheme(),this.resizeSideColumns();try{const o=e.currentLocation();if(o.start){const e=t.canonical(o.start.href);let a={};$.each(this.flattenToc(t),(function(o,n){t.spine.get(n.href).canonical!=e||(a=n)})),a&&a.label&&$(".chapter_title").html(a.label.trim()+" | "),this.generateTocBar(t,this.flattenToc(t))}}catch(t){console.warn(t)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),e.on("displayed",(function(){console.log("rendition displayed")})),e.on("relocated",e=>this.onRelocated(t,e))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const t=await localforage.getItem(this.cacheId("lastread"));t&&t.cfi&&$(".lastread_input").val(t.page+"%").attr("title","[local] "+t.cfi),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title","[remote] "+t.cfi)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",(function(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",(function(t){localforage.setItem("epube.enable-wheel",t.target.checked)})),"undefined"!=typeof EpubeApp?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",(function(t){localforage.setItem("epube.keep-ui-visible",t.target.checked)}));const e=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o}\n\t\t\t\t&mdash; ${parseInt(e)?new Date(1e3*e).toLocaleString("en-GB"):"Unknown"}\n\t\t\t\t(${this.isOnline()?"<span class='text-success'>Online</span>":"<span class='text-danger'>Offline</span>"})\n\t\t\t\t`),$(".font_family").val(await localforage.getItem("epube.fontFamily")||"Arial"),$(".theme_name").val(await localforage.getItem("epube.theme")||"default");const a=$(".font_size").html("");for(let t=10;t<=32;t++){const e=$("<option>").val(t).html(t+" px");a.append(e)}a.val(await localforage.getItem("epube.fontSize")||16);const n=$(".line_height").html("");for(let t=100;t<=220;t+=10){const e=$("<option>").val(t).html(t+"%");n.append(e)}n.val(await localforage.getItem("epube.lineHeight")||140)}),$("#dict-modal").on("shown.bs.modal",(function(){$(".dict_result").scrollTop(0)})),$(".dict_search_btn").on("click",(function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})),$(".wiki_search_btn").on("click",(function(){$(".dict_result").html("Loading, please wait..."),$.post("backend.php",{op:"wikisearch",query:$(".dict_query").val()}).then(t=>{try{console.log("wikisearch resp",t);let e="";$.each(t.query.pages,(t,o)=>{e+=o.extract}),$(".dict_result").html(e&&"undefined"!=e?e:"No definition found for "+$(".dict_query").val()+".")}catch(t){console.error(t),$(".dict_result").text("Error while processing data: "+t)}}).fail(t=>{console.error(t),$(".dict_result").text("Error while retrieving data.")})}))}initToc(t){const e=this;function o(o){try{const a=t.spine.get(o).cfiBase,n=t.locations._locations.find((function(t){return-1!=t.indexOf(a)}));return Math.round(e.book.locations.locationFromCfi(n)/10)}catch(t){console.warn(t)}return""}$("#toc-modal").on("shown.bs.modal",(function(){const e=t.navigation.toc,a=$(".toc_list");a.html(""),$.each(e,(function(e,n){try{const e=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(e.attr("data-href"))}));a.append($("<li>").append(e)),function e(a,n,i){if(3==i)return!1;if(a.subitems){const s=$("<ul class='toc_sublist list-unstyled'>");$.each(a.subitems,(function(a,n){const l=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(l.attr("data-href"))}));s.append($("<li>").append(l)),e(n,s,i+1)})),n.append(s)}}(n,a,0)}catch(t){console.warn(t)}})),a.children().length<=1&&(a.html(""),$.each(t.spine.items,(function(e,o){const n=$("<a>").attr("href","#").attr("title",o.url).html("Section "+(e+1)).attr("data-href",o.href).on("click",()=>{t.rendition.display(n.attr("data-href"))});a.append($("<li>").append(n))})))}))}cleanupEmbeddedStyles(t){$(t).find("p").filter((t,e)=>$(e).text().length>=32?e:null).css("text-align","justify"),$(t).find("html").attr("class",""),$(t).find("pre").css("white-space","pre-wrap"),$(t).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, 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",""),$(t).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),void 0!==this.hyphenate.en&&$(t).find("p, div").each((t,e)=>{const o=$(e);o.html(this.hyphenate.en(o.html())),o.html(this.hyphenate.ru(o.html()))})}generateFontsCss(t){return`\n\t\t\t/** Calibri */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibriz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrib.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrii.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibri.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Cambria */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambria.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Caecilia */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caecilia.ttf"]});\n\t\t\t\tfont-weight : normal;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliab.ttf"]});\n\t\t\t\tfont-weight : bold;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliai.ttf"]});\n\t\t\t\tfont-style : italic;\n\t\t\t}\n\n\t\t\t/** Palatino */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palabi.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/pala.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Consolas */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consola.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** IBM Plex Mono */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Bold.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-BoldItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-TextItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Text.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\t\t\t`}flattenTocSubItems(t,e){let o=[];return 3!=e&&(t.subitems&&$.each(t.subitems,(t,a)=>{a._nest=e,o.push(a),o=o.concat(this.flattenTocSubItems(a,e+1))}),o)}flattenToc(t){if(this._flattened_toc)return this._flattened_toc;{let e=[];return $.each(t.navigation.toc,(t,o)=>{o._nest=0,e.push(o),e=e.concat(this.flattenTocSubItems(o,1))}),this._flattened_toc=e,e}}generateTocBar(t,e){$(".spacer").html(""),$.each(e,(function(e,o){try{const e=t.spine.get(o.href).cfiBase,a=t.locations._locations.find((function(t){return-1!=t.indexOf(e)}));if(a){const e=Math.round(100*t.locations.percentageFromCfi(a));$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",o._nest).css("left",e+"%").css("_width",3-o._nest+"px").attr("title",o.label))}}catch(t){console.warn(t)}})),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(t,t.rendition.currentLocation())}updateTocBarPosition(t,e){const o=Math.round(e.start.location/t.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let t=await localforage.getItem("epube.fontSize"),e=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");t=t?t+"px":"16px",e=e||"Arial",o=o?o+"%":"140%",console.log("style",e,t,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":t,"font-family":"'"+e+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let a=await localforage.getItem("epube.theme")||"default";console.log("called for theme",a),"default"==a&&"undefined"!=typeof EpubeApp&&EpubeApp.isNightMode()&&(a="night"),console.log("setting main UI theme",a),$("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("epube-reader theme-"+a).attr("data-is-loading","false"),"undefined"!=typeof EpubeApp&&window.setTimeout((function(){let t=window.getComputedStyle(document.querySelector("body"),null).getPropertyValue("background-color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);t&&(console.log("sending bgcolor",t),EpubeApp.setStatusBarColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])));t=window.getComputedStyle(document.querySelector(".header .title"),null).getPropertyValue("color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),t&&(console.log("sending accent_color",t),EpubeApp.setAccentColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])))}),250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(n=>{console.log(`applying styles and theme ${a} to `,n),n.css("font-size",t),n.css("font-family","'"+e+"'"),n.css("line-height",o),n.css("text-align","justify"),$(n.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+a)})}hotkeyHandler(t){try{if($(".modal").is(":visible"))return;39!=t.which&&32!=t.which&&34!=t.which||(t.preventDefault(),this.nextPage()),37!=t.which&&33!=t.which||(t.preventDefault(),this.prevPage()),27==t.which&&(t.preventDefault(),this.showUI(!0))}catch(t){console.warn(t)}}resizeSideColumns(){let t=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(e=>{t+=parseInt(e.window.getComputedStyle(e.document.querySelector("body")).getPropertyValue("padding-left"))}),console.log(`resizing side columns to ${t} px`),$("#left, #right").width(t)}async markAsRead(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const t=100,e=this.book.locations.cfiFromPercentage(1),o=(new Date).getTime();if(this.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:t,cfi:e,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:e,page:t,total:t,timestamp:o}),await this.openLastRead()}}async close(){const t=this.book.rendition.currentLocation().start.cfi,e=Math.round(100*this.book.locations.percentageFromCfi(t)),o=(new Date).getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:e,total:100,timestamp:o}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:e,cfi:t,timestamp:o},()=>{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(t){return"epube-book."+this.urlParam("b")+(t?"."+t:"")}showUI(t){t?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()}toggleUI(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()}async lookupWord(t,e){t=t.replace(/­/g,""),console.log("lookupWord",t),$(".dict_result").html("Loading, please wait..."),$("#dict-modal").modal("show");try{const o=await $.post("backend.php",{op:"define",word:t});o&&($(".dict_result").html(o.result.join("<br/>")),$(".dict_query").val(t),e&&e())}catch(t){console.error(t),$(".dict_result").html(`Network error while looking up word: ${t.responseText}.`)}}search(){const t=$(".search_input").val(),e=$(".search_results");e.html(""),t&&(e.html("<li>Loading, please wait...</li>"),Promise.all(this.book.spine.spineItems.map(e=>e.load(this.book.load.bind(this.book)).then(e.find.bind(e,t)).finally(e.unload.bind(e)))).then(t=>Promise.resolve([].concat.apply([],t))).then(t=>{e.html(""),$.each(t,(t,o)=>{const a=$("<a>").attr("href","#").html("<b class='pull-right'>"+this.book.locations.locationFromCfi(o.cfi)+"</b>"+o.excerpt).attr("data-cfi",o.cfi).attr("data-id",o.id).on("click",()=>{this.book.rendition.display(a.attr("data-cfi"))});e.append($("<li>").append(a))})}))}nextPage(){this.book.rendition.next(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}prevPage(){this.book.rendition.prev(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}async openPrevious(t){const e=$(t).attr("data-location-cfi");e&&await this.book.rendition.display(e),$(t).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(t,e){if(0==t.locations.length())return;const o=e.start.cfi,a=Math.round(100*t.locations.percentageFromCfi(o));$("#cur_page").text(Math.floor(e.start.location/10)),$("#total_pages").text(Math.floor(t.locations.length()/10)),$("#page_pct").text(Math.round(100*t.locations.percentageFromCfi(o))+"%"),this.updateTocBarPosition(t,e);const n=e.start.displayed;if(n&&($("#chapter_cur_page").text(n.page),$("#chapter_total_pages").text(n.total),n.total>0&&$("#chapter_pct").text(Math.round(n.page/n.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const t=(new Date).getTime();console.log("storing lastread",a,o,t),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:t}),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:t}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const t=this.book.locations.length(),e=(new Date).getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:this.urlParam("id"),timestamp:e}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:t,timestamp:e}),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:-1,cfi:"",id:this.urlParam("id"),timestamp:(new Date).getTime()}),await $.post("backend.php",{op:"deletepagination",id:this.urlParam("id")}).catch(t=>console.log(t)),window.location.reload())}async openLastRead(){$(".loading").show(),$(".loading-message").html("Opening last read page…"),$("#settings-modal").modal("hide");const t=this.book.rendition;if(!t)return void console.error("no rendition to work on");let e=!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}),e=await this.moveToCfiVerify(t,a.cfi))}catch(t){console.log("unable to get remote lastread, continuing..."),console.warn(t)}if(!e&&o&&o.cfi){console.log("using local lastread cfi: "+o.cfi);try{await this.moveToCfiVerify(t,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()}calculateCfiDelta(t,e){const o=new ePub.CFI(t),a=new ePub.CFI(e);if(console.log("calculateCfiDelta",o,a),o.path.steps.length!=a.path.steps.length)return-1;let n=0;for(let t=0;t<o.path.steps.length;t++){if(o.path.steps[t].type!=a.path.steps[t].type)return-1;if(o.path.steps[t].id!=a.path.steps[t].id)return-1;null===o.path.steps[t].id&&"element"===o.path.steps[t].type&&(n+=Math.abs(o.path.steps[t].index-a.path.steps[t].index))}return n}async moveToCfiVerify(t,e,o=5,a=5){for(let n=1;n<o;n++){this.blockLastReadUpdate(),console.log(`trying to open ${e}: attempt ${n} of ${o}...`),await t.display(e);let i=!1;try{i=t.currentLocation().start.cfi}catch(t){console.warn("location not yet available, will retry:",t)}try{const t=this.calculateCfiDelta(e,i);if(console.log(`opened cfi ${i} expected ${e}; delta: ${t}`),i==e||-1!=t&&t<=a)return console.log("cfi move verified!"),!0}catch(t){console.warn("exception while parsing cfi, will retry: ",t)}}return!1}async onThemeChanged(t){const e=$(t).val();await localforage.setItem("epube.theme",e),this.applyTheme()}async onLineHeightChanged(t){const e=$(t).val();await localforage.setItem("epube.lineHeight",e),this.applyTheme()}async onTextSizeChanged(t){const e=$(t).val();await localforage.setItem("epube.fontSize",e),this.applyTheme()}async onFontChanged(t){const e=$(t).val();await localforage.setItem("epube.fontFamily",e),this.applyTheme()}}class ReaderLoader{_res_data=[];CACHE_NAME="epube-v3";async init(t){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const e=[];let o=!1;const a=await caches.open(this.CACHE_NAME);(await a.keys()).forEach(t=>{if(!t.url.match("backend.php")){console.log("[loader] loading resource",t.url);const a=fetch(t.url).then(async e=>{if(e.ok){const t=new URL(e.url);if(t.searchParams.delete("ts"),e.url.match("\\.ttf|\\.otf")){const o=await e.blob();console.log("[loader] storing blob",t.href),this._res_data[t.toString()]=URL.createObjectURL(o)}else{const o=await e.text();console.log("[loader] storing text",t.href),this._res_data[t.toString()]=o}}else console.warn("[loader] failed for resource",t.url,e),$(".loading-message").html(`Unable to load resource.<br/><small>${t.url}</small>`),o=!0});e.push(a)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",o),t(o)}}
\ No newline at end of file
+import localforage from"localforage";import{AppCommon}from"./appcommon";import{Cookie}from"./cookie";export class AppClass extends AppCommon{constructor(){super(...arguments),this.index_mode="",this.cached_urls=[],this.version="UNKNOWN",this.buildTimestamp=0,this.csrf_token=""}init(){let t=0;this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e,o)=>{if("post"!==e.type||"post"!==t.type)return;const a=typeof e.data;"object"==a?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==a&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),"favorites"==this.urlParam("mode")?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",e=>{"refresh-started"==e.data&&(console.log("cache refresh started"),t=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),e.data&&0==e.data.indexOf("refreshed:")&&(++t,$(".dl-progress").fadeIn().text("Updated "+t+" files...")),"refresh-finished"==e.data&&(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?).")}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(t){const e=t.getAttribute("data-book-id");if(this.isOnline()){const t=await $.post("backend.php",{op:"getinfo",id:e}),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}else{const t=await localforage.getItem("epube-book."+e),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((t,e)=>{const o=$(e);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(t){const e=t.getAttribute("data-book-id");return("0"==t.getAttribute("data-is-fav")||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:e},o=>{if(o){let a="[Error]";0==o.status?a="Add to favorites":1==o.status&&(a="Remove from favorites"),$(t).html(a).attr("data-is-fav",o.status),"favorites"==this.index_mode&&0==o.status&&$("#cell-"+e).remove()}}),!1}async refreshCache(t=!1){if("serviceWorker"in navigator){const e=await localforage.getItem("epube.cache-version");if(console.log("local version",e,"remote version",this.version),t||e!=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 t=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",t),t?$(".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()}),3e3))}}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 t=$(".offline_dropitem");$.each(t,(t,e)=>{this.updateOfflinePrompt(e)})}async updateOfflinePrompt(t){const e=t.getAttribute("data-book-id"),o="epube-book."+e;await localforage.getItem(o)?(t.onclick=()=>(this.remove(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Remove offline data"):(t.onclick=()=>(this.get(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Make available offline")}offlineInit(){"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode();const t=this.urlParam("query");t&&$(".search_query").val(t),this.populateList()}get(t,e){console.log("offline cache: "+t),$.post("backend.php",{op:"getinfo",id:t},o=>{if(o){const a="epube-book."+t;localforage.setItem(a,o).then(o=>{console.log(a+" got data");const n=[];n.push(fetch("backend.php?op=download&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got book"),localforage.setItem(a+".book",t.blob()))}))),n.push(fetch("backend.php?op=getpagination&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got pagination"),t.text().then((function(t){localforage.setItem(a+".locations",JSON.parse(t))})))}))),n.push(fetch("backend.php?op=getlastread&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got lastread"),t.text().then((function(t){localforage.setItem(a+".lastread",JSON.parse(t))})))}))),o.has_cover&&n.push(fetch("backend.php?op=cover&id="+t,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got cover"),localforage.setItem(a+".cover",t.blob()))}))),Promise.all(n).then(()=>{console.log("download done, running callback",e),e(),$(".dl-progress").show().html("Finished downloading <b>"+o.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout((function(){$(".dl-progress").fadeOut()}),5e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((t,e)=>{const o=$(e).attr("id").replace("cell-",""),a=$(e).find(".offline_dropitem")[0];if(o){const t="epube-book."+o;localforage.getItem(t).then(t=>{t||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(t){const e=t.getAttribute("data-book-id");this.remove(e,()=>{$("#cell-"+e).remove()})}remove(t,e){if(confirm("Remove download?")){const o="epube-book."+t,a=[];console.log("offline remove: "+t),localforage.iterate((function(t,e){e.match(o)&&a.push(localforage.removeItem(e))})),Promise.all(a).then(()=>{console.log("remove done, running callback",e),window.setTimeout(()=>{e()},250)})}}async search(){const t=$(".search_query").val();return await localforage.setItem("epube.search-query",t),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const t=[];localforage.iterate((function(e,o){o.match("epube-book")&&t.push(localforage.removeItem(o))})),await Promise.all(t),this.populateList()}}populateList(){let t=this.urlParam("query");t&&(t=String(t).toLowerCase());const e=$("#books_container");e.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(o){if(o[0]&&o[3]){const a=o[0];if(t){if(!(a.series_name&&a.series_name.toLowerCase().match(t)||a.title&&a.title.toLowerCase().match(t)||a.author_sort&&a.author_sort.toLowerCase().match(t)))return}let n="";o&&o[1]&&(n=URL.createObjectURL(o[1]));let i=!1,s=!1;const l=o[2];l&&(i=l.page>0,s=l.total>0&&l.total-l.page<5);const r=s?"read":"",c=i?"in_progress":"",d=a.series_name?`<div><a class="series_link" href="#">${a.series_name+" ["+a.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${a.id}">\n\t\t\t\t\t\t<a class="thumbnail ${r}" href="read.html?id=${a.epub_id}&b=${a.id}">\n\t\t\t\t\t\t\t<img style="display : none">\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div class="caption">\n\t\t\t\t\t\t\t<div><a class="${c}" href="read.html?id=${a.epub_id}&b=${a.id}">${a.title}</a></div>\n\t\t\t\t\t\t\t<div><a class="author_link" href="#">${a.author_sort}</a></div>\n\t\t\t\t\t\t\t${d}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="dropdown" style="white-space : nowrap">\n\t\t\t\t\t\t\t<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>\n\t\t\t\t\t\t\t<ul class="dropdown-menu">\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="return App.showSummary(this)">Summary</a></li>\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="App.removeFromList(this)">Remove offline data</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>`);n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",a.series_name+" ["+a.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(a.series_name)),h.find(".author_link").attr("title",a.author_sort).attr("href","offline.html?query="+encodeURIComponent(a.author_sort)),e.append(h)}}))}))}}export class AppCommon{urlParam(t){try{const e=new RegExp("[?&]"+t+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(e[1].replace(/\+/g," "))||0}catch(t){return 0}}isOnline(){return"undefined"!=typeof EpubeApp&&void 0!==EpubeApp.isOnline?EpubeApp.isOnline():navigator.onLine}initNightMode(){if("undefined"==typeof EpubeApp){if(window.matchMedia){const t=window.matchMedia("(prefers-color-scheme: dark)");t.addEventListener("change",()=>{this.applyNightMode(t.matches)}),this.applyNightMode(t.matches)}}else this.applyNightMode(EpubeApp.isNightMode())}applyNightMode(t){console.log("night mode changed to",t),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(t?"theme-dark.min.css":"bootstrap-theme.min.css"))}}export class Cookie{static set(t,e,o){const a=new Date;a.setTime(a.getTime()+1e3*o);const n="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+"; "+n}static get(t){t+="=";const e=document.cookie.split(";");for(let o=0;o<e.length;o++){let a=e[o];for(;" "==a.charAt(0);)a=a.substring(1);if(0==a.indexOf(t))return decodeURIComponent(a.substring(t.length,a.length))}return""}static delete(t){document.cookie=t+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT"}}import localforage from"localforage";import{Cookie}from"./cookie";import{AppCommon}from"./appcommon";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;export class ReaderClass extends AppCommon{constructor(){super(...arguments),this.csrf_token="",this.last_stored_cfi="",this.startup_finished=!1,this.open_last_read_when_displayed=!0}init(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e)=>{if("post"!==e.type||"post"!==t.type)return;const o=typeof e.data;"object"==o?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==o&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$("#left").on("mouseup",()=>{this.prevPage()}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader,this.loader.init(t=>{t?this.applyTheme():this.initSecondStage()})}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(t){if(console.log("onOfflineModeChanged",t),!t&&this.book){const t=this.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=Math.round(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:e,timestamp:(new Date).getTime()},(function(){})).fail((function(t){t&&401==t.status&&(window.location.href="index.php")}))}}async initSecondStage(){"undefined"!=typeof EpubeApp?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme();if(!await localforage.getItem(this.cacheId())){const t=this.urlParam("b");console.log("requesting bookinfo for book",t);try{const e=await $.post("backend.php",{op:"getinfo",id:t});if(e.has_cover){const e=await fetch("backend.php?op=cover&id="+t);e.ok&&await localforage.setItem(this.cacheId("cover"),e.blob())}await localforage.setItem(this.cacheId(),e),console.log("bookinfo saved")}catch(t){return void $(".loading-message").html(`Unable to load book info.<br/><small>${t.responseText}</small>`)}}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…");const e=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(!e.ok)return void $(".loading-message").html("Unable to download book: "+e.status);if(t=await e.blob(),!t)return void $(".loading-message").html("Unable to get book blob data.");await localforage.setItem(this.cacheId("book"),t),console.log("saved local data for book")}const e=new FileReader,o=this;e.onload=function(){try{o.openBookData(this.result)}catch(t){console.error(t),$(".loading-message").html("Unable to load book blob: "+t)}},e.onerror=t=>{console.log("filereader error",t),$(".loading-message").html("Unable to open book.<br/><small>"+t+"</small>")},e.readAsArrayBuffer(t)}async openBookData(t){const e=ePub();this.book=e;try{await e.open(t)}catch(t){return console.error(t),void $(".loading-message").html("Unable to open book.<br/><small>"+t.message+"</small>")}await e.ready,console.log("book is ready"),await this.showBookInfo(e),await this.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",String(t));n&&await o.display(e.locations._locations[10*parseInt(n)])});await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(e,o),this.initModals(),this.initToc(e),this.blockLastReadUpdate(),await o.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(t){const e=await localforage.getItem(this.cacheId());let o,a;if(e)o=e.title,a=e.author_sort;else{const e=t.package.metadata;o=e.title,a=e.creator}document.title=o+" – "+a+" – The Epube",$(".title").text(o).attr("title",o+" – "+a),"undefined"!=typeof EpubeApp&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(t){let e=await localforage.getItem(this.cacheId("locations"));if(e&&"string"==typeof e[0]){console.log("loading local locations...");try{return void await t.locations.load(e)}catch(t){console.warn(t)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations…");const o=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(o.ok){console.log("got locations from server");try{e=await o.json()}catch(t){console.warn(t)}if(e&&"string"==typeof e[0]){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),e);try{return void t.locations.load(e)}catch(t){console.warn(t)}}}}$(".loading-message").html("Preparing locations…");let o=0;e=await t.locations.generate(100,t=>{if(o||(o=t.length()),o>0){const e=Math.round(100*(1-t.length()/o));$(".loading-message").html(`Preparing locations (${e}%)…`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(e),total:100}),await localforage.setItem(this.cacheId("locations"),e)}initRenditionHooks(t,e){console.log("initRenditionHooks"),t.spine.hooks.content.register(t=>{this.cleanupEmbeddedStyles(t)}),e.hooks.content.register(async o=>{o.on("linkClicked",t=>{console.log("linkClicked",t),this.blockLastReadUpdate(),-1==t.indexOf("://")&&($(".prev_location_btn").attr("data-location-cfi",e.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async e=>{if(this.isOnline()){const a=await t.getRange(e),n=a.endContainer.data.substring(a.startOffset,a.endOffset);console.log("selected",e,n),n.match(/^[\w­]+$/)&&this.lookupWord(n,()=>{"undefined"!=typeof EpubeApp&&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 n=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+n),console.log("contents",o),$(o.window).on("click tap",t=>{if(0==t.button){if($(".modal").is(":visible"))return;"undefined"!=typeof EpubeApp?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async t=>{await localforage.getItem("epube.enable-wheel")&&(t.originalEvent.deltaY>0?this.nextPage():t.originalEvent.deltaY<0&&this.prevPage())})}),e.on("keyup",t=>{this.hotkeyHandler(t)}),e.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),e.on("rendered",async o=>{console.log("rendition rendered section",o),this.applyTheme(),this.resizeSideColumns();try{const o=e.currentLocation();if(o.start){const e=t.canonical(o.start.href);let a={};$.each(this.flattenToc(t),(function(o,n){t.spine.get(n.href).canonical!=e||(a=n)})),a&&a.label&&$(".chapter_title").html(a.label.trim()+" | "),this.generateTocBar(t,this.flattenToc(t))}}catch(t){console.warn(t)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),e.on("displayed",(function(){console.log("rendition displayed")})),e.on("relocated",e=>this.onRelocated(t,e))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const t=await localforage.getItem(this.cacheId("lastread"));t&&t.cfi&&$(".lastread_input").val(t.page+"%").attr("title","[local] "+t.cfi),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title","[remote] "+t.cfi)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",(function(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",(function(t){localforage.setItem("epube.enable-wheel",t.target.checked)})),"undefined"!=typeof EpubeApp?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",(function(t){localforage.setItem("epube.keep-ui-visible",t.target.checked)}));const e=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o}\n\t\t\t\t&mdash; ${parseInt(e)?new Date(1e3*parseInt(e)).toLocaleString("en-GB"):"Unknown"}\n\t\t\t\t(${this.isOnline()?"<span class='text-success'>Online</span>":"<span class='text-danger'>Offline</span>"})\n\t\t\t\t`),$(".font_family").val(await localforage.getItem("epube.fontFamily")||"Arial"),$(".theme_name").val(await localforage.getItem("epube.theme")||"default");const a=$(".font_size").html("");for(let t=10;t<=32;t++){const e=$("<option>").val(t).html(t+" px");a.append(e)}a.val(await localforage.getItem("epube.fontSize")||16);const n=$(".line_height").html("");for(let t=100;t<=220;t+=10){const e=$("<option>").val(t).html(t+"%");n.append(e)}n.val(await localforage.getItem("epube.lineHeight")||140)}),$("#dict-modal").on("shown.bs.modal",(function(){$(".dict_result").scrollTop(0)})),$(".dict_search_btn").on("click",(function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})),$(".wiki_search_btn").on("click",(function(){$(".dict_result").html("Loading, please wait..."),$.post("backend.php",{op:"wikisearch",query:$(".dict_query").val()}).then(t=>{try{console.log("wikisearch resp",t);let e="";$.each(t.query.pages,(t,o)=>{e+=o.extract}),$(".dict_result").html(e&&"undefined"!=e?e:"No definition found for "+$(".dict_query").val()+".")}catch(t){console.error(t),$(".dict_result").text("Error while processing data: "+t)}}).fail(t=>{console.error(t),$(".dict_result").text("Error while retrieving data.")})}))}initToc(t){const e=this;function o(o){try{const a=t.spine.get(o).cfiBase,n=t.locations._locations.find((function(t){return-1!=t.indexOf(a)}));return Math.round(e.book.locations.locationFromCfi(n)/10)}catch(t){console.warn(t)}return""}$("#toc-modal").on("shown.bs.modal",(function(){const e=t.navigation.toc,a=$(".toc_list");a.html(""),$.each(e,(function(e,n){try{const e=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(e.attr("data-href"))}));a.append($("<li>").append(e)),function e(a,n,i){if(3==i)return!1;if(a.subitems){const s=$("<ul class='toc_sublist list-unstyled'>");$.each(a.subitems,(function(a,n){const l=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(l.attr("data-href"))}));s.append($("<li>").append(l)),e(n,s,i+1)})),n.append(s)}}(n,a,0)}catch(t){console.warn(t)}})),a.children().length<=1&&(a.html(""),$.each(t.spine.items,(function(e,o){const n=$("<a>").attr("href","#").attr("title",o.url).html("Section "+(e+1)).attr("data-href",o.href).on("click",()=>{t.rendition.display(n.attr("data-href"))});a.append($("<li>").append(n))})))}))}cleanupEmbeddedStyles(t){$(t).find("p").filter((t,e)=>$(e).text().length>=32?e:null).css("text-align","justify"),$(t).find("html").attr("class",""),$(t).find("pre").css("white-space","pre-wrap"),$(t).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, 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",""),$(t).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),void 0!==this.hyphenate.en&&$(t).find("p, div").each((t,e)=>{const o=$(e);o.html(this.hyphenate.en(o.html())),o.html(this.hyphenate.ru(o.html()))})}generateFontsCss(t){return`\n\t\t\t/** Calibri */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibriz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrib.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrii.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibri.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Cambria */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambria.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Caecilia */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caecilia.ttf"]});\n\t\t\t\tfont-weight : normal;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliab.ttf"]});\n\t\t\t\tfont-weight : bold;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliai.ttf"]});\n\t\t\t\tfont-style : italic;\n\t\t\t}\n\n\t\t\t/** Palatino */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palabi.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/pala.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Consolas */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consola.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** IBM Plex Mono */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Bold.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-BoldItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-TextItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Text.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\t\t\t`}flattenTocSubItems(t,e){let o=[];return 3!=e&&(t.subitems&&$.each(t.subitems,(t,a)=>{a._nest=e,o.push(a),o=o.concat(this.flattenTocSubItems(a,e+1))}),o)}flattenToc(t){if(this._flattened_toc)return this._flattened_toc;{let e=[];return $.each(t.navigation.toc,(t,o)=>{o._nest=0,e.push(o),e=e.concat(this.flattenTocSubItems(o,1))}),this._flattened_toc=e,e}}generateTocBar(t,e){$(".spacer").html(""),$.each(e,(function(e,o){try{const e=t.spine.get(o.href).cfiBase,a=t.locations._locations.find((function(t){return-1!=t.indexOf(e)}));if(a){const e=Math.round(100*t.locations.percentageFromCfi(a));$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",o._nest).css("left",e+"%").css("_width",3-o._nest+"px").attr("title",o.label))}}catch(t){console.warn(t)}})),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(t,t.rendition.currentLocation())}updateTocBarPosition(t,e){const o=Math.round(e.start.location/t.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let t=await localforage.getItem("epube.fontSize"),e=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");t=t?t+"px":"16px",e=e||"Arial",o=o?o+"%":"140%",console.log("style",e,t,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":t,"font-family":"'"+e+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let a=await localforage.getItem("epube.theme")||"default";console.log("called for theme",a),"default"==a&&"undefined"!=typeof EpubeApp&&EpubeApp.isNightMode()&&(a="night"),console.log("setting main UI theme",a),$("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("epube-reader theme-"+a).attr("data-is-loading","false"),"undefined"!=typeof EpubeApp&&window.setTimeout((function(){let t=window.getComputedStyle(document.querySelector("body"),null).getPropertyValue("background-color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);t&&(console.log("sending bgcolor",t),EpubeApp.setStatusBarColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])));t=window.getComputedStyle(document.querySelector(".header .title"),null).getPropertyValue("color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),t&&(console.log("sending accent_color",t),EpubeApp.setAccentColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])))}),250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(n=>{console.log(`applying styles and theme ${a} to `,n),n.css("font-size",t),n.css("font-family","'"+e+"'"),n.css("line-height",o),n.css("text-align","justify"),$(n.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+a)})}hotkeyHandler(t){try{if($(".modal").is(":visible"))return;39!=t.which&&32!=t.which&&34!=t.which||(t.preventDefault(),this.nextPage()),37!=t.which&&33!=t.which||(t.preventDefault(),this.prevPage()),27==t.which&&(t.preventDefault(),this.showUI(!0))}catch(t){console.warn(t)}}resizeSideColumns(){let t=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(e=>{t+=parseInt(e.window.getComputedStyle(e.document.querySelector("body")).getPropertyValue("padding-left"))}),console.log(`resizing side columns to ${t} px`),$("#left, #right").width(t)}async markAsRead(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const t=100,e=this.book.locations.cfiFromPercentage(1),o=(new Date).getTime();if(this.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:t,cfi:e,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:e,page:t,total:t,timestamp:o}),await this.openLastRead()}}async close(){const t=this.book.rendition.currentLocation().start.cfi,e=Math.round(100*this.book.locations.percentageFromCfi(t)),o=(new Date).getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:e,total:100,timestamp:o}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:e,cfi:t,timestamp:o},()=>{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(t=""){return"epube-book."+this.urlParam("b")+(t?"."+t:"")}showUI(t){t?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()}toggleUI(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()}async lookupWord(t,e){t=t.replace(/­/g,""),console.log("lookupWord",t),$(".dict_result").html("Loading, please wait..."),$("#dict-modal").modal("show");try{const o=await $.post("backend.php",{op:"define",word:t});o&&($(".dict_result").html(o.result.join("<br/>")),$(".dict_query").val(t),e&&e())}catch(t){console.error(t),$(".dict_result").html(`Network error while looking up word: ${t.responseText}.`)}}search(){const t=$(".search_input").val(),e=$(".search_results");e.html(""),t&&(e.html("<li>Loading, please wait...</li>"),Promise.all(this.book.spine.spineItems.map(e=>e.load(this.book.load.bind(this.book)).then(e.find.bind(e,t)).finally(e.unload.bind(e)))).then(t=>Promise.resolve([].concat.apply([],t))).then(t=>{e.html(""),$.each(t,(t,o)=>{const a=$("<a>").attr("href","#").html("<b class='pull-right'>"+this.book.locations.locationFromCfi(o.cfi)+"</b>"+o.excerpt).attr("data-cfi",o.cfi).attr("data-id",o.id).on("click",()=>{this.book.rendition.display(a.attr("data-cfi"))});e.append($("<li>").append(a))})}))}nextPage(){this.book.rendition.next(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}prevPage(){this.book.rendition.prev(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}async openPrevious(t){const e=$(t).attr("data-location-cfi");e&&await this.book.rendition.display(e),$(t).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(t,e){if(0==t.locations.length())return;const o=e.start.cfi,a=Math.round(100*t.locations.percentageFromCfi(o));$("#cur_page").text(Math.floor(e.start.location/10)),$("#total_pages").text(Math.floor(t.locations.length()/10)),$("#page_pct").text(Math.round(100*t.locations.percentageFromCfi(o))+"%"),this.updateTocBarPosition(t,e);const n=e.start.displayed;if(n&&($("#chapter_cur_page").text(n.page),$("#chapter_total_pages").text(n.total),n.total>0&&$("#chapter_pct").text(Math.round(n.page/n.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const t=(new Date).getTime();console.log("storing lastread",a,o,t),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:t}),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:t}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const t=this.book.locations.length(),e=(new Date).getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:this.urlParam("id"),timestamp:e}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:t,timestamp:e}),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:-1,cfi:"",id:this.urlParam("id"),timestamp:(new Date).getTime()}),await $.post("backend.php",{op:"deletepagination",id:this.urlParam("id")}).catch(t=>console.log(t)),window.location.reload())}async openLastRead(){$(".loading").show(),$(".loading-message").html("Opening last read page…"),$("#settings-modal").modal("hide");const t=this.book.rendition;if(!t)return void console.error("no rendition to work on");let e=!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}),e=await this.moveToCfiVerify(t,a.cfi))}catch(t){console.log("unable to get remote lastread, continuing..."),console.warn(t)}if(!e&&o&&o.cfi){console.log("using local lastread cfi: "+o.cfi);try{await this.moveToCfiVerify(t,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()}calculateCfiDelta(t,e){const o=new ePub.CFI(t),a=new ePub.CFI(e);if(console.log("calculateCfiDelta",o,a),o.path.steps.length!=a.path.steps.length)return-1;let n=0;for(let t=0;t<o.path.steps.length;t++){if(o.path.steps[t].type!=a.path.steps[t].type)return-1;if(o.path.steps[t].id!=a.path.steps[t].id)return-1;null===o.path.steps[t].id&&"element"===o.path.steps[t].type&&(n+=Math.abs(o.path.steps[t].index-a.path.steps[t].index))}return n}async moveToCfiVerify(t,e,o=5,a=5){for(let n=1;n<o;n++){this.blockLastReadUpdate(),console.log(`trying to open ${e}: attempt ${n} of ${o}...`),await t.display(e);let i=!1;try{i=t.currentLocation().start.cfi}catch(t){console.warn("location not yet available, will retry:",t)}try{const t=this.calculateCfiDelta(e,i);if(console.log(`opened cfi ${i} expected ${e}; delta: ${t}`),i==e||-1!=t&&t<=a)return console.log("cfi move verified!"),!0}catch(t){console.warn("exception while parsing cfi, will retry: ",t)}}return!1}async onThemeChanged(t){const e=$(t).val();await localforage.setItem("epube.theme",e),this.applyTheme()}async onLineHeightChanged(t){const e=$(t).val();await localforage.setItem("epube.lineHeight",e),this.applyTheme()}async onTextSizeChanged(t){const e=$(t).val();await localforage.setItem("epube.fontSize",e),this.applyTheme()}async onFontChanged(t){const e=$(t).val();await localforage.setItem("epube.fontFamily",e),this.applyTheme()}}class ReaderLoader{constructor(){this._res_data=[],this.CACHE_NAME="epube-v3"}async init(t){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const e=[];let o=!1;const a=await caches.open(this.CACHE_NAME);(await a.keys()).forEach(t=>{if(!t.url.match("backend.php")){console.log("[loader] loading resource",t.url);const a=fetch(t.url).then(async e=>{if(e.ok){const t=new URL(e.url);if(t.searchParams.delete("ts"),e.url.match("\\.ttf|\\.otf")){const o=await e.blob();console.log("[loader] storing blob",t.href),this._res_data[t.toString()]=URL.createObjectURL(o)}else{const o=await e.text();console.log("[loader] storing text",t.href),this._res_data[t.toString()]=o}}else console.warn("[loader] failed for resource",t.url,e),$(".loading-message").html(`Unable to load resource.<br/><small>${t.url}</small>`),o=!0});e.push(a)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",o),t(o)}}
\ No newline at end of file