From 8e7043199069569727cfc7ea2b8b20d65a57a8a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:48:03 -0500 Subject: [PATCH 01/27] Tests: a mock BookOrbit server and a probe script The stand-in the BookOrbit work is tested against: the KOReader sign-in, version and capabilities, catalog, covers, downloads, match-check, progress (plugin and KOSync), and the main API's key, audiobook manifest, audio files and listening position. Written from BookOrbit's routes and field names at commit e60ab43; none of its code is copied. tools/gzreader/bookorbit-probe.py asks a real server the same questions and prints status codes and field names only. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- tools/gzreader/bookorbit-probe.py | 174 +++++++ tools/gzreader/tests/mock_bookorbit.py | 539 ++++++++++++++++++++ tools/gzreader/tests/mock_bookorbit_test.py | 233 +++++++++ tools/gzreader/tests/run.sh | 4 + 4 files changed, 950 insertions(+) create mode 100644 tools/gzreader/bookorbit-probe.py create mode 100644 tools/gzreader/tests/mock_bookorbit.py create mode 100644 tools/gzreader/tests/mock_bookorbit_test.py diff --git a/tools/gzreader/bookorbit-probe.py b/tools/gzreader/bookorbit-probe.py new file mode 100644 index 000000000..fb31e714a --- /dev/null +++ b/tools/gzreader/bookorbit-probe.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Ask a real BookOrbit server the questions GZreader's BookOrbit support +depends on, and print what came back in a form that is safe to paste into a +pull request: status codes, field names and counts only. It never prints the +address, the user name, the password, the API key, a book's title or any +other value from the library. + + python3 tools/gzreader/bookorbit-probe.py + +It asks for the server's address, the KOReader sync user name and password +(BookOrbit: Settings, KOReader), and optionally an API key (for audiobooks). +Or set BOOKORBIT_URL, BOOKORBIT_KO_USER, BOOKORBIT_KO_PASSWORD and +BOOKORBIT_API_KEY. It only reads books and positions; the one trace it leaves is +a device named "GZreader probe" in BookOrbit's KOReader device list (from the +match check), which can be removed there. +""" +import getpass, hashlib, json, os, ssl, sys, urllib.error, urllib.request + +MOCK_SHAPES = { # what the tests' mock server (tests/mock_bookorbit.py) sends, to compare with + "list item": {"id", "title", "authors", "seriesId", "seriesName", "seriesIndex", "progressPercentage", "lastReadAt", + "readStatus", "formats", "hasCover", "thumbnailUrl", "detailUrl", "addedAt", "updatedAt"}, + "file": {"id", "format", "role", "downloadVariant", "sizeBytes", "sourceSizeBytes", "durationSeconds", "fileHash", + "downloadUrl", "devicePath"}, + "manifest": {"schema", "schemaVersion", "revision", "book", "assets", "chapters", "totalDurationMs"}, + "asset": {"assetId", "fileId", "sequence", "format", "durationMs", "sizeBytes", "etag"}, +} + + +def ask(env, prompt, secret=False, optional=False): + v = os.environ.get(env) + if v: + return v.strip() + if not sys.stdin.isatty(): + return "" if optional else sys.exit("Set %s (not a terminal, so I can't ask)." % env) + v = (getpass.getpass(prompt) if secret else input(prompt)).strip() + if not v and not optional: + sys.exit("Needed: " + prompt.strip(": ")) + return v + + +def call(base, path, headers, method="GET", body=None, want_bytes=0): + data = json.dumps(body).encode() if body is not None else None + h = dict(headers) + if data is not None: + h["Content-Type"] = "application/json" + req = urllib.request.Request(base + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=30, context=ssl.create_default_context()) as r: + code, raw, hdr = r.status, r.read(want_bytes or 4 << 20), r.headers + except urllib.error.HTTPError as e: + code, raw, hdr = e.code, e.read(1 << 16), e.headers + except (urllib.error.URLError, OSError) as e: + return None, None, {}, type(e).__name__ + if want_bytes: + return code, raw, hdr, None + try: + return code, json.loads(raw) if raw else None, hdr, None + except ValueError: + return code, None, hdr, "not JSON" + + +def keys(v): + return sorted(v) if isinstance(v, dict) else type(v).__name__ + + +def line(name, code, note=""): + print("%-44s %s %s" % (name, code if code is not None else "no answer", note)) + + +def compare(name, got): + want = MOCK_SHAPES[name] + got = set(got) + if got >= want: + extra = sorted(got - want) + print(" %s: has every field GZreader's tests use%s" % (name, extra and "; also " + ", ".join(extra) or "")) + else: + print(" %s: MISSING %s" % (name, ", ".join(sorted(want - got)))) + + +def main(): + base = ask("BOOKORBIT_URL", "BookOrbit address (https://...): ").rstrip("/") + if not base.startswith(("http://", "https://")): + sys.exit("The address must start with http:// or https://") + user = ask("BOOKORBIT_KO_USER", "KOReader sync user name: ") + password = ask("BOOKORBIT_KO_PASSWORD", "KOReader sync password (not shown): ", secret=True) + key = ask("BOOKORBIT_API_KEY", "API key for audiobooks (not shown; Enter to skip): ", secret=True, optional=True) + ko = {"x-auth-user": user, "x-auth-key": hashlib.md5(password.encode()).hexdigest()} + A = base + "/api/v1" + print("\nBookOrbit probe (status codes and field names only)\n") + + code, j, _, err = call(A, "/koreader/users/auth", ko) + line("sign-in (koreader/users/auth)", code, err or keys(j)) + if code != 200: + print("\nThe sign-in didn't work, so the rest is skipped. 401: wrong user name or password; 403: sync is switched off" + " for these credentials in BookOrbit.") + return 1 + code, j, _, err = call(A, "/koreader/plugin/version", ko) + line("version", code, err or (isinstance(j, dict) and "server %s; capabilities: %s" % ( + j.get("serverVersion"), ", ".join(j.get("capabilities") or [])) or "")) + + code, j, _, err = call(A, "/koreader/plugin/catalog/root", ko) + line("catalog root", code, err or (isinstance(j, dict) and "sections: " + ", ".join( + str(s.get("section")) for s in j.get("sections") or []) or keys(j))) + for s in ("libraries", "collections", "authors", "series"): + code, j, _, err = call(A, "/koreader/plugin/catalog/sections/" + s, ko) + items = isinstance(j, dict) and j.get("items") or [] + line("section " + s, code, err or "%d entries; entry fields: %s" % (len(items), items and keys(items[0]) or "-")) + + code, j, _, err = call(A, "/koreader/plugin/catalog/books?size=5&sort=recently_added", ko) + items = isinstance(j, dict) and j.get("items") or [] + line("books (first 5)", code, err or "total %s; page fields: %s" % (isinstance(j, dict) and j.get("total"), keys(j))) + file_hash = None + if items: + compare("list item", items[0]) + code, d, _, err = call(A, "/koreader/plugin/catalog/books/%d" % items[0]["id"], ko) + line("book detail", code, err or "") + files = isinstance(d, dict) and d.get("files") or [] + if files: + compare("file", files[0]) + f = files[0] + file_hash = f.get("fileHash") + print(" file: format %s, role %s, variant %s, hash %s" % ( + f.get("format"), f.get("role"), f.get("downloadVariant"), + "32 hex (KOReader's kind)" if isinstance(file_hash, str) and len(file_hash) == 32 else "absent or another kind")) + code, raw, hdr, err = call(base, f["downloadUrl"], ko, want_bytes=4096) + line("download (first 4 KB only)", code, err or "type %s; length header %s" % ( + hdr.get("Content-Type"), "present" if hdr.get("Content-Length") else "absent")) + if items[0].get("thumbnailUrl"): + code, raw, hdr, err = call(base, items[0]["thumbnailUrl"], ko, want_bytes=64) + line("cover", code, err or "type %s; ETag %s" % (hdr.get("Content-Type"), "present" if hdr.get("ETag") else "absent")) + if file_hash: + dev = {"deviceId": "gzreader-probe", "deviceModel": "GZreader probe", "pluginVersion": "0.0.0"} + code, j, _, err = call(A, "/koreader/plugin/match-check", ko, "POST", dict(dev, hashes=[file_hash])) + line("match-check (that book's hash)", code, err or "%s; matched %d" % (keys(j), len(isinstance(j, dict) and j.get("matches") or []))) + code, j, _, err = call(A, "/koreader/syncs/progress/" + file_hash, ko) + line("reading position (KOSync)", code, err or (j and keys(j) or "none stored ({})")) + + if not key: + print("\nNo API key given: audiobooks not checked.") + return 0 + api = {"Authorization": "Bearer " + key} + code, j, _, err = call(A, "/auth/me", api) + line("API key (auth/me)", code, err or (isinstance(j, dict) and "method %s" % j.get("authenticationMethod") or "")) + if code != 200: + return 1 + audio = ["m4b", "mp3", "m4a", "flac", "ogg", "opus"] + query = {"sort": [{"field": "title", "dir": "asc"}], "pagination": {"page": 1, "size": 1}, + "filter": {"type": "group", "join": "AND", "rules": [ + {"type": "rule", "field": "format", "operator": "includesAny", "value": audio + [f.upper() for f in audio]}]}} + code, j, _, err = call(A, "/books/query", api, "POST", query) + items = isinstance(j, dict) and j.get("items") or [] + line("books/query (audiobooks)", code, err or "total %s; page fields: %s; card fields: %s" % ( + isinstance(j, dict) and j.get("total"), keys(j), items and keys(items[0]) or "-")) + if not items: + print(" no audiobook found (none in the library, or the format filter doesn't match): send this line back") + return 0 + bid = items[0].get("id") + code, m, _, err = call(A, "/audiobooks/%s/manifest" % bid, api) + line("audiobook manifest", code, err or "") + if isinstance(m, dict) and m.get("assets"): + compare("manifest", m) + compare("asset", m["assets"][0]) + print(" %d file(s), %d chapter(s), formats: %s" % (len(m["assets"]), len(m.get("chapters") or []), + ", ".join(sorted({str(a.get("format")) for a in m["assets"]})))) + code, raw, hdr, err = call(A, "/audiobooks/%s/assets/%s/content" % (bid, m["assets"][0]["assetId"]), + dict(api, Range="bytes=0-1023"), want_bytes=1024) + line("audio file (first 1 KB, resumable?)", code, err or "Content-Range %s" % ("present" if hdr.get("Content-Range") else "absent")) + code, j, _, err = call(A, "/audiobooks/%s/playback-state" % bid, api) + line("listening position", code, err or (j and keys(j) or "none stored")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gzreader/tests/mock_bookorbit.py b/tools/gzreader/tests/mock_bookorbit.py new file mode 100644 index 000000000..5cfccda38 --- /dev/null +++ b/tools/gzreader/tests/mock_bookorbit.py @@ -0,0 +1,539 @@ +"""Mock BookOrbit server: the routes GZreader's BookOrbit backend uses. + +Shapes and checks follow BookOrbit's source at commit e60ab43 (2026-11-21; +github.com/bookorbit/bookorbit: server/src/modules/koreader, .../audiobook, +packages/types/src/koreader.ts and audiobook.ts). Nothing of BookOrbit's code +is copied: this is a stand-in written from its routes and field names. + +Two sign-ins, as the real server: + * the KOReader API (/api/v1/koreader/...): headers x-auth-user and + x-auth-key (the password, or its MD5 as KOSync clients send); + * the main API (/api/v1/auth/me, /api/v1/audiobooks/...): an API key + ("bok_" + 49 characters) as Authorization: Bearer or X-Api-Key. + + python3 -I mock_bookorbit.py + +Control routes for tests (no sign-in): GET /_mock/state, POST /_mock/set +(a JSON object merged into STATE's switches), POST /_mock/reset. +""" +import hashlib, json, re, sys, time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse, parse_qs, quote + +KO_USER, KO_PASSWORD = "will-kindle", "hunter22" +API_KEY = "bok_" + "a1B2c3D4e5" * 4 + "f6G7h8I9j" # 53 characters +MD5 = re.compile(r"^[0-9a-f]{32}$", re.I) +DEVICE_ID = re.compile(r"^[A-Za-z0-9_-]{1,100}$") +DEVICE_TIME = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$") +ASSET_ID = re.compile(r"^aud_[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I) +UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.I) +ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$") +CAPABILITIES = ["catalogBulkManifest", "catalogDashboardSections", "bookmarkSync", "readAloudDeliveryVariants", + "readAloudDeliverySettings", "catalogListsV2", "catalogPublishedSort", "sidecarState", + "annotationPendingBooks", "catalogBooksQuery"] +SORTS = {"title", "author", "published", "recently_added", "recently_updated", "recently_read", "series"} + +# A tiny valid PNG (1x1) for thumbnails, and the "book files" (their bytes are +# what a download returns; hash = KOReader's partial MD5, which for a file this +# small is the MD5 of its first 1024 bytes at offset 0... the mock just keeps +# the value a test gives it). +PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489" + "0000000d49444154789c6360606060000000050001a5f645400000000049454e44ae426082") + + +def book(i, title, authors, library, series=None, idx=None, fmt="epub", collections=()): + data = ("%s by %s\n" % (title, ", ".join(authors))).encode() * 40 + return {"id": i, "title": title, "authors": authors, "libraryId": library, "seriesName": series, + "seriesId": (900 + sum(map(ord, series)) % 90) if series else None, "seriesIndex": idx, + "format": fmt, "fileId": 5000 + i, "data": data, "hash": hashlib.md5(data).hexdigest(), + "collections": list(collections), "addedAt": "2026-10-%02dT08:00:00.000Z" % (i % 27 + 1), + "updatedAt": "2026-11-%02dT09:30:00.000Z" % (i % 20 + 1)} + + +LIBRARIES = {1: "Fiction", 2: "Non-fiction"} +COLLECTIONS = {11: "Beach reads", 12: "Book club"} +BOOKS = [ + book(101, "The Long Way Round", ["Ada Marsh"], 1, "Waymarks", 1, collections=[11]), + book(102, "The Short Way Back", ["Ada Marsh"], 1, "Waymarks", 2), + book(103, "A Field Guide to Fog", ["Ben Okafor"], 2, collections=[12]), + book(104, "Night Trains", ["Clara Voss", "Ben Okafor"], 1, collections=[11, 12]), + book(105, "Tide Tables", ["Dmitri Hale"], 2, fmt="pdf"), +] +AUDIOBOOK = { + "id": 201, "title": "The Long Way Round", "authors": ["Ada Marsh"], "narrators": ["June Park"], + "assets": [ + {"assetId": "aud_11111111-1111-4111-8111-111111111111", "fileId": 6201, "sequence": 0, "format": "mp3", + "durationMs": 60000, "data": b"ID3" + b"\0" * 4000}, + {"assetId": "aud_22222222-2222-4222-8222-222222222222", "fileId": 6202, "sequence": 1, "format": "mp3", + "durationMs": 45000, "data": b"ID3" + b"\1" * 3000}, + ], +} + + +def fresh(): + return { + "capabilities": list(CAPABILITIES), + "sync_enabled": True, # the KOReader credentials' "sync enabled" switch + "ko_permission": True, # the account's KOReader sync permission + "api_keys_enabled": True, + "api_key_write": True, # False: a read key (PUT answers 403 API_KEY_READ_ONLY) + "offline": False, # every route answers 503 + "progress": {}, # hash -> {percentage, progress, device, device_id, timestamp} + "playback": {}, # book id -> state + "seen": [], # (method, path) of signed-in requests, newest last + "devices": {}, # deviceId -> deviceModel + } + + +STATE = fresh() + + +def manifest_revision(): + h = hashlib.sha256() + for a in AUDIOBOOK["assets"]: + h.update(a["assetId"].encode() + a["data"]) + return h.hexdigest() + + +def pct100(p): + """KOReader sends 0-1; BookOrbit keeps and shows 0-100, to two places.""" + return round(p * 10000) / 100.0 + + +def list_item(b): + p = STATE["progress"].get(b["hash"]) + return {"id": b["id"], "title": b["title"], "authors": b["authors"], "seriesId": b["seriesId"], + "seriesName": b["seriesName"], "seriesIndex": b["seriesIndex"], + "progressPercentage": p and pct100(p["percentage"]), "lastReadAt": p and p["updatedAt"], + "readStatus": p and "reading" or None, "formats": [b["format"]], "hasCover": True, + "thumbnailUrl": "/api/v1/koreader/plugin/catalog/books/%d/thumbnail" % b["id"], + "detailUrl": "/api/v1/koreader/plugin/catalog/books/%d" % b["id"], + "addedAt": b["addedAt"], "updatedAt": b["updatedAt"]} + + +def detail(b): + d = list_item(b) + p = STATE["progress"].get(b["hash"]) + d.update({"subtitle": None, "description": "About %s." % b["title"], "publisher": "Example House", + "publishedDate": "2020-05-01", "publishedYear": 2020, "language": "en", "isbn10": None, "isbn13": None, + "libraryId": b["libraryId"], "libraryName": LIBRARIES[b["libraryId"]], "rating": None, "pageCount": 240, + "collections": [{"id": c, "name": COLLECTIONS[c]} for c in b["collections"]], "genres": [], "tags": [], + "progress": p and {"fileId": b["fileId"], "percentage": pct100(p["percentage"]), + "koreaderProgress": p.get("progress"), "updatedAt": p["updatedAt"]} or None, + "files": [{"id": b["fileId"], "format": b["format"], "role": "content", "downloadVariant": "original", + "sizeBytes": len(b["data"]), "sourceSizeBytes": len(b["data"]), "durationSeconds": None, "fileHash": b["hash"], + "downloadUrl": "/api/v1/koreader/plugin/catalog/files/%d/download" % b["fileId"], + "devicePath": "%s/%s.%s" % (b["authors"][0], b["title"], b["format"])}], + "relatedSections": []}) + return d + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + # ---------------------------------------------------------------- plumbing + def send(self, code, body=None, ctype="application/json", headers=None): + raw = body if isinstance(body, (bytes, bytearray)) else json.dumps(body if body is not None else {}).encode() + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(raw))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(raw) + + def error(self, code, message, error_code=None): + body = {"statusCode": code, "message": message, "path": self.path.split("?")[0], + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()), "requestId": "req-mock"} + if error_code: + body["errorCode"] = error_code + self.send(code, body) + + def body(self): + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n) if n else b"" + try: + return json.loads(raw) if raw else {} + except ValueError: + return None + + def ko_user(self): + """The KOReader guard: x-auth-user + x-auth-key (the password or its MD5).""" + user, key = self.headers.get("x-auth-user"), self.headers.get("x-auth-key") + if not user or not key: + return self.error(401, "Missing KOReader credentials") + if user != KO_USER: + return self.error(401, "Invalid credentials") + if not STATE["sync_enabled"]: + return self.error(403, "Sync is disabled") + want = hashlib.md5(KO_PASSWORD.encode()).hexdigest() + got = key.lower() if MD5.match(key) else hashlib.md5(key.encode()).hexdigest() + if got != want: + return self.error(401, "Invalid credentials") + if not STATE["ko_permission"]: + return self.error(401, "KOReader sync permission revoked") + return user + + def api_key(self, write=False): + """The main API's key: Bearer or X-Api-Key, never the query string.""" + auth = self.headers.get("Authorization") + m = re.match(r"^Bearer\s+(\S+)\s*$", auth or "", re.I) + bearer = m and m.group(1) or None + header = (self.headers.get("X-Api-Key") or "").strip() or None + if header and auth is not None and bearer != header: + return self.error(401, "Conflicting credentials") + key = header or (bearer if bearer and bearer.startswith("bok_") else None) + if not key: + return self.error(401, "Unauthorized") # (a Bearer that isn't a key is taken for a session token) + if len(key) != len(API_KEY): + return self.error(401, "Invalid API key") # malformed: the real key carries a checksum + if not STATE["api_keys_enabled"]: + return self.error(401, "API keys are turned off on this server", "API_KEYS_DISABLED") + if key != API_KEY: + return self.error(401, "Invalid API key") + if write and not STATE["api_key_write"]: + return self.error(403, "This API key is read-only", "API_KEY_READ_ONLY") + return key + + def device(self, dto): + """PluginDeviceDto: what every plugin POST carries.""" + if not isinstance(dto, dict): + return self.error(400, "Bad JSON") + if not isinstance(dto.get("deviceId"), str) or not DEVICE_ID.match(dto["deviceId"]): + return self.error(400, "deviceId must match /^[A-Za-z0-9_-]{1,100}$/") + if not isinstance(dto.get("deviceModel"), str) or len(dto["deviceModel"]) > 100: + return self.error(400, "deviceModel must be a string of at most 100 characters") + if not isinstance(dto.get("pluginVersion"), str) or len(dto["pluginVersion"]) > 20: + return self.error(400, "pluginVersion must be a string of at most 20 characters") + if "deviceTime" in dto and not (isinstance(dto["deviceTime"], str) and DEVICE_TIME.match(dto["deviceTime"])): + return self.error(400, "deviceTime must be YYYY-MM-DD HH:MM:SS") + STATE["devices"][dto["deviceId"]] = dto["deviceModel"] + return True + + # ---------------------------------------------------------------- routes + def do_GET(self): + self.route("GET") + + def do_POST(self): + self.route("POST") + + def do_PUT(self): + self.route("PUT") + + def do_DELETE(self): + self.route("DELETE") + + def route(self, method): + global STATE + url = urlparse(self.path) + path, q = url.path, {k: v[-1] for k, v in parse_qs(url.query).items()} + if path == "/_mock/state": + return self.send(200, {k: v for k, v in STATE.items()}) + if path == "/_mock/reset": + STATE = fresh() + return self.send(200, {"ok": True}) + if path == "/_mock/set": + STATE.update(self.body() or {}) + return self.send(200, {"ok": True}) + if STATE["offline"]: + return self.error(503, "Service Unavailable") + if not path.startswith("/api/v1/"): + return self.error(404, "Not Found") + p = path[len("/api/v1/"):] + if p.startswith("koreader/"): + if not self.ko_user(): + return + STATE["seen"].append([method, p]) + return self.koreader(method, p[len("koreader/"):], q) + if p == "auth/me" and method == "GET": + if not self.api_key(): + return + return self.send(200, {"id": 1, "username": "will", "name": "Will", "email": "will@example.com", "active": True, + "isSuperuser": False, "isDefaultPassword": False, "settings": {}, "avatarUrl": None, + "provisioningMethod": "local", "authenticationMethod": "api_key", + "permissions": ["koreader_sync", "book_download"]}) + if p == "books/query" and method == "POST": + # Marked safe for read-only keys in the real server. Only the part GZreader uses: the + # audiobooks, found by a format rule. (The real card has many more fields.) + if not self.api_key(): + return + d = self.body() + pg = isinstance(d, dict) and d.get("pagination") + if not isinstance(pg, dict) or not isinstance(pg.get("page"), int) or not isinstance(pg.get("size"), int) \ + or not isinstance(d.get("sort"), list): + return self.error(400, "sort and pagination are required") + rules = (d.get("filter") or {}).get("rules") or [] + fmts = {str(v).lower() for r in rules if r.get("field") == "format" and r.get("operator") == "includesAny" + for v in r.get("value") or []} + items = [{"id": AUDIOBOOK["id"], "title": AUDIOBOOK["title"], "authors": AUDIOBOOK["authors"]}] \ + if not rules or fmts & {a["format"] for a in AUDIOBOOK["assets"]} else [] + items = items[(pg["page"] - 1) * pg["size"]:pg["page"] * pg["size"]] + return self.send(201, {"items": items, "total": len(items), "page": pg["page"], "size": pg["size"]}) + if p.startswith("audiobooks/"): + if not self.api_key(write=method != "GET"): + return + STATE["seen"].append([method, p]) + return self.audiobooks(method, p[len("audiobooks/"):]) + return self.error(404, "Not Found") + + # KOReader API ------------------------------------------------------------ + def koreader(self, method, p, q): + if p == "users/auth" and method == "GET": + return self.send(200, {"authorized": "OK", "username": KO_USER}) + if p == "plugin/version" and method == "GET": + return self.send(200, {"pluginVersion": "0.9.0", "serverVersion": "0.9.0", "capabilities": STATE["capabilities"]}) + m = re.match(r"^syncs/progress/([^/]+)$", p) + if m and method == "GET": + p = STATE["progress"].get(m.group(1)) + return self.send(200, p and {"document": m.group(1), "percentage": p["percentage"], "progress": p.get("progress") or "", + "device": p["device"], "device_id": p["device_id"], "timestamp": p["timestamp"]} or {}) + if p == "syncs/progress" and method == "PUT": + d = self.body() + if not isinstance(d, dict) or not isinstance(d.get("document"), str): + return self.error(400, "document must be a string") + if not isinstance(d.get("percentage"), (int, float)) or not 0 <= d["percentage"] <= 1: + return self.error(400, "percentage must be a number from 0 to 1") + if not any(b["hash"] == d["document"] for b in BOOKS): + return self.error(404, "Book not found for the given document hash") + self.keep_progress(d["document"], d, d.get("device"), d.get("device_id")) + return self.send(200, {"document": d["document"], "timestamp": STATE["progress"][d["document"]]["timestamp"]}) + if p == "plugin/match-check" and method == "POST": + d = self.body() + if not self.device(d): + return + hashes = d.get("hashes") + if not isinstance(hashes, list) or not 1 <= len(hashes) <= 500 or not all(isinstance(h, str) and MD5.match(h) for h in hashes): + return self.error(400, "hashes must be 1 to 500 MD5 hex strings") + by = {b["hash"]: b for b in BOOKS} + return self.send(201, {"matches": [{"hash": h, "bookId": by[h]["id"], "bookFileId": by[h]["fileId"]} for h in hashes if h in by], + "libraryVersion": "lib-%d" % len(BOOKS)}) + if p == "plugin/progress" and method == "POST": + d = self.body() + if not self.device(d): + return + items = d.get("items") + if not isinstance(items, list) or not items: + return self.error(400, "items must be a non-empty array") + by = {b["hash"] for b in BOOKS} + results, unmatched = [], [] + for it in items: + if not isinstance(it, dict) or not isinstance(it.get("hash"), str) or not MD5.match(it["hash"]): + return self.error(400, "hash must be an MD5 hex string") + if not isinstance(it.get("percentage"), (int, float)) or not 0 <= it["percentage"] <= 1: + return self.error(400, "percentage must be a number from 0 to 1") + if "progress" in it and not isinstance(it["progress"], str): + return self.error(400, "progress must be a string") + if it["hash"] in by: + self.keep_progress(it["hash"], it, d["deviceModel"], d["deviceId"]) + results.append({"hash": it["hash"], "accepted": True}) + else: + unmatched.append(it["hash"]) + return self.send(201, {"results": results, "unmatched": unmatched}) + if p.startswith("plugin/catalog/") and method == "GET": + return self.catalog(p[len("plugin/catalog/"):], q) + return self.error(404, "Not Found") + + def keep_progress(self, h, src, device, device_id): + STATE["progress"][h] = {"percentage": src["percentage"], "progress": src.get("progress"), "device": device or "KOReader", + "device_id": device_id or "mock", "timestamp": int(src.get("timestamp") or time.time()), + "updatedAt": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())} + + def page(self, items, q, base): + try: + size = int(q.get("size", 20)) + page = int(q.get("page", 1)) + except ValueError: + return self.error(400, "page and size must be integers") + if not 1 <= size <= 100 or page < 1: + return self.error(400, "size must be from 1 to 100 and page at least 1") + start = (page - 1) * size + part = items[start:start + size] + more = start + size < len(items) + return self.send(200, {"items": part, "total": len(items), "page": page, "size": size, "hasNext": more, + "hasPrevious": page > 1, + "nextUrl": more and "%s&page=%d" % (base, page + 1) or None, + "previousUrl": page > 1 and "%s&page=%d" % (base, page - 1) or None, + "seriesSummary": None}) + + def catalog(self, p, q): + C = "/api/v1/koreader/plugin/catalog" + if p == "root": + return self.send(200, {"sections": [ + {"id": "continue-reading", "title": "Continue reading", "section": "continue-reading", + "booksHref": C + "/books?sort=recently_read&readStatus=reading"}, + {"id": "recent", "title": "Recently added", "section": "recent", "booksHref": C + "/books?sort=recently_added"}, + {"id": "libraries", "title": "Libraries", "section": "libraries", "href": C + "/sections/libraries"}, + {"id": "collections", "title": "Collections", "section": "collections", "href": C + "/sections/collections"}, + {"id": "smart-scopes", "title": "SmartScopes", "section": "smart-scopes", "href": C + "/sections/smart-scopes"}, + {"id": "authors", "title": "Authors", "section": "authors", "href": C + "/sections/authors"}, + {"id": "series", "title": "Series", "section": "series", "href": C + "/sections/series"}, + {"id": "all-books", "title": "All Books", "section": "all-books", "booksHref": C + "/books?sort=title"}]}) + m = re.match(r"^sections/([^/]+)$", p) + if m: + s = m.group(1) + if s == "libraries": + return self.send(200, {"section": s, "items": [ + {"id": str(i), "title": n, "section": s, "count": sum(b["libraryId"] == i for b in BOOKS), + "booksHref": C + "/books?sort=title&libraryId=%d" % i} for i, n in LIBRARIES.items()]}) + if s == "collections": + return self.send(200, {"section": s, "items": [ + {"id": str(i), "title": n, "section": s, "count": sum(i in b["collections"] for b in BOOKS), + "booksHref": C + "/books?sort=title&collectionId=%d" % i} for i, n in COLLECTIONS.items()]}) + if s == "smart-scopes": + return self.send(200, {"section": s, "items": []}) + if s == "authors": + names = sorted({a for b in BOOKS for a in b["authors"]}) + items = [{"id": n, "title": n, "section": s, "count": sum(n in b["authors"] for b in BOOKS), + "booksHref": C + "/books?sort=title&author=" + quote(n), "authorId": i + 1, "hasPhoto": False, + "photoUrl": None} for i, n in enumerate(names)] + elif s == "series": + names = sorted({b["seriesName"] for b in BOOKS if b["seriesName"]}) + items = [] + for n in names: + sid = next(b["seriesId"] for b in BOOKS if b["seriesName"] == n) + items.append({"id": "series-%d" % sid, "title": n, "section": s, "count": sum(b["seriesName"] == n for b in BOOKS), + "seriesId": sid, "booksHref": C + "/books?sort=series&seriesId=%d" % sid, + "authorNames": sorted({a for b in BOOKS if b["seriesName"] == n for a in b["authors"]})}) + else: + return self.error(400, "Unknown catalog section") + # (authors and series are the two sections the real server pages) + return self.send(200, {"section": s, "items": items, "page": 1, "hasNext": False, "hasPrevious": False, + "nextUrl": None, "previousUrl": None, "query": None, "total": len(items)}) + if p == "books": + if q.get("sort", "recently_added") not in SORTS: + return self.error(400, "sort must be one of " + ", ".join(sorted(SORTS))) + books = list(BOOKS) + if "readStatus" in q: + if q["readStatus"] not in ("unread", "reading", "finished"): + return self.error(400, "readStatus must be one of unread, reading, finished") + reading = lambda b: b["hash"] in STATE["progress"] + books = [b for b in books if {"reading": reading(b), "unread": not reading(b), "finished": False}[q["readStatus"]]] + for key, test in (("libraryId", lambda b, v: b["libraryId"] == int(v)), + ("collectionId", lambda b, v: int(v) in b["collections"]), + ("seriesId", lambda b, v: b["seriesId"] == int(v)), + ("author", lambda b, v: v in b["authors"]), + ("series", lambda b, v: b["seriesName"] == v), + ("format", lambda b, v: b["format"] == v.lower()), + ("q", lambda b, v: v.lower() in (b["title"] + " " + " ".join(b["authors"])).lower())): + if key in q: + try: + books = [b for b in books if test(b, q[key])] + except ValueError: + return self.error(400, "%s must be a number" % key) + sort = q.get("sort", "recently_added") + keyf = {"title": lambda b: b["title"].lower(), "author": lambda b: b["authors"][0].lower(), + "series": lambda b: ((b["seriesName"] or "~"), b["seriesIndex"] or 0)}.get(sort, lambda b: b["addedAt"]) + desc = q.get("order", "desc" if sort.startswith("recently") else "asc") == "desc" + books.sort(key=keyf, reverse=desc) + base = "/api/v1/koreader/plugin/catalog/books?" + "&".join("%s=%s" % (k, v) for k, v in sorted(q.items()) if k != "page") + return self.page([list_item(b) for b in books], q, base) + m = re.match(r"^books/(\d+)$", p) + if m: + b = next((b for b in BOOKS if b["id"] == int(m.group(1))), None) + return self.send(200, detail(b)) if b else self.error(404, "Book not found") + m = re.match(r"^books/(\d+)/thumbnail$", p) + if m: + if not any(b["id"] == int(m.group(1)) for b in BOOKS): + return self.error(404, "No thumbnail") + if self.headers.get("If-None-Match") == '"1790000000000"': + return self.send(304, b"", "image/png") + return self.send(200, PNG, "image/png", {"ETag": '"1790000000000"', "Cache-Control": "no-cache"}) + m = re.match(r"^files/(\d+)/download$", p) + if m: + b = next((b for b in BOOKS if b["fileId"] == int(m.group(1))), None) + if not b: + return self.error(404, "File not found") + return self.send(200, b["data"], "application/epub+zip" if b["format"] == "epub" else "application/pdf", + {"Content-Disposition": 'attachment; filename="%s.%s"' % (b["title"], b["format"])}) + return self.error(404, "Not Found") + + # Main API: audiobooks ------------------------------------------------------ + def audiobooks(self, method, p): + m = re.match(r"^(\d+)/(.+)$", p) + if not m or int(m.group(1)) != AUDIOBOOK["id"]: + return self.error(404, "Book has no audiobook assets") + rest, bid = m.group(2), AUDIOBOOK["id"] + if rest == "manifest" and method == "GET": + assets = [{"assetId": a["assetId"], "fileId": a["fileId"], "sequence": a["sequence"], "format": a["format"], + "durationMs": a["durationMs"], "sizeBytes": len(a["data"]), + "etag": hashlib.md5(a["data"]).hexdigest()} for a in AUDIOBOOK["assets"]] + chapters, at = [], 0 + for a in AUDIOBOOK["assets"]: + chapters.append({"id": "ch-%d" % a["sequence"], "title": "Part %d" % (a["sequence"] + 1), "assetId": a["assetId"], + "sequence": a["sequence"], "startMs": at, "endMs": at + a["durationMs"], "assetOffsetMs": 0}) + at += a["durationMs"] + return self.send(200, {"schema": "bookorbit.audiobook-manifest", "schemaVersion": 2, "revision": manifest_revision(), + "book": {"id": bid, "title": AUDIOBOOK["title"], "authors": AUDIOBOOK["authors"], + "narrators": AUDIOBOOK["narrators"], "hasCover": True}, + "assets": assets, "chapters": chapters, "totalDurationMs": at}) + m = re.match(r"^assets/([^/]+)/content$", rest) + if m and method == "GET": + a = next((a for a in AUDIOBOOK["assets"] if a["assetId"] == m.group(1)), None) + if not a: + return self.error(404, "Audiobook asset not found") + data, size = a["data"], len(a["data"]) + rng = re.match(r"bytes=(\d+)-(\d*)", self.headers.get("Range") or "") + if rng: + start = int(rng.group(1)) + end = int(rng.group(2)) if rng.group(2) else size - 1 + if start >= size or end < start or end >= size: + return self.send(416, b"", "audio/mpeg", {"Content-Range": "bytes */%d" % size}) + return self.send(206, data[start:end + 1], "audio/mpeg", + {"Accept-Ranges": "bytes", "Content-Range": "bytes %d-%d/%d" % (start, end, size)}) + return self.send(200, data, "audio/mpeg", {"Accept-Ranges": "bytes"}) + if rest == "playback-state": + cur = STATE["playback"].get(bid) + if method == "GET": + if not cur: + return self.send(200, b"") # null: the real server sends 200 with no body + return self.send(200, {k: v for k, v in cur.items() if k != "operationId"}) + if method == "DELETE": + STATE["playback"].pop(bid, None) + return self.send(204, b"") + if method == "PUT": + d = self.body() + if not isinstance(d, dict): + return self.error(400, "Bad JSON") + checks = (("assetId", lambda v: isinstance(v, str) and ASSET_ID.match(v)), + ("positionMs", lambda v: isinstance(v, int) and not isinstance(v, bool) and v >= 0), + ("capturedAt", lambda v: isinstance(v, str) and ISO.match(v)), + ("operationId", lambda v: isinstance(v, str) and UUID.match(v)), + ("baseRevision", lambda v: isinstance(v, int) and not isinstance(v, bool) and v >= 0), + ("manifestRevision", lambda v: isinstance(v, str) and re.match(r"^[0-9a-f]{64}$", v))) + for name, ok in checks: + if not ok(d.get(name)): + return self.error(400, "%s is not valid" % name) + extra = set(d) - {n for n, _ in checks} + if extra: + return self.error(400, "property %s should not exist" % sorted(extra)[0]) + if d["manifestRevision"] != manifest_revision(): + return self.error(412, "Audiobook manifest has changed") + a = next((a for a in AUDIOBOOK["assets"] if a["assetId"] == d["assetId"]), None) + if not a: + return self.error(400, "assetId does not belong to this audiobook") + if cur and cur.get("operationId") == d["operationId"]: + return self.send(200, {k: v for k, v in cur.items() if k != "operationId"}) # a resend: no change + if d["positionMs"] > a["durationMs"] + 1000: + return self.error(400, "positionMs exceeds the asset duration") + if d["baseRevision"] != (cur["revision"] if cur else 0): + return self.error(409, "Playback state revision conflict") + pos = min(d["positionMs"], a["durationMs"]) + total = sum(x["durationMs"] for x in AUDIOBOOK["assets"]) + before = sum(x["durationMs"] for x in AUDIOBOOK["assets"] if x["sequence"] < a["sequence"]) + pct = max(0.0, min(100.0, (before + pos) * 100.0 / total)) + STATE["playback"][bid] = {"assetId": d["assetId"], "positionMs": pos, "percentage": pct, + "completed": pct >= 100, "capturedAt": d["capturedAt"], + "revision": (cur["revision"] if cur else 0) + 1, + "manifestRevision": d["manifestRevision"], "operationId": d["operationId"]} + return self.send(200, {k: v for k, v in STATE["playback"][bid].items() if k != "operationId"}) + return self.error(404, "Not Found") + + +if __name__ == "__main__": + port = int(sys.argv[1]) if len(sys.argv) > 1 else 18096 + print("mock BookOrbit on 127.0.0.1:%d (KOReader user %s, API key %s...)" % (port, KO_USER, API_KEY[:8]), flush=True) + ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() diff --git a/tools/gzreader/tests/mock_bookorbit_test.py b/tools/gzreader/tests/mock_bookorbit_test.py new file mode 100644 index 000000000..7c5877d65 --- /dev/null +++ b/tools/gzreader/tests/mock_bookorbit_test.py @@ -0,0 +1,233 @@ +"""The mock BookOrbit server answers as the real one does (routes, sign-ins, +field names, refusals), so the tests built on it mean something. + + python3 -I mock_bookorbit_test.py +""" +import hashlib, json, os, subprocess, sys, time, urllib.request, urllib.error + +PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18196 +HERE = os.path.dirname(os.path.abspath(__file__)) +BASE = "http://127.0.0.1:%d" % PORT +USER, PASSWORD = "will-kindle", "hunter22" +KEY = "bok_" + "a1B2c3D4e5" * 4 + "f6G7h8I9j" +KO = {"x-auth-user": USER, "x-auth-key": hashlib.md5(PASSWORD.encode()).hexdigest()} +API = {"Authorization": "Bearer " + KEY} +DEV = {"deviceId": "kindle-pw3_01", "deviceModel": "Kindle Paperwhite 3", "pluginVersion": "1.35.0"} +passed = failed = 0 + + +def check(cond, name): + global passed, failed + if cond: + passed += 1 + else: + failed += 1 + print("FAIL: " + name) + + +def call(method, path, headers=None, body=None, raw=False): + data = json.dumps(body).encode() if body is not None else None + h = dict(headers or {}) + if data is not None: + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=10) as r: + code, out, hdr = r.status, r.read(), r.headers + except urllib.error.HTTPError as e: + code, out, hdr = e.code, e.read(), e.headers + if raw: + return code, out, hdr + try: + return code, json.loads(out) if out else None + except ValueError: + return code, None + + +proc = subprocess.Popen([sys.executable, "-I", os.path.join(HERE, "mock_bookorbit.py"), str(PORT)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +try: + for _ in range(50): + try: + call("GET", "/_mock/state") + break + except OSError: + time.sleep(0.1) + + # --- the KOReader sign-in + code, j = call("GET", "/api/v1/koreader/users/auth", KO) + check(code == 200 and j == {"authorized": "OK", "username": USER}, "sign-in with the MD5 key") + code, j = call("GET", "/api/v1/koreader/users/auth", {"x-auth-user": USER, "x-auth-key": PASSWORD}) + check(code == 200, "sign-in with the plain password") + check(call("GET", "/api/v1/koreader/users/auth")[0] == 401, "no credentials: 401") + check(call("GET", "/api/v1/koreader/users/auth", {"x-auth-user": USER, "x-auth-key": "wrong"})[0] == 401, "wrong password: 401") + check(call("GET", "/api/v1/koreader/users/auth", API)[0] == 401, "an API key is not a KOReader sign-in") + call("POST", "/_mock/set", body={"sync_enabled": False}) + check(call("GET", "/api/v1/koreader/users/auth", KO)[0] == 403, "sync switched off: 403") + call("POST", "/_mock/reset") + + # --- version and capabilities + code, j = call("GET", "/api/v1/koreader/plugin/version", KO) + check(code == 200 and "bookmarkSync" in j["capabilities"] and j["serverVersion"], "version lists capabilities") + call("POST", "/_mock/set", body={"capabilities": ["catalogListsV2"]}) + check(call("GET", "/api/v1/koreader/plugin/version", KO)[1]["capabilities"] == ["catalogListsV2"], "capabilities can be switched") + call("POST", "/_mock/reset") + + # --- catalog + code, j = call("GET", "/api/v1/koreader/plugin/catalog/root", KO) + check(code == 200 and [i["section"] for i in j["sections"]] == ["continue-reading", "recent", "libraries", "collections", + "smart-scopes", "authors", "series", "all-books"], "catalog root") + check(j["sections"][2]["href"].endswith("/sections/libraries") and "booksHref" in j["sections"][7], "root: lists and book links") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/sections/libraries", KO) + check(code == 200 and j["section"] == "libraries" and j["items"][0]["title"] == "Fiction" and j["items"][0]["count"] == 3, "libraries section") + check(j["items"][0]["id"] == "1" and "libraryId=1" in j["items"][0]["booksHref"], "libraries: id and link") + check(call("GET", "/api/v1/koreader/plugin/catalog/sections/nope", KO)[0] == 400, "unknown section: 400") + code, a = call("GET", "/api/v1/koreader/plugin/catalog/sections/authors", KO) + check(a["total"] == 4 and a["items"][0]["title"] == "Ada Marsh" and a["items"][0]["authorId"] == 1, "authors section") + check(call("GET", a["items"][0]["booksHref"], KO)[1]["total"] == 2, "an author's link lists their books") + code, se = call("GET", "/api/v1/koreader/plugin/catalog/sections/series", KO) + check(call("GET", se["items"][0]["booksHref"], KO)[1]["items"][0]["seriesIndex"] == 1, "a series link lists it in order") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/books?size=2&sort=title", KO) + check(code == 200 and j["total"] == 5 and len(j["items"]) == 2 and j["hasNext"] and not j["hasPrevious"] and j["nextUrl"], "books: first page") + check(j["items"][0]["title"] == "A Field Guide to Fog" and j["items"][0]["formats"] == ["epub"], "books: sorted by title") + need = {"id", "title", "authors", "seriesId", "seriesName", "seriesIndex", "progressPercentage", "lastReadAt", "readStatus", + "formats", "hasCover", "thumbnailUrl", "detailUrl", "addedAt", "updatedAt"} + check(j["seriesSummary"] is None and set(j["items"][0]) == need, "books: the list item's fields") + code, j = call("GET", "/api/v1/koreader/plugin/catalog/books?size=2&sort=title&page=3", KO) + check(len(j["items"]) == 1 and not j["hasNext"] and j["hasPrevious"], "books: last page") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?libraryId=2", KO)[1]["total"] == 2, "books: by library") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?collectionId=12", KO)[1]["total"] == 2, "books: by collection") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?q=okafor", KO)[1]["total"] == 2, "books: search") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?sort=bogus", KO)[0] == 400, "books: bad sort is refused") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?size=500", KO)[0] == 400, "books: oversize page is refused") + code, d = call("GET", "/api/v1/koreader/plugin/catalog/books/101", KO) + f = d["files"][0] + check(code == 200 and d["libraryName"] == "Fiction" and d["seriesName"] == "Waymarks" and f["format"] == "epub" and f["role"] == "content" and f["downloadUrl"], "book detail") + check(call("GET", "/api/v1/koreader/plugin/catalog/books/999", KO)[0] == 404, "missing book: 404") + code, png, hdr = call("GET", "/api/v1/koreader/plugin/catalog/books/101/thumbnail", KO, raw=True) + check(code == 200 and png[:4] == b"\x89PNG" and hdr["Content-Type"] == "image/png", "thumbnail is a PNG") + check(call("GET", "/api/v1/koreader/plugin/catalog/books/101/thumbnail", dict(KO, **{"If-None-Match": hdr["ETag"]}), raw=True)[0] == 304, + "thumbnail: not changed is 304") + code, data, hdr = call("GET", f["downloadUrl"], KO, raw=True) + check(code == 200 and len(data) == f["sizeBytes"] and hashlib.md5(data).hexdigest() == f["fileHash"], "download gives the file") + check(call("GET", f["downloadUrl"])[0] == 401, "download needs the sign-in") + + # --- matching and progress + h = f["fileHash"] + code, j = call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, hashes=[h, "0" * 32])) + check(code == 201 and j["matches"] == [{"hash": h, "bookId": 101, "bookFileId": f["id"]}] and j["libraryVersion"], "match-check") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, {"hashes": [h]})[0] == 400, "match-check needs the device fields") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, deviceId="bad id!", hashes=[h]))[0] == 400, "bad deviceId is refused") + check(call("POST", "/api/v1/koreader/plugin/match-check", KO, dict(DEV, hashes=["x"]))[0] == 400, "a non-MD5 hash is refused") + code, j = call("POST", "/api/v1/koreader/plugin/progress", KO, + dict(DEV, items=[{"hash": h, "percentage": 0.42, "progress": "/body/DocFragment[3]/body/p[7]/text().0", "timestamp": 1790000000}, + {"hash": "f" * 32, "percentage": 0.1}])) + check(code == 201 and j["results"] == [{"hash": h, "accepted": True}] and j["unmatched"] == ["f" * 32], "progress: accepted and unmatched") + check(call("POST", "/api/v1/koreader/plugin/progress", KO, dict(DEV, items=[{"hash": h, "percentage": 42}]))[0] == 400, "progress: percentage is 0 to 1") + code, j = call("GET", "/api/v1/koreader/syncs/progress/" + h, KO) + check(code == 200 and j["percentage"] == 0.42 and j["progress"].startswith("/body/") and j["document"] == h + and j["device"] == DEV["deviceModel"] and j["timestamp"] == 1790000000, "KOSync reads the position back") + check(call("GET", "/api/v1/koreader/syncs/progress/" + "e" * 32, KO) == (200, {}), "KOSync: no position is {}") + code, j = call("PUT", "/api/v1/koreader/syncs/progress", KO, {"document": h, "percentage": 0.5, "progress": "x", "device": "K", "device_id": "k1"}) + check(code == 200 and j["document"] == h and j["timestamp"], "KOSync writes a position") + check(call("PUT", "/api/v1/koreader/syncs/progress", KO, {"document": "d" * 32, "percentage": 0.5})[0] == 404, "KOSync: unknown book is 404") + d = call("GET", "/api/v1/koreader/plugin/catalog/books/101", KO)[1] + check(d["progressPercentage"] == 50 and d["progress"]["fileId"] == f["id"] and d["readStatus"] == "reading", + "the catalog shows the progress, out of 100") + check(call("GET", "/api/v1/koreader/plugin/catalog/books?readStatus=reading", KO)[1]["total"] == 1, "books: by read status") + + # --- the main API: key, audiobooks + code, j = call("GET", "/api/v1/auth/me", API) + check(code == 200 and j["authenticationMethod"] == "api_key", "API key as Bearer") + check(call("GET", "/api/v1/auth/me", {"X-Api-Key": KEY})[0] == 200, "API key as X-Api-Key") + check(call("GET", "/api/v1/auth/me?api_key=" + KEY)[0] == 401, "API key in the address is refused") + check(call("GET", "/api/v1/auth/me", {"Authorization": "Bearer bok_wrong"})[0] == 401, "wrong API key: 401") + check(call("GET", "/api/v1/auth/me", {"Authorization": "Bearer " + KEY, "X-Api-Key": KEY[:-1] + "x"})[1]["message"] == "Conflicting credentials", + "two keys that disagree are refused") + call("POST", "/_mock/set", body={"api_keys_enabled": False}) + check(call("GET", "/api/v1/auth/me", API)[1].get("errorCode") == "API_KEYS_DISABLED", "API keys switched off") + call("POST", "/_mock/set", body={"api_keys_enabled": True}) + check(call("GET", "/api/v1/auth/me", KO)[0] == 401, "a KOReader sign-in is not an API key") + code, m = call("GET", "/api/v1/audiobooks/201/manifest", API) + a0, a1 = m["assets"] + check(code == 200 and m["schema"] == "bookorbit.audiobook-manifest" and len(m["revision"]) == 64 and m["totalDurationMs"] == 105000 and a0["sequence"] == 0 + and m["chapters"][1]["startMs"] == 60000 and m["chapters"][1]["assetId"] == a1["assetId"], "audiobook manifest") + check(call("GET", "/api/v1/audiobooks/999/manifest", API)[0] == 404, "missing audiobook: 404") + url = "/api/v1/audiobooks/201/assets/%s/content" % a0["assetId"] + code, data, hdr = call("GET", url, API, raw=True) + check(code == 200 and len(data) == a0["sizeBytes"] and hdr["Accept-Ranges"] == "bytes", "audio file, whole") + code, part, hdr = call("GET", url, dict(API, Range="bytes=1000-"), raw=True) + check(code == 206 and part == data[1000:] and hdr["Content-Range"] == "bytes 1000-%d/%d" % (len(data) - 1, len(data)), "audio file, resumed") + check(call("GET", url, dict(API, Range="bytes=999999-"), raw=True)[0] == 416, "audio file: a range past the end is 416") + check(call("GET", url, raw=True)[0] == 401, "audio file needs the key") + + state = "/api/v1/audiobooks/201/playback-state" + check(call("GET", state, API, raw=True)[:2] == (200, b""), "no position yet: an empty reply") + put = {"assetId": a1["assetId"], "positionMs": 15000, "capturedAt": "2026-11-22T10:00:00.000Z", + "operationId": "3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6b", "baseRevision": 0, "manifestRevision": m["revision"]} + code, j = call("PUT", state, API, put) + check(code == 200 and j["revision"] == 1 and j["positionMs"] == 15000 and abs(j["percentage"] - 7500000 / 105000.0) < 1e-9 + and j["completed"] is False and "operationId" not in j, "position saved, out of 100") + check(call("PUT", state, API, put)[1]["revision"] == 1, "the same operation sent twice changes nothing") + code, j = call("PUT", state, API, dict(put, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6c", positionMs=20000)) + check(code == 409, "a stale base revision is a conflict") + code, j = call("PUT", state, API, dict(put, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6c", positionMs=20000, baseRevision=1)) + check(code == 200 and j["revision"] == 2, "the next save with the new base revision") + check(call("PUT", state, API, dict(put, manifestRevision="0" * 64, baseRevision=2, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6d"))[0] + == 412, "an old manifest revision is refused (412)") + check(call("PUT", state, API, dict(put, positionMs=99000, baseRevision=2, operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6e"))[0] == 400, + "a position past the file's end is refused") + check(call("PUT", state, API, dict(put, assetId="aud_33333333-3333-4333-8333-333333333333", baseRevision=2, + operationId="3f2b8c1e-5a4d-4e6f-9a7b-1c2d3e4f5a6f"))[0] == 400, "another book's file is refused") + check(call("PUT", state, API, dict(put, assetId="6201"))[0] == 400, "the asset id must be aud_") + check(call("PUT", state, API, dict(put, positionMs=1.5))[0] == 400, "the position is whole milliseconds") + check(call("PUT", state, API, dict(put, extra=1))[0] == 400, "unknown fields are refused") + call("POST", "/_mock/set", body={"api_key_write": False}) + code, j = call("PUT", state, API, put) + check(code == 403 and j["errorCode"] == "API_KEY_READ_ONLY", "a read-only key can't save a position") + check(call("GET", state, API)[1]["revision"] == 2, "a read-only key can read it") + call("POST", "/_mock/set", body={"api_key_write": True}) + check(call("DELETE", state, API, raw=True)[0] == 204 and call("GET", state, API, raw=True)[1] == b"", "position cleared") + + # --- finding the audiobooks, and the probe script + q = {"sort": [{"field": "title", "dir": "asc"}], "pagination": {"page": 1, "size": 5}, + "filter": {"type": "group", "join": "AND", "rules": [{"type": "rule", "field": "format", "operator": "includesAny", "value": ["MP3"]}]}} + code, j = call("POST", "/api/v1/books/query", API, q) + check(code == 201 and j["total"] == 1 and j["items"][0]["id"] == 201, "books/query finds the audiobook by format") + q["filter"]["rules"][0]["value"] = ["epub"] + check(call("POST", "/api/v1/books/query", API, q)[1]["total"] == 0, "books/query: no audio format, no audiobook") + check(call("POST", "/api/v1/books/query", API, {"page": 1})[0] == 400, "books/query needs sort and pagination") + call("POST", "/_mock/set", body={"api_key_write": False}) + check(call("POST", "/api/v1/books/query", API, q)[0] == 201, "a read-only key can run books/query") + call("POST", "/_mock/set", body={"api_key_write": True}) + + call("POST", "/_mock/set", body={"seen": []}) + env = dict(os.environ, BOOKORBIT_URL=BASE, BOOKORBIT_KO_USER=USER, BOOKORBIT_KO_PASSWORD=PASSWORD, BOOKORBIT_API_KEY=KEY) + probe = [sys.executable, "-I", os.path.join(HERE, "..", "bookorbit-probe.py")] + r = subprocess.run(probe, env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + out = r.stdout + r.stderr + check(r.returncode == 0 and "MISSING" not in out and "no answer" not in out, "the probe runs clean against the mock") + check(out.count("has every field GZreader's tests use") == 4, "the probe compares four shapes") + check("audio file (first 1 KB, resumable?) 206" in out and "2 file(s), 2 chapter(s)" in out, "the probe reaches the audiobook") + for secret, what in ((PASSWORD, "password"), (KO["x-auth-key"], "password's MD5"), (KEY, "API key"), (USER, "user name"), + ("127.0.0.1", "address"), ("Long Way", "a book's title"), ("Marsh", "an author")): + check(secret not in out, "the probe never prints the " + what) + seen = call("GET", "/_mock/state")[1] + check(all(m == "GET" or p in ("koreader/plugin/match-check",) for m, p in seen["seen"]) and len(seen["seen"]) > 10 + and seen["playback"] == {}, "the probe only reads") + env["BOOKORBIT_KO_PASSWORD"] = "nope-nope" + r = subprocess.run(probe, env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60) + check(r.returncode == 1 and "401" in r.stdout and "nope-nope" not in r.stdout and "version" not in r.stdout, "the probe stops at a failed sign-in") + + # --- the server away + call("POST", "/_mock/set", body={"offline": True}) + check(call("GET", "/api/v1/koreader/users/auth", KO)[0] == 503, "offline: 503") + call("POST", "/_mock/reset") + seen = call("GET", "/_mock/state")[1] + check(seen["seen"] == [] and seen["progress"] == {}, "reset clears the state") +finally: + proc.terminate() + proc.wait(timeout=5) + +print("%d passed, %d failed" % (passed, failed)) +sys.exit(1 if failed else 0) diff --git a/tools/gzreader/tests/run.sh b/tools/gzreader/tests/run.sh index 9b22933ce..622c8c792 100755 --- a/tools/gzreader/tests/run.sh +++ b/tools/gzreader/tests/run.sh @@ -272,6 +272,10 @@ echo "== the Nook package, from the Kindle 2/3/DX package (GZreader/app or korea timeout 120 bash "$T/package_nook_test.sh" "$REPO" 2>&1 | grep -E "FAIL|passed" [ "${PIPESTATUS[0]}" -eq 0 ] || failed=$((failed + 1)) +echo "== the mock BookOrbit server, and the probe script" +timeout 120 python3 -I "$T/mock_bookorbit_test.py" $((PORT + 60)) 2>&1 | grep -E "FAIL|passed" +[ "${PIPESTATUS[0]}" -eq 0 ] || failed=$((failed + 1)) + echo "== the wiki's links" timeout 60 python3 "$T/wiki_test.py" 2>&1 | grep -E "FAIL|passed" [ "${PIPESTATUS[0]}" -eq 0 ] || failed=$((failed + 1)) From 65838407be18a57eea9a964832f5bf841e464eae Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:18:30 -0500 Subject: [PATCH 02/27] BookOrbit as the book server: sign in, browse, covers, download A second client with the Grimmory client's methods (gzreader_bookorbit.lua), answering in the shapes the Catalog, the index, covers and downloads already read. plugin.api stays the same table; its class changes with the sign-in (store.backend). Sign-in is BookOrbit's KOReader sync user: only the password's MD5 is kept (with the other secrets, off the USB drive). Nothing is sent to BookOrbit yet (books_only): progress, highlights, bookmarks, statistics, shelves and audiobooks come in their own steps. Each server has its own book ids: the other server's list of downloads is put aside (the files stay), and covers are kept in separate folders. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HqNYrwobY8un97LQ2jriQC --- .../gzreader.koplugin/gzreader_bookorbit.lua | 436 ++++++++++++++++++ .../gzreader.koplugin/gzreader_browser.lua | 30 +- .../gzreader.koplugin/gzreader_changelog.lua | 6 + plugins/gzreader.koplugin/gzreader_copy.lua | 6 +- plugins/gzreader.koplugin/gzreader_covers.lua | 11 +- .../gzreader.koplugin/gzreader_grimstats.lua | 2 +- plugins/gzreader.koplugin/gzreader_index.lua | 4 + .../gzreader.koplugin/gzreader_pairpage.lua | 17 +- plugins/gzreader.koplugin/gzreader_phone.lua | 28 +- .../gzreader.koplugin/gzreader_secrets.lua | 3 +- .../gzreader.koplugin/gzreader_shelves.lua | 6 +- .../gzreader.koplugin/gzreader_storage.lua | 2 +- plugins/gzreader.koplugin/gzreader_sync.lua | 2 +- plugins/gzreader.koplugin/main.lua | 143 ++++-- tools/gzreader/emulator/bookorbit_browse.lua | 83 ++++ tools/gzreader/tests/mock_bookorbit.py | 19 +- tools/gzreader/tests/run_tests.lua | 214 +++++++++ wiki/BookOrbit.md | 54 +++ wiki/Home.md | 1 + wiki/Setup-Page-and-Connections.md | 2 + wiki/_Sidebar.md | 1 + 21 files changed, 1006 insertions(+), 64 deletions(-) create mode 100644 plugins/gzreader.koplugin/gzreader_bookorbit.lua create mode 100644 tools/gzreader/emulator/bookorbit_browse.lua create mode 100644 wiki/BookOrbit.md diff --git a/plugins/gzreader.koplugin/gzreader_bookorbit.lua b/plugins/gzreader.koplugin/gzreader_bookorbit.lua new file mode 100644 index 000000000..6e137f53b --- /dev/null +++ b/plugins/gzreader.koplugin/gzreader_bookorbit.lua @@ -0,0 +1,436 @@ +--[[-- +BookOrbit as the book server, in place of Grimmory. + +The same methods as the Grimmory client (gzreader_api.lua), answering in the +shapes the rest of GZreader already reads (a list page's `content`, a book's +`primaryFileType`…), so the Catalog, the library index, covers and downloads +work unchanged. Main swaps `plugin.api`'s class to this one when the sign-in +is a BookOrbit one (`store.backend == "bookorbit"`, Grimmory:useBackend). + +BookOrbit's KOReader API (/api/v1/koreader/…) is what it offers e-readers: + * sign-in: the KOReader sync user name and password from BookOrbit's + Settings → KOReader, sent on every request as x-auth-user and x-auth-key + (the password's MD5, as KOReader's own sync does). Only that MD5 is kept + (store.bookorbit.key; off the USB drive, gzreader_secrets.lua): the + password itself is never stored. + * the catalog: /koreader/plugin/catalog/… (sections, books, a book, its + cover, its file). + +This is the first part: sign in, browse, covers, download. Reading progress, +highlights, bookmarks, statistics, collections and audiobooks are not sent to +BookOrbit yet (`books_only`: main and the sync modules leave them alone), so +every method for those answers nil, "unsupported". + +Written from BookOrbit's routes and field names; none of its code is here. +]] + +local Api = require("gzreader_api") +local lfs = require("libs/libkoreader-lfs") +local ltn12 = require("ltn12") +local Log = require("gzreader_log") + +local BookOrbit = { + books_only = true, + NAME = "BookOrbit", + BASE = "/api/v1/koreader", + CATALOG = "/api/v1/koreader/plugin/catalog", + PAGE_MAX = 100, -- (the server's limit for one page) + -- what KOReader opens, in the order a book with several files is offered + READABLE = { "epub", "kepub", "azw3", "mobi", "fb2", "pdf", "cbz", "cbr", "djvu", "txt" }, + AUDIO = { m4b = true, mp3 = true, m4a = true, flac = true, ogg = true, opus = true, aac = true, wav = true }, + READABLE_TYPES = Api.READABLE_TYPES, + IN_PROGRESS = Api.IN_PROGRESS, +} +BookOrbit.__index = BookOrbit + +local READABLE_RANK = {} +for i, f in ipairs(BookOrbit.READABLE) do READABLE_RANK[f] = i end + +-- (JSON null is a function here: only real values are taken) +local function s(v) return type(v) == "string" and v ~= "" and v or nil end +local function n(v) return type(v) == "number" and v or nil end +local function list(v) return type(v) == "table" and v or {} end + +function BookOrbit:new(store, on_change) + return setmetatable({ store = store, on_change = on_change or function() end }, self) +end + +function BookOrbit:isPaired() + local b = self.store.bookorbit + return self.store.server ~= nil and type(b) == "table" and type(b.key) == "string" and b.key ~= "" +end + +function BookOrbit:ensureToken() + if self:isPaired() then return true end + return false, "not_paired" +end + +function BookOrbit:clearTokens() + if type(self.store.bookorbit) == "table" then self.store.bookorbit.key = nil end + self.on_change() +end + +--- (nothing to tell the server: the sign-in is only kept here) +function BookOrbit:logout() self:clearTokens() end + +function BookOrbit:authHeaders() + return { ["x-auth-user"] = tostring(self.store.username or ""), ["x-auth-key"] = tostring((self.store.bookorbit or {}).key or "") } +end + +--- A signed-in request. `path` is relative to the server. Returns code, data, err, headers +--- (as the Grimmory client's call does). +function BookOrbit:call(method, path, opts) + if not self:isPaired() then return nil, nil, "not_paired" end + local o = {} + for k, v in pairs(opts or {}) do o[k] = v end + o.headers = self:authHeaders() + for k, v in pairs((opts or {}).headers or {}) do o.headers[k] = v end + local code, data, headers = Api.rawRequest(method, self.store.server .. path, o) + if not code then return nil, nil, "unreachable" end + if code == 401 or code == 403 then + -- (the password was changed, or sync was switched off for it, in BookOrbit: the + -- sign-in is kept, so switching it back on there is enough) + Log.warn("BookOrbit refused this Kindle's sign-in (HTTP " .. tostring(code) .. ")") + return code, data, code == 403 and "bookorbit_sync_off" or "bookorbit_refused", headers + end + return code, data, nil, headers +end + +local function get(self, path, timeouts) + local code, data, err = self:call("GET", path, { timeouts = timeouts or { 10, 30 } }) + if code == 200 and type(data) == "table" then return data end + return nil, err or ("http_" .. tostring(code)), code +end + +--- Sign in with the KOReader sync user name and password. Returns true, or false, err. +function BookOrbit:login(server, username, password) + local md5 = require("ffi/sha2").md5 + local key = md5(password) + -- no scheme typed and no HTTPS: plain HTTP only on the home network (gzreader_lan.lua) + local candidates = { server } + local typed_bare = server:match("^https://") and not self.explicit_https + if typed_bare and require("gzreader_lan").isPrivate(server) then + candidates[2] = "http://" .. server:sub(9) + end + local last_err + for _i, base in ipairs(candidates) do + local code, data = Api.rawRequest("GET", base .. BookOrbit.BASE .. "/users/auth", { + headers = { ["x-auth-user"] = username, ["x-auth-key"] = key }, + timeouts = { 10, 20 }, + }) + if code == 200 and type(data) == "table" and data.authorized == "OK" then + self.store.server = base + self.store.username = username + self.store.bookorbit = { key = key } + self.store.access_token, self.store.refresh_token, self.store.access_expires_at = nil, nil, nil + self:readVersion() + self.on_change() + return true + elseif code == 401 then + return false, "bookorbit_credentials" + elseif code == 403 then + return false, "bookorbit_sync_off" + elseif code == 429 then + return false, "rate_limited" + elseif code then + -- (a 404 here: an address that answers but isn't BookOrbit, or one too old for this) + last_err = code == 404 and "bookorbit_not_found" or ("http_" .. code) + break + else + last_err = "unreachable" + end + end + if last_err == "unreachable" and typed_bare and not candidates[2] then last_err = "no_https" end + return false, last_err +end + +--- What this server can do (its version and capabilities), kept for the parts that depend on it. +function BookOrbit:readVersion() + local data = get(self, BookOrbit.BASE .. "/plugin/version", { 8, 15 }) + local b = self.store.bookorbit + if type(data) ~= "table" or type(b) ~= "table" then return nil end + b.server_version = s(data.serverVersion) + b.capabilities = {} + for _i, c in ipairs(list(data.capabilities)) do + if type(c) == "string" then b.capabilities[c] = true end + end + return b.capabilities +end + +function BookOrbit:can(capability) + local b = self.store.bookorbit + return type(b) == "table" and type(b.capabilities) == "table" and b.capabilities[capability] == true +end + +function BookOrbit:me() + if not self:isPaired() then return nil, "not_paired" end + return { username = self.store.username, name = self.store.username } +end + +---------------------------------------------------------------- books + +--- The file GZreader would open: the first format KOReader reads, by READABLE's order. +function BookOrbit.pickFormat(formats) + local best, rank + for _i, f in ipairs(list(formats)) do + local r = type(f) == "string" and READABLE_RANK[f:lower()] + if r and (not rank or r < rank) then best, rank = f:lower(), r end + end + return best +end + +local STATUS = { reading = "READING", finished = "READ", unread = "UNREAD" } + +local function fileName(title, format) + local name = tostring(title or "book"):gsub("[%c/\\:%*%?\"<>|]", " "):gsub("%s+", " "):gsub("^%s+", ""):gsub("[%s%.]+$", "") + if name == "" then name = "book" end + if #name > 120 then name = name:sub(1, 120):gsub("[\128-\191]*$", ""):gsub("[\192-\255]$", "") end + return name .. "." .. format +end +BookOrbit.fileName = fileName + +--- A catalog list item as the app's book lists give one. +function BookOrbit.toBook(item) + if type(item) ~= "table" or n(item.id) == nil then return nil end + local format = BookOrbit.pickFormat(item.formats) + local audio = false + for _i, f in ipairs(list(item.formats)) do + if type(f) == "string" and BookOrbit.AUDIO[f:lower()] then audio = true end + end + local authors = {} + for _i, a in ipairs(list(item.authors)) do if s(a) then authors[#authors + 1] = a end end + local title = s(item.title) or ("Book " .. tostring(item.id)) + return { + id = item.id, + title = title, + authors = authors, + seriesName = s(item.seriesName), + seriesNumber = n(item.seriesIndex), + primaryFileType = format and format:upper() or (audio and "AUDIOBOOK" or nil), + primaryFileName = format and fileName(title, format) or nil, + readProgress = n(item.progressPercentage), -- (0–100, as Grimmory's) + lastReadTime = s(item.lastReadAt), + readStatus = STATUS[item.readStatus], + addedOn = s(item.addedAt), + hasCover = item.hasCover == true, + } +end + +local SORT = { title = "title", addedOn = "recently_added", lastReadTime = "recently_read", seriesNumber = "series", + author = "author", publishedDate = "published", updatedOn = "recently_updated" } + +local function wantsOnlyAudio(types) + if type(types) ~= "table" or #types == 0 then return false end + for _i, t in ipairs(types) do + if tostring(t):upper() ~= "AUDIOBOOK" then return false end + end + return true +end + +local function emptyPage(page, size) + return { content = {}, page = page, size = size, totalElements = 0, totalPages = 0, hasNext = false, hasPrevious = page > 0 } +end + +--- A page of books. params as the Grimmory client's: page (from 0), size, sort, dir, search, +--- libraryId, shelfId (a collection), magicShelfId (a SmartScope), authors, series, status, fileType. +function BookOrbit:listBooks(params) + params = params or {} + local page, size = tonumber(params.page) or 0, math.min(tonumber(params.size) or 20, BookOrbit.PAGE_MAX) + if wantsOnlyAudio(params.fileType) then return emptyPage(page, size) end -- (audiobooks: not yet) + local q = { page = page + 1, size = size, sort = SORT[params.sort] or "title", + order = (params.dir == "asc" or params.dir == "desc") and params.dir or nil, + q = s(params.search), libraryId = params.libraryId, collectionId = params.shelfId, smartScopeId = params.magicShelfId, + author = s(params.authors), series = s(params.series) } + if type(params.status) == "table" or params.status == "READING" then q.readStatus = "reading" end + local data, err = get(self, BookOrbit.CATALOG .. "/books" .. Api.query(q), { 15, 45 }) + if not data then return nil, err end + local content = {} + for _i, item in ipairs(list(data.items)) do + local book = BookOrbit.toBook(item) + -- (a book with nothing KOReader opens, an audiobook say, isn't listed among the books) + if book and book.primaryFileType and book.primaryFileType ~= "AUDIOBOOK" then content[#content + 1] = book end + end + local total = n(data.total) or #content + return { content = content, page = page, size = size, totalElements = total, + totalPages = math.ceil(total / size), hasNext = data.hasNext == true, hasPrevious = data.hasPrevious == true } +end + +function BookOrbit:searchBooks(q, page, size) + return self:listBooks{ search = q, page = page or 0, size = size or 25, sort = "title", dir = "asc" } +end + +--- The Grimmory lists the home page asks for by name. +function BookOrbit:simpleList(endpoint, limit) + local params = { page = 0, size = limit or 20, sort = "addedOn", dir = "desc" } + if endpoint == "continue-reading" then params.sort, params.status = "lastReadTime", BookOrbit.IN_PROGRESS end + local data, err = self:listBooks(params) + if not data then return nil, err end + return data.content +end + +function BookOrbit:continueReading(limit) return self:simpleList("continue-reading", limit) end + +local function section(self, name) + local data, err = get(self, BookOrbit.CATALOG .. "/sections/" .. name) + if not data then return nil, err end + local out = {} + for _i, e in ipairs(list(data.items)) do + local id = type(e) == "table" and (tonumber(e.id) or s(e.id)) + if id then out[#out + 1] = { id = id, name = s(e.title) or tostring(id), bookCount = n(e.count) } end + end + return out +end + +function BookOrbit:listLibraries() return section(self, "libraries") end + +--- How many books each library has ({ [id as text] = count }), for the library index: +--- BookOrbit's book lists don't say which library a book is in. +function BookOrbit:libraryCounts() + local libs = section(self, "libraries") + if not libs then return nil end + local out = {} + for _i, lib in ipairs(libs) do out[tostring(lib.id)] = lib.bookCount or 0 end + return out +end + +--- Collections, and SmartScopes as the "magic" ones. +function BookOrbit:listShelves() + local out, err = section(self, "collections") + if not out then return nil, err end + for _i, e in ipairs(section(self, "smart-scopes") or {}) do + e.magic = true + out[#out + 1] = e + end + return out +end + +local function detail(self, book_id) + return get(self, BookOrbit.CATALOG .. "/books/" .. tostring(book_id), { 10, 20 }) +end + +--- The file of a book's detail that GZreader downloads: one the server serves +--- (role "content") in the first format KOReader reads. +function BookOrbit.pickFile(d) + local best, rank + for _i, f in ipairs(list(type(d) == "table" and d.files)) do + local r = type(f) == "table" and type(f.format) == "string" and READABLE_RANK[f.format:lower()] + if r and f.role == "content" and s(f.downloadUrl) and (not rank or r < rank) then best, rank = f, r end + end + return best +end + +local function names(v) + local out = {} + for _i, x in ipairs(list(v)) do + local name = s(x) or (type(x) == "table" and s(x.name)) + if name then out[#out + 1] = name end + end + return out +end + +--- A book's record, as Grimmory's /books/{id}: its file and metadata. +function BookOrbit:getBook(book_id) + local d, err = detail(self, book_id) + if not d then return nil, err end + local f = BookOrbit.pickFile(d) + local book = BookOrbit.toBook(d) or { id = d.id } + book.primaryFile = f and { id = f.id, bookType = f.format:upper(), fileSizeKb = n(f.sizeBytes) and math.ceil(f.sizeBytes / 1024) or nil, + fileHash = s(f.fileHash) } or nil + book.primaryFileId = f and f.id or nil + book.fileSizeKb = book.primaryFile and book.primaryFile.fileSizeKb or nil + book.libraryId = n(d.libraryId) + book.metadata = { title = book.title, subtitle = s(d.subtitle), description = s(d.description), publisher = s(d.publisher), + publishedDate = s(d.publishedDate), pageCount = n(d.pageCount), seriesName = book.seriesName, seriesNumber = book.seriesNumber, + categories = names(d.genres), authors = book.authors } + return book +end + +--- A book's page (description, publisher…), as Grimmory's app detail. +function BookOrbit:getBookDetail(book_id) + local book, err = self:getBook(book_id) + if not book then return nil, err end + local m = book.metadata + return { id = book.id, title = book.title, subtitle = m.subtitle, description = m.description, categories = m.categories, + pageCount = m.pageCount, publisher = m.publisher, publishedDate = m.publishedDate, + seriesName = m.seriesName, seriesNumber = m.seriesNumber } +end + +---------------------------------------------------------------- covers and files + +function BookOrbit:downloadThumbnail(book_id, path, kind) + if not self:isPaired() then return false, "not_paired" end + if kind == "audiobook" then return false, "http_404", 404 end -- (audiobooks: not yet) + local part = path .. ".part" + local fh, ferr = io.open(part, "wb") + if not fh then return false, ferr end + local headers = self:authHeaders() + headers["Accept"] = "image/*" + local code, _, resp = Api.rawRequest("GET", self.store.server .. BookOrbit.CATALOG .. "/books/" .. tostring(book_id) .. "/thumbnail", { + headers = headers, sink = ltn12.sink.file(fh), timeouts = { 10, 30 }, + }) + local ctype = type(resp) == "table" and (resp["content-type"] or resp["Content-Type"]) or "" + if code == 200 and (lfs.attributes(part, "size") or 0) > 0 and tostring(ctype):find("image", 1, true) then + os.rename(part, path) + return true + end + os.remove(part) + return false, code and ("http_" .. code) or "unreachable", code +end + +function BookOrbit:downloadThumbnails(items) + local got, none = 0, {} + for _i, it in ipairs(items or {}) do + local ok, err, code = self:downloadThumbnail(it.id, it.path, it.kind) + if ok then + got = got + 1 + elseif code == 404 then + none[#none + 1] = it.id + elseif err == "unreachable" or err == "not_paired" or code == 401 or code == 403 then + break + end + end + return { got = got, none = none } +end + +--- A book's file straight into `path`. BookOrbit's download doesn't continue a part +--- (no Range), so a part left by an interrupted download is started again. +function BookOrbit:downloadToFile(book_id, path, _resume) + local d, err = detail(self, book_id) + if not d then return false, err end + local f = BookOrbit.pickFile(d) + if not f then return false, "bookorbit_no_file" end + local fh, ferr = io.open(path, "wb") + if not fh then return false, ferr end + local headers = self:authHeaders() + headers["Accept"] = "*/*" + -- (the address the server gave for this file; only ever on the signed-in server) + local where = f.downloadUrl:sub(1, 1) == "/" and f.downloadUrl or (BookOrbit.CATALOG .. "/files/" .. tostring(f.id) .. "/download") + local code, _, resp, status = Api.rawRequest("GET", self.store.server .. where, { + headers = headers, + sink = require("gzreader_xferlog").sink(ltn12.sink.file(fh), "book " .. tostring(book_id)), + timeouts = { 30, -1 }, + }) + if code == 200 then + local want = type(resp) == "table" and tonumber(resp["content-length"]) + local have = lfs.attributes(path, "size") or 0 + if have > 0 and (not want or want == have) then return true end + os.remove(path) + return false, "stalled: " .. tostring(have) .. " of " .. tostring(want) .. " bytes" + end + os.remove(path) + return false, code and ("http_" .. code) or tostring(status or "unreachable") +end + +---------------------------------------------------------------- not yet + +-- Grimmory-only (its single sign-on, its web list) or not sent to BookOrbit yet: each +-- answers nil, "unsupported". Main and the sync modules don't call them while +-- `books_only` is set; this is so a call that slips through fails quietly. +for _i, name in ipairs{ "listWebBooks", "listMyShelves", "setBookShelves", "listAuthors", "listSeries", "putProgress", + "audiobookInfo", "downloadAudio", "listBookmarks", "createBookmark", "deleteBookmark", "listAnnotations", + "createAnnotation", "updateAnnotation", "deleteAnnotation", "listBookNotes", "createBookNote", "updateBookNote", + "deleteBookNote", "putRating", "postSession", "hasSession", "publicSettings", "oidcExchange" } do + BookOrbit[name] = function() return nil, "unsupported" end +end + +return BookOrbit diff --git a/plugins/gzreader.koplugin/gzreader_browser.lua b/plugins/gzreader.koplugin/gzreader_browser.lua index 3d45be739..c1ac67114 100644 --- a/plugins/gzreader.koplugin/gzreader_browser.lua +++ b/plugins/gzreader.koplugin/gzreader_browser.lua @@ -255,6 +255,12 @@ local function hostOf(server) return type(server) == "string" and (server:gsub("^https?://", ""):gsub("/+$", "")) or "?" end +--- The book server's name, as shown: "Grimmory", or "BookOrbit" when signed in to that. +function Browser.serverName(self) + local p = type(self) == "table" and self.plugin + return type(p) == "table" and type(p.serverName) == "function" and p:serverName() or "Grimmory" +end + --- The Grimmory card (last in the Books and Audiobooks pages' bookcase, as --- Plex's is on the Music page): who you are, or that you aren't signed in. function Browser:grimmoryItem(gz_id) @@ -265,7 +271,7 @@ function Browser:grimmoryItem(gz_id) else sub = (store.server and store.username) and _("signed out") or _("not signed in") end - return { gz_id = gz_id, gz_kind = "section", gz_contents = "none", text = _("Grimmory"), mandatory = sub, + return { gz_id = gz_id, gz_kind = "section", gz_contents = "none", text = Browser.serverName(self), mandatory = sub, callback = function() self:openGrimmory() end } end @@ -296,12 +302,13 @@ function Browser.grimmoryItems(self) local function account() return T(_("%1 · %2"), store.username or "?", hostOf(store.server)) end local items = {} local function add(text, icon, fn) items[#items + 1] = { text = text, gz_icon = icon, callback = fn } end + local orbit = type(plugin.backend) == "function" and plugin:backend() == "bookorbit" if Browser.signedIn(self) then items[1] = { text = _("Signed in"), mandatory = account(), gz_icon = "name:settings_account_outline", select_enabled = false } add(_("Rebuild library"), "refresh", function() plugin:rebuildLibrary() end) if not usb then add(_("Reconnect with QR code"), "send", function() plugin:onGrimmoryPair() end) - add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin() end) + add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin(nil, orbit and "bookorbit" or nil) end) end elseif usb then -- (a Kindle without Wi-Fi signs in through the sync page) @@ -312,8 +319,17 @@ function Browser.grimmoryItems(self) mandatory = (store.server and store.username) and account() or nil, gz_icon = "name:settings_account_outline", select_enabled = false } add(_("Connect with QR code"), "send", function() plugin:onGrimmoryPair() end) - add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin() end) + add(_("Connect by typing"), "keyboard", function() plugin:keyboardLogin(nil, orbit and "bookorbit" or nil) end) add(_("Copy from another GZreader"), "copy", function() require("gzreader_copy").receive(plugin, { only = "grimmory" }) end) + if orbit then + add(_("Connect to Grimmory by typing"), "keyboard", function() plugin:keyboardLogin(nil, "grimmory") end) + elseif type(plugin.backend) == "function" then + add(_("Connect to BookOrbit by typing"), "keyboard", function() plugin:keyboardLogin(nil, "bookorbit") end) + end + end + if orbit then + items[#items + 1] = Rows.about(_("About BookOrbit"), T(_("BookOrbit is your book server: the Catalog's books come from it. For now you can browse and download them; reading progress, highlights, bookmarks and audiobooks aren't synced with BookOrbit yet.\n\nSign in with the %1 sync user name and password you made in BookOrbit (Settings → %1), not your website sign-in.\n\nRebuild library: BookOrbit's list of books fetched again, when the Catalog is missing books or shows old ones."), "KOReader")) + return Rows.mark(items) end items[#items + 1] = Rows.about(_("About Grimmory"), usb and _("Grimmory is your book server. This Kindle has no Wi-Fi: sign in on the sync page on a computer, then sync. Books, progress and shelves come and go with each sync.") @@ -322,7 +338,7 @@ function Browser.grimmoryItems(self) end function Browser:openGrimmory() - self:push(_("Grimmory"), Browser.grimmoryItems(self)) + self:push(Browser.serverName(self), Browser.grimmoryItems(self)) end --- Signed in (or out) while the Catalog is open: its page again, from the top. @@ -339,7 +355,7 @@ function Browser:bookItems() if not Browser.signedIn(self) then return Browser.signedOutItems(self, "books") end return { gz_root = true, - { gz_id = "search", gz_action = "search", text = _("Search Grimmory…"), callback = function() self:promptSearch() end }, + { gz_id = "search", gz_action = "search", text = T(_("Search %1…"), Browser.serverName(self)), callback = function() self:promptSearch() end }, { gz_id = "continue", text = _("Continue reading"), callback = function() self:openSimple("continue-reading", _("Continue reading")) end }, { gz_id = "recent", text = _("Recently added"), callback = function() self:openSimple("recently-added", _("Recently added")) end }, { gz_id = "all", text = _("All books"), callback = function() self:openPaged(_("All books"), { sort = "title", dir = "asc" }) end }, @@ -940,7 +956,7 @@ function Browser:openPaged(title, params, with_series_number, opts) or (opts.audio and Browser.audioScope()) or nil header = { { gz_action = "search", - text = scoped and T(_("Search in %1…"), title) or (opts.audio and _("Search audiobooks…") or _("Search Grimmory…")), + text = scoped and T(_("Search in %1…"), title) or (opts.audio and _("Search audiobooks…") or T(_("Search %1…"), Browser.serverName(self))), callback = function() self:promptSearch(scope) end, } } end @@ -1162,7 +1178,7 @@ end function Browser:promptSearch(scope, text) local dialog dialog = InputDialog:new{ - title = scope and T(_("Search in %1"), scope.title) or _("Search Grimmory"), + title = scope and T(_("Search in %1"), scope.title) or T(_("Search %1"), Browser.serverName(self)), input = text, input_hint = _("Title, author or series"), buttons = {{ diff --git a/plugins/gzreader.koplugin/gzreader_changelog.lua b/plugins/gzreader.koplugin/gzreader_changelog.lua index 330df6a81..e7c423556 100644 --- a/plugins/gzreader.koplugin/gzreader_changelog.lua +++ b/plugins/gzreader.koplugin/gzreader_changelog.lua @@ -6,6 +6,12 @@ -- on one line (the beta branch combines "next" lines). A plain string is the -- text alone (the screen shows its first sentence). return { + { + version = "next", + changes = { + { short = "BookOrbit can be the book server instead of Grimmory (first part: browse and download)", text = "GZreader can now sign in to a BookOrbit server instead of Grimmory. Choose BookOrbit under Book server on the setup page, or Settings → Accounts and services → Books → Connect to BookOrbit by typing, and give BookOrbit's address and the KOReader sync user name and password you made in BookOrbit (Settings → KOReader; not your website sign-in). The Catalog then shows BookOrbit's books: all books, libraries, collections as shelves, SmartScopes as magic shelves, authors, series and search, with covers, and you can download books and have a collection download by itself. This is the first part: reading progress, highlights, bookmarks, statistics and audiobooks aren't sent to BookOrbit yet, so GZreader only reads from it. A Kindle is signed in to one book server at a time: the books downloaded from the other one stay on the Kindle but leave the Downloads tab until you sign in to it again. The password is never stored (only its MD5, which is what BookOrbit's e-reader sign-in uses, kept on the Kindle's own disk), and nothing of the sign-in is logged." }, + }, + }, { version = "1.35.0", changes = { diff --git a/plugins/gzreader.koplugin/gzreader_copy.lua b/plugins/gzreader.koplugin/gzreader_copy.lua index d7cc324dd..b5ebcb470 100644 --- a/plugins/gzreader.koplugin/gzreader_copy.lua +++ b/plugins/gzreader.koplugin/gzreader_copy.lua @@ -109,7 +109,7 @@ end --- What this device could send, without anything secret (shown on the other). function Copy.offer(plugin) local store, out = plugin.store, { name = Copy.deviceName(plugin) } - if plugin.api and plugin.api:isPaired() then + if plugin.api and plugin.api:isPaired() and not plugin.api.books_only then out.grimmory = { host = host(store.server), username = store.username } end local ms = store.memos or {} @@ -135,7 +135,7 @@ end function Copy.payload(plugin, want) local store, out = plugin.store, {} want = type(want) == "table" and want or {} - if want.grimmory and plugin.api and plugin.api:isPaired() then + if want.grimmory and plugin.api and plugin.api:isPaired() and not plugin.api.books_only then -- (the address and account: Grimmory's sign-in stays on this device) out.grimmory = { server = store.server, username = store.username } end @@ -548,7 +548,7 @@ end function Copy.defaults(plugin, offer, only) local store = plugin.store local has = { - grimmory = plugin.api and plugin.api:isPaired(), + grimmory = plugin.api and plugin.api:isPaired() and not plugin.api.books_only, memos = (store.memos or {}).token ~= nil, caldav = (store.caldav or {}).password ~= nil, } diff --git a/plugins/gzreader.koplugin/gzreader_covers.lua b/plugins/gzreader.koplugin/gzreader_covers.lua index 898fa95af..beb242265 100644 --- a/plugins/gzreader.koplugin/gzreader_covers.lua +++ b/plugins/gzreader.koplugin/gzreader_covers.lua @@ -38,8 +38,17 @@ function Covers.notePlex(id, thumb) if id and thumb then Covers.plex_thumbs[tostring(id)] = thumb end end +--- Covers are kept by book id, and each book server has its own ids: BookOrbit's +--- are in their own folder (space = "bookorbit"; nil: Grimmory's, as before). +function Covers.useSpace(space) + space = space and ("-" .. space) or "" + if space == (Covers.space or "") then return end + Covers.space, Covers.dir_ok = space, nil + Covers.memory = {} -- (the shrunk ones in memory are the other server's books) +end + function Covers.dir() - local dir = DataStorage:getDataDir() .. "/cache/gzreader-covers" + local dir = DataStorage:getDataDir() .. "/cache/gzreader-covers" .. (Covers.space or "") if not Covers.dir_ok then lfs.mkdir(DataStorage:getDataDir() .. "/cache") lfs.mkdir(dir) diff --git a/plugins/gzreader.koplugin/gzreader_grimstats.lua b/plugins/gzreader.koplugin/gzreader_grimstats.lua index bf9c286b7..47d24ccb3 100644 --- a/plugins/gzreader.koplugin/gzreader_grimstats.lua +++ b/plugins/gzreader.koplugin/gzreader_grimstats.lua @@ -75,7 +75,7 @@ end --- Fetch them if they're old (and Wi-Fi is on): Home redraws when they change. function GS.refresh(plugin, force) - if GS.busy or not (plugin.api and plugin.api:isPaired()) then return end + if GS.busy or not (plugin.api and plugin.api:isPaired()) or plugin.api.books_only then return end local cached = plugin.store.grimmory_stats if not force and cached and os.time() - (tonumber(cached.at) or 0) < GS.TTL then return end local NetworkMgr = require("ui/network/manager") diff --git a/plugins/gzreader.koplugin/gzreader_index.lua b/plugins/gzreader.koplugin/gzreader_index.lua index 291b8fd91..cf4b3bbcf 100644 --- a/plugins/gzreader.koplugin/gzreader_index.lua +++ b/plugins/gzreader.koplugin/gzreader_index.lua @@ -91,6 +91,10 @@ local function collect(api, report) page = page + 1 report(page, pages) end + -- (a server whose book lists don't say each book's library, BookOrbit, counts them itself) + if next(libraries) == nil and type(api.libraryCounts) == "function" then + libraries = api:libraryCounts() or libraries + end -- Subtitles: only Grimmory's web book list has them. Optional (older -- servers may not have /books/page); failures just leave them out. local subtitles = {} diff --git a/plugins/gzreader.koplugin/gzreader_pairpage.lua b/plugins/gzreader.koplugin/gzreader_pairpage.lua index ca1569027..b7cdff352 100644 --- a/plugins/gzreader.koplugin/gzreader_pairpage.lua +++ b/plugins/gzreader.koplugin/gzreader_pairpage.lua @@ -156,10 +156,14 @@ local function grimmorySection(st, base) local g = st.grimmory or {} local parts = { '

