From ce204013263d27c4cf5fa1f6db03d1c27900c44b Mon Sep 17 00:00:00 2001 From: listlessbird <124798751+listlessbird@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:10:26 +0530 Subject: [PATCH 1/3] feat(kindle-core): fetch and convert web articles Readability extraction (dom_smoothie), images re-encoded as JPEG, and the page's preview image as the cover. A book without a cover is built as a PDOC with no thumbnail instead of failing. --- .../kindle-core/cpp/generated/kindle_core.cpp | 36 + .../kindle-core/cpp/generated/kindle_core.hpp | 2 + .../modules/kindle-core/rust/Cargo.lock | 730 +++++++++++++++++- .../modules/kindle-core/rust/Cargo.toml | 10 +- .../modules/kindle-core/rust/src/article.rs | 196 +++++ .../modules/kindle-core/rust/src/lib.rs | 162 +++- .../src/generated/kindle_core-ffi.ts | 2 + .../kindle-core/src/generated/kindle_core.ts | 197 ++++- apps/mobile/src/lib/kindleCore.ts | 24 +- 9 files changed, 1315 insertions(+), 44 deletions(-) create mode 100644 apps/mobile/modules/kindle-core/rust/src/article.rs diff --git a/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.cpp b/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.cpp index 1b81c52..ab24089 100644 --- a/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.cpp +++ b/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.cpp @@ -129,6 +129,10 @@ extern "C" { uint64_t callback_data, UniffiForeignFutureResultVoid result ); + /*handle*/ uint64_t uniffi_kindle_core_fn_func_convert_article( + RustBuffer url, + RustBuffer out_dir + ); /*handle*/ uint64_t uniffi_kindle_core_fn_func_convert_epub( RustBuffer epub_path, RustBuffer out_dir @@ -334,6 +338,8 @@ extern "C" { /*handle*/ uint64_t handle, RustCallStatus *uniffi_out_err ); + uint16_t uniffi_kindle_core_checksum_func_convert_article( + ); uint16_t uniffi_kindle_core_checksum_func_convert_epub( ); uint16_t uniffi_kindle_core_checksum_func_device_thumbnail( @@ -1838,6 +1844,14 @@ NativeKindleCore::NativeKindleCore( return this->cpp_uniffi_internal_fn_func_ffi__read_string_from_buffer(rt, thisVal, args, count); } ); + props["ubrn_uniffi_kindle_core_fn_func_convert_article"] = jsi::Function::createFromHostFunction( + rt, + jsi::PropNameID::forAscii(rt, "ubrn_uniffi_kindle_core_fn_func_convert_article"), + 2, + [this](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { + return this->cpp_uniffi_kindle_core_fn_func_convert_article(rt, thisVal, args, count); + } + ); props["ubrn_uniffi_kindle_core_fn_func_convert_epub"] = jsi::Function::createFromHostFunction( rt, jsi::PropNameID::forAscii(rt, "ubrn_uniffi_kindle_core_fn_func_convert_epub"), @@ -2238,6 +2252,14 @@ NativeKindleCore::NativeKindleCore( return this->cpp_ffi_kindle_core_rust_future_complete_void(rt, thisVal, args, count); } ); + props["ubrn_uniffi_kindle_core_checksum_func_convert_article"] = jsi::Function::createFromHostFunction( + rt, + jsi::PropNameID::forAscii(rt, "ubrn_uniffi_kindle_core_checksum_func_convert_article"), + 0, + [this](jsi::Runtime &rt, const jsi::Value &thisVal, const jsi::Value *args, size_t count) -> jsi::Value { + return this->cpp_uniffi_kindle_core_checksum_func_convert_article(rt, thisVal, args, count); + } + ); props["ubrn_uniffi_kindle_core_checksum_func_convert_epub"] = jsi::Function::createFromHostFunction( rt, jsi::PropNameID::forAscii(rt, "ubrn_uniffi_kindle_core_checksum_func_convert_epub"), @@ -2418,6 +2440,13 @@ jsi::Value NativeKindleCore::cpp_uniffi_internal_fn_func_ffi__read_string_from_b } // Methods calling directly into the uniffi generated C API of the Rust crate. +jsi::Value NativeKindleCore::cpp_uniffi_kindle_core_fn_func_convert_article(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) { + auto value = uniffi_kindle_core_fn_func_convert_article(uniffi::kindle_core::Bridging::fromJs(rt, callInvoker, args[0]), uniffi::kindle_core::Bridging::fromJs(rt, callInvoker, args[1]) + ); + + + return uniffi_jsi::Bridging::toJs(rt, callInvoker, value); +} jsi::Value NativeKindleCore::cpp_uniffi_kindle_core_fn_func_convert_epub(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) { auto value = uniffi_kindle_core_fn_func_convert_epub(uniffi::kindle_core::Bridging::fromJs(rt, callInvoker, args[0]), uniffi::kindle_core::Bridging::fromJs(rt, callInvoker, args[1]) ); @@ -2804,6 +2833,13 @@ jsi::Value NativeKindleCore::cpp_ffi_kindle_core_rust_future_complete_void(jsi:: return jsi::Value::undefined(); } +jsi::Value NativeKindleCore::cpp_uniffi_kindle_core_checksum_func_convert_article(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) { + auto value = uniffi_kindle_core_checksum_func_convert_article( + ); + + + return uniffi_jsi::Bridging::toJs(rt, callInvoker, value); +} jsi::Value NativeKindleCore::cpp_uniffi_kindle_core_checksum_func_convert_epub(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) { auto value = uniffi_kindle_core_checksum_func_convert_epub( ); diff --git a/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.hpp b/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.hpp index 2a19dda..38db706 100644 --- a/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.hpp +++ b/apps/mobile/modules/kindle-core/cpp/generated/kindle_core.hpp @@ -22,6 +22,7 @@ class NativeKindleCore : public jsi::HostObject { jsi::Value cpp_uniffi_internal_fn_func_ffi__string_to_buffer(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_internal_fn_func_ffi__string_from_buffer(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_internal_fn_func_ffi__read_string_from_buffer(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); + jsi::Value cpp_uniffi_kindle_core_fn_func_convert_article(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_kindle_core_fn_func_convert_epub(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_kindle_core_fn_func_device_thumbnail(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_ffi_kindle_core_rust_future_poll_u8(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); @@ -72,6 +73,7 @@ class NativeKindleCore : public jsi::HostObject { jsi::Value cpp_ffi_kindle_core_rust_future_cancel_void(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_ffi_kindle_core_rust_future_free_void(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_ffi_kindle_core_rust_future_complete_void(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); + jsi::Value cpp_uniffi_kindle_core_checksum_func_convert_article(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_kindle_core_checksum_func_convert_epub(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_uniffi_kindle_core_checksum_func_device_thumbnail(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); jsi::Value cpp_ffi_kindle_core_uniffi_contract_version(jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count); diff --git a/apps/mobile/modules/kindle-core/rust/Cargo.lock b/apps/mobile/modules/kindle-core/rust/Cargo.lock index 4ba98c8..d8d3980 100644 --- a/apps/mobile/modules/kindle-core/rust/Cargo.lock +++ b/apps/mobile/modules/kindle-core/rust/Cargo.lock @@ -95,7 +95,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -106,7 +106,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -241,6 +241,12 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64-simd" version = "0.7.0" @@ -259,6 +265,21 @@ dependencies = [ "serde", ] +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" + [[package]] name = "bit_field" version = "0.10.3" @@ -527,6 +548,19 @@ dependencies = [ "smallvec", ] +[[package]] +name = "cssparser" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" +dependencies = [ + "cssparser-macros 0.7.1", + "dtoa-short", + "itoa", + "phf 0.14.0", + "smallvec", +] + [[package]] name = "cssparser-color" version = "0.5.0" @@ -616,6 +650,52 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dom_query" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35b4f772a1a8b88e5545a67c2d3a62a93d4edccc5a68f2145fe52e39c96d275" +dependencies = [ + "bit-set", + "cssparser 0.38.0", + "foldhash", + "html5ever 0.40.1", + "memchr", + "nom 8.0.0", + "precomputed-hash", + "selectors 0.41.0", + "tendril", +] + +[[package]] +name = "dom_smoothie" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62881cc91e0aa9ba2cf6105b05af584e1914be593b7013925a1e2fbf586fa33e" +dependencies = [ + "dom_query", + "flagset", + "foldhash", + "gjson", + "html-escape", + "itoa", + "phf 0.14.0", + "tendril", + "thiserror", + "unicode-segmentation", +] + [[package]] name = "dtoa" version = "1.0.11" @@ -676,7 +756,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -723,6 +803,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.10" @@ -734,6 +820,21 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + [[package]] name = "fs-err" version = "2.11.0" @@ -835,6 +936,12 @@ dependencies = [ "weezl", ] +[[package]] +name = "gjson" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43503cc176394dd30a6525f5f36e838339b8b5619be33ed9a7783841580a97b6" + [[package]] name = "glob" version = "0.3.4" @@ -890,6 +997,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "html-escape" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9356095b4b41197bba32173600e1582792cda618f65d12f68e2e77d273413c5" + [[package]] name = "html5ever" version = "0.39.0" @@ -897,7 +1010,138 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" dependencies = [ "log", - "markup5ever", + "markup5ever 0.39.0", +] + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever 0.40.0", + "memchr", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", ] [[package]] @@ -1018,12 +1262,16 @@ dependencies = [ name = "kindle-core" version = "0.1.0" dependencies = [ + "dom_query", + "dom_smoothie", "futures-channel", "image", "kindling-mobi", "pollster", "thiserror", "uniffi", + "ureq", + "url", "zip", ] @@ -1126,6 +1374,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lock_api" version = "0.4.14" @@ -1158,7 +1412,18 @@ checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" dependencies = [ "log", "tendril", - "web_atoms", + "web_atoms 0.2.6", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms 0.3.0", ] [[package]] @@ -1429,11 +1694,22 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ - "phf_macros", + "phf_macros 0.13.1", "phf_shared 0.13.1", "serde", ] +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + [[package]] name = "phf_codegen" version = "0.11.3" @@ -1454,6 +1730,16 @@ dependencies = [ "phf_shared 0.13.1", ] +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", +] + [[package]] name = "phf_generator" version = "0.11.3" @@ -1474,6 +1760,16 @@ dependencies = [ "phf_shared 0.13.1", ] +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + [[package]] name = "phf_macros" version = "0.13.1" @@ -1487,6 +1783,19 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -1505,6 +1814,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1536,6 +1854,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1861,6 +2188,20 @@ version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rkyv" version = "0.7.46" @@ -1915,7 +2256,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -1939,9 +2315,9 @@ dependencies = [ "cssparser 0.36.0", "ego-tree", "getopts", - "html5ever", + "html5ever 0.39.0", "precomputed-hash", - "selectors", + "selectors 0.36.1", "tendril", ] @@ -1986,7 +2362,24 @@ dependencies = [ "phf_codegen 0.13.1", "precomputed-hash", "rustc-hash", - "servo_arc", + "servo_arc 0.4.3", + "smallvec", +] + +[[package]] +name = "selectors" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" +dependencies = [ + "bitflags", + "cssparser 0.38.0", + "derive_more", + "log", + "new_debug_unreachable", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.5.0", "smallvec", ] @@ -2070,6 +2463,15 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "servo_arc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "shlex" version = "2.0.1" @@ -2154,6 +2556,18 @@ dependencies = [ "precomputed-hash", ] +[[package]] +name = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.14.0", + "precomputed-hash", +] + [[package]] name = "string_cache_codegen" version = "0.6.1" @@ -2166,12 +2580,30 @@ dependencies = [ "quote", ] +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", +] + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "1.0.109" @@ -2205,6 +2637,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tap" version = "1.0.1" @@ -2221,7 +2664,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -2277,6 +2720,16 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -2459,12 +2912,80 @@ dependencies = [ "weedle2", ] +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + [[package]] name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" version = "1.29.0" @@ -2566,8 +3087,29 @@ checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" dependencies = [ "phf 0.13.1", "phf_codegen 0.13.1", - "string_cache", - "string_cache_codegen", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", +] + +[[package]] +name = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf 0.14.0", + "phf_codegen 0.14.0", + "string_cache 0.11.0", + "string_cache_codegen 0.11.2", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", ] [[package]] @@ -2591,6 +3133,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -2600,6 +3151,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "winnow" version = "0.7.15" @@ -2621,6 +3236,12 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "wyz" version = "0.5.1" @@ -2636,6 +3257,29 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -2656,6 +3300,66 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zip" version = "2.6.1" diff --git a/apps/mobile/modules/kindle-core/rust/Cargo.toml b/apps/mobile/modules/kindle-core/rust/Cargo.toml index 8e41f78..32cbc70 100644 --- a/apps/mobile/modules/kindle-core/rust/Cargo.toml +++ b/apps/mobile/modules/kindle-core/rust/Cargo.toml @@ -14,12 +14,18 @@ kindling-mobi = "=0.45.6" uniffi = "0.31" thiserror = "2" futures-channel = "0.3" +# Web articles: Readability's extraction, the page and its images over rustls, and any image +# format re-encoded as the JPEG the Kindle reads. `image` matches kindling's, with its formats. +dom_smoothie = "0.20" +dom_query = "0.30" +ureq = "3.5" +url = "2" +image = "0.25.10" [dev-dependencies] pollster = "0.4" -# Same versions kindling uses, to build fixture EPUBs in tests. +# Same version kindling uses, to build fixture EPUBs in tests. zip = { version = "2.6.1", default-features = false, features = ["deflate"] } -image = { version = "0.25.10", default-features = false, features = ["jpeg"] } [profile.release] opt-level = "s" diff --git a/apps/mobile/modules/kindle-core/rust/src/article.rs b/apps/mobile/modules/kindle-core/rust/src/article.rs new file mode 100644 index 0000000..fc68f45 --- /dev/null +++ b/apps/mobile/modules/kindle-core/rust/src/article.rs @@ -0,0 +1,196 @@ +//! A web article as an unpacked EPUB: fetch the page, keep what Readability calls the article, +//! and store its images as JPEGs beside it, so kindling builds it like any other book. + +use std::io::Cursor; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use dom_query::Document; +use dom_smoothie::Readability; +use ureq::ResponseExt; + +use crate::{ConvertError, Stop, checkpoint, io}; + +// Some sites serve a stub or a block page to clients that do not look like a browser. +const USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"; +const MAX_PAGE_BYTES: u64 = 10 << 20; +const MAX_IMAGE_BYTES: u64 = 10 << 20; +const MAX_IMAGES: usize = 40; +/// The Paperwhite's screen is 1072 px wide; wider images only cost space. +const MAX_IMAGE_WIDTH: u32 = 1072; +/// Smaller images are icons and tracking pixels, not a cover. +const MIN_COVER_WIDTH: u32 = 300; + +/// Writes the article at `url` into `dir` as `article.xhtml`, `images/` and the returned +/// `content.opf`. A page that cannot be reached is `Fetch`, which the app retries once online. +pub(crate) fn write(url: &str, dir: &Path, cancelled: &dyn Fn() -> bool) -> Result { + let agent = agent(); + let (page_url, html) = fetch_page(&agent, url)?; + checkpoint(cancelled)?; + + let article = Readability::new(html, Some(&page_url), None) + .and_then(|mut readability| readability.parse()) + .map_err(|error| ConvertError::Article(error.to_string()))?; + let base = url::Url::parse(&page_url).map_err(|error| ConvertError::Article(error.to_string()))?; + let host = base.host_str().unwrap_or_default().trim_start_matches("www.").to_owned(); + let title = non_empty(Some(article.title.clone())).unwrap_or_else(|| host.clone()); + let byline = non_empty(article.byline.clone()); + let site = non_empty(article.site_name.clone()).unwrap_or_else(|| host.clone()); + let author = byline.clone().unwrap_or_else(|| site.clone()); + + std::fs::create_dir_all(dir.join("images")).map_err(io)?; + let content = Document::fragment(article.content.clone()); + content.select("source, video, audio, iframe, object, embed, noscript").remove(); + + let mut images = Vec::new(); + for img in content.select("img").nodes() { + checkpoint(cancelled)?; + let jpeg = (images.len() < MAX_IMAGES) + .then(|| image_source(img.attr("src").as_deref(), img.attr("srcset").as_deref())) + .flatten() + .and_then(|src| fetch_image(&agent, &src, 0)); + match jpeg { + Some(jpeg) => { + let href = format!("images/{}.jpg", images.len() + 1); + std::fs::write(dir.join(&href), &jpeg.bytes).map_err(io)?; + img.remove_attrs(&["srcset", "sizes", "loading", "decoding", "width", "height", "style"]); + img.set_attr("src", &href); + images.push((href, jpeg)); + } + None => img.remove_from_parent(), + } + } + + // The page's own preview image, or else the article's first large one. + let cover = article + .image + .as_deref() + .and_then(|src| base.join(src).ok()) + .and_then(|src| fetch_image(&agent, src.as_str(), MIN_COVER_WIDTH)) + .or_else(|| images.iter().find(|(_, jpeg)| jpeg.width >= MIN_COVER_WIDTH).map(|(_, jpeg)| jpeg.clone())); + if let Some(cover) = &cover { + std::fs::write(dir.join("cover.jpg"), &cover.bytes).map_err(io)?; + } + checkpoint(cancelled)?; + + let language = non_empty(article.lang.clone()).unwrap_or_else(|| "en".into()); + let header = [byline.as_deref(), Some(site.as_str())].into_iter().flatten().map(escape).collect::>().join(" · "); + let xhtml = format!( + r#" + + +{title} + +

