From 8729119984e88c9b46d0d0fbdbeb5cfe6413e0d0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 01:36:21 +0100 Subject: [PATCH] [format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export --- Cargo.lock | 915 +++++++++++++++++++++++ Cargo.toml | 39 + crates/liber-format/Cargo.toml | 30 + crates/liber-format/src/drm.rs | 56 ++ crates/liber-format/src/entities.rs | 168 +++++ crates/liber-format/src/epub.rs | 432 +++++++++++ crates/liber-format/src/fb2.rs | 260 +++++++ crates/liber-format/src/html.rs | 65 ++ crates/liber-format/src/lib.rs | 278 +++++++ crates/liber-format/src/mobi.rs | 493 ++++++++++++ crates/liber-format/src/position.rs | 312 ++++++++ crates/liber-format/src/sanitize.rs | 348 +++++++++ crates/liber-format/src/text.rs | 181 +++++ crates/liber-format/src/txt.rs | 129 ++++ crates/liber-format/src/xml.rs | 220 ++++++ crates/liber-format/src/zip.rs | 361 +++++++++ crates/liber-format/tests/common/mod.rs | 356 +++++++++ crates/liber-format/tests/corpus.rs | 19 + crates/liber-format/tests/formats.rs | 179 +++++ crates/liber-format/tests/fuzz.rs | 36 + crates/liber-format/tests/hostile.rs | 389 ++++++++++ crates/liber-format/tests/positions.rs | 161 ++++ crates/liber-format/tests/purity.rs | 65 ++ crates/liber-library/Cargo.toml | 23 + crates/liber-library/src/event.rs | 160 ++++ crates/liber-library/src/export.rs | 311 ++++++++ crates/liber-library/src/import.rs | 439 +++++++++++ crates/liber-library/src/lib.rs | 84 +++ crates/liber-library/src/library.rs | 660 ++++++++++++++++ crates/liber-library/src/stats.rs | 99 +++ crates/liber-library/tests/common/mod.rs | 136 ++++ crates/liber-library/tests/export.rs | 139 ++++ crates/liber-library/tests/import.rs | 152 ++++ crates/liber-library/tests/stats.rs | 69 ++ crates/liber-library/tests/sync.rs | 192 +++++ 35 files changed, 7956 insertions(+) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/liber-format/Cargo.toml create mode 100644 crates/liber-format/src/drm.rs create mode 100644 crates/liber-format/src/entities.rs create mode 100644 crates/liber-format/src/epub.rs create mode 100644 crates/liber-format/src/fb2.rs create mode 100644 crates/liber-format/src/html.rs create mode 100644 crates/liber-format/src/lib.rs create mode 100644 crates/liber-format/src/mobi.rs create mode 100644 crates/liber-format/src/position.rs create mode 100644 crates/liber-format/src/sanitize.rs create mode 100644 crates/liber-format/src/text.rs create mode 100644 crates/liber-format/src/txt.rs create mode 100644 crates/liber-format/src/xml.rs create mode 100644 crates/liber-format/src/zip.rs create mode 100644 crates/liber-format/tests/common/mod.rs create mode 100644 crates/liber-format/tests/corpus.rs create mode 100644 crates/liber-format/tests/formats.rs create mode 100644 crates/liber-format/tests/fuzz.rs create mode 100644 crates/liber-format/tests/hostile.rs create mode 100644 crates/liber-format/tests/positions.rs create mode 100644 crates/liber-format/tests/purity.rs create mode 100644 crates/liber-library/Cargo.toml create mode 100644 crates/liber-library/src/event.rs create mode 100644 crates/liber-library/src/export.rs create mode 100644 crates/liber-library/src/import.rs create mode 100644 crates/liber-library/src/lib.rs create mode 100644 crates/liber-library/src/library.rs create mode 100644 crates/liber-library/src/stats.rs create mode 100644 crates/liber-library/tests/common/mod.rs create mode 100644 crates/liber-library/tests/export.rs create mode 100644 crates/liber-library/tests/import.rs create mode 100644 crates/liber-library/tests/stats.rs create mode 100644 crates/liber-library/tests/sync.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..d6097f0 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,915 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[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" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + +[[package]] +name = "chardetng" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53" +dependencies = [ + "cfg-if", + "encoding_rs", + "memchr", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever", + "memchr", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "liber-format" +version = "0.1.0" +dependencies = [ + "base64", + "chardetng", + "crc32fast", + "encoding_rs", + "html5ever", + "markup5ever_rcdom", + "miniz_oxide", + "proptest", + "quick-xml", + "serde", + "serde_json", + "sha2", + "thiserror", + "unicode-normalization", +] + +[[package]] +name = "liber-library" +version = "0.1.0" +dependencies = [ + "csv", + "encoding_rs", + "liber-format", + "proptest", + "serde", + "serde_json", + "sha2", + "thiserror", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms", +] + +[[package]] +name = "markup5ever_rcdom" +version = "0.40.1+unofficial" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64206f12eb431c03d9b6f293846f8b0517578905b6c0cac266aa52f09c11ad7c" +dependencies = [ + "html5ever", + "markup5ever", + "tendril", + "xml5ever", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[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", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "xml5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73290529dc9bc6c6155bf77fdd70ce0061f98ad387586aa3104cddab29206961" +dependencies = [ + "log", + "markup5ever", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3bf3fcc --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,39 @@ +[workspace] +resolver = "3" +members = ["crates/liber-format", "crates/liber-library"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "MPL-2.0" +repository = "https://gitea.marek-novak.cz/mnovak/Liber-public" +rust-version = "1.88" + +[workspace.lints.rust] +unsafe_code = "forbid" + +# Every dependency here is listed with its licence in docs/DEPENDENCIES.md before it is used. +[workspace.dependencies] +liber-format = { path = "crates/liber-format" } +quick-xml = "0.42" +html5ever = "0.40" +markup5ever_rcdom = "0.40" +encoding_rs = "0.8" +chardetng = "1" +miniz_oxide = "0.8" +crc32fast = "1" +sha2 = "0.10" +base64 = "0.22" +unicode-normalization = "0.1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +csv = "1" +proptest = "1" + +[profile.dev.package."*"] +opt-level = 2 +debug = false + +[profile.dev] +debug = "line-tables-only" diff --git a/crates/liber-format/Cargo.toml b/crates/liber-format/Cargo.toml new file mode 100644 index 0000000..6bd3210 --- /dev/null +++ b/crates/liber-format/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "liber-format" +description = "Liber Domi: e-book formats (EPUB, FB2, TXT, DRM-free MOBI/AZW3) into one sanitized document model" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +quick-xml.workspace = true +html5ever.workspace = true +markup5ever_rcdom.workspace = true +encoding_rs.workspace = true +chardetng.workspace = true +miniz_oxide.workspace = true +crc32fast.workspace = true +sha2.workspace = true +base64.workspace = true +unicode-normalization.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +proptest.workspace = true +miniz_oxide.workspace = true diff --git a/crates/liber-format/src/drm.rs b/crates/liber-format/src/drm.rs new file mode 100644 index 0000000..81e1938 --- /dev/null +++ b/crates/liber-format/src/drm.rs @@ -0,0 +1,56 @@ +//! DRM detection (docs/FORMATS.md §2). Detection only: there is no decrypt path anywhere in Liber. + +use crate::xml; +use crate::zip::Zip; +use crate::{FormatError, Limits, Result}; + +/// Font obfuscation is not DRM: these algorithms only scramble embedded fonts. +const FONT_OBFUSCATION: &[&str] = &["http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"]; + +/// KFX and Topaz containers, refused before anything else looks at the bytes. +pub(crate) fn refuse_other_containers(bytes: &[u8]) -> Result<()> { + let head = &bytes[..bytes.len().min(1024)]; + if crate::text::find(head, b"\xeaDRMION\xee").is_some() { + return Err(FormatError::Drm); + } + if bytes.starts_with(b"TPZ") { + return Err(FormatError::Drm); + } + if bytes.starts_with(b"CONT\x02\x00") { + return Err(FormatError::Unsupported("KFX books (convert them with the tool that made them)".into())); + } + Ok(()) +} + +pub(crate) fn epub(zip: &Zip, limits: &Limits) -> Result<()> { + for marker in ["META-INF/rights.xml", "META-INF/license.lcpl", "META-INF/sinf.xml"] { + if zip.find(marker).is_some() { + return Err(FormatError::Drm); + } + } + if let Some(bytes) = zip.read_name_capped("META-INF/encryption.xml", limits.max_xml as u64)? { + let text = crate::text::decode_xml(&bytes); + let root = match xml::parse(&text, limits) { + Ok(r) => r, + // An encryption.xml Liber cannot read: treat the book as protected rather than guess. + Err(FormatError::Unsafe(w)) => return Err(FormatError::Unsafe(w)), + Err(_) => return Err(FormatError::Drm), + }; + let methods: Vec = root + .descendants() + .into_iter() + .filter(|e| e.is("EncryptionMethod")) + .filter_map(|e| e.attr("Algorithm").map(str::to_owned)) + .collect(); + if methods.iter().any(|m| !FONT_OBFUSCATION.contains(&m.trim())) { + return Err(FormatError::Drm); + } + } + Ok(()) +} + +/// The PalmDOC header's encryption type (record 0, offset 12). +pub(crate) fn mobi(record0: &[u8]) -> Result<()> { + let enc = record0.get(12..14).map(|b| u16::from_be_bytes([b[0], b[1]])).unwrap_or(0); + if enc != 0 { Err(FormatError::Drm) } else { Ok(()) } +} diff --git a/crates/liber-format/src/entities.rs b/crates/liber-format/src/entities.rs new file mode 100644 index 0000000..d472822 --- /dev/null +++ b/crates/liber-format/src/entities.rs @@ -0,0 +1,168 @@ +//! The named entities an XHTML book may use without declaring them: the five XML ones and HTML 4's (Latin-1, +//! symbols, specials). Nothing is ever resolved from a DOCTYPE. + +pub fn resolve(name: &str) -> Option<&'static str> { + Some(match name { + "amp" => "&", + "lt" => "<", + "gt" => ">", + "quot" => "\"", + "apos" => "'", + "nbsp" => "\u{a0}", + "iexcl" => "¡", + "cent" => "¢", + "pound" => "£", + "curren" => "¤", + "yen" => "¥", + "brvbar" => "¦", + "sect" => "§", + "uml" => "¨", + "copy" => "©", + "ordf" => "ª", + "laquo" => "«", + "not" => "¬", + "shy" => "\u{ad}", + "reg" => "®", + "macr" => "¯", + "deg" => "°", + "plusmn" => "±", + "sup2" => "²", + "sup3" => "³", + "acute" => "´", + "micro" => "µ", + "para" => "¶", + "middot" => "·", + "cedil" => "¸", + "sup1" => "¹", + "ordm" => "º", + "raquo" => "»", + "frac14" => "¼", + "frac12" => "½", + "frac34" => "¾", + "iquest" => "¿", + "Agrave" => "À", + "Aacute" => "Á", + "Acirc" => "Â", + "Atilde" => "Ã", + "Auml" => "Ä", + "Aring" => "Å", + "AElig" => "Æ", + "Ccedil" => "Ç", + "Egrave" => "È", + "Eacute" => "É", + "Ecirc" => "Ê", + "Euml" => "Ë", + "Igrave" => "Ì", + "Iacute" => "Í", + "Icirc" => "Î", + "Iuml" => "Ï", + "ETH" => "Ð", + "Ntilde" => "Ñ", + "Ograve" => "Ò", + "Oacute" => "Ó", + "Ocirc" => "Ô", + "Otilde" => "Õ", + "Ouml" => "Ö", + "times" => "×", + "Oslash" => "Ø", + "Ugrave" => "Ù", + "Uacute" => "Ú", + "Ucirc" => "Û", + "Uuml" => "Ü", + "Yacute" => "Ý", + "THORN" => "Þ", + "szlig" => "ß", + "agrave" => "à", + "aacute" => "á", + "acirc" => "â", + "atilde" => "ã", + "auml" => "ä", + "aring" => "å", + "aelig" => "æ", + "ccedil" => "ç", + "egrave" => "è", + "eacute" => "é", + "ecirc" => "ê", + "euml" => "ë", + "igrave" => "ì", + "iacute" => "í", + "icirc" => "î", + "iuml" => "ï", + "eth" => "ð", + "ntilde" => "ñ", + "ograve" => "ò", + "oacute" => "ó", + "ocirc" => "ô", + "otilde" => "õ", + "ouml" => "ö", + "divide" => "÷", + "oslash" => "ø", + "ugrave" => "ù", + "uacute" => "ú", + "ucirc" => "û", + "uuml" => "ü", + "yacute" => "ý", + "thorn" => "þ", + "yuml" => "ÿ", + "OElig" => "Œ", + "oelig" => "œ", + "Scaron" => "Š", + "scaron" => "š", + "Yuml" => "Ÿ", + "fnof" => "ƒ", + "circ" => "ˆ", + "tilde" => "˜", + "ensp" => "\u{2002}", + "emsp" => "\u{2003}", + "thinsp" => "\u{2009}", + "zwnj" => "\u{200c}", + "zwj" => "\u{200d}", + "lrm" => "\u{200e}", + "rlm" => "\u{200f}", + "ndash" => "–", + "mdash" => "—", + "lsquo" => "‘", + "rsquo" => "’", + "sbquo" => "‚", + "ldquo" => "“", + "rdquo" => "”", + "bdquo" => "„", + "dagger" => "†", + "Dagger" => "‡", + "bull" => "•", + "hellip" => "…", + "permil" => "‰", + "prime" => "′", + "Prime" => "″", + "lsaquo" => "‹", + "rsaquo" => "›", + "oline" => "‾", + "frasl" => "⁄", + "euro" => "€", + "trade" => "™", + "larr" => "←", + "uarr" => "↑", + "rarr" => "→", + "darr" => "↓", + "harr" => "↔", + "minus" => "−", + "infin" => "∞", + "ne" => "≠", + "le" => "≤", + "ge" => "≥", + "loz" => "◊", + "spades" => "♠", + "clubs" => "♣", + "hearts" => "♥", + "diams" => "♦", + "alpha" => "α", + "beta" => "β", + "gamma" => "γ", + "delta" => "δ", + "pi" => "π", + "sigma" => "σ", + "omega" => "ω", + "Omega" => "Ω", + _ => return None, + }) +} diff --git a/crates/liber-format/src/epub.rs b/crates/liber-format/src/epub.rs new file mode 100644 index 0000000..53c50a0 --- /dev/null +++ b/crates/liber-format/src/epub.rs @@ -0,0 +1,432 @@ +//! EPUB 2 and 3. + +use crate::sanitize::{Resolver, is_remote, sanitize}; +use crate::xml::{self, XEl}; +use crate::zip::Zip; +use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, drm, text}; +use std::collections::{BTreeMap, HashMap}; + +struct Item { + href: String, + media: String, + props: String, +} + +/// Percent-decodes and normalises `rel` against the directory `base` (`""` for the root). `None` if it climbs out. +pub(crate) fn join(base: &str, rel: &str) -> Option { + let rel = rel.split(['#', '?']).next().unwrap_or(""); + let decoded = percent_decode(rel); + let mut parts: Vec<&str> = + if decoded.starts_with('/') { Vec::new() } else { base.split('/').filter(|s| !s.is_empty()).collect() }; + for seg in decoded.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop()?; + } + s => parts.push(s), + } + } + Some(parts.join("/")) +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' + && i + 2 < b.len() + && let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16)) + { + out.push((h * 16 + l) as u8); + i += 3; + continue; + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn dir_of(path: &str) -> &str { + path.rfind('/').map_or("", |i| &path[..i]) +} + +fn fragment(href: &str) -> Option { + href.split_once('#').map(|(_, f)| percent_decode(f)).filter(|f| !f.is_empty()) +} + +/// Sniffs a raster image; `None` for anything else (SVG included). +pub(crate) fn raster(bytes: &[u8]) -> Option<&'static str> { + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + Some("image/png") + } else if bytes.starts_with(b"\xff\xd8\xff") { + Some("image/jpeg") + } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { + Some("image/gif") + } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some("image/webp") + } else { + None + } +} + +struct Ctx<'z, 'a> { + zip: &'z Zip<'a>, + limits: &'z Limits, + /// Spine path → chapter index. + spine: HashMap, + images: Vec, + by_path: HashMap>, + base: String, + chapter: usize, + warnings: Vec, +} + +impl Ctx<'_, '_> { + fn load_image(&mut self, path: &str) -> Option { + if let Some(i) = self.by_path.get(path) { + return *i; + } + let r = (|| { + if self.images.len() >= self.limits.max_images { + return None; + } + let e = self.zip.find(path)?; + let bytes = self.zip.read(e).ok()?; + let media_type = raster(&bytes)?; + let index = self.images.len(); + self.images.push(Image { index, media_type, bytes }); + Some(index) + })(); + self.by_path.insert(path.to_owned(), r); + r + } +} + +impl Resolver for Ctx<'_, '_> { + fn link(&mut self, href: &str) -> Option { + if is_remote(href) { + return None; + } + let frag = fragment(href); + let path_part = href.split('#').next().unwrap_or(""); + let ch = if path_part.is_empty() { self.chapter } else { *self.spine.get(&join(&self.base, path_part)?)? }; + Some(match frag { + Some(f) => format!("{ch}#{f}"), + None => ch.to_string(), + }) + } + + fn image(&mut self, src: &str) -> Option { + if is_remote(src) { + self.warnings.push("a remote image was not loaded".into()); + return None; + } + let path = join(&self.base, src)?; + self.load_image(&path) + } +} + +fn read_xml(zip: &Zip, path: &str, limits: &Limits) -> Result> { + match zip.read_name_capped(path, limits.max_xml as u64)? { + Some(b) => xml::parse(&text::decode_xml(&b), limits).map(Some), + None => Ok(None), + } +} + +pub(crate) fn open(zip: &Zip, limits: &Limits) -> Result { + drm::epub(zip, limits)?; + let container = read_xml(zip, "META-INF/container.xml", limits)? + .ok_or_else(|| FormatError::Malformed("no META-INF/container.xml".into()))?; + let opf_path = container + .descendants() + .into_iter() + .filter(|e| e.is("rootfile")) + .find(|e| e.attr("media-type").is_none_or(|m| m.contains("oebps-package"))) + .and_then(|e| e.attr("full-path")) + .and_then(|p| join("", p)) + .ok_or_else(|| FormatError::Malformed("container.xml names no package".into()))?; + let opf = + read_xml(zip, &opf_path, limits)?.ok_or_else(|| FormatError::Malformed(format!("{opf_path} is missing")))?; + let opf_dir = dir_of(&opf_path).to_owned(); + + let mut items: HashMap = HashMap::new(); + if let Some(manifest) = opf.child("manifest") { + for it in manifest.children_named("item") { + if let (Some(id), Some(href)) = (it.attr("id"), it.attr("href")) + && let Some(href) = join(&opf_dir, href) + { + items.insert( + id.to_owned(), + Item { + href, + media: it.attr("media-type").unwrap_or("").to_owned(), + props: it.attr("properties").unwrap_or("").to_owned(), + }, + ); + } + } + } + let spine_el = opf.child("spine").ok_or_else(|| FormatError::Malformed("the package has no spine".into()))?; + let mut spine: Vec<(String, bool)> = Vec::new(); + for r in spine_el.children_named("itemref") { + if let Some(it) = r.attr("idref").and_then(|id| items.get(id)) + && (it.media.contains("html") || it.media.is_empty()) + && !spine.iter().any(|(h, _)| *h == it.href) + { + spine.push((it.href.clone(), r.attr("linear") != Some("no"))); + } + } + if spine.len() > limits.max_chapters { + return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters))); + } + let metadata = metadata(&opf); + + let mut ctx = Ctx { + zip, + limits, + spine: spine.iter().enumerate().map(|(i, (h, _))| (h.clone(), i)).collect(), + images: Vec::new(), + by_path: HashMap::new(), + base: String::new(), + chapter: 0, + warnings: Vec::new(), + }; + let mut chapters = Vec::new(); + let mut footnotes = BTreeMap::new(); + for (i, (href, linear)) in spine.iter().enumerate() { + ctx.base = dir_of(href).to_owned(); + ctx.chapter = i; + let root = match chapter_body(zip, href, limits) { + Ok(b) => b, + Err(e @ (FormatError::Unsafe(_) | FormatError::TooLarge(_))) => return Err(e), + Err(e) => { + ctx.warnings.push(format!("{href}: {}", e.message())); + XEl::new("body") + } + }; + let s = sanitize(&root, &mut ctx); + if s.dropped > 0 { + ctx.warnings.push(format!("{href}: {} element(s) dropped (remote or unsupported images)", s.dropped)); + } + for (id, x) in s.notes { + footnotes.insert(format!("{i}#{id}"), x); + } + chapters.push(crate::chapter(href.clone(), None, *linear, s.root)); + } + + // Table of contents: the EPUB 3 nav, else the NCX. + let nav = items.values().find(|it| it.props.split_whitespace().any(|p| p == "nav")); + let mut toc = Vec::new(); + if let Some(nav) = nav + && let Ok(Some(doc)) = chapter_body(zip, &nav.href, limits).map(Some) + { + let base = dir_of(&nav.href).to_owned(); + if let Some(n) = doc + .descendants() + .into_iter() + .filter(|e| e.is("nav")) + .find(|e| e.attr("epub:type").is_some_and(|t| t.split_whitespace().any(|w| w == "toc"))) + && let Some(ol) = n.child("ol") + { + toc = nav_list(ol, &base, &ctx.spine, 0); + } + } + if toc.is_empty() { + let ncx = spine_el + .attr("toc") + .and_then(|id| items.get(id)) + .or_else(|| items.values().find(|it| it.media == "application/x-dtbncx+xml")); + if let Some(ncx) = ncx + && let Ok(Some(root)) = read_xml(zip, &ncx.href, limits) + && let Some(map) = root.child("navMap") + { + toc = ncx_list(map, dir_of(&ncx.href), &ctx.spine, 0); + } + } + // Chapter titles from the TOC where the chapter has no heading of its own. + fn first_titles(entries: &[TocEntry], out: &mut BTreeMap) { + for e in entries { + out.entry(e.chapter).or_insert_with(|| e.title.clone()); + first_titles(&e.children, out); + } + } + let mut titles = BTreeMap::new(); + first_titles(&toc, &mut titles); + for (i, c) in chapters.iter_mut().enumerate() { + if let Some(t) = titles.get(&i) { + c.title = Some(t.clone()); + } + } + + // Cover: EPUB 3 `cover-image`, else the EPUB 2 ``. + let cover_path = items + .values() + .find(|it| it.props.split_whitespace().any(|p| p == "cover-image")) + .map(|it| it.href.clone()) + .or_else(|| { + let id = opf + .child("metadata")? + .children_named("meta") + .find(|m| m.attr("name") == Some("cover"))? + .attr("content")? + .to_owned(); + items.get(&id).map(|it| it.href.clone()) + }); + let cover = cover_path.and_then(|p| ctx.load_image(&p)); + + Ok(Document { + format: Format::Epub, + metadata, + chapters, + toc, + footnotes, + images: ctx.images, + cover, + warnings: ctx.warnings, + }) +} + +/// A chapter's ``: XML first, then tag soup if the chapter is not well-formed. +fn chapter_body(zip: &Zip, href: &str, limits: &Limits) -> Result { + let bytes = zip + .read_name_capped(href, limits.max_xml as u64)? + .ok_or_else(|| FormatError::Malformed(format!("{href} is missing")))?; + let s = text::decode_xml(&bytes); + let root = match xml::parse(&s, limits) { + Ok(r) => r, + Err(e @ FormatError::Unsafe(_)) => return Err(e), + Err(_) => crate::html::parse(&s, limits)?, + }; + if root.is("body") { + return Ok(root); + } + Ok(root.child("body").cloned().unwrap_or(root)) +} + +fn toc_target(base: &str, href: &str, spine: &HashMap) -> Option<(usize, Option)> { + if is_remote(href) { + return None; + } + let path = join(base, href)?; + Some((*spine.get(&path)?, fragment(href))) +} + +fn nav_list(ol: &XEl, base: &str, spine: &HashMap, depth: usize) -> Vec { + let mut out = Vec::new(); + if depth > 16 { + return out; + } + for li in ol.children_named("li") { + let label = li.child("a").or_else(|| li.child("span")); + let title = label.map(|l| text::collapse(&l.text())).unwrap_or_default(); + let children = li.child("ol").map(|o| nav_list(o, base, spine, depth + 1)).unwrap_or_default(); + match label.and_then(|l| l.attr("href")).and_then(|h| toc_target(base, h, spine)) { + Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }), + _ => out.extend(children), + } + } + out +} + +fn ncx_list(parent: &XEl, base: &str, spine: &HashMap, depth: usize) -> Vec { + let mut out = Vec::new(); + if depth > 16 { + return out; + } + for p in parent.children_named("navPoint") { + let title = p.child("navLabel").map(|l| text::collapse(&l.text())).unwrap_or_default(); + let children = ncx_list(p, base, spine, depth + 1); + match p.child("content").and_then(|c| c.attr("src")).and_then(|h| toc_target(base, h, spine)) { + Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }), + _ => out.extend(children), + } + } + out +} + +/// Strips markup from a description (it is often escaped HTML). +pub(crate) fn plain(s: &str) -> String { + let mut out = String::new(); + let mut tag = false; + for c in s.chars() { + match c { + '<' => tag = true, + '>' if tag => { + tag = false; + out.push(' '); + } + c if !tag => out.push(c), + _ => {} + } + } + let out = out + .replace(" ", " ") + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\""); + text::collapse(&out) +} + +fn metadata(opf: &XEl) -> Metadata { + let mut m = Metadata::default(); + let Some(md) = opf.child("metadata") else { return m }; + let all: Vec<&XEl> = md.descendants(); + let refines = |id: Option<&str>, prop: &str| -> Option { + let id = id?; + all.iter() + .filter(|e| e.is("meta")) + .find(|e| e.attr("refines") == Some(&format!("#{id}")) && e.attr("property") == Some(prop)) + .map(|e| text::collapse(&e.text())) + }; + for e in md.elements() { + let v = text::collapse(&e.text()); + match e.local() { + "title" if m.title.is_none() && !v.is_empty() => m.title = Some(v), + "creator" => { + let role = e.attr("opf:role").map(str::to_owned).or_else(|| refines(e.attr("id"), "role")); + if role.as_deref().is_none_or(|r| r == "aut") && !v.is_empty() { + m.authors.push(v); + } + } + "language" if m.language.is_none() && !v.is_empty() => m.language = Some(v), + "identifier" if !v.is_empty() => m.identifiers.push(v), + "publisher" if m.publisher.is_none() && !v.is_empty() => m.publisher = Some(v), + "date" if m.published.is_none() && !v.is_empty() => m.published = Some(v), + "description" if m.description.is_none() => { + let p = plain(&e.text()); + if !p.is_empty() { + m.description = Some(p); + } + } + "subject" if !v.is_empty() => m.subjects.push(v), + "meta" => { + if e.attr("name") == Some("calibre:series") + && let Some(c) = e.attr("content") + { + m.series.get_or_insert_with(Series::default).name = c.trim().to_owned(); + } + if e.attr("name") == Some("calibre:series_index") + && let Some(c) = e.attr("content") + { + m.series.get_or_insert_with(Series::default).index = c.trim().parse().ok(); + } + if e.attr("property") == Some("belongs-to-collection") && !v.is_empty() { + let kind = refines(e.attr("id"), "collection-type"); + if kind.as_deref().is_none_or(|k| k == "series") { + let index = refines(e.attr("id"), "group-position").and_then(|p| p.parse().ok()); + m.series = Some(Series { name: v, index }); + } + } + } + _ => {} + } + } + if m.series.as_ref().is_some_and(|s| s.name.is_empty()) { + m.series = None; + } + m +} diff --git a/crates/liber-format/src/fb2.rs b/crates/liber-format/src/fb2.rs new file mode 100644 index 0000000..f7846d9 --- /dev/null +++ b/crates/liber-format/src/fb2.rs @@ -0,0 +1,260 @@ +//! FictionBook 2 (and `.fb2.zip`): FB2's vocabulary mapped to XHTML, then the same sanitizer as every format. + +use crate::sanitize::{Resolver, is_remote, sanitize}; +use crate::xml::{self, XEl, XNode}; +use crate::zip::Zip; +use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, text}; +use base64::Engine; +use std::collections::{BTreeMap, HashMap}; + +pub(crate) fn open_zip(zip: &Zip, limits: &Limits) -> Result { + let e = zip + .entries() + .iter() + .find(|e| e.name.to_lowercase().ends_with(".fb2")) + .ok_or_else(|| FormatError::Malformed("the archive holds no .fb2 file".into()))?; + open(&zip.read_capped(e, limits.max_xml as u64)?, limits) +} + +struct Ctx<'a> { + binaries: HashMap, + images: Vec, + loaded: HashMap>, + ids: HashMap, + limits: &'a Limits, + warnings: Vec, +} + +impl Resolver for Ctx<'_> { + fn link(&mut self, href: &str) -> Option { + if is_remote(href) { + return None; + } + let id = href.strip_prefix('#')?; + let ch = self.ids.get(id)?; + Some(format!("{ch}#{id}")) + } + + fn image(&mut self, src: &str) -> Option { + if is_remote(src) { + self.warnings.push("a remote image was not loaded".into()); + return None; + } + let id = src.strip_prefix('#')?.to_owned(); + if let Some(r) = self.loaded.get(&id) { + return *r; + } + let r = (|| { + if self.images.len() >= self.limits.max_images { + return None; + } + let (_, b64) = self.binaries.get(&id)?; + let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect(); + if clean.len() as u64 > self.limits.max_entry * 4 / 3 + 4 { + return None; + } + let bytes = base64::engine::general_purpose::STANDARD.decode(clean).ok()?; + let media_type = crate::epub::raster(&bytes)?; + let index = self.images.len(); + self.images.push(Image { index, media_type, bytes }); + Some(index) + })(); + self.loaded.insert(id, r); + r + } +} + +fn person(a: &XEl) -> Option { + let part = |n: &str| a.child(n).map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + let name: Vec = ["first-name", "middle-name", "last-name"].iter().filter_map(|n| part(n)).collect(); + if name.is_empty() { part("nickname") } else { Some(name.join(" ")) } +} + +fn metadata(root: &XEl) -> Metadata { + let mut m = Metadata::default(); + let Some(desc) = root.child("description") else { return m }; + if let Some(ti) = desc.child("title-info") { + m.title = ti.child("book-title").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + m.authors = ti.children_named("author").filter_map(person).collect(); + m.language = ti.child("lang").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + m.subjects = ti.children_named("genre").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()).collect(); + m.description = ti.child("annotation").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + m.published = ti.child("date").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + if let Some(seq) = ti.child("sequence") + && let Some(name) = seq.attr("name") + { + m.series = Some(Series { + name: name.trim().to_owned(), + index: seq.attr("number").and_then(|n| n.trim().parse().ok()), + }); + } + } + if let Some(pi) = desc.child("publish-info") { + if let Some(isbn) = pi.child("isbn") { + m.identifiers.push(text::collapse(&isbn.text())); + } + m.publisher = pi.child("publisher").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + if m.published.is_none() { + m.published = pi.child("year").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()); + } + } + m +} + +/// FB2 → XHTML vocabulary. `level` is the section depth (for heading levels). +fn convert(e: &XEl, level: usize) -> XEl { + let name = match e.local() { + "section" => "section", + "title" => ["h1", "h2", "h3", "h4", "h5", "h6"][(level + 1).min(5)], + "subtitle" => "h6", + "p" | "v" | "text-author" | "date" => "p", + "emphasis" => "em", + "strong" => "strong", + "strikethrough" => "s", + "sub" => "sub", + "sup" => "sup", + "code" => "code", + "empty-line" => "br", + "epigraph" | "cite" => "blockquote", + "poem" | "stanza" | "annotation" => "div", + "a" => "a", + "image" => "img", + "table" | "tr" | "td" | "th" => e.local(), + _ => "span", + }; + let mut out = XEl::new(name); + for (k, v) in &e.attrs { + match xml::local(k) { + "id" => out.attrs.push(("id".into(), v.clone())), + "href" if name == "a" => out.attrs.push(("href".into(), v.clone())), + "href" if name == "img" => out.attrs.push(("src".into(), v.clone())), + "alt" | "title" | "colspan" | "rowspan" => out.attrs.push((xml::local(k).to_owned(), v.clone())), + _ => {} + } + } + let in_title = e.is("title"); + let mut first = true; + for c in &e.children { + match c { + XNode::Text(t) => out.push_text(t), + XNode::El(child) => { + let next = if e.is("section") { level + 1 } else { level }; + let mut conv = convert(child, next); + if in_title && child.is("p") { + conv.name = "span".into(); + if !first { + out.children.push(XNode::El(XEl::new("br"))); + } + first = false; + } + out.children.push(XNode::El(conv)); + } + } + } + out +} + +fn collect_ids(e: &XEl, chapter: usize, out: &mut HashMap) { + if let Some(id) = e.attr("id") { + out.entry(id.to_owned()).or_insert(chapter); + } + for d in e.descendants() { + if let Some(id) = d.attr("id") { + out.entry(id.to_owned()).or_insert(chapter); + } + } +} + +pub(crate) fn open(bytes: &[u8], limits: &Limits) -> Result { + let s = text::decode_xml(bytes); + let root = xml::parse(&s, limits)?; + if !root.is("FictionBook") { + return Err(FormatError::Malformed("not a FictionBook document".into())); + } + let metadata = metadata(&root); + let mut binaries = HashMap::new(); + for b in root.children_named("binary") { + if let Some(id) = b.attr("id") { + binaries.insert(id.to_owned(), ("", b.text())); + } + } + // Chapter sources: the main bodies' title pages and top-level sections, then the notes bodies. + let mut sources: Vec<(XEl, bool, bool)> = Vec::new(); // (converted chapter, linear, notes) + for body in root.children_named("body") { + let notes = matches!(body.attr("name"), Some("notes" | "comments")); + if notes { + sources.push((convert(body, 0), false, true)); + continue; + } + let mut front = XEl::new("div"); + let mut sections = Vec::new(); + for c in body.elements() { + if c.is("section") { + sections.push(convert(c, 0)); + } else { + front.children.push(XNode::El(convert(c, 0))); + } + } + let empty = front.children.is_empty(); + if !empty { + sources.push((front, true, false)); + } + if sections.is_empty() && empty { + sources.push((convert(body, 0), true, false)); + } + for s in sections { + sources.push((s, true, false)); + } + } + if sources.len() > limits.max_chapters { + return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters))); + } + let mut ids = HashMap::new(); + for (i, (src, _, _)) in sources.iter().enumerate() { + collect_ids(src, i, &mut ids); + } + let mut ctx = Ctx { binaries, images: Vec::new(), loaded: HashMap::new(), ids, limits, warnings: Vec::new() }; + let mut chapters = Vec::new(); + let mut footnotes = BTreeMap::new(); + let mut toc = Vec::new(); + for (i, (src, linear, notes)) in sources.iter().enumerate() { + let mut wrap = XEl::new("body"); + wrap.children.push(XNode::El(src.clone())); + let s = sanitize(&wrap, &mut ctx); + if *notes { + for sec in s.root.descendants() { + if sec.name == "section" + && let Some(id) = sec.attr("id") + { + let mut w = crate::Element::new("div"); + w.children = sec.children.clone(); + footnotes.insert(format!("{i}#{id}"), crate::sanitize::serialize(&w)); + } + } + } + let ch = crate::chapter(format!("chapter-{i}"), None, *linear, s.root); + if let Some(t) = &ch.title + && *linear + { + toc.push(TocEntry { title: t.clone(), chapter: i, fragment: None, children: vec![] }); + } + chapters.push(ch); + } + let cover = root + .child("description") + .and_then(|d| d.child("title-info")) + .and_then(|t| t.child("coverpage")) + .and_then(|c| c.child("image")) + .and_then(|i| i.attr("href").map(str::to_owned)) + .and_then(|h| ctx.image(&h)); + Ok(Document { + format: Format::Fb2, + metadata, + chapters, + toc, + footnotes, + images: ctx.images, + cover, + warnings: ctx.warnings, + }) +} diff --git a/crates/liber-format/src/html.rs b/crates/liber-format/src/html.rs new file mode 100644 index 0000000..1a2fbcb --- /dev/null +++ b/crates/liber-format/src/html.rs @@ -0,0 +1,65 @@ +//! Tag-soup HTML (MOBI text, XHTML that is not well-formed) through html5ever into the same owned tree as XML. +//! The walk is depth-capped: below `max_depth` only text is collected, iteratively. + +use crate::xml::{XEl, XNode}; +use crate::{FormatError, Limits, Result}; +use html5ever::tendril::TendrilSink; +use markup5ever_rcdom::{Handle, NodeData, RcDom}; + +/// Parses an HTML document; returns its `` element (html5ever always makes one). +pub(crate) fn parse(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_text { + return Err(FormatError::TooLarge("the text is larger than the limit".into())); + } + let dom = html5ever::parse_document(RcDom::default(), Default::default()).one(text); + let mut doc = XEl::new("#document"); + let kids: Vec = dom.document.children.borrow().clone(); + for k in kids { + convert(&k, &mut doc, 0, limits.max_depth); + } + doc.elements() + .find(|e| e.is("html")) + .cloned() + .ok_or_else(|| FormatError::Malformed("HTML without a document element".into())) +} + +fn convert(h: &Handle, parent: &mut XEl, depth: usize, max: usize) { + match &h.data { + NodeData::Text { contents } => parent.push_text(&contents.borrow()), + NodeData::Element { name, attrs, .. } => { + if depth >= max { + parent.push_text(&text_of(h)); + return; + } + let mut el = XEl::new(&name.local); + for a in attrs.borrow().iter() { + let key = match &a.name.prefix { + Some(p) => format!("{p}:{}", a.name.local), + None => a.name.local.to_string(), + }; + el.attrs.push((key, a.value.to_string())); + } + let kids: Vec = h.children.borrow().clone(); + for k in &kids { + convert(k, &mut el, depth + 1, max); + } + parent.children.push(XNode::El(el)); + } + _ => {} + } +} + +fn text_of(h: &Handle) -> String { + let mut s = String::new(); + let mut stack = vec![h.clone()]; + while let Some(n) = stack.pop() { + match &n.data { + NodeData::Text { contents } => s.push_str(&contents.borrow()), + NodeData::Element { name, .. } if crate::sanitize::DROP.contains(&&*name.local) => continue, + _ => {} + } + let kids: Vec = n.children.borrow().clone(); + stack.extend(kids.into_iter().rev()); + } + s +} diff --git a/crates/liber-format/src/lib.rs b/crates/liber-format/src/lib.rs new file mode 100644 index 0000000..31afb2d --- /dev/null +++ b/crates/liber-format/src/lib.rs @@ -0,0 +1,278 @@ +//! Liber's book formats (docs/FORMATS.md): EPUB 2/3, FB2, TXT and DRM-free MOBI/AZW3 in, one sanitized +//! [`Document`] out. Pure: bytes in, values out. No file system, no network, no clock. +//! +//! ``` +//! let txt = "Chapter 1\n\nIt was a dark and stormy night.\n".as_bytes(); +//! let doc = liber_format::open(txt, Some("storm.txt"), &liber_format::Limits::default()).unwrap(); +//! assert_eq!(doc.format, liber_format::Format::Txt); +//! assert_eq!(doc.chapters.len(), 1); +//! ``` + +mod drm; +mod entities; +mod epub; +mod fb2; +mod html; +mod mobi; +pub mod position; +mod sanitize; +pub mod text; +mod txt; +mod xml; +pub mod zip; + +pub use position::{Anchor, Point, Quote, Resolved}; +pub use sanitize::{Element, Node}; + +use serde::Serialize; +use std::collections::BTreeMap; + +/// The one sentence the app shows for a protected book. +pub const DRM_MESSAGE: &str = "This book is DRM-protected, so Liber cannot open it."; + +/// What a file is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Format { + Epub, + Fb2, + Txt, + Mobi, + Azw3, + Pdf, +} + +impl Format { + pub fn as_str(self) -> &'static str { + match self { + Format::Epub => "epub", + Format::Fb2 => "fb2", + Format::Txt => "txt", + Format::Mobi => "mobi", + Format::Azw3 => "azw3", + Format::Pdf => "pdf", + } + } +} + +/// Why a book did not open. [`FormatError::message`] is the sentence for the person. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum FormatError { + #[error("DRM-protected")] + Drm, + /// A PDF: the app opens it read-only in its PDF view. + #[error("a PDF")] + Pdf, + #[error("unsupported: {0}")] + Unsupported(String), + #[error("too large: {0}")] + TooLarge(String), + /// Zip slip, symlinks, entity declarations: refused, never sanitized around. + #[error("unsafe: {0}")] + Unsafe(String), + #[error("malformed: {0}")] + Malformed(String), +} + +impl FormatError { + pub fn message(&self) -> String { + match self { + FormatError::Drm => DRM_MESSAGE.to_owned(), + FormatError::Pdf => "This is a PDF: Liber opens it read-only.".to_owned(), + FormatError::Unsupported(w) => format!("Liber cannot open this book: {w}."), + FormatError::TooLarge(w) => format!("This book is too large to open safely: {w}."), + FormatError::Unsafe(w) => format!("Liber refused this file because it is unsafe: {w}."), + FormatError::Malformed(w) => format!("This book file is damaged: {w}."), + } + } +} + +pub type Result = std::result::Result; + +/// Hard caps for one book. Every size read out of a file is checked against these before anything is allocated. +#[derive(Clone, Debug)] +pub struct Limits { + pub max_input: u64, + pub max_entries: usize, + pub max_entry: u64, + pub max_total: u64, + /// Inflated / compressed, for entries larger than 1 MiB. + pub max_ratio: u64, + pub max_xml: usize, + pub max_depth: usize, + pub max_chapters: usize, + pub max_images: usize, + pub max_text: usize, +} + +impl Default for Limits { + fn default() -> Self { + const MIB: u64 = 1024 * 1024; + Limits { + max_input: 1024 * MIB, + max_entries: 10_000, + max_entry: 64 * MIB, + max_total: 512 * MIB, + max_ratio: 100, + max_xml: 32 * MIB as usize, + max_depth: 256, + max_chapters: 5_000, + max_images: 5_000, + max_text: 256 * MIB as usize, + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Series { + pub name: String, + pub index: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Metadata { + pub title: Option, + pub authors: Vec, + pub language: Option, + pub identifiers: Vec, + /// The first valid ISBN among the identifiers, as ISBN-13. + pub isbn: Option, + pub publisher: Option, + pub published: Option, + /// Plain text. + pub description: Option, + pub subjects: Vec, + pub series: Option, +} + +/// One chapter: the sanitized tree and its serialization. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Chapter { + /// Stable within the book: the spine path (EPUB) or `chapter-`. + pub href: String, + pub title: Option, + pub linear: bool, + /// `
…
`: insert with an XML parser, never `innerHTML`. + pub xhtml: String, + /// SHA-256 of `xhtml`, hex. + pub hash: String, + /// Length of the chapter's text in UTF-16 code units. + pub text_len: usize, + #[serde(skip)] + pub root: Element, +} + +impl Chapter { + /// The chapter's text: every text node in document order, nothing added. + pub fn text(&self) -> String { + let mut s = String::new(); + self.root.collect_text(&mut s); + s + } +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct TocEntry { + pub title: String, + pub chapter: usize, + pub fragment: Option, + pub children: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Image { + pub index: usize, + pub media_type: &'static str, + #[serde(skip)] + pub bytes: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Document { + pub format: Format, + pub metadata: Metadata, + pub chapters: Vec, + pub toc: Vec, + /// `"#"` → the note's sanitized XHTML, for the footnote popover. + pub footnotes: BTreeMap, + pub images: Vec, + pub cover: Option, + /// Things dropped on the way (remote images, unreadable chapters), for the import report. + pub warnings: Vec, +} + +impl Document { + /// The book's text fingerprint (docs/FORMATS.md §6). + pub fn fingerprint(&self) -> String { + let mut all = String::new(); + for c in &self.chapters { + c.root.collect_text(&mut all); + all.push(' '); + } + text::fingerprint(&all) + } +} + +/// What the bytes are, by content (the name is only a hint for TXT and FB2). +pub fn sniff(bytes: &[u8], name: Option<&str>) -> Option { + if bytes.starts_with(b"%PDF-") { + return Some(Format::Pdf); + } + if bytes.len() >= 68 && &bytes[60..68] == b"BOOKMOBI" { + return Some(Format::Mobi); + } + if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") { + let lower = name.map(|n| n.to_lowercase()).unwrap_or_default(); + return Some(if lower.ends_with(".fb2.zip") || lower.ends_with(".fbz") { Format::Fb2 } else { Format::Epub }); + } + let head = &bytes[..bytes.len().min(4096)]; + if text::find(head, b", limits: &Limits) -> Result { + if bytes.len() as u64 > limits.max_input { + return Err(FormatError::TooLarge(format!("the file is larger than {} MiB", limits.max_input >> 20))); + } + drm::refuse_other_containers(bytes)?; + let mut doc = match sniff(bytes, name) { + Some(Format::Pdf) => return Err(FormatError::Pdf), + Some(Format::Mobi) => mobi::open(bytes, limits)?, + Some(Format::Epub) => { + let zip = zip::Zip::parse(bytes, limits)?; + if is_fb2_zip(&zip) { fb2::open_zip(&zip, limits)? } else { epub::open(&zip, limits)? } + } + Some(Format::Fb2) => { + if bytes.starts_with(b"PK") { + fb2::open_zip(&zip::Zip::parse(bytes, limits)?, limits)? + } else { + fb2::open(bytes, limits)? + } + } + _ => txt::open(bytes, name, limits)?, + }; + if doc.chapters.is_empty() { + return Err(FormatError::Malformed("the book has no readable text".into())); + } + doc.metadata.isbn = doc.metadata.identifiers.iter().find_map(|i| text::isbn13(i)); + Ok(doc) +} + +fn is_fb2_zip(zip: &zip::Zip) -> bool { + zip.find("mimetype").is_none() + && zip.find("META-INF/container.xml").is_none() + && zip.entries().iter().filter(|e| !e.is_dir()).count() == 1 + && zip.entries().iter().any(|e| e.name.to_lowercase().ends_with(".fb2")) +} + +/// Builds a chapter from its sanitized tree. +pub(crate) fn chapter(href: String, title: Option, linear: bool, root: Element) -> Chapter { + let xhtml = sanitize::serialize(&root); + let hash = text::sha256_hex(xhtml.as_bytes()); + let text_len = root.text_len_utf16(); + let title = title.or_else(|| root.first_heading()).map(|t| text::collapse(&t)).filter(|t| !t.is_empty()); + Chapter { href, title, linear, xhtml, hash, text_len, root } +} diff --git a/crates/liber-format/src/mobi.rs b/crates/liber-format/src/mobi.rs new file mode 100644 index 0000000..7f82f43 --- /dev/null +++ b/crates/liber-format/src/mobi.rs @@ -0,0 +1,493 @@ +//! DRM-free MOBI (6) and AZW3 (KF8): the PalmDB records, PalmDOC LZ77 and HUFF/CDIC decompression, the trailing +//! entries, EXTH metadata, images by record. Every offset and count read from the file is checked against it. + +use crate::html; +use crate::sanitize::{Resolver, is_remote, sanitize}; +use crate::xml::XEl; +use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, drm, text}; + +fn be16(d: &[u8], o: usize) -> Option { + Some(u16::from_be_bytes(d.get(o..o + 2)?.try_into().ok()?)) +} +fn be32(d: &[u8], o: usize) -> Option { + Some(u32::from_be_bytes(d.get(o..o + 4)?.try_into().ok()?)) +} +fn bad(w: &str) -> FormatError { + FormatError::Malformed(format!("the MOBI file is broken ({w})")) +} + +/// The PalmDB's records, as slices. +fn records(d: &[u8]) -> Result> { + let n = be16(d, 76).ok_or_else(|| bad("header"))? as usize; + if n == 0 || 78 + n * 8 > d.len() { + return Err(bad("record list")); + } + let mut offs = Vec::with_capacity(n); + for i in 0..n { + offs.push(be32(d, 78 + i * 8).ok_or_else(|| bad("record list"))? as usize); + } + let mut out = Vec::with_capacity(n); + for i in 0..n { + let start = offs[i]; + let end = if i + 1 < n { offs[i + 1] } else { d.len() }; + if start > end || end > d.len() { + return Err(bad("a record lies outside the file")); + } + out.push(&d[start..end]); + } + Ok(out) +} + +/// PalmDOC LZ77, writing at most `cap` bytes. +pub(crate) fn palmdoc(data: &[u8], out: &mut Vec, cap: usize) -> Result<()> { + let start = out.len(); + let mut i = 0; + while i < data.len() { + if out.len() - start > cap { + return Err(bad("a text record inflates past its size")); + } + let c = data[i]; + i += 1; + match c { + 0x00 | 0x09..=0x7f => out.push(c), + 0x01..=0x08 => { + let n = c as usize; + let lit = data.get(i..i + n).ok_or_else(|| bad("a literal runs past the record"))?; + out.extend_from_slice(lit); + i += n; + } + 0x80..=0xbf => { + let next = *data.get(i).ok_or_else(|| bad("a back-reference is cut off"))?; + i += 1; + let v = ((c as usize) << 8) | next as usize; + let dist = (v >> 3) & 0x7ff; + let len = (v & 7) + 3; + if dist == 0 || dist > out.len() - start { + return Err(bad("a back-reference points before the record")); + } + for _ in 0..len { + let b = out[out.len() - dist]; + out.push(b); + } + } + _ => { + out.push(b' '); + out.push(c ^ 0x80); + } + } + } + Ok(()) +} + +/// HUFF/CDIC (calibre's `huffcdic.py`, rewritten with bounds). +struct Huff { + dict1: Vec<(u32, bool, u64)>, + mincode: [u64; 33], + maxcode: [u64; 33], + dict: Vec<(Vec, bool)>, +} + +impl Huff { + fn new(huff: &[u8], cdics: &[&[u8]]) -> Result { + if !huff.starts_with(b"HUFF") { + return Err(bad("the HUFF record")); + } + let off1 = be32(huff, 8).ok_or_else(|| bad("HUFF"))? as usize; + let off2 = be32(huff, 12).ok_or_else(|| bad("HUFF"))? as usize; + let mut dict1 = Vec::with_capacity(256); + for i in 0..256 { + let v = be32(huff, off1 + i * 4).ok_or_else(|| bad("HUFF table 1"))?; + let codelen = v & 0x1f; + let term = v & 0x80 != 0; + if codelen == 0 || (codelen <= 8 && !term) { + return Err(bad("HUFF table 1")); + } + let maxcode = (((v >> 8) as u64 + 1) << (32 - codelen)).wrapping_sub(1); + dict1.push((codelen, term, maxcode)); + } + let mut mincode = [0u64; 33]; + let mut maxcode = [0u64; 33]; + for codelen in 1..=32usize { + let lo = be32(huff, off2 + (codelen - 1) * 8).ok_or_else(|| bad("HUFF table 2"))? as u64; + let hi = be32(huff, off2 + (codelen - 1) * 8 + 4).ok_or_else(|| bad("HUFF table 2"))? as u64; + mincode[codelen] = lo << (32 - codelen); + maxcode[codelen] = ((hi + 1) << (32 - codelen)).wrapping_sub(1); + } + let mut dict = Vec::new(); + for c in cdics { + if !c.starts_with(b"CDIC") { + return Err(bad("a CDIC record")); + } + let phrases = be32(c, 8).ok_or_else(|| bad("CDIC"))? as usize; + let bits = be32(c, 12).ok_or_else(|| bad("CDIC"))?; + if bits > 24 { + return Err(bad("CDIC")); + } + let n = (1usize << bits).min(phrases.saturating_sub(dict.len())); + for i in 0..n { + let off = be16(c, 16 + i * 2).ok_or_else(|| bad("CDIC offsets"))? as usize; + let blen = be16(c, 16 + off).ok_or_else(|| bad("CDIC phrase"))? as usize; + let len = blen & 0x7fff; + let data = c.get(18 + off..18 + off + len).ok_or_else(|| bad("CDIC phrase"))?; + dict.push((data.to_vec(), blen & 0x8000 != 0)); + } + } + Ok(Huff { dict1, mincode, maxcode, dict }) + } + + fn unpack(&mut self, data: &[u8], out: &mut Vec, depth: usize, cap: usize) -> Result<()> { + if depth > 32 { + return Err(bad("HUFF phrases nest too deep")); + } + let mut bitsleft = data.len() as i64 * 8; + let mut padded = data.to_vec(); + padded.extend_from_slice(&[0; 8]); + let mut pos = 0usize; + let rd = |p: usize| u64::from_be_bytes(padded[p..p + 8].try_into().unwrap_or([0; 8])); + let mut x = rd(0); + let mut n: i64 = 32; + loop { + if out.len() > cap { + return Err(bad("HUFF output past its size")); + } + if n <= 0 { + pos += 4; + if pos + 8 > padded.len() { + break; + } + x = rd(pos); + n += 32; + } + let code = (x >> n) & 0xffff_ffff; + let (mut codelen, term, mut maxcode) = self.dict1[(code >> 24) as usize]; + if !term { + while codelen < 32 && code < self.mincode[codelen as usize] { + codelen += 1; + } + maxcode = self.maxcode[codelen as usize]; + } + n -= codelen as i64; + bitsleft -= codelen as i64; + if bitsleft < 0 { + break; + } + let r = (maxcode.wrapping_sub(code) >> (32 - codelen)) as usize; + let (slice, done) = self.dict.get(r).cloned().ok_or_else(|| bad("a HUFF code outside the dictionary"))?; + if done { + out.extend_from_slice(&slice); + } else { + // Mark as in progress, so a cycle fails instead of looping. + self.dict[r] = (Vec::new(), true); + let mut expanded = Vec::new(); + self.unpack(&slice, &mut expanded, depth + 1, cap)?; + out.extend_from_slice(&expanded); + self.dict[r] = (expanded, true); + } + } + Ok(()) + } +} + +/// The trailing entries at the end of a text record (calibre's `getSizeOfTrailingDataEntries`). +fn trailing(rec: &[u8], flags: u16) -> usize { + let mut num = 0usize; + let mut f = flags >> 1; + while f != 0 { + if f & 1 != 0 && num < rec.len() { + let end = rec.len() - num; + let mut v = 0usize; + for &b in &rec[end.saturating_sub(4)..end] { + if b & 0x80 != 0 { + v = 0; + } + v = (v << 7) | (b & 0x7f) as usize; + } + num += v; + } + f >>= 1; + } + if flags & 1 != 0 && num < rec.len() { + num += (rec[rec.len() - num - 1] & 0x3) as usize + 1; + } + num.min(rec.len()) +} + +struct Exth { + entries: Vec<(u32, Vec)>, +} + +impl Exth { + fn get(&self, t: u32) -> Option { + self.entries.iter().find(|(k, _)| *k == t).map(|(_, v)| text::collapse(&String::from_utf8_lossy(v))) + } + fn all(&self, t: u32) -> Vec { + self.entries.iter().filter(|(k, _)| *k == t).map(|(_, v)| text::collapse(&String::from_utf8_lossy(v))).collect() + } + fn u32(&self, t: u32) -> Option { + self.entries + .iter() + .find(|(k, v)| *k == t && v.len() == 4) + .map(|(_, v)| u32::from_be_bytes([v[0], v[1], v[2], v[3]])) + } +} + +fn exth(r0: &[u8], header_len: usize) -> Exth { + let mut entries = Vec::new(); + let flags = be32(r0, 0x80).unwrap_or(0); + let at = 16 + header_len; + if flags & 0x40 != 0 && r0.get(at..at + 4) == Some(b"EXTH") { + let count = be32(r0, at + 8).unwrap_or(0) as usize; + let mut p = at + 12; + for _ in 0..count.min(4096) { + let (Some(t), Some(len)) = (be32(r0, p), be32(r0, p + 4)) else { break }; + let len = len as usize; + if len < 8 { + break; + } + match r0.get(p + 8..p + len) { + Some(v) => entries.push((t, v.to_vec())), + None => break, + } + p += len; + } + } + Exth { entries } +} + +/// One MOBI section (a MOBI 6 file, or the KF8 half of a combined file) starting at record `base`. +struct Section<'a> { + recs: &'a [&'a [u8]], + base: usize, + exth: Exth, + version: u32, + encoding: u32, + title: Option, + first_resource: usize, +} + +fn section<'a>(recs: &'a [&'a [u8]], base: usize) -> Result> { + let r0 = *recs.get(base).ok_or_else(|| bad("record 0"))?; + if r0.get(16..20) != Some(b"MOBI") { + return Err(bad("no MOBI header")); + } + drm::mobi(r0)?; + let header_len = be32(r0, 20).ok_or_else(|| bad("MOBI header"))? as usize; + let encoding = be32(r0, 28).unwrap_or(1252); + let version = be32(r0, 36).unwrap_or(6); + let name_off = be32(r0, 84).unwrap_or(0) as usize; + let name_len = be32(r0, 88).unwrap_or(0) as usize; + let title = + r0.get(name_off..name_off.saturating_add(name_len)).map(|b| decode(b, encoding)).filter(|s| !s.is_empty()); + let first_resource = be32(r0, 0x6c).unwrap_or(u32::MAX) as usize; + Ok(Section { recs, base, exth: exth(r0, header_len), version, encoding, title, first_resource }) +} + +fn decode(b: &[u8], encoding: u32) -> String { + if encoding == 65001 { + String::from_utf8_lossy(b).into_owned() + } else { + encoding_rs::WINDOWS_1252.decode_without_bom_handling(b).0.into_owned() + } +} + +fn text_of(s: &Section, limits: &Limits) -> Result> { + let r0 = s.recs[s.base]; + let compression = be16(r0, 0).ok_or_else(|| bad("PalmDOC header"))?; + let text_len = be32(r0, 4).ok_or_else(|| bad("PalmDOC header"))? as usize; + let count = be16(r0, 8).ok_or_else(|| bad("PalmDOC header"))? as usize; + let header_len = be32(r0, 20).unwrap_or(0) as usize; + let flags = if header_len >= 0xe4 { be16(r0, 0xf2).unwrap_or(0) } else { 0 }; + let cap = text_len.min(limits.max_text); + if s.base + count >= s.recs.len() { + return Err(bad("more text records than records")); + } + let mut out = Vec::with_capacity(cap.min(64 * 1024 * 1024)); + let mut huff = if compression == 17480 { + let first = be32(r0, 0x70).ok_or_else(|| bad("HUFF index"))? as usize + s.base; + let n = be32(r0, 0x74).ok_or_else(|| bad("HUFF count"))? as usize; + if n == 0 || first + n > s.recs.len() { + return Err(bad("HUFF records outside the file")); + } + Some(Huff::new(s.recs[first], &s.recs[first + 1..first + n])?) + } else { + None + }; + for i in 1..=count { + let rec = s.recs[s.base + i]; + let rec = &rec[..rec.len() - trailing(rec, flags)]; + let room = cap.saturating_sub(out.len()) + 8192; + match compression { + 1 => out.extend_from_slice(&rec[..rec.len().min(room)]), + 2 => palmdoc(rec, &mut out, room)?, + 17480 => { + let start = out.len(); + huff.as_mut().ok_or_else(|| bad("HUFF"))?.unpack(rec, &mut out, 0, start + room)?; + } + c => return Err(FormatError::Unsupported(format!("MOBI compression {c}"))), + } + if out.len() >= cap { + break; + } + } + out.truncate(cap); + Ok(out) +} + +struct Ctx<'a> { + section: &'a Section<'a>, + images: Vec, + loaded: std::collections::HashMap>, + limits: &'a Limits, +} + +impl Ctx<'_> { + fn resource(&mut self, n: usize) -> Option { + if let Some(r) = self.loaded.get(&n) { + return *r; + } + let r = (|| { + if n == 0 || self.images.len() >= self.limits.max_images || self.section.first_resource == u32::MAX as usize + { + return None; + } + let rec = *self.section.recs.get(self.section.base + self.section.first_resource + n - 1)?; + let media_type = crate::epub::raster(rec)?; + let index = self.images.len(); + self.images.push(Image { index, media_type, bytes: rec.to_vec() }); + Some(index) + })(); + self.loaded.insert(n, r); + r + } +} + +impl Resolver for Ctx<'_> { + fn link(&mut self, _href: &str) -> Option { + // `filepos` and `kindle:pos` links are not mapped in v0.1 (docs/FORMATS.md §7): the text stays. + None + } + + fn image(&mut self, src: &str) -> Option { + if let Some(rest) = src.strip_prefix("kindle:embed:") { + let digits: String = rest.chars().take_while(|c| c.is_ascii_alphanumeric()).collect(); + let n = usize::from_str_radix(&digits, 32).ok()?; + return self.resource(n); + } + // MOBI 6: `recindex` arrives here as `recindex:`. + if let Some(r) = src.strip_prefix("recindex:") { + let n: usize = r.trim_start_matches('0').parse().ok()?; + return self.resource(n); + } + if is_remote(src) { + return None; + } + None + } +} + +/// MOBI 6 writes ``; give it a `src` the resolver understands. +fn fix_recindex(e: &mut XEl) { + let mut stack: Vec<&mut XEl> = vec![e]; + while let Some(el) = stack.pop() { + if el.is("img") + && let Some(r) = el.attr("recindex").map(str::to_owned) + { + el.attrs.retain(|(k, _)| k != "src"); + el.attrs.push(("src".into(), format!("recindex:{r}"))); + } + for c in el.children.iter_mut() { + if let crate::xml::XNode::El(child) = c { + stack.push(child); + } + } + } +} + +/// Splits the text into chapter-sized HTML pieces: KF8 at each new document, MOBI 6 at page breaks. +fn pieces(t: &str, kf8: bool) -> Vec { + let lower = t.to_ascii_lowercase(); + let marks: Vec = if kf8 { + lower.match_indices(" prev { + out.push(t[prev..m].to_owned()); + } + prev = m; + } + out.push(t[prev..].to_owned()); + out.retain(|p| !p.trim().is_empty()); + out +} + +pub(crate) fn open(bytes: &[u8], limits: &Limits) -> Result { + let recs = records(bytes)?; + let first = section(&recs, 0)?; + // A combined file: EXTH 121 points at the KF8 half, which is preferred. + let kf8_base = first.exth.u32(121).map(|b| b as usize).filter(|&b| b > 0 && b < recs.len()); + let sec = match kf8_base { + Some(b) => match section(&recs, b) { + Ok(s) => s, + Err(FormatError::Drm) => return Err(FormatError::Drm), + Err(_) => first, + }, + None => first, + }; + let kf8 = sec.version >= 8; + let raw = text_of(&sec, limits)?; + let t = decode(&raw, sec.encoding); + + let mut md = Metadata { + title: sec.exth.get(503).or_else(|| sec.title.clone()), + authors: sec.exth.all(100), + publisher: sec.exth.get(101), + description: sec.exth.get(103).map(|d| crate::epub::plain(&d)), + subjects: sec.exth.all(105), + published: sec.exth.get(106), + language: sec.exth.get(524), + ..Metadata::default() + }; + md.identifiers = sec.exth.all(104); + let mut ctx = Ctx { section: &sec, images: Vec::new(), loaded: Default::default(), limits }; + let parts = pieces(&t, kf8); + if parts.len() > limits.max_chapters { + return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters))); + } + let mut chapters = Vec::new(); + let mut toc = Vec::new(); + for (i, p) in parts.iter().enumerate() { + let mut doc = html::parse(p, limits)?; + fix_recindex(&mut doc); + let body = doc.child("body").cloned().unwrap_or(doc); + let s = sanitize(&body, &mut ctx); + let ch = crate::chapter(format!("chapter-{i}"), None, true, s.root); + if ch.text_len == 0 && ch.root.descendants().iter().all(|e| e.name != "img") { + continue; + } + if let Some(title) = &ch.title { + toc.push(crate::TocEntry { + title: title.clone(), + chapter: chapters.len(), + fragment: None, + children: vec![], + }); + } + chapters.push(ch); + } + let cover = sec.exth.u32(201).and_then(|c| ctx.resource(c as usize + 1)); + let images = ctx.images; + Ok(Document { + format: if kf8 { Format::Azw3 } else { Format::Mobi }, + metadata: md, + chapters, + toc, + footnotes: Default::default(), + images, + cover, + warnings: vec![], + }) +} diff --git a/crates/liber-format/src/position.rs b/crates/liber-format/src/position.rs new file mode 100644 index 0000000..6d1b5e9 --- /dev/null +++ b/crates/liber-format/src/position.rs @@ -0,0 +1,312 @@ +//! Positions (docs/FORMATS.md §5): CFI points over the sanitized chapter tree, and anchors that degrade to +//! "approximate" or "lost" instead of pointing at other text. + +use crate::Document; +use crate::sanitize::{Element, Node}; +use crate::text::{byte_at_utf16, utf16_len}; +use serde::{Deserialize, Serialize}; + +const CONTEXT: usize = 32; + +/// A point in a chapter: `epubcfi(/6/<2(chapter+1)>!/4:)`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Point { + pub chapter: usize, + pub steps: Vec, + /// UTF-16 code units into the text node. + pub offset: u32, +} + +impl Point { + pub fn to_cfi(&self) -> String { + let mut s = format!("epubcfi(/6/{}!/4", 2 * (self.chapter + 1)); + for st in &self.steps { + s.push_str(&format!("/{st}")); + } + s.push_str(&format!(":{})", self.offset)); + s + } + + pub fn parse(cfi: &str) -> Option { + let inner = cfi.trim().strip_prefix("epubcfi(")?.strip_suffix(')')?; + let (pkg, path) = inner.split_once('!')?; + let spine: u32 = pkg.strip_prefix("/6/")?.split('[').next()?.parse().ok()?; + if spine < 2 || !spine.is_multiple_of(2) { + return None; + } + let (path, offset) = match path.rsplit_once(':') { + Some((p, o)) => (p, o.parse().ok()?), + None => (path, 0), + }; + let mut parts = path.split('/').skip(1); + if parts.next()?.split('[').next()? != "4" { + return None; + } + let mut steps = Vec::new(); + for p in parts { + let n: u32 = p.split('[').next()?.parse().ok()?; + if n == 0 { + return None; + } + steps.push(n); + } + if steps.len() > 512 { + return None; + } + Some(Point { chapter: (spine / 2 - 1) as usize, steps, offset }) + } +} + +/// One text node: its CFI steps, where it starts in the chapter's text (UTF-16), and its text. +struct TextNode<'a> { + steps: Vec, + start: usize, + text: &'a str, +} + +fn text_nodes(root: &Element) -> Vec> { + fn walk<'a>(e: &'a Element, path: &mut Vec, at: &mut usize, out: &mut Vec>) { + let mut k = 0u32; + for c in &e.children { + match c { + Node::Element(child) => { + k += 1; + path.push(2 * k); + walk(child, path, at, out); + path.pop(); + } + Node::Text(t) => { + let mut steps = path.clone(); + steps.push(2 * k + 1); + out.push(TextNode { steps, start: *at, text: t }); + *at += utf16_len(t); + } + } + } + } + let mut out = Vec::new(); + walk(root, &mut Vec::new(), &mut 0, &mut out); + out +} + +/// The point at a UTF-16 offset into the chapter's text. At a boundary between two text nodes, `end` picks the +/// earlier node (the end of a range) and otherwise the later one (the start of a range). +pub fn point_at(chapter: usize, root: &Element, offset: usize, end: bool) -> Point { + let nodes = text_nodes(root); + let before = |n: &&TextNode| offset > n.start && offset <= n.start + utf16_len(n.text); + let after = |n: &&TextNode| offset >= n.start && offset < n.start + utf16_len(n.text); + let pick = if end { + nodes.iter().find(before).or_else(|| nodes.iter().find(after)) + } else { + nodes.iter().find(after).or_else(|| nodes.iter().find(before)) + } + .or_else(|| nodes.last()); + match pick { + Some(n) => { + let len = utf16_len(n.text); + let o = offset.saturating_sub(n.start).min(len); + Point { chapter, steps: n.steps.clone(), offset: o as u32 } + } + None => Point { chapter, steps: vec![], offset: 0 }, + } +} + +/// The UTF-16 offset into the chapter's text that a point names, if it names one. +pub fn offset_of(root: &Element, p: &Point) -> Option { + let nodes = text_nodes(root); + if let Some(n) = nodes.iter().find(|n| n.steps == p.steps) { + let o = p.offset as usize; + return (o <= utf16_len(n.text)).then_some(n.start + o); + } + // A point on an element (an even last step): the start of its text. + if p.steps.last().is_some_and(|s| s % 2 == 0) && p.offset == 0 { + return nodes.iter().find(|n| n.steps.starts_with(&p.steps)).map(|n| n.start); + } + if p.steps.is_empty() && p.offset == 0 { + return Some(0); + } + None +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Quote { + pub exact: String, + pub prefix: String, + pub suffix: String, +} + +/// What a highlight, note or bookmark stores about where it is. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Anchor { + pub chapter: usize, + pub start: String, + pub end: String, + pub chapter_hash: String, + pub quote: Quote, +} + +/// Where an anchor is in a document. Offsets are UTF-16 into the chapter's text. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Resolved { + Exact { chapter: usize, start: usize, end: usize }, + Approximate { chapter: usize, start: usize, end: usize }, + Lost, +} + +fn u16_of_byte(s: &str, b: usize) -> usize { + utf16_len(&s[..b]) +} + +fn tail_chars(s: &str, n: usize) -> String { + let v: Vec = s.chars().collect(); + v[v.len().saturating_sub(n)..].iter().collect() +} + +fn head_chars(s: &str, n: usize) -> String { + s.chars().take(n).collect() +} + +/// An anchor for `[start, end)` (UTF-16) in a chapter; `None` if the range is empty or outside the text. +pub fn anchor(doc: &Document, chapter: usize, start: usize, end: usize) -> Option { + let ch = doc.chapters.get(chapter)?; + let text = ch.text(); + let (bs, be) = (byte_at_utf16(&text, start)?, byte_at_utf16(&text, end)?); + if bs >= be { + return None; + } + Some(Anchor { + chapter, + start: point_at(chapter, &ch.root, start, false).to_cfi(), + end: point_at(chapter, &ch.root, end, true).to_cfi(), + chapter_hash: ch.hash.clone(), + quote: Quote { + exact: text[bs..be].to_owned(), + prefix: tail_chars(&text[..bs], CONTEXT), + suffix: head_chars(&text[be..], CONTEXT), + }, + }) +} + +fn common_suffix(a: &str, b: &str) -> usize { + a.chars().rev().zip(b.chars().rev()).take_while(|(x, y)| x == y).count() +} + +fn common_prefix(a: &str, b: &str) -> usize { + a.chars().zip(b.chars()).take_while(|(x, y)| x == y).count() +} + +/// Lowercased, whitespace runs to one space; with each output char's byte index in the input. +fn normalized(s: &str) -> (String, Vec) { + let mut out = String::new(); + let mut map = Vec::new(); + let mut space = false; + for (i, c) in s.char_indices() { + if c.is_whitespace() { + if !space { + out.push(' '); + map.push(i); + } + space = true; + } else { + space = false; + for l in c.to_lowercase() { + out.push(l); + map.push(i); + } + } + } + map.push(s.len()); + (out, map) +} + +pub fn resolve(doc: &Document, a: &Anchor) -> Resolved { + if a.quote.exact.is_empty() { + return Resolved::Lost; + } + if let Some(ch) = doc.chapters.get(a.chapter) + && let (Some(ps), Some(pe)) = (Point::parse(&a.start), Point::parse(&a.end)) + && let (Some(s), Some(e)) = (offset_of(&ch.root, &ps), offset_of(&ch.root, &pe)) + && s < e + { + let text = ch.text(); + if let (Some(bs), Some(be)) = (byte_at_utf16(&text, s), byte_at_utf16(&text, e)) { + let same = text[bs..be] == a.quote.exact; + if same && ch.hash == a.chapter_hash { + return Resolved::Exact { chapter: a.chapter, start: s, end: e }; + } + if same + && tail_chars(&text[..bs], CONTEXT) == a.quote.prefix + && head_chars(&text[be..], CONTEXT) == a.quote.suffix + { + return Resolved::Exact { chapter: a.chapter, start: s, end: e }; + } + } + } + // Search: the anchor's chapter first, then outwards. + let mut order: Vec = (0..doc.chapters.len()).collect(); + order.sort_by_key(|&i| (i as i64 - a.chapter as i64).unsigned_abs()); + for exact_pass in [true, false] { + for &ci in &order { + let text = doc.chapters[ci].text(); + let hits = if exact_pass { find_exact(&text, &a.quote) } else { find_loose(&text, &a.quote) }; + let mut hits: Vec<(usize, usize, usize)> = hits; // (score, byte start, byte end) + if hits.is_empty() { + continue; + } + hits.sort_by_key(|h| std::cmp::Reverse(h.0)); + if hits.len() > 1 && hits[0].0 == hits[1].0 { + // Two equally good places: never guess. + return Resolved::Lost; + } + let (_, bs, be) = hits[0]; + return Resolved::Approximate { chapter: ci, start: u16_of_byte(&text, bs), end: u16_of_byte(&text, be) }; + } + } + Resolved::Lost +} + +fn find_exact(text: &str, q: &Quote) -> Vec<(usize, usize, usize)> { + let mut out = Vec::new(); + let mut from = 0; + while let Some(p) = text[from..].find(&q.exact) { + let bs = from + p; + let be = bs + q.exact.len(); + let score = common_suffix(&text[..bs], &q.prefix) + common_prefix(&text[be..], &q.suffix); + out.push((score, bs, be)); + if out.len() >= 1000 { + break; + } + from = bs + q.exact.chars().next().map_or(1, char::len_utf8); + } + out +} + +fn find_loose(text: &str, q: &Quote) -> Vec<(usize, usize, usize)> { + let (nt, map) = normalized(text); + let (nq, _) = normalized(&q.exact); + let nq = nq.trim(); + if nq.chars().count() < 8 { + return Vec::new(); + } + let (np, _) = normalized(&q.prefix); + let (ns, _) = normalized(&q.suffix); + let mut out = Vec::new(); + let mut from = 0; + while let Some(p) = nt[from..].find(nq) { + let s = from + p; + let e = s + nq.len(); + let score = common_suffix(&nt[..s], &np) + common_prefix(&nt[e..], &ns); + // Map normalized byte offsets back to the original text. + let cs = nt[..s].chars().count(); + let ce = nt[..e].chars().count(); + if let (Some(&bs), Some(&be)) = (map.get(cs), map.get(ce)) { + out.push((score, bs, be)); + } + if out.len() >= 1000 { + break; + } + from = s + nq.chars().next().map_or(1, char::len_utf8); + } + out +} diff --git a/crates/liber-format/src/sanitize.rs b/crates/liber-format/src/sanitize.rs new file mode 100644 index 0000000..d16c35a --- /dev/null +++ b/crates/liber-format/src/sanitize.rs @@ -0,0 +1,348 @@ +//! The sanitizer (docs/FORMATS.md §3, §4): a whitelist from the parsed tree to Liber's own tree, and the +//! serializer that turns that tree into well-formed XHTML the WebView's XML parser reads back unchanged. + +use crate::xml::{XEl, XNode, local}; + +/// Dropped with everything inside. +pub(crate) const DROP: &[&str] = &[ + "script", "style", "iframe", "frame", "frameset", "object", "embed", "applet", "form", "input", "button", "select", + "textarea", "option", "optgroup", "datalist", "output", "noscript", "template", "audio", "video", "source", + "track", "canvas", "link", "meta", "base", "title", "head", "math", "param", "map", "area", "dialog", "portal", + "slot", "picture", "keygen", "menu", "marquee", "frame", +]; + +/// Kept (with the attribute whitelist); everything else is unwrapped. +const KEEP: &[&str] = &[ + "p", + "div", + "span", + "section", + "article", + "aside", + "header", + "footer", + "main", + "nav", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "blockquote", + "pre", + "code", + "em", + "i", + "strong", + "b", + "u", + "s", + "sub", + "sup", + "small", + "br", + "hr", + "ul", + "ol", + "li", + "dl", + "dt", + "dd", + "table", + "thead", + "tbody", + "tfoot", + "tr", + "td", + "th", + "caption", + "colgroup", + "col", + "figure", + "figcaption", + "img", + "a", + "abbr", + "cite", + "q", + "dfn", + "kbd", + "samp", + "var", + "mark", + "ruby", + "rt", + "rp", + "bdi", + "bdo", + "wbr", + "time", + "del", + "ins", +]; + +const VOID: &[&str] = &["br", "hr", "img", "wbr", "col"]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Node { + Element(Element), + Text(String), +} + +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Element { + pub name: String, + pub attrs: Vec<(String, String)>, + pub children: Vec, +} + +impl Element { + pub fn new(name: &str) -> Element { + Element { name: name.to_owned(), ..Element::default() } + } + + pub fn attr(&self, k: &str) -> Option<&str> { + self.attrs.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str()) + } + + /// Appends text, merged with a preceding text node; characters XML cannot carry are dropped here, so the tree + /// and its serialization hold the same text. + pub fn push_text(&mut self, t: &str) { + let t: String = t + .chars() + .filter(|&c| !((c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r')) && c != '\u{FFFE}' && c != '\u{FFFF}') + .collect(); + if t.is_empty() { + return; + } + if let Some(Node::Text(last)) = self.children.last_mut() { + last.push_str(&t); + } else { + self.children.push(Node::Text(t)); + } + } + + pub fn push(&mut self, e: Element) { + self.children.push(Node::Element(e)); + } + + /// Every text node below, in order (iterative). + pub fn collect_text(&self, out: &mut String) { + let mut stack: Vec<&Node> = self.children.iter().rev().collect(); + while let Some(n) = stack.pop() { + match n { + Node::Text(t) => out.push_str(t), + Node::Element(e) => stack.extend(e.children.iter().rev()), + } + } + } + + pub fn text(&self) -> String { + let mut s = String::new(); + self.collect_text(&mut s); + s + } + + pub fn text_len_utf16(&self) -> usize { + crate::text::utf16_len(&self.text()) + } + + pub fn element_children(&self) -> impl Iterator { + self.children.iter().filter_map(|c| if let Node::Element(e) = c { Some(e) } else { None }) + } + + /// Every descendant element, in document order (iterative). + pub fn descendants(&self) -> Vec<&Element> { + let mut out = Vec::new(); + let mut stack: Vec<&Element> = self.element_children().collect::>().into_iter().rev().collect(); + while let Some(e) = stack.pop() { + out.push(e); + stack.extend(e.element_children().collect::>().into_iter().rev()); + } + out + } + + pub fn first_heading(&self) -> Option { + self.descendants() + .into_iter() + .find(|e| matches!(e.name.as_str(), "h1" | "h2" | "h3" | "h4" | "h5" | "h6")) + .map(|h| h.text()) + } +} + +/// Resolves links and images while sanitizing. Both answer `None` for anything outside the book. +pub(crate) trait Resolver { + /// `href` as written → `"#"` (or `""`). + fn link(&mut self, href: &str) -> Option; + /// `src` as written → the image's index. + fn image(&mut self, src: &str) -> Option; +} + +pub(crate) fn is_remote(url: &str) -> bool { + let u = url.trim().to_ascii_lowercase(); + u.starts_with("//") || u.split_once(':').is_some_and(|(s, _)| !s.contains('/') && s.len() > 1) +} + +pub(crate) struct Sanitized { + pub root: Element, + pub notes: Vec<(String, String)>, + pub dropped: usize, +} + +/// Sanitizes the children of `body` into a chapter root. +pub(crate) fn sanitize(body: &XEl, r: &mut dyn Resolver) -> Sanitized { + let mut root = Element::new("div"); + let mut dropped = 0; + children(body, &mut root, r, &mut dropped); + let notes = collect_notes(&root); + Sanitized { root, notes, dropped } +} + +fn children(from: &XEl, to: &mut Element, r: &mut dyn Resolver, dropped: &mut usize) { + for c in &from.children { + match c { + XNode::Text(t) => to.push_text(t), + XNode::El(e) => one(e, to, r, dropped), + } + } +} + +fn one(e: &XEl, to: &mut Element, r: &mut dyn Resolver, dropped: &mut usize) { + let name = e.local().to_ascii_lowercase(); + if name == "svg" { + // An SVG cover page: keep its one raster image, drop the rest of the SVG. + if let Some(img) = e.find("image") + && let Some(href) = img.attr("xlink:href").or_else(|| img.attr("href")) + && let Some(i) = r.image(href) + { + let mut out = Element::new("img"); + out.attrs.push(("data-img".into(), i.to_string())); + out.attrs.push(("alt".into(), String::new())); + to.push(out); + } else { + *dropped += 1; + } + return; + } + if DROP.contains(&name.as_str()) { + return; + } + if !KEEP.contains(&name.as_str()) { + children(e, to, r, dropped); + return; + } + let mut out = Element::new(&name); + for (k, v) in &e.attrs { + let kl = k.to_ascii_lowercase(); + let ll = local(&kl); + let v = v.trim(); + match (kl.as_str(), ll) { + ("epub:type", _) => out.attrs.push(("data-epub-type".into(), short(v))), + (_, "id") if !kl.contains(':') || kl == "xml:id" => out.attrs.push(("id".into(), short(v))), + ("lang" | "xml:lang", _) => out.attrs.push(("lang".into(), short(v))), + ("title" | "dir" | "alt", _) => out.attrs.push((kl.clone(), short(v))), + ("colspan" | "rowspan", _) if v.len() <= 3 && v.bytes().all(|b| b.is_ascii_digit()) => { + out.attrs.push((kl.clone(), v.to_owned())) + } + ("href", _) if name == "a" => { + if let Some(t) = r.link(v) { + out.attrs.push(("data-href".into(), t)); + } + } + ("src", _) if name == "img" => { + if let Some(i) = r.image(v) { + out.attrs.push(("data-img".into(), i.to_string())); + } + } + _ => {} + } + } + if name == "img" && out.attr("data-img").is_none() { + *dropped += 1; + return; + } + // One attribute of a name: the first wins. + let mut seen = std::collections::BTreeSet::new(); + out.attrs.retain(|(k, _)| seen.insert(k.clone())); + if !VOID.contains(&name.as_str()) { + children(e, &mut out, r, dropped); + } + to.push(out); +} + +fn short(v: &str) -> String { + v.chars().filter(|c| !c.is_control()).take(1024).collect() +} + +fn note_type(t: &str) -> bool { + t.split_whitespace().any(|w| matches!(w, "footnote" | "endnote" | "rearnote" | "note")) +} + +fn collect_notes(root: &Element) -> Vec<(String, String)> { + let mut out = Vec::new(); + for e in root.descendants() { + let is_note = e.attr("data-epub-type").is_some_and(note_type) || e.name == "aside"; + if is_note && let Some(id) = e.attr("id") { + let mut wrap = Element::new("div"); + wrap.children = e.children.clone(); + out.push((id.to_owned(), serialize(&wrap))); + } + } + out +} + +fn esc(s: &str, out: &mut String, attr: bool) { + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' if attr => out.push_str("""), + // XML 1.0 forbids most controls; drop them rather than break the document. + c if (c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r') => {} + '\r' => out.push_str(" "), + '\u{FFFE}' | '\u{FFFF}' => {} + c => out.push(c), + } + } +} + +/// The root as `
…
`. +pub fn serialize(root: &Element) -> String { + let mut out = String::new(); + out.push_str("
"); + // Iterative: (element, child index) frames. + let mut stack: Vec<(&Element, usize)> = vec![(root, 0)]; + while let Some((e, i)) = stack.pop() { + if i < e.children.len() { + stack.push((e, i + 1)); + match &e.children[i] { + Node::Text(t) => esc(t, &mut out, false), + Node::Element(c) => { + out.push('<'); + out.push_str(&c.name); + for (k, v) in &c.attrs { + out.push(' '); + out.push_str(k); + out.push_str("=\""); + esc(v, &mut out, true); + out.push('"'); + } + if c.children.is_empty() && VOID.contains(&c.name.as_str()) { + out.push_str("/>"); + } else { + out.push('>'); + stack.push((c, 0)); + } + } + } + } else if !std::ptr::eq(e, root) { + out.push_str("'); + } + } + out.push_str("
"); + out +} diff --git a/crates/liber-format/src/text.rs b/crates/liber-format/src/text.rs new file mode 100644 index 0000000..f700d44 --- /dev/null +++ b/crates/liber-format/src/text.rs @@ -0,0 +1,181 @@ +//! Text helpers: decoding, hashing, the text fingerprint, ISBNs. + +use sha2::{Digest, Sha256}; +use unicode_normalization::UnicodeNormalization; + +pub fn sha256_hex(bytes: &[u8]) -> String { + let d = Sha256::digest(bytes); + let mut s = String::with_capacity(64); + for b in d { + s.push_str(&format!("{b:02x}")); + } + s +} + +/// SHA-256 of the text, NFKC-normalised, lowercased, letters and digits only (docs/FORMATS.md §6). +pub fn fingerprint(text: &str) -> String { + let mut h = Sha256::new(); + let mut buf = [0u8; 4]; + for c in text.nfkc() { + if c.is_alphanumeric() { + for l in c.to_lowercase() { + h.update(l.encode_utf8(&mut buf).as_bytes()); + } + } + } + let d = h.finalize(); + d.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The first position of `needle` in `hay`. +pub fn find(hay: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() || hay.len() < needle.len() { + return None; + } + hay.windows(needle.len()).position(|w| w == needle) +} + +/// Whitespace runs to one space, trimmed. +pub fn collapse(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut space = false; + for c in s.chars() { + if c.is_whitespace() { + space = !out.is_empty(); + } else { + if space { + out.push(' '); + space = false; + } + out.push(c); + } + } + out +} + +pub fn utf16_len(s: &str) -> usize { + s.chars().map(char::len_utf16).sum() +} + +/// The byte index in `s` of UTF-16 offset `u`, or `None` past the end or inside a surrogate pair. +pub fn byte_at_utf16(s: &str, u: usize) -> Option { + let mut n = 0; + for (i, c) in s.char_indices() { + if n == u { + return Some(i); + } + n += c.len_utf16(); + if n > u { + return None; + } + } + (n == u).then_some(s.len()) +} + +/// Decodes a text file: BOM, then strict UTF-8, then detection with the Czech hint (Windows-1250 and friends). +/// Returns the text and the encoding's name. +pub fn decode_text(bytes: &[u8]) -> (String, &'static str) { + if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) { + let (s, _) = enc.decode_without_bom_handling(&bytes[bom..]); + return (s.into_owned(), enc.name()); + } + if let Ok(s) = std::str::from_utf8(bytes) { + return (s.to_owned(), "UTF-8"); + } + let mut det = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Deny); + det.feed(bytes, true); + let enc = det.guess(Some(b"cz"), chardetng::Utf8Detection::Allow); + let (s, _) = enc.decode_without_bom_handling(bytes); + (s.into_owned(), enc.name()) +} + +/// Decodes an XML document: BOM, then the declaration's `encoding`, else UTF-8 (lossy). +pub fn decode_xml(bytes: &[u8]) -> String { + if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) { + return enc.decode_without_bom_handling(&bytes[bom..]).0.into_owned(); + } + let head = &bytes[..bytes.len().min(512)]; + if head.starts_with(b"") + { + let decl = String::from_utf8_lossy(&head[..end]).to_lowercase(); + if let Some(p) = decl.find("encoding") { + let rest = &decl[p + 8..]; + let rest = rest.trim_start().strip_prefix('=').unwrap_or(rest).trim_start(); + let q = rest.chars().next().unwrap_or('"'); + let label: String = rest.chars().skip(1).take_while(|&c| c != q).collect(); + if let Some(enc) = encoding_rs::Encoding::for_label(label.trim().as_bytes()) + && enc != encoding_rs::UTF_8 + { + return enc.decode_without_bom_handling(bytes).0.into_owned(); + } + } + } + String::from_utf8_lossy(bytes).into_owned() +} + +/// An ISBN-10 or ISBN-13 (with or without hyphens, `urn:isbn:` or `isbn:`), check digit verified, as ISBN-13. +pub fn isbn13(s: &str) -> Option { + let s = s.trim(); + let lower = s.to_lowercase(); + let s = lower.strip_prefix("urn:isbn:").or_else(|| lower.strip_prefix("isbn:")).unwrap_or(&lower).trim(); + let chars: Vec = s.chars().filter(|c| !matches!(c, '-' | ' ')).collect(); + if chars.len() == 13 && chars.iter().all(char::is_ascii_digit) { + let d: Vec = chars.iter().map(|c| c.to_digit(10).unwrap_or(0)).collect(); + let sum: u32 = d[..12].iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum(); + let check = (10 - sum % 10) % 10; + if check == d[12] && (chars.starts_with(&['9', '7', '8']) || chars.starts_with(&['9', '7', '9'])) { + return Some(chars.iter().collect()); + } + return None; + } + if chars.len() == 10 + && chars[..9].iter().all(char::is_ascii_digit) + && (chars[9].is_ascii_digit() || chars[9] == 'x') + { + let sum: u32 = chars + .iter() + .enumerate() + .map(|(i, c)| (10 - i as u32) * if *c == 'x' { 10 } else { c.to_digit(10).unwrap_or(0) }) + .sum(); + if !sum.is_multiple_of(11) { + return None; + } + let body: String = std::iter::once("978".to_owned()).chain(chars[..9].iter().map(|c| c.to_string())).collect(); + let d: Vec = body.chars().map(|c| c.to_digit(10).unwrap_or(0)).collect(); + let sum: u32 = d.iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum(); + return Some(format!("{body}{}", (10 - sum % 10) % 10)); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn isbns() { + assert_eq!(isbn13("978-0-441-17271-9").as_deref(), Some("9780441172719")); + assert_eq!(isbn13("0441172717").as_deref(), Some("9780441172719")); + assert_eq!(isbn13("urn:isbn:080442957X").as_deref(), Some("9780804429573")); + assert_eq!(isbn13("9780441172718"), None); + assert_eq!(isbn13("urn:uuid:1234"), None); + } + + #[test] + fn utf16() { + let s = "a😀b"; + assert_eq!(utf16_len(s), 4); + assert_eq!(byte_at_utf16(s, 3), Some(5)); + assert_eq!(byte_at_utf16(s, 2), None); + assert_eq!(byte_at_utf16(s, 4), Some(6)); + } + + #[test] + fn windows_1250() { + let (enc_bytes, _, _) = + encoding_rs::WINDOWS_1250.encode("Příliš žluťoučký kůň úpěl ďábelské ódy. Šťastný Řehoř."); + let (s, name) = decode_text(&enc_bytes); + assert!(s.starts_with("Příliš žluťoučký"), "{s} ({name})"); + } +} diff --git a/crates/liber-format/src/txt.rs b/crates/liber-format/src/txt.rs new file mode 100644 index 0000000..1845ec0 --- /dev/null +++ b/crates/liber-format/src/txt.rs @@ -0,0 +1,129 @@ +//! Plain text: encoding detection, paragraphs, chapters by heading lines or by size. + +use crate::sanitize::Element; +use crate::{Document, Format, FormatError, Limits, Metadata, Result, TocEntry, text}; + +const CHUNK: usize = 40_000; + +fn roman(s: &str) -> bool { + let s = s.trim_end_matches('.'); + !s.is_empty() && s.len() <= 8 && s.chars().all(|c| matches!(c, 'I' | 'V' | 'X' | 'L' | 'C')) +} + +/// A heading line: `Chapter 3`, `KAPITOLA III.`, `Kapitel 3`, a lone Roman numeral or number. +pub(crate) fn heading(p: &str) -> bool { + let p = p.trim(); + if p.is_empty() || p.chars().count() > 80 || p.contains('\n') { + return false; + } + if roman(p) + || (p.trim_end_matches('.').len() <= 3 + && p.trim_end_matches('.').chars().all(|c| c.is_ascii_digit()) + && !p.is_empty()) + { + return true; + } + const NUMBERS: &[&str] = &[ + "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "first", + "second", "third", "last", "první", "druhá", "třetí", "eins", "zwei", "drei", + ]; + let lower = p.to_lowercase(); + for w in ["chapter", "kapitola", "kapitel", "část", "part", "book", "kniha", "buch", "teil"] { + if let Some(rest) = lower.strip_prefix(w) + && rest.starts_with(' ') + { + let next = rest.split_whitespace().next().unwrap_or("").trim_end_matches(['.', ':']); + return (!next.is_empty() && next.chars().all(|c| c.is_ascii_digit())) + || roman(&next.to_uppercase()) + || NUMBERS.contains(&next); + } + } + ["prologue", "epilogue", "prolog", "epilog"].iter().any(|w| lower == *w || lower.starts_with(&format!("{w}:"))) +} + +pub(crate) fn open(bytes: &[u8], name: Option<&str>, limits: &Limits) -> Result { + let (raw, _enc) = text::decode_text(bytes); + if raw.len() > limits.max_text { + return Err(FormatError::TooLarge("the text is larger than the limit".into())); + } + if raw.chars().take(4096).filter(|c| *c == '\u{0}').count() > 16 { + return Err(FormatError::Unsupported("this does not look like a book (binary data)".into())); + } + let s = raw.replace("\r\n", "\n").replace('\r', "\n"); + let blank_separated = s.contains("\n\n"); + let paras: Vec = if blank_separated { + s.split("\n\n") + .map(|p| p.lines().map(str::trim).filter(|l| !l.is_empty()).collect::>().join(" ")) + .collect() + } else { + s.lines().map(|l| l.trim().to_owned()).collect() + }; + let paras: Vec = paras.into_iter().filter(|p| !p.is_empty()).collect(); + + let mut meta = Metadata::default(); + // Project Gutenberg's header. + for line in s.lines().take(100) { + if let Some(t) = line.strip_prefix("Title:") { + meta.title.get_or_insert_with(|| text::collapse(t)); + } else if let Some(a) = line.strip_prefix("Author:") { + if meta.authors.is_empty() { + meta.authors.push(text::collapse(a)); + } + } else if let Some(l) = line.strip_prefix("Language:") { + meta.language.get_or_insert_with(|| text::collapse(l)); + } + } + if meta.title.is_none() { + meta.title = name.map(|n| { + let base = n.rsplit(['/', '\\']).next().unwrap_or(n); + base.rsplit_once('.').map_or(base, |(b, _)| b).replace('_', " ") + }); + } + + // Chapters: at heading lines; else by size. + let mut groups: Vec<(Option, Vec)> = Vec::new(); + let has_headings = paras.iter().filter(|p| heading(p)).count() >= 2; + for p in paras { + if has_headings && heading(&p) { + groups.push((Some(p), Vec::new())); + continue; + } + let size: usize = groups.last().map_or(0, |g| g.1.iter().map(String::len).sum()); + if groups.is_empty() || (!has_headings && size > CHUNK) { + groups.push((None, Vec::new())); + } + if let Some(g) = groups.last_mut() { + g.1.push(p); + } + } + if groups.len() > limits.max_chapters { + return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters))); + } + let mut chapters = Vec::new(); + let mut toc = Vec::new(); + for (i, (title, ps)) in groups.into_iter().enumerate() { + let mut root = Element::new("div"); + if let Some(t) = &title { + let mut h = Element::new("h2"); + h.push_text(t); + root.push(h); + toc.push(TocEntry { title: text::collapse(t), chapter: i, fragment: None, children: vec![] }); + } + for p in ps { + let mut e = Element::new("p"); + e.push_text(&p); + root.push(e); + } + chapters.push(crate::chapter(format!("chapter-{i}"), title, true, root)); + } + Ok(Document { + format: Format::Txt, + metadata: meta, + chapters, + toc, + footnotes: Default::default(), + images: vec![], + cover: None, + warnings: vec![], + }) +} diff --git a/crates/liber-format/src/xml.rs b/crates/liber-format/src/xml.rs new file mode 100644 index 0000000..3de581f --- /dev/null +++ b/crates/liber-format/src/xml.rs @@ -0,0 +1,220 @@ +//! A small owned XML tree over quick-xml, for OPF, NCX, nav, FB2 and well-formed XHTML. Entity declarations are +//! refused; only XML's and HTML's named entities and numeric references resolve; depth is capped while building, +//! with an explicit stack, so no input recurses. + +use crate::{FormatError, Limits, Result, entities}; +use quick_xml::XmlVersion; +use quick_xml::events::{BytesStart, Event}; + +#[derive(Clone, Debug)] +pub(crate) enum XNode { + El(XEl), + Text(String), +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct XEl { + /// The qualified name as written (`dc:title`). + pub name: String, + pub attrs: Vec<(String, String)>, + pub children: Vec, +} + +pub(crate) fn local(q: &str) -> &str { + q.rsplit(':').next().unwrap_or(q) +} + +impl XEl { + pub fn new(name: &str) -> XEl { + XEl { name: name.to_owned(), ..XEl::default() } + } + + pub fn local(&self) -> &str { + local(&self.name) + } + + pub fn is(&self, l: &str) -> bool { + self.local().eq_ignore_ascii_case(l) + } + + /// An attribute by exact qualified name, else by local name. + pub fn attr(&self, name: &str) -> Option<&str> { + self.attrs + .iter() + .find(|(k, _)| k == name) + .or_else(|| self.attrs.iter().find(|(k, _)| local(k).eq_ignore_ascii_case(local(name)))) + .map(|(_, v)| v.as_str()) + } + + pub fn elements(&self) -> impl Iterator { + self.children.iter().filter_map(|c| if let XNode::El(e) = c { Some(e) } else { None }) + } + + pub fn child(&self, l: &str) -> Option<&XEl> { + self.elements().find(|e| e.is(l)) + } + + pub fn children_named<'s>(&'s self, l: &'s str) -> impl Iterator + 's { + self.elements().filter(move |e| e.is(l)) + } + + /// Every descendant element in document order (iterative). + pub fn descendants(&self) -> Vec<&XEl> { + let mut out = Vec::new(); + let mut stack: Vec<&XEl> = self.elements().collect::>().into_iter().rev().collect(); + while let Some(e) = stack.pop() { + out.push(e); + let kids: Vec<&XEl> = e.elements().collect(); + stack.extend(kids.into_iter().rev()); + } + out + } + + pub fn find(&self, l: &str) -> Option<&XEl> { + self.descendants().into_iter().find(|e| e.is(l)) + } + + /// All text below, in order (iterative). + pub fn text(&self) -> String { + let mut s = String::new(); + let mut stack: Vec<&XNode> = self.children.iter().rev().collect(); + while let Some(n) = stack.pop() { + match n { + XNode::Text(t) => s.push_str(t), + XNode::El(e) => stack.extend(e.children.iter().rev()), + } + } + s + } + + pub fn push_text(&mut self, t: &str) { + if t.is_empty() { + return; + } + if let Some(XNode::Text(last)) = self.children.last_mut() { + last.push_str(t); + } else { + self.children.push(XNode::Text(t.to_owned())); + } + } +} + +fn element(e: &BytesStart) -> XEl { + let name = e.name().as_ref().to_owned(); + let mut attrs = Vec::new(); + for a in e.attributes().with_checks(false).flatten() { + let key = a.key.as_ref().to_owned(); + let value = match a.normalized_value_with(XmlVersion::Implicit1_0, 16, entities::resolve) { + Ok(v) => v.into_owned(), + Err(_) => a.value.to_string(), + }; + attrs.push((key, value)); + } + XEl { name, attrs, children: Vec::new() } +} + +/// Parses a whole document and returns its root element. +pub(crate) fn parse(s: &str, limits: &Limits) -> Result { + if s.len() > limits.max_xml { + return Err(FormatError::TooLarge(format!("an XML document over {} MiB", limits.max_xml >> 20))); + } + let mut r = quick_xml::Reader::from_str(s); + { + let c = r.config_mut(); + c.check_end_names = true; + c.trim_text(false); + } + let mut stack: Vec = Vec::new(); + let mut skip = 0usize; + let mut root: Option = None; + loop { + let ev = + r.read_event().map_err(|e| FormatError::Malformed(format!("XML at byte {}: {e}", r.buffer_position())))?; + match ev { + Event::Eof => break, + Event::DocType(t) => { + let d = t.xml10_content().to_ascii_lowercase(); + if d.contains(" { + if root.is_some() { + return Err(FormatError::Malformed("XML: content after the root element".into())); + } + if skip > 0 || stack.len() >= limits.max_depth { + skip += 1; + } else { + stack.push(element(&e)); + } + } + Event::Empty(e) => { + if skip == 0 && stack.len() < limits.max_depth { + let el = element(&e); + match stack.last_mut() { + Some(top) => top.children.push(XNode::El(el)), + None if root.is_none() => root = Some(el), + None => return Err(FormatError::Malformed("XML: two root elements".into())), + } + } + } + Event::End(_) => { + if skip > 0 { + skip -= 1; + } else if let Some(done) = stack.pop() { + match stack.last_mut() { + Some(top) => top.children.push(XNode::El(done)), + None => root = Some(done), + } + } + } + Event::Text(t) => { + if let Some(top) = stack.last_mut() { + top.push_text(&t.xml10_content()); + } + } + Event::CData(t) => { + if let Some(top) = stack.last_mut() { + top.push_text(&t.xml10_content()); + } + } + Event::GeneralRef(g) => { + if let Some(top) = stack.last_mut() { + let resolved: String = if g.is_char_ref() { + match g.resolve_char_ref() { + Ok(Some(c)) => c.to_string(), + _ => String::new(), + } + } else { + let name = g.xml10_content(); + match entities::resolve(&name) { + Some(v) => v.to_owned(), + None => format!("&{name};"), + } + }; + top.push_text(&resolved); + } + } + _ => {} + } + } + if !stack.is_empty() { + return Err(FormatError::Malformed("XML: the document ends inside an element".into())); + } + root.ok_or_else(|| FormatError::Malformed("XML: no root element".into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn entities_and_depth() { + let l = Limits { max_depth: 3, ..Limits::default() }; + let root = parse("x& A&unknown;deep", &l).unwrap(); + assert_eq!(root.text(), "x&\u{a0}A&unknown;deep"); + assert!(root.find("d").is_none()); + let err = parse("]>&x;", &l).unwrap_err(); + assert!(matches!(err, FormatError::Unsafe(_))); + } +} diff --git a/crates/liber-format/src/zip.rs b/crates/liber-format/src/zip.rs new file mode 100644 index 0000000..d4263fc --- /dev/null +++ b/crates/liber-format/src/zip.rs @@ -0,0 +1,361 @@ +//! A small zip reader and writer, written for hostile input (docs/FORMATS.md §3): the central directory is checked +//! entry by entry before anything is read, names are refused rather than cleaned, and inflation stops at a cap that +//! never trusts the sizes the archive declares. Stored and deflate only; no ZIP64, no encryption. + +use crate::{FormatError, Limits, Result}; +use std::cell::Cell; +use std::io::{self, Read, Write}; + +const EOCD: u32 = 0x0605_4b50; +const CENTRAL: u32 = 0x0201_4b50; +const LOCAL: u32 = 0x0403_4b50; +const DESCRIPTOR: u32 = 0x0807_4b50; +const MIB: u64 = 1024 * 1024; + +#[derive(Clone, Debug)] +pub struct Entry { + pub name: String, + method: u16, + crc: u32, + csize: u64, + usize: u64, + local: u64, +} + +impl Entry { + pub fn is_dir(&self) -> bool { + self.name.ends_with('/') + } + /// The size the archive declares (never trusted for allocation). + pub fn declared_size(&self) -> u64 { + self.usize + } +} + +/// A parsed archive over borrowed bytes. +pub struct Zip<'a> { + data: &'a [u8], + entries: Vec, + limits: Limits, + inflated: Cell, +} + +fn u16_at(d: &[u8], o: usize) -> Option { + Some(u16::from_le_bytes(d.get(o..o + 2)?.try_into().ok()?)) +} +fn u32_at(d: &[u8], o: usize) -> Option { + Some(u32::from_le_bytes(d.get(o..o + 4)?.try_into().ok()?)) +} +fn bad(w: &str) -> FormatError { + FormatError::Malformed(format!("the archive is broken ({w})")) +} + +/// Whether a name may appear in an archive Liber reads: relative, no `..`, no backslash, no drive, no controls. +pub fn safe_name(name: &str) -> bool { + if name.is_empty() || name.len() > 1024 { + return false; + } + if name.starts_with('/') || name.contains('\\') || name.chars().any(|c| c.is_control()) { + return false; + } + let b = name.as_bytes(); + if b.len() >= 2 && b[1] == b':' { + return false; + } + !name.split('/').any(|seg| seg == "..") +} + +impl<'a> Zip<'a> { + pub fn parse(data: &'a [u8], limits: &Limits) -> Result> { + if data.len() < 22 { + return Err(bad("too short")); + } + let from = data.len().saturating_sub(22 + 65_535); + let eocd = (from..=data.len() - 22) + .rev() + .find(|&i| u32_at(data, i) == Some(EOCD)) + .ok_or_else(|| bad("no end of central directory: the file is truncated or not a zip"))?; + let count = u16_at(data, eocd + 10).ok_or_else(|| bad("eocd"))? as usize; + let cd_size = u32_at(data, eocd + 12).ok_or_else(|| bad("eocd"))? as u64; + let cd_off = u32_at(data, eocd + 16).ok_or_else(|| bad("eocd"))? as u64; + if count == 0xFFFF || cd_size == 0xFFFF_FFFF || cd_off == 0xFFFF_FFFF { + return Err(FormatError::Unsupported("ZIP64 archives".into())); + } + if u16_at(data, eocd + 4) != Some(0) || u16_at(data, eocd + 6) != Some(0) { + return Err(FormatError::Unsupported("multi-part archives".into())); + } + if count > limits.max_entries { + return Err(FormatError::TooLarge(format!("more than {} files in the archive", limits.max_entries))); + } + if cd_off + cd_size > eocd as u64 { + return Err(bad("the central directory points past its end")); + } + let mut entries = Vec::with_capacity(count); + let mut p = cd_off as usize; + for _ in 0..count { + if u32_at(data, p) != Some(CENTRAL) { + return Err(bad("a central directory entry")); + } + let made_by = u16_at(data, p + 4).ok_or_else(|| bad("entry"))?; + let flags = u16_at(data, p + 8).ok_or_else(|| bad("entry"))?; + let method = u16_at(data, p + 10).ok_or_else(|| bad("entry"))?; + let crc = u32_at(data, p + 16).ok_or_else(|| bad("entry"))?; + let csize = u32_at(data, p + 20).ok_or_else(|| bad("entry"))? as u64; + let usize = u32_at(data, p + 24).ok_or_else(|| bad("entry"))? as u64; + let nlen = u16_at(data, p + 28).ok_or_else(|| bad("entry"))? as usize; + let elen = u16_at(data, p + 30).ok_or_else(|| bad("entry"))? as usize; + let clen = u16_at(data, p + 32).ok_or_else(|| bad("entry"))? as usize; + let external = u32_at(data, p + 38).ok_or_else(|| bad("entry"))?; + let local = u32_at(data, p + 42).ok_or_else(|| bad("entry"))? as u64; + let raw = data.get(p + 46..p + 46 + nlen).ok_or_else(|| bad("an entry name"))?; + let name = String::from_utf8_lossy(raw).into_owned(); + if !safe_name(&name) { + return Err(FormatError::Unsafe(format!("the archive contains the path {name:?}"))); + } + if made_by >> 8 == 3 && (external >> 16) & 0o170000 == 0o120000 { + return Err(FormatError::Unsafe(format!("the archive contains a symbolic link ({name})"))); + } + if flags & 1 != 0 { + return Err(FormatError::Unsupported("password-protected archives".into())); + } + if csize == 0xFFFF_FFFF || usize == 0xFFFF_FFFF || local == 0xFFFF_FFFF { + return Err(FormatError::Unsupported("ZIP64 archives".into())); + } + if local + 30 > data.len() as u64 || local + csize > data.len() as u64 { + return Err(bad("an entry points past the end: the file is truncated")); + } + entries.push(Entry { name, method, crc, csize, usize, local }); + p += 46 + nlen + elen + clen; + } + Ok(Zip { data, entries, limits: limits.clone(), inflated: Cell::new(0) }) + } + + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// An entry by exact name, else ignoring ASCII case. + pub fn find(&self, name: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.name == name) + .or_else(|| self.entries.iter().find(|e| e.name.eq_ignore_ascii_case(name))) + } + + /// Reads one entry, inflating at most up to the caps. + pub fn read(&self, e: &Entry) -> Result> { + self.read_capped(e, u64::MAX) + } + + /// Reads one entry with an extra cap for this kind of file (an XML document: `max_xml`). + pub fn read_capped(&self, e: &Entry, extra: u64) -> Result> { + let d = self.data; + let l = e.local as usize; + if u32_at(d, l) != Some(LOCAL) { + return Err(bad("a local header")); + } + let nlen = u16_at(d, l + 26).ok_or_else(|| bad("local"))? as usize; + let elen = u16_at(d, l + 28).ok_or_else(|| bad("local"))? as usize; + let start = l + 30 + nlen + elen; + let body = d.get(start..start + e.csize as usize).ok_or_else(|| bad("an entry is cut off"))?; + let used = self.inflated.get(); + let left = self.limits.max_total.saturating_sub(used); + let mut cap = self.limits.max_entry.min(left).min(extra); + if e.csize > 0 { + cap = cap.min((e.csize.saturating_mul(self.limits.max_ratio)).max(MIB)); + } + let out = match e.method { + 0 => { + if body.len() as u64 > cap { + return Err(FormatError::TooLarge(format!("{} is larger than the limit", e.name))); + } + body.to_vec() + } + 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(body, cap as usize).map_err(|err| { + if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput { + FormatError::TooLarge(format!( + "{} inflates beyond the limit (a zip bomb, or a book over the size cap)", + e.name + )) + } else { + bad(&format!("{} does not inflate", e.name)) + } + })?, + m => return Err(FormatError::Unsupported(format!("compression method {m}"))), + }; + if crc32fast::hash(&out) != e.crc { + return Err(bad(&format!("{} fails its checksum", e.name))); + } + self.inflated.set(used + out.len() as u64); + Ok(out) + } + + pub fn read_name(&self, name: &str) -> Result>> { + self.read_name_capped(name, u64::MAX) + } + + pub fn read_name_capped(&self, name: &str, extra: u64) -> Result>> { + match self.find(name) { + Some(e) => self.read_capped(e, extra).map(Some), + None => Ok(None), + } + } +} + +/// A streaming zip writer: deflated in-memory entries, and stored streams with a data descriptor (no seeking). +pub struct ZipWriter { + w: W, + at: u64, + central: Vec, + count: u16, +} + +impl ZipWriter { + pub fn new(w: W) -> ZipWriter { + ZipWriter { w, at: 0, central: Vec::new(), count: 0 } + } + + fn put(&mut self, b: &[u8]) -> io::Result<()> { + self.w.write_all(b)?; + self.at += b.len() as u64; + Ok(()) + } + + fn check(&self, name: &str) -> io::Result<()> { + if !safe_name(name) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsafe name {name:?}"))); + } + if self.count == u16::MAX - 1 { + return Err(io::Error::other("too many entries for a zip without ZIP64")); + } + Ok(()) + } + + fn header(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32) -> io::Result { + let off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?; + let mut h = Vec::with_capacity(30 + name.len()); + h.extend_from_slice(&LOCAL.to_le_bytes()); + h.extend_from_slice(&20u16.to_le_bytes()); + h.extend_from_slice(&(flags | 0x0800).to_le_bytes()); + h.extend_from_slice(&method.to_le_bytes()); + h.extend_from_slice(&0u16.to_le_bytes()); // time + h.extend_from_slice(&0x21u16.to_le_bytes()); // date 1980-01-01 + h.extend_from_slice(&crc.to_le_bytes()); + h.extend_from_slice(&csize.to_le_bytes()); + h.extend_from_slice(&usize.to_le_bytes()); + h.extend_from_slice(&(name.len() as u16).to_le_bytes()); + h.extend_from_slice(&0u16.to_le_bytes()); + h.extend_from_slice(name.as_bytes()); + self.put(&h)?; + Ok(off) + } + + #[allow(clippy::too_many_arguments)] + fn record(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32, off: u32) { + let c = &mut self.central; + c.extend_from_slice(&CENTRAL.to_le_bytes()); + c.extend_from_slice(&0x0314u16.to_le_bytes()); // made by Unix, 2.0 + c.extend_from_slice(&20u16.to_le_bytes()); + c.extend_from_slice(&(flags | 0x0800).to_le_bytes()); + c.extend_from_slice(&method.to_le_bytes()); + c.extend_from_slice(&0u16.to_le_bytes()); + c.extend_from_slice(&0x21u16.to_le_bytes()); + c.extend_from_slice(&crc.to_le_bytes()); + c.extend_from_slice(&csize.to_le_bytes()); + c.extend_from_slice(&usize.to_le_bytes()); + c.extend_from_slice(&(name.len() as u16).to_le_bytes()); + c.extend_from_slice(&[0; 8]); // extra, comment, disk, internal + c.extend_from_slice(&(0o100644u32 << 16).to_le_bytes()); + c.extend_from_slice(&off.to_le_bytes()); + c.extend_from_slice(name.as_bytes()); + self.count += 1; + } + + /// Adds an in-memory file; `deflate` compresses it. + pub fn add(&mut self, name: &str, data: &[u8], deflate: bool) -> io::Result<()> { + self.check(name)?; + let crc = crc32fast::hash(data); + let usize = u32::try_from(data.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?; + let (method, body) = + if deflate { (8, miniz_oxide::deflate::compress_to_vec(data, 6)) } else { (0, data.to_vec()) }; + let csize = u32::try_from(body.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?; + let off = self.header(name, 0, method, crc, csize, usize)?; + self.put(&body)?; + self.record(name, 0, method, crc, csize, usize, off); + Ok(()) + } + + /// Adds a file streamed from `r`, stored (book files are compressed already), with a data descriptor. + pub fn add_stream(&mut self, name: &str, r: &mut dyn Read) -> io::Result<()> { + self.check(name)?; + let off = self.header(name, 0x0008, 0, 0, 0, 0)?; + let mut hasher = crc32fast::Hasher::new(); + let mut n: u64 = 0; + let mut buf = vec![0u8; 64 * 1024]; + loop { + let k = r.read(&mut buf)?; + if k == 0 { + break; + } + hasher.update(&buf[..k]); + self.put(&buf[..k])?; + n += k as u64; + } + let size = u32::try_from(n).map_err(|_| io::Error::other("an entry over 4 GiB"))?; + let crc = hasher.finalize(); + let mut d = Vec::with_capacity(16); + d.extend_from_slice(&DESCRIPTOR.to_le_bytes()); + d.extend_from_slice(&crc.to_le_bytes()); + d.extend_from_slice(&size.to_le_bytes()); + d.extend_from_slice(&size.to_le_bytes()); + self.put(&d)?; + self.record(name, 0x0008, 0, crc, size, size, off); + Ok(()) + } + + pub fn finish(mut self) -> io::Result { + let cd_off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?; + let central = std::mem::take(&mut self.central); + self.put(¢ral)?; + let mut e = Vec::with_capacity(22); + e.extend_from_slice(&EOCD.to_le_bytes()); + e.extend_from_slice(&[0; 4]); + e.extend_from_slice(&self.count.to_le_bytes()); + e.extend_from_slice(&self.count.to_le_bytes()); + e.extend_from_slice(&(central.len() as u32).to_le_bytes()); + e.extend_from_slice(&cd_off.to_le_bytes()); + e.extend_from_slice(&0u16.to_le_bytes()); + self.put(&e)?; + self.w.flush()?; + Ok(self.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip() { + let mut w = ZipWriter::new(Vec::new()); + w.add("mimetype", b"application/epub+zip", false).unwrap(); + w.add("a/b.txt", "žluťoučký kůň".repeat(100).as_bytes(), true).unwrap(); + w.add_stream("c.bin", &mut &b"streamed"[..]).unwrap(); + let bytes = w.finish().unwrap(); + let z = Zip::parse(&bytes, &Limits::default()).unwrap(); + assert_eq!(z.entries().len(), 3); + assert_eq!(z.read_name("mimetype").unwrap().unwrap(), b"application/epub+zip"); + assert_eq!(z.read_name("a/b.txt").unwrap().unwrap(), "žluťoučký kůň".repeat(100).as_bytes()); + assert_eq!(z.read_name("c.bin").unwrap().unwrap(), b"streamed"); + } + + #[test] + fn names() { + for n in ["../x", "a/../../x", "/etc/passwd", "C:x", "c:/x", "a\\b", "a\0b", ""] { + assert!(!safe_name(n), "{n:?}"); + } + for n in ["OEBPS/content.opf", "a..b/c", "..a", "META-INF/"] { + assert!(safe_name(n), "{n:?}"); + } + } +} diff --git a/crates/liber-format/tests/common/mod.rs b/crates/liber-format/tests/common/mod.rs new file mode 100644 index 0000000..91173fe --- /dev/null +++ b/crates/liber-format/tests/common/mod.rs @@ -0,0 +1,356 @@ +//! Fixture builders: every test book is generated here, so no binary is ever committed. +#![allow(dead_code)] + +use liber_format::zip::ZipWriter; + +pub const CONTAINER: &str = r#" + + +"#; + +pub fn xhtml(body: &str) -> String { + format!( + "\n\nt\ + {body}" + ) +} + +/// An EPUB 3 with the given chapter bodies (`(title, body)`), plus extra files. +pub struct Epub { + pub title: String, + pub chapters: Vec<(String, String)>, + pub extra: Vec<(String, Vec)>, + pub extra_manifest: String, + pub metadata_extra: String, + pub opf_override: Option, +} + +impl Epub { + pub fn new(title: &str) -> Epub { + Epub { + title: title.into(), + chapters: vec![], + extra: vec![], + extra_manifest: String::new(), + metadata_extra: String::new(), + opf_override: None, + } + } + + pub fn chapter(mut self, title: &str, body: &str) -> Epub { + self.chapters.push((title.into(), body.into())); + self + } + + pub fn file(mut self, name: &str, data: &[u8]) -> Epub { + self.extra.push((name.into(), data.to_vec())); + self + } + + pub fn opf(&self) -> String { + if let Some(o) = &self.opf_override { + return o.clone(); + } + let mut manifest = + String::from(r#""#); + let mut spine = String::new(); + for (i, _) in self.chapters.iter().enumerate() { + manifest + .push_str(&format!(r#""#)); + spine.push_str(&format!(r#""#)); + } + manifest.push_str(&self.extra_manifest); + format!( + r##" + + + {}Karel Čapek + aut + Some Translatortrl + csurn:isbn:978-80-207-1247-9 + <p>A <b>play</b> about robots.</p> + Drama + Plays + series2 + {} + +{manifest} +{spine} +"##, + self.title, self.metadata_extra + ) + } + + pub fn nav(&self) -> String { + let mut li = String::new(); + for (i, (t, _)) in self.chapters.iter().enumerate() { + li.push_str(&format!(r#"
  • {t}
  • "#)); + } + xhtml(&format!(r#""#)) + } + + pub fn build(&self) -> Vec { + let mut w = ZipWriter::new(Vec::new()); + w.add("mimetype", b"application/epub+zip", false).unwrap(); + w.add("META-INF/container.xml", CONTAINER.as_bytes(), true).unwrap(); + w.add("OEBPS/content.opf", self.opf().as_bytes(), true).unwrap(); + w.add("OEBPS/nav.xhtml", self.nav().as_bytes(), true).unwrap(); + for (i, (_, body)) in self.chapters.iter().enumerate() { + w.add(&format!("OEBPS/text/ch{i}.xhtml"), xhtml(body).as_bytes(), true).unwrap(); + } + for (n, d) in &self.extra { + w.add(n, d, true).unwrap(); + } + w.finish().unwrap() + } +} + +/// One entry of a hand-made zip, for archives the safe writer refuses to make. +pub struct Raw { + pub name: String, + pub data: Vec, + pub deflate: bool, + pub unix_mode: u32, + /// Overrides the declared uncompressed size. + pub declared: Option, +} + +impl Raw { + pub fn file(name: &str, data: &[u8]) -> Raw { + Raw { name: name.into(), data: data.to_vec(), deflate: true, unix_mode: 0o100644, declared: None } + } +} + +pub fn raw_zip(entries: &[Raw]) -> Vec { + let mut out = Vec::new(); + let mut central = Vec::new(); + for e in entries { + let crc = crc32(&e.data); + let body = if e.deflate { deflate(&e.data) } else { e.data.clone() }; + let method: u16 = if e.deflate { 8 } else { 0 }; + let usize = e.declared.unwrap_or(e.data.len() as u32); + let off = out.len() as u32; + out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + out.extend_from_slice(&20u16.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&method.to_le_bytes()); + out.extend_from_slice(&[0, 0, 0x21, 0]); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&usize.to_le_bytes()); + out.extend_from_slice(&(e.name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(e.name.as_bytes()); + out.extend_from_slice(&body); + central.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); + central.extend_from_slice(&0x0314u16.to_le_bytes()); + central.extend_from_slice(&20u16.to_le_bytes()); + central.extend_from_slice(&0u16.to_le_bytes()); + central.extend_from_slice(&method.to_le_bytes()); + central.extend_from_slice(&[0, 0, 0x21, 0]); + central.extend_from_slice(&crc.to_le_bytes()); + central.extend_from_slice(&(body.len() as u32).to_le_bytes()); + central.extend_from_slice(&usize.to_le_bytes()); + central.extend_from_slice(&(e.name.len() as u16).to_le_bytes()); + central.extend_from_slice(&[0; 8]); + central.extend_from_slice(&(e.unix_mode << 16).to_le_bytes()); + central.extend_from_slice(&off.to_le_bytes()); + central.extend_from_slice(e.name.as_bytes()); + } + let cd_off = out.len() as u32; + out.extend_from_slice(¢ral); + out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + out.extend_from_slice(&(central.len() as u32).to_le_bytes()); + out.extend_from_slice(&cd_off.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out +} + +pub fn crc32(d: &[u8]) -> u32 { + let mut c: u32 = 0xffff_ffff; + for &b in d { + c ^= b as u32; + for _ in 0..8 { + c = if c & 1 != 0 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 }; + } + } + !c +} + +/// Raw deflate with stored blocks only (enough for fixtures; the bomb uses `deflate_zeros`). +pub fn deflate(d: &[u8]) -> Vec { + let mut out = Vec::new(); + let chunks: Vec<&[u8]> = if d.is_empty() { vec![&[][..]] } else { d.chunks(65_535).collect() }; + for (i, c) in chunks.iter().enumerate() { + out.push(if i + 1 == chunks.len() { 1 } else { 0 }); + out.extend_from_slice(&(c.len() as u16).to_le_bytes()); + out.extend_from_slice(&(!(c.len() as u16)).to_le_bytes()); + out.extend_from_slice(c); + } + out +} + +/// A raw deflate stream of `n` zero bytes, tiny (fixed Huffman, length-258 back-references): a bomb. +pub fn deflate_zeros(n: usize) -> Vec { + struct Bits { + out: Vec, + acc: u32, + n: u32, + } + impl Bits { + fn put(&mut self, v: u32, len: u32) { + self.acc |= v << self.n; + self.n += len; + while self.n >= 8 { + self.out.push(self.acc as u8); + self.acc >>= 8; + self.n -= 8; + } + } + fn put_rev(&mut self, code: u32, len: u32) { + let mut r = 0; + for i in 0..len { + r |= ((code >> i) & 1) << (len - 1 - i); + } + self.put(r, len); + } + } + let mut b = Bits { out: vec![], acc: 0, n: 0 }; + b.put(1, 1); // final + b.put(1, 2); // fixed Huffman + // literal 0: code 0x30 (8 bits) + b.put_rev(0x30, 8); + let mut left = n - 1; + while left >= 258 { + // length 258: code 285 → 7-bit code 285-256 = 29 → 0b0011101 (codes 256..279 are 7 bits from 0)... 285 is + // in 280..287: 8 bits, 0xC0 + (285 - 280). + b.put_rev(0xC0 + 5, 8); + // distance 1: code 0 (5 bits), no extra bits + b.put_rev(0, 5); + left -= 258; + } + for _ in 0..left { + b.put_rev(0x30, 8); + } + b.put_rev(0, 7); // end of block (256) + if b.n > 0 { + b.out.push(b.acc as u8); + } + b.out +} + +/// A PalmDB MOBI 6 (or KF8 with `version = 8`) around `html`, uncompressed (1) or PalmDOC literals (2). +pub struct Mobi { + pub html: String, + pub compression: u16, + pub encryption: u16, + pub version: u32, + pub images: Vec>, + pub exth: Vec<(u32, Vec)>, + pub title: String, +} + +impl Mobi { + pub fn new(html: &str) -> Mobi { + Mobi { + html: html.into(), + compression: 2, + encryption: 0, + version: 6, + images: vec![], + exth: vec![], + title: "Mobi Title".into(), + } + } + + pub fn build(&self) -> Vec { + let text = self.html.as_bytes(); + let mut text_recs: Vec> = Vec::new(); + for chunk in text.chunks(4096) { + text_recs.push(match self.compression { + 2 => palmdoc_literals(chunk), + _ => chunk.to_vec(), + }); + } + let mut exth = Vec::new(); + let mut entries = self.exth.clone(); + entries.push((100, "Karel Čapek".as_bytes().to_vec())); + entries.push((104, b"9788020712479".to_vec())); + exth.extend_from_slice(b"EXTH"); + let body_len: usize = entries.iter().map(|(_, v)| 8 + v.len()).sum(); + exth.extend_from_slice(&((12 + body_len) as u32).to_be_bytes()); + exth.extend_from_slice(&(entries.len() as u32).to_be_bytes()); + for (t, v) in &entries { + exth.extend_from_slice(&t.to_be_bytes()); + exth.extend_from_slice(&((8 + v.len()) as u32).to_be_bytes()); + exth.extend_from_slice(v); + } + let header_len: u32 = 0xe8; + let mut r0 = vec![0u8; 16 + header_len as usize]; + r0[0..2].copy_from_slice(&self.compression.to_be_bytes()); + r0[4..8].copy_from_slice(&(text.len() as u32).to_be_bytes()); + r0[8..10].copy_from_slice(&(text_recs.len() as u16).to_be_bytes()); + r0[10..12].copy_from_slice(&4096u16.to_be_bytes()); + r0[12..14].copy_from_slice(&self.encryption.to_be_bytes()); + r0[16..20].copy_from_slice(b"MOBI"); + r0[20..24].copy_from_slice(&header_len.to_be_bytes()); + r0[24..28].copy_from_slice(&2u32.to_be_bytes()); + r0[28..32].copy_from_slice(&65001u32.to_be_bytes()); + r0[36..40].copy_from_slice(&self.version.to_be_bytes()); + let first_image = 1 + text_recs.len() as u32; + r0[0x6c..0x70].copy_from_slice(&first_image.to_be_bytes()); + r0[0x80..0x84].copy_from_slice(&0x40u32.to_be_bytes()); + r0.extend_from_slice(&exth); + let name_off = r0.len() as u32; + r0[84..88].copy_from_slice(&name_off.to_be_bytes()); + r0[88..92].copy_from_slice(&(self.title.len() as u32).to_be_bytes()); + r0.extend_from_slice(self.title.as_bytes()); + r0.extend_from_slice(&[0, 0]); + let mut recs = vec![r0]; + recs.extend(text_recs); + recs.extend(self.images.iter().cloned()); + let mut out = vec![0u8; 78 + recs.len() * 8 + 2]; + out[..10].copy_from_slice(b"liber-test"); + out[60..68].copy_from_slice(b"BOOKMOBI"); + out[76..78].copy_from_slice(&(recs.len() as u16).to_be_bytes()); + let mut off = out.len(); + for (i, r) in recs.iter().enumerate() { + out[78 + i * 8..82 + i * 8].copy_from_slice(&(off as u32).to_be_bytes()); + off += r.len(); + } + for r in recs { + out.extend_from_slice(&r); + } + out + } +} + +/// PalmDOC with literal runs only: bytes 0x09–0x7f as themselves, others in 1–8 byte literal runs. +pub fn palmdoc_literals(d: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < d.len() { + let b = d[i]; + if (0x09..=0x7f).contains(&b) || b == 0 { + out.push(b); + i += 1; + } else { + let n = (d.len() - i).min(8); + out.push(n as u8); + out.extend_from_slice(&d[i..i + n]); + i += n; + } + } + out +} + +/// A 1×1 PNG. +pub const PNG: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, + 0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, + 0x1f, 0, 5, 0, 1, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, +]; diff --git a/crates/liber-format/tests/corpus.rs b/crates/liber-format/tests/corpus.rs new file mode 100644 index 0000000..adc23b9 --- /dev/null +++ b/crates/liber-format/tests/corpus.rs @@ -0,0 +1,19 @@ +//! Opens every file `fixtures-fetch/fetch.mjs` put in `fixtures/fetched/` (none by default): no panic, bounded +//! time, nothing active or remote in the output. + +#[test] +fn fetched_corpus() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched"); + let Ok(entries) = std::fs::read_dir(&dir) else { return }; + for e in entries.flatten() { + let bytes = std::fs::read(e.path()).unwrap(); + let t = std::time::Instant::now(); + if let Ok(d) = liber_format::open(&bytes, e.file_name().to_str(), &liber_format::Limits::default()) { + for c in &d.chapters { + let x = c.xhtml.replacen("http://www.w3.org/1999/xhtml", "", 1); + assert!(!x.contains("První \"obr\"/ text.

    ") + .chapter("Druhá", "

    Heading two

    Text back.

    ") + .file("OEBPS/images/a.png", PNG) + .file("OEBPS/images/cover.png", PNG); + e.extra_manifest = + r#""#.into(); + let d = open(&e.build(), Some("rur.epub"), &Limits::default()).unwrap(); + assert_eq!(d.format, Format::Epub); + assert_eq!(d.metadata.title.as_deref(), Some("R.U.R.")); + assert_eq!(d.metadata.authors, vec!["Karel Čapek"], "translators are not authors"); + assert_eq!(d.metadata.language.as_deref(), Some("cs")); + assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479")); + assert_eq!(d.metadata.description.as_deref(), Some("A play about robots.")); + assert_eq!(d.metadata.series.as_ref().map(|s| (s.name.as_str(), s.index)), Some(("Plays", Some(2.0)))); + assert_eq!(d.toc.len(), 2); + assert_eq!(d.chapters[0].title.as_deref(), Some("Předmluva")); + assert_eq!(d.images.len(), 2); + assert!(d.chapters[0].xhtml.contains("data-img=\"0\"")); + assert_eq!(d.cover, Some(1)); + assert!(d.chapters[1].xhtml.contains("data-href=\"0\"")); +} + +#[test] +fn fb2_in_windows_1251_with_notes_and_images() { + let fb2 = format!( + r##" + +sfАркадийСтругацкий +Пикник на обочинеru + +978-0-441-17271-9 +<p>Пикник</p><p>на обочине</p> +
    <p>Глава 1</p>

    Текст с ударением1.

    +
    +
    <p>Глава 2</p>

    Ещё текст.

    Строка
    + +
    <p>1</p>

    Примечание.

    +{} +
    "##, + b64(PNG) + ); + let (bytes, _, _) = encoding_rs::WINDOWS_1251.encode(&fb2); + let d = open(&bytes, Some("piknik.fb2"), &Limits::default()).unwrap(); + assert_eq!(d.format, Format::Fb2); + assert_eq!(d.metadata.title.as_deref(), Some("Пикник на обочине")); + assert_eq!(d.metadata.authors, vec!["Аркадий Стругацкий"]); + assert_eq!(d.metadata.series.as_ref().map(|s| s.index), Some(Some(3.0))); + assert_eq!(d.metadata.isbn.as_deref(), Some("9780441172719")); + assert_eq!(d.chapters.len(), 4, "title page, two sections, notes"); + assert_eq!(d.chapters[1].title.as_deref(), Some("Глава 1")); + assert!(d.chapters[1].xhtml.contains("ударением")); + let notes = d.chapters.len() - 1; + assert!(d.chapters[1].xhtml.contains(&format!("data-href=\"{notes}#n1\"")), "{}", d.chapters[1].xhtml); + assert!(d.footnotes.get(&format!("{notes}#n1")).is_some_and(|n| n.contains("Примечание"))); + assert!(!d.chapters[notes].linear); + assert_eq!(d.images.len(), 1); + assert_eq!(d.cover, Some(0)); + + // The same book zipped. + let mut w = liber_format::zip::ZipWriter::new(Vec::new()); + w.add("piknik.fb2", &bytes, true).unwrap(); + let z = w.finish().unwrap(); + let dz = open(&z, Some("piknik.fb2.zip"), &Limits::default()).unwrap(); + assert_eq!(dz.format, Format::Fb2); + assert_eq!(dz.fingerprint(), d.fingerprint()); +} + +fn b64(d: &[u8]) -> String { + const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in d.chunks(3) { + let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; + for i in 0..4 { + if i <= c.len() { + s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + s.push('='); + } + } + } + s +} + +#[test] +fn txt_in_windows_1250_with_chapters() { + let text = "Title: Válka s mloky\r\nAuthor: Karel Čapek\r\n\r\nKAPITOLA I.\r\n\r\nKapitán van Toch šel\r\npo břehu.\r\n\r\nŘekl: „Ano.“\r\n\r\nKAPITOLA II.\r\n\r\nMloci přišli.\r\n"; + let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(text); + let d = open(&bytes, Some("valka_s_mloky.txt"), &Limits::default()).unwrap(); + assert_eq!(d.format, Format::Txt); + assert_eq!(d.metadata.title.as_deref(), Some("Válka s mloky")); + assert_eq!(d.metadata.authors, vec!["Karel Čapek"]); + assert_eq!(d.chapters.len(), 3, "front matter and two chapters"); + assert_eq!(d.chapters[1].title.as_deref(), Some("KAPITOLA I.")); + assert!(d.chapters[1].text().contains("Kapitán van Toch šel po břehu."), "hard wraps joined"); + assert!(d.chapters[1].text().contains("„Ano.“")); + // Plain UTF-8 without headings: one chapter, the file name as title. + let d = + open("Just one line of text.\nAnd another.".as_bytes(), Some("C:\\books\\my_notes.txt"), &Limits::default()) + .unwrap(); + assert_eq!(d.chapters.len(), 1); + assert_eq!(d.metadata.title.as_deref(), Some("my notes")); +} + +#[test] +fn mobi6_with_pagebreaks_images_and_exth() { + let mut m = Mobi::new( + "

    Jedna

    Příliš žluťoučký kůň.

    \ +

    Dvě

    Second part.

    Unclosed para", + ); + m.images.push(PNG.to_vec()); + m.exth.push((201, 0u32.to_be_bytes().to_vec())); + m.exth.push((503, b"Updated Title".to_vec())); + let d = open(&m.build(), Some("kun.mobi"), &Limits::default()).unwrap(); + assert_eq!(d.format, Format::Mobi); + assert_eq!(d.metadata.title.as_deref(), Some("Updated Title")); + assert_eq!(d.metadata.authors, vec!["Karel Čapek"]); + assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479")); + assert_eq!(d.chapters.len(), 2); + assert_eq!(d.chapters[0].title.as_deref(), Some("Jedna")); + assert!(d.chapters[0].text().contains("Příliš žluťoučký kůň.")); + assert!(d.chapters[0].xhtml.contains("data-img=\"0\""), "{}", d.chapters[0].xhtml); + assert!(d.chapters[1].xhtml.contains("part")); + assert_eq!(d.cover, Some(0)); + // Uncompressed records read the same. + m.compression = 1; + let d1 = open(&m.build(), None, &Limits::default()).unwrap(); + assert_eq!(d1.fingerprint(), d.fingerprint()); +} + +#[test] +fn azw3_splits_at_documents_and_reads_kindle_embed() { + let mut m = Mobi::new( + "

    First file text.

    \ + \ +

    Second file text.

    ", + ); + m.version = 8; + m.images.push(PNG.to_vec()); + let d = open(&m.build(), Some("x.azw3"), &Limits::default()).unwrap(); + assert_eq!(d.format, Format::Azw3); + assert_eq!(d.chapters.len(), 2); + assert!(d.chapters[0].text().contains("First file text.")); + assert!(d.chapters[0].xhtml.contains("data-img=\"0\"")); + assert!(d.chapters[1].text().contains("Second file text.")); +} + +#[test] +fn the_same_text_in_two_formats_has_one_fingerprint() { + let html = "

    Kapitola

    Stejný text, jiný formát.

    "; + let epub = open(&Epub::new("x").chapter("Kapitola", html).build(), None, &Limits::default()).unwrap(); + let mobi = + open(&Mobi::new(&format!("{html}")).build(), None, &Limits::default()).unwrap(); + assert_eq!(epub.fingerprint(), mobi.fingerprint()); + let other = + open(&Epub::new("x").chapter("Kapitola", "

    Jiný text.

    ").build(), None, &Limits::default()).unwrap(); + assert_ne!(epub.fingerprint(), other.fingerprint()); +} + +#[test] +fn pdf_is_handed_to_the_pdf_view() { + assert_eq!(sniff(b"%PDF-1.7\n...", None), Some(Format::Pdf)); + assert_eq!(open(b"%PDF-1.7\n...", None, &Limits::default()).unwrap_err(), FormatError::Pdf); +} + +#[test] +fn binary_garbage_is_not_a_book() { + let junk: Vec = (0..10_000u32).map(|i| (i * 7 % 256) as u8).collect(); + let r = open(&junk, Some("junk.bin"), &Limits::default()); + assert!(r.is_err() || r.unwrap().chapters.len() <= 1); +} diff --git a/crates/liber-format/tests/fuzz.rs b/crates/liber-format/tests/fuzz.rs new file mode 100644 index 0000000..ea0b5da --- /dev/null +++ b/crates/liber-format/tests/fuzz.rs @@ -0,0 +1,36 @@ +//! Random mutations of valid books never panic and finish in bounded time. + +mod common; +use common::*; +use liber_format::{Limits, open}; +use proptest::prelude::*; + +fn seeds() -> Vec> { + let mut m = + Mobi::new("

    A

    Text ž

    B

    "); + m.images.push(PNG.to_vec()); + vec![ + Epub::new("Fuzz").chapter("One", "

    Hello world x

    ").file("OEBPS/a.png", PNG).build(), + m.build(), + br#"F

    t

    "#.to_vec(), + ] +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + #[test] + fn mutations_never_panic(which in 0usize..3, flips in prop::collection::vec((any::(), any::()), 1..16), cut in any::>()) { + let mut b = seeds().swap_remove(which); + for (at, v) in flips { + let i = at % b.len(); + b[i] = v; + } + if let Some(c) = cut { + b.truncate(c % (b.len() + 1)); + } + let limits = Limits { max_total: 16 << 20, max_entry: 8 << 20, max_xml: 4 << 20, max_text: 8 << 20, ..Limits::default() }; + let t = std::time::Instant::now(); + let _ = open(&b, None, &limits); + prop_assert!(t.elapsed().as_secs() < 5); + } +} diff --git a/crates/liber-format/tests/hostile.rs b/crates/liber-format/tests/hostile.rs new file mode 100644 index 0000000..9992e6e --- /dev/null +++ b/crates/liber-format/tests/hostile.rs @@ -0,0 +1,389 @@ +//! Mandatory test 1: hostile e-books (docs/FORMATS.md §3). Each is refused or sanitized; nothing is written +//! anywhere (the crate has no file-system or network code: `purity.rs`); no remote URL survives. + +mod common; +use common::*; +use liber_format::{DRM_MESSAGE, FormatError, Limits, open}; + +fn epub_with(extra: Vec) -> Vec { + let e = Epub::new("Hostile").chapter("One", "

    Hello.

    "); + let mut entries = vec![ + Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, + Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), + Raw::file("OEBPS/content.opf", e.opf().as_bytes()), + Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), + Raw::file("OEBPS/text/ch0.xhtml", xhtml("

    Hello.

    ").as_bytes()), + ]; + entries.extend(extra); + raw_zip(&entries) +} + +fn err(bytes: &[u8]) -> FormatError { + open(bytes, Some("x.epub"), &Limits::default()).expect_err("must be refused") +} + +#[test] +fn baseline_opens() { + let d = open(&epub_with(vec![]), None, &Limits::default()).unwrap(); + assert_eq!(d.chapters[0].text(), "Hello."); +} + +#[test] +fn zip_slip_is_refused_and_nothing_is_written() { + let marker = format!("liber-zipslip-{}.txt", std::process::id()); + for name in [ + format!("../../{marker}"), + format!("OEBPS/../../{marker}"), + format!("/tmp/{marker}"), + format!("C:{marker}"), + format!("..\\..\\{marker}"), + ] { + let bytes = epub_with(vec![Raw::file(&name, b"pwned")]); + assert!(matches!(err(&bytes), FormatError::Unsafe(_)), "{name}"); + } + for dir in [std::env::current_dir().unwrap(), std::env::temp_dir()] { + let mut d = dir.clone(); + for _ in 0..3 { + assert!(!d.join(&marker).exists(), "{} exists", d.join(&marker).display()); + d.pop(); + } + } +} + +#[test] +fn symlinks_are_refused() { + let link = Raw { unix_mode: 0o120777, deflate: false, ..Raw::file("OEBPS/link.xhtml", b"/etc/passwd") }; + assert!(matches!(err(&epub_with(vec![link])), FormatError::Unsafe(_))); +} + +#[test] +fn zip_bomb_stops_at_the_ratio_cap() { + // 256 MiB of zeros in about 250 kB (about 1000:1), declared as 10 bytes: stopped by the ratio cap. + let bomb = miniz_oxide::deflate::compress_to_vec(&vec![0u8; 256 << 20], 6); + assert!(bomb.len() < 400_000, "{}", bomb.len()); + let bytes = replace_last_entry_body(&[], &bomb, 10); + let t = std::time::Instant::now(); + let e = err(&bytes); + assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}"); + assert!(t.elapsed().as_secs() < 5); +} + +#[test] +fn zip_bomb_under_the_ratio_stops_at_the_xml_cap() { + // 64 MiB of zeros at about 160:1 (fixed Huffman), under the ratio cap: stopped at max_xml for a chapter. + let bomb = deflate_zeros(64 << 20); + assert!(bomb.len() < 500_000, "{}", bomb.len()); + let bytes = replace_last_entry_body(&[], &bomb, 10); + let t = std::time::Instant::now(); + let e = err(&bytes); + assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}"); + assert!(t.elapsed().as_secs() < 5); +} + +/// Rebuilds a raw zip whose last entry's deflated body is `body`, declaring `declared` bytes. +fn replace_last_entry_body(_old: &[u8], body: &[u8], declared: u32) -> Vec { + let e = Epub::new("Bomb").chapter("One", "

    x

    "); + let mut out = raw_zip(&[ + Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, + Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), + Raw::file("OEBPS/content.opf", e.opf().as_bytes()), + Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), + ]); + // Strip the EOCD and central directory of that archive, then append our own entry and directories. + let z = liber_format::zip::Zip::parse(&out, &Limits::default()).unwrap(); + let n = z.entries().len(); + drop(z); + let eocd = out.len() - 22; + let cd_off = u32::from_le_bytes(out[eocd + 16..eocd + 20].try_into().unwrap()) as usize; + let central = out[cd_off..eocd].to_vec(); + out.truncate(cd_off); + let name = b"OEBPS/text/ch0.xhtml"; + let off = out.len() as u32; + let crc = 0u32; // never reached: inflation stops at the cap first + out.extend_from_slice(&0x0403_4b50u32.to_le_bytes()); + out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(&declared.to_le_bytes()); + out.extend_from_slice(&(name.len() as u16).to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(name); + out.extend_from_slice(body); + let mut cd = central; + cd.extend_from_slice(&0x0201_4b50u32.to_le_bytes()); + cd.extend_from_slice(&[0x14, 0x03, 20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]); + cd.extend_from_slice(&crc.to_le_bytes()); + cd.extend_from_slice(&(body.len() as u32).to_le_bytes()); + cd.extend_from_slice(&declared.to_le_bytes()); + cd.extend_from_slice(&(name.len() as u16).to_le_bytes()); + cd.extend_from_slice(&[0; 8]); + cd.extend_from_slice(&(0o100644u32 << 16).to_le_bytes()); + cd.extend_from_slice(&off.to_le_bytes()); + cd.extend_from_slice(name); + let new_cd = out.len() as u32; + out.extend_from_slice(&cd); + out.extend_from_slice(&0x0605_4b50u32.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&((n + 1) as u16).to_le_bytes()); + out.extend_from_slice(&((n + 1) as u16).to_le_bytes()); + out.extend_from_slice(&(cd.len() as u32).to_le_bytes()); + out.extend_from_slice(&new_cd.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out +} + +#[test] +fn many_small_entries_stop_at_the_total_cap() { + let big = vec![b'a'; 900 * 1024]; + let mut extra = Vec::new(); + for i in 0..12 { + extra.push(Raw::file(&format!("OEBPS/img{i}.png"), &big)); + } + let mut epub = Epub::new("Total").chapter("One", ""); + let mut body = String::new(); + for i in 0..12 { + body.push_str(&format!("")); + } + epub.chapters[0].1 = body.clone(); + let mut entries = vec![ + Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, + Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), + Raw::file("OEBPS/content.opf", epub.opf().as_bytes()), + Raw::file("OEBPS/nav.xhtml", epub.nav().as_bytes()), + Raw::file("OEBPS/text/ch0.xhtml", xhtml(&format!("

    x

    {body}")).as_bytes()), + ]; + entries.extend(extra); + let bytes = raw_zip(&entries); + let limits = Limits { max_total: 4 << 20, ..Limits::default() }; + // Images over the total cap are not loaded (and are not raster anyway); the book still opens, bounded. + let d = open(&bytes, None, &limits).unwrap(); + assert_eq!(d.images.len(), 0); + // A chapter over the total cap refuses the book. + let limits = Limits { max_total: 1024, ..Limits::default() }; + assert!(matches!(open(&bytes, None, &limits).unwrap_err(), FormatError::TooLarge(_))); +} + +#[test] +fn too_many_entries() { + let mut extra = Vec::new(); + for i in 0..50 { + extra.push(Raw::file(&format!("f{i}"), b"x")); + } + let limits = Limits { max_entries: 20, ..Limits::default() }; + assert!(matches!(open(&epub_with(extra), None, &limits).unwrap_err(), FormatError::TooLarge(_))); +} + +#[test] +fn xxe_and_billion_laughs_are_refused() { + let xxe_opf = r#"]> +&xxe; +"#; + let mut e = Epub::new("x").chapter("One", "

    Hi

    "); + e.opf_override = Some(xxe_opf.into()); + assert!(matches!(err(&e.build()), FormatError::Unsafe(_))); + + let laughs = "\ + ]>

    &c;

    "; + let mut e = Epub::new("x").chapter("One", ""); + let mut entries = vec![ + Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, + Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), + Raw::file("OEBPS/content.opf", e.opf().as_bytes()), + Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()), + ]; + entries.push(Raw::file("OEBPS/text/ch0.xhtml", laughs.as_bytes())); + e.extra.clear(); + assert!(matches!(err(&raw_zip(&entries)), FormatError::Unsafe(_))); + + // A plain external DTD reference is harmless: nothing is ever fetched, the book opens. + let dtd = "

    Fine text

    "; + entries.pop(); + entries.push(Raw::file("OEBPS/text/ch0.xhtml", dtd.as_bytes())); + let d = open(&raw_zip(&entries), None, &Limits::default()).unwrap(); + assert_eq!(d.chapters[0].text(), "Fine\u{a0}text"); +} + +const NASTY: &str = r#" +

    Text js link and web.

    + + + + +
    + +
    Styled
    + + +

    in svg

    +x + +

    Safe emphasis stays.

    +"#; + +#[test] +fn scripts_handlers_forms_and_remote_urls_are_stripped() { + let bytes = Epub::new("Nasty") + .chapter("One", NASTY) + .file("OEBPS/style.css", b"@import url(https://evil.example/i.css);") + .build(); + let d = open(&bytes, None, &Limits::default()).unwrap(); + let x = d.chapters[0].xhtml.replacen("
    ", "
    ", 1); + for bad in [ + "emphasis")); + assert!(x.contains("js link") && x.contains("web"), "link text stays: {x}"); + assert!(d.images.is_empty()); + for f in d.footnotes.values() { + assert!(!f.contains("http")); + } +} + +#[test] +fn truncated_archives() { + let good = Epub::new("Cut").chapter("One", "

    Hello there.

    ").build(); + for cut in [good.len() / 2, good.len() - 10, 30, 0] { + let e = err(&good[..cut]); + assert!(matches!(e, FormatError::Malformed(_)), "cut at {cut}: {e:?}"); + } + // A flipped byte in a deflated body fails its checksum or inflation, never yields garbage silently. + let mut flipped = good.clone(); + let at = good.len() / 2; + flipped[at] ^= 0xff; + let r = open(&flipped, None, &Limits::default()); + assert!(r.is_err() || r.as_ref().unwrap().chapters.iter().all(|c| !c.xhtml.contains("x

    "); + e.opf_override = Some("unclosed".into()); + assert!(matches!(err(&e.build()), FormatError::Malformed(_))); + e.opf_override = Some("".into()); + assert!(matches!(err(&e.build()), FormatError::Malformed(_))); + let no_opf = raw_zip(&[ + Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") }, + Raw::file("META-INF/container.xml", CONTAINER.as_bytes()), + ]); + assert!(matches!(err(&no_opf), FormatError::Malformed(_))); + // A spine pointing at a missing chapter: the book opens without it only if another chapter has text. + e.opf_override = None; + let mut bytes_e = Epub::new("Missing"); + bytes_e.chapters.push(("One".into(), "

    x

    ".into())); + let ok = bytes_e.build(); + assert!(open(&ok, None, &Limits::default()).is_ok()); +} + +#[test] +fn deep_nesting_does_not_overflow() { + let depth = 100_000; + let body = format!("{}deep{}", "
    ".repeat(depth), "
    ".repeat(depth)); + // So repetitive it compresses past the ratio cap: allow it here, depth is what is tested. + let l = Limits { max_ratio: 100_000, ..Limits::default() }; + let d = open(&Epub::new("Deep").chapter("One", &body).build(), None, &l).unwrap(); + assert!(d.chapters[0].text().contains("deep")); + // Tag soup (not well-formed): through html5ever, still capped. + let soup = format!("{}soup

    unclosed", "

    ".repeat(20_000)); + let d = open(&Epub::new("Soup").chapter("One", &soup).build(), None, &l).unwrap(); + assert!(d.chapters[0].text().contains("soup")); +} + +#[test] +fn drm_is_refused_with_the_one_sentence() { + let rights = + epub_with(vec![Raw::file("META-INF/rights.xml", b"")]); + let lcp = epub_with(vec![Raw::file("META-INF/license.lcpl", b"{}")]); + let fairplay = epub_with(vec![Raw::file("META-INF/sinf.xml", b"")]); + let aes = epub_with(vec![Raw::file( + "META-INF/encryption.xml", + br#" + +"#, + )]); + for (what, b) in [("rights", rights), ("lcp", lcp), ("fairplay", fairplay), ("aes", aes)] { + let e = err(&b); + assert_eq!(e, FormatError::Drm, "{what}"); + assert_eq!(e.message(), DRM_MESSAGE); + } + // Font obfuscation only: not DRM. + let fonts = epub_with(vec![Raw::file( + "META-INF/encryption.xml", + br#" + +"#, + )]); + assert!(open(&fonts, None, &Limits::default()).is_ok()); + // MOBI with Mobipocket DRM, KFX, Topaz. + let mut m = Mobi::new("

    secret

    "); + m.encryption = 2; + assert_eq!(err(&m.build()), FormatError::Drm); + let mut kfx = b"\xeaDRMION\xee".to_vec(); + kfx.extend_from_slice(&[0; 100]); + assert_eq!(err(&kfx), FormatError::Drm); + assert_eq!(err(b"TPZ0\x00\x00garbage"), FormatError::Drm); +} + +#[test] +fn hostile_mobi() { + let good = Mobi::new("

    Hello mobi.

    ").build(); + assert!(open(&good, None, &Limits::default()).is_ok()); + // A record offset past the end. + let mut b = good.clone(); + b[78..82].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(err(&b), FormatError::Malformed(_))); + // More text records than records. + let mut b = good.clone(); + let r0 = u32::from_be_bytes(good[78..82].try_into().unwrap()) as usize; + b[r0 + 8..r0 + 10].copy_from_slice(&500u16.to_be_bytes()); + assert!(matches!(err(&b), FormatError::Malformed(_))); + // A PalmDOC back-reference before the start of the record. + let mut m = Mobi::new("x"); + m.compression = 1; + let mut b = m.build(); + b[r0..r0 + 2].copy_from_slice(&2u16.to_be_bytes()); + let r1 = u32::from_be_bytes(b[86..90].try_into().unwrap()) as usize; + b[r1] = 0x80; + b.push(0xff); + let _ = open(&b, None, &Limits::default()); + // HUFF/CDIC compression with no HUFF records: refused cleanly. + let mut b = good.clone(); + b[r0..r0 + 2].copy_from_slice(&17480u16.to_be_bytes()); + assert!(matches!(err(&b), FormatError::Malformed(_))); + // Absurd text length is capped by max_text, not allocated. + let mut b = good.clone(); + b[r0 + 4..r0 + 8].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(open(&b, None, &Limits::default()).is_ok()); +} diff --git a/crates/liber-format/tests/positions.rs b/crates/liber-format/tests/positions.rs new file mode 100644 index 0000000..d69c0f9 --- /dev/null +++ b/crates/liber-format/tests/positions.rs @@ -0,0 +1,161 @@ +//! Mandatory test 2 (the core's half): a highlight's position survives re-rendering and re-import, and a changed +//! edition degrades to "approximate" or "lost", never to other text. Font size and theme do not exist here: they +//! never reach the tree (the app's test renders the same chapter under different settings). + +mod common; +use common::*; +use liber_format::position::{Point, anchor, offset_of, point_at, resolve}; +use liber_format::{Limits, Resolved, open}; + +const CH0: &str = "

    Prolog

    Úvodní slovo.

    "; +const CH1: &str = "

    Kapitola první

    \ +

    Bylo to v temné a bouřlivé noci, když 😀 robot poprvé promluvil.

    \ +

    Druhý odstavec s 1 poznámkou.

    \ + "; +const CH2: &str = "

    Kapitola druhá

    Konec.

    "; + +fn book(ch1: &str) -> Vec { + Epub::new("R.U.R.").chapter("Prolog", CH0).chapter("Kapitola první", ch1).chapter("Kapitola druhá", CH2).build() +} + +fn find16(text: &str, needle: &str) -> (usize, usize) { + let b = text.find(needle).expect("needle"); + let s = text[..b].encode_utf16().count(); + (s, s + needle.encode_utf16().count()) +} + +fn quote_at(doc: &liber_format::Document, r: &Resolved) -> String { + match r { + Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => { + let t: Vec = doc.chapters[*chapter].text().encode_utf16().collect(); + String::from_utf16(&t[*start..*end]).unwrap() + } + Resolved::Lost => String::new(), + } +} + +#[test] +fn cfi_round_trips_on_every_text_offset() { + let d = open(&book(CH1), None, &Limits::default()).unwrap(); + let ch = &d.chapters[1]; + let n = ch.text_len; + for off in 0..=n { + for end in [false, true] { + let p = point_at(1, &ch.root, off, end); + let parsed = Point::parse(&p.to_cfi()).unwrap(); + assert_eq!(parsed, p); + // Offsets inside a surrogate pair do not exist in the text; every other offset maps back. + let t = ch.text(); + if liber_format::text::byte_at_utf16(&t, off).is_some() { + assert_eq!(offset_of(&ch.root, &parsed), Some(off), "offset {off} cfi {}", p.to_cfi()); + } + } + } +} + +#[test] +fn cfi_shape() { + let d = open(&book(CH1), None, &Limits::default()).unwrap(); + let t = d.chapters[1].text(); + let (s, e) = find16(&t, "temné a bouřlivé"); + let a = anchor(&d, 1, s, e).unwrap(); + // Chapter 1 → /6/4; root /4; the first

    is the second element (after

    ): /4; is its first element: /2. + assert_eq!(a.start, "epubcfi(/6/4!/4/4/2/1:0)"); + assert_eq!(a.end, "epubcfi(/6/4!/4/4/2/1:16)"); + assert_eq!(a.quote.exact, "temné a bouřlivé"); + assert_eq!(a.quote.prefix, "Kapitola prvníBylo to v "); + assert!(a.quote.suffix.starts_with(" noci, když 😀")); +} + +#[test] +fn a_highlight_survives_reimport_of_the_same_file() { + let bytes = book(CH1); + let d1 = open(&bytes, None, &Limits::default()).unwrap(); + let t = d1.chapters[1].text(); + let (s, e) = find16(&t, "noci, když 😀 robot"); + let a = anchor(&d1, 1, s, e).unwrap(); + for _ in 0..3 { + let d2 = open(&bytes, None, &Limits::default()).unwrap(); + assert_eq!(d2.chapters[1].xhtml, d1.chapters[1].xhtml, "the sanitizer is deterministic"); + assert_eq!(resolve(&d2, &a), Resolved::Exact { chapter: 1, start: s, end: e }); + } +} + +#[test] +fn a_highlight_across_elements() { + let d = open(&book(CH1), None, &Limits::default()).unwrap(); + let t = d.chapters[1].text(); + let (s, e) = find16(&t, "v temné a bouřlivé noci"); + let a = anchor(&d, 1, s, e).unwrap(); + assert_ne!(Point::parse(&a.start).unwrap().steps, Point::parse(&a.end).unwrap().steps); + let r = resolve(&d, &a); + assert_eq!(r, Resolved::Exact { chapter: 1, start: s, end: e }); + assert_eq!(quote_at(&d, &r), "v temné a bouřlivé noci"); +} + +#[test] +fn a_changed_edition_gives_approximate_at_the_same_words() { + let d1 = open(&book(CH1), None, &Limits::default()).unwrap(); + let t = d1.chapters[1].text(); + let (s, e) = find16(&t, "robot poprvé promluvil"); + let a = anchor(&d1, 1, s, e).unwrap(); + // The new edition adds a paragraph before it and re-wraps the emphasis. + let edited = CH1 + .replace("

    Bylo to", "

    Nový úvodní odstavec.

    Bylo to") + .replace("temné a bouřlivé", "temné a bouřlivé"); + let d2 = open(&book(&edited), None, &Limits::default()).unwrap(); + let r = resolve(&d2, &a); + assert!(matches!(r, Resolved::Approximate { chapter: 1, .. }), "{r:?}"); + assert_eq!(quote_at(&d2, &r), "robot poprvé promluvil"); +} + +#[test] +fn a_moved_chapter_is_found_in_another_chapter() { + let d1 = open(&book(CH1), None, &Limits::default()).unwrap(); + let t = d1.chapters[1].text(); + let (s, e) = find16(&t, "Druhý odstavec"); + let a = anchor(&d1, 1, s, e).unwrap(); + let moved = Epub::new("R.U.R.") + .chapter("Kapitola první", CH1) + .chapter("Prolog", CH0) + .chapter("Kapitola druhá", CH2) + .build(); + let d2 = open(&moved, None, &Limits::default()).unwrap(); + let r = resolve(&d2, &a); + assert!(matches!(r, Resolved::Approximate { chapter: 0, .. }), "{r:?}"); + assert_eq!(quote_at(&d2, &r), "Druhý odstavec"); +} + +#[test] +fn removed_text_is_lost_never_elsewhere() { + let d1 = open(&book(CH1), None, &Limits::default()).unwrap(); + let t = d1.chapters[1].text(); + let (s, e) = find16(&t, "robot poprvé promluvil"); + let a = anchor(&d1, 1, s, e).unwrap(); + // Same length, same structure, different words: the CFI still resolves, but to other text. + let reworded = CH1.replace("robot poprvé promluvil", "stroj zase mlčel dlouho"); + let d2 = open(&book(&reworded), None, &Limits::default()).unwrap(); + assert_eq!(resolve(&d2, &a), Resolved::Lost); +} + +#[test] +fn an_ambiguous_quote_is_lost() { + let ch = "

    ano ano

    ano ano

    "; + let d1 = open(&Epub::new("A").chapter("A", ch).build(), None, &Limits::default()).unwrap(); + let a = anchor(&d1, 0, 0, 3).unwrap(); + // The same file: exact. + assert!(matches!(resolve(&d1, &a), Resolved::Exact { .. })); + // A new edition where the context no longer tells the occurrences apart. + let d2 = + open(&Epub::new("A").chapter("A", "

    x

    ano ano

    ano ano

    ").build(), None, &Limits::default()) + .unwrap(); + let r = resolve(&d2, &a); + assert!(r == Resolved::Lost || quote_at(&d2, &r) == "ano", "{r:?}"); +} + +#[test] +fn footnotes_and_links() { + let d = open(&book(CH1), None, &Limits::default()).unwrap(); + assert!(d.chapters[1].xhtml.contains("data-href=\"1#n1\""), "{}", d.chapters[1].xhtml); + assert_eq!(d.footnotes.get("1#n1").map(|s| s.contains("Poznámka pod čarou")), Some(true)); +} diff --git a/crates/liber-format/tests/purity.rs b/crates/liber-format/tests/purity.rs new file mode 100644 index 0000000..6d8268c --- /dev/null +++ b/crates/liber-format/tests/purity.rs @@ -0,0 +1,65 @@ +//! The core is pure: no file system, no network, no clock, no processes in either crate's sources, and no network +//! crate anywhere in Cargo.lock. This is the "network-blocked run" for a library that cannot open a socket at all. + +use std::path::Path; + +const FORBIDDEN: &[&str] = &[ + "std::fs", + "std::net", + "TcpStream", + "UdpSocket", + "std::process", + "Command::new", + "SystemTime", + "Instant::now", + "File::open", + "File::create", + "env::var", + "std::env", +]; + +fn scan(dir: &Path, hits: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + scan(&p, hits); + } else if p.extension().is_some_and(|x| x == "rs") { + let s = std::fs::read_to_string(&p).unwrap(); + for f in FORBIDDEN { + if s.contains(f) { + hits.push(format!("{}: {f}", p.display())); + } + } + } + } +} + +#[test] +fn sources_have_no_io() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut hits = Vec::new(); + scan(&root.join("liber-format/src"), &mut hits); + scan(&root.join("liber-library/src"), &mut hits); + assert!(hits.is_empty(), "{hits:#?}"); +} + +#[test] +fn no_network_crate_in_the_lockfile() { + let lock = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.lock")).unwrap(); + for c in [ + "reqwest", + "ureq", + "hyper", + "curl", + "tokio", + "isahc", + "attohttpc", + "native-tls", + "rustls", + "openssl", + "socket2", + "mio", + ] { + assert!(!lock.contains(&format!("name = \"{c}\"")), "{c} is in Cargo.lock"); + } +} diff --git a/crates/liber-library/Cargo.toml b/crates/liber-library/Cargo.toml new file mode 100644 index 0000000..efbc143 --- /dev/null +++ b/crates/liber-library/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "liber-library" +description = "Liber Domi: book identity, the library model, the event log and its merge, stats, CSV import, export" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +liber-format.workspace = true +sha2.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +csv.workspace = true + +[dev-dependencies] +proptest.workspace = true +encoding_rs.workspace = true diff --git a/crates/liber-library/src/event.rs b/crates/liber-library/src/event.rs new file mode 100644 index 0000000..bb3b12b --- /dev/null +++ b/crates/liber-library/src/event.rs @@ -0,0 +1,160 @@ +//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere. + +use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person}; +use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; + +/// A hybrid logical clock value: wall milliseconds, then a counter. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct Hlc { + pub wall: u64, + pub logical: u32, +} + +/// One device's clock. `now_ms` is always a parameter. +#[derive(Clone, Debug, Default)] +pub struct Clock { + last: Hlc, +} + +impl Clock { + pub fn tick(&mut self, now_ms: u64) -> Hlc { + self.last = if now_ms > self.last.wall { + Hlc { wall: now_ms, logical: 0 } + } else { + Hlc { wall: self.last.wall, logical: self.last.logical + 1 } + }; + self.last + } + + /// Takes in a clock value seen on another device, so later local events order after it. + pub fn observe(&mut self, seen: Hlc) { + if seen > self.last { + self.last = seen; + } + } + + pub fn last(&self) -> Hlc { + self.last + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Event { + /// Unique: made by the device (random, or derived from the device and a counter). + pub id: String, + pub hlc: Hlc, + pub device: String, + pub op: Op, +} + +impl Event { + /// The total order: clock, then device, then id. + pub fn order(&self, other: &Event) -> Ordering { + (self.hlc, &self.device, &self.id).cmp(&(other.hlc, &other.device, &other.id)) + } +} + +/// Every change Liber records. Unknown fields are refused, so an event from a newer schema is rejected rather than +/// half-applied. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] +pub enum Op { + /// `restore`: from an export, where two books may share an identity on purpose: never merge. + BookAdd { + book: String, + info: BookInfo, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + restore: bool, + }, + /// `base`: the id of the event whose value the editor saw (`Library::version`). For text fields, a different + /// base means a concurrent edit: both versions are kept. + BookSet { + book: String, + field: Field, + value: serde_json::Value, + base: Option, + }, + BookRemove { + book: String, + }, + BookFileAdd { + book: String, + file: BookFile, + }, + BookFileRemove { + book: String, + sha256: String, + }, + ShelfAdd { + book: String, + shelf: String, + }, + ShelfRemove { + book: String, + shelf: String, + }, + ReadStart { + book: String, + read: String, + date: Option, + }, + ReadEnd { + read: String, + date: Option, + outcome: Outcome, + }, + ReadRemove { + read: String, + }, + Lend { + loan: String, + book: String, + person: Person, + since: String, + due: Option, + }, + Return { + loan: String, + date: String, + }, + Position { + book: String, + cfi: String, + chapter: u32, + progress: f64, + label: Option, + }, + HighlightAdd { + id: String, + book: String, + kind: Mark, + anchor: serde_json::Value, + colour: Colour, + note: String, + created: u64, + }, + HighlightSet { + id: String, + colour: Option, + note: Option, + base: Option, + }, + HighlightRemove { + id: String, + }, + Session { + id: String, + book: String, + start: u64, + end: u64, + active_ms: u64, + pages: u32, + date: String, + }, + Goal { + year: i32, + kind: GoalKind, + target: u32, + }, +} diff --git a/crates/liber-library/src/export.rs b/crates/liber-library/src/export.rs new file mode 100644 index 0000000..2c307eb --- /dev/null +++ b/crates/liber-library/src/export.rs @@ -0,0 +1,311 @@ +//! The `liber-export` format: one zip with `library.json` (the whole library), `books.csv`, `highlights/.md` +//! and, on request, the original book files under `files/`. Importing `library.json` into an empty library gives +//! back exactly the same library (`ops_from`). + +use crate::library::{Book, BookFile, Field, Library, Mark, Text}; +use crate::{Event, Hlc, Op}; +use liber_format::zip::ZipWriter; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::io::{self, Read, Write}; + +pub const FORMAT: &str = "liber-export"; +pub const VERSION: u32 = 1; +pub const MAX_JSON: usize = 256 * 1024 * 1024; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Envelope { + format: String, + version: u32, + exported_at: String, + library: Library, +} + +pub fn to_json(lib: &Library, exported_at: &str) -> String { + let env = + Envelope { format: FORMAT.into(), version: VERSION, exported_at: exported_at.into(), library: lib.clone() }; + serde_json::to_string_pretty(&env).unwrap_or_default() +} + +/// Reads `library.json`. The library it holds is checked by replaying it through events (`ops_from`), so whatever +/// the file says passes the same rules as every other change. +pub fn from_json(s: &str) -> Result { + if s.len() > MAX_JSON { + return Err("The export is larger than 256 MiB.".into()); + } + let env: Envelope = serde_json::from_str(s).map_err(|e| format!("This is not a Liber export ({e})."))?; + if env.format != FORMAT || env.version != VERSION { + return Err(format!( + "This export is {} version {}; Liber reads {FORMAT} version {VERSION}.", + env.format, env.version + )); + } + let events = events_from(&env.library, "restore", 0); + Ok(Library::from_events(&events)) +} + +/// The events that rebuild `lib` in an empty library, stamped from `device` starting at `wall`. +pub fn events_from(lib: &Library, device: &str, wall: u64) -> Vec { + ops_from(lib) + .into_iter() + .enumerate() + .map(|(i, op)| Event { + id: format!("{device}-{i}"), + hlc: Hlc { wall, logical: i as u32 }, + device: device.into(), + op, + }) + .collect() +} + +fn text_ops(t: &Text, mut set: impl FnMut(String, Option) -> Op) -> Vec { + match &t.conflict { + // The other version first, then the current one as a concurrent edit: the fold keeps both, as here. + Some(c) => vec![set(c.clone(), None), set(t.value.clone(), Some("restore-concurrent".into()))], + None if !t.value.is_empty() => vec![set(t.value.clone(), None)], + None => vec![], + } +} + +pub fn ops_from(lib: &Library) -> Vec { + let mut ops = Vec::new(); + for b in lib.books.values() { + let id = b.id.clone(); + let set = |field: Field, value: serde_json::Value| Op::BookSet { book: id.clone(), field, value, base: None }; + ops.push(Op::BookAdd { book: id.clone(), info: b.info.clone(), restore: true }); + for f in &b.files { + ops.push(Op::BookFileAdd { book: id.clone(), file: f.clone() }); + } + if b.paper { + ops.push(set(Field::Paper, json!(true))); + } + ops.push(set(Field::Possession, serde_json::to_value(&b.possession).unwrap_or_default())); + for s in &b.shelves { + ops.push(Op::ShelfAdd { book: id.clone(), shelf: s.clone() }); + } + if let Some(r) = b.rating { + ops.push(set(Field::Rating, json!(r))); + } + ops.extend(text_ops(&b.review, |v, base| Op::BookSet { + book: id.clone(), + field: Field::Review, + value: json!(v), + base, + })); + ops.extend(text_ops(&b.notes, |v, base| Op::BookSet { + book: id.clone(), + field: Field::Notes, + value: json!(v), + base, + })); + if !b.moods.is_empty() { + ops.push(set(Field::Moods, json!(b.moods))); + } + if !b.tags.is_empty() { + ops.push(set(Field::Tags, json!(b.tags))); + } + if b.cover.is_some() { + ops.push(set(Field::Cover, json!(b.cover))); + } + for l in &b.loans { + ops.push(Op::Lend { + loan: l.id.clone(), + book: id.clone(), + person: l.person.clone(), + since: l.since.clone(), + due: l.due.clone(), + }); + if let Some(d) = &l.returned { + ops.push(Op::Return { loan: l.id.clone(), date: d.clone() }); + } + } + for r in &b.reads { + ops.push(Op::ReadStart { book: id.clone(), read: r.id.clone(), date: r.started.clone() }); + if let Some(o) = r.outcome { + ops.push(Op::ReadEnd { read: r.id.clone(), date: r.finished.clone(), outcome: o }); + } + } + if b.to_read { + ops.push(set(Field::ToRead, json!(true))); + } + let pos = |p: &crate::library::Position| Op::Position { + book: id.clone(), + cfi: p.cfi.clone(), + chapter: p.chapter, + progress: p.progress, + label: p.label.clone(), + }; + if let Some(f) = &b.position { + ops.push(pos(f)); + } + if let Some(l) = &b.last_position + && Some(l) != b.position.as_ref() + { + ops.push(pos(l)); + } + } + for h in lib.highlights.values() { + let (first, rest) = match &h.note.conflict { + Some(c) => (c.clone(), Some(h.note.value.clone())), + None => (h.note.value.clone(), None), + }; + ops.push(Op::HighlightAdd { + id: h.id.clone(), + book: h.book.clone(), + kind: h.kind, + anchor: h.anchor.clone(), + colour: h.colour, + note: first, + created: h.created, + }); + if let Some(v) = rest { + ops.push(Op::HighlightSet { + id: h.id.clone(), + colour: None, + note: Some(v), + base: Some("restore-concurrent".into()), + }); + } + } + for s in lib.sessions.values() { + ops.push(Op::Session { + id: s.id.clone(), + book: s.book.clone(), + start: s.start, + end: s.end, + active_ms: s.active_ms, + pages: s.pages, + date: s.date.clone(), + }); + } + for g in lib.goals.values() { + ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target }); + } + ops +} + +/// A spreadsheet cell that cannot run as a formula: a leading `= + - @`, tab or CR gets a `'`. +pub fn safe_cell(s: &str) -> String { + if s.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{s}") } else { s.to_owned() } +} + +pub fn books_csv(lib: &Library) -> String { + let mut w = csv::Writer::from_writer(Vec::new()); + let _ = w.write_record([ + "id", + "title", + "authors", + "isbn13", + "status", + "possession", + "lent_to", + "shelves", + "rating_half_stars", + "pages", + "series", + "started", + "finished", + "moods", + "tags", + "review", + ]); + for b in lib.books.values() { + let last = b.reads.last(); + let possession = match &b.possession { + crate::Possession::Owned => "owned".to_owned(), + crate::Possession::Borrowed { from, .. } => format!("borrowed from {}", from.name), + crate::Possession::Wishlist => "wishlist".to_owned(), + crate::Possession::None => String::new(), + }; + let row = [ + b.id.clone(), + b.info.title.clone(), + b.info.authors.join("; "), + b.info.isbn13.clone().unwrap_or_default(), + serde_json::to_value(b.status()).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(), + possession, + b.lent_to().map(|l| l.person.name.clone()).unwrap_or_default(), + b.shelves.iter().cloned().collect::>().join("; "), + b.rating.map(|r| r.to_string()).unwrap_or_default(), + b.info.pages.map(|p| p.to_string()).unwrap_or_default(), + b.info.series.as_ref().map(|s| s.name.clone()).unwrap_or_default(), + last.and_then(|r| r.started.clone()).unwrap_or_default(), + last.and_then(|r| r.finished.clone()).unwrap_or_default(), + b.moods.iter().cloned().collect::>().join("; "), + b.tags.iter().cloned().collect::>().join("; "), + b.review.value.clone(), + ]; + let _ = w.write_record(row.iter().map(|c| safe_cell(c))); + } + String::from_utf8(w.into_inner().unwrap_or_default()).unwrap_or_default() +} + +/// A file name for a book: letters, digits, `-`, at most 60 characters, plus the id's start. +pub fn slug(b: &Book) -> String { + let mut s: String = b + .info + .title + .chars() + .map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }) + .collect::() + .split('-') + .filter(|x| !x.is_empty()) + .collect::>() + .join("-"); + s = s.chars().take(60).collect(); + let id: String = b.id.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect(); + if s.is_empty() { id } else { format!("{s}-{id}") } +} + +pub fn highlights_markdown(lib: &Library, book: &str) -> String { + let Some(b) = lib.books.get(book) else { return String::new() }; + let mut out = format!("# {}\n", b.info.title); + if !b.info.authors.is_empty() { + out.push_str(&format!("\n*{}*\n", b.info.authors.join(", "))); + } + let mut hs: Vec<_> = lib.highlights.values().filter(|h| h.book == b.id).collect(); + hs.sort_by_key(|h| (h.anchor.get("chapter").and_then(|c| c.as_u64()).unwrap_or(0), h.created)); + for h in hs { + let quote = h.anchor.pointer("/quote/exact").and_then(|q| q.as_str()).unwrap_or(""); + out.push('\n'); + match h.kind { + Mark::Bookmark => out.push_str("- Bookmark\n"), + _ if !quote.is_empty() => { + for line in quote.lines() { + out.push_str(&format!("> {line}\n")); + } + } + _ => {} + } + if !h.note.value.is_empty() { + out.push_str(&format!("\n{}\n", h.note.value)); + } + if let Some(c) = &h.note.conflict { + out.push_str(&format!("\n(Other version: {c})\n")); + } + } + out +} + +/// Gives a reader for a book file to include in the export, or `None` to leave it out. +pub type FileSource<'a> = dyn FnMut(&Book, &BookFile) -> Option> + 'a; + +/// Writes the whole export. `file` returns a reader for a book file the person chose to include, or `None`. +pub fn write_zip(lib: &Library, w: W, exported_at: &str, file: &mut FileSource<'_>) -> io::Result { + let mut z = ZipWriter::new(w); + z.add("library.json", to_json(lib, exported_at).as_bytes(), true)?; + z.add("books.csv", books_csv(lib).as_bytes(), true)?; + for b in lib.books.values() { + if lib.highlights.values().any(|h| h.book == b.id) { + z.add(&format!("highlights/{}.md", slug(b)), highlights_markdown(lib, &b.id).as_bytes(), true)?; + } + for f in &b.files { + if let Some(mut r) = file(b, f) { + let ext: String = f.format.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect(); + z.add_stream(&format!("files/{}-{}.{ext}", slug(b), &f.sha256[..f.sha256.len().min(8)]), &mut r)?; + } + } + } + z.finish() +} diff --git a/crates/liber-library/src/import.rs b/crates/liber-library/src/import.rs new file mode 100644 index 0000000..278e964 --- /dev/null +++ b/crates/liber-library/src/import.rs @@ -0,0 +1,439 @@ +//! Goodreads and StoryGraph CSV import. Every row is imported or listed with its reason; columns Liber does not +//! map are kept on the book (`import_extra`) and named in the report. The CSV is hostile: the input and each field +//! are capped, values are stored as text and never evaluated. + +use crate::library::{BookInfo, Field, Library, Outcome, Possession}; +use crate::{MOODS, Op, isbn13, parse_date}; +use serde::Serialize; +use serde_json::json; +use std::collections::{BTreeMap, BTreeSet}; + +pub const MAX_INPUT: usize = 32 * 1024 * 1024; +pub const MAX_FIELD: usize = 64 * 1024; +pub const MAX_ROWS: usize = 100_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Source { + Goodreads, + StoryGraph, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Report { + pub source: Source, + pub rows: usize, + pub imported: usize, + /// (row number, 1-based after the header; why) + pub skipped: Vec<(usize, String)>, + /// Columns Liber does not know: their values are kept on each book. + pub unknown_columns: Vec, + /// Columns Liber knows but does not use (also kept on each book). + pub unused_columns: Vec, + /// (row, column) of fields cut at 64 KiB. + pub truncated: Vec<(usize, String)>, +} + +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ImportError { + #[error("The file is larger than 32 MiB, which is too large for a reading-list export.")] + TooLarge, + #[error("This is not a Goodreads or StoryGraph export (the header is not one Liber knows).")] + UnknownFormat, + #[error("The file is not valid CSV: {0}")] + Csv(String), + #[error("The file has more than 100,000 rows.")] + TooManyRows, +} + +const GOODREADS_USED: &[&str] = &[ + "Title", + "Author", + "Additional Authors", + "ISBN", + "ISBN13", + "My Rating", + "Publisher", + "Binding", + "Number of Pages", + "Year Published", + "Original Publication Year", + "Date Read", + "Date Added", + "Bookshelves", + "Exclusive Shelf", + "My Review", + "Private Notes", + "Read Count", + "Owned Copies", +]; +const GOODREADS_UNUSED: &[&str] = &["Book Id", "Author l-f", "Average Rating", "Bookshelves with positions", "Spoiler"]; +const STORYGRAPH_USED: &[&str] = &[ + "Title", + "Authors", + "ISBN/UID", + "Format", + "Read Status", + "Date Added", + "Last Date Read", + "Dates Read", + "Read Count", + "Moods", + "Star Rating", + "Review", + "Tags", + "Owned?", +]; +const STORYGRAPH_UNUSED: &[&str] = &[ + "Contributors", + "Pace", + "Character- or Plot-Driven?", + "Strong Character Development?", + "Loveable Characters?", + "Diverse Characters?", + "Flawed Characters?", + "Content Warnings", + "Content Warning Description", +]; + +/// Goodreads writes `="0441172717"` so spreadsheets keep leading zeros. +fn unwrap_excel(s: &str) -> &str { + s.trim().strip_prefix("=\"").and_then(|x| x.strip_suffix('"')).unwrap_or(s.trim()) +} + +fn ms_of(date: &str) -> Option { + let d = parse_date(date)?; + let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?); + let days = crate::days_from_civil(y, m, dd); + (days >= 0).then(|| days as u64 * 86_400_000) +} + +/// Goodreads reviews are HTML with `
    `. +fn review_text(s: &str) -> String { + let s = s.replace("
    ", "\n").replace("
    ", "\n").replace("
    ", "\n"); + let mut out = String::new(); + let mut tag = false; + for c in s.chars() { + match c { + '<' => tag = true, + '>' if tag => tag = false, + c if !tag => out.push(c), + _ => {} + } + } + out.trim().to_owned() +} + +fn list(s: &str) -> Vec { + s.split(',').map(|x| x.trim().to_owned()).filter(|x| !x.is_empty()).collect() +} + +fn norm_key(title: &str, author: &str) -> String { + let f = |s: &str| s.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect::(); + format!("{}|{}", f(title), f(author)) +} + +struct Row<'a> { + cols: &'a [String], + vals: Vec, +} + +impl Row<'_> { + fn get(&self, c: &str) -> &str { + self.cols.iter().position(|x| x == c).and_then(|i| self.vals.get(i)).map(|s| s.trim()).unwrap_or("") + } +} + +/// Parses an export into events. `new_id` makes ids (books, reads); `now_ms` is the fallback "added" time. +pub fn import_csv( + bytes: &[u8], + existing: &Library, + new_id: &mut dyn FnMut() -> String, + now_ms: u64, +) -> Result<(Vec, Report), ImportError> { + if bytes.len() > MAX_INPUT { + return Err(ImportError::TooLarge); + } + let (text, _) = liber_format::text::decode_text(bytes); + let mut rdr = csv::ReaderBuilder::new().flexible(true).has_headers(true).from_reader(text.as_bytes()); + let cols: Vec = rdr + .headers() + .map_err(|e| ImportError::Csv(e.to_string()))? + .iter() + .map(|h| h.trim().trim_start_matches('\u{feff}').to_owned()) + .collect(); + let has = |c: &str| cols.iter().any(|x| x == c); + let source = if has("Exclusive Shelf") && has("Title") { + Source::Goodreads + } else if has("Read Status") && has("Title") { + Source::StoryGraph + } else { + return Err(ImportError::UnknownFormat); + }; + let (used, unused) = match source { + Source::Goodreads => (GOODREADS_USED, GOODREADS_UNUSED), + Source::StoryGraph => (STORYGRAPH_USED, STORYGRAPH_UNUSED), + }; + let mut report = Report { + source, + rows: 0, + imported: 0, + skipped: vec![], + unknown_columns: cols + .iter() + .filter(|c| !c.is_empty() && !used.contains(&c.as_str()) && !unused.contains(&c.as_str())) + .cloned() + .collect(), + unused_columns: cols.iter().filter(|c| unused.contains(&c.as_str())).cloned().collect(), + truncated: vec![], + }; + let mut seen: BTreeSet = existing + .books + .values() + .map(|b| norm_key(&b.info.title, b.info.authors.first().map(String::as_str).unwrap_or(""))) + .collect(); + let mut seen_isbn: BTreeSet = existing.books.values().filter_map(|b| b.info.isbn13.clone()).collect(); + let mut ops = Vec::new(); + for (i, rec) in rdr.records().enumerate() { + let n = i + 1; + if n > MAX_ROWS { + return Err(ImportError::TooManyRows); + } + report.rows += 1; + let rec = match rec { + Ok(r) => r, + Err(e) => { + report.skipped.push((n, format!("not valid CSV: {e}"))); + continue; + } + }; + let mut vals = Vec::with_capacity(rec.len()); + for (ci, v) in rec.iter().enumerate() { + if v.len() > MAX_FIELD { + let mut end = MAX_FIELD; + while !v.is_char_boundary(end) { + end -= 1; + } + report.truncated.push((n, cols.get(ci).cloned().unwrap_or_default())); + vals.push(v[..end].to_owned()); + } else { + vals.push(v.to_owned()); + } + } + let row = Row { cols: &cols, vals }; + let title = row.get("Title").to_owned(); + if title.is_empty() { + report.skipped.push((n, "no title".into())); + continue; + } + let mut extra = BTreeMap::new(); + for (ci, c) in cols.iter().enumerate() { + if !used.contains(&c.as_str()) && !c.is_empty() { + let v = row.vals.get(ci).map(|s| s.trim()).unwrap_or(""); + if !v.is_empty() { + let prefix = match source { + Source::Goodreads => "goodreads", + Source::StoryGraph => "storygraph", + }; + extra.insert(format!("{prefix}:{c}"), v.to_owned()); + } + } + } + let r = match source { + Source::Goodreads => goodreads(&row, extra, now_ms), + Source::StoryGraph => storygraph(&row, extra, now_ms), + }; + let author = r.info.authors.first().cloned().unwrap_or_default(); + let key = norm_key(&r.info.title, &author); + if r.info.isbn13.as_ref().is_some_and(|i| seen_isbn.contains(i)) || seen.contains(&key) { + report.skipped.push((n, format!("“{}” is already in your library", r.info.title))); + continue; + } + seen.insert(key); + if let Some(i) = &r.info.isbn13 { + seen_isbn.insert(i.clone()); + } + let book = new_id(); + ops.push(Op::BookAdd { book: book.clone(), info: r.info, restore: false }); + let set = |field: Field, value: serde_json::Value| Op::BookSet { book: book.clone(), field, value, base: None }; + if let Some(rt) = r.rating { + ops.push(set(Field::Rating, json!(rt))); + } + if !r.review.is_empty() { + ops.push(set(Field::Review, json!(r.review))); + } + if !r.notes.is_empty() { + ops.push(set(Field::Notes, json!(r.notes))); + } + if r.owned { + ops.push(set(Field::Possession, serde_json::to_value(Possession::Owned).unwrap_or_default())); + } + if r.paper { + ops.push(set(Field::Paper, json!(true))); + } + if !r.moods.is_empty() { + ops.push(set(Field::Moods, json!(r.moods))); + } + if !r.tags.is_empty() { + ops.push(set(Field::Tags, json!(r.tags))); + } + if r.to_read { + ops.push(set(Field::ToRead, json!(true))); + } + for s in r.shelves { + ops.push(Op::ShelfAdd { book: book.clone(), shelf: s }); + } + for (start, end, outcome) in r.reads { + let read = new_id(); + ops.push(Op::ReadStart { book: book.clone(), read: read.clone(), date: start }); + if let Some(o) = outcome { + ops.push(Op::ReadEnd { read, date: end, outcome: o }); + } + } + report.imported += 1; + } + Ok((ops, report)) +} + +struct Parsed { + info: BookInfo, + rating: Option, + review: String, + notes: String, + owned: bool, + paper: bool, + moods: BTreeSet, + tags: BTreeSet, + to_read: bool, + shelves: Vec, + /// (started, finished, outcome) + reads: Vec<(Option, Option, Option)>, +} + +fn paper_binding(b: &str) -> bool { + let b = b.to_lowercase(); + ["paperback", "hardcover", "mass market", "hardback", "board book", "library binding", "leather", "spiral"] + .iter() + .any(|p| b.contains(p)) +} + +fn goodreads(row: &Row, extra: BTreeMap, now_ms: u64) -> Parsed { + let mut authors = vec![row.get("Author").to_owned()]; + authors.extend(list(row.get("Additional Authors"))); + authors.retain(|a| !a.is_empty()); + let isbn = isbn13(unwrap_excel(row.get("ISBN13"))).or_else(|| isbn13(unwrap_excel(row.get("ISBN")))); + let published = [row.get("Original Publication Year"), row.get("Year Published")] + .iter() + .find(|y| !y.is_empty()) + .map(|y| y.to_string()); + let rating: u8 = row.get("My Rating").parse().unwrap_or(0); + let exclusive = row.get("Exclusive Shelf").to_owned(); + let mut shelves: Vec = list(row.get("Bookshelves")) + .into_iter() + .filter(|s| !matches!(s.as_str(), "read" | "currently-reading" | "to-read")) + .collect(); + let read_count: usize = row.get("Read Count").parse().unwrap_or(0); + let date_read = parse_date(row.get("Date Read")); + let mut reads = Vec::new(); + let mut to_read = false; + match exclusive.as_str() { + "read" => { + for _ in 1..read_count.clamp(1, 50) { + reads.push((None, None, Some(Outcome::Read))); + } + reads.push((None, date_read.clone(), Some(Outcome::Read))); + } + "currently-reading" => reads.push((None, None, None)), + "to-read" => to_read = true, + other if !other.is_empty() && !shelves.iter().any(|s| s == other) => { + shelves.push(other.to_owned()); + } + _ => {} + } + Parsed { + info: BookInfo { + title: row.get("Title").to_owned(), + authors, + isbn13: isbn, + publisher: Some(row.get("Publisher").to_owned()).filter(|s| !s.is_empty()), + published, + pages: row.get("Number of Pages").parse().ok().filter(|p| *p > 0), + added: ms_of(row.get("Date Added")).unwrap_or(now_ms), + import_extra: extra, + ..BookInfo::default() + }, + rating: (1..=5).contains(&rating).then_some(rating * 2), + review: review_text(row.get("My Review")), + notes: row.get("Private Notes").to_owned(), + owned: row.get("Owned Copies").parse::().unwrap_or(0) > 0, + paper: paper_binding(row.get("Binding")), + moods: BTreeSet::new(), + tags: BTreeSet::new(), + to_read, + shelves, + reads, + } +} + +fn storygraph(row: &Row, extra: BTreeMap, now_ms: u64) -> Parsed { + let uid = row.get("ISBN/UID"); + let star: f64 = row.get("Star Rating").parse().unwrap_or(0.0); + let rating = (star > 0.0 && star <= 5.0).then(|| ((star * 2.0).round() as u8).clamp(1, 10)); + let status = row.get("Read Status").to_lowercase(); + let mut reads = Vec::new(); + for range in list(row.get("Dates Read")) { + let (a, b) = + range.split_once('-').map(|(a, b)| (parse_date(a), parse_date(b))).unwrap_or((None, parse_date(&range))); + reads.push((a, b, Some(Outcome::Read))); + } + let mut to_read = false; + match status.as_str() { + "read" if reads.is_empty() => { + let n: usize = row.get("Read Count").parse().unwrap_or(1); + for i in 0..n.clamp(1, 50) { + let last = (i + 1 == n.max(1)).then(|| parse_date(row.get("Last Date Read"))).flatten(); + reads.push((None, last, Some(Outcome::Read))); + } + } + "read" => {} + "currently-reading" | "paused" => reads.push((None, None, None)), + "did-not-finish" => reads.push((None, parse_date(row.get("Last Date Read")), Some(Outcome::DidNotFinish))), + "to-read" => to_read = true, + _ => {} + } + let mut moods = BTreeSet::new(); + let mut tags: BTreeSet = list(row.get("Tags")).into_iter().collect(); + for m in list(row.get("Moods")) { + let l = m.to_lowercase(); + if MOODS.contains(&l.as_str()) { + moods.insert(l); + } else { + tags.insert(m); + } + } + let mut info = BookInfo { + title: row.get("Title").to_owned(), + authors: list(row.get("Authors")), + isbn13: isbn13(uid), + added: ms_of(row.get("Date Added")).unwrap_or(now_ms), + import_extra: extra, + ..BookInfo::default() + }; + if info.isbn13.is_none() && !uid.is_empty() { + info.import_extra.insert("storygraph:ISBN/UID".into(), uid.to_owned()); + } + let format = row.get("Format").to_lowercase(); + Parsed { + info, + rating, + review: row.get("Review").to_owned(), + notes: String::new(), + owned: matches!(row.get("Owned?").to_lowercase().as_str(), "yes" | "true"), + paper: format.contains("paperback") || format.contains("hardcover"), + moods, + tags, + to_read, + shelves: vec![], + reads, + } +} diff --git a/crates/liber-library/src/lib.rs b/crates/liber-library/src/lib.rs new file mode 100644 index 0000000..fad9bcd --- /dev/null +++ b/crates/liber-library/src/lib.rs @@ -0,0 +1,84 @@ +//! Liber's library (docs in the app repo, `docs/01_books.md`): the model, the event log and its merge, stats, +//! Goodreads/StoryGraph import and the `liber-export` format. Pure: time, ids and devices are parameters. +//! +//! Every change is an [`Event`]; the [`Library`] is a fold of the events in their total order +//! (hybrid logical clock, then device, then id). Two devices holding the same events hold the same library, +//! whatever order the events arrived in: that is the whole sync guarantee. + +pub mod event; +pub mod export; +pub mod import; +pub mod library; +pub mod stats; + +pub use event::{Clock, Event, Hlc, Op}; +pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text}; + +pub use liber_format::text::isbn13; + +/// StoryGraph's moods: Liber's fixed mood list (own tags are separate). +pub const MOODS: &[&str] = &[ + "adventurous", + "challenging", + "dark", + "emotional", + "funny", + "hopeful", + "informative", + "inspiring", + "lighthearted", + "mysterious", + "reflective", + "relaxing", + "sad", + "tense", +]; + +/// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm). +pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m as i64 + 9) % 12; + let doy = (153 * mp + 2) / 5 + d as i64 - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// `YYYY-MM-DD` (or `YYYY/MM/DD`) → `YYYY-MM-DD`, checked. +pub fn parse_date(s: &str) -> Option { + let s = s.trim(); + let parts: Vec<&str> = s.split(['-', '/']).collect(); + if parts.len() != 3 { + return None; + } + let y: i32 = parts[0].parse().ok()?; + let m: u32 = parts[1].parse().ok()?; + let d: u32 = parts[2].parse().ok()?; + if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || !(1..=31).contains(&d) { + return None; + } + let dim = [ + 31, + if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 29 } else { 28 }, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + if d > dim[(m - 1) as usize] { + return None; + } + Some(format!("{y:04}-{m:02}-{d:02}")) +} + +/// The year of a `YYYY-MM-DD` date. +pub fn year_of(date: &str) -> Option { + date.get(..4)?.parse().ok() +} diff --git a/crates/liber-library/src/library.rs b/crates/liber-library/src/library.rs new file mode 100644 index 0000000..d00d9d8 --- /dev/null +++ b/crates/liber-library/src/library.rs @@ -0,0 +1,660 @@ +//! The library as a fold of events (see `lib.rs`): books and their states, shelves, reads, loans, positions, +//! highlights, reading sessions and goals. + +use crate::event::{Event, Op}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Someone from the people directory (`id`), or a plain name until it is wired. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Person { + pub id: Option, + pub name: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Series { + pub name: String, + pub index: Option, +} + +/// What is known about a book when it is added. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct BookInfo { + pub title: String, + pub authors: Vec, + pub isbn13: Option, + /// The text fingerprint of an e-book (liber-format), for merging the same book from two sources. + pub fingerprint: Option, + pub series: Option, + pub language: Option, + pub publisher: Option, + pub published: Option, + pub description: Option, + pub pages: Option, + pub genres: Vec, + /// Unix ms, given by the device. + pub added: u64, + /// Columns an import did not map, kept rather than dropped. + pub import_extra: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BookFile { + pub sha256: String, + pub format: String, + pub size: u64, + pub name: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Possession { + Owned, + Borrowed { + from: Person, + due: Option, + }, + Wishlist, + #[default] + None, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Read, + DidNotFinish, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReadStatus { + ToRead, + Reading, + Read, + DidNotFinish, + None, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Read { + pub id: String, + pub started: Option, + pub finished: Option, + pub outcome: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Loan { + pub id: String, + pub person: Person, + pub since: String, + pub due: Option, + pub returned: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Position { + pub cfi: String, + pub chapter: u32, + pub progress: f64, + pub label: Option, +} + +/// A text field that may hold two versions after concurrent edits on two devices. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Text { + pub value: String, + /// The other version, shown with a marker until someone edits the field again. + pub conflict: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Field { + Title, + Authors, + Series, + Language, + Publisher, + Published, + Description, + Pages, + Isbn13, + Genres, + Paper, + Possession, + Rating, + Review, + Notes, + Moods, + Tags, + ToRead, + Cover, +} + +impl Field { + fn key(self) -> &'static str { + match self { + Field::Title => "title", + Field::Authors => "authors", + Field::Series => "series", + Field::Language => "language", + Field::Publisher => "publisher", + Field::Published => "published", + Field::Description => "description", + Field::Pages => "pages", + Field::Isbn13 => "isbn13", + Field::Genres => "genres", + Field::Paper => "paper", + Field::Possession => "possession", + Field::Rating => "rating", + Field::Review => "review", + Field::Notes => "notes", + Field::Moods => "moods", + Field::Tags => "tags", + Field::ToRead => "to_read", + Field::Cover => "cover", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Mark { + Highlight, + Note, + Bookmark, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Colour { + Yellow, + Green, + Blue, + Pink, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GoalKind { + Books, + Pages, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Book { + pub id: String, + pub info: BookInfo, + pub files: Vec, + pub paper: bool, + pub possession: Possession, + pub loans: Vec, + pub reads: Vec, + pub to_read: bool, + pub shelves: BTreeSet, + /// Half stars, 1–10. + pub rating: Option, + pub review: Text, + pub notes: Text, + pub moods: BTreeSet, + pub tags: BTreeSet, + /// A blob reference (the cover image's sha256). + pub cover: Option, + /// The furthest position reached on any device. + pub position: Option, + /// The most recent position, when it is behind the furthest: "Jump back to page X?". + pub last_position: Option, +} + +impl Book { + fn new(id: &str, info: BookInfo) -> Book { + Book { + id: id.to_owned(), + info, + files: vec![], + paper: false, + possession: Possession::None, + loans: vec![], + reads: vec![], + to_read: false, + shelves: BTreeSet::new(), + rating: None, + review: Text::default(), + notes: Text::default(), + moods: BTreeSet::new(), + tags: BTreeSet::new(), + cover: None, + position: None, + last_position: None, + } + } + + pub fn status(&self) -> ReadStatus { + match self.reads.last() { + Some(r) => match r.outcome { + None => ReadStatus::Reading, + Some(Outcome::Read) => ReadStatus::Read, + Some(Outcome::DidNotFinish) => ReadStatus::DidNotFinish, + }, + None if self.to_read => ReadStatus::ToRead, + None => ReadStatus::None, + } + } + + /// The loan that is out now. + pub fn lent_to(&self) -> Option<&Loan> { + self.loans.iter().find(|l| l.returned.is_none()) + } + + /// The position to offer "Jump back to …" for. + pub fn jump_back(&self) -> Option<&Position> { + let (Some(f), Some(l)) = (&self.position, &self.last_position) else { return None }; + (l.progress + 1e-9 < f.progress).then_some(l) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Highlight { + pub id: String, + pub book: String, + pub kind: Mark, + /// A `liber_format::Anchor` (or a page for PDFs), opaque here. + pub anchor: serde_json::Value, + pub colour: Colour, + pub note: Text, + pub created: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Session { + pub id: String, + pub book: String, + pub start: u64, + pub end: u64, + pub active_ms: u64, + pub pages: u32, + /// The local day it counts for (`YYYY-MM-DD`, from the device). + pub date: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Goal { + pub year: i32, + pub kind: GoalKind, + pub target: u32, +} + +/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content +/// (books, highlights, sessions, goals), not the bookkeeping of how it was built. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct Library { + pub books: BTreeMap, + pub highlights: BTreeMap, + pub sessions: BTreeMap, + pub goals: BTreeMap, + #[serde(skip)] + aliases: BTreeMap, + #[serde(skip)] + versions: BTreeMap<(String, &'static str), String>, + #[serde(skip)] + removed_books: BTreeSet, + #[serde(skip)] + removed_highlights: BTreeSet, + #[serde(skip)] + read_book: BTreeMap, + #[serde(skip)] + loan_book: BTreeMap, +} + +impl PartialEq for Library { + fn eq(&self, o: &Library) -> bool { + self.books == o.books && self.highlights == o.highlights && self.sessions == o.sessions && self.goals == o.goals + } +} + +/// Field values longer than this are cut (a review, a note). +pub const MAX_TEXT: usize = 64 * 1024; + +fn clip(s: String) -> String { + if s.len() <= MAX_TEXT { + return s; + } + let mut end = MAX_TEXT; + while !s.is_char_boundary(end) { + end -= 1; + } + s[..end].to_owned() +} + +impl Library { + /// Folds events in their total order. + pub fn from_events<'a>(events: impl IntoIterator) -> Library { + let mut v: Vec<&Event> = events.into_iter().collect(); + v.sort_by(|a, b| a.order(b)); + v.dedup_by(|a, b| a.id == b.id); + let mut lib = Library::default(); + for e in v { + lib.apply(e); + } + lib + } + + /// The canonical id of a book (after identity merges). + pub fn canonical(&self, id: &str) -> String { + let mut cur = id.to_owned(); + for _ in 0..64 { + match self.aliases.get(&cur) { + Some(n) => cur = n.clone(), + None => break, + } + } + cur + } + + /// The event id that last set a field (the `base` for the next edit). + pub fn version(&self, book: &str, field: Field) -> Option<&str> { + self.versions.get(&(self.canonical(book), field.key())).map(String::as_str) + } + + pub fn highlight_version(&self, id: &str) -> Option<&str> { + self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str) + } + + /// An existing book with the same identity: ISBN-13, else text fingerprint. + pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> { + if let Some(i) = isbn13 + && let Some(b) = self.books.values().find(|b| b.info.isbn13.as_deref() == Some(i)) + { + return Some(b); + } + if let Some(f) = fingerprint { + return self.books.values().find(|b| b.info.fingerprint.as_deref() == Some(f)); + } + None + } + + fn book_mut(&mut self, id: &str) -> Option<&mut Book> { + let c = self.canonical(id); + self.books.get_mut(&c) + } + + fn set_text( + versions: &mut BTreeMap<(String, &'static str), String>, + key: (String, &'static str), + t: &mut Text, + value: String, + base: &Option, + event: &str, + ) { + let current = versions.get(&key); + let concurrent = current.is_some() && base.as_deref() != current.map(String::as_str) && t.value != value; + if concurrent { + t.conflict = Some(std::mem::replace(&mut t.value, clip(value))); + } else { + t.value = clip(value); + t.conflict = None; + } + versions.insert(key, event.to_owned()); + } + + pub fn apply(&mut self, e: &Event) { + match &e.op { + Op::BookAdd { book, info, restore } => { + if self.removed_books.contains(book) || self.books.contains_key(book) || self.aliases.contains_key(book) + { + return; + } + let isbn = info.isbn13.as_deref().and_then(crate::isbn13); + let mut info = info.clone(); + info.isbn13 = isbn; + info.title = clip(info.title); + info.description = info.description.map(clip); + let same = if *restore { + None + } else { + self.find_identity(info.isbn13.as_deref(), info.fingerprint.as_deref()).map(|b| b.id.clone()) + }; + match same { + Some(existing) => { + self.aliases.insert(book.clone(), existing.clone()); + if let Some(b) = self.books.get_mut(&existing) { + let i = &mut b.info; + if i.isbn13.is_none() { + i.isbn13 = info.isbn13; + } + if i.fingerprint.is_none() { + i.fingerprint = info.fingerprint; + } + if i.pages.is_none() { + i.pages = info.pages; + } + if i.series.is_none() { + i.series = info.series; + } + for (k, v) in info.import_extra { + i.import_extra.entry(k).or_insert(v); + } + } + } + None => { + self.books.insert(book.clone(), Book::new(book, info)); + } + } + } + Op::BookRemove { book } => { + let c = self.canonical(book); + self.books.remove(&c); + self.removed_books.insert(c.clone()); + self.highlights.retain(|_, h| h.book != c); + } + Op::BookSet { book, field, value, base } => { + let c = self.canonical(book); + let key = (c.clone(), field.key()); + let Some(b) = self.books.get_mut(&c) else { return }; + let s = |v: &serde_json::Value| v.as_str().map(|s| clip(s.to_owned())); + let set_of = |v: &serde_json::Value| -> Option> { + serde_json::from_value::>(v.clone()) + .ok() + .map(|s| s.into_iter().take(256).map(clip).collect()) + }; + let ok = match field { + Field::Review | Field::Notes => { + let Some(v) = s(value) else { return }; + let t = if *field == Field::Review { &mut b.review } else { &mut b.notes }; + Self::set_text(&mut self.versions, key, t, v, base, &e.id); + return; + } + Field::Title => s(value).filter(|t| !t.is_empty()).map(|t| b.info.title = t).is_some(), + Field::Authors => { + serde_json::from_value::>(value.clone()).map(|a| b.info.authors = a).is_ok() + } + Field::Series => { + serde_json::from_value::>(value.clone()).map(|v| b.info.series = v).is_ok() + } + Field::Language => serde_json::from_value(value.clone()).map(|v| b.info.language = v).is_ok(), + Field::Publisher => serde_json::from_value(value.clone()).map(|v| b.info.publisher = v).is_ok(), + Field::Published => serde_json::from_value(value.clone()).map(|v| b.info.published = v).is_ok(), + Field::Description => serde_json::from_value::>(value.clone()) + .map(|v| b.info.description = v.map(clip)) + .is_ok(), + Field::Pages => serde_json::from_value(value.clone()).map(|v| b.info.pages = v).is_ok(), + Field::Isbn13 => serde_json::from_value::>(value.clone()) + .map(|v| b.info.isbn13 = v.as_deref().and_then(crate::isbn13)) + .is_ok(), + Field::Genres => serde_json::from_value(value.clone()).map(|v| b.info.genres = v).is_ok(), + Field::Paper => value.as_bool().map(|v| b.paper = v).is_some(), + Field::Possession => serde_json::from_value(value.clone()).map(|v| b.possession = v).is_ok(), + Field::Rating => serde_json::from_value::>(value.clone()) + .ok() + .map(|v| b.rating = v.filter(|r| (1..=10).contains(r))) + .is_some(), + Field::Moods => set_of(value).map(|v| b.moods = v).is_some(), + Field::Tags => set_of(value).map(|v| b.tags = v).is_some(), + Field::ToRead => value.as_bool().map(|v| b.to_read = v).is_some(), + Field::Cover => serde_json::from_value(value.clone()).map(|v| b.cover = v).is_ok(), + }; + if ok { + self.versions.insert(key, e.id.clone()); + } + } + Op::BookFileAdd { book, file } => { + if let Some(b) = self.book_mut(book) + && !b.files.iter().any(|f| f.sha256 == file.sha256) + { + b.files.push(file.clone()); + } + } + Op::BookFileRemove { book, sha256 } => { + if let Some(b) = self.book_mut(book) { + b.files.retain(|f| f.sha256 != *sha256); + } + } + Op::ShelfAdd { book, shelf } => { + if let Some(b) = self.book_mut(book) + && !shelf.trim().is_empty() + && b.shelves.len() < 256 + { + b.shelves.insert(clip(shelf.trim().to_owned())); + } + } + Op::ShelfRemove { book, shelf } => { + if let Some(b) = self.book_mut(book) { + b.shelves.remove(shelf.trim()); + } + } + Op::ReadStart { book, read, date } => { + let c = self.canonical(book); + if self.read_book.contains_key(read) { + return; + } + if let Some(b) = self.books.get_mut(&c) { + b.reads.push(Read { id: read.clone(), started: date.clone(), finished: None, outcome: None }); + b.to_read = false; + self.read_book.insert(read.clone(), c); + } + } + Op::ReadEnd { read, date, outcome } => { + if let Some(c) = self.read_book.get(read).cloned() + && let Some(b) = self.books.get_mut(&c) + && let Some(r) = b.reads.iter_mut().find(|r| r.id == *read) + { + r.finished = date.clone(); + r.outcome = Some(*outcome); + } + } + Op::ReadRemove { read } => { + if let Some(c) = self.read_book.get(read).cloned() + && let Some(b) = self.books.get_mut(&c) + { + b.reads.retain(|r| r.id != *read); + } + } + Op::Lend { loan, book, person, since, due } => { + let c = self.canonical(book); + if self.loan_book.contains_key(loan) { + return; + } + if let Some(b) = self.books.get_mut(&c) { + b.loans.push(Loan { + id: loan.clone(), + person: person.clone(), + since: since.clone(), + due: due.clone(), + returned: None, + }); + self.loan_book.insert(loan.clone(), c); + } + } + Op::Return { loan, date } => { + if let Some(c) = self.loan_book.get(loan).cloned() + && let Some(b) = self.books.get_mut(&c) + && let Some(l) = b.loans.iter_mut().find(|l| l.id == *loan) + && l.returned.is_none() + { + l.returned = Some(date.clone()); + } + } + Op::Position { book, cfi, chapter, progress, label } => { + if !progress.is_finite() { + return; + } + let p = Position { + cfi: cfi.clone(), + chapter: *chapter, + progress: progress.clamp(0.0, 1.0), + label: label.clone(), + }; + if let Some(b) = self.book_mut(book) { + if b.position.as_ref().is_none_or(|f| p.progress >= f.progress) { + b.position = Some(p.clone()); + } + b.last_position = Some(p); + } + } + Op::HighlightAdd { id, book, kind, anchor, colour, note, created } => { + if self.removed_highlights.contains(id) || self.highlights.contains_key(id) { + return; + } + let c = self.canonical(book); + if !self.books.contains_key(&c) { + return; + } + self.highlights.insert( + id.clone(), + Highlight { + id: id.clone(), + book: c, + kind: *kind, + anchor: anchor.clone(), + colour: *colour, + note: Text { value: clip(note.clone()), conflict: None }, + created: *created, + }, + ); + self.versions.insert((format!("hl:{id}"), "note"), e.id.clone()); + } + Op::HighlightSet { id, colour, note, base } => { + let Some(h) = self.highlights.get_mut(id) else { return }; + if let Some(c) = colour { + h.colour = *c; + } + if let Some(n) = note { + Self::set_text( + &mut self.versions, + (format!("hl:{id}"), "note"), + &mut h.note, + n.clone(), + base, + &e.id, + ); + } + } + Op::HighlightRemove { id } => { + self.highlights.remove(id); + self.removed_highlights.insert(id.clone()); + } + Op::Session { id, book, start, end, active_ms, pages, date } => { + let c = self.canonical(book); + if self.books.contains_key(&c) && end >= start { + self.sessions.entry(id.clone()).or_insert(Session { + id: id.clone(), + book: c, + start: *start, + end: *end, + active_ms: (*active_ms).min(end - start), + pages: *pages, + date: date.clone(), + }); + } + } + Op::Goal { year, kind, target } => { + self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target }); + } + } + } +} diff --git a/crates/liber-library/src/stats.rs b/crates/liber-library/src/stats.rs new file mode 100644 index 0000000..10d2cf7 --- /dev/null +++ b/crates/liber-library/src/stats.rs @@ -0,0 +1,99 @@ +//! Reading stats per year and all time (no comparison with anyone). + +use crate::library::{Goal, GoalKind, Library, Outcome}; +use crate::year_of; +use serde::Serialize; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Stats { + /// `None`: all time. + pub year: Option, + pub books: u32, + pub did_not_finish: u32, + /// Pages of the books finished (from their page counts). + pub pages: u64, + pub active_minutes: u64, + /// Pages turned in sessions per active hour. + pub pace: Option, + pub moods: BTreeMap, + pub genres: BTreeMap, + /// (book id, pages) + pub longest: Option<(String, u32)>, + pub shortest: Option<(String, u32)>, + pub goal: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct GoalProgress { + pub kind: GoalKind, + pub target: u32, + pub done: u64, +} + +/// Stats for one year (`Some(y)`, by finish date and session day) or all time (`None`). +pub fn stats(lib: &Library, year: Option) -> Stats { + let mut s = Stats { year, ..Stats::default() }; + let in_year = |date: Option<&str>| match year { + None => true, + Some(y) => date.and_then(year_of) == Some(y), + }; + for b in lib.books.values() { + for r in &b.reads { + let Some(outcome) = r.outcome else { continue }; + if !in_year(r.finished.as_deref()) { + continue; + } + match outcome { + Outcome::DidNotFinish => s.did_not_finish += 1, + Outcome::Read => { + s.books += 1; + if let Some(p) = b.info.pages { + s.pages += p as u64; + if s.longest.as_ref().is_none_or(|(_, l)| p > *l) { + s.longest = Some((b.id.clone(), p)); + } + if s.shortest.as_ref().is_none_or(|(_, l)| p < *l) { + s.shortest = Some((b.id.clone(), p)); + } + } + for m in &b.moods { + *s.moods.entry(m.clone()).or_default() += 1; + } + for g in &b.info.genres { + *s.genres.entry(g.clone()).or_default() += 1; + } + } + } + } + } + let mut active_ms = 0u64; + let mut pages_turned = 0u64; + for x in lib.sessions.values() { + if in_year(Some(&x.date)) { + active_ms += x.active_ms; + pages_turned += x.pages as u64; + } + } + s.active_minutes = active_ms / 60_000; + if active_ms >= 60_000 { + s.pace = Some(pages_turned as f64 / (active_ms as f64 / 3_600_000.0)); + } + if let Some(y) = year + && let Some(Goal { kind, target, .. }) = lib.goals.get(&y) + { + let done = match kind { + GoalKind::Books => s.books as u64, + GoalKind::Pages => s.pages, + }; + s.goal = Some(GoalProgress { kind: *kind, target: *target, done }); + } + s +} + +/// Active reading time for one page view (docs/01_books.md): the time on the page, at most two minutes. +pub const IDLE_CAP_MS: u64 = 2 * 60 * 1000; + +pub fn active_ms(on_page_ms: u64) -> u64 { + on_page_ms.min(IDLE_CAP_MS) +} diff --git a/crates/liber-library/tests/common/mod.rs b/crates/liber-library/tests/common/mod.rs new file mode 100644 index 0000000..a190ca3 --- /dev/null +++ b/crates/liber-library/tests/common/mod.rs @@ -0,0 +1,136 @@ +#![allow(dead_code)] +//! A seeded generator of plausible operations from several devices. + +use liber_library::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person, Possession, Series}; +use liber_library::{Clock, Event, Op}; +use serde_json::json; + +pub struct Rng(pub u64); +impl Rng { + pub fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + pub fn below(&mut self, n: u64) -> u64 { + self.next() % n.max(1) + } + pub fn pick<'a, T>(&mut self, v: &'a [T]) -> &'a T { + &v[self.below(v.len() as u64) as usize] + } +} + +pub const BOOKS: &[&str] = &["b-valka", "b-dune", "b-rur", "b-babicka"]; + +pub fn info(i: usize) -> BookInfo { + let titles = ["Válka s mloky", "Dune", "R.U.R.", "Babička"]; + BookInfo { + title: titles[i].into(), + authors: vec![["Karel Čapek", "Frank Herbert", "Karel Čapek", "Božena Němcová"][i].into()], + isbn13: [Some("9788020712479"), Some("9780441172719"), None, None][i].map(str::to_owned), + fingerprint: [None, None, Some("fp-rur"), None][i].map(str::to_owned), + pages: Some([280, 604, 100, 320][i]), + series: (i == 1).then(|| Series { name: "Dune".into(), index: Some(1.0) }), + genres: vec!["classic".into()], + added: 1_700_000_000_000 + i as u64, + ..BookInfo::default() + } +} + +/// One random operation by `dev` (its own ids carry the device name, so they never collide). +pub fn op(r: &mut Rng, dev: &str, n: usize) -> Op { + let bi = r.below(BOOKS.len() as u64) as usize; + let book = BOOKS[bi].to_string(); + let hl = format!("h-{dev}-{}", r.below(6)); + let date = format!("2025-{:02}-{:02}", 1 + r.below(12), 1 + r.below(28)); + match r.below(17) { + 0 | 1 => Op::BookAdd { book, info: info(bi), restore: false }, + 2 => Op::BookSet { book, field: Field::Review, value: json!(format!("review {dev} {n}")), base: None }, + 3 => Op::BookSet { book, field: Field::Rating, value: json!(1 + r.below(10)), base: None }, + 4 => Op::ShelfAdd { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() }, + 5 => Op::ShelfRemove { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() }, + 6 => Op::Position { + book, + cfi: format!("epubcfi(/6/{}!/4/2/1:{})", 2 * (1 + r.below(5)), r.below(100)), + chapter: r.below(5) as u32, + progress: r.below(1000) as f64 / 1000.0, + label: Some(format!("{}", r.below(300))), + }, + 7 => Op::HighlightAdd { + id: hl, + book, + kind: *r.pick(&[Mark::Highlight, Mark::Note, Mark::Bookmark]), + anchor: json!({"chapter": r.below(5), "quote": {"exact": format!("quote {dev} {n}"), "prefix": "", "suffix": ""}}), + colour: *r.pick(&[Colour::Yellow, Colour::Green, Colour::Blue, Colour::Pink]), + note: format!("note {dev} {n}"), + created: 1_700_000_000_000 + n as u64, + }, + 8 => Op::HighlightSet { id: hl, colour: Some(Colour::Pink), note: Some(format!("edit {dev} {n}")), base: None }, + 9 => Op::HighlightRemove { id: hl }, + 10 => Op::ReadStart { book, read: format!("r-{dev}-{n}"), date: Some(date) }, + 11 => Op::ReadEnd { + read: format!("r-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), + date: Some(date), + outcome: *r.pick(&[Outcome::Read, Outcome::DidNotFinish]), + }, + 12 => Op::Lend { + loan: format!("l-{dev}-{n}"), + book, + person: Person { id: None, name: "Jana".into() }, + since: date, + due: None, + }, + 13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date }, + 14 => Op::Session { + id: format!("s-{dev}-{n}"), + book, + start: 1000, + end: 1000 + r.below(600_000), + active_ms: r.below(400_000), + pages: r.below(30) as u32, + date, + }, + 15 => Op::BookSet { + book, + field: Field::Possession, + value: serde_json::to_value(r.pick(&[ + Possession::Owned, + Possession::Wishlist, + Possession::Borrowed { + from: Person { id: Some("p1".into()), name: "Petr".into() }, + due: Some("2025-12-01".into()), + }, + ])) + .unwrap(), + base: None, + }, + _ => match r.below(3) { + 0 => Op::Goal { year: 2025, kind: GoalKind::Books, target: 10 + r.below(40) as u32 }, + 1 => Op::BookFileAdd { + book, + file: BookFile { + sha256: format!("{:064x}", r.below(4)), + format: "epub".into(), + size: 1000, + name: "x.epub".into(), + }, + }, + _ => Op::BookSet { book, field: Field::Notes, value: json!(format!("notes {dev} {n}")), base: None }, + }, + } +} + +/// `count` events from device `dev`, its clock `skew_ms` off the shared timeline. +pub fn events(seed: u64, dev: &str, count: usize, skew_ms: i64) -> Vec { + let mut r = Rng(seed | 1); + let mut c = Clock::default(); + let mut out = Vec::new(); + let mut t: i64 = 1_750_000_000_000; + for n in 0..count { + t += r.below(5_000) as i64; + let hlc = c.tick((t + skew_ms) as u64); + out.push(Event { id: format!("{dev}-{n}"), hlc, device: dev.into(), op: op(&mut r, dev, n) }); + } + out +} diff --git a/crates/liber-library/tests/export.rs b/crates/liber-library/tests/export.rs new file mode 100644 index 0000000..8c66f35 --- /dev/null +++ b/crates/liber-library/tests/export.rs @@ -0,0 +1,139 @@ +//! Mandatory test 4: export, then import into an empty library, reproduces books, states, shelves, highlights and +//! stats exactly. + +mod common; +use common::{events, info}; +use liber_library::export::{from_json, to_json, write_zip}; +use liber_library::library::{Colour, Field, Mark}; +use liber_library::stats::stats; +use liber_library::{Clock, Event, Library, Op}; +use proptest::prelude::*; +use serde_json::json; +use std::io::Read; + +fn assert_round_trip(lib: &Library) { + let json = to_json(lib, "2026-11-17T10:00:00Z"); + let back = from_json(&json).expect("import"); + assert_eq!(&back, lib); + for y in [None, Some(2024), Some(2025), Some(2026)] { + assert_eq!(stats(&back, y), stats(lib, y), "stats {y:?}"); + } + // Exporting the imported library gives the same file. + assert_eq!(to_json(&back, "2026-11-17T10:00:00Z"), json); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 150, ..ProptestConfig::default() })] + #[test] + fn random_libraries_round_trip(seed in any::(), n in 1usize..120) { + let mut all = events(seed, "phone", n, 0); + all.extend(events(seed ^ 0x5555, "desk", n / 2, 90_000)); + let lib = Library::from_events(&all); + assert_round_trip(&lib); + } +} + +#[test] +fn a_library_with_conflicts_round_trips() { + let mut c = Clock::default(); + let mut d = Clock::default(); + let mut e = |id: &str, dev: &str, t: u64, op: Op| { + let hlc = if dev == "a" { c.tick(t) } else { d.tick(t) }; + Event { id: id.into(), hlc, device: dev.into(), op } + }; + let evs = vec![ + e("1", "a", 1, Op::BookAdd { book: "b".into(), info: info(0), restore: false }), + e("2", "a", 2, Op::BookSet { book: "b".into(), field: Field::Review, value: json!("A"), base: None }), + e( + "3", + "a", + 3, + Op::BookSet { book: "b".into(), field: Field::Review, value: json!("B"), base: Some("2".into()) }, + ), + e( + "4", + "b", + 3, + Op::BookSet { book: "b".into(), field: Field::Review, value: json!("C"), base: Some("2".into()) }, + ), + e( + "5", + "a", + 4, + Op::HighlightAdd { + id: "h".into(), + book: "b".into(), + kind: Mark::Note, + anchor: json!({"quote": {"exact": "slovo"}}), + colour: Colour::Green, + note: "x".into(), + created: 4, + }, + ), + e( + "6", + "a", + 5, + Op::HighlightSet { id: "h".into(), colour: None, note: Some("y".into()), base: Some("5".into()) }, + ), + e( + "7", + "b", + 5, + Op::HighlightSet { id: "h".into(), colour: None, note: Some("z".into()), base: Some("5".into()) }, + ), + e("8", "a", 6, Op::BookAdd { book: "same-isbn".into(), info: info(1), restore: false }), + e( + "9", + "a", + 7, + Op::BookSet { book: "b".into(), field: Field::Isbn13, value: json!("9780441172719"), base: None }, + ), + ]; + let lib = Library::from_events(&evs); + assert!(lib.books["b"].review.conflict.is_some()); + assert!(lib.highlights["h"].note.conflict.is_some()); + assert_eq!(lib.books.len(), 2, "two books share an ISBN after an edit; the export keeps both"); + assert_round_trip(&lib); +} + +#[test] +fn the_zip_holds_json_csv_markdown_and_files() { + let mut all = events(42, "phone", 200, 0); + all.push(Event { + id: "file".into(), + hlc: liber_library::Hlc { wall: u64::MAX / 2, logical: 0 }, + device: "phone".into(), + op: Op::BookFileAdd { + book: "b-valka".into(), + file: liber_library::library::BookFile { + sha256: "ab".repeat(32), + format: "epub".into(), + size: 5, + name: "v.epub".into(), + }, + }, + }); + let lib = Library::from_events(&all); + let bytes = write_zip(&lib, Vec::new(), "2026-11-17T10:00:00Z", &mut |_, f| { + (f.sha256 == "ab".repeat(32)).then(|| Box::new(&b"EPUB!"[..]) as Box) + }) + .unwrap(); + let z = liber_format::zip::Zip::parse(&bytes, &liber_format::Limits::default()).unwrap(); + let names: Vec<&str> = z.entries().iter().map(|e| e.name.as_str()).collect(); + assert!(names.contains(&"library.json") && names.contains(&"books.csv")); + if !lib.highlights.is_empty() { + assert!(names.iter().any(|n| n.starts_with("highlights/") && n.ends_with(".md"))); + } + let file = names.iter().find(|n| n.starts_with("files/")).expect("the book file"); + assert_eq!(z.read_name(file).unwrap().unwrap(), b"EPUB!"); + let json = String::from_utf8(z.read_name("library.json").unwrap().unwrap()).unwrap(); + assert_eq!(from_json(&json).unwrap(), lib); +} + +#[test] +fn a_foreign_or_newer_export_is_refused() { + assert!(from_json("{}").is_err()); + assert!(from_json(r#"{"format":"liber-export","version":2,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}}}"#).is_err()); + assert!(from_json(r#"{"format":"liber-export","version":1,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}},"extra":1}"#).is_err()); +} diff --git a/crates/liber-library/tests/import.rs b/crates/liber-library/tests/import.rs new file mode 100644 index 0000000..381da3b --- /dev/null +++ b/crates/liber-library/tests/import.rs @@ -0,0 +1,152 @@ +//! Mandatory test 3: Goodreads and StoryGraph CSVs (quotes, commas, Czech) import every row; unknown columns are +//! reported and kept; hostile CSVs (formula injection, a 100 MB line) are handled safely. + +use liber_library::import::{ImportError, Source, import_csv}; +use liber_library::{Clock, Event, Library, Op, ReadStatus}; + +pub const GOODREADS: &str = "\u{feff}Book Id,Title,Author,Author l-f,Additional Authors,ISBN,ISBN13,My Rating,Average Rating,Publisher,Binding,Number of Pages,Year Published,Original Publication Year,Date Read,Date Added,Bookshelves,Bookshelves with positions,Exclusive Shelf,My Review,Spoiler,Private Notes,Read Count,Owned Copies,My Custom Column\n\ +1,\"Válka s mloky\",Karel Čapek,\"Čapek, Karel\",,\"=\"\"802071247X\"\"\",\"=\"\"\"\"\",5,4.10,\"Československý spisovatel\",Paperback,280,2004,1936,2023/05/14,2023/01/02,\"klasika, favourites\",\"klasika (#3), favourites (#1)\",read,\"Skvělé!

    Mloci, \"\"lidé\"\" a obchod.\",,soukromá poznámka,2,1,custom value\n\ +2,\"Dune, Part One\",Frank Herbert,\"Herbert, Frank\",\"Someone Else\",\"=\"\"0441172717\"\"\",\"=\"\"9780441172719\"\"\",0,4.25,Ace,Mass Market Paperback,604,1990,1965,,2024/02/03,to-read,to-read (#4),to-read,,,,0,0,\n\ +3,R.U.R.,Karel Čapek,\"Čapek, Karel\",,,,3,3.80,,Kindle Edition,100,2010,1920,,2024/03/01,currently-reading,,currently-reading,,,,1,0,\n"; + +pub const STORYGRAPH: &str = "Title,Authors,Contributors,ISBN/UID,Format,Read Status,Date Added,Last Date Read,Dates Read,Read Count,Moods,Pace,Character- or Plot-Driven?,Strong Character Development?,Loveable Characters?,Diverse Characters?,Flawed Characters?,Star Rating,Review,Content Warnings,Content Warning Description,Tags,Owned?\n\ +Babička,Božena Němcová,,9788020712479,paperback,read,2023/01/01,2023/02/10,\"2022/12/01-2022/12/20, 2023/01/15-2023/02/10\",2,\"reflective, emotional, cozy\",slow,Character,Yes,Yes,No,Yes,4.25,\"Krásná, \"\"klidná\"\" kniha.\",,,\"czech, classics\",Yes\n\ +Neznámá kniha,\"A. Author, B. Author\",,abc-uid-123,digital,did-not-finish,2023/03/01,2023/03/05,,0,,,,,,,,0,,,,,No\n\ +Další,C. Author,,,audio,to-read,2023/04/01,,,0,,,,,,,,,,,,,No\n"; + +fn ids() -> impl FnMut() -> String { + let mut n = 0; + move || { + n += 1; + format!("id{n:04}") + } +} + +pub fn apply(lib_ops: Vec) -> Library { + let mut c = Clock::default(); + let events: Vec = lib_ops + .into_iter() + .enumerate() + .map(|(i, op)| Event { id: format!("e{i}"), hlc: c.tick(1_700_000_000_000), device: "d".into(), op }) + .collect(); + Library::from_events(&events) +} + +#[test] +fn goodreads_imports_every_row() { + let (ops, r) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap(); + assert_eq!(r.source, Source::Goodreads); + assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped); + assert_eq!(r.unknown_columns, vec!["My Custom Column"]); + assert!(r.unused_columns.contains(&"Average Rating".to_owned())); + let lib = apply(ops); + let valka = lib.books.values().find(|b| b.info.title == "Válka s mloky").unwrap(); + assert_eq!(valka.info.isbn13.as_deref(), Some("9788020712479")); + assert_eq!(valka.info.authors, vec!["Karel Čapek"]); + assert_eq!(valka.info.publisher.as_deref(), Some("Československý spisovatel")); + assert_eq!(valka.info.published.as_deref(), Some("1936")); + assert_eq!(valka.rating, Some(10)); + assert_eq!(valka.review.value, "Skvělé!\n\nMloci, \"lidé\" a obchod."); + assert_eq!(valka.notes.value, "soukromá poznámka"); + assert_eq!(valka.status(), ReadStatus::Read); + assert_eq!(valka.reads.len(), 2, "read twice"); + assert_eq!(valka.reads[1].finished.as_deref(), Some("2023-05-14")); + assert!(valka.paper); + assert_eq!(valka.shelves.iter().cloned().collect::>(), vec!["favourites", "klasika"]); + assert_eq!(valka.info.import_extra.get("goodreads:My Custom Column").map(String::as_str), Some("custom value")); + assert_eq!(valka.info.import_extra.get("goodreads:Book Id").map(String::as_str), Some("1")); + let dune = lib.books.values().find(|b| b.info.title == "Dune, Part One").unwrap(); + assert_eq!(dune.info.authors, vec!["Frank Herbert", "Someone Else"]); + assert_eq!(dune.status(), ReadStatus::ToRead); + assert_eq!(dune.rating, None); + let rur = lib.books.values().find(|b| b.info.title == "R.U.R.").unwrap(); + assert_eq!(rur.status(), ReadStatus::Reading); + assert!(!rur.paper); +} + +#[test] +fn storygraph_imports_every_row() { + let (ops, r) = import_csv(STORYGRAPH.as_bytes(), &Library::default(), &mut ids(), 0).unwrap(); + assert_eq!(r.source, Source::StoryGraph); + assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped); + assert!(r.unknown_columns.is_empty()); + let lib = apply(ops); + let b = lib.books.values().find(|b| b.info.title == "Babička").unwrap(); + assert_eq!(b.reads.len(), 2); + assert_eq!(b.reads[0].started.as_deref(), Some("2022-12-01")); + assert_eq!(b.reads[1].finished.as_deref(), Some("2023-02-10")); + assert_eq!(b.rating, Some(9), "4.25 stars rounds to 4.5"); + assert_eq!(b.moods.iter().cloned().collect::>(), vec!["emotional", "reflective"]); + assert!(b.tags.contains("cozy") && b.tags.contains("czech")); + assert_eq!(b.review.value, "Krásná, \"klidná\" kniha."); + assert_eq!(b.info.import_extra.get("storygraph:Pace").map(String::as_str), Some("slow")); + let n = lib.books.values().find(|b| b.info.title == "Neznámá kniha").unwrap(); + assert_eq!(n.status(), ReadStatus::DidNotFinish); + assert_eq!(n.info.authors, vec!["A. Author", "B. Author"]); + assert_eq!(n.info.import_extra.get("storygraph:ISBN/UID").map(String::as_str), Some("abc-uid-123")); +} + +#[test] +fn windows_1250_csv() { + let plain = GOODREADS.replace('\u{feff}', ""); + let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(&plain); + let (ops, r) = import_csv(&bytes, &Library::default(), &mut ids(), 0).unwrap(); + assert_eq!(r.imported, 3); + assert!(apply(ops).books.values().any(|b| b.info.title == "Válka s mloky")); +} + +#[test] +fn importing_twice_adds_nothing() { + let (ops, _) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap(); + let lib = apply(ops); + let (ops2, r) = import_csv(GOODREADS.as_bytes(), &lib, &mut ids(), 0).unwrap(); + assert!(ops2.is_empty()); + assert_eq!(r.skipped.len(), 3); +} + +#[test] +fn formula_injection_is_stored_as_text_and_exported_inert() { + let csv = "Title,Authors,ISBN/UID,Read Status,Review\n\"=HYPERLINK(\"\"http://evil\"\",\"\"x\"\")\",@SUM(A1),,to-read,+cmd|' /C calc'!A0\n"; + let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap(); + assert_eq!(r.imported, 1); + let lib = apply(ops); + let b = lib.books.values().next().unwrap(); + assert_eq!(b.info.title, "=HYPERLINK(\"http://evil\",\"x\")"); + let out = liber_library::export::books_csv(&lib); + assert!(out.contains("'=HYPERLINK"), "{out}"); + assert!(out.contains("'@SUM(A1)")); + assert!(out.contains("'+cmd")); + for line in out.lines().skip(1) { + for cell in line.split(',') { + let c = cell.trim_start_matches('"'); + assert!(!c.starts_with(['=', '+', '@']), "{cell}"); + } + } +} + +#[test] +fn a_100_mb_line_is_refused_early_and_a_huge_field_is_cut() { + let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\n"); + csv.push_str(&"x".repeat(100 * 1024 * 1024)); + let t = std::time::Instant::now(); + assert_eq!(import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap_err(), ImportError::TooLarge); + assert!(t.elapsed().as_secs() < 5); + let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\nBig,A,,read,\""); + csv.push_str(&"ř".repeat(5 * 1024 * 1024)); + csv.push_str("\"\n"); + let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap(); + assert_eq!(r.imported, 1); + assert_eq!(r.truncated, vec![(1, "Review".to_owned())]); + let lib = apply(ops); + assert!(lib.books.values().next().unwrap().review.value.len() <= 64 * 1024); +} + +#[test] +fn not_an_export() { + assert_eq!( + import_csv(b"a,b,c\n1,2,3\n", &Library::default(), &mut ids(), 0).unwrap_err(), + ImportError::UnknownFormat + ); + let junk: Vec = (0..50_000u32).map(|i| (i * 31 % 251) as u8).collect(); + assert!(import_csv(&junk, &Library::default(), &mut ids(), 0).is_err()); +} diff --git a/crates/liber-library/tests/stats.rs b/crates/liber-library/tests/stats.rs new file mode 100644 index 0000000..b72d4a1 --- /dev/null +++ b/crates/liber-library/tests/stats.rs @@ -0,0 +1,69 @@ +mod common; +use common::info; +use liber_library::library::{GoalKind, Outcome}; +use liber_library::stats::{active_ms, stats}; +use liber_library::{Clock, Event, Library, Op}; +use serde_json::json; + +#[test] +fn yearly_and_all_time() { + let mut c = Clock::default(); + let mut n = 0; + let mut e = |op: Op| { + n += 1; + Event { id: format!("e{n}"), hlc: c.tick(n), device: "d".into(), op } + }; + let evs = vec![ + e(Op::BookAdd { book: "a".into(), info: info(0), restore: false }), + e(Op::BookAdd { book: "b".into(), info: info(1), restore: false }), + e(Op::BookAdd { book: "c".into(), info: info(2), restore: false }), + e(Op::BookSet { + book: "a".into(), + field: liber_library::library::Field::Moods, + value: json!(["dark", "tense"]), + base: None, + }), + e(Op::ReadStart { book: "a".into(), read: "r1".into(), date: Some("2025-01-02".into()) }), + e(Op::ReadEnd { read: "r1".into(), date: Some("2025-02-01".into()), outcome: Outcome::Read }), + e(Op::ReadStart { book: "b".into(), read: "r2".into(), date: Some("2025-03-01".into()) }), + e(Op::ReadEnd { read: "r2".into(), date: Some("2025-04-01".into()), outcome: Outcome::Read }), + e(Op::ReadStart { book: "c".into(), read: "r3".into(), date: None }), + e(Op::ReadEnd { read: "r3".into(), date: Some("2024-05-01".into()), outcome: Outcome::DidNotFinish }), + e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }), + e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }), + e(Op::Session { + id: "s1".into(), + book: "a".into(), + start: 0, + end: 3_600_000, + active_ms: 1_800_000, + pages: 30, + date: "2025-01-10".into(), + }), + e(Op::Session { + id: "s2".into(), + book: "b".into(), + start: 0, + end: 3_600_000, + active_ms: 9_999_999_999, + pages: 60, + date: "2025-03-10".into(), + }), + e(Op::Goal { year: 2025, kind: GoalKind::Books, target: 12 }), + ]; + let lib = Library::from_events(&evs); + let s = stats(&lib, Some(2025)); + assert_eq!((s.books, s.did_not_finish, s.pages), (2, 0, 280 + 604)); + assert_eq!(s.active_minutes, 30 + 60, "a session's active time is capped at its length"); + assert_eq!(s.pace, Some(60.0)); + assert_eq!(s.longest, Some(("b".into(), 604))); + assert_eq!(s.shortest, Some(("a".into(), 280))); + assert_eq!(s.moods.get("dark"), Some(&1)); + assert_eq!(s.genres.get("classic"), Some(&2)); + let g = s.goal.unwrap(); + assert_eq!((g.target, g.done), (12, 2)); + let all = stats(&lib, None); + assert_eq!((all.books, all.did_not_finish), (3, 1), "a re-read counts again"); + assert_eq!(stats(&lib, Some(2024)).did_not_finish, 1); + assert_eq!(active_ms(10 * 60_000), 2 * 60_000, "two minutes per page at most"); +} diff --git a/crates/liber-library/tests/sync.rs b/crates/liber-library/tests/sync.rs new file mode 100644 index 0000000..add09da --- /dev/null +++ b/crates/liber-library/tests/sync.rs @@ -0,0 +1,192 @@ +//! Mandatory test 5 (the core's half): devices with clock skew and dropped connections converge; highlights made +//! offline on both merge; positions keep the furthest with a "jump back" offer; concurrent text edits keep both. +//! (The app's `liber-store` tests the relay: ciphertext only on the wire.) + +mod common; +use common::{Rng, events, info}; +use liber_library::library::{Colour, Field, Mark}; +use liber_library::{Clock, Event, Library, Op}; +use proptest::prelude::*; +use serde_json::json; + +fn shuffle(mut v: Vec, r: &mut Rng) -> Vec { + for i in (1..v.len()).rev() { + let j = r.below(i as u64 + 1) as usize; + v.swap(i, j); + } + v +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 200, ..ProptestConfig::default() })] + + /// Two devices, skewed clocks, events delivered in random order, with duplicates, in several partial rounds + /// (dropped connections): once both hold every event, both hold the same library. + #[test] + fn devices_converge(seed in any::(), skew in -180_000i64..180_000, na in 1usize..60, nb in 1usize..60) { + let a = events(seed, "phone", na, 0); + let b = events(seed.rotate_left(17) ^ 0x9e37, "desk", nb, skew); + let mut r = Rng(seed ^ 0xabcdef | 1); + // Device A's view: its own events, then B's arriving in random batches, some twice. + let mut on_a = a.clone(); + let mut incoming = shuffle(b.clone(), &mut r); + while !incoming.is_empty() { + let k = 1 + r.below(incoming.len() as u64) as usize; + let batch: Vec = incoming.drain(..k).collect(); + on_a.extend(batch.iter().cloned()); + if r.below(3) == 0 { + on_a.extend(batch); // a retried upload + } + // A partial library after each round never panics. + let _ = Library::from_events(&on_a); + } + let mut on_b = b.clone(); + on_b.extend(shuffle(a.clone(), &mut r)); + let la = Library::from_events(&on_a); + let lb = Library::from_events(&on_b); + prop_assert_eq!(&la, &lb); + // And the stats agree. + prop_assert_eq!(liber_library::stats::stats(&la, Some(2025)), liber_library::stats::stats(&lb, Some(2025))); + } +} + +fn ev(id: &str, dev: &str, c: &mut Clock, t: u64, op: Op) -> Event { + Event { id: id.into(), hlc: c.tick(t), device: dev.into(), op } +} + +fn add(book: &str) -> Op { + Op::BookAdd { book: book.into(), info: info(0), restore: false } +} + +#[test] +fn highlights_made_offline_on_both_devices_merge() { + let (mut pc, mut dc) = (Clock::default(), Clock::default()); + let base = ev("p0", "phone", &mut pc, 1000, add("b")); + let hl = |id: &str, dev: &str, c: &mut Clock, t: u64, q: &str| { + ev( + &format!("{dev}-{id}"), + dev, + c, + t, + Op::HighlightAdd { + id: id.into(), + book: "b".into(), + kind: Mark::Highlight, + anchor: json!({"quote": {"exact": q}}), + colour: Colour::Yellow, + note: String::new(), + created: t, + }, + ) + }; + let p = [base.clone(), hl("h1", "phone", &mut pc, 2000, "na telefonu")]; + let d = [base, hl("h2", "desk", &mut dc, 1500, "na počítači")]; + let all: Vec = p.iter().chain(d.iter()).cloned().collect(); + let lib = Library::from_events(&all); + assert_eq!(lib.highlights.len(), 2); + // A deletion on one device and an edit on the other: the deletion wins, everywhere. + let mut more = all.clone(); + more.push(ev("d-del", "desk", &mut dc, 3000, Op::HighlightRemove { id: "h1".into() })); + more.push(ev( + "p-edit", + "phone", + &mut pc, + 3500, + Op::HighlightSet { id: "h1".into(), colour: Some(Colour::Blue), note: None, base: None }, + )); + let l = Library::from_events(&more); + assert!(!l.highlights.contains_key("h1")); + assert!(l.highlights.contains_key("h2")); +} + +#[test] +fn positions_keep_the_furthest_and_offer_a_jump_back() { + let mut c = Clock::default(); + let pos = |id: &str, c: &mut Clock, t: u64, p: f64| { + ev( + id, + "x", + c, + t, + Op::Position { + book: "b".into(), + cfi: format!("epubcfi(/6/2!/4/2/1:{})", (p * 100.0) as u32), + chapter: 0, + progress: p, + label: Some(format!("{}", (p * 300.0) as u32)), + }, + ) + }; + let events = vec![ev("a", "x", &mut c, 1, add("b")), pos("p1", &mut c, 10, 0.6), pos("p2", &mut c, 20, 0.3)]; + let l = Library::from_events(&events); + let b = &l.books["b"]; + assert_eq!(b.position.as_ref().unwrap().progress, 0.6); + assert_eq!(b.jump_back().unwrap().progress, 0.3, "the newest position is behind: offer to jump back"); + let mut ev2 = events.clone(); + ev2.push(pos("p3", &mut c, 30, 0.7)); + assert!(Library::from_events(&ev2).books["b"].jump_back().is_none()); +} + +#[test] +fn concurrent_text_edits_keep_both_versions() { + let (mut pc, mut dc) = (Clock::default(), Clock::default()); + let a = ev("a", "phone", &mut pc, 1, add("b")); + let r0 = ev( + "r0", + "phone", + &mut pc, + 2, + Op::BookSet { book: "b".into(), field: Field::Review, value: json!("first"), base: None }, + ); + // Both devices saw r0, then edited offline. + let rp = ev( + "rp", + "phone", + &mut pc, + 10, + Op::BookSet { + book: "b".into(), + field: Field::Review, + value: json!("phone's version"), + base: Some("r0".into()), + }, + ); + dc.observe(r0.hlc); + let rd = ev( + "rd", + "desk", + &mut dc, + 9, + Op::BookSet { book: "b".into(), field: Field::Review, value: json!("desk's version"), base: Some("r0".into()) }, + ); + let l = Library::from_events(&[a.clone(), r0.clone(), rp.clone(), rd.clone()]); + let review = &l.books["b"].review; + let mut both = vec![review.value.clone(), review.conflict.clone().unwrap()]; + both.sort(); + assert_eq!(both, vec!["desk's version", "phone's version"]); + // The next edit, made seeing the merged state, clears the marker. + let v = l.version("b", Field::Review).map(str::to_owned); + let fix = ev( + "fix", + "desk", + &mut dc, + 20, + Op::BookSet { book: "b".into(), field: Field::Review, value: json!("merged"), base: v }, + ); + let l = Library::from_events(&[a, r0, rp, rd, fix]); + assert_eq!(l.books["b"].review.value, "merged"); + assert!(l.books["b"].review.conflict.is_none()); +} + +#[test] +fn the_same_book_added_on_two_devices_merges() { + let (mut pc, mut dc) = (Clock::default(), Clock::default()); + let p = ev("p", "phone", &mut pc, 5, Op::BookAdd { book: "phone-id".into(), info: info(1), restore: false }); + let d = ev("d", "desk", &mut dc, 3, Op::BookAdd { book: "desk-id".into(), info: info(1), restore: false }); + let s = ev("s", "phone", &mut pc, 6, Op::ShelfAdd { book: "phone-id".into(), shelf: "sci-fi".into() }); + let l = Library::from_events(&[p, d, s]); + assert_eq!(l.books.len(), 1); + let b = l.books.values().next().unwrap(); + assert_eq!(b.id, "desk-id", "the earlier add wins; the other id is an alias"); + assert!(b.shelves.contains("sci-fi")); +}