Grimmory

', '

Your book library: browse and download books on the Kindle, reading progress kept in sync.

' } + local orbit = g.backend == "bookorbit" if g.connected then - parts[#parts + 1] = status(true, "Connected as " .. esc(g.username) .. " · " .. esc(g.host)) + parts[#parts + 1] = status(true, (orbit and "Connected to BookOrbit as " or "Connected as ") .. esc(g.username) .. " · " .. esc(g.host)) + if orbit then + parts[#parts + 1] = '

With BookOrbit you can browse and download your books. Reading progress, highlights and bookmarks aren\'t sent to BookOrbit yet.

' + end parts[#parts + 1] = form(base .. "/grimmory/disconnect", - '", "Disconnecting…") parts[#parts + 1] = "
Sign in again or with another account
" else @@ -188,8 +192,15 @@ local function grimmorySection(st, base) else body = pw end + -- which book server: Grimmory (the default) or BookOrbit (its KOReader sync user; no single sign-on) + local picked = (g.form or {}).backend or g.backend + local which = '" + .. '

BookOrbit: use the KOReader sync user name and password from BookOrbit\'s Settings → KOReader (not your website sign-in). ' + .. "For now: browse and download books; nothing is synced back yet.

" parts[#parts + 1] = form(base .. "/grimmory", - input("g_server", "server", "Grimmory address", (g.form or {}).server, 'required placeholder="https://books.example.com or 192.168.1.20:6060" ' .. URL_ATTRS) + which .. input("g_server", "server", "Server address", (g.form or {}).server, 'required placeholder="https://books.example.com or 192.168.1.20:6060" ' .. URL_ATTRS) .. body, "Connecting…") if g.connected then parts[#parts + 1] = "
" end parts[#parts + 1] = "
" diff --git a/plugins/gzreader.koplugin/gzreader_phone.lua b/plugins/gzreader.koplugin/gzreader_phone.lua index e02ce16ab..5af6ded41 100644 --- a/plugins/gzreader.koplugin/gzreader_phone.lua +++ b/plugins/gzreader.koplugin/gzreader_phone.lua @@ -107,7 +107,7 @@ local function state(S, flash) local st = { base = S.base, flash = flash.text and { ok = flash.ok, text = flash.text } or nil } -- Grimmory local store = plugin.store - local g = { connected = plugin.api and plugin.api:isPaired() or false, username = store.username, + local g = { connected = plugin.api and plugin.api:isPaired() or false, username = store.username, backend = plugin:backend(), host = host(store.server) } g.redirect_uri, g.sso_relay = Phone.ssoRedirect(plugin, S.origin) g.form = sec == "grimmory" and flash.form @@ -389,7 +389,7 @@ function Phone.open(plugin, opts) if cached ~= nil then return cached end local srv = Api.normalizeServer(server_input) if not srv then return nil end - local base, settings = plugin.api:publicSettings(srv) + local base, settings = plugin:clientFor("grimmory"):publicSettings(srv) if not base or type(settings) ~= "table" then return nil end local info = false if settings.oidcEnabled == true then @@ -408,14 +408,15 @@ function Phone.open(plugin, opts) end local function grimmoryFailed(form, err) if failedLogin() then return 200, "text/html", PairPage.gone() end - return back({ section = "grimmory", error = err, form = { server = form.server, username = form.username } }) + return back({ section = "grimmory", error = err, form = { server = form.server, username = form.username, backend = form.backend } }) end local function startSso(form) local srv = Api.normalizeServer(form.server or "") if not srv then return grimmoryFailed(form, _("Enter your Grimmory address first.")) end - plugin.api.explicit_https = (form.server or ""):match("^%s*https://") ~= nil - local base, settings = plugin.api:publicSettings(srv) + local client = plugin:clientFor("grimmory") -- (single sign-on is Grimmory's) + client.explicit_https = (form.server or ""):match("^%s*https://") ~= nil + local base, settings = client:publicSettings(srv) if not base then return grimmoryFailed(form, plugin:describeError(settings)) end local pd = type(settings.oidcProviderDetails) == "table" and settings.oidcProviderDetails or {} if settings.oidcEnabled ~= true or not Api.str(pd.clientId) or not Api.str(pd.issuerUri) then @@ -455,15 +456,15 @@ function Phone.open(plugin, opts) return 200, "text/html", PairPage.gone() end S.sso = nil -- single use - local previous = { plugin.store.server, plugin.store.username } - local ok, err = plugin.api:oidcExchange(session.base, { + local previous = plugin:signedInAs() + local ok, err = plugin:clientFor("grimmory"):oidcExchange(session.base, { code = params.code, code_verifier = session.verifier, redirect_uri = session.redirect_uri, nonce = session.nonce, state = session.state, }, Phone.originOf(session.redirect_uri)) if ok then Log.info("sso: signed in as", tostring(plugin.store.username), session.relay and "(hand-off page)" or "(this Kindle's address)") if not session.relay then plugin.store.sso_direct_ok = true end - plugin:afterLogin(previous) + plugin:afterLogin(previous, "grimmory") return grimmoryOk() end Log.warn("sso: exchange failed:", tostring(err)) @@ -472,8 +473,11 @@ function Phone.open(plugin, opts) local routes = {} routes["/grimmory"] = function(form) - if form.action == "sso" then return startSso(form) end - local ok, err = plugin:connect(form.server or "", form.username or "", form.password or "") + if form.action == "sso" and form.backend ~= "bookorbit" then return startSso(form) end + if form.action == "sso" and form.backend == "bookorbit" then + return grimmoryFailed(form, T(_("BookOrbit is signed in to with its %1 sync user name and password, not single sign-on."), "KOReader")) + end + local ok, err = plugin:connect(form.server or "", form.username or "", form.password or "", form.backend) if ok then return grimmoryOk() end return grimmoryFailed(form, err) end @@ -482,8 +486,8 @@ function Phone.open(plugin, opts) pcall(plugin.api.logout, plugin.api) plugin.api:clearTokens() S.changes.grimmory = true - Log.info("phone: disconnected from Grimmory") - toast(_("Disconnected from Grimmory.")) + Log.info("phone: disconnected from", plugin:serverName()) + toast(T(_("Disconnected from %1."), plugin:serverName())) return back({ ok = true, text = _("Disconnected from Grimmory. Downloaded books stay on the Kindle."), section = "grimmory" }) end -- Plex: its own sign-in page (a "strong" PIN), then back here diff --git a/plugins/gzreader.koplugin/gzreader_secrets.lua b/plugins/gzreader.koplugin/gzreader_secrets.lua index a09bf0f31..eef41e7c9 100644 --- a/plugins/gzreader.koplugin/gzreader_secrets.lua +++ b/plugins/gzreader.koplugin/gzreader_secrets.lua @@ -7,7 +7,7 @@ state (settings/gzreader.lua, and gzreader_recent.lua between full saves) held the sign-ins in it: the CalDAV password, the Home Assistant, Memos and Plex tokens, the Immich key, the Access key and Cloudflare token, the handwriting services' keys (Claude, OpenAI-style), Grimmory's -sign-in tokens and the calendar links (their keys are in the address). +sign-in tokens, BookOrbit's sign-in key and the calendar links (their keys are in the address). Those (PATHS, and each calendar link's url) are kept in SECRET_FILE on the Kindle's own disk instead (/var/local: not shared over USB), and every save @@ -35,6 +35,7 @@ local Secrets = { -- { key, key, … } inside the state PATHS = { { "refresh_token" }, { "access_token" }, + { "bookorbit", "key" }, { "caldav", "password" }, { "memos", "token" }, { "plex", "token" }, { "plex", "server", "token" }, diff --git a/plugins/gzreader.koplugin/gzreader_shelves.lua b/plugins/gzreader.koplugin/gzreader_shelves.lua index 7c75c2429..d0c59862d 100644 --- a/plugins/gzreader.koplugin/gzreader_shelves.lua +++ b/plugins/gzreader.koplugin/gzreader_shelves.lua @@ -306,7 +306,7 @@ end local function online(plugin) local api = plugin.api - if type(api) ~= "table" or api.offline or not api:isPaired() then return false end + if type(api) ~= "table" or api.offline or api.books_only or not api:isPaired() then return false end local ok, NetworkMgr = pcall(require, "ui/network/manager") return ok and NetworkMgr:isConnected() and true or false end @@ -409,6 +409,10 @@ end function Shelves.ready(plugin) local _ = require("gettext") local api = plugin.api + if type(api) == "table" and api.books_only then + info(_("Putting books on shelves isn't available with BookOrbit yet."), 4) + return false + end if type(api) == "table" and api:isPaired() then return true end if type(api) == "table" and api.offline then info(_("Sign in to Grimmory to continue: plug this Kindle into a computer and sync with the sync page (Settings → General → Transfer → Sync through a computer)."), 6) diff --git a/plugins/gzreader.koplugin/gzreader_storage.lua b/plugins/gzreader.koplugin/gzreader_storage.lua index 6fbdec4bc..c36695145 100644 --- a/plugins/gzreader.koplugin/gzreader_storage.lua +++ b/plugins/gzreader.koplugin/gzreader_storage.lua @@ -200,7 +200,7 @@ function Storage.measure(plugin) out.notes = Storage.notes(data_dir, settings_dir) out.calendar = { bytes = fileSize(settings_dir .. "/gzreader-calendar.json") } local caches = fileSize(settings_dir .. "/gzreader_index.json") + fileSize(settings_dir .. "/bookinfo_cache.sqlite3") - for _i, d in ipairs({ "gzreader-thumbs", "gzreader-lists", "gzreader-covers", "gz-covers", "gzreader-update" }) do + for _i, d in ipairs({ "gzreader-thumbs", "gzreader-lists", "gzreader-covers", "gzreader-covers-bookorbit", "gz-covers", "gzreader-update" }) do caches = caches + (Storage.dirSize(data_dir .. "/cache/" .. d)) end out.caches = { bytes = caches } diff --git a/plugins/gzreader.koplugin/gzreader_sync.lua b/plugins/gzreader.koplugin/gzreader_sync.lua index 44355216a..73885f147 100644 --- a/plugins/gzreader.koplugin/gzreader_sync.lua +++ b/plugins/gzreader.koplugin/gzreader_sync.lua @@ -425,7 +425,7 @@ end function Sync:canTalk() -- (syncing through a computer: the library copy has the other devices' places) - return self.api:isPaired() and (NetworkMgr:isConnected() or self.api.offline == true) + return self.api:isPaired() and not self.api.books_only and (NetworkMgr:isConnected() or self.api.offline == true) end --- Grimmory's progress fields of a book (what a download keeps for the diff --git a/plugins/gzreader.koplugin/main.lua b/plugins/gzreader.koplugin/main.lua index 892f12662..f176fa1fb 100644 --- a/plugins/gzreader.koplugin/main.lua +++ b/plugins/gzreader.koplugin/main.lua @@ -194,6 +194,7 @@ function Grimmory:init() self.store.pending.ratings = self.store.pending.ratings or {} Log.enabled = self.store.logging_disabled ~= true self.api = Api:new(self.store, function() self:save() end) + if self.store.backend == "bookorbit" then self:useBackend("bookorbit") end -- no Wi-Fi (Kindle 2, DX): Grimmory through a computer, the library -- from the copy the sync page left (gzreader_usbsync.lua) local Usb = require("gzreader_usbsync") @@ -488,7 +489,7 @@ do end function Grimmory:syncEnabled() - return self.store.sync_disabled ~= true and self.api:isPaired() + return self.store.sync_disabled ~= true and self.api:isPaired() and not self:booksOnly() end -- exit: the next save is a whole one, and there is one if only the recent part @@ -577,6 +578,7 @@ function Grimmory:menuItems() { text_func = function() if self.api:isPaired() then + if self:backend() == "bookorbit" then return T(_("Connected to BookOrbit as %1"), self.store.username or "?") end return T(_("Connected as %1"), self.store.username or "?") end return _("Not connected") @@ -643,6 +645,11 @@ function Grimmory:menuItems() text = _("Connect by typing"), callback = function() self:keyboardLogin() end, }, + { + text = _("Connect to BookOrbit by typing"), + help_text = T(_("BookOrbit instead of Grimmory as this Kindle's book server. It asks for BookOrbit's address and the %1 sync user name and password (BookOrbit: Settings → %1). For now you can browse and download your books; reading progress, highlights and bookmarks aren't sent to BookOrbit yet."), "KOReader"), + callback = function() self:keyboardLogin(nil, "bookorbit") end, + }, { text = _("Single sign-on (SSO)"), sub_item_table_func = function() return self:ssoMenu() end, @@ -849,6 +856,13 @@ local ERRORS = { bad_credentials = _("Wrong username or password."), rate_limited = _("Too many attempts. Wait a minute and try again."), usb = _("This Kindle syncs with Grimmory through a computer: Menu → Sync with computer."), + -- (the name goes in as an argument: gettext.lua turns "KOReader" in a message into "GZreader") + bookorbit_credentials = T(_("Wrong user name or password. BookOrbit wants the %1 sync user name and password (BookOrbit: Settings → %1), not the ones you sign in to its website with. Also check that the address is BookOrbit's."), "KOReader"), + bookorbit_sync_off = T(_("BookOrbit has sync switched off for this %1 user. Switch it on in BookOrbit: Settings → %1."), "KOReader"), + bookorbit_refused = T(_("BookOrbit didn't accept this Kindle's sign-in. If you changed the %1 sync password in BookOrbit, connect again."), "KOReader"), + bookorbit_not_found = _("That address answered, but not as BookOrbit (or its BookOrbit is too old for e-readers). Check the address."), + bookorbit_no_file = _("BookOrbit has no file for this book that this Kindle can open."), + unsupported = _("That isn't available with BookOrbit yet."), no_https = require("gzreader_lan").noHttpsText(), } @@ -858,11 +872,36 @@ function Grimmory:describeError(err) return T(_("The download stalled (%1). Check the Kindle's Wi-Fi signal and try again."), err:gsub("^stalled:%s*", "")) end if type(err) == "string" and err:match("^http_") then - return T(_("Grimmory returned an error (%1)."), err:sub(6)) + return T(_("%1 returned an error (%2)."), self:serverName(), err:sub(6)) end return T(_("Something went wrong: %1"), tostring(err)) end +--- Which book server this Kindle is signed in to: "grimmory" (the default) or "bookorbit". +function Grimmory:backend() + return self.store.backend == "bookorbit" and "bookorbit" or "grimmory" +end + +function Grimmory:serverName() + return self:backend() == "bookorbit" and "BookOrbit" or "Grimmory" +end + +--- Make plugin.api the client for that server. The same table keeps being the +--- client (every part of GZreader that holds it follows): only its class changes. +function Grimmory:useBackend(name) + name = name == "bookorbit" and "bookorbit" or "grimmory" + self.store.backend = name == "bookorbit" and "bookorbit" or nil + if self.api.offline then return end -- (syncing through a computer: Grimmory's copy) + setmetatable(self.api, name == "bookorbit" and require("gzreader_bookorbit") or Api) + pcall(function() require("gzreader_covers").useSpace(name == "bookorbit" and "bookorbit" or nil) end) +end + +--- With BookOrbit, only the books so far (browse, covers, download): nothing is +--- synced to it yet (gzreader_bookorbit.lua). +function Grimmory:booksOnly() + return self.api.books_only == true +end + function Grimmory:exportLog() local lib = self:libraryDir() local dest_dir = lib:match("^(.+)/[^/]+$") or lib -- next to the library, not in it @@ -1159,28 +1198,66 @@ end ---------------------------------------------------------------- pairing --- Log in. Returns ok, err. -function Grimmory:connect(server_input, username, password) +function Grimmory:connect(server_input, username, password, backend) + backend = backend == "bookorbit" and "bookorbit" or "grimmory" local server = Api.normalizeServer(server_input) if not server then return false, _("That server address doesn't look right.") end username = (username or ""):gsub("^%s+", ""):gsub("%s+$", "") if username == "" or not password or password == "" then return false, _("Enter your username and password.") end - local previous = { self.store.server, self.store.username } - self.api.explicit_https = server_input:match("^%s*https://") ~= nil - local ok, err = self.api:login(server, username, password) - Log.info("password login to", ok and self.store.server or server, ok and "ok" or ("failed: " .. tostring(err))) + local previous = self:signedInAs() + local client = self:clientFor(backend) + client.explicit_https = server_input:match("^%s*https://") ~= nil + local ok, err = client:login(server, username, password) + Log.info(backend == "bookorbit" and "BookOrbit sign-in to" or "password login to", ok and self.store.server or server, + ok and "ok" or ("failed: " .. tostring(err))) if not ok then return false, self:describeError(err) end - self:afterLogin(previous) + self:afterLogin(previous, backend) return true end ---- Bookkeeping after any successful login. `previous` = { server, username } ---- from before the login. -function Grimmory:afterLogin(previous) - if type(previous) ~= "table" or previous[1] ~= self.store.server or previous[2] ~= self.store.username then - -- Different server/account: queued data belongs to the old one. +--- What this Kindle is signed in to, to compare after a sign-in (afterLogin). +function Grimmory:signedInAs() + return { self.store.server, self.store.username, self:backend() } +end + +--- The client to sign in to that book server with: plugin.api if it is that server's, +--- or one of its own (a sign-in that fails then leaves this Kindle as it was). +function Grimmory:clientFor(backend) + backend = backend == "bookorbit" and "bookorbit" or "grimmory" + if backend == self:backend() or self.api.offline then return self.api end + return (backend == "bookorbit" and require("gzreader_bookorbit") or Api):new(self.store, self.api.on_change) +end + +--- Bookkeeping after any successful login. `previous` = signedInAs() from before +--- the login; `backend`: the book server it was (nil: the one in use). +function Grimmory:afterLogin(previous, backend) + backend = backend or self:backend() + if backend ~= self:backend() then + if self.sync then pcall(self.sync.onLeave, self.sync) end + if backend ~= "bookorbit" then self.store.bookorbit = nil end + self:useBackend(backend) + end + if type(previous) ~= "table" or previous[1] ~= self.store.server or previous[2] ~= self.store.username + or (previous[3] or "grimmory") ~= self:backend() then + -- Different server/account: queued data belongs to the old one, and so do + -- the saved lists and the library index (book ids mean other books there). self.store.pending = { progress = {}, sessions = {}, ratings = {} } + local was = type(previous) == "table" and previous[3] or "grimmory" + if was ~= self:backend() then + -- The other server's books: its ids mean other books here, so the list of + -- its downloads is put aside (the files stay in the books folder) and comes + -- back if this Kindle signs in to it again; the saved lists go. + local other = self.store.downloads_other or {} + other[was] = self.store.downloads + self.store.downloads = other[self:backend()] or {} + other[self:backend()] = nil + self.store.downloads_other = other + pcall(self.writeManifest, self) + pcall(function() require("gzreader_listcache").clear() end) + Log.info("book server changed:", was, "->", self:backend()) + end self:save() end self:flushPending() @@ -1196,6 +1273,11 @@ function Grimmory:onGrimmoryPair(touchmenu) return true end +function Grimmory:onBookOrbitKeyboardLogin() + self:keyboardLogin(nil, "bookorbit") + return true +end + function Grimmory:onGrimmoryKeyboardLogin() self:keyboardLogin() return true @@ -1512,21 +1594,25 @@ end function Grimmory:announceConnected() UIManager:show(InfoMessage:new{ - text = T(_("Connected to Grimmory as %1."), self.store.username or "") .. "\n\n" - .. _("Reading progress syncs automatically for books you download from Grimmory."), + text = T(_("Connected to %1 as %2."), self:serverName(), self.store.username or "") .. "\n\n" + .. (self:booksOnly() and _("You can browse and download your books. Reading progress, highlights and bookmarks aren't sent to BookOrbit yet.") + or _("Reading progress syncs automatically for books you download from Grimmory.")), }) end --- prefill = { server, username } (copied from another GZreader), or the saved ones. -function Grimmory:keyboardLogin(prefill) +function Grimmory:keyboardLogin(prefill, backend) prefill = type(prefill) == "table" and prefill or {} + backend = backend == "bookorbit" and "bookorbit" or "grimmory" + local same = backend == self:backend() -- (the saved address and name are that server's) local dialog dialog = MultiInputDialog:new{ - title = _("Connect to Grimmory"), + title = backend == "bookorbit" and _("Connect to BookOrbit") or _("Connect to Grimmory"), fields = { - { text = prefill.server or self.store.server or "", hint = _("Server, e.g. https://books.example.com") }, - { text = prefill.username or self.store.username or "", hint = _("Username") }, - { text = "", hint = _("Password"), text_type = "password" }, + { text = prefill.server or (same and self.store.server) or "", hint = _("Server, e.g. https://books.example.com") }, + { text = prefill.username or (same and self.store.username) or "", + hint = backend == "bookorbit" and T(_("%1 sync user name (BookOrbit: Settings → %1)"), "KOReader") or _("Username") }, + { text = "", hint = backend == "bookorbit" and T(_("%1 sync password"), "KOReader") or _("Password"), text_type = "password" }, }, buttons = {{ { text = _("Cancel"), id = "close", callback = function() UIManager:close(dialog) end }, @@ -1537,7 +1623,7 @@ function Grimmory:keyboardLogin(prefill) local msg = InfoMessage:new{ text = _("Connecting…"), timeout = 0 } UIManager:show(msg) UIManager:forceRePaint() - local ok, err = self:connect(f[1], f[2], f[3]) + local ok, err = self:connect(f[1], f[2], f[3], backend) UIManager:close(msg) if ok then self:announceConnected() @@ -1554,13 +1640,13 @@ end function Grimmory:confirmDisconnect() UIManager:show(ConfirmBox:new{ - text = _("Disconnect this Kindle from Grimmory? Downloaded books stay on the Kindle. Progress sync will stop until you connect again."), + text = T(_("Disconnect this Kindle from %1? Downloaded books stay on the Kindle. Progress sync will stop until you connect again."), self:serverName()), ok_text = _("Disconnect"), ok_callback = function() if self.sync then self.sync:onLeave() end NetworkMgr:runWhenConnected(function() self.api:logout() end) self.api:clearTokens() - UIManager:show(InfoMessage:new{ text = _("Disconnected from Grimmory."), timeout = 3 }) + UIManager:show(InfoMessage:new{ text = T(_("Disconnected from %1."), self:serverName()), timeout = 3 }) end, }) end @@ -1572,6 +1658,7 @@ Grimmory.gone_books = {} -- book ids Grimmory answered "not found" for (this run function Grimmory:queue(kind, book_id, body) local pending = self.store.pending + if self:booksOnly() then return end -- (nothing is sent to BookOrbit yet: nothing is kept to send) if kind == "progress" and Grimmory.gone_books[tostring(book_id)] then return end if kind == "progress" then pending.progress[tostring(book_id)] = body @@ -1590,7 +1677,7 @@ end --- Send progress and reading sessions queued while offline. In the --- background (gzreader_async): sending a backlog can take many seconds. function Grimmory:flushPending() - if self.flushing or not self.api:isPaired() or not NetworkMgr:isConnected() then return end + if self.flushing or not self.api:isPaired() or self:booksOnly() or not NetworkMgr:isConnected() then return end local pending = self.store.pending pending.ratings = pending.ratings or {} if next(pending.progress) == nil and #pending.sessions == 0 and next(pending.ratings) == nil then return end @@ -2154,7 +2241,7 @@ function Grimmory:writeManifest() end end local f = io.open(dir .. "/" .. MANIFEST, "wb") - if f then f:write(JSON.encode({ version = 1, books = list })); f:close() end + if f then f:write(JSON.encode({ version = 1, backend = self:backend(), books = list })); f:close() end end --- Merge the backup list into the settings (after an update wiped them). @@ -2165,7 +2252,9 @@ function Grimmory:restoreFromManifest() local ok, data = pcall(JSON.decode, f:read("*a")) f:close() local restored = 0 - if ok and type(data) == "table" and type(data.books) == "table" then + -- (a list from the other book server isn't this one's: its ids are other books here) + if ok and type(data) == "table" and type(data.books) == "table" + and (type(data.backend) == "string" and data.backend or "grimmory") == self:backend() then for _, b in ipairs(data.books) do local id = b.id and tostring(b.id) local path = type(b.file) == "string" and (dir .. "/" .. b.file) @@ -2395,7 +2484,7 @@ end --- Downloads from before 1.22.4: ask Grimmory for their authors (in the --- background, while Wi-Fi is on anyway; 40 at a time; each book once). function Grimmory:backfillAuthors() - if self.backfilling or not self.api:isPaired() or not Net.connected() then return end + if self.backfilling or not self.api:isPaired() or self:booksOnly() or not Net.connected() then return end local ids = {} for id, e in pairs(self.store.downloads or {}) do if type(e) == "table" and e.authors == nil and not e.authors_asked and tonumber(id) then diff --git a/tools/gzreader/emulator/bookorbit_browse.lua b/tools/gzreader/emulator/bookorbit_browse.lua new file mode 100644 index 000000000..b47d4df8e --- /dev/null +++ b/tools/gzreader/emulator/bookorbit_browse.lua @@ -0,0 +1,83 @@ +-- BookOrbit as the book server (tests/mock_bookorbit.py on 127.0.0.1:18096): +-- sign in with the KOReader sync user, then the Catalog's first page, the +-- libraries, All books and the menu's first line. Prints what each step found. +local s = { start = 16 } +local function add(t) s[#s + 1] = t end +local function plugin() return require("apps/filemanager/filemanager").instance.gzreader end +local function browser() return require("gzreader_browser").current end +add({ fn = function() + local UIManager = require("ui/uimanager") + for i = #UIManager._window_stack, 1, -1 do + local w = UIManager._window_stack[i].widget + if w.name == "setup guide" or w.name == "QR code screen" then UIManager:close(w) end + end +end, after = 6 }) +add({ fn = function(E) + local p = plugin() + local ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "wrong", "bookorbit") + E.say("wrong password:", tostring(ok), tostring(err)) + ok, err = p:connect("http://127.0.0.1:18096", "will-kindle", "hunter22", "bookorbit") + E.say("sign-in:", tostring(ok), tostring(err), "backend", p:backend(), "books only", tostring(p:booksOnly()), + "server", tostring((p.store.bookorbit or {}).server_version)) + p:announceConnected() +end, after = 2 }) +add({ shot = "bookorbit-1-connected" }) +add({ fn = function() + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + plugin():onShowGrimmoryLibrary() +end, after = 12 }) +add({ shot = "bookorbit-2-catalog" }) +add({ fn = function() browser():openLibraries() end, after = 8 }) +add({ fn = function(E) + local m = browser().menu + local names = {} + for _i, it in ipairs(m and m.item_table or {}) do names[#names + 1] = tostring(it.text) .. "=" .. tostring(it.mandatory or it.gz_count) end + E.say("libraries:", table.concat(names, ", ")) +end }) +add({ shot = "bookorbit-3-libraries" }) +add({ fn = function() browser():openPaged("All books", { sort = "title", dir = "asc" }) end, after = 12 }) +add({ fn = function(E) + local m = browser().menu + local names = {} + for _i, it in ipairs(m and m.item_table or {}) do names[#names + 1] = tostring(it.text) end + E.say("all books:", #names, table.concat(names, " | ")) +end }) +add({ shot = "bookorbit-4-all-books" }) +-- a download through the plugin (quietly, as the shelf's auto-download does), then that auto-download +add({ fn = function() + require("gzreader_download").background = true + plugin():downloadAndOpen({ id = 101, title = "The Long Way Round", authors = { "Ada Marsh" }, primaryFileType = "EPUB", + primaryFileName = "The Long Way Round.epub" }, nil) +end, after = 20 }) +add({ fn = function(E) + local e = plugin().store.downloads["101"] + local lfs = require("libs/libkoreader-lfs") + E.say("downloaded 101:", tostring(e and e.path and e.path:match("[^/]+$")), "bytes", tostring(e and lfs.attributes(e.path, "size")), + "file id", tostring(e and e.file_id)) + local SS = require("gzreader_shelfsync") + SS.set(plugin(), { id = 11, name = "Beach reads" }) + SS.run(plugin(), true) +end, after = 25 }) +add({ fn = function(E) + local got = {} + for id, e in pairs(plugin().store.downloads) do got[#got + 1] = id .. "=" .. tostring(e.path and e.path:match("[^/]+$")) end + table.sort(got) + E.say("after the shelf's auto-download:", table.concat(got, ", ")) + local UIManager = require("ui/uimanager") + local top = UIManager._window_stack[#UIManager._window_stack].widget + if top and top.text then UIManager:close(top) end + require("apps/filemanager/filemanager").instance.gzreader:onShowGrimmoryLibrary() +end, after = 8 }) +add({ shot = "bookorbit-5-after-downloads" }) +add({ fn = function(E) + local p = plugin() + E.say("menu:", p:menuItems()[1].text_func(), "| sync:", tostring(p:syncEnabled()), "| covers:", require("gzreader_covers").dir():match("[^/]+$")) + local log = io.open(require("datastorage"):getDataDir() .. "/gzreader.log", "rb") + local text = log and log:read("*a") or "" + if log then log:close() end + E.say("log has the password:", tostring(text:find("hunter22", 1, true) ~= nil), "its MD5:", + tostring(text:find(require("ffi/sha2").md5("hunter22"), 1, true) ~= nil), "x-auth-key:", tostring(text:find("x-auth-key", 1, true) ~= nil)) +end }) +return s diff --git a/tools/gzreader/tests/mock_bookorbit.py b/tools/gzreader/tests/mock_bookorbit.py index 5cfccda38..40444bfb0 100644 --- a/tools/gzreader/tests/mock_bookorbit.py +++ b/tools/gzreader/tests/mock_bookorbit.py @@ -33,12 +33,19 @@ "annotationPendingBooks", "catalogBooksQuery"] SORTS = {"title", "author", "published", "recently_added", "recently_updated", "recently_read", "series"} -# A tiny valid PNG (1x1) for thumbnails, and the "book files" (their bytes are -# what a download returns; hash = KOReader's partial MD5, which for a file this -# small is the MD5 of its first 1024 bytes at offset 0... the mock just keeps -# the value a test gives it). -PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489" - "0000000d49444154789c6360606060000000050001a5f645400000000049454e44ae426082") +# The "book files": their bytes are what a download returns. fileHash here is the +# file's MD5 (the real server's is KOReader's partial MD5; the tests only need the +# two ends to agree). +def _png(w, h): + """A plain cover: light grey with a dark edge (stdlib only).""" + import struct, zlib + rows = b"".join(b"\0" + bytes(60 if x < 3 or y < 3 or x >= w - 3 or y >= h - 3 else 205 for x in range(w)) for y in range(h)) + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 0, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") + + +PNG = _png(120, 168) def book(i, title, authors, library, series=None, idx=None, fmt="epub", collections=()): diff --git a/tools/gzreader/tests/run_tests.lua b/tools/gzreader/tests/run_tests.lua index c143bd10e..f3cacfdf0 100644 --- a/tools/gzreader/tests/run_tests.lua +++ b/tools/gzreader/tests/run_tests.lua @@ -15088,5 +15088,219 @@ print("Immich photos for notes and drawings (gzreader_immichpick.lua): the Memos plugin.store.memos, plugin.store.immich = saved.memos, saved.immich end)() +print("BookOrbit as the book server: sign in, browse, covers, download") +;(function() + local BP = PORT + 61 + local BO = "http://127.0.0.1:" .. BP + os.execute("python3 -I " .. PLUGIN .. "/../../tools/gzreader/tests/mock_bookorbit.py " .. BP + .. " > " .. WORK .. "/bookorbit.log 2>&1 & echo $! > " .. WORK .. "/bookorbit.pid") + local function bctl(path, body) + local pp = io.popen("curl -s " .. (body and ("-H 'Content-Type: application/json' -d '" .. body .. "' ") or "") .. BO .. path) + local t = pp:read("*a"); pp:close() + return t ~= "" and json.decode(t) or {} + end + for _try = 1, 50 do + if bctl("/_mock/state").capabilities then break end + socket.sleep(0.2) + end + local BookOrbit = require("gzreader_bookorbit") + local Api = require("gzreader_api") + local Covers = require("gzreader_covers") + local lfs = require("libs/libkoreader-lfs") + local md5 = require("ffi/sha2").md5 + + -- the pure parts + check(BookOrbit.pickFormat({ "pdf", "m4b", "EPUB" }) == "epub" and BookOrbit.pickFormat({ "m4b" }) == nil and BookOrbit.pickFormat(nil) == nil, + "the format to read: the first KOReader opens, EPUB before PDF; none for an audiobook") + local tb = BookOrbit.toBook({ id = 7, title = "A: B/C?", authors = { "X", json.null }, formats = { "epub" }, seriesName = json.null, + seriesIndex = 2, progressPercentage = 42.5, readStatus = "reading", lastReadAt = "2026-11-21T10:00:00.000Z" }) + check(tb.id == 7 and tb.primaryFileType == "EPUB" and tb.primaryFileName == "A B C.epub" and #tb.authors == 1 and tb.seriesName == nil + and tb.seriesNumber == 2 and tb.readProgress == 42.5 and tb.readStatus == "READING", "a catalog item as a GZreader book (nulls dropped, a safe file name)") + check(BookOrbit.toBook({ id = 8, title = "T", formats = { "m4b" } }).primaryFileType == "AUDIOBOOK" and BookOrbit.toBook({ title = "no id" }) == nil, + "an audiobook is told apart; an item without an id is left out") + check(BookOrbit.pickFile({ files = { { id = 1, format = "pdf", role = "content", downloadUrl = "/a" }, { id = 2, format = "epub", role = "primary", downloadUrl = "/b" }, + { id = 3, format = "epub", role = "content", downloadUrl = "/c" } } }).id == 3, "the file to download: one the server serves, EPUB first") + + -- signing in + local saved = { server = plugin.store.server, username = plugin.store.username, downloads = plugin.store.downloads } + -- (earlier tests put their stand-ins back as fields of the client itself, which would hide the other class's methods) + for k, v in pairs(plugin.api) do + if type(v) == "function" and k ~= "on_change" then plugin.api[k] = nil end + end + check(plugin:backend() == "grimmory" and plugin.api:isPaired() and not plugin:booksOnly(), "before: signed in to Grimmory") + plugin.store.downloads = { ["101"] = { path = "/nowhere/grimmory-book.epub", title = "Grimmory's 101" } } + local g_refresh = plugin.store.refresh_token + local ok, err = plugin:connect(BO, "will-kindle", "wrong", "bookorbit") + check(not ok and err:find("KOReader sync user name", 1, true) and plugin:backend() == "grimmory" and plugin.store.refresh_token == g_refresh + and plugin.store.server == saved.server and getmetatable(plugin.api) == Api, + "a wrong BookOrbit password: said plainly, and the Grimmory sign-in is untouched") + bctl("/_mock/set", '{"sync_enabled": false}') + ok, err = plugin:connect(BO, "will-kindle", "hunter22", "bookorbit") + check(not ok and err:find("sync switched off", 1, true), "sync switched off in BookOrbit: said so") + bctl("/_mock/set", '{"sync_enabled": true}') + ok, err = plugin:connect("http://127.0.0.1:" .. PORT, "will-kindle", "hunter22", "bookorbit") + check(not ok and err:find("check that the address is BookOrbit's", 1, true) and plugin:backend() == "grimmory", + "Grimmory's address given as BookOrbit's (it answers 401): the message also says to check the address") + check(plugin:describeError("bookorbit_not_found"):find("not as BookOrbit", 1, true) ~= nil, "an address with no BookOrbit there (404): said so") + local api_table = plugin.api + ok, err = plugin:connect(BO, "will-kindle", "hunter22", "bookorbit") + check(ok and plugin:backend() == "bookorbit" and plugin.api == api_table and getmetatable(plugin.api) == BookOrbit and plugin:booksOnly() + and plugin.api:isPaired() and plugin:serverName() == "BookOrbit", "signed in to BookOrbit: the same client table, now BookOrbit's") + check(plugin.store.server == BO and plugin.store.username == "will-kindle" and plugin.store.bookorbit.key == md5("hunter22") + and plugin.store.refresh_token == nil and plugin.store.access_token == nil, "kept: the address, the name and the password's MD5; Grimmory's tokens gone") + local dump = require("dump") and require("dump")(plugin.store) or "" + check(not dump:find("hunter22", 1, true), "the password itself is nowhere in the settings") + check(plugin.store.bookorbit.server_version == "0.9.0" and plugin.api:can("bookmarkSync") and not plugin.api:can("nope"), "the server's version and capabilities are read") + check(next(plugin.store.downloads) == nil and plugin.store.downloads_other.grimmory["101"].title == "Grimmory's 101", + "Grimmory's list of downloads is put aside (its ids are other books here)") + check(Covers.dir():match("gzreader%-covers%-bookorbit$") ~= nil, "BookOrbit's covers have their own folder") + local S = require("gzreader_secrets") + local in_secrets = false + for _i, p in ipairs(S.PATHS) do if p[1] == "bookorbit" and p[2] == "key" then in_secrets = true end end + check(in_secrets, "the sign-in key is one of the secrets kept off the USB drive") + check(not plugin:syncEnabled(), "nothing is synced to BookOrbit yet: progress sync is off") + plugin:queue("progress", 101, { percentage = 10 }) + check(next(plugin.store.pending.progress) == nil, "…and nothing is queued to send") + + -- browsing + local page = plugin.api:listBooks{ page = 0, size = 2, sort = "title", dir = "asc", fileType = plugin.api.READABLE_TYPES } + check(page and #page.content == 2 and page.totalElements == 5 and page.totalPages == 3 and page.hasNext and not page.hasPrevious + and page.content[1].title == "A Field Guide to Fog" and page.content[1].primaryFileType == "EPUB" + and page.content[1].primaryFileName == "A Field Guide to Fog.epub", "a page of books, as the Catalog reads one") + local last = plugin.api:listBooks{ page = 2, size = 2, sort = "title", dir = "asc" } + check(last and #last.content == 1 and not last.hasNext and last.content[1].primaryFileType == "PDF", "the last page; a PDF book") + check(plugin.api:listBooks{ page = 0, size = 50, libraryId = 2 }.totalElements == 2, "a library's books") + check(plugin.api:listBooks{ page = 0, size = 50, shelfId = 12 }.totalElements == 2, "a collection's books (GZreader's shelf)") + check(plugin.api:listBooks{ page = 0, size = 50, authors = "Ada Marsh" }.totalElements == 2, "an author's books") + local ser = plugin.api:listBooks{ page = 0, size = 50, series = "Waymarks", sort = "seriesNumber", dir = "asc" } + check(ser.totalElements == 2 and ser.content[1].seriesNumber == 1 and ser.content[2].seriesNumber == 2, "a series, in order") + check(plugin.api:searchBooks("okafor").totalElements == 2 and plugin.api:listBooks{ page = 0, size = 50, search = "trains" }.content[1].id == 104, "searching") + check(plugin.api:listBooks{ page = 0, size = 500 }.size == 100, "a page is never asked for bigger than the server gives") + local audio = plugin.api:listBooks{ page = 0, size = 20, fileType = { "AUDIOBOOK" } } + check(audio and #audio.content == 0 and audio.totalPages == 0, "audiobooks: an empty list for now, not an error") + local libs = plugin.api:listLibraries() + check(libs and #libs == 2 and libs[1].id == 1 and libs[1].name == "Fiction" and libs[1].bookCount == 3, "libraries") + local shelves = plugin.api:listShelves() + check(shelves and #shelves == 2 and shelves[1].name == "Beach reads" and shelves[1].bookCount == 2 and not shelves[1].magic, "collections as shelves") + local recent = plugin.api:simpleList("recently-added", 3) + check(recent and #recent == 3 and recent[1].addedOn >= recent[2].addedOn, "recently added, newest first") + check(#plugin.api:continueReading(10) == 0, "continue reading: nothing in progress yet") + local full = plugin.api:getBook(101) + check(full and full.primaryFile.id == 5101 and full.primaryFileId == 5101 and full.metadata.description == "About The Long Way Round." + and full.libraryId == 1 and full.fileSizeKb == 2 and #full.primaryFile.fileHash == 32, "a book's record: its file and metadata") + local d = plugin.api:getBookDetail(101) + check(d and d.publisher == "Example House" and d.pageCount == 240 and d.seriesName == "Waymarks" and d.seriesNumber == 1, "a book's page") + local none, nerr = plugin.api:getBook(999) + check(none == nil and nerr == "http_404" and plugin:describeError(nerr) == "BookOrbit returned an error (404).", "a missing book: BookOrbit's error, by name") + -- the library index (authors and series come from it) builds from these pages + local Index = require("gzreader_index") + local built + Index.build(plugin, false, function(data) built = data end) + runLoop(function() return built ~= nil end, 30) + if type(built) ~= "table" then print(" index:", tostring(built)) end + check(type(built) == "table" and built.total == 5 and built.authors["Ben Okafor"] == 2 and built.series["Waymarks"].count == 2 + and built.libraries["1"] == 3, "the library index builds from BookOrbit (authors, series, libraries)") + + -- covers and files + local cover = WORK .. "/bo-cover.jpg" + os.remove(cover) + check(plugin.api:downloadThumbnail(101, cover) == true and lfs.attributes(cover, "size") > 50, "a cover") + local c_ok, c_err, c_code = plugin.api:downloadThumbnail(999, cover .. "2") + check(c_ok == false and c_code == 404 and lfs.attributes(cover .. "2.part") == nil, "no cover: 404, nothing left behind") + local got = plugin.api:downloadThumbnails{ { id = 102, path = WORK .. "/bo-c102.jpg" }, { id = 999, path = WORK .. "/bo-c999.jpg" } } + check(got.got == 1 and #got.none == 1 and got.none[1] == 999, "a page of covers: the ones there, and which have none") + local file = WORK .. "/bo-book.epub.part" + local f = io.open(file, "wb"); f:write("an interrupted part from before"); f:close() + local d_ok, d_err = plugin.api:downloadToFile(101, file, true) + local fh = io.open(file, "rb"); local data = fh and fh:read("*a") or ""; if fh then fh:close() end + check(d_ok == true and md5(data) == full.primaryFile.fileHash and #data == 1280, "a book's file, whole (an old part is started again, not added to)", d_err) + d_ok, d_err = plugin.api:downloadToFile(999, file .. "x") + check(d_ok == false and d_err == "http_404" and lfs.attributes(file .. "x") == nil, "a missing book's file: an error, nothing left behind") + local seen = bctl("/_mock/state").seen + local only_get = #seen > 10 + for _i, e in ipairs(seen) do if e[1] ~= "GET" then only_get = false end end + check(only_get, "browsing and downloading only ever read from BookOrbit") + + -- a refused sign-in later, and the server away + bctl("/_mock/set", '{"ko_permission": false}') + local r, rerr = plugin.api:listLibraries() + check(r == nil and rerr == "bookorbit_refused" and plugin.api:isPaired(), "refused later: an error to show, the sign-in kept") + bctl("/_mock/set", '{"ko_permission": true, "offline": true}') + r, rerr = plugin.api:listBooks{ page = 0, size = 5 } + check(r == nil and rerr == "http_503", "the server down: its error") + bctl("/_mock/set", '{"offline": false}') + check(select(2, plugin.api:putProgress(101, {})) == "unsupported" and select(2, plugin.api:listAnnotations(101)) == "unsupported", + "what isn't sent to BookOrbit yet answers \"unsupported\"") + + -- the setup page + PS.new = function(self, o) screen = o; return o end + plugin:startQrPairing() + local url = screen.url:gsub("#.*$", "") + local code, body = phone("'" .. url .. "'") + local sec = body and body:match('
') or "" + check(code == 200 and sec:find("Connected to BookOrbit as will%-kindle") and sec:find('