about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-03-21 18:40:41 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-03-21 18:40:41 +0300
commitfc0f29c411096e847f33976ccddc9c30a1fb6600 (patch)
tree0b6e464ee18974b7592c49a5960d20f627b29d79
parentfbf06987e8f9d4ce505c5c957eb9266c79d210c4 (diff)
downloadthe-epube-fc0f29c411096e847f33976ccddc9c30a1fb6600.tar.gz
the-epube-fc0f29c411096e847f33976ccddc9c30a1fb6600.tar.xz
classy App
-rw-r--r--.eslintrc.js2
-rw-r--r--dist/app.min.js2
-rw-r--r--gulpfile.js2
-rw-r--r--index.php3
-rw-r--r--js/app.d.ts2
-rw-r--r--js/app.js697
-rw-r--r--js/localforage.d.ts123
-rw-r--r--js/reader.d.ts0
-rw-r--r--js/reader.js1
-rw-r--r--offline.html10
-rw-r--r--read.html2
11 files changed, 496 insertions, 348 deletions
diff --git a/.eslintrc.js b/.eslintrc.js
index 553c93a..9669099 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -7,7 +7,7 @@ module.exports = {
     },
     "extends": "eslint:recommended",
     "parserOptions": {
-        "ecmaVersion": 2018
+        "ecmaVersion": "latest"
     },
     "rules": {
         "accessor-pairs": "error",
diff --git a/dist/app.min.js b/dist/app.min.js
index eeb2058..baaafad 100644
--- a/dist/app.min.js
+++ b/dist/app.min.js
@@ -1 +1 @@
-"use strict";$.urlParam=function(t){try{const e=new RegExp("[?&]"+t+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(e[1].replace(/\+/g," "))||0}catch(t){return 0}};const Cookie={set:function(t,e,o){const a=new Date;a.setTime(a.getTime()+1e3*o);const n="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+"; "+n},get:function(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""},delete:function(t){document.cookie=t+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT"}},App={_dl_progress_timeout:!1,index_mode:"",cached_urls:[],version:"UNKNOWN",buildTimestamp:0,csrf_token:"",init:function(){let t=0;this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((function(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:App.csrf_token})):"string"==a&&(t.data=e.data+"&csrf_token="+encodeURIComponent(App.srf_token)),console.log(">>>",t)})),"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),"favorites"==$.urlParam("mode")?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),App.initNightMode(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",(function(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",App.version),localforage.setItem("epube.cache-timestamp",App.buildTimestamp),window.location.reload())})),App.showCovers(),App.Offline.markBooks(),App.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")},logout:function(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})},showSummary:function(t){const e=t.getAttribute("data-book-id");return $.post("backend.php",{op:"getinfo",id:e},(function(t){const e=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(e),$("#summary-modal").modal()})),!1},showCovers:function(){$("img[data-book-id]").each((t,e)=>{if((e=$(e)).attr("data-cover-link")){const t=$("<img>").on("load",(function(){e.css("background-image","url("+e.attr("data-cover-link")+")").fadeIn(),t.attr("src",null)})).attr("src",e.attr("data-cover-link"))}})},toggleFavorite:function(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},(function(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"==App.index_mode&&0==o.status&&$("#cell-"+e).remove()}})),!1},refreshCache:function(t){"serviceWorker"in navigator?localforage.getItem("epube.cache-version").then((function(e){console.log("local version",e,"remote version",App.version),(t||e!=App.version)&&(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:App.cached_urls}):localforage.getItem("epube.initial-load-done").then((function(t){console.log("initial load done",t),t?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):localforage.setItem("epube.initial-load-done",!0).then((function(){$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout((function(){window.location.reload()}),3e3)}))})))})):$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")},isOnline:function(){return"undefined"!=typeof EpubeApp&&void 0!==EpubeApp.isOnline?EpubeApp.isOnline():navigator.onLine},appCheckOffline:function(){EpubeApp.setOffline(!App.isOnline)},initNightMode:function(){if("undefined"==typeof EpubeApp){if(window.matchMedia){const t=window.matchMedia("(prefers-color-scheme: dark)");t.addEventListener("change",()=>{App.applyNightMode(t.matches)}),App.applyNightMode(t.matches)}}else App.applyNightMode(EpubeApp.isNightMode())},applyNightMode:function(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"))},Offline:{init:function(){"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),App.initNightMode();const t=$.urlParam("query");t&&$(".search_query").val(t),App.Offline.populateList()},get:function(t,e){console.log("offline cache: "+t),$.post("backend.php",{op:"getinfo",id:t},(function(o){if(o){const a="epube-book."+t;localforage.setItem(a,o).then((function(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"),e(),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((function(){$(".dl-progress").show().html("Finished downloading <b>"+o.title+"</b>"),window.clearTimeout(App._dl_progress_timeout),App._dl_progress_timeout=window.setTimeout((function(){$(".dl-progress").fadeOut()}),5e3)}))}))}}))},getAll:function(){confirm("Download all books on this page?")&&$(".row > div").each((function(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((function(t){t||App.Offline.get(o,(function(){App.Offline.mark(a)}))}))}}))},markBooks:function(){const t=$(".offline_dropitem");$.each(t,(function(t,e){App.Offline.mark(e)}))},mark:function(t){const e=t.getAttribute("data-book-id"),o="epube-book."+e;localforage.getItem(o).then((function(o){o?(t.onclick=function(){return App.Offline.remove(e,(function(){App.Offline.mark(t)})),!1},t.innerHTML="Remove offline data"):(t.onclick=function(){return App.Offline.get(e,(function(){App.Offline.mark(t)})),!1},t.innerHTML="Make available offline")}))},removeFromList:function(t){const e=t.getAttribute("data-book-id");return App.Offline.remove(e,(function(){$("#cell-"+e).remove()}))},remove:function(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((function(){window.setTimeout((function(){e()}),500)}))}},search:function(){const t=$(".search_query").val();return localforage.setItem("epube.search-query",t).then((function(){App.Offline.populateList()})),!1},removeAll:function(){if(confirm("Remove all downloaded books?")){const t=[];localforage.iterate((function(e,o){o.match("epube-book")&&t.push(localforage.removeItem(o))})),Promise.all(t).then((function(){window.setTimeout((function(){App.Offline.populateList()}),500)}))}},showSummary:function(t){const e=t.getAttribute("data-book-id");return localforage.getItem("epube-book."+e).then((function(t){const e=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(e),$("#summary-modal").modal()})),!1},populateList:function(){let t=$.urlParam("query");t&&(t=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=!1;o&&o[1]&&(n=URL.createObjectURL(o[1]));let i=!1,r=!1;const l=o[2];l&&(i=l.page>0,r=l.total>0&&l.total-l.page<5);const s=r?"read":"",c=i?"in_progress":"",d=a.series_name?`<div><a class="series_link" href="#">${a.series_name+" ["+a.series_index+"]"}</a></div>`:"",f=$(`<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\t<a class="thumbnail ${s}" href="read.html?id=${a.epub_id}&b=${a.id}">\n\t\t\t\t\t\t\t\t<img style="display : none">\n\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t<div class="caption">\n\t\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\t<div><a class="author_link" href="#">${a.author_sort}</a></div>\n\t\t\t\t\t\t\t\t${d}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class="dropdown" style="white-space : nowrap">\n\t\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\t<ul class="dropdown-menu">\n\t\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="return App.Offline.showSummary(this)">Summary</a></li>\n\t\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="App.Offline.removeFromList(this)">Remove offline data</a></li>\n\t\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>`);n?f.find("img").css("background-image","url("+n+")").fadeIn():f.fadeIn(),f.find(".series_link").attr("title",a.series_name+" ["+a.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(a.series_name)),f.find(".author_link").attr("title",a.author_sort).attr("href","offline.html?query="+encodeURIComponent(a.author_sort)),e.append(f)}}))}))}}},DEFAULT_FONT_SIZE=16,DEFAULT_FONT_FAMILY="Arial",DEFAULT_LINE_HEIGHT=140,MIN_LENGTH_TO_JUSTIFY=32,LOCATION_DIVISOR=10,PAGE_RESET_PROGRESS=-1,CACHE_PREFIX="epube",CACHE_NAME="epube-v3";Promise.allSettled=Promise.allSettled||(t=>Promise.all(t.map(t=>t.then(t=>({status:"fulfilled",value:t})).catch(t=>({status:"rejected",reason:t})))));const Reader={csrf_token:"",last_stored_cfi:"",startup_finished:!1,open_last_read_when_displayed:!0,hyphenate:{},init:function(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((function(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:Reader.csrf_token})):"string"==o&&(t.data=e.data+"&csrf_token="+encodeURIComponent(Reader.srf_token)),console.log(">>>",t)})),$(document).on("keyup",(function(t){Reader.hotkeyHandler(t)})),$("#left").on("mouseup",(function(){Reader.Page.prev()})),$("#right").on("mouseup",(function(){Reader.Page.next()})),Reader.Loader.init()},isTouchDevice:function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0},onOfflineModeChanged:function(t){if(console.log("onOfflineModeChanged",t),!t&&window.book){const t=window.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=parseInt(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:o,cfi:e,timestamp:(new Date).getTime()},(function(){})).fail((function(t){t&&401==t.status&&(window.location="index.php")}))}},initSecondStage:async function(){"undefined"!=typeof EpubeApp?EpubeApp.setPage("PAGE_READER"):($(window).on("online",(function(){Reader.onOfflineModeChanged(!1)})),$(window).on("offline",(function(){Reader.onOfflineModeChanged(!0)}))),Reader.applyTheme();if(!await localforage.getItem(Reader.cacheId())){const t=$.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(Reader.cacheId("cover"),e.blob())}await localforage.setItem(Reader.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(Reader.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="+$.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(Reader.cacheId("book"),t),console.log("saved local data for book")}const e=new FileReader;e.onload=function(){try{Reader.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)},openBookData:async function(t){const e=ePub();window.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 Reader.showBookInfo(e),await Reader.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",(async function(){const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",t);n&&await o.display(e.locations._locations[10*n])}));await localforage.getItem("epube.enable-hyphens")&&(Reader.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),Reader.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),Reader.initRenditionHooks(e,o),Reader.initModals(),Reader.initToc(e),Reader.Page.blockLastReadUpdate(),await o.display(),console.log("startup finished"),Reader.startup_finished=!0},showBookInfo:async function(t){const e=await localforage.getItem(Reader.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))},loadLocations:async function(t){let e=await localforage.getItem(Reader.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(App.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations…");const o=await fetch("backend.php?op=getpagination&id="+$.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(Reader.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=parseInt(100*(1-t.length()/o));$(".loading-message").html(`Preparing locations (${e}%)…`)}}),$.post("backend.php",{op:"storepagination",id:$.urlParam("id"),payload:JSON.stringify(e),total:100}),await localforage.setItem(Reader.cacheId("locations"),e)},initRenditionHooks:function(t,e){console.log("initRenditionHooks"),t.spine.hooks.content.register((function(t){Reader.cleanupEmbeddedStyles(t)})),e.hooks.content.register(async o=>{o.on("linkClicked",t=>{console.log("linkClicked",t),Reader.Page.blockLastReadUpdate(),-1==t.indexOf("://")&&($(".prev_location_btn").attr("data-location-cfi",e.currentLocation().start.cfi).show(),window.setTimeout((function(){Reader.showUI(!0)}),50))}),o.on("selected",async e=>{if(App.isOnline()){const a=await t.getRange(e),n=a.endContainer.data.substring(a.startOffset,a.endOffset);console.log("selected",e,n),n.match(/^[\w­]+$/)&&Reader.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(Reader.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(Reader.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",(function(t){if(0==t.button){if($(".modal").is(":visible"))return;"undefined"!=typeof EpubeApp?EpubeApp.toggleActionBar():Reader.showUI(!0)}})),$(o.window).on("wheel",(async function(t){await localforage.getItem("epube.enable-wheel")&&(t.originalEvent.deltaY>0?Reader.Page.next():t.originalEvent.deltaY<0&&Reader.Page.prev())}))}),e.on("keyup",t=>{Reader.hotkeyHandler(t)}),e.on("resized",(function(){console.log("rendition resized"),Reader.Page.blockLastReadUpdate(),Reader.open_last_read_when_displayed=!0})),e.on("rendered",(async function(o){console.log("rendition rendered section",o),$(".chapter").html($("<span>").addClass("glyphicon glyphicon-th-list")),Reader.applyTheme(),Reader.resizeSideColumns();try{const o=e.currentLocation();if(o.start){const e=t.canonical(o.start.href);let a=!1;$.each(Reader.flattenToc(t),(function(o,n){t.spine.get(n.href).canonical!=e||(a=n)})),a&&a.label&&$(".chapter").append("&nbsp;"+a.label.trim()+" | "),Reader.generateTocBar(t,Reader.flattenToc(t))}}catch(t){console.warn(t)}Reader.open_last_read_when_displayed&&(Reader.open_last_read_when_displayed=!1,await Reader.Page.openLastRead())})),e.on("displayed",(function(){console.log("rendition displayed")})),e.on("relocated",e=>Reader.Page.onRelocated(t,e))},initModals:function(){$("#settings-modal").on("shown.bs.modal",(async function(){const t=await localforage.getItem(Reader.cacheId("lastread"));t&&t.cfi&&$(".lastread_input").val(t.page+"%").attr("title","[local] "+t.cfi),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:$.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(${App.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:function(t){function e(e){try{const o=t.spine.get(e).cfiBase,a=t.locations._locations.find((function(t){return-1!=t.indexOf(o)}));return parseInt(window.book.locations.locationFromCfi(a)/10)}catch(t){console.warn(t)}return""}$("#toc-modal").on("shown.bs.modal",(function(){const o=t.navigation.toc,a=$(".toc_list");a.html(""),$.each(o,(function(o,n){try{const o=$("<a>").attr("href","#").html("<b class='pull-right'>"+e(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(o.attr("data-href"))}));a.append($("<li>").append(o)),function o(a,n,i){if(3==i)return!1;if(a.subitems){const r=$("<ul class='toc_sublist list-unstyled'>");$.each(a.subitems,(function(a,n){const l=$("<a>").attr("href","#").html("<b class='pull-right'>"+e(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(l.attr("data-href"))}));r.append($("<li>").append(l)),o(n,r,i+1)})),n.append(r)}}(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).click((function(){t.rendition.display(n.attr("data-href"))}));a.append($("<li>").append(n))})))}))},cleanupEmbeddedStyles:function(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!==Reader.hyphenate.en&&$(t).find("p, div").each((t,e)=>{(e=$(e)).html(Reader.hyphenate.en(e.html())),e.html(Reader.hyphenate.ru(e.html()))})},generateFontsCss:function(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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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:function(t,e){let o=[];return 3!=e&&(t.subitems&&$.each(t.subitems,(function(t,a){a._nest=e,o.push(a),o=o.concat(Reader.flattenTocSubItems(a,e+1))})),o)},flattenToc:function(t){if(this._flattened_toc)return this._flattened_toc;{let e=[];return $.each(t.navigation.toc,(function(t,o){o._nest=0,e.push(o),e=e.concat(Reader.flattenTocSubItems(o,1))})),this._flattened_toc=e,e}},generateTocBar:function(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'>")),Reader.updateTocBarPosition(t,t.rendition.currentLocation())},updateTocBarPosition:function(t,e){const o=Math.round(e.start.location/t.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")},applyTheme:async function(){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..."),window.book&&window.book.rendition&&window.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),window.book&&window.book.rendition&&window.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:function(t){try{if($(".modal").is(":visible"))return;39!=t.which&&32!=t.which&&34!=t.which||(t.preventDefault(),Reader.Page.next()),37!=t.which&&33!=t.which||(t.preventDefault(),Reader.Page.prev()),27==t.which&&(t.preventDefault(),Reader.showUI(!0))}catch(t){console.warn(t)}},resizeSideColumns:function(){let t=$("#reader").position().left;window.book&&window.book.rendition&&window.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)},markAsRead:async function(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const t=100,e=window.book.locations.cfiFromPercentage(1),o=(new Date).getTime();if(App.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:t,cfi:e,id:$.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(Reader.cacheId("lastread"),{cfi:e,page:t,total:t,timestamp:o}),await Reader.Page.openLastRead()}},close:async function(){const t=window.book.rendition.currentLocation().start.cfi,e=parseInt(100*window.book.locations.percentageFromCfi(t)),o=(new Date).getTime();await localforage.setItem(Reader.cacheId("lastread"),{cfi:t,page:e,total:100,timestamp:o}),App.isOnline()?$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:e,cfi:t,timestamp:o},(function(){window.location=$.urlParam("rt")?"index.php?mode="+$.urlParam("rt"):"index.php"})).fail((function(){window.location="index.php"})):window.location="index.php"},cacheId:function(t){return"epube-book."+$.urlParam("b")+(t?"."+t:"")},showUI:function(t){t?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()},toggleUI:function(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()},lookupWord:async function(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:function(){const t=$(".search_input").val(),e=$(".search_results");e.html(""),t&&(e.html("<li>Loading, please wait...</li>"),Promise.all(window.book.spine.spineItems.map(e=>e.load(window.book.load.bind(window.book)).then(e.find.bind(e,t)).finally(e.unload.bind(e)))).then(t=>Promise.resolve([].concat.apply([],t))).then((function(t){e.html(""),$.each(t,(function(t,o){const a=$("<a>").attr("href","#").html("<b class='pull-right'>"+window.book.locations.locationFromCfi(o.cfi)+"</b>"+o.excerpt).attr("data-cfi",o.cfi).attr("data-id",o.id).click((function(){window.book.rendition.display(a.attr("data-cfi"))}));e.append($("<li>").append(a))}))})))},Loader:{_res_data:[],init:async function(){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const t=[];let e=!1;const o=await caches.open("epube-v3");(await o.keys()).forEach(o=>{if(!o.url.match("backend.php")){console.log("[loader] loading resource",o.url);const a=fetch(o.url).then(async t=>{if(t.ok){const e=new URL(t.url);if(e.searchParams.delete("ts"),t.url.match("\\.ttf|\\.otf")){const o=await t.blob();console.log("[loader] storing blob",e.href),Reader.Loader._res_data[e.toString()]=URL.createObjectURL(o)}else{const o=await t.text();console.log("[loader] storing text",e.href),Reader.Loader._res_data[e.toString()]=o}}else console.warn("[loader] failed for resource",o.url,t),$(".loading-message").html(`Unable to load resource.<br/><small>${o.url}</small>`),e=!0});t.push(a)}}),await Promise.allSettled(t),console.log("[loader] resource load complete, failed: ",e),e?Reader.applyTheme():Reader.initSecondStage()}},Page:{_prevent_lastread_timeout:!1,_prevent_lastread:!1,next:function(){window.book.rendition.next(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then((function(t){t||Reader.showUI(!1)}))},prev:function(){window.book.rendition.prev(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then((function(t){t||Reader.showUI(!1)}))},openPrevious:async function(t){const e=$(t).attr("data-location-cfi");e&&await window.book.rendition.display(e),$(t).fadeOut()},blockLastReadUpdate:function(){console.log("blocking last read updates..."),Reader.Page._prevent_lastread_timeout&&window.clearTimeout(Reader.Page._prevent_lastread_timeout),Reader.Page._prevent_lastread_timeout=window.setTimeout(()=>{Reader.Page._prevent_lastread=!1,Reader.Page._prevent_lastread_timeout=!1,console.log("unblocked last read updates")},1e3),Reader.Page._prevent_lastread=!0},onRelocated:async function(t,e){if(0==t.locations.length())return;const o=e.start.cfi,a=parseInt(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(parseInt(100*t.locations.percentageFromCfi(o))+"%"),Reader.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(parseInt(n.page/n.total*100)+"%")),Reader.startup_finished&&Reader.last_stored_cfi!=o&&!Reader.Page._prevent_lastread){const t=(new Date).getTime();console.log("storing lastread",a,o,t),await localforage.setItem(Reader.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:t}),App.isOnline()&&(console.log("updating remote lastread",o),Reader.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:a,cfi:o,timestamp:t}))}},clearLastRead:async function(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const t=window.book.locations.length(),e=(new Date).getTime();App.isOnline()&&await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:$.urlParam("id"),timestamp:e}),await localforage.setItem(Reader.cacheId("lastread"),{cfi:"",page:0,total:t,timestamp:e}),await window.book.rendition.display(window.book.locations.cfiFromPercentage(0)),$(".lastread_input").val("0%")}},resetLocations:async function(){confirm("Reset stored pagination data? This will also reset reading progress.")&&($("#settings-modal").modal("hide"),await localforage.removeItem(Reader.cacheId("lastread")),await localforage.removeItem(Reader.cacheId("locations")),await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:$.urlParam("id"),timestamp:(new Date).getTime()}),await $.post("backend.php",{op:"deletepagination",id:$.urlParam("id")}).catch(t=>console.log(t)),window.location.reload())},openLastRead:async function(){$(".loading").show(),$(".loading-message").html("Opening last read page…"),$("#settings-modal").modal("hide");const t=window.book.rendition;if(!t)return void console.error("no rendition to work on");let e=!1;const o=await localforage.getItem(Reader.cacheId("lastread"))||{};if(console.log("got local lastread",o),App.isOnline())try{const a=await $.post("backend.php",{op:"getlastread",id:$.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(Reader.cacheId("lastread"),{cfi:a.cfi,page:a.page,total:a.total,timestamp:a.timestamp}),e=await Reader.Page.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 Reader.Page.moveToCfiVerify(t,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()},calculateCfiDelta:function(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},moveToCfiVerify:async function(t,e,o=5,a=5){for(let n=1;n<o;n++){Reader.Page.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=Reader.Page.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}},Settings:{onThemeChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.theme",e),Reader.applyTheme()},onLineHeightChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.lineHeight",e),Reader.applyTheme()},onTextSizeChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.fontSize",e),Reader.applyTheme()},onFontChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.fontFamily",e),Reader.applyTheme()}}};function __get_reader(){return Reader}function __get_app(){return App}
\ No newline at end of file
+"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 AppClass{_dl_progress_timeout;index_mode="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";urlParam(t){try{const e=new RegExp("[?&]"+t+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(e[1].replace(/\+/g," "))||0}catch(t){return 0}}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())$.post("backend.php",{op:"getinfo",id:e},(function(t){const e=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(e),$("#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)=>{let 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.")}isOnline(){return"undefined"!=typeof EpubeApp&&void 0!==EpubeApp.isOnline?EpubeApp.isOnline():navigator.onLine}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}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"))}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(async 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)})})}})}async 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,l=!1;const r=o[2];r&&(i=r.page>0,l=r.total>0&&r.total-r.page<5);const s=l?"read":"",c=i?"in_progress":"",d=a.series_name?`<div><a class="series_link" href="#">${a.series_name+" ["+a.series_index+"]"}</a></div>`:"",f=$(`<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 ${s}" 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?f.find("img").css("background-image","url("+n+")").fadeIn():f.fadeIn(),f.find(".series_link").attr("title",a.series_name+" ["+a.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(a.series_name)),f.find(".author_link").attr("title",a.author_sort).attr("href","offline.html?query="+encodeURIComponent(a.author_sort)),e.append(f)}}))}))}}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,CACHE_PREFIX="epube",CACHE_NAME="epube-v3";Promise.allSettled=Promise.allSettled||(t=>Promise.all(t.map(t=>t.then(t=>({status:"fulfilled",value:t})).catch(t=>({status:"rejected",reason:t})))));const Reader={csrf_token:"",last_stored_cfi:"",startup_finished:!1,open_last_read_when_displayed:!0,hyphenate:{},init:function(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((function(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:Reader.csrf_token})):"string"==o&&(t.data=e.data+"&csrf_token="+encodeURIComponent(Reader.srf_token)),console.log(">>>",t)})),$(document).on("keyup",(function(t){Reader.hotkeyHandler(t)})),$("#left").on("mouseup",(function(){Reader.Page.prev()})),$("#right").on("mouseup",(function(){Reader.Page.next()})),Reader.Loader.init()},isTouchDevice:function(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0},onOfflineModeChanged:function(t){if(console.log("onOfflineModeChanged",t),!t&&window.book){const t=window.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=parseInt(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:o,cfi:e,timestamp:(new Date).getTime()},(function(){})).fail((function(t){t&&401==t.status&&(window.location="index.php")}))}},initSecondStage:async function(){"undefined"!=typeof EpubeApp?EpubeApp.setPage("PAGE_READER"):($(window).on("online",(function(){Reader.onOfflineModeChanged(!1)})),$(window).on("offline",(function(){Reader.onOfflineModeChanged(!0)}))),Reader.applyTheme();if(!await localforage.getItem(Reader.cacheId())){const t=$.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(Reader.cacheId("cover"),e.blob())}await localforage.setItem(Reader.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(Reader.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="+$.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(Reader.cacheId("book"),t),console.log("saved local data for book")}const e=new FileReader;e.onload=function(){try{Reader.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)},openBookData:async function(t){const e=ePub();window.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 Reader.showBookInfo(e),await Reader.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",(async function(){const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",t);n&&await o.display(e.locations._locations[10*n])}));await localforage.getItem("epube.enable-hyphens")&&(Reader.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),Reader.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),Reader.initRenditionHooks(e,o),Reader.initModals(),Reader.initToc(e),Reader.Page.blockLastReadUpdate(),await o.display(),console.log("startup finished"),Reader.startup_finished=!0},showBookInfo:async function(t){const e=await localforage.getItem(Reader.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))},loadLocations:async function(t){let e=await localforage.getItem(Reader.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(App.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations…");const o=await fetch("backend.php?op=getpagination&id="+$.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(Reader.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=parseInt(100*(1-t.length()/o));$(".loading-message").html(`Preparing locations (${e}%)…`)}}),$.post("backend.php",{op:"storepagination",id:$.urlParam("id"),payload:JSON.stringify(e),total:100}),await localforage.setItem(Reader.cacheId("locations"),e)},initRenditionHooks:function(t,e){console.log("initRenditionHooks"),t.spine.hooks.content.register((function(t){Reader.cleanupEmbeddedStyles(t)})),e.hooks.content.register(async o=>{o.on("linkClicked",t=>{console.log("linkClicked",t),Reader.Page.blockLastReadUpdate(),-1==t.indexOf("://")&&($(".prev_location_btn").attr("data-location-cfi",e.currentLocation().start.cfi).show(),window.setTimeout((function(){Reader.showUI(!0)}),50))}),o.on("selected",async e=>{if(App.isOnline()){const a=await t.getRange(e),n=a.endContainer.data.substring(a.startOffset,a.endOffset);console.log("selected",e,n),n.match(/^[\w­]+$/)&&Reader.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(Reader.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(Reader.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",(function(t){if(0==t.button){if($(".modal").is(":visible"))return;"undefined"!=typeof EpubeApp?EpubeApp.toggleActionBar():Reader.showUI(!0)}})),$(o.window).on("wheel",(async function(t){await localforage.getItem("epube.enable-wheel")&&(t.originalEvent.deltaY>0?Reader.Page.next():t.originalEvent.deltaY<0&&Reader.Page.prev())}))}),e.on("keyup",t=>{Reader.hotkeyHandler(t)}),e.on("resized",(function(){console.log("rendition resized"),Reader.Page.blockLastReadUpdate(),Reader.open_last_read_when_displayed=!0})),e.on("rendered",(async function(o){console.log("rendition rendered section",o),$(".chapter").html($("<span>").addClass("glyphicon glyphicon-th-list")),Reader.applyTheme(),Reader.resizeSideColumns();try{const o=e.currentLocation();if(o.start){const e=t.canonical(o.start.href);let a=!1;$.each(Reader.flattenToc(t),(function(o,n){t.spine.get(n.href).canonical!=e||(a=n)})),a&&a.label&&$(".chapter").append("&nbsp;"+a.label.trim()+" | "),Reader.generateTocBar(t,Reader.flattenToc(t))}}catch(t){console.warn(t)}Reader.open_last_read_when_displayed&&(Reader.open_last_read_when_displayed=!1,await Reader.Page.openLastRead())})),e.on("displayed",(function(){console.log("rendition displayed")})),e.on("relocated",e=>Reader.Page.onRelocated(t,e))},initModals:function(){$("#settings-modal").on("shown.bs.modal",(async function(){const t=await localforage.getItem(Reader.cacheId("lastread"));t&&t.cfi&&$(".lastread_input").val(t.page+"%").attr("title","[local] "+t.cfi),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:$.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(${App.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:function(t){function e(e){try{const o=t.spine.get(e).cfiBase,a=t.locations._locations.find((function(t){return-1!=t.indexOf(o)}));return parseInt(window.book.locations.locationFromCfi(a)/10)}catch(t){console.warn(t)}return""}$("#toc-modal").on("shown.bs.modal",(function(){const o=t.navigation.toc,a=$(".toc_list");a.html(""),$.each(o,(function(o,n){try{const o=$("<a>").attr("href","#").html("<b class='pull-right'>"+e(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(o.attr("data-href"))}));a.append($("<li>").append(o)),function o(a,n,i){if(3==i)return!1;if(a.subitems){const l=$("<ul class='toc_sublist list-unstyled'>");$.each(a.subitems,(function(a,n){const r=$("<a>").attr("href","#").html("<b class='pull-right'>"+e(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(r.attr("data-href"))}));l.append($("<li>").append(r)),o(n,l,i+1)})),n.append(l)}}(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).click((function(){t.rendition.display(n.attr("data-href"))}));a.append($("<li>").append(n))})))}))},cleanupEmbeddedStyles:function(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!==Reader.hyphenate.en&&$(t).find("p, div").each((t,e)=>{(e=$(e)).html(Reader.hyphenate.en(e.html())),e.html(Reader.hyphenate.ru(e.html()))})},generateFontsCss:function(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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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(${Reader.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:function(t,e){let o=[];return 3!=e&&(t.subitems&&$.each(t.subitems,(function(t,a){a._nest=e,o.push(a),o=o.concat(Reader.flattenTocSubItems(a,e+1))})),o)},flattenToc:function(t){if(this._flattened_toc)return this._flattened_toc;{let e=[];return $.each(t.navigation.toc,(function(t,o){o._nest=0,e.push(o),e=e.concat(Reader.flattenTocSubItems(o,1))})),this._flattened_toc=e,e}},generateTocBar:function(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'>")),Reader.updateTocBarPosition(t,t.rendition.currentLocation())},updateTocBarPosition:function(t,e){const o=Math.round(e.start.location/t.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")},applyTheme:async function(){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..."),window.book&&window.book.rendition&&window.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),window.book&&window.book.rendition&&window.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:function(t){try{if($(".modal").is(":visible"))return;39!=t.which&&32!=t.which&&34!=t.which||(t.preventDefault(),Reader.Page.next()),37!=t.which&&33!=t.which||(t.preventDefault(),Reader.Page.prev()),27==t.which&&(t.preventDefault(),Reader.showUI(!0))}catch(t){console.warn(t)}},resizeSideColumns:function(){let t=$("#reader").position().left;window.book&&window.book.rendition&&window.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)},markAsRead:async function(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const t=100,e=window.book.locations.cfiFromPercentage(1),o=(new Date).getTime();if(App.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:t,cfi:e,id:$.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(Reader.cacheId("lastread"),{cfi:e,page:t,total:t,timestamp:o}),await Reader.Page.openLastRead()}},close:async function(){const t=window.book.rendition.currentLocation().start.cfi,e=parseInt(100*window.book.locations.percentageFromCfi(t)),o=(new Date).getTime();await localforage.setItem(Reader.cacheId("lastread"),{cfi:t,page:e,total:100,timestamp:o}),App.isOnline()?$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:e,cfi:t,timestamp:o},(function(){window.location=$.urlParam("rt")?"index.php?mode="+$.urlParam("rt"):"index.php"})).fail((function(){window.location="index.php"})):window.location="index.php"},cacheId:function(t){return"epube-book."+$.urlParam("b")+(t?"."+t:"")},showUI:function(t){t?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()},toggleUI:function(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()},lookupWord:async function(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:function(){const t=$(".search_input").val(),e=$(".search_results");e.html(""),t&&(e.html("<li>Loading, please wait...</li>"),Promise.all(window.book.spine.spineItems.map(e=>e.load(window.book.load.bind(window.book)).then(e.find.bind(e,t)).finally(e.unload.bind(e)))).then(t=>Promise.resolve([].concat.apply([],t))).then((function(t){e.html(""),$.each(t,(function(t,o){const a=$("<a>").attr("href","#").html("<b class='pull-right'>"+window.book.locations.locationFromCfi(o.cfi)+"</b>"+o.excerpt).attr("data-cfi",o.cfi).attr("data-id",o.id).click((function(){window.book.rendition.display(a.attr("data-cfi"))}));e.append($("<li>").append(a))}))})))},Loader:{_res_data:[],init:async function(){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const t=[];let e=!1;const o=await caches.open("epube-v3");(await o.keys()).forEach(o=>{if(!o.url.match("backend.php")){console.log("[loader] loading resource",o.url);const a=fetch(o.url).then(async t=>{if(t.ok){const e=new URL(t.url);if(e.searchParams.delete("ts"),t.url.match("\\.ttf|\\.otf")){const o=await t.blob();console.log("[loader] storing blob",e.href),Reader.Loader._res_data[e.toString()]=URL.createObjectURL(o)}else{const o=await t.text();console.log("[loader] storing text",e.href),Reader.Loader._res_data[e.toString()]=o}}else console.warn("[loader] failed for resource",o.url,t),$(".loading-message").html(`Unable to load resource.<br/><small>${o.url}</small>`),e=!0});t.push(a)}}),await Promise.allSettled(t),console.log("[loader] resource load complete, failed: ",e),e?Reader.applyTheme():Reader.initSecondStage()}},Page:{_prevent_lastread_timeout:!1,_prevent_lastread:!1,next:function(){window.book.rendition.next(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then((function(t){t||Reader.showUI(!1)}))},prev:function(){window.book.rendition.prev(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then((function(t){t||Reader.showUI(!1)}))},openPrevious:async function(t){const e=$(t).attr("data-location-cfi");e&&await window.book.rendition.display(e),$(t).fadeOut()},blockLastReadUpdate:function(){console.log("blocking last read updates..."),Reader.Page._prevent_lastread_timeout&&window.clearTimeout(Reader.Page._prevent_lastread_timeout),Reader.Page._prevent_lastread_timeout=window.setTimeout(()=>{Reader.Page._prevent_lastread=!1,Reader.Page._prevent_lastread_timeout=!1,console.log("unblocked last read updates")},1e3),Reader.Page._prevent_lastread=!0},onRelocated:async function(t,e){if(0==t.locations.length())return;const o=e.start.cfi,a=parseInt(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(parseInt(100*t.locations.percentageFromCfi(o))+"%"),Reader.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(parseInt(n.page/n.total*100)+"%")),Reader.startup_finished&&Reader.last_stored_cfi!=o&&!Reader.Page._prevent_lastread){const t=(new Date).getTime();console.log("storing lastread",a,o,t),await localforage.setItem(Reader.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:t}),App.isOnline()&&(console.log("updating remote lastread",o),Reader.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:$.urlParam("id"),page:a,cfi:o,timestamp:t}))}},clearLastRead:async function(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const t=window.book.locations.length(),e=(new Date).getTime();App.isOnline()&&await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:$.urlParam("id"),timestamp:e}),await localforage.setItem(Reader.cacheId("lastread"),{cfi:"",page:0,total:t,timestamp:e}),await window.book.rendition.display(window.book.locations.cfiFromPercentage(0)),$(".lastread_input").val("0%")}},resetLocations:async function(){confirm("Reset stored pagination data? This will also reset reading progress.")&&($("#settings-modal").modal("hide"),await localforage.removeItem(Reader.cacheId("lastread")),await localforage.removeItem(Reader.cacheId("locations")),await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:$.urlParam("id"),timestamp:(new Date).getTime()}),await $.post("backend.php",{op:"deletepagination",id:$.urlParam("id")}).catch(t=>console.log(t)),window.location.reload())},openLastRead:async function(){$(".loading").show(),$(".loading-message").html("Opening last read page…"),$("#settings-modal").modal("hide");const t=window.book.rendition;if(!t)return void console.error("no rendition to work on");let e=!1;const o=await localforage.getItem(Reader.cacheId("lastread"))||{};if(console.log("got local lastread",o),App.isOnline())try{const a=await $.post("backend.php",{op:"getlastread",id:$.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(Reader.cacheId("lastread"),{cfi:a.cfi,page:a.page,total:a.total,timestamp:a.timestamp}),e=await Reader.Page.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 Reader.Page.moveToCfiVerify(t,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()},calculateCfiDelta:function(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},moveToCfiVerify:async function(t,e,o=5,a=5){for(let n=1;n<o;n++){Reader.Page.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=Reader.Page.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}},Settings:{onThemeChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.theme",e),Reader.applyTheme()},onLineHeightChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.lineHeight",e),Reader.applyTheme()},onTextSizeChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.fontSize",e),Reader.applyTheme()},onFontChanged:async function(t){const e=$(t).val();await localforage.setItem("epube.fontFamily",e),Reader.applyTheme()}}};function __get_reader(){return Reader}function __get_app(){return App}
\ No newline at end of file
diff --git a/gulpfile.js b/gulpfile.js
index 28f6c49..ba113ad 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -36,7 +36,7 @@ gulp.task('minifyLibsJS', function(cb) {
 
 gulp.task('minifyJS', function(cb) {
 	gulp
-		.src(['js/app.js', 'js/reader.js'])
+		.src(['js/*.js'])
 		.pipe(concat('app.min.js'))
 		.pipe(uglify())
 		.on('error', swallowError)
diff --git a/index.php b/index.php
index 75e6895..01bba22 100644
--- a/index.php
+++ b/index.php
@@ -70,6 +70,8 @@
 	<script type="text/javascript">
 		'use strict';
 
+		const	App = new AppClass();
+
 		if ('serviceWorker' in navigator) {
 			navigator.serviceWorker
 				.register('worker.js')
@@ -77,6 +79,7 @@
 					console.log("service worker registered");
 
 					$(document).ready(function() {
+
 						App.cached_urls = JSON.parse('<?= json_encode($check_files_mtime) ?>');
 						App.index_mode = "<?= $mode ?>";
 						App.version = "<?= Config::get_version(true) ?>";
diff --git a/js/app.d.ts b/js/app.d.ts
new file mode 100644
index 0000000..58eddc3
--- /dev/null
+++ b/js/app.d.ts
@@ -0,0 +1,2 @@
+declare var EpubeApp: class;
+declare var localforage: LocalForage;
diff --git a/js/app.js b/js/app.js
index 7714246..15cb883 100644
--- a/js/app.js
+++ b/js/app.js
@@ -1,25 +1,17 @@
+// @ts-check
 'use strict';
 
 /* global localforage, EpubeApp, $ */
 
-$.urlParam = function(name){
-	try {
-		const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
-		return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
-	} catch (e) {
-		return 0;
-	}
-};
-
-/* exported Cookie */
-const Cookie = {
-	set: function (name, value, lifetime) {
+class Cookie {
+	static set(name, value, lifetime) {
 		const d = new Date();
 		d.setTime(d.getTime() + lifetime * 1000);
 		const expires = "expires=" + d.toUTCString();
 		document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires;
-	},
-	get: function (name) {
+	}
+
+	static get(name) {
 		name = name + "=";
 		const ca = document.cookie.split(';');
 		for (let i=0; i < ca.length; i++) {
@@ -28,21 +20,32 @@ const Cookie = {
 			if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length));
 		}
 		return "";
-	},
-	delete: function(name) {
+	}
+
+	static delete(name) {
 		const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT";
 		document.cookie = name + "=; " + expires;
 	}
-};
-
-const App = {
-	_dl_progress_timeout: false,
-	index_mode: "",
-	cached_urls: [],
-	version: "UNKNOWN",
-	buildTimestamp: 0,
-	csrf_token: "",
-	init: function() {
+}
+
+class AppClass {
+	_dl_progress_timeout;
+	index_mode = "";
+	cached_urls = [];
+	version = "UNKNOWN";
+	buildTimestamp = 0;
+	csrf_token = "";
+
+	urlParam(name){
+		try {
+			const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
+			return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
+		} catch (e) {
+			return 0;
+		}
+	}
+
+	init() {
 		let refreshed_files = 0;
 
 		this.csrf_token = Cookie.get('epube_csrf_token');
@@ -50,7 +53,7 @@ const App = {
 		console.log('setting prefilter for token', this.csrf_token);
 
 		/* eslint-disable no-unused-vars */
-		$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
+		$.ajaxPrefilter((options, originalOptions, jqXHR) => {
 			if (originalOptions.type !== 'post' || options.type !== 'post') {
 				return;
 			}
@@ -58,9 +61,9 @@ const App = {
 			const datatype = typeof originalOptions.data;
 
 			if (datatype == 'object')
-				options.data = $.param($.extend(originalOptions.data, {"csrf_token": App.csrf_token}));
+				options.data = $.param($.extend(originalOptions.data, {"csrf_token": this.csrf_token}));
 			else if (datatype == 'string')
-				options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(App.srf_token);
+				options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token);
 
 			console.log('>>>', options);
 		});
@@ -71,16 +74,16 @@ const App = {
 			$(".separate-search").show();
 			$("body").addClass("is-epube-app");
 
-			if ($.urlParam("mode") == "favorites")
+			if (this.urlParam("mode") == "favorites")
 				EpubeApp.setPage("PAGE_FAVORITES");
 			else
 				EpubeApp.setPage("PAGE_LIBRARY");
 		}
 
-		App.initNightMode();
+		this.initNightMode();
 
 		if ('serviceWorker' in navigator) {
-			navigator.serviceWorker.addEventListener('message', function(event) {
+			navigator.serviceWorker.addEventListener('message', (event) => {
 
 				if (event.data == 'refresh-started') {
 					console.log('cache refresh started');
@@ -100,51 +103,66 @@ const App = {
 				}
 
 				if (event.data == 'refresh-finished') {
-					localforage.setItem("epube.cache-version", App.version);
-					localforage.setItem("epube.cache-timestamp", App.buildTimestamp);
+					localforage.setItem("epube.cache-version", this.version);
+					localforage.setItem("epube.cache-timestamp", this.buildTimestamp);
 					window.location.reload()
 				}
 
 			});
 
-			App.showCovers();
-			App.Offline.markBooks();
-			App.refreshCache();
+			this.showCovers();
+			this.updateOfflinePrompts();
+			this.refreshCache();
 
 		} else {
 			$(".container-main")
 				.addClass("alert alert-danger")
 				.html("Service worker support missing in browser (are you using plain HTTP?).");
 		}
-	},
-	logout: function() {
+	}
+
+	logout() {
 		$.post("backend.php", {op: "logout"}).then(() => {
 			window.location.reload();
 		});
-	},
-	showSummary: function(elem) {
-		const id = elem.getAttribute("data-book-id");
+	}
+
+	async showSummary(elem) {
+		const bookId = elem.getAttribute("data-book-id");
+
+		if (this.isOnline()) {
 
-		$.post("backend.php", {op: 'getinfo', id: id}, function(data) {
+			$.post("backend.php", {op: 'getinfo', id: bookId}, function(data) {
+
+				const comment = data.comment ? data.comment : 'No description available';
+
+				$("#summary-modal .modal-title").html(data.title);
+				$("#summary-modal .book-summary").html(comment);
 
+				$("#summary-modal").modal();
+
+			});
+
+		} else {
+			const data = await localforage.getItem("epube-book." + bookId);
 			const comment = data.comment ? data.comment : 'No description available';
 
 			$("#summary-modal .modal-title").html(data.title);
 			$("#summary-modal .book-summary").html(comment);
 
 			$("#summary-modal").modal();
-
-		});
+		}
 
 		return false;
-	},
-	showCovers: function() {
-		$("img[data-book-id]").each((i,e) => {
-			e = $(e);
+	}
+
+	showCovers() {
+		$("img[data-book-id]").each((i, elem) => {
+			let e = $(elem);
 
 			if (e.attr('data-cover-link')) {
 				const img = $("<img>")
-					.on("load", function() {
+					.on("load", () => {
 						e.css("background-image", "url(" + e.attr('data-cover-link') + ")")
 							.fadeIn();
 
@@ -153,13 +171,14 @@ const App = {
 					.attr("src", e.attr('data-cover-link'));
 			}
 		});
-	},
-	toggleFavorite: function(elem) {
+	}
+
+	toggleFavorite(elem) {
 		const bookId = elem.getAttribute("data-book-id");
 
 		if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {
 
-			$.post("backend.php", {op: "togglefav", id: bookId}, function(data) {
+			$.post("backend.php", {op: "togglefav", id: bookId}, (data) => {
 				if (data) {
 					let msg = "[Error]";
 
@@ -171,7 +190,7 @@ const App = {
 
 					$(elem).html(msg).attr('data-is-fav', data.status);
 
-					if (App.index_mode == "favorites" && data.status == 0) {
+					if (this.index_mode == "favorites" && data.status == 0) {
 						$("#cell-" + bookId).remove();
 					}
 				}
@@ -179,64 +198,65 @@ const App = {
 		}
 
 		return false;
-	},
-	refreshCache: function(force) {
+	}
+
+	async refreshCache(force) {
 		if ('serviceWorker' in navigator) {
-			localforage.getItem("epube.cache-version").then(function(version) {
-				console.log('local version', version, 'remote version', App.version);
+			const version = await localforage.getItem("epube.cache-version");
+
+			console.log('local version', version, 'remote version', this.version);
 
-				if (force || version != App.version) {
-					console.log('asking worker to refresh cache');
+			if (force || version != this.version) {
+				console.log('asking worker to refresh cache');
 
-					if (navigator.serviceWorker.controller) {
-						navigator.serviceWorker.controller.postMessage({msg: "refresh-cache", urls: App.cached_urls});
+				if (navigator.serviceWorker.controller) {
+					navigator.serviceWorker.controller.postMessage({msg: "refresh-cache", urls: this.cached_urls});
+				} else {
+					const done = await localforage.getItem("epube.initial-load-done");
+
+					console.log("initial load done?", done);
+
+					if (done) {
+						$(".dl-progress")
+							.show()
+							.addClass("alert-danger")
+							.html("Could not communicate with service worker. Try reloading the page.");
 					} else {
-						localforage.getItem("epube.initial-load-done").then(function(done) {
-
-							console.log("initial load done", done);
-
-							if (done) {
-								$(".dl-progress")
-									.show()
-									.addClass("alert-danger")
-									.html("Could not communicate with service worker. Try reloading the page.");
-							} else {
-								localforage.setItem("epube.initial-load-done", true).then(function() {
-									$(".dl-progress")
-										.show()
-										.addClass("alert-info")
-										.html("Page will reload to activate service worker...");
-
-									window.setTimeout(function() {
-										window.location.reload();
-									}, 3*1000);
-
-								});
-							}
+						await localforage.setItem("epube.initial-load-done", true);
 
-						});
+						$(".dl-progress")
+							.show()
+							.addClass("alert-info")
+							.html("Page will reload to activate service worker...");
+
+						window.setTimeout(function() {
+							window.location.reload();
+						}, 3*1000);
 					}
 				}
-			});
+			}
 		} else {
 			$(".dl-progress")
 				.show()
 				.addClass("alert-danger")
 				.html("Could not communicate with service worker. Try reloading the page.");
 		}
-	},
-	isOnline: function() {
+	}
+
+	isOnline() {
 		if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined")
 			return EpubeApp.isOnline();
 		else
 			return navigator.onLine;
-	},
-	appCheckOffline: function() {
-		EpubeApp.setOffline(!App.isOnline);
-	},
-	initNightMode: function() {
+	}
+
+	appCheckOffline() {
+		EpubeApp.setOffline(!this.isOnline);
+	}
+
+	initNightMode() {
 		if (typeof EpubeApp != "undefined") {
-			App.applyNightMode(EpubeApp.isNightMode());
+			this.applyNightMode(EpubeApp.isNightMode());
 			return;
 		}
 
@@ -244,330 +264,321 @@ const App = {
 			const mql = window.matchMedia('(prefers-color-scheme: dark)');
 
 			mql.addEventListener("change", () => {
-				App.applyNightMode(mql.matches);
+				this.applyNightMode(mql.matches);
 			});
 
-			App.applyNightMode(mql.matches);
+			this.applyNightMode(mql.matches);
 		}
-	},
-	applyNightMode: function(is_night) {
+	}
+
+	applyNightMode(is_night) {
 		console.log("night mode changed to", is_night);
 
 		$("#theme_css").attr("href",
 			"lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css"));
-	},
-	Offline: {
-		init: function() {
-			if (typeof EpubeApp != "undefined") {
-				$(".navbar").hide();
-				$(".epube-app-filler").show();
-				$("body").addClass("is-epube-app");
-
-				EpubeApp.setPage("PAGE_OFFLINE");
-			}
+	}
 
-			App.initNightMode();
+	updateOfflinePrompts() {
+		const elems = $(".offline_dropitem");
 
-			const query = $.urlParam("query");
+		$.each(elems, (i, elem) => {
+			this.updateOfflinePrompt(elem);
+		});
+	}
 
-			if (query)
-				$(".search_query").val(query);
+	async updateOfflinePrompt(elem) {
+		const bookId = elem.getAttribute("data-book-id");
+		const cacheId = "epube-book." + bookId;
 
-			App.Offline.populateList();
-		},
-		get: function(bookId, callback) {
-			console.log("offline cache: " + bookId);
+		const book = await localforage.getItem(cacheId);
 
-			$.post("backend.php", {op: "getinfo", id: bookId}, function(data) {
+		if (book) {
+			elem.onclick = () => {
+				this.remove(bookId, () => {
+					this.updateOfflinePrompt(elem);
+				});
 
-				if (data) {
-					const cacheId = 'epube-book.' + bookId;
+				return false;
+			};
 
-					localforage.setItem(cacheId, data).then(function(data) {
+			elem.innerHTML = "Remove offline data";
 
-						console.log(cacheId + ' got data');
+		} else {
+			elem.onclick = () => {
+				this.get(bookId, () => {
+					this.updateOfflinePrompt(elem);
+				});
+				return false;
+			};
 
-						const promises = [];
+			elem.innerHTML = "Make available offline";
+		}
+	}
 
-						promises.push(fetch('backend.php?op=download&id=' + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-							if (resp.status == 200) {
-								console.log(cacheId + ' got book');
+	offlineInit() {
+		if (typeof EpubeApp != "undefined") {
+			$(".navbar").hide();
+			$(".epube-app-filler").show();
+			$("body").addClass("is-epube-app");
 
-								callback();
+			EpubeApp.setPage("PAGE_OFFLINE");
+		}
 
-								localforage.setItem(cacheId + '.book', resp.blob());
-							}
-						}));
+		this.initNightMode();
 
-						promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-							if (resp.status == 200) {
-								console.log(cacheId + ' got pagination');
+		const query = this.urlParam("query");
 
-								resp.text().then(function(text) {
-									localforage.setItem(cacheId + '.locations', JSON.parse(text));
-								});
-							}
-						}));
+		if (query)
+			$(".search_query").val(query);
 
-						promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-							if (resp.status == 200) {
-								console.log(cacheId + ' got lastread');
-								resp.text().then(function(text) {
-									localforage.setItem(cacheId + '.lastread', JSON.parse(text));
-								});
-							}
-						}));
+		this.populateList();
+	}
 
-						if (data.has_cover) {
+	get(bookId, callback) {
+		console.log("offline cache: " + bookId);
 
-							promises.push(fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) {
+		$.post("backend.php", {op: "getinfo", id: bookId}, (data) => {
 
-								if (resp.status == 200) {
-									console.log(cacheId + ' got cover');
-									localforage.setItem(cacheId + '.cover', resp.blob());
-								}
+			if (data) {
+				const cacheId = 'epube-book.' + bookId;
 
-							}));
+				localforage.setItem(cacheId, data).then(async (data) => {
 
+					console.log(cacheId + ' got data');
+
+					const promises = [];
+
+					promises.push(fetch('backend.php?op=download&id=' + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+						if (resp.status == 200) {
+							console.log(cacheId + ' got book');
+
+							localforage.setItem(cacheId + '.book', resp.blob());
 						}
+					}));
 
-						Promise.all(promises).then(function() {
-							$(".dl-progress")
-								.show()
-								.html("Finished downloading <b>" + data.title + "</b>");
+					promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+						if (resp.status == 200) {
+							console.log(cacheId + ' got pagination');
 
-							window.clearTimeout(App._dl_progress_timeout);
+							resp.text().then(function(text) {
+								localforage.setItem(cacheId + '.locations', JSON.parse(text));
+							});
+						}
+					}));
+
+					promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+						if (resp.status == 200) {
+							console.log(cacheId + ' got lastread');
+							resp.text().then(function(text) {
+								localforage.setItem(cacheId + '.lastread', JSON.parse(text));
+							});
+						}
+					}));
 
-							App._dl_progress_timeout = window.setTimeout(function() {
-								$(".dl-progress").fadeOut();
-							}, 5*1000);
-						});
-					});
-				}
-			});
-		},
-		getAll: function() {
-			if (confirm("Download all books on this page?")) {
+					if (data.has_cover) {
+						promises.push(fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) {
+							if (resp.status == 200) {
+								console.log(cacheId + ' got cover');
+								localforage.setItem(cacheId + '.cover', resp.blob());
+							}
+						}));
+					}
 
-				$(".row > div").each(function (i, row) {
-					const bookId = $(row).attr("id").replace("cell-", "");
-					const dropitem = $(row).find(".offline_dropitem")[0];
+					Promise.all(promises).then(() => {
+						console.log('download done, running callback', callback);
 
-					if (bookId) {
+						callback();
 
-						const cacheId = 'epube-book.' + bookId;
-						localforage.getItem(cacheId).then(function(book) {
+						$(".dl-progress")
+							.show()
+							.html("Finished downloading <b>" + data.title + "</b>");
 
-							if (!book) {
-								App.Offline.get(bookId, function() {
-									App.Offline.mark(dropitem);
-								});
-							}
+						window.clearTimeout(this._dl_progress_timeout);
 
-						});
+						this._dl_progress_timeout = window.setTimeout(function() {
+							$(".dl-progress").fadeOut();
+						}, 5*1000);
+					})
 
-					}
 				});
 			}
-		},
-		markBooks: function() {
-			const elems = $(".offline_dropitem");
+		});
+	}
 
-			$.each(elems, function (i, elem) {
-				App.Offline.mark(elem);
-			});
-		},
-		mark: function(elem) {
-			const bookId = elem.getAttribute("data-book-id");
-			const cacheId = "epube-book." + bookId;
-
-			localforage.getItem(cacheId).then(function(book) {
-				if (book) {
-					elem.onclick = function() {
-						App.Offline.remove(bookId, function() {
-							App.Offline.mark(elem);
-						});
-						return false;
-					};
-
-					elem.innerHTML = "Remove offline data";
+	async getAll() {
+		if (confirm("Download all books on this page?")) {
 
-				} else {
-					elem.onclick = function() {
-						App.Offline.get(bookId, function() {
-							App.Offline.mark(elem);
-						});
-						return false;
-					};
-
-					elem.innerHTML = "Make available offline";
+			$(".row > div").each((i, row) => {
+				const bookId = $(row).attr("id").replace("cell-", "");
+				const dropitem = $(row).find(".offline_dropitem")[0];
+
+				if (bookId) {
+
+					const cacheId = 'epube-book.' + bookId;
+
+					localforage.getItem(cacheId).then((book) => {
+						if (!book) {
+							this.get(bookId, () => {
+								this.updateOfflinePrompt(dropitem);
+							});
+						}
+					});
 				}
 			});
-		},
+		}
+	}
 
-		removeFromList: function(elem) {
-			const bookId = elem.getAttribute("data-book-id");
+	removeFromList(elem) {
+		const bookId = elem.getAttribute("data-book-id");
 
-			return App.Offline.remove(bookId, function() {
-				$("#cell-" + bookId).remove();
-			});
-		},
-		remove: function(id, callback) {
-			if (confirm("Remove download?")) {
+		this.remove(bookId, () => {
+			$("#cell-" + bookId).remove();
+		});
+	}
 
-				const cacheId = "epube-book." + id;
-				const promises = [];
+	remove(id, callback) {
+		if (confirm("Remove download?")) {
 
-				console.log("offline remove: " + id);
+			const cacheId = "epube-book." + id;
+			const promises = [];
 
-				localforage.iterate(function(value, key /*, i */) {
-					if (key.match(cacheId)) {
-						promises.push(localforage.removeItem(key));
-					}
-				});
+			console.log("offline remove: " + id);
 
-				Promise.all(promises).then(function() {
-					window.setTimeout(function() {
-						callback();
-					}, 500);
-				});
-			}
-		},
-		search: function() {
-			const query = $(".search_query").val();
+			localforage.iterate(function(value, key /*, i */) {
+				if (key.match(cacheId)) {
+					promises.push(localforage.removeItem(key));
+				}
+			});
 
-			localforage.setItem("epube.search-query", query).then(function() {
-				App.Offline.populateList();
+			Promise.all(promises).then(() => {
+				console.log('remove done, running callback', callback);
+
+				// just promise.all is not enough, need to wait a bit for localforage to actually delete item (?)
+				window.setTimeout(() => {
+					callback();
+				}, 250);
 			});
+		}
+	}
 
-			return false;
-		},
-		removeAll: function() {
-			if (confirm("Remove all downloaded books?")) {
+	async search() {
+		const query = $(".search_query").val();
 
-				const promises = [];
+		await localforage.setItem("epube.search-query", query);
 
-				localforage.iterate(function(value, key/*, i*/) {
+		this.populateList();
 
-					if (key.match("epube-book")) {
-						promises.push(localforage.removeItem(key));
-					}
-				});
+		return false;
+	}
 
-				Promise.all(promises).then(function() {
-					window.setTimeout(function() {
-						App.Offline.populateList();
-					}, 500);
-				});
-			}
-		},
-		showSummary: function(elem) {
-			const bookId = elem.getAttribute("data-book-id");
+	async removeAll() {
+		if (confirm("Remove all downloaded books?")) {
 
-			localforage.getItem("epube-book." + bookId).then(function(data) {
+			const promises = [];
 
-				const comment = data.comment ? data.comment : 'No description available';
+			localforage.iterate(function(value, key/*, i*/) {
+				if (key.match("epube-book")) {
+					promises.push(localforage.removeItem(key));
+				}
+			});
 
-				$("#summary-modal .modal-title").html(data.title);
-				$("#summary-modal .book-summary").html(comment);
+			await Promise.all(promises);
 
-				$("#summary-modal").modal();
+			this.populateList();
+		}
+	}
 
-			});
+	populateList() {
+		let query = this.urlParam("query");
 
-			return false;
-		},
-		populateList: function() {
-			let query = $.urlParam("query");
+		if (query) query = String(query).toLowerCase();
 
-			if (query) query = query.toLowerCase();
+		const books = $("#books_container");
+		books.html("");
 
-			const books = $("#books_container");
-			books.html("");
+		localforage.iterate(function(value, key/*, i*/) {
+			if (key.match(/epube-book\.\d{1,}$/)) {
 
-			localforage.iterate(function(value, key/*, i*/) {
-				if (key.match(/epube-book\.\d{1,}$/)) {
+				Promise.all([
+					localforage.getItem(key),
+					localforage.getItem(key + ".cover"),
+					localforage.getItem(key + ".lastread"),
+					localforage.getItem(key + ".book")
+				]).then(function(results) {
 
-					Promise.all([
-						localforage.getItem(key),
-						localforage.getItem(key + ".cover"),
-						localforage.getItem(key + ".lastread"),
-						localforage.getItem(key + ".book")
-					]).then(function(results) {
+					if (results[0] && results[3]) {
+						const info = results[0];
 
-						if (results[0] && results[3]) {
-							const info = results[0];
+						if (query) {
+							const match =
+								(info.series_name && info.series_name.toLowerCase().match(query)) ||
+								(info.title && info.title.toLowerCase().match(query)) ||
+								(info.author_sort && info.author_sort.toLowerCase().match(query));
 
-							if (query) {
-								const match =
-									(info.series_name && info.series_name.toLowerCase().match(query)) ||
-									(info.title && info.title.toLowerCase().match(query)) ||
-									(info.author_sort && info.author_sort.toLowerCase().match(query));
+							if (!match) return;
+						}
 
-								if (!match) return;
-							}
 
+						let cover = "";
 
-							let cover = false;
+						if (results && results[1]) {
+							cover = URL.createObjectURL(results[1]);
+						}
 
-							if (results && results[1]) {
-								cover = URL.createObjectURL(results[1]);
-							}
+						let in_progress = false;
+						let is_read = false;
 
-							let in_progress = false;
-							let is_read = false;
+						const lastread = results[2];
+						if (lastread) {
+							in_progress = lastread.page > 0;
+							is_read = lastread.total > 0 && lastread.total - lastread.page < 5;
+						}
 
-							const lastread = results[2];
-							if (lastread) {
-								in_progress = lastread.page > 0;
-								is_read = lastread.total > 0 && lastread.total - lastread.page < 5;
-							}
+						const thumb_class = is_read ? "read" : "";
+						const title_class = in_progress ? "in_progress" : "";
+
+						const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : "";
+
+						const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}">
+						<a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}">
+							<img style="display : none">
+						</a>
+						<div class="caption">
+							<div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div>
+							<div><a class="author_link" href="#">${info.author_sort}</a></div>
+							${series_link}
+						</div>
+						<div class="dropdown" style="white-space : nowrap">
+							<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
+							<ul class="dropdown-menu">
+								<li><a href="#" data-book-id="${info.id}" onclick="return App.showSummary(this)">Summary</a></li>
+								<li><a href="#" data-book-id="${info.id}" onclick="App.removeFromList(this)">Remove offline data</a></li>
+							</ul>
+						</div>
+					</div>`);
+
+						if (cover) {
+							cell.find("img")
+								.css("background-image", "url(" + cover + ")")
+								.fadeIn();
+						} else {
+							cell
+								.fadeIn();
+						}
 
-							const thumb_class = is_read ? "read" : "";
-							const title_class = in_progress ? "in_progress" : "";
-
-							const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : "";
-
-							const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}">
-							<a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}">
-								<img style="display : none">
-							</a>
-							<div class="caption">
-								<div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div>
-								<div><a class="author_link" href="#">${info.author_sort}</a></div>
-								${series_link}
-							</div>
-							<div class="dropdown" style="white-space : nowrap">
-								<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
-								<ul class="dropdown-menu">
-									<li><a href="#" data-book-id="${info.id}" onclick="return App.Offline.showSummary(this)">Summary</a></li>
-									<li><a href="#" data-book-id="${info.id}" onclick="App.Offline.removeFromList(this)">Remove offline data</a></li>
-								</ul>
-							</div>
-						</div>`);
-
-							if (cover) {
-								cell.find("img")
-									.css("background-image", "url(" + cover + ")")
-									.fadeIn();
-							} else {
-								cell
-									.fadeIn();
-							}
+						cell.find(".series_link")
+							.attr("title", info.series_name + " [" + info.series_index  + "]")
+							.attr("href", "offline.html?query=" + encodeURIComponent(info.series_name));
 
-							cell.find(".series_link")
-								.attr("title", info.series_name + " [" + info.series_index  + "]")
-								.attr("href", "offline.html?query=" + encodeURIComponent(info.series_name));
+						cell.find(".author_link")
+							.attr("title", info.author_sort)
+							.attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort));
 
-							cell.find(".author_link")
-								.attr("title", info.author_sort)
-								.attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort));
+						books.append(cell);
+					}
+				});
+			}
+		});
+	}
 
-							books.append(cell);
-						}
-					});
-				}
-			});
-		}
-	},
-};
+}
diff --git a/js/localforage.d.ts b/js/localforage.d.ts
new file mode 100644
index 0000000..7fb8f58
--- /dev/null
+++ b/js/localforage.d.ts
@@ -0,0 +1,123 @@
+interface LocalForageDbInstanceOptions {
+    name?: string;
+
+    storeName?: string;
+}
+
+interface LocalForageOptions extends LocalForageDbInstanceOptions {
+    driver?: string | string[];
+
+    size?: number;
+
+    version?: number;
+
+    description?: string;
+}
+
+interface LocalForageDbMethodsCore {
+    getItem<T>(key: string, callback?: (err: any, value: T | null) => void): Promise<T | null>;
+
+    setItem<T>(key: string, value: T, callback?: (err: any, value: T) => void): Promise<T>;
+
+    removeItem(key: string, callback?: (err: any) => void): Promise<void>;
+
+    clear(callback?: (err: any) => void): Promise<void>;
+
+    length(callback?: (err: any, numberOfKeys: number) => void): Promise<number>;
+
+    key(keyIndex: number, callback?: (err: any, key: string) => void): Promise<string>;
+
+    keys(callback?: (err: any, keys: string[]) => void): Promise<string[]>;
+
+    iterate<T, U>(iteratee: (value: T, key: string, iterationNumber: number) => U,
+            callback?: (err: any, result: U) => void): Promise<U>;
+}
+
+interface LocalForageDropInstanceFn {
+    (dbInstanceOptions?: LocalForageDbInstanceOptions, callback?: (err: any) => void): Promise<void>;
+}
+
+interface LocalForageDriverMethodsOptional {
+    dropInstance?: LocalForageDropInstanceFn;
+}
+
+// duplicating LocalForageDriverMethodsOptional to preserve TS v2.0 support,
+// since Partial<> isn't supported there
+interface LocalForageDbMethodsOptional {
+    dropInstance: LocalForageDropInstanceFn;
+}
+
+interface LocalForageDriverDbMethods extends LocalForageDbMethodsCore, LocalForageDriverMethodsOptional {}
+
+interface LocalForageDriverSupportFunc {
+    (): Promise<boolean>;
+}
+
+interface LocalForageDriver extends LocalForageDriverDbMethods {
+    _driver: string;
+
+    _initStorage(options: LocalForageOptions): void;
+
+    _support?: boolean | LocalForageDriverSupportFunc;
+}
+
+interface LocalForageSerializer {
+    serialize<T>(value: T | ArrayBuffer | Blob, callback: (value: string, error: any) => void): void;
+
+    deserialize<T>(value: string): T | ArrayBuffer | Blob;
+
+    stringToBuffer(serializedString: string): ArrayBuffer;
+
+    bufferToString(buffer: ArrayBuffer): string;
+}
+
+interface LocalForageDbMethods extends LocalForageDbMethodsCore, LocalForageDbMethodsOptional {}
+
+interface LocalForage extends LocalForageDbMethods {
+    LOCALSTORAGE: string;
+    WEBSQL: string;
+    INDEXEDDB: string;
+
+    /**
+     * Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded.
+     * If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver()
+     * @param {LocalForageOptions} options?
+     */
+    config(options: LocalForageOptions): boolean;
+    config(options: string): any;
+    config(): LocalForageOptions;
+
+    /**
+     * Create a new instance of localForage to point to a different store.
+     * All the configuration options used by config are supported.
+     * @param {LocalForageOptions} options
+     */
+    createInstance(options: LocalForageOptions): LocalForage;
+
+    driver(): string;
+
+    /**
+     * Force usage of a particular driver or drivers, if available.
+     * @param {string} driver
+     */
+    setDriver(driver: string | string[], callback?: () => void, errorCallback?: (error: any) => void): Promise<void>;
+
+    defineDriver(driver: LocalForageDriver, callback?: () => void, errorCallback?: (error: any) => void): Promise<void>;
+
+    /**
+     * Return a particular driver
+     * @param {string} driver
+     */
+    getDriver(driver: string): Promise<LocalForageDriver>;
+
+    getSerializer(callback?: (serializer: LocalForageSerializer) => void): Promise<LocalForageSerializer>;
+
+    supports(driverName: string): boolean;
+
+    ready(callback?: (error: any) => void): Promise<void>;
+}
+
+declare module "localforage" {
+    let localforage: LocalForage;
+    export = localforage;
+}
diff --git a/js/reader.d.ts b/js/reader.d.ts
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/js/reader.d.ts
diff --git a/js/reader.js b/js/reader.js
index 129ad52..f68f5cd 100644
--- a/js/reader.js
+++ b/js/reader.js
@@ -1,3 +1,4 @@
+// @ts-check
 'use strict';
 
 /* global localforage, EpubeApp, App, Cookie, $ */
diff --git a/offline.html b/offline.html
index 3545127..efb414c 100644
--- a/offline.html
+++ b/offline.html
@@ -15,6 +15,8 @@
 	<script type="text/javascript">
 		'use strict';
 
+		const App = new AppClass();
+
 		if ('serviceWorker' in navigator) {
 			navigator.serviceWorker
 					.register('worker.js')
@@ -22,7 +24,7 @@
 						console.log("service worker registered");
 
 						$(document).ready(function() {
-							App.Offline.init();
+							App.offlineInit();
 						});
 					});
 		} else {
@@ -65,7 +67,11 @@
 		</form>
 
 		<ul class="nav navbar-nav navbar-right">
-			<li><a href="#" onclick="App.Offline.removeAll()" title="Remove all downloads">
+			<li><a href="#" title="Refresh script cache" onclick="return App.refreshCache(true)">
+				<span class="glyphicon glyphicon-refresh"></span> <span class='hidden-sm hidden-md hidden-lg'>Refresh script cache</span></a></li>
+			</li>
+
+			<li><a href="#" onclick="App.removeAll()" title="Remove all downloads">
 				<span class="glyphicon glyphicon-remove-circle text-danger"></span> <span class='hidden-sm hidden-md hidden-lg'>Remove all downloads</span>
 			</a></li>
 		</ul>
diff --git a/read.html b/read.html
index 7e9f58b..271d8d3 100644
--- a/read.html
+++ b/read.html
@@ -27,6 +27,8 @@
 	<script type="text/javascript">
 		'use strict';
 
+		const Reader = new ReaderClass();
+
 		if ('serviceWorker' in navigator) {
 			navigator.serviceWorker
 					.register('worker.js')