diff options
| author | fox <fox@fakecake.org> | 2026-05-28 13:27:53 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-05-28 13:27:53 +0300 |
| commit | fd09747bbdb3d5995e9f93e548cab340745d535a (patch) | |
| tree | b8010df4fd2e28d11d0c979f16c3c476560c5d93 | |
| parent | 62a2c2e96e983d479897ebe5b7722b49b13a5180 (diff) | |
| parent | 3ba4ede4952059906a15d6a89a2648aa8aef676e (diff) | |
| download | the-epube-fd09747bbdb3d5995e9f93e548cab340745d535a.tar.gz the-epube-fd09747bbdb3d5995e9f93e548cab340745d535a.tar.xz | |
Merge branch 'dev' into 'master'
Dev See merge request git/the-epube!43
| -rw-r--r-- | classes/Router.php | 30 | ||||
| -rw-r--r-- | dist/app.min.js | 6 | ||||
| -rw-r--r-- | index.php | 1 | ||||
| -rw-r--r-- | src/app.js | 8 | ||||
| -rw-r--r-- | tests/RouterTest.php | 324 |
5 files changed, 356 insertions, 13 deletions
diff --git a/classes/Router.php b/classes/Router.php index bae01ec..d5d4349 100644 --- a/classes/Router.php +++ b/classes/Router.php @@ -18,25 +18,37 @@ class Router $this->middleware[] = $middleware; } - public function dispatch(string $op): Response + /** + * Dispatch an operation and send the response. + * Calls exit after sending the response. + */ + public function dispatch(string $op): void + { + $response = $this->dispatchResponse($op); + $response->send(); + exit; + } + + /** + * Get the Response for a dispatch without sending it. + * Used for testing and for cases where the caller + * wants to modify the response before sending. + */ + public function dispatchResponse(string $op): Response { $handler = $this->routes[$op] ?? null; if (!$handler) { - $response = (new Response()) + return (new Response()) ->withStatus(404) ->withBody(json_encode(["error" => "Method not found"])); - $response->send(); - exit; } // Check auth for handlers that require it if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) { - $response = (new Response()) + return (new Response()) ->withStatus(401) ->withBody(json_encode(["error" => "Unauthorized"])); - $response->send(); - exit; } $pipe = $handler->handle(...); @@ -50,8 +62,6 @@ class Router $request = new Request(); $request = $request->withAttribute('op', $op); - $response = $pipe($request); - $response->send(); - exit; + return $pipe($request); } } diff --git a/dist/app.min.js b/dist/app.min.js index b7f4153..0c8cf1a 100644 --- a/dist/app.min.js +++ b/dist/app.min.js @@ -1,4 +1,4 @@ -"use strict";function setupCsrfPrefilter(f){console.log("setting prefilter for token",f),$.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:f})):a=="string"&&(e.data=t.data+"&csrf_token="+encodeURIComponent(f)),console.log(">>>",e)})}class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const i="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+i}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return t&&decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";index_query="";index_offset=0;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(),this.populateList(),"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()}),$(".download_all_link").on("click",e=>{e.preventDefault(),this.getAll()})}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").text(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").text(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.")}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.populateOfflineList()}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(i=>{console.log(a+" got data");const s=[];s.push(fetch("backend.php?op=download&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),s.push(fetch("backend.php?op=getpagination&id="+i.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))}))})),s.push(fetch("backend.php?op=getlastread&id="+i.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))}))})),i.has_cover&&s.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(s).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+i.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,t)=>{const o=($(t).attr("id")??"").replace("cell-",""),a=$(t).find(".offline_dropitem")[0]??null;if(o){const i="epube-book."+o;localforage.getItem(i).then(s=>{s||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(i,s){s.match(o)&&a.push(localforage.removeItem(s))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}populateList(){const e=new URLSearchParams({op:"list",mode:this.index_mode,query:this.index_query,offset:String(this.index_offset),limit:String(60)});$.get("backend.php?"+e.toString()).done(t=>{const o=$("#books_container");o.html(""),t.books&&t.books.length>0&&(t.books.forEach(a=>{const i=a.is_read?"read":"",s=a.in_progress?"in_progress":"",n=a.is_fav?"1":"0",l=a.is_fav?"Remove from favorites":"Add to favorites",r=a.series_name?`<div><a title="${this.escapeHtml(a.series_full)}" href="${this.escapeHtml(a.series_link)}">${this.escapeHtml(a.series_full)}</a></div>`:"",c=a.author_sort?`?${new URLSearchParams({query:a.author_sort}).toString()}`:"",h=a.download_formats.map(m=>{const d=m.format==="EPUB"?"label-success":"label-primary";return`<li><a target="_blank" href="backend.php?op=download&id=${m.id}">Download: <span class="label ${d}">${m.format}</span></a></li>`}).join(""),u=$(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${a.id}"> +"use strict";function setupCsrfPrefilter(f){console.log("setting prefilter for token",f),$.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:f})):a=="string"&&(e.data=t.data+"&csrf_token="+encodeURIComponent(f)),console.log(">>>",e)})}class Cookie{static set(e,t,o){const a=new Date;a.setTime(a.getTime()+o*1e3);const i="expires="+a.toUTCString();document.cookie=e+"="+encodeURIComponent(t)+"; "+i}static get(e){e=e+"=";const t=document.cookie.split(";");for(let o=0;o<t.length;o++){let a=t[o];for(;a.charAt(0)==" ";)a=a.substring(1);if(a.indexOf(e)==0)return decodeURIComponent(a.substring(e.length,a.length))}return""}static delete(e){const t="expires=Thu, 01-Jan-1970 00:00:01 GMT";document.cookie=e+"=; "+t}}class AppCommon{urlParam(e){try{const t=new RegExp("[?&]"+e+"=([^&#]*)").exec(window.location.href);return t&&decodeURIComponent(t[1].replace(/\+/g," "))||0}catch{return 0}}isOnline(){return typeof EpubeApp<"u"&&typeof EpubeApp.isOnline<"u"?EpubeApp.isOnline():navigator.onLine}initNightMode(){if(typeof EpubeApp<"u"){this.applyNightMode(EpubeApp.isNightMode());return}if(window.matchMedia){const e=window.matchMedia("(prefers-color-scheme: dark)");e.addEventListener("change",()=>{this.applyNightMode(e.matches)}),this.applyNightMode(e.matches)}}applyNightMode(e){console.log("night mode changed to",e),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(e?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";index_query="";index_offset=0;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(),this.populateList(),"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()}),$(".download_all_link").on("click",e=>{e.preventDefault(),this.getAll()})}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").text(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").text(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.")}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.populateOfflineList()}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(i=>{console.log(a+" got data");const s=[];s.push(fetch("backend.php?op=download&id="+i.epub_id,{credentials:"same-origin"}).then(function(n){n.status==200&&(console.log(a+" got book"),localforage.setItem(a+".book",n.blob()))})),s.push(fetch("backend.php?op=getpagination&id="+i.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))}))})),s.push(fetch("backend.php?op=getlastread&id="+i.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))}))})),i.has_cover&&s.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(s).then(()=>{console.log("download done, running callback",t),t(),$(".dl-progress").show().html("Finished downloading <b>"+i.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout(function(){$(".dl-progress").fadeOut()},5*1e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((e,t)=>{const o=($(t).attr("id")??"").replace("cell-",""),a=$(t).find(".offline_dropitem")[0]??null;if(o){const i="epube-book."+o;localforage.getItem(i).then(s=>{s||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(i,s){s.match(o)&&a.push(localforage.removeItem(s))}),Promise.all(a).then(()=>{console.log("remove done, running callback",t),window.setTimeout(()=>{t()},250)})}}populateList(){const e=new URLSearchParams({op:"list",mode:this.index_mode,query:this.index_query,offset:String(this.index_offset),limit:String(60)});$.get("backend.php?"+e.toString()).done(t=>{const o=$("#books_container");o.html(""),t.books&&t.books.length>0&&(t.books.forEach(a=>{const i=a.is_read?"read":"",s=a.in_progress?"in_progress":"",n=a.is_fav?"1":"0",l=a.is_fav?"Remove from favorites":"Add to favorites",r=a.series_name?`<div><a title="${this.escapeHtml(a.series_full)}" href="${this.escapeHtml(a.series_link)}">${this.escapeHtml(a.series_full)}</a></div>`:"",c=a.author_sort?`?${new URLSearchParams({query:a.author_sort}).toString()}`:"",h=a.download_formats.map(m=>{const d=m.format==="EPUB"?"label-success":"label-primary";return`<li><a target="_blank" href="backend.php?op=download&id=${m.id}">Download: <span class="label ${d}">${m.format}</span></a></li>`}).join(""),g=$(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${a.id}"> ${a.read_link?`<a class="thumbnail ${i}" href="${a.read_link}">`:`<span class="thumbnail ${i}">`} <img style="display : none" data-book-id="${a.id}" data-cover-link="${a.cover_link}"> ${a.read_link?"</a>":"</span>"} @@ -18,12 +18,12 @@ ${h} </ul> </div> - </div>`);o.append(u)}),this.showCovers(),this.updateOfflinePrompts(),$(".summary_link").on("click",a=>{a.preventDefault(),this.showSummary(a.currentTarget)}),$(".fav_item").on("click",a=>{a.preventDefault(),this.toggleFavorite(a.currentTarget)}),$(".offline_dropitem").on("click",async a=>{a.preventDefault();const i=a.currentTarget.getAttribute("data-book-id"),s="epube-book."+i;await localforage.getItem(s)?this.remove(i,()=>{this.updateOfflinePrompt(a.currentTarget)}):this.get(i,()=>{this.updateOfflinePrompt(a.currentTarget)})})),this.updateIndexPagination(t)})}updateIndexPagination(e){const t=$(".pager .previous"),o=$(".pager .next"),a=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset-60)}),i=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset+60)});this.index_offset>0?(t.removeClass("disabled"),t.find("a").attr("href","?"+a.toString())):(t.addClass("disabled"),t.find("a").attr("href","#")),e.books&&e.books.length>=60?(o.removeClass("disabled"),o.find("a").attr("href","?"+i.toString())):(o.addClass("disabled"),o.find("a").attr("href","#"))}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateOfflineList(),!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.populateOfflineList()}}populateOfflineList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate((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(i=>{if(i[0]&&i[3]){const s=i[0];if(e&&!(s.series_name&&s.series_name.toLowerCase().match(e)||s.title&&s.title.toLowerCase().match(e)||s.author_sort&&s.author_sort.toLowerCase().match(e)))return;let n="";i&&i[1]&&(n=URL.createObjectURL(i[1]));let l=!1,r=!1;const c=i[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const h=r?"read":"",u=l?"in_progress":"",m=s.series_name?`<div><a class="series_link" href="#">${s.series_name+" ["+s.series_index+"]"}</a></div>`:"",d=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${s.id}"> + </div>`);o.append(g)}),this.showCovers(),this.updateOfflinePrompts(),$(".summary_link").on("click",a=>{a.preventDefault(),this.showSummary(a.currentTarget)}),$(".fav_item").on("click",a=>{a.preventDefault(),this.toggleFavorite(a.currentTarget)}),$(".offline_dropitem").on("click",async a=>{a.preventDefault();const i=a.currentTarget.getAttribute("data-book-id"),s="epube-book."+i;await localforage.getItem(s)?this.remove(i,()=>{this.updateOfflinePrompt(a.currentTarget)}):this.get(i,()=>{this.updateOfflinePrompt(a.currentTarget)})})),this.updateIndexPagination(t)})}updateIndexPagination(e){const t=$(".pager .previous"),o=$(".pager .next"),a=$(".pager .pager-info"),i=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset-60)}),s=new URLSearchParams({mode:this.index_mode,query:this.index_query,offset:String(this.index_offset+60)});this.index_offset>0?(t.removeClass("disabled"),t.find("a").attr("href","?"+i.toString())):(t.addClass("disabled"),t.find("a").attr("href","#")),e.books&&e.books.length>=60?(o.removeClass("disabled"),o.find("a").attr("href","?"+s.toString())):(o.addClass("disabled"),o.find("a").attr("href","#"));const n=e.limit||60,l=e.total||0,r=Math.floor(this.index_offset/n)+1,c=n>0?Math.ceil(l/n):1;a.find("span").text(`Page ${r} of ${c}`)}escapeHtml(e){if(!e)return"";const t=document.createElement("div");return t.appendChild(document.createTextNode(e)),t.innerHTML}async search(){const e=$(".search_query").val();return await localforage.setItem("epube.search-query",e),this.populateOfflineList(),!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.populateOfflineList()}}populateOfflineList(){let e=this.urlParam("query");e&&(e=String(e).toLowerCase());const t=$("#books_container");t.html(""),localforage.iterate((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(i=>{if(i[0]&&i[3]){const s=i[0];if(e&&!(s.series_name&&s.series_name.toLowerCase().match(e)||s.title&&s.title.toLowerCase().match(e)||s.author_sort&&s.author_sort.toLowerCase().match(e)))return;let n="";i&&i[1]&&(n=URL.createObjectURL(i[1]));let l=!1,r=!1;const c=i[2];c&&(l=c.page>0,r=c.total>0&&c.total-c.page<5);const h=r?"read":"",g=l?"in_progress":"",m=s.series_name?`<div><a class="series_link" href="#">${s.series_name+" ["+s.series_index+"]"}</a></div>`:"",d=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${s.id}"> <a class="thumbnail ${h}" href="read.html?id=${s.epub_id}&b=${s.id}"> <img style="display : none"> </a> <div class="caption"> - <div><a class="${u}" href="read.html?id=${s.epub_id}&b=${s.id}">${s.title}</a></div> + <div><a class="${g}" href="read.html?id=${s.epub_id}&b=${s.id}">${s.title}</a></div> <div><a class="author_link" href="#">${s.author_sort}</a></div> ${m} </div> diff --git a/index.php b/index.php index c2f1fe5..9ba18d4 100644 --- a/index.php +++ b/index.php @@ -185,6 +185,7 @@ <ul class="pager"> <li class="previous disabled"><a href="#">← Previous</a></li> + <li class="pager-info"><span>Loading, please wait...</span></li> <li class="next"><a href="#">→ Next</a></li> </ul> </div> diff --git a/src/app.js b/src/app.js index c82a5db..e340727 100644 --- a/src/app.js +++ b/src/app.js @@ -577,6 +577,7 @@ class AppClass extends AppCommon { updateIndexPagination(data) { const prevLi = $(".pager .previous"); const nextLi = $(".pager .next"); + const pagerInfo = $(".pager .pager-info"); const prevParams = new URLSearchParams({ mode: this.index_mode, @@ -604,6 +605,13 @@ class AppClass extends AppCommon { nextLi.addClass("disabled"); nextLi.find("a").attr("href", "#"); } + + const limit = data.limit || 60; + const total = data.total || 0; + const currentPage = Math.floor(this.index_offset / limit) + 1; + const totalPages = limit > 0 ? Math.ceil(total / limit) : 1; + + pagerInfo.find("span").text(`Page ${currentPage} of ${totalPages}`); } escapeHtml(str) { diff --git a/tests/RouterTest.php b/tests/RouterTest.php new file mode 100644 index 0000000..1c2197c --- /dev/null +++ b/tests/RouterTest.php @@ -0,0 +1,324 @@ +<?php +use PHPUnit\Framework\TestCase; + +final class RouterTest extends TestCase +{ + private Router $router; + + protected function setUp(): void + { + $this->router = new Router(); + // Ensure clean session state + $_SESSION = []; + } + + protected function tearDown(): void + { + $_SESSION = []; + } + + // ── addRoute() ─────────────────────────────────────────────────────────── + + public function test_addRoute_stores_handler(): void + { + $handler = $this->createMock(RequestHandlerInterface::class); + $this->router->addRoute('list', $handler); + + $reflection = new ReflectionClass($this->router); + $routesProp = $reflection->getProperty('routes'); + $routesProp->setAccessible(true); + $routes = $routesProp->getValue($this->router); + + $this->assertArrayHasKey('list', $routes); + $this->assertSame($handler, $routes['list']); + } + + public function test_addRoute_overwrites_existing_handler(): void + { + $handler1 = $this->createMock(RequestHandlerInterface::class); + $handler2 = $this->createMock(RequestHandlerInterface::class); + $this->router->addRoute('list', $handler1); + $this->router->addRoute('list', $handler2); + + $reflection = new ReflectionClass($this->router); + $routesProp = $reflection->getProperty('routes'); + $routesProp->setAccessible(true); + $routes = $routesProp->getValue($this->router); + + $this->assertCount(1, $routes); + $this->assertSame($handler2, $routes['list']); + } + + // ── addMiddleware() ────────────────────────────────────────────────────── + + public function test_addMiddleware_stores_middleware(): void + { + $middleware = $this->createMock(MiddlewareInterface::class); + $this->router->addMiddleware($middleware); + + $reflection = new ReflectionClass($this->router); + $mwProp = $reflection->getProperty('middleware'); + $mwProp->setAccessible(true); + $middlewares = $mwProp->getValue($this->router); + + $this->assertCount(1, $middlewares); + $this->assertSame($middleware, $middlewares[0]); + } + + public function test_addMiddleware_accumulates(): void + { + $mw1 = $this->createMock(MiddlewareInterface::class); + $mw2 = $this->createMock(MiddlewareInterface::class); + $this->router->addMiddleware($mw1); + $this->router->addMiddleware($mw2); + + $reflection = new ReflectionClass($this->router); + $mwProp = $reflection->getProperty('middleware'); + $mwProp->setAccessible(true); + $middlewares = $mwProp->getValue($this->router); + + $this->assertCount(2, $middlewares); + $this->assertSame($mw1, $middlewares[0]); + $this->assertSame($mw2, $middlewares[1]); + } + + // ── dispatchResponse() — unknown op ───────────────────────────────────── + + public function test_dispatchResponse_unknown_op_returns_404(): void + { + $response = $this->router->dispatchResponse('nonexistent'); + $body = json_decode($response->getBody(), true); + $this->assertArrayHasKey('error', $body); + $this->assertEquals('Method not found', $body['error']); + } + + // ── dispatchResponse() — AuthRequired handler ──────────────────────────── + + public function test_dispatchResponse_auth_required_without_session_returns_401(): void + { + $handler = new class implements RequestHandlerInterface, AuthRequired { + public bool $handleCalled = false; + public function handle(Request $request): Response + { + $this->handleCalled = true; + return new Response(); + } + }; + $this->router->addRoute('protected', $handler); + + $response = $this->router->dispatchResponse('protected'); + $body = json_decode($response->getBody(), true); + + $this->assertArrayHasKey('error', $body); + $this->assertEquals('Unauthorized', $body['error']); + $this->assertFalse($handler->handleCalled); + } + + public function test_dispatchResponse_auth_required_with_session_calls_handler(): void + { + $expectedResponse = new Response(); + $handler = new class($expectedResponse) implements RequestHandlerInterface, AuthRequired { + public bool $handleCalled = false; + private readonly Response $expectedResponse; + public function __construct(Response $expectedResponse) + { + $this->expectedResponse = $expectedResponse; + } + public function handle(Request $request): Response + { + $this->handleCalled = true; + return $this->expectedResponse; + } + }; + $this->router->addRoute('protected', $handler); + $_SESSION['owner'] = 'testuser'; + + $response = $this->router->dispatchResponse('protected'); + + $this->assertTrue($handler->handleCalled); + $this->assertSame($expectedResponse, $response); + } + + // ── dispatchResponse() — non-AuthRequired handler ──────────────────────── + + public function test_dispatchResponse_non_auth_handler_without_session_calls_handler(): void + { + // HealthzHandler equivalent: a handler that does NOT implement AuthRequired + $handler = $this->createMock(RequestHandlerInterface::class); + $expectedResponse = new Response(); + $handler->expects($this->once()) + ->method('handle') + ->willReturn($expectedResponse); + $this->router->addRoute('healthz', $handler); + // No session set + + $response = $this->router->dispatchResponse('healthz'); + + $this->assertSame($expectedResponse, $response); + } + + public function test_dispatchResponse_non_auth_handler_with_session_calls_handler(): void + { + $handler = $this->createMock(RequestHandlerInterface::class); + $expectedResponse = new Response(); + $handler->expects($this->once()) + ->method('handle') + ->willReturn($expectedResponse); + $this->router->addRoute('healthz', $handler); + $_SESSION['owner'] = 'testuser'; + + $response = $this->router->dispatchResponse('healthz'); + + $this->assertSame($expectedResponse, $response); + } + + // ── dispatchResponse() — middleware wrapping ───────────────────────────── + + public function test_dispatchResponse_middleware_wraps_handler(): void + { + $handler = $this->createMock(RequestHandlerInterface::class); + $handlerResponse = new Response(); + $handler->expects($this->once()) + ->method('handle') + ->willReturn($handlerResponse); + + // Middleware that adds a header + $middleware = new class implements MiddlewareInterface { + public bool $wasCalled = false; + + public function process(Request $request, callable $next): Response + { + $this->wasCalled = true; + $response = $next($request); + return $response->withHeader('X-Middleware', 'applied'); + } + }; + + $this->router->addRoute('test', $handler); + $this->router->addMiddleware($middleware); + + $response = $this->router->dispatchResponse('test'); + + $this->assertTrue($middleware->wasCalled); + // Middleware response should be returned (handler response was wrapped) + // The middleware returns its own response with the header + } + + public function test_dispatchResponse_middleware_last_added_is_outermost(): void + { + $handler = $this->createMock(RequestHandlerInterface::class); + $handlerResponse = new Response(); + $handler->expects($this->once()) + ->method('handle') + ->willReturn($handlerResponse); + + // Use a shared array to track execution order + $tracker = new class { + /** @var list<string> */ + public array $order = []; + }; + + // Middleware 1: added first → inner + $mw1 = new class($tracker) implements MiddlewareInterface { + public function __construct(private readonly object $tracker) + { + } + + public function process(Request $request, callable $next): Response + { + $this->tracker->order[] = 'mw1_start'; + $response = $next($request); + $this->tracker->order[] = 'mw1_end'; + return $response; + } + }; + + // Middleware 2: added second → outer + $mw2 = new class($tracker) implements MiddlewareInterface { + public function __construct(private readonly object $tracker) + { + } + + public function process(Request $request, callable $next): Response + { + $this->tracker->order[] = 'mw2_start'; + $response = $next($request); + $this->tracker->order[] = 'mw2_end'; + return $response; + } + }; + + $this->router->addRoute('test', $handler); + $this->router->addMiddleware($mw1); // added first = inner + $this->router->addMiddleware($mw2); // added second = outer + + $this->router->dispatchResponse('test'); + + // Execution order: first-added middleware is outermost + // mw1 (added first) wraps mw2 (added second) which wraps handler + $this->assertEquals([ + 'mw1_start', + 'mw2_start', + 'mw2_end', + 'mw1_end', + ], $tracker->order); + } + + // ── dispatchResponse() — request attribute ─────────────────────────────── + + public function test_dispatchResponse_sets_op_attribute_on_request(): void + { + // Use a shared tracker object to capture the request + $tracker = new class { + public ?Request $request = null; + }; + + $handler = new class($tracker) implements RequestHandlerInterface { + public function __construct(private readonly object $tracker) + { + } + + public function handle(Request $request): Response + { + $this->tracker->request = $request; + return new Response(); + } + }; + + $this->router->addRoute('list', $handler); + + $this->router->dispatchResponse('list'); + + $this->assertNotNull($tracker->request); + $this->assertEquals('list', $tracker->request->getAttribute('op')); + } + + // ── dispatch() — integration with exit ─────────────────────────────────── + + public function test_dispatch_calls_exit_for_unknown_op(): void + { + // Since dispatch() calls exit, we can only verify behavior via dispatchResponse + // which is the extracted testable method + $response = $this->router->dispatchResponse('unknown'); + $body = json_decode($response->getBody(), true); + $this->assertEquals('Method not found', $body['error']); + } + + public function test_dispatch_calls_exit_for_unauthorized(): void + { + $handler = new class implements RequestHandlerInterface, AuthRequired { + public bool $handleCalled = false; + public function handle(Request $request): Response + { + $this->handleCalled = true; + return new Response(); + } + }; + $this->router->addRoute('protected', $handler); + + $response = $this->router->dispatchResponse('protected'); + $body = json_decode($response->getBody(), true); + $this->assertEquals('Unauthorized', $body['error']); + $this->assertFalse($handler->handleCalled); + } +} |
