From fbbcdb168b87421d754382f8aef5ab5fdfc72713 Mon Sep 17 00:00:00 2001 From: Andrew Dolgov Date: Mon, 19 Feb 2024 20:53:47 +0300 Subject: stop bothering with mtime to detect cache refresh need --- dist/app.min.js | 2 +- index.php | 8 -------- js/app.js | 8 +++----- 3 files changed, 4 insertions(+), 14 deletions(-) diff --git a/dist/app.min.js b/dist/app.min.js index 4d089b3..e6f22b2 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>>",t)})),"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),"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-timestamp",App.last_mtime),localforage.setItem("epube.cache-version",App.version),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=$("").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-timestamp").then((function(e){console.log("stamp",e,"last mtime",App.last_mtime,"version",App.version),(t||e!=App.last_mtime)&&(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(),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 "+o.title+""),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?`
${a.series_name+" ["+a.series_index+"]"}
`:"",f=$(`
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t
${a.title}
\n\t\t\t\t\t\t\t\t
${a.author_sort}
\n\t\t\t\t\t\t\t\t${d}\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
`);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,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()},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.
${t.responseText}`)}}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.
"+t+"")},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.
"+t.message+"")}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:!0,minSpreadWidth:961});$(".location").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.applyStyles(!0),console.log("book displayed"),Reader.initRenditionHooks(e,o),Reader.initModals(),Reader.initToc(e),Reader.initStyleHooks(e),await Reader.Page.openLastRead(),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"),e=await o.json(),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…"),e=await t.locations.generate(100),$.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){e.hooks.content.register(async t=>{t.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))});const o=window.location.href.match(/^.*\//)[0];"undefined"!=typeof EpubeApp?$(t.document.head).append($('')):$(t.document.head).append($("