{title}

+

{header}

+{content} +
+

{url}

+ + +"#, + lang = escape(&language), + title = escape(&title), + content = content.html_root().inner_html(), + url = escape(&page_url), + ); + std::fs::write(dir.join("article.xhtml"), xhtml).map_err(io)?; + + let items: String = images + .iter() + .enumerate() + .map(|(n, (href, _))| format!(r#""#)) + .chain(cover.iter().map(|_| r#""#.to_owned())) + .collect(); + let opf = format!( + r#" + + +{title}{author}{site} +{url}{url}{lang}{cover_meta} + +{items} + + +"#, + title = escape(&title), + author = escape(&author), + site = escape(&site), + url = escape(&page_url), + lang = escape(&language), + cover_meta = if cover.is_some() { r#""# } else { "" }, + ); + let opf_path = dir.join("content.opf"); + std::fs::write(&opf_path, opf).map_err(io)?; + + Ok(opf_path) +} + +fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(30))) + .user_agent(USER_AGENT) + .build() + .into() +} + +/// The page's final URL, after redirects, and its HTML. +fn fetch_page(agent: &ureq::Agent, url: &str) -> Result<(String, String), ConvertError> { + let mut response = agent + .get(url) + .header("Accept", "text/html,application/xhtml+xml") + .call() + .map_err(fetch_error)?; + let content_type = response.body().mime_type().unwrap_or("text/html").to_owned(); + if !content_type.contains("html") { + return Err(ConvertError::Article(format!("the link is a {content_type} file, not a web page"))); + } + let page_url = response.get_uri().to_string(); + let bytes = response.body_mut().with_config().limit(MAX_PAGE_BYTES).read_to_vec().map_err(fetch_error)?; + Ok((page_url, String::from_utf8_lossy(&bytes).into_owned())) +} + +/// No response at all is `Fetch`: the phone is offline, or the site is down. An answer that +/// is not a page is `Article`, which trying again will not fix. +fn fetch_error(error: ureq::Error) -> ConvertError { + match error { + ureq::Error::StatusCode(code) => ConvertError::Article(format!("the page answered {code}")), + ureq::Error::BadUri(_) | ureq::Error::BodyExceedsLimit(_) => ConvertError::Article(error.to_string()), + _ => ConvertError::Fetch(error.to_string()), + } +} + +#[derive(Clone)] +struct Jpeg { + bytes: Vec, + width: u32, +} + +/// Any image format the `image` crate reads, as a JPEG no wider than the Kindle's screen. +/// A missing or unreadable image is left out of the book rather than failing it. +fn fetch_image(agent: &ureq::Agent, url: &str, min_width: u32) -> Option { + let bytes = agent.get(url).call().ok()?.body_mut().with_config().limit(MAX_IMAGE_BYTES).read_to_vec().ok()?; + let image = image::load_from_memory(&bytes).ok()?; + if image.width() < min_width.max(2) { + return None; + } + let image = if image.width() > MAX_IMAGE_WIDTH { image.resize(MAX_IMAGE_WIDTH, u32::MAX, image::imageops::FilterType::Triangle) } else { image }; + let mut jpeg = Vec::new(); + image.to_rgb8().write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).ok()?; + Some(Jpeg { bytes: jpeg, width: image.width() }) +} + +/// `src`, or the last (usually largest) `srcset` candidate for images that only have that. +fn image_source(src: Option<&str>, srcset: Option<&str>) -> Option { + let src = src.map(str::trim).filter(|s| s.starts_with("http")); + let from_set = || srcset?.split(',').filter_map(|c| c.split_whitespace().next()).filter(|s| s.starts_with("http")).last(); + src.or_else(from_set).map(str::to_owned) +} + +fn non_empty(value: Option) -> Option { + value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()) +} + +fn escape(text: &str) -> String { + text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} diff --git a/apps/mobile/modules/kindle-core/rust/src/lib.rs b/apps/mobile/modules/kindle-core/rust/src/lib.rs index d9e96f1..7aaf82c 100644 --- a/apps/mobile/modules/kindle-core/rust/src/lib.rs +++ b/apps/mobile/modules/kindle-core/rust/src/lib.rs @@ -1,4 +1,5 @@ -//! EPUB -> Kindle conversion for the Android app, exported to TypeScript through uniffi. +//! EPUB and web article -> Kindle conversion for the Android app, exported to TypeScript through +//! uniffi. //! //! One call does what the stock-reader Kindle needs: a KF8 `.azw3` tagged EBOK with an ASIN //! (EXTH 113 + 501, required for lock-screen covers) plus the exact thumbnail file the firmware @@ -13,15 +14,19 @@ use std::path::{Path, PathBuf}; use kindling::{epub, extracted::ExtractedEpub, mobi, mobi_rewrite}; +mod article; + uniffi::setup_scaffolding!(); #[derive(Debug, uniffi::Record)] pub struct Converted { /// `/.azw3` pub book_path: String, - /// The firmware's file name for this book's cover: `thumbnail_<asin>_EBOK_portrait.jpg`. - pub thumbnail_name: String, - pub thumbnail_path: String, + /// The firmware's file name for this book's cover: `thumbnail_<asin>_EBOK_portrait.jpg`. None + /// for a book without a cover, which is built as a PDOC: an EBOK without its thumbnail would + /// get Amazon's "No image available" placeholder. + pub thumbnail_name: Option<String>, + pub thumbnail_path: Option<String>, pub title: String, pub author: String, } @@ -43,6 +48,11 @@ pub enum ConvertError { Thumbnail(String), #[error("i/o error: {0}")] Io(String), + /// No answer from the article's site, as when the phone is offline. + #[error("could not reach the page: {0}")] + Fetch(String), + #[error("could not read the page as an article: {0}")] + Article(String), } /// Convert `epub_path` into an EBOK AZW3 and its device thumbnail, both written to `out_dir`. @@ -54,6 +64,20 @@ pub async fn convert_epub(epub_path: String, out_dir: String) -> Result<Converte off_thread(move |cancelled| convert(Path::new(&epub_path), Path::new(&out_dir), cancelled)).await } +/// Fetch the web article at `url` and convert it like `convert_epub`: its title, byline, text, +/// and images, with the page's preview image as the cover. +#[uniffi::export] +pub async fn convert_article(url: String, out_dir: String) -> Result<Converted, ConvertError> { + off_thread(move |cancelled| { + let out_dir = Path::new(&out_dir); + let source = out_dir.join(".article"); + let result = article::write(&url, &source, cancelled).and_then(|opf| build(&opf, out_dir, cancelled)); + let _ = std::fs::remove_dir_all(&source); + result + }) + .await +} + /// Write the device thumbnail of an existing AZW3 (one with EXTH 113 + 501, as EBOK books have) /// into `out_dir`, named the way the firmware expects. #[uniffi::export] @@ -106,6 +130,7 @@ fn convert(epub_path: &Path, out_dir: &Path, cancelled: &dyn Fn() -> bool) -> Re fn build(opf_path: &Path, out_dir: &Path, cancelled: &dyn Fn() -> bool) -> Result<Converted, Stop> { let extracted = kindling(ConvertError::Epub, || ExtractedEpub::from_opf_path(opf_path))?; let (title, author) = (extracted.opf.title.clone(), extracted.opf.author.clone()); + let has_cover = extracted.opf.get_cover_image_href().is_some(); checkpoint(cancelled)?; std::fs::create_dir_all(out_dir).map_err(io)?; @@ -124,7 +149,9 @@ fn build(opf_path: &Path, out_dir: &Path, cancelled: &dyn Fn() -> bool) -> Resul true, // no_hd_images: the PW3 screen doesn't need the HD container false, // creator_tag true, // kf8_only: .azw3 - Some("EBOK"), // doc_type: EBOK + EXTH 113 is what gives a lock-screen cover + // EBOK + EXTH 113 is what gives a lock-screen cover. Without one, a PDOC gets the + // firmware's own title tile. + Some(if has_cover { "EBOK" } else { "PDOC" }), true, // kindle_limits (CLI default; books only warn) true, // self_check: post-build readback false, // kindlegen_parity (comics only) @@ -135,11 +162,13 @@ fn build(opf_path: &Path, out_dir: &Path, cancelled: &dyn Fn() -> bool) -> Resul })?; // A failed or cancelled conversion leaves nothing in `out_dir` for the app to clean up. - let thumb = checkpoint(cancelled).and_then(|()| Ok(write_thumbnail(&book_path, out_dir)?)); + let thumb = checkpoint(cancelled).and_then(|()| Ok(if has_cover { Some(write_thumbnail(&book_path, out_dir)?) } else { None })); let thumb = thumb.and_then(|thumb| match checkpoint(cancelled) { Ok(()) => Ok(thumb), Err(stop) => { - let _ = std::fs::remove_file(&thumb.path); + if let Some(thumb) = thumb { + let _ = std::fs::remove_file(&thumb.path); + } Err(stop) } }); @@ -149,8 +178,8 @@ fn build(opf_path: &Path, out_dir: &Path, cancelled: &dyn Fn() -> bool) -> Resul Ok(Converted { book_path: path_string(book_path), - thumbnail_name: thumb.name, - thumbnail_path: thumb.path, + thumbnail_name: thumb.as_ref().map(|t| t.name.clone()), + thumbnail_path: thumb.map(|t| t.path), title, author, }) @@ -266,6 +295,112 @@ mod tests { path } + fn png(width: u32, height: u32) -> Vec<u8> { + let mut png = Vec::new(); + image::RgbImage::from_pixel(width, height, image::Rgb([30, 90, 200])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + png + } + + /// Serves `routes` (path -> content type and body) on localhost, 404 for anything else, and + /// returns the base URL. + fn serve(routes: Vec<(&'static str, &'static str, Vec<u8>)>) -> String { + use std::io::{BufRead, BufReader}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let mut request = String::new(); + BufReader::new(&stream).read_line(&mut request).unwrap(); + let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned(); + let route = routes.iter().find(|(p, _, _)| *p == path); + let (status, content_type, body) = route.map_or(("404 Not Found", "text/plain", &b""[..]), |(_, t, b)| ("200 OK", *t, b)); + let head = format!("HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + let _ = stream.write_all(head.as_bytes()).and_then(|()| stream.write_all(body)); + } + }); + base + } + + fn article_page(head: &str, figure: &str) -> Vec<u8> { + let paragraph = "<p>The river had been rising for three days before anyone in the village thought to move the boats, and by then the current was strong enough to pull a grown man off his feet.</p>"; + format!( + r#"<!DOCTYPE html><html lang="en"><head><title>Flood Season | The Gazette{head} + + +

Flood Season

{figure}{}
Subscribe today
"#, + paragraph.repeat(8) + ) + .into_bytes() + } + + #[test] + fn writes_an_article_with_its_images_as_jpegs() { + let dir = Scratch::new("article-write"); + let base = serve(vec![ + ("/story", "text/html; charset=utf-8", article_page( + r#""#, + r#"
The river
"#, + )), + ("/preview.png", "image/png", png(1200, 630)), + ("/figure.png", "image/png", png(1600, 900)), + ]); + let opf = article::write(&format!("{base}/story"), &dir.0, &|| false).unwrap(); + let xhtml = std::fs::read_to_string(dir.0.join("article.xhtml")).unwrap(); + assert!(xhtml.contains(r#"src="images/1.jpg""#), "{xhtml}"); + assert!(!xhtml.contains("gone.png") && !xhtml.contains("Subscribe today"), "{xhtml}"); + let figure = image::open(dir.0.join("images/1.jpg")).unwrap(); + assert_eq!((figure.width(), figure.height()), (1072, 603), "scaled to the Kindle's width"); + assert!(std::fs::read(dir.0.join("cover.jpg")).unwrap().starts_with(&[0xFF, 0xD8])); + let opf = std::fs::read_to_string(opf).unwrap(); + assert!(opf.contains("Flood Season") && opf.contains("Ada Byline"), "{opf}"); + } + + #[test] + fn converts_an_article_into_a_book_with_its_cover() { + let dir = Scratch::new("article-convert"); + let base = serve(vec![ + ("/story", "text/html", article_page(r#""#, "")), + ("/preview.png", "image/png", png(1200, 630)), + ]); + let out = dir.0.join("out"); + let converted = pollster::block_on(convert_article(format!("{base}/story"), path_string(out.clone()))).unwrap(); + assert_eq!((converted.title.as_str(), converted.author.as_str()), ("Flood Season", "Ada Byline")); + assert!(converted.thumbnail_name.unwrap().ends_with("_EBOK_portrait.jpg")); + let mut files = dir.files("out"); + files.sort(); + assert_eq!(files.len(), 2, "the book and its thumbnail, without the unpacked article: {files:?}"); + } + + #[test] + fn an_article_without_images_is_a_personal_document_without_a_thumbnail() { + let dir = Scratch::new("article-plain"); + let base = serve(vec![("/story", "text/html", article_page("", ""))]); + let converted = pollster::block_on(convert_article(format!("{base}/story"), path_string(dir.0.join("out")))).unwrap(); + assert_eq!(converted.thumbnail_name, None); + assert!(converted.book_path.ends_with("/Flood Season - Ada Byline.azw3")); + } + + #[test] + fn an_unreachable_page_is_a_fetch_error() { + let dir = Scratch::new("article-offline"); + // Bound and dropped, so nothing listens there. + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let result = pollster::block_on(convert_article(format!("http://127.0.0.1:{port}/story"), path_string(dir.0.join("out")))); + assert!(matches!(result, Err(ConvertError::Fetch(_))), "{result:?}"); + assert!(dir.files("out").is_empty()); + } + + #[test] + fn a_missing_page_is_an_article_error() { + let dir = Scratch::new("article-missing"); + let base = serve(vec![]); + let result = pollster::block_on(convert_article(format!("{base}/story"), path_string(dir.0.join("out")))); + assert!(matches!(result, Err(ConvertError::Article(ref message)) if message.contains("404")), "{result:?}"); + } + #[test] fn file_stem_is_safe_and_readable() { assert_eq!(file_stem("Memories of Ice: Book 3", "Steven Erikson"), "Memories of Ice_ Book 3 - Steven Erikson"); @@ -280,8 +415,9 @@ mod tests { let converted = pollster::block_on(convert_epub(path_string(epub), path_string(out))).unwrap(); assert_eq!((converted.title.as_str(), converted.author.as_str()), ("Fixture", "Tester")); assert!(converted.book_path.ends_with("/Fixture - Tester.azw3")); - assert!(converted.thumbnail_name.starts_with("thumbnail_") && converted.thumbnail_name.ends_with("_EBOK_portrait.jpg")); - assert!(std::fs::read(&converted.thumbnail_path).unwrap().starts_with(&[0xFF, 0xD8])); + let thumbnail_name = converted.thumbnail_name.unwrap(); + assert!(thumbnail_name.starts_with("thumbnail_") && thumbnail_name.ends_with("_EBOK_portrait.jpg")); + assert!(std::fs::read(converted.thumbnail_path.unwrap()).unwrap().starts_with(&[0xFF, 0xD8])); assert_eq!(dir.files("source"), ["book.epub"], "kindling's extraction is cleaned up"); } @@ -351,8 +487,8 @@ mod tests { let epub = fixture_epub(&dir.0); let converted = pollster::block_on(convert_epub(path_string(epub), path_string(dir.0.join("book")))).unwrap(); let thumb = pollster::block_on(device_thumbnail(converted.book_path, path_string(dir.0.join("thumbs")))).unwrap(); - assert_eq!(thumb.name, converted.thumbnail_name); - assert_eq!(std::fs::read(thumb.path).unwrap(), std::fs::read(converted.thumbnail_path).unwrap()); + assert_eq!(Some(thumb.name), converted.thumbnail_name); + assert_eq!(std::fs::read(thumb.path).unwrap(), std::fs::read(converted.thumbnail_path.unwrap()).unwrap()); } #[test] diff --git a/apps/mobile/modules/kindle-core/src/generated/kindle_core-ffi.ts b/apps/mobile/modules/kindle-core/src/generated/kindle_core-ffi.ts index 22a3f68..3bd9ef9 100644 --- a/apps/mobile/modules/kindle-core/src/generated/kindle_core-ffi.ts +++ b/apps/mobile/modules/kindle-core/src/generated/kindle_core-ffi.ts @@ -67,9 +67,11 @@ interface NativeModuleInterface { ubrn_ffi_kindle_core_rust_future_cancel_void(handle: bigint): void; ubrn_ffi_kindle_core_rust_future_complete_void(handle: bigint, uniffi_out_err: UniffiRustCallStatus): void; ubrn_ffi_kindle_core_rust_future_free_void(handle: bigint): void; + ubrn_uniffi_kindle_core_fn_func_convert_article(url: Uint8Array, outDir: Uint8Array): bigint; ubrn_uniffi_kindle_core_fn_func_convert_epub(epubPath: Uint8Array, outDir: Uint8Array): bigint; ubrn_uniffi_kindle_core_fn_func_device_thumbnail(azw3Path: Uint8Array, outDir: Uint8Array): bigint; ubrn_ffi_kindle_core_uniffi_contract_version(): number; + ubrn_uniffi_kindle_core_checksum_func_convert_article(): number; ubrn_uniffi_kindle_core_checksum_func_convert_epub(): number; ubrn_uniffi_kindle_core_checksum_func_device_thumbnail(): number; // Codegen call sites use these via `nativeModule().rustbuffer_alloc(...)` diff --git a/apps/mobile/modules/kindle-core/src/generated/kindle_core.ts b/apps/mobile/modules/kindle-core/src/generated/kindle_core.ts index da48c0f..c691fc3 100644 --- a/apps/mobile/modules/kindle-core/src/generated/kindle_core.ts +++ b/apps/mobile/modules/kindle-core/src/generated/kindle_core.ts @@ -6,7 +6,7 @@ import nativeModule from "./kindle_core-ffi"; import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, } from "./kindle_core-ffi"; -import { type UniffiByteArray, AbstractFfiConverterByteArray, Cursor, FfiConverterUInt8, RustBuffer, UniffiError, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTypeNameSymbol, variantOrdinalSymbol, +import { type UniffiByteArray, AbstractFfiConverterByteArray, Cursor, FfiConverterOptional, FfiConverterUInt8, RustBuffer, UniffiError, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTypeNameSymbol, variantOrdinalSymbol, } from "@ubjs/core"; const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 })); @@ -19,6 +19,50 @@ const uniffiIsDebug = // Public interface members begin here. +/** + * Fetch the web article at `url` and convert it like `convert_epub`: its title, byline, text, + * and images, with the page's preview image as the cover. + */ +export async function convertArticle(url: string, outDir: string, asyncOpts_?: { signal: AbortSignal }): Promise /*throws*/ { + const __stack = uniffiIsDebug ? new Error().stack : undefined; + try { + return await uniffiRustCallAsync( + /*rustCaller:*/ uniffiCaller, + /*rustFutureFunc:*/ () => { + return nativeModule().ubrn_uniffi_kindle_core_fn_func_convert_article(FfiConverterString.lower(url, nativeModule().rustbuffer_alloc),FfiConverterString.lower(outDir, nativeModule().rustbuffer_alloc) + ); + }, + /*pollFunc:*/ nativeModule().ubrn_ffi_kindle_core_rust_future_poll_rust_buffer, + /*cancelFunc:*/ nativeModule().ubrn_ffi_kindle_core_rust_future_cancel_rust_buffer, + /*completeFunc:*/ nativeModule().ubrn_ffi_kindle_core_rust_future_complete_rust_buffer, + /*freeFunc:*/ nativeModule().ubrn_ffi_kindle_core_rust_future_free_rust_buffer, + // Async returns always go through the JS-side converter: the + // FFI symbol returns the future handle (u64), and the user-level + // RustBuffer comes back via the shared `rust_future_complete_*` + // export. The bytes the runtime hands back must be deserialized + // here using the per-callable return-type converter. + // Borrowed view over foreign memory: the call site owns the free, + // as on the sync paths. Unconditional — a no-op where buffers are + // already JS-owned. + /*liftFunc:*/ (__rb) => { + try { + return FfiConverterTypeConverted.lift(__rb); + } finally { + nativeModule().rustbuffer_free(__rb); + } + }, + /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString), + /*asyncOpts:*/ asyncOpts_, + /*errorHandler:*/ FfiConverterTypeConvertError.lift.bind(FfiConverterTypeConvertError) + ); + } catch (__error: any) { + if (uniffiIsDebug && __error instanceof Error) { + __error.stack = __stack; + } + throw __error; + } + } + /** * Convert `epub_path` into an EBOK AZW3 and its device thumbnail, both written to `out_dir`. * A Promise in TypeScript: the CPU-bound work (seconds for a large book) runs on its own thread, @@ -167,10 +211,12 @@ export type Converted = { */ bookPath: string, /** - * The firmware's file name for this book's cover: `thumbnail__EBOK_portrait.jpg`. + * The firmware's file name for this book's cover: `thumbnail__EBOK_portrait.jpg`. None + * for a book without a cover, which is built as a PDOC: an EBOK without its thumbnail would + * get Amazon's "No image available" placeholder. */ - thumbnailName: string, - thumbnailPath: string, + thumbnailName?: string, + thumbnailPath?: string, title: string, author: string } @@ -197,23 +243,23 @@ const FfiConverterTypeConverted = (() => { readFromCursor(c: Cursor): TypeName { return { bookPath: FfiConverterString.readFromCursor(c), - thumbnailName: FfiConverterString.readFromCursor(c), - thumbnailPath: FfiConverterString.readFromCursor(c), + thumbnailName: FfiConverterOptionalString.readFromCursor(c), + thumbnailPath: FfiConverterOptionalString.readFromCursor(c), title: FfiConverterString.readFromCursor(c), author: FfiConverterString.readFromCursor(c) }; } writeIntoCursor(value: TypeName, c: Cursor): void { FfiConverterString.writeIntoCursor(value.bookPath, c); - FfiConverterString.writeIntoCursor(value.thumbnailName, c); - FfiConverterString.writeIntoCursor(value.thumbnailPath, c); + FfiConverterOptionalString.writeIntoCursor(value.thumbnailName, c); + FfiConverterOptionalString.writeIntoCursor(value.thumbnailPath, c); FfiConverterString.writeIntoCursor(value.title, c); FfiConverterString.writeIntoCursor(value.author, c); } allocationSize(value: TypeName): number { return FfiConverterString.allocationSize(value.bookPath) + - FfiConverterString.allocationSize(value.thumbnailName) + - FfiConverterString.allocationSize(value.thumbnailPath) + + FfiConverterOptionalString.allocationSize(value.thumbnailName) + + FfiConverterOptionalString.allocationSize(value.thumbnailPath) + FfiConverterString.allocationSize(value.title) + FfiConverterString.allocationSize(value.author); @@ -274,7 +320,9 @@ export enum ConvertError_Tags { Epub = "Epub", Build = "Build", Thumbnail = "Thumbnail", - Io = "Io" + Io = "Io", + Fetch = "Fetch", + Article = "Article" } export const ConvertError = (() => { @@ -450,6 +498,95 @@ Readonly< } + type Fetch__interface = { + tag: ConvertError_Tags.Fetch; + inner: +Readonly< +[string +]> + }; + /** + * No answer from the article's site, as when the phone is offline. + */ + class Fetch_ extends UniffiError implements Fetch__interface { + /** + * @private + * This field is private and should not be used, use `tag` instead. + */ + readonly [uniffiTypeNameSymbol] = "ConvertError"; + readonly tag = ConvertError_Tags.Fetch; + readonly inner: +Readonly< +[string +]>; + constructor(v0: string) { + super("ConvertError", "Fetch"); + + this.inner = Object.freeze([v0]); + } + static new(v0: string): Fetch_ { + return new Fetch_(v0); + } + + static instanceOf(obj: any): obj is Fetch_ { + return obj.tag === ConvertError_Tags.Fetch; + } + static hasInner(obj: any): obj is Fetch_ { + return Fetch_.instanceOf(obj); + } + + static getInner(obj: Fetch_): +Readonly< +[string +]> { + return obj.inner; + } + + } + + type Article__interface = { + tag: ConvertError_Tags.Article; + inner: +Readonly< +[string +]> + }; + class Article_ extends UniffiError implements Article__interface { + /** + * @private + * This field is private and should not be used, use `tag` instead. + */ + readonly [uniffiTypeNameSymbol] = "ConvertError"; + readonly tag = ConvertError_Tags.Article; + readonly inner: +Readonly< +[string +]>; + constructor(v0: string) { + super("ConvertError", "Article"); + + this.inner = Object.freeze([v0]); + } + static new(v0: string): Article_ { + return new Article_(v0); + } + + static instanceOf(obj: any): obj is Article_ { + return obj.tag === ConvertError_Tags.Article; + } + static hasInner(obj: any): obj is Article_ { + return Article_.instanceOf(obj); + } + + static getInner(obj: Article_): +Readonly< +[string +]> { + return obj.inner; + } + + } + function instanceOf(obj: any): obj is ConvertError { return obj[uniffiTypeNameSymbol] === "ConvertError"; } @@ -459,12 +596,14 @@ Readonly< Epub: Epub_, Build: Build_, Thumbnail: Thumbnail_, - Io: Io_ + Io: Io_, + Fetch: Fetch_, + Article: Article_ }); })(); export type ConvertError = InstanceType< - typeof ConvertError['Epub' | 'Build' | 'Thumbnail' | 'Io'] + typeof ConvertError['Epub' | 'Build' | 'Thumbnail' | 'Io' | 'Fetch' | 'Article'] >; // FfiConverter for enum ConvertError @@ -477,6 +616,8 @@ const FfiConverterTypeConvertError = (() => { case 2: return new ConvertError.Build(FfiConverterString.readFromCursor(c)); case 3: return new ConvertError.Thumbnail(FfiConverterString.readFromCursor(c)); case 4: return new ConvertError.Io(FfiConverterString.readFromCursor(c)); + case 5: return new ConvertError.Fetch(FfiConverterString.readFromCursor(c)); + case 6: return new ConvertError.Article(FfiConverterString.readFromCursor(c)); default: throw new UniffiInternalError.UnexpectedEnumCase(); } } @@ -506,6 +647,18 @@ const FfiConverterTypeConvertError = (() => { FfiConverterString.writeIntoCursor(inner[0], c); return; } + case ConvertError_Tags.Fetch: { + c.writeI32(5); + const inner = value.inner; + FfiConverterString.writeIntoCursor(inner[0], c); + return; + } + case ConvertError_Tags.Article: { + c.writeI32(6); + const inner = value.inner; + FfiConverterString.writeIntoCursor(inner[0], c); + return; + } default: // Throwing from here means that ConvertError_Tags hasn't matched an ordinal. throw new UniffiInternalError.UnexpectedEnumCase(); @@ -537,6 +690,18 @@ const FfiConverterTypeConvertError = (() => { size += FfiConverterString.allocationSize(inner[0]); return size; } + case ConvertError_Tags.Fetch: { + const inner = value.inner; + let size = 4; + size += FfiConverterString.allocationSize(inner[0]); + return size; + } + case ConvertError_Tags.Article: { + const inner = value.inner; + let size = 4; + size += FfiConverterString.allocationSize(inner[0]); + return size; + } default: throw new UniffiInternalError.UnexpectedEnumCase(); } } @@ -544,6 +709,9 @@ const FfiConverterTypeConvertError = (() => { return new FFIConverter(); })(); +// FfiConverter for string | undefined +const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString); + /** * This should be called before anything else. @@ -563,6 +731,9 @@ function uniffiEnsureInitialized() { if (bindingsContractVersion !== scaffoldingContractVersion) { throw new UniffiInternalError.ContractVersionMismatch(scaffoldingContractVersion, bindingsContractVersion); } + if (nativeModule().ubrn_uniffi_kindle_core_checksum_func_convert_article() !== 9897) { + throw new UniffiInternalError.ApiChecksumMismatch("uniffi_kindle_core_checksum_func_convert_article"); + } if (nativeModule().ubrn_uniffi_kindle_core_checksum_func_convert_epub() !== 13316) { throw new UniffiInternalError.ApiChecksumMismatch("uniffi_kindle_core_checksum_func_convert_epub"); } diff --git a/apps/mobile/src/lib/kindleCore.ts b/apps/mobile/src/lib/kindleCore.ts index bd1d704..aae2846 100644 --- a/apps/mobile/src/lib/kindleCore.ts +++ b/apps/mobile/src/lib/kindleCore.ts @@ -9,11 +9,14 @@ export type Converted = Native.Converted; export type Thumbnail = Native.Thumbnail; export class ConvertError extends Schema.TaggedError()("ConvertError", { - stage: Schema.Literals(["Epub", "Build", "Thumbnail", "Io"]), + stage: Schema.Literals(["Epub", "Build", "Thumbnail", "Io", "Fetch", "Article"]), message: Schema.String, }) {} -/** The Rust EPUB converter in modules/kindle-core. Paths are file system paths, not `file://` URIs. */ +/** + * The Rust converter in modules/kindle-core. Paths are file system paths, not `file://` URIs. A book + * without a cover converts without a thumbnail. + */ export class KindleCore extends Context.Service< KindleCore, { @@ -26,6 +29,14 @@ export class KindleCore extends Context.Service< epubPath: string, outDir: string, ) => Effect.Effect; + /** + * Fetches a web article and converts its readable part, as `convertEpub` does. Fails in the + * `Fetch` stage when the page cannot be reached, as when the phone is offline. + */ + readonly convertArticle: ( + url: string, + outDir: string, + ) => Effect.Effect; /** Writes the Kindle thumbnail of an existing EBOK `.azw3` into `outDir`. */ readonly deviceThumbnail: ( azw3Path: string, @@ -55,6 +66,13 @@ export const make = Effect.gen(function* () { return yield* call((signal) => native.convertEpub(epubPath, outDir, { signal })); }); + const convertArticle = Effect.fn("KindleCore.convertArticle")(function* ( + url: string, + outDir: string, + ) { + return yield* call((signal) => native.convertArticle(url, outDir, { signal })); + }); + const deviceThumbnail = Effect.fn("KindleCore.deviceThumbnail")(function* ( azw3Path: string, outDir: string, @@ -62,7 +80,7 @@ export const make = Effect.gen(function* () { return yield* call((signal) => native.deviceThumbnail(azw3Path, outDir, { signal })); }); - return KindleCore.of({ convertEpub, deviceThumbnail }); + return KindleCore.of({ convertEpub, convertArticle, deviceThumbnail }); }); export const layer = Layer.effect(KindleCore, make); From da88590501d98b0d98fa76676c8e756c09eb6178 Mon Sep 17 00:00:00 2001 From: listlessbird <124798751+listlessbird@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:10:27 +0530 Subject: [PATCH 2/3] feat(mobile): share a link to send its article to the Kindle Shared text with a link becomes an article book that converts from its page. A fetch that fails offline retries once the phone is back online, and the sheet can still send it. --- .agents/skills/kindle-drop-ui/SKILL.md | 12 +- .../android/src/main/AndroidManifest.xml | 2 +- .../kindledrop/sharesheet/ShareActivity.kt | 13 +- .../src/features/library/BookScreen.tsx | 2 +- .../src/features/library/LibraryScreen.tsx | 2 +- .../src/features/library/libraryCopy.ts | 23 ++- apps/mobile/src/features/sending/book.test.ts | 66 +++++++-- apps/mobile/src/features/sending/book.ts | 74 ++++++++-- .../src/features/sending/sender.test.ts | 136 +++++++++++++++++- apps/mobile/src/features/sending/sender.ts | 103 ++++++++++--- apps/mobile/src/features/share/ShareSheet.tsx | 91 ++++++++---- apps/mobile/src/features/share/shareState.ts | 67 ++++++--- apps/mobile/src/state/books.test.ts | 1 + 13 files changed, 491 insertions(+), 101 deletions(-) diff --git a/.agents/skills/kindle-drop-ui/SKILL.md b/.agents/skills/kindle-drop-ui/SKILL.md index 7350bd7..4f93061 100644 --- a/.agents/skills/kindle-drop-ui/SKILL.md +++ b/.agents/skills/kindle-drop-ui/SKILL.md @@ -36,7 +36,7 @@ Use exactly one term per concept. | Concept | Use | Never | |---|---|---| | The action | Send, Sending, Send to Kindle | Upload, Drop, Push, Deliver | -| Converting the EPUB | Converting | Processing, Building | +| Converting the EPUB or article | Converting | Processing, Building | | Sending to the mailbox | Uploading, with a percentage | Syncing | | In the mailbox, Kindle asleep | Waiting for Kindle | Queued, Pending | | The Kindle took it | On Kindle | Delivered, Synced, Done | @@ -55,17 +55,17 @@ The mockups are in [mockups.html](mockups.html). Open it in a browser. - A status chip at the top shows "Kindle checked in 2 h ago" with a green dot. When the Kindle hasn't checked in for more than a day, the dot turns amber and the chip stays neutral. - Under a "Sending" section, each row has a cover, title, author, and a status line. Converting shows an indeterminate bar. Uploading shows a determinate bar and "Uploading · 46%". Waiting shows "Waiting for Kindle". - Under a "Recent" section, rows show "On Kindle · Yesterday" or, for failures, "Couldn't convert · Tap for details" in the danger color. Recent keeps books for 30 days, the mailbox's lifetime. A long-press clears a row. -- The empty state has the title "No books yet", the line "Share an EPUB, AZW3, PDF, or TXT file from any app. It arrives the next time your Kindle wakes", and a "Choose a file" button. +- The empty state has the title "No books yet", the line "Share an EPUB, AZW3, PDF, or TXT file, or a link to an article, from any app. It arrives the next time your Kindle wakes", and a "Choose a file" button. **Share sheet.** The app opens as a bottom sheet over the app you shared from. -- It shows the cover, title, author, and "EPUB · 9.1 MB", with **Send to Kindle** as the primary action and **Cancel** as a text button. +- It shows the cover, title, author, and "EPUB · 9.1 MB" (or "Article · example.com" for a shared link), with **Send to Kindle** as the primary action and **Cancel** as a text button. - Conversion starts the moment the file arrives, so tapping Send feels instant. Cancel discards the conversion's output. - After Send, the sheet closes and the source app stays in front. - "Confirm before sending" is on by default. When it's off, sharing sends at once and shows a brief "Sending to Kindle" confirmation. **Book** (detail). - The cover, title, and author are centered at the top. -- A four-step timeline follows: Converted (size and time), Uploaded (time), Waiting for Kindle ("Arrives the next time your Kindle wakes"), and On Kindle. Only an EPUB is converted, so an AZW3, PDF, or TXT file starts at Uploaded. +- A four-step timeline follows: Converted (size and time), Uploaded (time), Waiting for Kindle ("Arrives the next time your Kindle wakes"), and On Kindle. Only an EPUB or an article is converted, so an AZW3, PDF, or TXT file starts at Uploaded. - The one action is "Cancel sending" while the book is waiting. For a failure, show the error copy and "Try again". **First run** (Connect your Kindle). @@ -87,6 +87,8 @@ At the bottom is "Disconnect Kindle" in the danger color, behind a confirmation |---|---| | Conversion failed | Couldn't convert this book. Try another copy of the file. | | Unsupported file | Dropcap sends EPUB, AZW3, PDF, and TXT files. | +| Article failed, offline | Couldn't load this article. Sending resumes when you're back online. | +| Article failed, no article on the page | Couldn't find an article on this page. Try another link. | | Upload failed, offline | Couldn't upload. Dropcap retries when you're back online. | | Upload failed, server | Couldn't upload. Try again in a few minutes. | | Pairing code unreadable | This isn't a Dropcap pairing code. | @@ -114,6 +116,8 @@ At the bottom is "Disconnect Kindle" in the danger color, behind a confirmation | Shared file unreadable | Couldn't open this file. Try sharing it again. | | Share sheet, not connected | Title "Connect your Kindle", body "Scan the pairing code from your computer, then share the book again", actions **Connect Kindle** and **Cancel** | | Share sheet, unsupported file | Title is the file's name, body is the unsupported file copy, action **Close** | +| Share sheet, text without a link | Title is the shared subject or "Shared text", body "This text has no link to an article. Share the page from your browser.", action **Close** | +| Share sheet, article offline | The article failed offline copy, with **Send to Kindle** still available | | Book, timeline failure | "Couldn't convert" or "Couldn't upload" under the step that failed | | Book, canceled | "Sending canceled · 28 Oct, 10:05 am" under Waiting for Kindle | | Book, missing | Title "Book not found", body "It may have been cleared from Recent" | diff --git a/apps/mobile/modules/share-sheet/android/src/main/AndroidManifest.xml b/apps/mobile/modules/share-sheet/android/src/main/AndroidManifest.xml index 35b3558..e0d2a95 100644 --- a/apps/mobile/modules/share-sheet/android/src/main/AndroidManifest.xml +++ b/apps/mobile/modules/share-sheet/android/src/main/AndroidManifest.xml @@ -16,7 +16,7 @@ - + diff --git a/apps/mobile/modules/share-sheet/android/src/main/java/com/listlessbird/kindledrop/sharesheet/ShareActivity.kt b/apps/mobile/modules/share-sheet/android/src/main/java/com/listlessbird/kindledrop/sharesheet/ShareActivity.kt index c56a6b1..6ae1847 100644 --- a/apps/mobile/modules/share-sheet/android/src/main/java/com/listlessbird/kindledrop/sharesheet/ShareActivity.kt +++ b/apps/mobile/modules/share-sheet/android/src/main/java/com/listlessbird/kindledrop/sharesheet/ShareActivity.kt @@ -10,7 +10,7 @@ import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultReactActivityDelegate /** - * Receives one shared file and renders the JS `share` root over the app that shared it. It runs in + * Receives one shared file, or shared text such as a browser's link to a page, and renders the JS `share` root over the app that shared it. It runs in * the sender's task, so finishing it returns there. It skips Expo's ReactActivityDelegateWrapper on * purpose: the dev launcher would adopt it as the app's main activity. */ @@ -29,10 +29,11 @@ class ShareActivity : ReactActivity() { finish() } - // `uri`, `mimeType`, `name` and `bytes`, each only when the sender provides it. + // `uri`, `mimeType`, `name` and `bytes` for a file, or `text` and `subject` for shared text, each + // only when the sender provides it. private fun sharedFile(intent: Intent): Bundle { val props = Bundle() - val uri = streamOf(intent) ?: return props + val uri = streamOf(intent) ?: return sharedText(intent, props) props.putString("uri", uri.toString()) (intent.type ?: contentResolver.getType(uri))?.let { props.putString("mimeType", it) } @@ -50,6 +51,12 @@ class ShareActivity : ReactActivity() { return props } + private fun sharedText(intent: Intent, props: Bundle): Bundle { + intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.let { props.putString("text", it.toString()) } + intent.getStringExtra(Intent.EXTRA_SUBJECT)?.let { props.putString("subject", it) } + return props + } + private fun streamOf(intent: Intent): Uri? { val stream = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) diff --git a/apps/mobile/src/features/library/BookScreen.tsx b/apps/mobile/src/features/library/BookScreen.tsx index c419e63..81cc49b 100644 --- a/apps/mobile/src/features/library/BookScreen.tsx +++ b/apps/mobile/src/features/library/BookScreen.tsx @@ -113,7 +113,7 @@ export function BookScreen({ route }: StaticScreenProps<{ readonly id: string }> ); const steps = timelineOf(shown, uploadProgress, now); - const failure = failureOf(shown.status); + const failure = failureOf(shown); const cancelError = AsyncResult.matchWithError(canceled, { onInitial: () => undefined, diff --git a/apps/mobile/src/features/library/LibraryScreen.tsx b/apps/mobile/src/features/library/LibraryScreen.tsx index e83aeb7..24460fa 100644 --- a/apps/mobile/src/features/library/LibraryScreen.tsx +++ b/apps/mobile/src/features/library/LibraryScreen.tsx @@ -174,7 +174,7 @@ export function LibraryScreen() { variant="plain" icon="book" title="No books yet" - detail="Share an EPUB, AZW3, PDF, or TXT file from any app. It arrives the next time your Kindle wakes." + detail="Share an EPUB, AZW3, PDF, or TXT file, or a link to an article, from any app. It arrives the next time your Kindle wakes." action={