diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-05-24 10:39:02 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-05-24 10:39:02 +0300 |
| commit | d661d2b5ee1e619cd53de79af3f6b16bc2ec5f22 (patch) | |
| tree | e9c5d0e9e8b4f601c0ba62fb3b637da91eafdb56 | |
| parent | ab8491cfcc34b46eaed06d8d317cd626bf26956d (diff) | |
| download | the-epube-d661d2b5ee1e619cd53de79af3f6b16bc2ec5f22.tar.gz the-epube-d661d2b5ee1e619cd53de79af3f6b16bc2ec5f22.tar.xz | |
split csrf prefilter into separate file, add tsconfig.json for vscodium
| -rw-r--r-- | build.js | 1 | ||||
| -rw-r--r-- | dist/app.min.js | 4 | ||||
| -rw-r--r-- | package-lock.json | 14 | ||||
| -rw-r--r-- | package.json | 1 | ||||
| -rw-r--r-- | src/app.js | 18 | ||||
| -rw-r--r-- | src/csrf.js | 26 | ||||
| -rw-r--r-- | src/reader.js | 18 | ||||
| -rw-r--r-- | tsconfig.json | 10 |
8 files changed, 56 insertions, 36 deletions
diff --git a/build.js b/build.js index eb3962e..f76d254 100644 --- a/build.js +++ b/build.js @@ -28,6 +28,7 @@ const LESS_FILES = [ ] const JS_FILES = [ + 'src/csrf.js', 'src/app.js', 'src/reader.js' ]; diff --git a/dist/app.min.js b/dist/app.min.js index 8b1d831..8ea28e4 100644 --- a/dist/app.min.js +++ b/dist/app.min.js @@ -1,4 +1,4 @@ -"use strict";class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const s="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+s}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";init(){let e=0;this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,o,a)=>{if(o.type!=="post"||t.type!=="post")return;const s=typeof o.data;s=="object"?t.data=$.param($.extend(o.data,{csrf_token:this.csrf_token})):s=="string"&&(t.data=o.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),this.urlParam("mode")=="favorites"?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),this.initCommonEventHandlers(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",t=>{t.data=="refresh-started"&&(console.log("cache refresh started"),e=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),t.data&&t.data.indexOf("refreshed:")==0&&(++e,$(".dl-progress").fadeIn().text("Updated "+e+" files...")),t.data=="refresh-finished"&&(localforage.setItem("epube.cache-version",this.version),localforage.setItem("epube.cache-timestamp",this.buildTimestamp),window.location.reload())}),this.showCovers(),this.updateOfflinePrompts(),this.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")}initCommonEventHandlers(){$(".refresh_cache_link").on("click",()=>{this.refreshCache(!0)}),$(".remove_all_downloads").on("click",()=>{this.removeAll()}),$(".logout_link").on("click",()=>{this.logout()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const t=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:t}),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+t),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,t)=>{const o=$(t);if(o.attr("data-cover-link")){const a=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),a.attr("src",null)}).attr("src",o.attr("data-cover-link"))}})}toggleFavorite(e){const t=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:t},o=>{if(o){let a="[Error]";o.status==0?a="Add to favorites":o.status==1&&(a="Remove from favorites"),$(e).html(a).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+t).remove()}}),!1}async refreshCache(e){if("serviceWorker"in navigator){const t=await localforage.getItem("epube.cache-version");if(console.log("local version",t,"remote version",this.version),e||t!=this.version)if(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller)navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:this.cached_urls});else{const o=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",o),o?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):(await localforage.setItem("epube.initial-load-done",!0),$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout(function(){window.location.reload()},3*1e3))}}else $(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(t,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const t=e.getAttribute("data-book-id"),o="epube-book."+t;await localforage.getItem(o)?(e.onclick=()=>(this.remove(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}offlineInit(){typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode(),this.initCommonEventHandlers();const e=this.urlParam("query");e&&$(".search_query").val(e),this.populateList()}get(e,t){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const a="epube-book."+e;localforage.setItem(a,o).then(s=>{console.log(a+" got data");const i=[];i.push(fetch("backend.php?op=download&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),i.push(fetch("backend.php?op=getpagination&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got pagination"),n.text().then(function(l){localforage.setItem(a+".locations",JSON.parse(l))}))})),i.push(fetch("backend.php?op=getlastread&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got lastread"),n.text().then(function(l){localforage.setItem(a+".lastread",JSON.parse(l))}))})),s.has_cover&&i.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got cover"),localforage.setItem(a+".cover",n.blob()))})),Promise.all(i).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+s.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,t)=>{const o=$(t).attr("id").replace("cell-",""),a=$(t).find(".offline_dropitem")[0];if(o){const s="epube-book."+o;localforage.getItem(s).then(i=>{i||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(e){const t=e.getAttribute("data-book-id");this.remove(t,()=>{$("#cell-"+t).remove()})}remove(e,t){if(confirm("Remove download?")){const o="epube-book."+e,a=[];console.log("offline remove: "+e),localforage.iterate(function(s,i){i.match(o)&&a.push(localforage.removeItem(i))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(t,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateList()}}populateList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate(function(o,a){a.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(a),localforage.getItem(a+".cover"),localforage.getItem(a+".lastread"),localforage.getItem(a+".book")]).then(function(s){if(s[0]&&s[3]){const i=s[0];if(e&&!(i.series_name&&i.series_name.toLowerCase().match(e)||i.title&&i.title.toLowerCase().match(e)||i.author_sort&&i.author_sort.toLowerCase().match(e)))return;let n="";s&&s[1]&&(n=URL.createObjectURL(s[1]));let l=!1,r=!1;const c=s[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const h=r?"read":"",p=l?"in_progress":"",m=i.series_name?`<div><a class="series_link" href="#">${i.series_name+" ["+i.series_index+"]"}</a></div>`:"",d=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${i.id}"> +"use strict";function setupCsrfPrefilter(d){console.log("setting prefilter for token",d),$.ajaxPrefilter((e,t,o)=>{if(t.type!=="post"||e.type!=="post")return;const a=typeof t.data;a=="object"?e.data=$.param($.extend(t.data,{csrf_token:d})):a=="string"&&(e.data=t.data+"&csrf_token="+encodeURIComponent(d)),console.log(">>>",e)})}class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const s="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+s}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";init(){let e=0;this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),this.urlParam("mode")=="favorites"?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),this.initCommonEventHandlers(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",t=>{t.data=="refresh-started"&&(console.log("cache refresh started"),e=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),t.data&&t.data.indexOf("refreshed:")==0&&(++e,$(".dl-progress").fadeIn().text("Updated "+e+" files...")),t.data=="refresh-finished"&&(localforage.setItem("epube.cache-version",this.version),localforage.setItem("epube.cache-timestamp",this.buildTimestamp),window.location.reload())}),this.showCovers(),this.updateOfflinePrompts(),this.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")}initCommonEventHandlers(){$(".refresh_cache_link").on("click",()=>{this.refreshCache(!0)}),$(".remove_all_downloads").on("click",()=>{this.removeAll()}),$(".logout_link").on("click",()=>{this.logout()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(e){const t=e.getAttribute("data-book-id");if(this.isOnline()){const o=await $.post("backend.php",{op:"getinfo",id:t}),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}else{const o=await localforage.getItem("epube-book."+t),a=o.comment?o.comment:"No description available";$("#summary-modal .modal-title").html(o.title),$("#summary-modal .book-summary").html(a),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((e,t)=>{const o=$(t);if(o.attr("data-cover-link")){const a=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),a.attr("src",null)}).attr("src",o.attr("data-cover-link"))}})}toggleFavorite(e){const t=e.getAttribute("data-book-id");return(e.getAttribute("data-is-fav")=="0"||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:t},o=>{if(o){let a="[Error]";o.status==0?a="Add to favorites":o.status==1&&(a="Remove from favorites"),$(e).html(a).attr("data-is-fav",o.status),this.index_mode=="favorites"&&o.status==0&&$("#cell-"+t).remove()}}),!1}async refreshCache(e){if("serviceWorker"in navigator){const t=await localforage.getItem("epube.cache-version");if(console.log("local version",t,"remote version",this.version),e||t!=this.version)if(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller)navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:this.cached_urls});else{const o=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",o),o?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):(await localforage.setItem("epube.initial-load-done",!0),$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout(function(){window.location.reload()},3*1e3))}}else $(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}updateOfflinePrompts(){const e=$(".offline_dropitem");$.each(e,(t,o)=>{this.updateOfflinePrompt(o)})}async updateOfflinePrompt(e){const t=e.getAttribute("data-book-id"),o="epube-book."+t;await localforage.getItem(o)?(e.onclick=()=>(this.remove(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Remove offline data"):(e.onclick=()=>(this.get(t,()=>{this.updateOfflinePrompt(e)}),!1),e.innerHTML="Make available offline")}offlineInit(){typeof EpubeApp<"u"&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode(),this.initCommonEventHandlers();const e=this.urlParam("query");e&&$(".search_query").val(e),this.populateList()}get(e,t){console.log("offline cache: "+e),$.post("backend.php",{op:"getinfo",id:e},o=>{if(o){const a="epube-book."+e;localforage.setItem(a,o).then(s=>{console.log(a+" got data");const i=[];i.push(fetch("backend.php?op=download&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),i.push(fetch("backend.php?op=getpagination&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got pagination"),n.text().then(function(l){localforage.setItem(a+".locations",JSON.parse(l))}))})),i.push(fetch("backend.php?op=getlastread&id="+s.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got lastread"),n.text().then(function(l){localforage.setItem(a+".lastread",JSON.parse(l))}))})),s.has_cover&&i.push(fetch("backend.php?op=cover&id="+e,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got cover"),localforage.setItem(a+".cover",n.blob()))})),Promise.all(i).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+s.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,t)=>{const o=$(t).attr("id").replace("cell-",""),a=$(t).find(".offline_dropitem")[0];if(o){const s="epube-book."+o;localforage.getItem(s).then(i=>{i||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(e){const t=e.getAttribute("data-book-id");this.remove(t,()=>{$("#cell-"+t).remove()})}remove(e,t){if(confirm("Remove download?")){const o="epube-book."+e,a=[];console.log("offline remove: "+e),localforage.iterate(function(s,i){i.match(o)&&a.push(localforage.removeItem(i))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const e=[];localforage.iterate(function(t,o){o.match("epube-book")&&e.push(localforage.removeItem(o))}),await Promise.all(e),this.populateList()}}populateList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate(function(o,a){a.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(a),localforage.getItem(a+".cover"),localforage.getItem(a+".lastread"),localforage.getItem(a+".book")]).then(function(s){if(s[0]&&s[3]){const i=s[0];if(e&&!(i.series_name&&i.series_name.toLowerCase().match(e)||i.title&&i.title.toLowerCase().match(e)||i.author_sort&&i.author_sort.toLowerCase().match(e)))return;let n="";s&&s[1]&&(n=URL.createObjectURL(s[1]));let l=!1,r=!1;const c=s[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const h=r?"read":"",p=l?"in_progress":"",m=i.series_name?`<div><a class="series_link" href="#">${i.series_name+" ["+i.series_index+"]"}</a></div>`:"",f=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${i.id}"> <a class="thumbnail ${h}" href="read.html?id=${i.epub_id}&b=${i.id}"> <img style="display : none"> </a> @@ -14,7 +14,7 @@ <li><a href="#" data-book-id="${i.id}" onclick="App.removeFromList(this)">Remove offline data</a></li> </ul> </div> - </div>`);n?d.find("img").css("background-image","url("+n+")").fadeIn():d.fadeIn(),d.find(".series_link").attr("title",i.series_name+" ["+i.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(i.series_name)),d.find(".author_link").attr("title",i.author_sort).attr("href","offline.html?query="+encodeURIComponent(i.author_sort)),t.append(d)}})})}}const DEFAULT_FONT_SIZE=16,DEFAULT_FONT_FAMILY="Arial",DEFAULT_LINE_HEIGHT=140,MIN_LENGTH_TO_JUSTIFY=32,LOCATION_DIVISOR=10,PAGE_RESET_PROGRESS=-1;class ReaderClass extends AppCommon{csrf_token="";last_stored_cfi="";startup_finished=!1;open_last_read_when_displayed=!0;hyphenate={};_prevent_lastread_timeout;_prevent_lastread;book;async init(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,o)=>{if(o.type!=="post"||t.type!=="post")return;const a=typeof o.data;a=="object"?t.data=$.param($.extend(o.data,{csrf_token:this.csrf_token})):a=="string"&&(t.data=o.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",t=>{this.openPrevious(t.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader;const e=await this.loader.init();console.log("[init] load failed",e),e?(this.applyTheme(),$(".loading-message").text("Resource loader failed to initialize.")):this.initSecondStage()}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(e){if(console.log("onOfflineModeChanged",e),!e&&this.book){console.log("we're online, storing lastread");const t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:new Date().getTime()},function(){}).fail(function(a){a&&a.status==401&&(window.location.href="index.php")})}}async initSecondStage(){if(typeof EpubeApp<"u"?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme(),!await localforage.getItem(this.cacheId())){const s=this.urlParam("b");console.log("requesting bookinfo for book",s);try{const i=await $.post("backend.php",{op:"getinfo",id:s});if(i.has_cover){const n=await fetch("backend.php?op=cover&id="+s);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),i),console.log("bookinfo saved")}catch(i){$(".loading-message").html(`Unable to load book info.<br/><small>${i.responseText}</small>`);return}}console.log("trying to load book...");let t=await localforage.getItem(this.cacheId("book"));if(!t){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const s=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(s.ok)if(t=await s.blob(),t)await localforage.setItem(this.cacheId("book"),t),console.log("saved local data for book");else{$(".loading-message").html("Unable to get book blob data.");return}else{$(".loading-message").html(`Unable to download book: ${s.status}`);return}}const o=new FileReader,a=this;o.onload=function(){try{a.openBookData(this.result)}catch(s){console.error(s),$(".loading-message").html("Unable to load book blob: "+s)}},o.onerror=s=>{console.log("filereader error",s),$(".loading-message").html("Unable to open book.<br/><small>"+s+"</small>")},o.readAsArrayBuffer(t)}async openBookData(e){this.book=new ePub.Book;try{await this.book.open(e)}catch(a){console.error(a),$(".loading-message").html("Unable to open book.<br/><small>"+a.message+"</small>");return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const t=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const a=Math.floor(t.currentLocation().start.location/LOCATION_DIVISOR),s=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),i=prompt("Jump to location [1-"+s+"]",String(a));i&&await t.display(this.book.locations._locations[parseInt(i)*LOCATION_DIVISOR])}),await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(this.book,t),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await t.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const t=await localforage.getItem(this.cacheId());let o,a;if(t)o=t.title,a=t.author_sort;else{const s=e.packaging.metadata;o=s.title,a=s.creator}document.title=o+" \u2013 "+a+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+a),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let t=await localforage.getItem(this.cacheId("locations"));if(t&&typeof t[0]=="string"){console.log("loading local locations...");try{await e.locations.load(t);return}catch(a){console.warn(a)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const a=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(a.ok){console.log("got locations from server");try{t=await a.json()}catch(s){console.warn(s)}if(t&&typeof t[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),t);try{e.locations.load(t);return}catch(s){console.warn(s)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;t=await e.locations.generate(100,a=>{if(o||(o=a.length()),o>0){const s=Math.round((1-a.length()/o)*100);$(".loading-message").html(`Preparing locations (${s}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(t),total:100}),await localforage.setItem(this.cacheId("locations"),t)}initRenditionHooks(e,t){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),t.hooks.content.register(async o=>{o.on("linkClicked",i=>{console.log("linkClicked",i),this.blockLastReadUpdate(),i.indexOf("://")==-1&&($(".prev_location_btn").attr("data-location-cfi",t.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async i=>{if(this.isOnline()){const n=await e.getRange(i),l=n.endContainer.data.substring(n.startOffset,n.endOffset);console.log("selected",i,l),l.match(/^[\w]+$/)&&this.lookupWord(l,()=>{typeof EpubeApp<"u"&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const a=window.location.href.match(/^.*\//)[0];$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[a+"dist/reader_iframe.min.css"]));const s=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+s),console.log("contents",o),$(o.window).on("click tap",i=>{if(i.button==0){if($(".modal").is(":visible"))return;typeof EpubeApp<"u"?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async i=>{await localforage.getItem("epube.enable-wheel")&&(i.originalEvent.deltaY>0?this.nextPage():i.originalEvent.deltaY<0&&this.prevPage())})}),t.on("keyup",o=>{this.hotkeyHandler(o)}),t.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),t.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=t.currentLocation();if(o.start){const a=e.canonical(o.start.href);let s={};$.each(this.flattenToc(e),function(i,n){if(e.spine.get(n.href).canonical==a){s=n;return}}),s&&s.label&&$(".chapter_title").html(s.label.trim()+" | "),this.generateTocBar(e,this.flattenToc(e))}}catch(o){console.warn(o)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),t.on("displayed",function(){console.log("rendition displayed")}),t.on("relocated",o=>this.onRelocated(e,o))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const e=await localforage.getItem(this.cacheId("lastread"));e&&e.cfi&&$(".lastread_input").val(e.page+"%").attr("title",`[local] ${e.cfi}`),$(".clear_last_read").off("click").on("click",()=>{this.clearLastRead()}),$(".open_last_read").off("click").on("click",()=>{this.openLastRead()}),$(".mark_as_read").off("click").on("click",()=>{this.markAsRead()}),$(".reset_locations").off("click").on("click",()=>{this.resetLocations()}),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},i=>{$(".lastread_input").val(i.page+"%").attr("title",`[remote] ${i.cfi}`)}),$(".font_family").off("change").on("change",i=>{this.onFontChanged(i.target)}),$(".font_size").off("change").on("change",i=>{this.onTextSizeChanged(i.target)}),$(".line_height").off("change").on("change",i=>{this.onLineHeightChanged(i.target)}),$(".theme_name").off("change").on("change",i=>{this.onThemeChanged(i.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",i=>{localforage.setItem("epube.enable-hyphens",i.target.checked),confirm("Toggling hyphens requires page reload. Reload now?")&&window.location.reload()}),$(".enable_wheel_checkbox").attr("checked",await localforage.getItem("epube.enable-wheel")).off("click").on("click",i=>{localforage.setItem("epube.enable-wheel",i.target.checked)}),typeof EpubeApp<"u"?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",i=>{localforage.setItem("epube.keep-ui-visible",i.target.checked)});const t=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o} + </div>`);n?f.find("img").css("background-image","url("+n+")").fadeIn():f.fadeIn(),f.find(".series_link").attr("title",i.series_name+" ["+i.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(i.series_name)),f.find(".author_link").attr("title",i.author_sort).attr("href","offline.html?query="+encodeURIComponent(i.author_sort)),t.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;class ReaderClass extends AppCommon{csrf_token="";last_stored_cfi="";startup_finished=!1;open_last_read_when_displayed=!0;hyphenate={};_prevent_lastread_timeout;_prevent_lastread;book;async init(){this.csrf_token=Cookie.get("epube_csrf_token"),setupCsrfPrefilter(this.csrf_token),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",t=>{this.openPrevious(t.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader;const e=await this.loader.init();console.log("[init] load failed",e),e?(this.applyTheme(),$(".loading-message").text("Resource loader failed to initialize.")):this.initSecondStage()}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(e){if(console.log("onOfflineModeChanged",e),!e&&this.book){console.log("we're online, storing lastread");const t=this.book.rendition.currentLocation().start.cfi,o=Math.round(this.book.locations.percentageFromCfi(t)*100);$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:t,timestamp:new Date().getTime()},function(){}).fail(function(a){a&&a.status==401&&(window.location.href="index.php")})}}async initSecondStage(){if(typeof EpubeApp<"u"?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme(),!await localforage.getItem(this.cacheId())){const s=this.urlParam("b");console.log("requesting bookinfo for book",s);try{const i=await $.post("backend.php",{op:"getinfo",id:s});if(i.has_cover){const n=await fetch("backend.php?op=cover&id="+s);n.ok&&await localforage.setItem(this.cacheId("cover"),n.blob())}await localforage.setItem(this.cacheId(),i),console.log("bookinfo saved")}catch(i){$(".loading-message").html(`Unable to load book info.<br/><small>${i.responseText}</small>`);return}}console.log("trying to load book...");let t=await localforage.getItem(this.cacheId("book"));if(!t){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book\u2026");const s=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(s.ok)if(t=await s.blob(),t)await localforage.setItem(this.cacheId("book"),t),console.log("saved local data for book");else{$(".loading-message").html("Unable to get book blob data.");return}else{$(".loading-message").html(`Unable to download book: ${s.status}`);return}}const o=new FileReader,a=this;o.onload=function(){try{a.openBookData(this.result)}catch(s){console.error(s),$(".loading-message").html("Unable to load book blob: "+s)}},o.onerror=s=>{console.log("filereader error",s),$(".loading-message").html("Unable to open book.<br/><small>"+s+"</small>")},o.readAsArrayBuffer(t)}async openBookData(e){this.book=new ePub.Book;try{await this.book.open(e)}catch(a){console.error(a),$(".loading-message").html("Unable to open book.<br/><small>"+a.message+"</small>");return}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const t=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const a=Math.floor(t.currentLocation().start.location/LOCATION_DIVISOR),s=Math.floor(this.book.locations.length()/LOCATION_DIVISOR),i=prompt("Jump to location [1-"+s+"]",String(a));i&&await t.display(this.book.locations._locations[parseInt(i)*LOCATION_DIVISOR])}),await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(this.book,t),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await t.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(e){const t=await localforage.getItem(this.cacheId());let o,a;if(t)o=t.title,a=t.author_sort;else{const s=e.packaging.metadata;o=s.title,a=s.creator}document.title=o+" \u2013 "+a+" \u2013 The Epube",$(".title").text(o).attr("title",o+" \u2013 "+a),typeof EpubeApp<"u"&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(e){let t=await localforage.getItem(this.cacheId("locations"));if(t&&typeof t[0]=="string"){console.log("loading local locations...");try{await e.locations.load(t);return}catch(a){console.warn(a)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations\u2026");const a=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(a.ok){console.log("got locations from server");try{t=await a.json()}catch(s){console.warn(s)}if(t&&typeof t[0]=="string"){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),t);try{e.locations.load(t);return}catch(s){console.warn(s)}}}}$(".loading-message").html("Preparing locations\u2026");let o=0;t=await e.locations.generate(100,a=>{if(o||(o=a.length()),o>0){const s=Math.round((1-a.length()/o)*100);$(".loading-message").html(`Preparing locations (${s}%)\u2026`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(t),total:100}),await localforage.setItem(this.cacheId("locations"),t)}initRenditionHooks(e,t){console.log("initRenditionHooks"),e.spine.hooks.content.register(o=>{this.cleanupEmbeddedStyles(o)}),t.hooks.content.register(async o=>{o.on("linkClicked",i=>{console.log("linkClicked",i),this.blockLastReadUpdate(),i.indexOf("://")==-1&&($(".prev_location_btn").attr("data-location-cfi",t.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async i=>{if(this.isOnline()){const n=await e.getRange(i),l=n.endContainer.data.substring(n.startOffset,n.endOffset);console.log("selected",i,l),l.match(/^[\w]+$/)&&this.lookupWord(l,()=>{typeof EpubeApp<"u"&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const a=window.location.href.match(/^.*\//)[0];$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[a+"dist/reader_iframe.min.css"]));const s=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class",typeof EpubeApp<"u"?"is-epube-app":"").addClass("theme-"+s),console.log("contents",o),$(o.window).on("click tap",i=>{if(i.button==0){if($(".modal").is(":visible"))return;typeof EpubeApp<"u"?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async i=>{await localforage.getItem("epube.enable-wheel")&&(i.originalEvent.deltaY>0?this.nextPage():i.originalEvent.deltaY<0&&this.prevPage())})}),t.on("keyup",o=>{this.hotkeyHandler(o)}),t.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),t.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=t.currentLocation();if(o.start){const a=e.canonical(o.start.href);let s={};$.each(this.flattenToc(e),function(i,n){if(e.spine.get(n.href).canonical==a){s=n;return}}),s&&s.label&&$(".chapter_title").html(s.label.trim()+" | "),this.generateTocBar(e,this.flattenToc(e))}}catch(o){console.warn(o)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),t.on("displayed",function(){console.log("rendition displayed")}),t.on("relocated",o=>this.onRelocated(e,o))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const e=await localforage.getItem(this.cacheId("lastread"));e&&e.cfi&&$(".lastread_input").val(e.page+"%").attr("title",`[local] ${e.cfi}`),$(".clear_last_read").off("click").on("click",()=>{this.clearLastRead()}),$(".open_last_read").off("click").on("click",()=>{this.openLastRead()}),$(".mark_as_read").off("click").on("click",()=>{this.markAsRead()}),$(".reset_locations").off("click").on("click",()=>{this.resetLocations()}),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},i=>{$(".lastread_input").val(i.page+"%").attr("title",`[remote] ${i.cfi}`)}),$(".font_family").off("change").on("change",i=>{this.onFontChanged(i.target)}),$(".font_size").off("change").on("change",i=>{this.onTextSizeChanged(i.target)}),$(".line_height").off("change").on("change",i=>{this.onLineHeightChanged(i.target)}),$(".theme_name").off("change").on("change",i=>{this.onThemeChanged(i.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",i=>{localforage.setItem("epube.enable-hyphens",i.target.checked),confirm("Toggling hyphens requires page reload. Reload now?")&&window.location.reload()}),$(".enable_wheel_checkbox").attr("checked",await localforage.getItem("epube.enable-wheel")).off("click").on("click",i=>{localforage.setItem("epube.enable-wheel",i.target.checked)}),typeof EpubeApp<"u"?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",i=>{localforage.setItem("epube.keep-ui-visible",i.target.checked)});const t=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o} — ${parseInt(t)?new Date(t*1e3).toLocaleString("en-GB"):"Unknown"} (${this.isOnline()?"<span class='text-success'>Online</span>":"<span class='text-danger'>Offline</span>"}) `),$(".font_family").val(await localforage.getItem("epube.fontFamily")||DEFAULT_FONT_FAMILY),$(".theme_name").val(await localforage.getItem("epube.theme")||"default");const a=$(".font_size").html("");for(let i=10;i<=32;i++){const n=$("<option>").val(i).html(i+" px");a.append(n)}a.val(await localforage.getItem("epube.fontSize")||DEFAULT_FONT_SIZE);const s=$(".line_height").html("");for(let i=100;i<=220;i+=10){const n=$("<option>").val(i).html(i+"%");s.append(n)}s.val(await localforage.getItem("epube.lineHeight")||DEFAULT_LINE_HEIGHT)}),$("#dict-modal").on("shown.bs.modal",()=>{$(".dict_query").off("change").on("change",()=>{this.lookupWord(null,null,".dict_query")}),$(".dict_result").scrollTop(0)}),$(".dict_search_btn").on("click",function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})}initToc(e){const t=this;function o(s){try{const i=e.spine.get(s).cfiBase,n=e.locations._locations.find(function(l){return l.indexOf(i)!=-1});return Math.round(t.book.locations.locationFromCfi(n)/LOCATION_DIVISOR)}catch(i){console.warn(i)}return""}function a(s,i,n){if(n==3)return!1;if(s.subitems){const l=$("<ul class='toc_sublist list-unstyled'>");$.each(s.subitems,function(r,c){const h=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(c.href)+"</b>"+c.label).attr("data-href",c.href).click(function(){e.rendition.display(h.attr("data-href"))});l.append($("<li>").append(h)),a(c,l,n+1)}),i.append(l)}}$("#toc-modal").on("shown.bs.modal",function(){const s=e.navigation.toc,i=$(".toc_list");i.html(""),$.each(s,function(n,l){try{const r=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(l.href)+"</b>"+l.label).attr("data-href",l.href).click(function(){e.rendition.display(r.attr("data-href"))});i.append($("<li>").append(r)),a(l,i,0)}catch(r){console.warn(r)}}),i.children().length<=1&&(i.html(""),$.each(e.spine.items,function(n,l){const r=$("<a>").attr("href","#").attr("title",l.url).html(`Section ${n+1}`).attr("data-href",l.href).on("click",()=>{e.rendition.display(r.attr("data-href"))});i.append($("<li>").append(r))}))})}cleanupEmbeddedStyles(e){$(e).find("p").filter((t,o)=>$(o).text().length>=MIN_LENGTH_TO_JUSTIFY?o:null).css("text-align","justify"),$(e).find("html").attr("class",""),$(e).find("pre").css("white-space","pre-wrap"),$(e).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li").attr("class","").css("font-family","inherit").css("font-size","inherit").css("line-height","inherit").css("color","").css("border","none ! important").css("background","").css("background-color","").attr("width","").attr("height",""),$(e).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),typeof this.hyphenate.en<"u"&&$(e).find("p, div").each((t,o)=>{const a=$(o);a.html(this.hyphenate.en(a.html())),a.html(this.hyphenate.ru(a.html()))})}generateFontsCss(e){return` diff --git a/package-lock.json b/package-lock.json index 703c260..ebe92eb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "localforage": "^1.9.0" }, "devDependencies": { + "@types/jquery": "^4.0.0", "chokidar": "^3.6.0", "cssnano": "^5.1.15", "esbuild": "^0.28.0", @@ -605,6 +606,13 @@ "node": ">= 8" } }, + "node_modules/@types/jquery": { + "version": "4.0.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/jquery/-/jquery-4.0.0.tgz", + "integrity": "sha512-Z+to+A2VkaHq1DfI2oSwsoCdhCHMpTSgjWzNcbNlRGYzksDBpPUgEcAL+RQjOBJRaLoEAOHXxqDGBVP+BblBwg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/localforage": { "version": "0.0.34", "resolved": "https://registry.npmjs.org/@types/localforage/-/localforage-0.0.34.tgz", @@ -3698,6 +3706,12 @@ "fastq": "^1.6.0" } }, + "@types/jquery": { + "version": "4.0.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/jquery/-/jquery-4.0.0.tgz", + "integrity": "sha512-Z+to+A2VkaHq1DfI2oSwsoCdhCHMpTSgjWzNcbNlRGYzksDBpPUgEcAL+RQjOBJRaLoEAOHXxqDGBVP+BblBwg==", + "dev": true + }, "@types/localforage": { "version": "0.0.34", "resolved": "https://registry.npmjs.org/@types/localforage/-/localforage-0.0.34.tgz", diff --git a/package.json b/package.json index dd55758..9667fa5 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ }, "description": "", "devDependencies": { + "@types/jquery": "^4.0.0", "chokidar": "^3.6.0", "cssnano": "^5.1.15", "esbuild": "^0.28.0", diff --git a/src/app.js b/src/app.js index c5f35b4..c5b7c71 100644 --- a/src/app.js +++ b/src/app.js @@ -90,23 +90,7 @@ class AppClass extends AppCommon { this.csrf_token = Cookie.get('epube_csrf_token'); - console.log('setting prefilter for token', this.csrf_token); - - /* eslint-disable no-unused-vars */ - $.ajaxPrefilter((options, originalOptions, jqXHR) => { - if (originalOptions.type !== 'post' || options.type !== 'post') { - return; - } - - const datatype = typeof originalOptions.data; - - if (datatype == 'object') - options.data = $.param($.extend(originalOptions.data, {"csrf_token": this.csrf_token})); - else if (datatype == 'string') - options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token); - - console.log('>>>', options); - }); + setupCsrfPrefilter(this.csrf_token); if (typeof EpubeApp != "undefined") { $(".navbar").hide(); diff --git a/src/csrf.js b/src/csrf.js new file mode 100644 index 0000000..f2b988d --- /dev/null +++ b/src/csrf.js @@ -0,0 +1,26 @@ +// @ts-check + +'use strict'; + +/** + * @param {string} token + */ +function setupCsrfPrefilter(token) { + console.log('setting prefilter for token', token); + + /* eslint-disable no-unused-vars */ + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + if (originalOptions.type !== 'post' || options.type !== 'post') { + return; + } + + const datatype = typeof originalOptions.data; + + if (datatype == 'object') + options.data = $.param($.extend(originalOptions.data, {"csrf_token": token})); + else if (datatype == 'string') + options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(token); + + console.log('>>>', options); + }); +} diff --git a/src/reader.js b/src/reader.js index 27f4337..91b6bbf 100644 --- a/src/reader.js +++ b/src/reader.js @@ -36,23 +36,7 @@ class ReaderClass extends AppCommon { async init() { this.csrf_token = Cookie.get('epube_csrf_token'); - console.log('setting prefilter for token', this.csrf_token); - - $.ajaxPrefilter((options, originalOptions/*, jqXHR*/) => { - - if (originalOptions.type !== 'post' || options.type !== 'post') { - return; - } - - const datatype = typeof originalOptions.data; - - if (datatype == 'object') - options.data = $.param($.extend(originalOptions.data, {"csrf_token": this.csrf_token})); - else if (datatype == 'string') - options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token); - - console.log('>>>', options); - }); + setupCsrfPrefilter(this.csrf_token); $(document).on("keyup", (e) => { this.hotkeyHandler(e); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..2fffcd9 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "noImplicitAny": false, + "noEmit": true, + "types": ["jquery", "localforage"] + }, + "include": ["src/**/*"] +} |
