diff options
| author | fox <fox@fakecake.org> | 2026-06-16 09:10:30 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-06-16 09:10:30 +0300 |
| commit | 50487d21f76da26cf59618fd312f66a62f7eae62 (patch) | |
| tree | d84ed79c203f53fa33f0af39c293f58a6a2fcda8 | |
| parent | 789758a094d4885432f165c0c8a419adeb55906c (diff) | |
| parent | 09735053c351ea046d237b5746aee366bd5b9b4f (diff) | |
| download | the-epube-50487d21f76da26cf59618fd312f66a62f7eae62.tar.gz the-epube-50487d21f76da26cf59618fd312f66a62f7eae62.tar.xz | |
Merge branch 'dev' into 'master'
add another type for booklist See merge request git/the-epube!57
| -rw-r--r-- | .eslintrc.js | 10 | ||||
| -rw-r--r-- | backend.php | 4 | ||||
| -rw-r--r-- | build.js | 2 | ||||
| -rw-r--r-- | classes/CsrfMiddleware.php | 2 | ||||
| -rw-r--r-- | phpstan.neon | 2 | ||||
| -rw-r--r-- | src/app.js | 264 | ||||
| -rw-r--r-- | src/csrf.js | 29 | ||||
| -rw-r--r-- | src/http.d.ts | 32 | ||||
| -rw-r--r-- | src/http.js | 150 | ||||
| -rw-r--r-- | src/reader.js | 143 | ||||
| -rw-r--r-- | tests_integration/ListTest.php | 146 |
11 files changed, 536 insertions, 248 deletions
diff --git a/.eslintrc.js b/.eslintrc.js index 8bf9969..b6df689 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,8 +12,16 @@ module.exports = { }, "globals": { "BUILD_CACHE_VERSION": "readonly", - "BUILD_VERSION": "readonly", + "BUILD_VERSION": "readonly", "BUILD_MANIFEST_ASSETS": "readonly", + "HttpError": "readonly", + "EpubeApp": "readonly", + "$": "readonly", + "localforage": "readonly", + "Http": "readonly", + "ePub": "readonly", + "Cookie": "readonly", + "AppCommon": "readonly", }, "rules": { "accessor-pairs": "error", diff --git a/backend.php b/backend.php index 028f4d1..07405de 100644 --- a/backend.php +++ b/backend.php @@ -7,7 +7,9 @@ define('STATIC_EXPIRES', 86400*14); define('PAGE_RESET_PROGRESS', -1); - $op = $_REQUEST["op"] ?? ""; + $request = new Request(); + + $op = $request->getString('op'); $router = new Router(); $router->addMiddleware(new CsrfMiddleware()); diff --git a/build.js b/build.js index 4c3b0da..5155dbe 100644 --- a/build.js +++ b/build.js @@ -41,7 +41,7 @@ const LESS_FILES = [ ] const JS_FILES = [ - 'src/csrf.js', + 'src/http.js', 'src/app.js', 'src/reader.js' ]; diff --git a/classes/CsrfMiddleware.php b/classes/CsrfMiddleware.php index c9374b0..5edf4e4 100644 --- a/classes/CsrfMiddleware.php +++ b/classes/CsrfMiddleware.php @@ -15,7 +15,7 @@ class CsrfMiddleware implements MiddlewareInterface $op = $request->getString('op'); - $csrfToken = $request->getString('csrf_token', ''); + $csrfToken = $request->fromBody()->getString('csrf_token', ''); if (!in_array($op, $this->csrfIgnore) && !validate_csrf($csrfToken)) { $response = (new Response()) diff --git a/phpstan.neon b/phpstan.neon index 7542412..77dac2f 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -15,5 +15,7 @@ parameters: - node_modules/* - vendor/**/* - lib/**/* + - tests/* + - tests_integration/* paths: - . diff --git a/src/app.js b/src/app.js index 82a0013..c661725 100644 --- a/src/app.js +++ b/src/app.js @@ -2,8 +2,6 @@ 'use strict'; -/* global localforage, EpubeApp, $, setupCsrfPrefilter */ - class Cookie { static set(name, value, lifetime) { const d = new Date(); @@ -153,18 +151,22 @@ class AppClass extends AppCommon { // Auth check: call backend with a minimal request; 401 means unauthorized try { - const authParams = new URLSearchParams({op: "list", limit: "1"}); - await $.get("backend.php?" + authParams.toString()); + const checkParams = new URLSearchParams({op: "list", limit: "1"}); + await Http.get("backend.php?" + checkParams.toString()); // If we get here without error, we're authenticated } catch (e) { + const err = /** @type {HttpError} */(e); // 401 Unauthorized — redirect to login - window.location.href = "login.php"; - return; + if (err.status === 401) { + window.location.href = "login.php"; + return; + } + throw e; } this.csrf_token = Cookie.get('epube_csrf_token'); - setupCsrfPrefilter(this.csrf_token); + Http.setCsrfToken(this.csrf_token); if (typeof EpubeApp != "undefined") { $(".navbar").hide(); @@ -221,10 +223,13 @@ class AppClass extends AppCommon { } - logout() { - $.post("backend.php", {op: "logout"}).then(() => { - window.location.reload(); - }); + async logout() { + try { + await Http.post("backend.php", {op: "logout"}); + } catch (e) { + console.warn('logout request failed', e); + } + window.location.reload(); } async showSummary(elem) { @@ -232,11 +237,11 @@ class AppClass extends AppCommon { if (this.isOnline()) { - /** @type{BookList} */ - const reply = await $.post("backend.php", {op: 'list', ids: bookId}); + /** @type{HttpResponse} */ + const reply = await Http.post("backend.php", {op: 'list', ids: bookId}); /** @type{BookInfo} */ - const data = reply['books'][0]; + const data = reply.data['books'][0]; const comment = data.comment ? data.comment : 'No description available'; @@ -281,54 +286,28 @@ class AppClass extends AppCommon { .attr('data-is-fav', is_fav ? 1 : 0); } - toggleFavorite(elem) { + async toggleFavorite(elem) { const bookId = elem.getAttribute("data-book-id"); if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) { - $.post("backend.php", {op: "togglefav", id: bookId}, (data) => { - if (data) { - this.updateFavoritePrompt(elem, data.status == "1"); + try { + const resp = await Http.post("backend.php", {op: "togglefav", id: bookId}); + if (resp.data) { + this.updateFavoritePrompt(elem, resp.data.status == "1"); - if (this.index_mode == "favorites" && data.status == 0) { + if (this.index_mode == "favorites" && resp.data.status == 0) { $("#cell-" + bookId).remove(); } } - }); + } catch (e) { + console.warn('toggleFavorite failed', e); + } } return false; } - /* async refreshCache(force) { - if ('serviceWorker' in navigator) { - const cachedVersion = await localforage.getItem("epube.cache-version"); - - console.log('cached version', cachedVersion, 'current version', this.version); - - if (force || cachedVersion != this.version) { - console.log('cache needs update, reloading...'); - - // Show progress if SW is already controlling the page - if (navigator.serviceWorker.controller) { - $(".dl-progress") - .show() - .addClass("alert-info") - .html("Updating cache..."); - } - - await localforage.setItem("epube.cache-version", this.version); - - // Reload — the SW will precache new assets on install - // and serve from cache on the next load - window.location.reload(); - } else { - // Version matches — save it so we don't keep reloading - await localforage.setItem("epube.cache-version", this.version); - } - } - } */ - updateOfflinePrompts() { const elems = $(".offline_dropitem"); @@ -385,78 +364,60 @@ class AppClass extends AppCommon { this.populateOfflineList(); } - get(bookId, callback) { + async get(bookId, callback) { console.log("offline cache: " + bookId); - $.post("backend.php", {op: "list", ids: bookId}, (/** @type{BookList} */ reply) => { - - /** @type{BookInfo} */ - const data = reply['books'][0]; - - if (data) { - const cacheId = 'epube-book.' + bookId; - - localforage.setItem(cacheId, data).then((data) => { - - console.log(cacheId + ' got data'); + /** @type {HttpResponse} */ + const reply = await Http.post("backend.php", {op: "list", ids: bookId}); - const promises = []; + /** @type{BookInfo} */ + const data = reply.data['books'][0]; - promises.push(fetch('backend.php?op=download&id=' + data.epub_id, {credentials: 'same-origin'}).then(function(resp) { - if (resp.status == 200) { - console.log(cacheId + ' got book'); + if (data) { + const cacheId = 'epube-book.' + bookId; - localforage.setItem(cacheId + '.book', resp.blob()); - } - })); - - promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) { - if (resp.status == 200) { - console.log(cacheId + ' got pagination'); - - resp.text().then(function(text) { - localforage.setItem(cacheId + '.locations', JSON.parse(text)); - }); - } - })); + await localforage.setItem(cacheId, data); + console.log(cacheId + ' got data'); - promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) { - if (resp.status == 200) { - console.log(cacheId + ' got lastread'); - resp.text().then(function(text) { - localforage.setItem(cacheId + '.lastread', JSON.parse(text)); - }); - } - })); - - if (data.has_cover) { - promises.push(fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) { - if (resp.status == 200) { - console.log(cacheId + ' got cover'); - localforage.setItem(cacheId + '.cover', resp.blob()); - } - })); - } + const promises = []; - Promise.all(promises).then(() => { - console.log('download done, running callback', callback); + promises.push(Http.blob('backend.php?op=download&id=' + data.epub_id).then((resp) => { + console.log(cacheId + ' got book'); + return localforage.setItem(cacheId + '.book', resp.blob); + }).catch((e) => console.warn('failed to download book', e))); + + promises.push(Http.text("backend.php?op=getpagination&id=" + data.epub_id).then((resp) => { + console.log(cacheId + ' got pagination'); + return localforage.setItem(cacheId + '.locations', JSON.parse(resp.text)); + }).catch((e) => console.warn('failed to download pagination', e))); + + promises.push(Http.text("backend.php?op=getlastread&id=" + data.epub_id).then((resp) => { + console.log(cacheId + ' got lastread'); + return localforage.setItem(cacheId + '.lastread', JSON.parse(resp.text)); + }).catch((e) => console.warn('failed to download lastread', e))); + + if (data.has_cover) { + promises.push(Http.blob("backend.php?op=cover&id=" + bookId).then((resp) => { + console.log(cacheId + ' got cover'); + return localforage.setItem(cacheId + '.cover', resp.blob); + }).catch((e) => console.warn('failed to download cover', e))); + } - callback(); + await Promise.all(promises); + console.log('download done, running callback', callback); - $(".dl-progress") - .show() - .html("Finished downloading <b>" + data.title + "</b>"); + callback(); - window.clearTimeout(this._dl_progress_timeout); + $(".dl-progress") + .show() + .html("Finished downloading <b>" + data.title + "</b>"); - this._dl_progress_timeout = window.setTimeout(function() { - $(".dl-progress").fadeOut(); - }, 5*1000); - }) + window.clearTimeout(this._dl_progress_timeout); - }); - } - }); + this._dl_progress_timeout = window.setTimeout(() => { + $(".dl-progress").fadeOut(); + }, 5*1000); + } } getAll() { @@ -514,7 +475,7 @@ class AppClass extends AppCommon { } } - populateList() { + async populateList() { const params = new URLSearchParams({ op: "list", mode: this.index_mode, @@ -523,49 +484,56 @@ class AppClass extends AppCommon { limit: String(60), }); - $.get("backend.php?" + params.toString()).done((data) => { - const books = $("#books_container"); - books.html(""); - - if (data.books && data.books.length > 0) { - data.books.forEach((book) => { - const download_html = book.download_formats - .map((fmt) => { - const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary"; - return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`; - }) - .join(""); - - const menuItems = [ - `<li><a href="#" class="summary_link" data-book-id="${book.id}">Summary</a></li>`, - `<li><a href="#" class="fav_item" data-is-fav="${book.is_fav ? "1" : "0"}" - data-book-id="${book.id}">${book.is_fav ? "Remove from favorites" : "Add to favorites"}</a></li>`, - ]; - - if (book.epub_id) { - menuItems.push(`<li><a href="#" data-book-id="${book.id}" class="offline_dropitem"></a></li>`); - menuItems.push('<li class="divider"></li>'); - } + /** @type {HttpResponse} */ + let resp; + try { + resp = await Http.get("backend.php?" + params.toString()); + } catch (e) { + const err = /** @type {HttpError} */(e); + if (err.status === 401) { + window.location.href = "login.php"; + } + return; + } + + const data = resp.data; + const books = $("#books_container"); + books.html(""); - menuItems.push(download_html); + if (data) { + data.books.forEach((book) => { + const download_html = book.download_formats + .map((fmt) => { + const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary"; + return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`; + }) + .join(""); - const cell = this.renderBookCell(book, { - menuItems: menuItems, - }); + const menuItems = [ + `<li><a href="#" class="summary_link" data-book-id="${book.id}">Summary</a></li>`, + `<li><a href="#" class="fav_item" data-is-fav="${book.is_fav ? "1" : "0"}" + data-book-id="${book.id}">${book.is_fav ? "Remove from favorites" : "Add to favorites"}</a></li>`, + ]; - books.append(cell); + if (book.epub_id) { + menuItems.push(`<li><a href="#" data-book-id="${book.id}" class="offline_dropitem"></a></li>`); + menuItems.push('<li class="divider"></li>'); + } + + menuItems.push(download_html); + + const cell = this.renderBookCell(book, { + menuItems: menuItems, }); - this.showCovers(); - this.updateOfflinePrompts(); - } + books.append(cell); + }); - this.updateIndexPagination(data); - }).fail((xhr) => { - if (xhr.status === 401) { - window.location.href = "login.php"; - } - }); + this.showCovers(); + this.updateOfflinePrompts(); + } + + this.updateIndexPagination(data); } updateIndexPagination(data) { @@ -625,7 +593,7 @@ class AppClass extends AppCommon { * @returns {JQuery<HTMLElement>} The created cell element. */ renderBookCell(book, opts) { - console.log('renderBookCell', book, opts); + //console.log('renderBookCell', book, opts); const cellThumbClass = book.is_read ? "read" : ""; const cellTitleClass = book.in_progress ? "in_progress" : ""; diff --git a/src/csrf.js b/src/csrf.js deleted file mode 100644 index fd35d29..0000000 --- a/src/csrf.js +++ /dev/null @@ -1,29 +0,0 @@ -// @ts-check - -'use strict'; - -/* global $ */ - -/** - * @param {string} token - */ -/* eslint-disable-next-line no-unused-vars */ -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/http.d.ts b/src/http.d.ts new file mode 100644 index 0000000..451b8a2 --- /dev/null +++ b/src/http.d.ts @@ -0,0 +1,32 @@ +// @ts-check + +declare class HttpError extends Error { + status?: number; + responseText?: string; +} + +declare interface Http { + static setCsrfToken(token: string): void; + static get(url: string): Promise<HttpResponse>; + static post(url: string, body: Record<string, string>): Promise<HttpResponse>; + static blob(url: string): Promise<HttpBlobResponse>; + static text(url: string): Promise<HttpTextResponse>; +} + +declare interface HttpResponse { + data: any; + ok: boolean; + status: number; +} + +declare interface HttpBlobResponse { + blob: Blob; + ok: boolean; + status: number; +} + +declare interface HttpTextResponse { + text: string; + ok: boolean; + status: number; +} diff --git a/src/http.js b/src/http.js new file mode 100644 index 0000000..e66888c --- /dev/null +++ b/src/http.js @@ -0,0 +1,150 @@ +// @ts-check + +'use strict'; + +/** + * @class + * @description Static HTTP client wrapping fetch with CSRF support. + * + * Usage: + * const resp = await Http.get('backend.php?op=list'); + * const data = resp.data; + * + * await Http.post('backend.php', { op: 'storelastread', id: 42 }); + * + * const { blob } = await Http.blob('backend.php?op=download&id=42'); + */ +// eslint-disable-next-line no-unused-vars +class Http { + /** @private @type {string} */ + static _csrfToken = ''; + + /** + * Set the CSRF token for subsequent requests. + * @param {string} token + */ + static setCsrfToken(token) { + Http._csrfToken = token; + } + + /** + * Append query parameters to a URL string. + * @private + * @param {string} url + * @param {Record<string, string> | null | undefined} params + * @returns {string} + */ + static _appendParams(url, params) { + if (!params || Object.keys(params).length === 0) return url; + const separator = url.includes('?') ? '&' : '?'; + const query = new URLSearchParams(params).toString(); + return `${url}${separator}${query}`; + } + + /** + * Throw a structured error for failed HTTP responses. + * @private + * @param {Response} resp + * @returns {never} + */ + static _throwHttpError(resp) { + /** @type {HttpError} */ + const err = new Error(`HTTP ${resp.status}: ${resp.statusText}`); + err.status = resp.status; + err.responseText = ''; + // Read error body asynchronously — don't block the throw + resp.text().then((t) => { err.responseText = t; }).catch(() => { + /* ignore */ + }); + throw err; + } + + /** + * Perform a GET request. Returns parsed JSON. + * @param {string} url + * @param {Record<string, string> | null} [params] - optional query parameters + * @returns {Promise<HttpResponse>} + */ + static async get(url, params) { + const urlWithParams = Http._appendParams(url, params); + const resp = await fetch(urlWithParams, { + method: 'GET', + credentials: 'same-origin', + }); + + if (!resp.ok) { + Http._throwHttpError(resp); + } + + const data = await resp.json(); + return { data, ok: true, status: resp.status }; + } + + /** + * Perform a POST request with form-encoded body. Returns parsed JSON. + * @param {string} url + * @param {Record<string, string>} body + * @returns {Promise<HttpResponse>} + */ + static async post(url, body) { + const params = new URLSearchParams(body); + if (Http._csrfToken) { + params.append('csrf_token', Http._csrfToken); + } + + const resp = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + body: params, // passing URLSearchParams here gives us automatic application/x-www-form-urlencoded content type + }); + + if (!resp.ok) { + Http._throwHttpError(resp); + } + + const data = await resp.json(); + return { data, ok: true, status: resp.status }; + } + + /** + * Perform a GET request and return the body as a Blob. + * @param {string} url + * @param {Record<string, string> | null} [params] - optional query parameters + * @returns {Promise<HttpBlobResponse>} + */ + static async blob(url, params) { + const urlWithParams = Http._appendParams(url, params); + const resp = await fetch(urlWithParams, { + method: 'GET', + credentials: 'same-origin', + }); + + if (!resp.ok) { + Http._throwHttpError(resp); + } + + const blob = await resp.blob(); + return { blob, ok: true, status: resp.status }; + } + + /** + * Perform a GET request and return the body as plain text. + * @param {string} url + * @param {Record<string, string> | null} [params] - optional query parameters + * @returns {Promise<HttpTextResponse>} + */ + static async text(url, params) { + const urlWithParams = Http._appendParams(url, params); + const resp = await fetch(urlWithParams, { + method: 'GET', + credentials: 'same-origin', + }); + + if (!resp.ok) { + Http._throwHttpError(resp); + } + + const text = await resp.text(); + return { text, ok: true, status: resp.status }; + } +} diff --git a/src/reader.js b/src/reader.js index 0c61a0c..1df71b5 100644 --- a/src/reader.js +++ b/src/reader.js @@ -2,8 +2,6 @@ 'use strict'; -/* global localforage, EpubeApp, ePub, Cookie, AppCommon, $, setupCsrfPrefilter */ - const DEFAULT_FONT_SIZE = 16; const DEFAULT_FONT_FAMILY = "Arial"; const DEFAULT_LINE_HEIGHT = 140; @@ -116,8 +114,7 @@ class ReaderClass extends AppCommon { this.csrf_token = Cookie.get('epube_csrf_token'); - /** global setupCsrfPrefilter */ - setupCsrfPrefilter(this.csrf_token); + Http.setCsrfToken(this.csrf_token); $(document).on("keyup", (e) => { this.hotkeyHandler(e); @@ -177,7 +174,7 @@ class ReaderClass extends AppCommon { /** * @param {boolean} offline */ - onOfflineModeChanged(offline) { + async onOfflineModeChanged(offline) { console.log('onOfflineModeChanged', offline); if (!offline && this.book) { @@ -186,15 +183,15 @@ class ReaderClass extends AppCommon { const currentCfi = this.book.rendition.currentLocation().start.cfi; const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf - $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, - cfi: currentCfi, timestamp: new Date().getTime() }, function() { - // - }) - .fail(function(e) { - if (e && e.status == 401) { - window.location.href = "index.html"; - } - }); + try { + await Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPage), + cfi: currentCfi, timestamp: String(new Date().getTime()) }); + } catch (e) { + const err = /** @type {HttpError} */(e); + if (err.status == 401) { + window.location.href = "index.html"; + } + } } } @@ -222,17 +219,17 @@ class ReaderClass extends AppCommon { console.log('requesting bookinfo for book', bookId) try { - /** @type{BookList} */ - const resp = await $.post("backend.php", {op: "list", ids: bookId }); + /** @type{HttpResponse} */ + const resp = await Http.post("backend.php", {op: "list", ids: bookId }); /** @type{BookInfo} */ - const info = resp['books'][0]; + const info = resp.data['books'][0]; if (info.has_cover) { - const cover = await fetch("backend.php?op=cover&id=" + bookId); + /** @type {HttpBlobResponse} */ + const cover = await Http.blob("backend.php", {op: "cover", id: bookId}); - if (cover.ok) - await localforage.setItem(this.cacheId('cover'), cover.blob()); + await localforage.setItem(this.cacheId('cover'), cover.blob); } await localforage.setItem(this.cacheId(), info); @@ -241,7 +238,7 @@ class ReaderClass extends AppCommon { } catch (e) { // @type {NetworkError} - const err = /** @type {*} */(e); + const err = /** @type {HttpError} */(e); console.error(err); @@ -259,18 +256,14 @@ class ReaderClass extends AppCommon { $(".loading-message").html("Downloading book…"); - const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id")); + /** @type {HttpBlobResponse} */ + const book_resp = await Http.blob("backend.php", {op: "download", id: this.urlParam("id")}); - if (book_resp.ok) { - book_data = await book_resp.blob(); + if (book_resp.blob) { + book_data = book_resp.blob; - if (book_data) { - await localforage.setItem(this.cacheId('book'), book_data); - console.log('saved local data for book'); - } else { - $(".loading-message").html("Unable to get book blob data."); - return; - } + await localforage.setItem(this.cacheId('book'), book_data); + console.log('saved local data for book'); } else { $(".loading-message").html(`Unable to download book: ${book_resp.status}`); @@ -406,14 +399,14 @@ class ReaderClass extends AppCommon { $(".loading-message").html("Downloading locations…"); - const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id")); - - if (resp.ok) { + try { + /** @type {HttpTextResponse} */ + const resp = await Http.text("backend.php", {op: "getpagination", id: this.urlParam("id")}); console.log("got locations from server"); // if this doesn't load, we'll generate locations and save them try { - locations = await resp.json(); + locations = JSON.parse(resp.text); } catch (e) { console.warn(e); } @@ -431,6 +424,8 @@ class ReaderClass extends AppCommon { console.warn(e); } } + } catch (e) { + console.warn('failed to fetch locations', e); } } @@ -450,8 +445,12 @@ class ReaderClass extends AppCommon { } }); - $.post("backend.php", { op: "storepagination", id: this.urlParam("id"), - payload: JSON.stringify(locations), total: 100}); + try { + await Http.post("backend.php", { op: "storepagination", id: this.urlParam("id"), + payload: JSON.stringify(locations), total: "100"}); + } catch (e) { + console.warn('failed to store pagination', e); + } await localforage.setItem(this.cacheId("locations"), locations); } @@ -642,12 +641,17 @@ class ReaderClass extends AppCommon { this.resetLocations(); }); - if (navigator.onLine) - $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => { + if (navigator.onLine) { + try { + /** @type {HttpResponse} */ + const lrResp = await Http.get("backend.php", { op: "getlastread", id: this.urlParam("id") }); $(".lastread_input") - .val(data.page + '%') - .attr('title', `[remote] ${data.cfi}`); - }); + .val(lrResp.data.page + '%') + .attr('title', `[remote] ${lrResp.data.cfi}`); + } catch (e) { + console.warn('failed to get remote lastread', e); + } + } $(".font_family") .off("change") @@ -1289,8 +1293,9 @@ class ReaderClass extends AppCommon { const lastread_timestamp = new Date().getTime(); if (this.isOnline()) { - const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp }); - $(".lastread_input").val(data.page + '%'); + /** @type {HttpResponse} */ + const data = await Http.post("backend.php", { op: "storelastread", page: String(total), cfi: lastCfi, id: this.urlParam("id"), timestamp: String(lastread_timestamp) }); + $(".lastread_input").val(data.data.page + '%'); } await localforage.setItem(this.cacheId("lastread"), @@ -1312,13 +1317,13 @@ class ReaderClass extends AppCommon { {cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp}); if (this.isOnline()) { - $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, - cfi: currentCfi, timestamp: lastread_timestamp }, () => { - window.location.href = this.urlParam("rt") ? "index.html?mode=" + this.urlParam("rt") : "index.html"; - }) - .fail(() => { - window.location.href = "index.html"; - }); + try { + await Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPage), + cfi: currentCfi, timestamp: String(lastread_timestamp) }); + } catch (e) { + console.warn('storelastread failed', e); + } + window.location.href = this.urlParam("rt") ? "index.html?mode=" + this.urlParam("rt") : "index.html"; } else { window.location.href = "index.html"; } @@ -1355,18 +1360,19 @@ class ReaderClass extends AppCommon { $("#dict-modal").modal('show'); try { - const data = await $.post("backend.php", {op: 'define', word: word}); + /** @type {HttpResponse} */ + const data = await Http.post("backend.php", {op: 'define', word: word}); - if (data) { + if (data.data) { - $(".dict_result").html(data.result.join("<br/>")); + $(".dict_result").html(data.data.result.join("<br/>")); $(".dict_query").val(word); if (callback) callback(); } } catch (e) { // @type {NetworkError} - const err = /** @type {*} */(e); + const err = /** @type {HttpError} */(e); console.error(err); @@ -1509,8 +1515,10 @@ class ReaderClass extends AppCommon { console.log("updating remote lastread", currentCfi); this.last_stored_cfi = currentCfi; - $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct, - cfi: currentCfi, timestamp: lastread_timestamp }); + Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPct), + cfi: currentCfi, timestamp: String(lastread_timestamp) }).catch((e) => { + console.warn('storelastread failed', e); + }); } } } @@ -1523,7 +1531,7 @@ class ReaderClass extends AppCommon { const lastread_timestamp = new Date().getTime(); if (this.isOnline()) - await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp }); + await Http.post("backend.php", { op: "storelastread", page: String(PAGE_RESET_PROGRESS), cfi: "", id: this.urlParam("id"), timestamp: String(lastread_timestamp) }); await localforage.setItem(this.cacheId("lastread"), {cfi: "", page: 0, total: total, timestamp: lastread_timestamp}); @@ -1541,10 +1549,10 @@ class ReaderClass extends AppCommon { await localforage.removeItem(this.cacheId("lastread")); await localforage.removeItem(this.cacheId("locations")); - await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() }) + await Http.post("backend.php", { op: "storelastread", page: String(PAGE_RESET_PROGRESS), cfi: "", id: this.urlParam("id"), timestamp: String(new Date().getTime()) }) // this might return 404 and its okay - await $.post("backend.php", + await Http.post("backend.php", { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e)) window.location.reload(); @@ -1571,18 +1579,19 @@ class ReaderClass extends AppCommon { if (this.isOnline()) { try { - const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }); + /** @type {HttpResponse} */ + const lr_remote = await Http.get("backend.php", { op: "getlastread", id: this.urlParam("id") }); - console.log('got remote lastread', lr_remote); + console.log('got remote lastread', lr_remote.data); - if (lr_remote) { - if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) { - console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`); + if (lr_remote.data) { + if (lr_remote.data.cfi && lr_local.cfi != lr_remote.data.cfi && (lr_remote.data.page >= (lr_local.page || 0))) { + console.log(`using remote lastread cfi ${lr_remote.data.cfi}: cfi is different and remote pct ${lr_remote.data.page}% is further than local pct ${lr_local.page}%`); await localforage.setItem(this.cacheId("lastread"), - {cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp}); + {cfi: lr_remote.data.cfi, page: lr_remote.data.page, total: lr_remote.data.total, timestamp: lr_remote.data.timestamp}); - location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi); + location_found = await this.moveToCfiVerify(rendition, lr_remote.data.cfi); } } } catch (e) { diff --git a/tests_integration/ListTest.php b/tests_integration/ListTest.php index 267a4b2..0dde8b8 100644 --- a/tests_integration/ListTest.php +++ b/tests_integration/ListTest.php @@ -233,4 +233,150 @@ final class ListTest extends TestCase $this->assertEquals(0, $body['total']); $this->assertCount(0, $body['books']); } + + // ── Selecting books by ids ────────────────────────────────────────────── + + /** + * Fetch book IDs from a full list so we can reference real IDs in subsequent tests. + */ + private function getAllBookIds(): array + { + $this->loginAs('test', 'test'); + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'limit' => 100, + ]); + + $this->assertEquals(200, $status); + return array_map(fn($b) => (int) $b['id'], $body['books']); + } + + public function test_list_by_ids_single(): void + { + $ids = $this->getAllBookIds(); + $this->assertGreaterThan(0, count($ids), 'Test data should contain at least one book'); + + $singleId = $ids[0]; + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => (string) $singleId, + ]); + + $this->assertEquals(200, $status); + $this->assertEquals(1, $body['total']); + $this->assertCount(1, $body['books']); + $this->assertEquals($singleId, (int) $body['books'][0]['id']); + } + + public function test_list_by_ids_multiple(): void + { + $ids = $this->getAllBookIds(); + $this->assertGreaterThanOrEqual(3, count($ids), 'Test data should contain at least 3 books'); + + $selectedIds = [$ids[0], $ids[1], $ids[2]]; + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => implode(',', $selectedIds), + ]); + + $this->assertEquals(200, $status); + $expectedTotal = count($selectedIds); + $this->assertEquals($expectedTotal, $body['total']); + $this->assertCount($expectedTotal, $body['books']); + + $foundIds = array_map(fn($b) => (int) $b['id'], $body['books']); + sort($foundIds); + $sortedSelected = $selectedIds; + sort($sortedSelected); + $this->assertEquals($sortedSelected, $foundIds); + } + + public function test_list_by_ids_nonexistent(): void + { + $this->loginAs('test', 'test'); + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => '999999', + ]); + + $this->assertEquals(200, $status); + $this->assertEquals(0, $body['total']); + $this->assertCount(0, $body['books']); + } + + public function test_list_by_ids_mixed_existing_and_nonexistent(): void + { + $ids = $this->getAllBookIds(); + $this->assertGreaterThan(0, count($ids)); + + $selectedIds = [$ids[0], 999999, $ids[1]]; + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => implode(',', $selectedIds), + ]); + + $this->assertEquals(200, $status); + $this->assertEquals(2, $body['total']); + $this->assertCount(2, $body['books']); + + $foundIds = array_map(fn($b) => (int) $b['id'], $body['books']); + $this->assertContains((int) $ids[0], $foundIds); + $this->assertContains((int) $ids[1], $foundIds); + } + + public function test_list_by_ids_overrides_query(): void + { + $ids = $this->getAllBookIds(); + $this->assertGreaterThan(0, count($ids)); + + // Use a query that would match many books, but restrict to a single id + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => (string) $ids[0], + 'query' => 'the', + ]); + + $this->assertEquals(200, $status); + $this->assertEquals(1, $body['total']); + $this->assertCount(1, $body['books']); + $foundIds = array_map(fn($b) => (int) $b['id'], $body['books']); + $this->assertContains((int) $ids[0], $foundIds); + } + + public function test_list_by_ids_empty_string_returns_all(): void + { + $this->loginAs('test', 'test'); + + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => '', + ]); + + $this->assertEquals(200, $status); + $this->assertGreaterThan(0, $body['total']); + $this->assertIsArray($body['books']); + } + + public function test_list_by_ids_with_invalid_values(): void + { + $ids = $this->getAllBookIds(); + $this->assertGreaterThan(0, count($ids)); + + // Mix of valid and invalid (non-numeric) values; intval should filter them out + [$status, $body] = $this->authenticatedPost($this->apiUrl, [ + 'op' => 'list', + 'ids' => (string) $ids[0] . ',abc,0,', + ]); + + $this->assertEquals(200, $status); + $this->assertEquals(1, $body['total']); + $this->assertCount(1, $body['books']); + $foundIds = array_map(fn($b) => (int) $b['id'], $body['books']); + $this->assertContains((int) $ids[0], $foundIds); + } } |
