diff --git a/Cargo.lock b/Cargo.lock index 8c2a54d..12a76a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,23 @@ # 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 = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -23,6 +40,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "android_system_properties" version = "0.1.5" @@ -110,6 +142,7 @@ dependencies = [ "chrono", "hex", "libc", + "lopdf", "regex", "reqwest", "rusqlite", @@ -133,7 +166,7 @@ dependencies = [ "base64", "chrono", "parking_lot", - "rand", + "rand 0.8.6", "regex", "reqwest", "rusqlite", @@ -141,10 +174,12 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "tokio-util", "toml", "tower", "tower-http", "uuid", + "zip", ] [[package]] @@ -155,7 +190,7 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" dependencies = [ "base64ct", "blake2", - "cpufeatures", + "cpufeatures 0.2.17", "password-hash", ] @@ -167,7 +202,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -276,9 +311,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bitflags" -version = "2.11.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "blake2" @@ -286,7 +321,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -298,6 +333,34 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.19.0" @@ -310,6 +373,15 @@ version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.41" @@ -326,6 +398,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" +[[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 0.10.1", +] + [[package]] name = "chrono" version = "0.4.42" @@ -339,6 +422,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clap" version = "4.5.48" @@ -370,7 +463,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -385,6 +478,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "cookie" version = "0.18.1" @@ -422,6 +521,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -431,6 +536,15 @@ 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.2" @@ -450,6 +564,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "deranged" version = "0.5.8" @@ -462,11 +585,22 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.6", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + [[package]] name = "displaydoc" version = "0.2.6" @@ -475,7 +609,16 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", +] + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", ] [[package]] @@ -533,6 +676,8 @@ version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ + "crc32fast", + "miniz_oxide", "zlib-rs", ] @@ -644,10 +789,22 @@ checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 5.3.0", "wasi 0.14.7+wasi-0.2.4", ] +[[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 6.0.0", + "rand_core 0.10.1", +] + [[package]] name = "h2" version = "0.4.15" @@ -754,6 +911,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.10.1" @@ -968,6 +1134,16 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1002,7 +1178,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" dependencies = [ - "cpufeatures", + "cpufeatures 0.2.17", ] [[package]] @@ -1049,12 +1225,49 @@ version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" +[[package]] +name = "lopdf" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3" +dependencies = [ + "aes", + "bitflags", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom 0.4.3", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand 0.10.3", + "rangemap", + "sha2", + "stringprep", + "thiserror", + "weezl", +] + [[package]] name = "matchit" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.7.6" @@ -1077,6 +1290,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.1" @@ -1122,6 +1345,15 @@ dependencies = [ "tempfile", ] +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1171,7 +1403,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1222,7 +1454,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -1292,6 +1524,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[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.8.6" @@ -1300,7 +1538,18 @@ checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1310,7 +1559,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -1322,6 +1571,18 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1553,7 +1814,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1602,13 +1863,24 @@ dependencies = [ "serde", ] +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha3" version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" dependencies = [ - "digest", + "digest 0.10.7", "keccak", ] @@ -1618,6 +1890,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -1652,6 +1930,17 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -1675,6 +1964,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -1692,7 +1992,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1729,6 +2029,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[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 3.0.9", +] + [[package]] name = "time" version = "0.3.51" @@ -1769,6 +2089,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.52.3" @@ -1792,7 +2118,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1969,12 +2295,33 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "untrusted" version = "0.9.0" @@ -2084,7 +2431,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-shared", ] @@ -2119,7 +2466,7 @@ checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -2143,6 +2490,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + [[package]] name = "windows-core" version = "0.62.2" @@ -2164,7 +2517,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2175,7 +2528,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2409,7 +2762,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "synstructure", ] @@ -2430,7 +2783,7 @@ checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -2450,7 +2803,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", "synstructure", ] @@ -2490,7 +2843,7 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9efe770..03c7f8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,3 +35,5 @@ axum-extra = { version = "0.9", features = ["cookie"] } parking_lot = "0.12" zip = { version = "8.6", default-features = false, features = ["deflate-flate2-zlib-rs"] } libc = "0.2" +lopdf = { version = "0.45", default-features = false } +tokio-util = { version = "0.7", features = ["io"] } diff --git a/crates/archivr-cli/src/main.rs b/crates/archivr-cli/src/main.rs index fe82d5b..fc5a90f 100644 --- a/crates/archivr-cli/src/main.rs +++ b/crates/archivr-cli/src/main.rs @@ -3,6 +3,7 @@ use archivr_core::{ archive, capture::CaptureConfig, downloader::ytdlp_tools::{tools_status, update_tools, ToolCandidate}, + export::{self, ExportFormat, ExportLayout, ExportOptions}, }; use clap::{Parser, Subcommand}; use std::{env, path::Path, process}; @@ -51,7 +52,24 @@ enum Command { #[arg(long = "force-with-info-removal")] force_with_info_removal: bool, }, - + /// Export entries as a shareable HTML/Markdown bundle or PDF + Export { + /// Entry UIDs to export, in output order + #[arg(required = true)] + entries: Vec, + /// Output format + #[arg(long, value_enum, default_value_t = ExportFormatArg::Html)] + format: ExportFormatArg, + /// Export each entry as its own file instead of one combined document + #[arg(long)] + separate: bool, + /// Omit the "Preserved with archivr" credit + #[arg(long)] + no_credit: bool, + /// Directory to write the export into + #[arg(short, long, default_value = ".")] + output_dir: String, + }, /// Inspect or update the yt-dlp binary and the JavaScript runtime (Deno) archivr runs #[command(name = "yt-dlp")] YtDlp { @@ -60,6 +78,23 @@ enum Command { }, } +#[derive(clap::ValueEnum, Debug, Clone, Copy)] +enum ExportFormatArg { + Html, + Pdf, + Markdown, +} + +impl From for ExportFormat { + fn from(a: ExportFormatArg) -> Self { + match a { + ExportFormatArg::Html => ExportFormat::Html, + ExportFormatArg::Pdf => ExportFormat::Pdf, + ExportFormatArg::Markdown => ExportFormat::Markdown, + } + } +} + #[derive(Subcommand, Debug)] enum YtDlpCmd { /// Download the latest yt-dlp zipapp and Deno into archivr's state directory @@ -125,6 +160,29 @@ fn main() -> Result<()> { Ok(()) } + + Command::Export { entries, format, separate, no_credit, output_dir } => { + let archive_path = match archive::find_archive_path()? { + Some(p) => p, + None => { + eprintln!("Not in an archive. Use 'archivr init' to create one."); + process::exit(1); + } + }; + let paths = archive::read_archive_paths(&archive_path)?; + let options = ExportOptions { + format: ExportFormat::from(format), + layout: if separate { ExportLayout::Separate } else { ExportLayout::Together }, + include_credit: !no_credit, + caller_bits: u32::MAX, + }; + let dest = std::path::Path::new(&output_dir); + let export_file = export::export_entries(&paths, &entries, &options)?; + let dest_path = export_file.persist_into(dest)?; + println!("Exported: {}", dest_path.display()); + Ok(()) + } + Command::YtDlp { subcmd } => match subcmd { YtDlpCmd::Update { version } => yt_dlp_update(version.as_deref()), YtDlpCmd::Status => yt_dlp_status(), diff --git a/crates/archivr-core/Cargo.toml b/crates/archivr-core/Cargo.toml index 888189a..b84a614 100644 --- a/crates/archivr-core/Cargo.toml +++ b/crates/archivr-core/Cargo.toml @@ -16,9 +16,10 @@ uuid.workspace = true reqwest = { workspace = true } base64.workspace = true zip.workspace = true +tempfile.workspace = true +lopdf.workspace = true [target.'cfg(unix)'.dependencies] libc.workspace = true [dev-dependencies] -tempfile = "3" diff --git a/crates/archivr-core/src/export/brand.rs b/crates/archivr-core/src/export/brand.rs new file mode 100644 index 0000000..05d3fa7 --- /dev/null +++ b/crates/archivr-core/src/export/brand.rs @@ -0,0 +1,56 @@ +//! Branding constants: export stylesheet and "Preserved with archivr" credit. + +/// Stylesheet embedded in every HTML export. +/// +/// Palette comes from `docs/branding/style-guide.html`. No web fonts are +/// loaded; the stacks fall back to Georgia. +pub(crate) const EXPORT_CSS: &str = r#":root{--ink:#20251f;--paper:#f5f0e7;--line:#d2c6b5;--line-soft:#e5dccd;--accent:#8d3f30;--link:#245f72;--muted:#6b6f66;--brand-text:#f4ead8; +--display:'Cormorant Garamond','Cormorant',Georgia,serif;--serif:'Spectral',Georgia,serif;--sans:'Helvetica Neue',Helvetica,Arial,sans-serif} +*{box-sizing:border-box}html{background:var(--paper);color:var(--ink)} +body{margin:0;font:17px/1.65 var(--serif);-webkit-font-smoothing:antialiased} +.ax-doc{max-width:760px;margin:0 auto;padding:64px 28px 32px} +a{color:var(--link);text-decoration-thickness:1px;text-underline-offset:2px} +.ax-eyebrow{margin:0 0 10px;font:500 10.5px/1 var(--sans);letter-spacing:.16em;text-transform:uppercase;color:var(--muted)} +.ax-title{margin:0;font:600 38px/1.12 var(--display);letter-spacing:.005em} +h2.ax-title{font-size:30px}h3.ax-title{font-size:23px} +.ax-meta{margin:12px 0 0;font:13px/1.5 var(--sans);color:var(--muted)}.ax-meta a{color:inherit} +.ax-masthead{padding-bottom:22px;margin-bottom:28px;border-bottom:1px solid var(--line)} +.ax-entry+.ax-entry{margin-top:72px;padding-top:56px;border-top:1px solid var(--line)} +.ax-collection{margin-bottom:56px}.ax-toc{margin:20px 0 0;padding-left:1.2em;font-size:16px}.ax-toc li{margin:4px 0} +.ax-muted{color:var(--muted);font:13px var(--sans)} +.ax-media{margin:0}.ax-media img,.ax-media video{display:block;max-width:100%;height:auto;border-radius:3px;background:var(--line-soft)} +.ax-media figcaption,.ax-aside{margin:10px 0 0;font:13px var(--sans);color:var(--muted)} +.ax-frame{display:block;width:100%;height:80vh;border:1px solid var(--line);border-radius:3px;background:#fff} +.ax-text{white-space:pre-wrap;overflow-wrap:anywhere} +.ax-placeholder{padding:28px;border:1px solid var(--line);border-radius:3px;font:13px var(--sans);color:var(--muted);text-align:center} +.ax-empty{color:var(--muted);font-style:italic} +.ax-children{list-style:none;margin:0;padding:0}.ax-entry--child{margin-top:40px} +.ax-post{padding:18px 0;border-bottom:1px solid var(--line-soft)}.ax-post:last-child{border-bottom:0} +.ax-post-head{display:flex;align-items:center;gap:10px;margin-bottom:8px} +.ax-avatar{width:36px;height:36px;border-radius:50%}.ax-post-name{font:600 15px var(--sans)} +.ax-post-text{white-space:pre-wrap;overflow-wrap:anywhere} +.ax-post-media{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:6px;margin-top:12px} +.ax-post-media img,.ax-post-media video{width:100%;border-radius:3px} +.ax-quote{margin:14px 0 0;padding:4px 16px;border-left:2px solid var(--line)} +.ax-post-link{display:inline-block;margin-top:10px;font:12px var(--sans);color:var(--muted)} +.ax-article-title{font:600 26px/1.2 var(--display);margin:6px 0 12px}.ax-article-cover{max-width:100%;border-radius:3px} +.ax-colophon{max-width:760px;margin:48px auto 0;padding:22px 28px 56px;border-top:1px solid var(--line);text-align:center} +.ax-credit{display:inline-flex;align-items:center;gap:8px;font:11px var(--sans);letter-spacing:.08em;color:var(--muted);text-decoration:none} +.ax-mark{display:inline-grid;place-items:center;width:16px;height:16px;border-radius:2.5px;background:var(--accent);color:var(--brand-text);font:600 12px/1 var(--display)} +.ax-wordmark{font:600 15px var(--display);letter-spacing:.01em;color:var(--ink)} +.ax-credit:hover .ax-wordmark{color:var(--accent)} +@media print{body{font-size:11.5pt}.ax-doc{padding:0;max-width:none}.ax-entry+.ax-entry{break-before:page;border-top:0;margin-top:0;padding-top:0} +.ax-post,.ax-media,.ax-quote{break-inside:avoid}.ax-colophon{margin-top:32px}} +@page{margin:18mm 16mm}"#; + +/// The "Preserved with archivr" footer element. Included verbatim when +/// `include_credit` is set; omitted entirely otherwise (no Archivr mention). +pub(crate) const CREDIT_HTML: &str = r#""#; + +/// Inline-style credit div injected into SingleFile snapshots for PDF export. +/// The wrapper uses `all:initial` so the host page cannot restyle it. +pub(crate) const CREDIT_INLINE_HTML: &str = r#"
+ + +Preserved with archivr
"#; diff --git a/crates/archivr-core/src/export/bundle.rs b/crates/archivr-core/src/export/bundle.rs new file mode 100644 index 0000000..c819ff7 --- /dev/null +++ b/crates/archivr-core/src/export/bundle.rs @@ -0,0 +1,190 @@ +//! ZIP bundle assembly for HTML and Markdown exports. + +use std::collections::HashSet; +use std::io; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use zip::write::SimpleFileOptions; +use zip::{CompressionMethod, ZipWriter}; + +use crate::export::model::Asset; + +// Extensions that should be compressed (text-like formats). +const COMPRESSED_EXTS: &[&str] = &[ + "html", "htm", "md", "txt", "css", "svg", "vtt", "srt", "json", +]; + +/// Build a ZIP at `zip_path` containing multiple entry folders. +/// +/// `folders` is a list of `(folder_name, html_or_md_content, assets)`. +/// Each folder becomes `/index.{ext}` plus +/// `/assets/` per asset. +/// `ext` is `"html"` or `"md"`. +pub(crate) fn write_zip_multi( + zip_path: &Path, + folders: &[(String, String, Vec)], + ext: &str, +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + let mut seen_assets: HashSet = HashSet::new(); + + for (folder, content, assets) in folders { + let index_path = format!("{folder}/index.{ext}"); + zip.start_file(&index_path, text_options(ext)) + .with_context(|| format!("failed to start {index_path}"))?; + io::copy(&mut content.as_bytes(), &mut zip)?; + + for asset in assets { + let entry_path = format!("{folder}/assets/{}", asset.name); + // Deduplicate: same name in same folder is skipped. + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let opts = asset_options(&asset.name, asset.byte_size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(&asset.source) + .with_context(|| format!("failed to open asset: {}", asset.source.display()))?; + io::copy(&mut f, &mut zip)?; + } + } + + zip.finish().context("failed to finish zip")?; + Ok(()) +} + +/// Build a ZIP for a single entry. +/// +/// `(content, assets)` — `assets` may include poster files. +pub(crate) fn write_zip_single( + zip_path: &Path, + slug: &str, + content: &str, + ext: &str, + assets: &[Asset], + extra_assets: &[PathBuf], // poster paths etc. (not an Asset with source+name) +) -> Result<()> { + let folders = vec![(slug.to_string(), content.to_string(), assets.to_vec())]; + write_zip_multi_with_extra(zip_path, &folders, ext, extra_assets) +} + +/// Variant that also writes caller-supplied extra paths (e.g. poster JPEGs +/// generated in the work dir) into `/assets/`. +pub(crate) fn write_zip_multi_with_extra( + zip_path: &Path, + folders: &[(String, String, Vec)], + ext: &str, + extra_assets: &[PathBuf], +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + let mut seen_assets: HashSet = HashSet::new(); + + for (folder, content, assets) in folders { + let index_path = format!("{folder}/index.{ext}"); + zip.start_file(&index_path, text_options(ext)) + .with_context(|| format!("failed to start {index_path}"))?; + io::copy(&mut content.as_bytes(), &mut zip)?; + + for asset in assets { + let entry_path = format!("{folder}/assets/{}", asset.name); + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let opts = asset_options(&asset.name, asset.byte_size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(&asset.source) + .with_context(|| format!("failed to open asset: {}", asset.source.display()))?; + io::copy(&mut f, &mut zip)?; + } + + // Extra assets (posters, etc.) for the first folder only — or the folder + // that owns the extra assets is determined by the caller. + // Here we write them under the last folder; callers that need per-folder + // placement should call write_zip_multi instead. + for extra in extra_assets { + let name = extra + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let entry_path = format!("{folder}/assets/{name}"); + if !seen_assets.insert(entry_path.clone()) { + continue; + } + let size = extra.metadata().map(|m| m.len()).unwrap_or(0); + let opts = asset_options(&name, size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start extra {entry_path}"))?; + let mut f = std::fs::File::open(extra) + .with_context(|| format!("failed to open extra asset: {}", extra.display()))?; + io::copy(&mut f, &mut zip)?; + } + } + + zip.finish().context("failed to finish zip")?; + Ok(()) +} + +/// Build a ZIP that holds multiple PDFs: `/-.pdf`. +pub(crate) fn write_pdf_zip( + zip_path: &Path, + folder: &str, + pdfs: &[(String, PathBuf)], // (name_in_zip, source_path) +) -> Result<()> { + let file = std::fs::File::create(zip_path) + .with_context(|| format!("failed to create zip: {}", zip_path.display()))?; + let mut zip = ZipWriter::new(file); + + for (name, source) in pdfs { + let entry_path = format!("{folder}/{name}"); + let size = source.metadata().map(|m| m.len()).unwrap_or(0); + let opts = asset_options(name, size); + zip.start_file(&entry_path, opts) + .with_context(|| format!("failed to start {entry_path}"))?; + let mut f = std::fs::File::open(source) + .with_context(|| format!("failed to open pdf: {}", source.display()))?; + io::copy(&mut f, &mut zip)?; + } + + zip.finish().context("failed to finish pdf zip")?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +fn text_options(_ext: &str) -> SimpleFileOptions { + SimpleFileOptions::default().compression_method(CompressionMethod::Deflated) + // Deflated for text content + // (ext check is implicit for index.html / index.md) + .compression_level(Some(6)) +} + +fn asset_options(name: &str, byte_size: u64) -> SimpleFileOptions { + let ext = std::path::Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()) + .unwrap_or_default(); + + let method = if COMPRESSED_EXTS.contains(&ext.as_str()) { + CompressionMethod::Deflated + } else { + CompressionMethod::Stored + }; + + let mut opts = SimpleFileOptions::default().compression_method(method); + if COMPRESSED_EXTS.contains(&ext.as_str()) { + opts = opts.compression_level(Some(6)); + } + if byte_size >= 4 * 1024 * 1024 * 1024 { + opts = opts.large_file(true); + } + opts +} diff --git a/crates/archivr-core/src/export/html.rs b/crates/archivr-core/src/export/html.rs new file mode 100644 index 0000000..ef49e93 --- /dev/null +++ b/crates/archivr-core/src/export/html.rs @@ -0,0 +1,705 @@ +//! HTML rendering for entry exports. + +use std::path::PathBuf; + +use crate::export::brand; +use crate::export::model::{Asset, ExportBody, ExportEntry, Post, Span, ext_of_s}; + +// --------------------------------------------------------------------------- +// Asset reference mode +// --------------------------------------------------------------------------- + +/// How asset `src` / `href` values are built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum AssetMode { + /// `assets/` — for ZIP bundles. + Bundle, + /// `file://` — for Chrome PDF printing. + Print, +} + +pub(crate) fn asset_src(mode: AssetMode, asset: &Asset) -> String { + match mode { + AssetMode::Bundle => format!("assets/{}", asset.name), + AssetMode::Print => file_url(&asset.source), + } +} + +pub(crate) fn asset_src_path(mode: AssetMode, path: &std::path::Path) -> String { + match mode { + AssetMode::Bundle => { + // Fallback: use the file name. + path.file_name() + .map(|n| format!("assets/{}", n.to_string_lossy())) + .unwrap_or_default() + } + AssetMode::Print => file_url(path), + } +} + +/// Percent-encodes a file path into a `file://` URL. +fn file_url(path: &std::path::Path) -> String { + let s = path.to_string_lossy(); + let mut out = String::with_capacity(s.len() + 7); + out.push_str("file://"); + for byte in s.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'_' | b'-' | b'~' => { + out.push(*byte as char) + } + b => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +// --------------------------------------------------------------------------- +// Shared helpers +// --------------------------------------------------------------------------- + +/// HTML-escape `& < > " '`. +pub(crate) fn esc(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +/// Returns `Some(s)` only for `http://` and `https://` URLs. +fn safe_href(s: &str) -> Option<&str> { + if s.starts_with("http://") || s.starts_with("https://") { + Some(s) + } else { + None + } +} + +/// Format `archived_at` (RFC 3339) as `"%-d %B %Y"`. +fn fmt_date(archived_at: &str) -> String { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_rfc3339(archived_at) { + dt.format("%-d %B %Y").to_string() + } else { + archived_at.to_string() + } +} + +/// Format Unix seconds as `"%-d %B %Y"`. +fn fmt_timestamp(secs: i64) -> String { + use chrono::{DateTime, Utc}; + let dt = DateTime::::from_timestamp(secs, 0) + .unwrap_or_else(|| DateTime::::from_timestamp(0, 0).unwrap()); + dt.format("%-d %B %Y").to_string() +} + +/// `"{Source} · {Kind}"`, or just `"{Source}"` when the kind is empty/unknown. +pub(crate) fn source_label(source_kind: &str, entity_kind: &str) -> String { + let src = match source_kind { + "youtube" => "YouTube", + "youtube_music" => "YouTube Music", + "spotify" => "Spotify", + "x" | "twitter" => "X", + "instagram" => "Instagram", + "facebook" => "Facebook", + "tiktok" => "TikTok", + "reddit" => "Reddit", + "snapchat" => "Snapchat", + "web" => "Web", + "local" => "File", + "text" => "Note", + other => { + // Capitalize first letter. + let mut c = other.chars(); + return match c.next() { + None => String::new(), + Some(f) => { + let mut s = f.to_uppercase().to_string(); + s.push_str(c.as_str()); + let kind_part = kind_label(entity_kind); + if kind_part.is_empty() { + s + } else { + format!("{s} · {kind_part}") + } + } + }; + } + }; + let kind_part = kind_label(entity_kind); + if kind_part.is_empty() { + src.to_string() + } else { + format!("{src} · {kind_part}") + } +} + +fn kind_label(entity_kind: &str) -> &str { + match entity_kind { + "video" => "Video", + "playlist" => "Playlist", + "channel" => "Channel", + "music" => "Track", + "album" => "Album", + "post" | "tweet" => "Post", + "tweet_thread" => "Thread", + "story" => "Story", + "page" => "Page", + "file" => "File", + "document" | "unknown" | "" => "", + other => other, + } +} + +/// Display title: `summary.title`, else `original_url`, else `"Untitled entry"`. +pub(crate) fn entry_title(entry: &ExportEntry) -> String { + entry + .summary + .title + .as_deref() + .filter(|t| !t.is_empty()) + .map(str::to_string) + .or_else(|| entry.summary.original_url.clone()) + .unwrap_or_else(|| "Untitled entry".to_string()) +} + +/// Strip a leading `www.` from a hostname. +fn strip_www(host: &str) -> &str { + host.strip_prefix("www.").unwrap_or(host) +} + +/// Return the host of an HTTP(S) URL, or `None`. +fn url_host(url: &str) -> Option { + // Very minimal: find `://` then take up to the next `/`. + let after = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://"))?; + let host = after.split('/').next()?; + Some(strip_www(host).to_string()) +} + +/// Return the file size formatted as B / KB / MB / GB (1024-based, 1 decimal). +fn fmt_size(bytes: u64) -> String { + if bytes < 1024 { + return format!("{bytes} B"); + } + let kb = bytes as f64 / 1024.0; + if kb < 1024.0 { + return format!("{kb:.1} KB"); + } + let mb = kb / 1024.0; + if mb < 1024.0 { + return format!("{mb:.1} MB"); + } + format!("{:.1} GB", mb / 1024.0) +} + +// --------------------------------------------------------------------------- +// Document rendering +// --------------------------------------------------------------------------- + +/// Render a complete HTML document for one or more entries. +/// +/// `mode` controls whether asset `src` values use bundle-relative paths +/// (`assets/`) or absolute `file://` URLs for PDF printing. +pub(crate) fn render_document( + entries: &[ExportEntry], + mode: AssetMode, + posters: &std::collections::HashMap, + include_credit: bool, +) -> String { + let together = entries.len() > 1; + let doc_title = if together { + format!("{} archived entries", entries.len()) + } else { + entry_title(&entries[0]) + }; + + let generator_meta = if include_credit { + r#""# + } else { + "" + }; + + let mut html = format!( + r#" + + +{generator_meta} +{title} +
+"#, + title = esc(&doc_title), + css = brand::EXPORT_CSS, + generator_meta = generator_meta, + ); + + if together { + html.push_str(&render_collection_header(entries)); + } + + for (i, entry) in entries.iter().enumerate() { + html.push_str(&render_entry(entry, i, together, mode, posters)); + } + + html.push_str("
"); + if include_credit { + html.push('\n'); + html.push_str(brand::CREDIT_HTML); + html.push('\n'); + } + html.push_str("\n"); + html +} + +/// Render a PDF cover page (collection header + TOC, no anchors per entry). +pub(crate) fn render_cover( + entries: &[ExportEntry], + include_credit: bool, +) -> String { + let generator_meta = if include_credit { + r#""# + } else { + "" + }; + + let mut html = format!( + r#" + + +{generator_meta} +{n} archived entries +
+"#, + n = entries.len(), + css = brand::EXPORT_CSS, + generator_meta = generator_meta, + ); + + html.push_str(&format!( + r#"

Collection

{n} archived entries

+
    "#, + n = entries.len(), + )); + for entry in entries { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + html.push_str(&format!( + r#"
  1. {title} {label}
  2. "#, + title = esc(&title), + label = esc(&label), + )); + } + html.push_str("
\n"); + html.push_str("
"); + if include_credit { + html.push('\n'); + html.push_str(brand::CREDIT_HTML); + html.push('\n'); + } + html.push_str("\n"); + html +} + +fn render_collection_header(entries: &[ExportEntry]) -> String { + let mut s = format!( + r#"

Collection

{n} archived entries

+
    "#, + n = entries.len(), + ); + for (i, entry) in entries.iter().enumerate() { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + s.push_str(&format!( + "
  1. {title} {label}
  2. ", + title = esc(&title), + label = esc(&label), + )); + } + s.push_str("
\n"); + s +} + +fn render_entry( + entry: &ExportEntry, + index: usize, + together: bool, + mode: AssetMode, + posters: &std::collections::HashMap, +) -> String { + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let date = fmt_date(&entry.summary.archived_at); + + let id_attr = format!(r#" id="entry-{index}""#); + let heading = if together { "h2" } else { "h1" }; + + let original_url_part = match &entry.summary.original_url { + Some(url) if safe_href(url).is_some() => { + let host = url_host(url).unwrap_or_else(|| url.clone()); + format!( + r#" · {host}"#, + url = esc(url), + host = esc(&host), + ) + } + _ => String::new(), + }; + + let mut s = format!( + r#"
+

{label}

+<{heading} class="ax-title">{title} +

Archived {url_part}

+
"#, + label = esc(&label), + title = esc(&title), + dt = esc(&entry.summary.archived_at), + url_part = original_url_part, + ); + + s.push_str(&render_body(&entry.body, mode, posters, &entry.subtitles, &title, 0)); + s.push_str("
\n"); + s +} + +fn render_body( + body: &ExportBody, + mode: AssetMode, + posters: &std::collections::HashMap, + subtitles: &[Asset], + entry_title: &str, + depth: usize, +) -> String { + match body { + ExportBody::Video(asset) => render_video(asset, mode, posters, subtitles), + ExportBody::Audio(asset) => render_audio(asset, mode), + ExportBody::Image(asset) => render_image(asset, mode, entry_title), + ExportBody::Pdf(asset) => render_pdf(asset, mode, entry_title), + ExportBody::Page(asset) => render_page(asset, mode, entry_title), + ExportBody::Text { text, .. } => { + format!(r#"
{}
"#, esc(text)) + } + ExportBody::TextTooLarge(asset) => render_download_link(asset, mode), + ExportBody::File(asset) => render_download_link(asset, mode), + ExportBody::Posts(posts) => render_posts(posts, mode, posters), + ExportBody::Container(children) => render_container(children, mode, posters, depth), + ExportBody::Empty => { + r#"

No archived content is available for this entry.

"# + .to_string() + } + } +} + +fn render_video( + asset: &Asset, + mode: AssetMode, + posters: &std::collections::HashMap, + subtitles: &[Asset], +) -> String { + let src = asset_src(mode, asset); + let poster = posters.get(&asset.name); + + match mode { + AssetMode::Bundle => { + let poster_attr = poster + .map(|p| { + let pname = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + format!(r#" poster="assets/{pname}""#) + }) + .unwrap_or_default(); + let tracks: String = subtitles + .iter() + .enumerate() + .map(|(i, sub)| { + let sub_src = asset_src(mode, sub); + let label = sub.name.clone(); + let srclang_attr = label + .split('-') + .next() + .map(|l| format!(r#" srclang="{l}""#)) + .unwrap_or_default(); + let default_attr = if i == 0 { r#" default"# } else { "" }; + format!( + r#""#, + label = esc(&label), + ) + }) + .collect(); + format!( + r#"
"#, + src = esc(&src), + ) + } + AssetMode::Print => { + if let Some(poster_path) = poster { + let poster_src = asset_src_path(mode, poster_path); + let name = asset.name.clone(); + format!( + r#"
Video · {name}
"#, + poster_src = esc(&poster_src), + name = esc(&name), + ) + } else { + format!( + r#"
Video · {}
"#, + esc(&asset.name) + ) + } + } + } +} + +fn render_audio(asset: &Asset, mode: AssetMode) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!(r#""#, esc(&src)) + } + AssetMode::Print => { + format!( + r#"
Audio · {}
"#, + esc(&asset.name) + ) + } + } +} + +fn render_image(asset: &Asset, mode: AssetMode, title: &str) -> String { + let src = asset_src(mode, asset); + format!( + r#"
{alt}
"#, + src = esc(&src), + alt = esc(title), + ) +} + +fn render_pdf(asset: &Asset, mode: AssetMode, title: &str) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!( + r#" +

Open the PDF

"#, + src = esc(&src), + ) + } + AssetMode::Print => { + // Handled separately in pdf.rs: the PDF asset is merged directly. + format!(r#"

{}

"#, esc(title)) + } + } +} + +fn render_page(asset: &Asset, mode: AssetMode, title: &str) -> String { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, asset); + format!( + r#" +

Open the archived page on its own

"#, + src = esc(&src), + title = esc(title), + ) + } + AssetMode::Print => { + // Handled in pdf.rs: the snapshot gets masthead/colophon injected. + format!(r#"

{}

"#, esc(title)) + } + } +} + +fn render_download_link(asset: &Asset, mode: AssetMode) -> String { + let src = asset_src(mode, asset); + let ext = ext_of_s(&asset.name).to_uppercase(); + let size = fmt_size(asset.byte_size); + format!( + r#"

Download {ext} file · {size}

"#, + src = esc(&src), + ext = esc(&ext), + ) +} + +fn render_posts( + posts: &[Post], + mode: AssetMode, + posters: &std::collections::HashMap, +) -> String { + let mut s = String::from(r#"
"#); + for post in posts { + s.push_str(&render_post(post, mode, posters, false)); + } + s.push_str("
"); + s +} + +fn render_post( + post: &Post, + mode: AssetMode, + posters: &std::collections::HashMap, + is_quote: bool, +) -> String { + let tag = if is_quote { "blockquote" } else { "section" }; + let class = if is_quote { "ax-quote" } else { "ax-post" }; + + let date = post + .created_at_secs + .map(fmt_timestamp) + .unwrap_or_default(); + + let avatar_html = post + .avatar + .as_ref() + .map(|a| { + let src = asset_src(mode, a); + format!(r#""#, src = esc(&src)) + }) + .unwrap_or_default(); + + let handle_html = post + .handle + .as_deref() + .map(|h| format!(" @{h} · {date}", h = esc(h))) + .unwrap_or_else(|| if date.is_empty() { String::new() } else { format!(" · {date}") }); + + let mut s = format!( + r#"<{tag} class="{class}"> +
{avatar_html}{name} {handle_html}
+"#, + name = esc(&post.name), + ); + + // Body: article or text. + if let Some((title, body, cover)) = &post.article { + if let Some(title) = title { + s.push_str(&format!( + r#"

{}

"#, + esc(title) + )); + } + if let Some(cover) = cover { + let src = asset_src(mode, cover); + s.push_str(&format!( + r#""#, + esc(&src) + )); + } + for para in body.split("\n\n") { + let trimmed = para.trim(); + if !trimmed.is_empty() { + s.push_str(&format!("

{}

", esc(trimmed))); + } + } + } else if !post.spans.is_empty() { + s.push_str(r#"
"#); + for span in &post.spans { + match span { + Span::Text(t) => s.push_str(&esc(t)), + Span::Link { text, href } => { + if let Some(h) = safe_href(href) { + s.push_str(&format!( + r#"{text}"#, + h = esc(h), + text = esc(text), + )); + } else { + s.push_str(&esc(text)); + } + } + } + } + s.push_str("
"); + } + + // Photos and videos. + if !post.photos.is_empty() || !post.videos.is_empty() { + s.push_str(r#"
"#); + for photo in &post.photos { + let src = asset_src(mode, photo); + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } + for (video, is_gif) in &post.videos { + match mode { + AssetMode::Bundle => { + let src = asset_src(mode, video); + if *is_gif { + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } else { + s.push_str(&format!( + r#""#, + src = esc(&src) + )); + } + } + AssetMode::Print => { + let poster = posters.get(&video.name); + if let Some(poster_path) = poster { + let poster_src = asset_src_path(mode, poster_path); + s.push_str(&format!( + r#""#, + poster_src = esc(&poster_src) + )); + } else { + s.push_str(&format!( + r#"
Video · {}
"#, + esc(&video.name) + )); + } + } + } + } + s.push_str("
"); + } + + // Quote. + if let Some(quote) = &post.quote { + s.push_str(&render_post(quote, mode, posters, true)); + } + + // Status link. + if let Some(url) = &post.status_url { + s.push_str(&format!( + r#"View on X"#, + url = esc(url) + )); + } + + s.push_str(&format!("")); + s +} + +fn render_container( + children: &[ExportEntry], + mode: AssetMode, + posters: &std::collections::HashMap, + depth: usize, +) -> String { + let mut s = String::from(r#"
    "#); + for child in children { + let title = entry_title(child); + let date = fmt_date(&child.summary.archived_at); + let child_body = render_body(&child.body, mode, posters, &child.subtitles, &title, depth + 1); + s.push_str(&format!( + r#"
  1. +

    {title}

    +

    +
    {child_body}
    +
  2. "#, + title = esc(&title), + dt = esc(&child.summary.archived_at), + )); + } + s.push_str("
"); + s +} diff --git a/crates/archivr-core/src/export/markdown.rs b/crates/archivr-core/src/export/markdown.rs new file mode 100644 index 0000000..ea823d9 --- /dev/null +++ b/crates/archivr-core/src/export/markdown.rs @@ -0,0 +1,281 @@ +//! Markdown rendering for entry exports. + +use std::path::PathBuf; + +use crate::export::model::{Asset, ExportBody, ExportEntry, Post, Span, ext_of_s}; +use crate::export::html::{entry_title, source_label}; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +fn fmt_date(archived_at: &str) -> String { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_rfc3339(archived_at) { + dt.format("%-d %B %Y").to_string() + } else { + archived_at.to_string() + } +} + +fn fmt_timestamp(secs: i64) -> String { + use chrono::{DateTime, Utc}; + let dt = DateTime::::from_timestamp(secs, 0) + .unwrap_or_else(|| DateTime::::from_timestamp(0, 0).unwrap()); + dt.format("%-d %B %Y").to_string() +} + +/// Escape `[` and `]` in link text. +fn esc_link(s: &str) -> String { + s.replace('[', "\\[").replace(']', "\\]") +} + +/// Normalise a title for headings (no newlines). +fn normalise_title(s: &str) -> String { + s.replace('\n', " ").replace('\r', "") +} + +/// URL hostname (no www.). +fn url_host(url: &str) -> Option { + let after = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://"))?; + let host = after.split('/').next()?; + Some(host.strip_prefix("www.").unwrap_or(host).to_string()) +} + +/// Asset src: `assets/`. +fn asset_ref(asset: &Asset) -> String { + format!("assets/{}", asset.name) +} + +/// Poster src. +fn poster_ref(poster: &std::path::Path) -> String { + poster + .file_name() + .map(|n| format!("assets/{}", n.to_string_lossy())) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Render a Markdown document for one or more entries. +pub(crate) fn render_markdown( + entries: &[ExportEntry], + posters: &std::collections::HashMap, + include_credit: bool, +) -> String { + let together = entries.len() > 1; + let mut out = String::new(); + + if together { + out.push_str(&format!("# {} archived entries\n\n", entries.len())); + for (i, entry) in entries.iter().enumerate() { + let title = normalise_title(&entry_title(entry)); + out.push_str(&format!("- [{title}](#{anchor})\n", anchor = entry_anchor(i))); + } + out.push('\n'); + for (i, entry) in entries.iter().enumerate() { + out.push_str(&format!( + "\n\n", + entry_anchor(i) + )); + out.push_str(&render_entry_body(entry, 2, posters)); + } + } else { + out.push_str(&render_entry_body(&entries[0], 1, posters)); + } + + if include_credit { + out.push_str("\n\n---\n\nPreserved with [archivr](https://github.com/thegeneralist01/archivr)\n"); + } + + out +} + +fn entry_anchor(index: usize) -> String { + format!("entry-{index}") +} + +/// Render a single entry as Markdown, starting with a heading at `level`. +fn render_entry_body( + entry: &ExportEntry, + level: usize, + posters: &std::collections::HashMap, +) -> String { + let title = normalise_title(&entry_title(entry)); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let date = fmt_date(&entry.summary.archived_at); + + let heading = "#".repeat(level); + + let url_part = entry + .summary + .original_url + .as_deref() + .filter(|u| u.starts_with("http://") || u.starts_with("https://")) + .map(|url| { + let host = url_host(url).unwrap_or_else(|| url.to_string()); + format!(" · [{host}]({url})") + }) + .unwrap_or_default(); + + let mut out = format!( + "{heading} {title}\n\n*{label} · Archived {date}{url_part}*\n\n", + heading = heading, + title = esc_link(&title), + label = esc_link(&label), + url_part = url_part, + ); + + out.push_str(&render_body_md(&entry.body, level + 1, posters, &title)); + out.push('\n'); + out +} + +fn render_body_md( + body: &ExportBody, + child_level: usize, + posters: &std::collections::HashMap, + entry_title: &str, +) -> String { + match body { + ExportBody::Video(asset) => { + let video_ref = asset_ref(asset); + if let Some(poster) = posters.get(&asset.name) { + let p = poster_ref(poster); + format!("[![Video]({p})]({video_ref})\n") + } else { + format!("[Video file]({video_ref})\n") + } + } + ExportBody::Audio(asset) => format!("[Audio file]({})\n", asset_ref(asset)), + ExportBody::Image(asset) => { + format!("![{title}]({src})\n", title = esc_link(entry_title), src = asset_ref(asset)) + } + ExportBody::Pdf(asset) => format!("[PDF document]({})\n", asset_ref(asset)), + ExportBody::Page(asset) => format!("[Archived page snapshot]({})\n", asset_ref(asset)), + ExportBody::Text { text, .. } => { + // Verbatim text. + format!("{}\n", text) + } + ExportBody::TextTooLarge(asset) | ExportBody::File(asset) => { + let ext = ext_of_s(&asset.name).to_uppercase(); + format!("[Download {ext} file]({})\n", asset_ref(asset)) + } + ExportBody::Posts(posts) => render_posts_md(posts, posters), + ExportBody::Container(children) => { + render_container_md(children, child_level, posters) + } + ExportBody::Empty => "*No archived content is available for this entry.*\n".to_string(), + } +} + +fn render_posts_md( + posts: &[Post], + posters: &std::collections::HashMap, +) -> String { + let mut parts: Vec = Vec::new(); + for post in posts { + parts.push(render_post_md(post, posters)); + } + parts.join("\n\n---\n\n") +} + +fn render_post_md( + post: &Post, + posters: &std::collections::HashMap, +) -> String { + let mut out = String::new(); + + let date = post + .created_at_secs + .map(fmt_timestamp) + .unwrap_or_default(); + + let handle_part = post + .handle + .as_deref() + .map(|h| format!(" @{h}")) + .unwrap_or_default(); + let date_part = if date.is_empty() { String::new() } else { format!(" · {date}") }; + + out.push_str(&format!( + "**{name}**{handle_part}{date_part}\n\n", + name = post.name, + )); + + // Body. + if let Some((title, body, cover)) = &post.article { + if let Some(t) = title { + out.push_str(&format!("**{t}**\n\n")); + } + if let Some(c) = cover { + out.push_str(&format!("![]({})\n\n", asset_ref(c))); + } + out.push_str(body); + out.push('\n'); + } else if !post.spans.is_empty() { + for span in &post.spans { + match span { + Span::Text(t) => out.push_str(t), + Span::Link { text, href } + if href.starts_with("http://") || href.starts_with("https://") => + { + out.push_str(&format!("[{text}]({href})")); + } + Span::Link { text, .. } => out.push_str(text), + } + } + out.push('\n'); + } + + // Photos. + for photo in &post.photos { + out.push_str(&format!("\n![]({})", asset_ref(photo))); + } + + // Videos. + for (video, _) in &post.videos { + let video_ref = asset_ref(video); + if let Some(poster) = posters.get(&video.name) { + let p = poster_ref(poster); + out.push_str(&format!("\n[![Video]({p})]({video_ref})")); + } else { + out.push_str(&format!("\n[Video]({video_ref})")); + } + } + + // Quote. + if let Some(quote) = &post.quote { + let quoted = render_post_md(quote, posters); + for line in quoted.lines() { + out.push_str(&format!("\n> {line}")); + } + out.push('\n'); + } + + // Status link. + if let Some(url) = &post.status_url { + out.push_str(&format!("\n[View on X]({url})\n")); + } + + out +} + +fn render_container_md( + children: &[ExportEntry], + level: usize, + posters: &std::collections::HashMap, +) -> String { + let mut out = String::new(); + for child in children { + let title = normalise_title(&entry_title(child)); + let date = fmt_date(&child.summary.archived_at); + let heading = "#".repeat(level); + out.push_str(&format!("{heading} {title}\n\n*Archived {date}*\n\n")); + out.push_str(&render_body_md(&child.body, level + 1, posters, &title)); + out.push('\n'); + } + out +} diff --git a/crates/archivr-core/src/export/mod.rs b/crates/archivr-core/src/export/mod.rs new file mode 100644 index 0000000..0687701 --- /dev/null +++ b/crates/archivr-core/src/export/mod.rs @@ -0,0 +1,1075 @@ +//! Entry export: HTML ZIP, PDF, Markdown ZIP. +//! +//! The public entry point is [`export_entries`]. + +mod brand; +mod bundle; +mod html; +mod markdown; +mod model; +mod pdf; + +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use chrono::Utc; +use tempfile::TempDir; + +use crate::archive::{self, ArchivePaths, EntrySummary}; +use crate::database; +use crate::env_config::env_or; +use crate::process; + + +// --------------------------------------------------------------------------- +// Public API types +// --------------------------------------------------------------------------- + +/// The supported output formats. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportFormat { + Html, + Pdf, + Markdown, +} + +impl ExportFormat { + pub fn parse(s: &str) -> Option { + match s.to_lowercase().as_str() { + "html" => Some(Self::Html), + "pdf" => Some(Self::Pdf), + "markdown" => Some(Self::Markdown), + _ => None, + } + } +} + +/// Whether multiple entries are combined into one document or each gets its own file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportLayout { + Together, + Separate, +} + +impl ExportLayout { + pub fn parse(s: &str) -> Option { + match s.to_lowercase().as_str() { + "together" => Some(Self::Together), + "separate" => Some(Self::Separate), + _ => None, + } + } +} + +/// Options controlling the export. +#[derive(Debug, Clone)] +pub struct ExportOptions { + pub format: ExportFormat, + pub layout: ExportLayout, + pub include_credit: bool, + /// Visibility bits for child (container) enumeration; CLI passes `u32::MAX`. + pub caller_bits: u32, +} + +/// Maximum number of entries per export request. +pub const MAX_EXPORT_ENTRIES: usize = 100; + +/// A completed export file inside a temporary work directory. +/// +/// Call [`ExportFile::open`] to get a readable file handle or +/// [`ExportFile::persist_into`] to move the file to a permanent location. +#[derive(Debug)] +pub struct ExportFile { + /// Absolute path to the output file inside `work_dir`. + pub path: PathBuf, + /// ASCII file name suitable for `Content-Disposition`. + pub filename: String, + pub content_type: &'static str, + work_dir: TempDir, +} + +impl ExportFile { + /// Open the file, then drop the work dir (unix unlink keeps the handle + /// alive for reading). Returns `(file, len, filename, content_type)`. + pub fn open(self) -> Result<(fs::File, u64, String, &'static str)> { + let file = fs::File::open(&self.path) + .with_context(|| format!("failed to open export file: {}", self.path.display()))?; + let len = file.metadata().map(|m| m.len()).unwrap_or(0); + let filename = self.filename.clone(); + let ct = self.content_type; + drop(self.work_dir); // unlinks temp dir; the open handle survives on unix + Ok((file, len, filename, ct)) + } + + /// Move the output file to `dest_dir/`. Errors if the + /// destination already exists. + pub fn persist_into(self, dest_dir: &Path) -> Result { + let dest = dest_dir.join(&self.filename); + if dest.exists() { + bail!("{} already exists", dest.display()); + } + // Try rename first (same device); fall back to copy+remove. + if fs::rename(&self.path, &dest).is_err() { + fs::copy(&self.path, &dest) + .with_context(|| format!("failed to copy export to {}", dest.display()))?; + let _ = fs::remove_file(&self.path); + } + drop(self.work_dir); + Ok(dest) + } +} + +// --------------------------------------------------------------------------- +// Main entry point +// --------------------------------------------------------------------------- + +/// Export the given entries. +/// +/// Returns an [`ExportFile`] inside a temporary directory; call +/// `open()` or `persist_into()` to retrieve the result. +pub fn export_entries( + paths: &ArchivePaths, + entry_uids: &[String], + options: &ExportOptions, +) -> Result { + // 1. Validate + if entry_uids.is_empty() { + bail!("entries must not be empty"); + } + if entry_uids.len() > MAX_EXPORT_ENTRIES { + bail!("select at most 100 entries"); + } + + // Deduplicate UIDs while preserving first-occurrence order. + let mut seen = std::collections::HashSet::new(); + let uids: Vec = entry_uids + .iter() + .filter(|uid| seen.insert((*uid).clone())) + .cloned() + .collect(); + + // 2. Open DB and load entries. + let conn = database::open_or_initialize(&paths.archive_path)?; + let mut summaries: Vec = Vec::new(); + for uid in &uids { + let detail = archive::get_entry_detail(&conn, uid)?; + match detail { + Some(d) => summaries.push(d.summary), + None => bail!("entry not found: {uid}"), + } + } + + // 3. Remove entries whose parent is also in the set. + let uid_set: std::collections::HashSet = uids.iter().cloned().collect(); + let summaries: Vec = summaries + .into_iter() + .filter(|s| { + s.parent_entry_uid + .as_ref() + .map_or(true, |p| !uid_set.contains(p)) + }) + .collect(); + + if summaries.is_empty() { + bail!("no entries to export after filtering"); + } + + // 4. Create work directory. + let exports_temp = paths.store_path.join("temp").join("exports"); + fs::create_dir_all(&exports_temp)?; + let work_dir = tempfile::Builder::new() + .prefix("export-") + .tempdir_in(&exports_temp) + .context("failed to create export work dir")?; + let wpath = work_dir.path().to_path_buf(); + + // 5. Load all entries. + let entries: Vec = summaries + .into_iter() + .map(|s| model::load_entry(&conn, &paths.store_path, s, options.caller_bits, 0)) + .collect::>>()?; + + // 6. Generate posters when format requires them. + let posters: HashMap = if options.format != ExportFormat::Markdown { + generate_posters(&entries, &wpath) + } else { + // Still generate for markdown (poster images as video links). + generate_posters(&entries, &wpath) + }; + + // 7. Dispatch. + let (out_path, filename, content_type) = + assemble(&entries, options, &wpath, &posters, &paths.store_path)?; + + Ok(ExportFile { + path: out_path, + filename, + content_type, + work_dir, + }) +} + +// --------------------------------------------------------------------------- +// Poster generation +// --------------------------------------------------------------------------- + +fn collect_video_names(entries: &[model::ExportEntry]) -> Vec<(PathBuf, String)> { + let mut out: Vec<(PathBuf, String)> = Vec::new(); + for entry in entries { + collect_videos_from_body(&entry.body, &mut out); + } + out +} + +fn collect_videos_from_body(body: &model::ExportBody, out: &mut Vec<(PathBuf, String)>) { + match body { + model::ExportBody::Video(a) => out.push((a.source.clone(), a.name.clone())), + model::ExportBody::Container(children) => { + for child in children { + collect_videos_from_body(&child.body, out); + } + } + model::ExportBody::Posts(posts) => { + for post in posts { + collect_post_videos(post, out); + } + } + _ => {} + } +} + +fn collect_post_videos(post: &model::Post, out: &mut Vec<(PathBuf, String)>) { + for (video, _) in &post.videos { + out.push((video.source.clone(), video.name.clone())); + } + if let Some(quote) = &post.quote { + collect_post_videos(quote, out); + } +} + +/// Run ffmpeg to generate poster images for all video assets. +/// Returns a map of video name → poster path. +fn generate_posters(entries: &[model::ExportEntry], work_dir: &Path) -> HashMap { + let ffmpeg_path = PathBuf::from(env_or("ARCHIVR_FFMPEG", "ffmpeg")); + let videos = collect_video_names(entries); + if videos.is_empty() { + return HashMap::new(); + } + + let poster_dir = work_dir.join("posters"); + if let Err(e) = fs::create_dir_all(&poster_dir) { + eprintln!("warn: export: failed to create poster dir: {e:#}"); + return HashMap::new(); + } + + let mut posters: HashMap = HashMap::new(); + let mut ffmpeg_missing = false; + + for (src, name) in &videos { + if ffmpeg_missing { + break; + } + let stem = Path::new(name) + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| name.clone()); + let poster_path = poster_dir.join(format!("{stem}-poster.jpg")); + + if let Some(p) = try_poster(&ffmpeg_path, src, &poster_path, &mut ffmpeg_missing) { + posters.insert(name.clone(), p); + } + } + posters +} + +/// Attempt to generate a poster for one video. Returns `Some(path)` on success. +fn try_poster( + ffmpeg: &Path, + src: &Path, + out: &Path, + ffmpeg_missing: &mut bool, +) -> Option { + let args: Vec = vec![ + "-nostdin".into(), + "-hide_banner".into(), + "-loglevel".into(), + "error".into(), + "-ss".into(), + "1".into(), + "-i".into(), + src.into(), + "-frames:v".into(), + "1".into(), + "-vf".into(), + "scale='min(1280,iw)':-2".into(), + "-q:v".into(), + "3".into(), + "-y".into(), + out.into(), + ]; + + let run = process::run_with_timeout(ffmpeg, &args, None, Duration::from_secs(60)); + match run { + Ok(_) if out.exists() && out.metadata().map(|m| m.len()).unwrap_or(0) > 0 => { + return Some(out.to_path_buf()); + } + Err(e) if is_not_found(&e) => { + eprintln!("warn: export: ffmpeg not found; skipping posters"); + *ffmpeg_missing = true; + return None; + } + _ => {} + } + + // Retry with -ss 0. + let args_retry: Vec = vec![ + "-nostdin".into(), + "-hide_banner".into(), + "-loglevel".into(), + "error".into(), + "-ss".into(), + "0".into(), + "-i".into(), + src.into(), + "-frames:v".into(), + "1".into(), + "-vf".into(), + "scale='min(1280,iw)':-2".into(), + "-q:v".into(), + "3".into(), + "-y".into(), + out.into(), + ]; + match process::run_with_timeout(ffmpeg, &args_retry, None, Duration::from_secs(60)) { + Ok(_) if out.exists() && out.metadata().map(|m| m.len()).unwrap_or(0) > 0 => { + Some(out.to_path_buf()) + } + Err(e) => { + let src_name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + eprintln!("warn: export: poster for {src_name}: {e:#}"); + None + } + Ok(_) => None, + } +} + +fn is_not_found(err: &anyhow::Error) -> bool { + err.chain() + .any(|e| { + e.downcast_ref::() + .map_or(false, |io| io.kind() == std::io::ErrorKind::NotFound) + }) +} + +// --------------------------------------------------------------------------- +// Assembly dispatch +// --------------------------------------------------------------------------- + +/// Returns `(out_path, filename, content_type)`. +fn assemble( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + store_path: &Path, +) -> Result<(PathBuf, String, &'static str)> { + let date = Utc::now().format("%Y-%m-%d").to_string(); + let n = entries.len(); + + match options.format { + ExportFormat::Html => assemble_html(entries, options, work_dir, posters, &date, n), + ExportFormat::Markdown => { + assemble_markdown(entries, options, work_dir, posters, &date, n) + } + ExportFormat::Pdf => assemble_pdf(entries, options, work_dir, posters, store_path, &date, n), + } +} + +// --------------------------------------------------------------------------- +// HTML assembly +// --------------------------------------------------------------------------- + +fn assemble_html( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + let all_assets = collect_all_assets(entries, posters); + + if n == 1 || options.layout == ExportLayout::Together { + // Single document: one folder. + let slug = if n == 1 { + entry_slug(entries[0].summary.title.as_deref().unwrap_or("")) + } else { + format!("export-{date}") + }; + let filename = if n == 1 { + format!("{slug}.zip") + } else { + format!("export-{n}-entries-{date}.zip") + }; + let html = html::render_document(entries, html::AssetMode::Bundle, posters, options.include_credit); + let zip_path = work_dir.join(&filename); + bundle::write_zip_single(&zip_path, &slug, &html, "html", &all_assets, &[])?; + Ok((zip_path, filename, "application/zip")) + } else { + // Separate: one folder per entry. + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let folders: Vec<(String, String, Vec)> = entries + .iter() + .enumerate() + .map(|(i, entry)| { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let folder = format!("{outer}/{nn}-{slug}"); + let html = html::render_document( + std::slice::from_ref(entry), + html::AssetMode::Bundle, + posters, + options.include_credit, + ); + let assets = collect_entry_assets(entry, posters); + (folder, html, assets) + }) + .collect(); + + bundle::write_zip_multi(&zip_path, &folders, "html")?; + Ok((zip_path, filename, "application/zip")) + } +} + +// --------------------------------------------------------------------------- +// Markdown assembly +// --------------------------------------------------------------------------- + +fn assemble_markdown( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + let all_assets = collect_all_assets(entries, posters); + + if n == 1 || options.layout == ExportLayout::Together { + let slug = if n == 1 { + entry_slug(entries[0].summary.title.as_deref().unwrap_or("")) + } else { + format!("export-{date}") + }; + let filename = if n == 1 { + format!("{slug}.zip") + } else { + format!("export-{n}-entries-{date}.zip") + }; + let md = markdown::render_markdown(entries, posters, options.include_credit); + let zip_path = work_dir.join(&filename); + bundle::write_zip_single(&zip_path, &slug, &md, "md", &all_assets, &[])?; + Ok((zip_path, filename, "application/zip")) + } else { + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let folders: Vec<(String, String, Vec)> = entries + .iter() + .enumerate() + .map(|(i, entry)| { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let folder = format!("{outer}/{nn}-{slug}"); + let md = markdown::render_markdown( + std::slice::from_ref(entry), + posters, + options.include_credit, + ); + let assets = collect_entry_assets(entry, posters); + (folder, md, assets) + }) + .collect(); + + bundle::write_zip_multi(&zip_path, &folders, "md")?; + Ok((zip_path, filename, "application/zip")) + } +} + +// --------------------------------------------------------------------------- +// PDF assembly +// --------------------------------------------------------------------------- + +fn assemble_pdf( + entries: &[model::ExportEntry], + options: &ExportOptions, + work_dir: &Path, + posters: &HashMap, + _store_path: &Path, + date: &str, + n: usize, +) -> Result<(PathBuf, String, &'static str)> { + if n == 1 { + let slug = entry_slug(entries[0].summary.title.as_deref().unwrap_or("")); + let filename = format!("{slug}.pdf"); + let pdf_path = work_dir.join(&filename); + let entry_path = + pdf::entry_pdf(&entries[0], 0, options.include_credit, work_dir, posters)?; + fs::rename(&entry_path, &pdf_path) + .or_else(|_| fs::copy(&entry_path, &pdf_path).map(|_| ()))?; + return Ok((pdf_path, filename, "application/pdf")); + } + + match options.layout { + ExportLayout::Together => { + let filename = format!("export-{n}-entries-{date}.pdf"); + let out = work_dir.join(&filename); + + // Cover page. + let cover_html = html::render_cover(entries, options.include_credit); + let cover_html_path = work_dir.join("cover.html"); + fs::write(&cover_html_path, &cover_html)?; + let cover_pdf_path = work_dir.join("cover.pdf"); + let profile_dir = work_dir.join("chrome-profile"); + fs::create_dir_all(&profile_dir)?; + pdf::print_pdf(&cover_html_path, &cover_pdf_path, &profile_dir)?; + + // Per-entry PDFs (no credit: it's on the cover). + let mut pdf_paths: Vec = vec![cover_pdf_path]; + for (i, entry) in entries.iter().enumerate() { + let p = pdf::entry_pdf(entry, i, false, work_dir, posters)?; + pdf_paths.push(p); + } + + pdf::merge_pdf_files(&pdf_paths, &out)?; + Ok((out, filename, "application/pdf")) + } + ExportLayout::Separate => { + // A ZIP of individual PDFs. + let outer = format!("export-{date}"); + let filename = format!("export-{n}-entries-{date}.zip"); + let zip_path = work_dir.join(&filename); + + let mut pdf_names: Vec<(String, PathBuf)> = Vec::new(); + for (i, entry) in entries.iter().enumerate() { + let nn = format!("{:02}", i + 1); + let slug = entry_slug(entry.summary.title.as_deref().unwrap_or("")); + let pdf_path = pdf::entry_pdf(entry, i, options.include_credit, work_dir, posters)?; + let name_in_zip = format!("{nn}-{slug}.pdf"); + pdf_names.push((name_in_zip, pdf_path)); + } + + bundle::write_pdf_zip(&zip_path, &outer, &pdf_names)?; + Ok((zip_path, filename, "application/zip")) + } + } +} + +// --------------------------------------------------------------------------- +// Asset collection +// --------------------------------------------------------------------------- + +/// Collect all assets referenced across all entries (and posters) without duplicates. +fn collect_all_assets( + entries: &[model::ExportEntry], + posters: &HashMap, +) -> Vec { + let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + let mut out: Vec = Vec::new(); + for entry in entries { + for asset in collect_entry_assets(entry, posters) { + if seen.insert(asset.name.clone()) { + out.push(asset); + } + } + } + out +} + +fn collect_entry_assets( + entry: &model::ExportEntry, + posters: &HashMap, +) -> Vec { + let mut out: Vec = Vec::new(); + collect_body_assets(&entry.body, posters, &mut out); + for sub in &entry.subtitles { + out.push(sub.clone()); + } + out +} + +fn collect_body_assets( + body: &model::ExportBody, + posters: &HashMap, + out: &mut Vec, +) { + match body { + model::ExportBody::Video(a) => { + out.push(a.clone()); + if let Some(poster) = posters.get(&a.name) { + if let Ok(sz) = poster.metadata().map(|m| m.len()) { + out.push(model::Asset { + source: poster.clone(), + name: poster + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + byte_size: sz, + }); + } + } + } + model::ExportBody::Audio(a) + | model::ExportBody::Image(a) + | model::ExportBody::Pdf(a) + | model::ExportBody::Page(a) + | model::ExportBody::TextTooLarge(a) + | model::ExportBody::File(a) => out.push(a.clone()), + model::ExportBody::Text { .. } | model::ExportBody::Empty => {} + model::ExportBody::Posts(posts) => { + for post in posts { + collect_post_assets(post, posters, out); + } + } + model::ExportBody::Container(children) => { + for child in children { + collect_entry_assets_into(child, posters, out); + } + } + } +} + +fn collect_post_assets( + post: &model::Post, + posters: &HashMap, + out: &mut Vec, +) { + if let Some(a) = &post.avatar { + out.push(a.clone()); + } + if let Some((_, _, cover)) = &post.article { + if let Some(a) = cover { + out.push(a.clone()); + } + } + for photo in &post.photos { + out.push(photo.clone()); + } + for (video, _) in &post.videos { + out.push(video.clone()); + if let Some(poster) = posters.get(&video.name) { + if let Ok(sz) = poster.metadata().map(|m| m.len()) { + out.push(model::Asset { + source: poster.clone(), + name: poster + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + byte_size: sz, + }); + } + } + } + if let Some(quote) = &post.quote { + collect_post_assets(quote, posters, out); + } +} + +fn collect_entry_assets_into( + entry: &model::ExportEntry, + posters: &HashMap, + out: &mut Vec, +) { + collect_body_assets(&entry.body, posters, out); + for sub in &entry.subtitles { + out.push(sub.clone()); + } +} + +// --------------------------------------------------------------------------- +// Naming helpers +// --------------------------------------------------------------------------- + +/// Convert a title to a URL-safe slug (lowercase ASCII-alphanumeric, `-` +/// for other runs, trimmed and capped at 60 bytes). +pub fn entry_slug(title: &str) -> String { + let mut slug = String::new(); + let mut in_sep = true; // start as true to trim leading separators + for ch in title.chars() { + if ch.is_ascii_alphanumeric() { + slug.push(ch.to_ascii_lowercase()); + in_sep = false; + } else if !in_sep { + slug.push('-'); + in_sep = true; + } + } + // Trim trailing `-`. + while slug.ends_with('-') { + slug.pop(); + } + // Cap at 60 bytes. + let mut end = 60.min(slug.len()); + while end > 0 && !slug.is_char_boundary(end) { + end -= 1; + } + slug.truncate(end); + if slug.is_empty() { "entry".to_string() } else { slug } +} + +// --------------------------------------------------------------------------- +// Stale export cleanup +// --------------------------------------------------------------------------- + +/// Remove export temp dirs older than `older_than` from +/// `/temp/exports`. +pub fn prune_stale_export_dirs(store_path: &Path, older_than: Duration) { + let exports_dir = store_path.join("temp").join("exports"); + let dir = match fs::read_dir(&exports_dir) { + Ok(d) => d, + Err(_) => return, + }; + let cutoff = std::time::SystemTime::now() - older_than; + for entry in dir.flatten() { + let meta = match entry.metadata() { + Ok(m) => m, + Err(_) => continue, + }; + let mtime = match meta.modified() { + Ok(t) => t, + Err(_) => continue, + }; + if mtime < cutoff { + let path = entry.path(); + if let Err(e) = fs::remove_dir_all(&path) { + eprintln!("warn: export cleanup: {}: {e:#}", path.display()); + } + } + } +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use super::pdf::merge_documents; + use crate::archive::initialize_archive; + use crate::database; + + struct TestCtx { + _tmp: tempfile::TempDir, + paths: ArchivePaths, + user_id: i64, + run_id: i64, + si_counter: std::cell::Cell, + } + + impl TestCtx { + fn new() -> Self { + let tmp = tempfile::TempDir::new().unwrap(); + let archive_dir = tmp.path().join(".archivr"); + let store_dir = tmp.path().join("store"); + let paths = initialize_archive(&archive_dir, &store_dir, "Test", false).unwrap(); + let conn = database::open_or_initialize(&paths.archive_path).unwrap(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 10).unwrap(); + TestCtx { _tmp: tmp, paths, user_id, run_id: run.id, si_counter: std::cell::Cell::new(0) } + } + + fn conn(&self) -> rusqlite::Connection { + database::open_or_initialize(&self.paths.archive_path).unwrap() + } + + /// Create a text entry with a .txt primary_media artifact. Returns entry_uid. + fn add_text_entry(&self, title: &str, content: &str) -> String { + let conn = self.conn(); + let n = self.si_counter.get(); + self.si_counter.set(n + 1); + let si_id = database::upsert_source_identity( + &conn, "text", "document", Some(&format!("t-{n}")), None, &format!("text:{n}"), + ).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_id, + archive_run_id: self.run_id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "text".to_string(), + entity_kind: "document".to_string(), + title: Some(title.to_string()), + visibility: "public".to_string(), + representation_kind: "text".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + // Write the file on disk. + let hash = format!("{n:064x}"); + let sub1 = &hash[0..1]; + let sub2 = &hash[1..2]; + let relpath = format!("raw/{sub1}/{sub2}/{hash}.txt"); + let file_path = self.paths.store_path.join(&relpath); + std::fs::create_dir_all(file_path.parent().unwrap()).unwrap(); + std::fs::write(&file_path, content).unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath, + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + entry.entry_uid + } + + /// Create a parent + child entry pair. Returns (parent_uid, child_uid). + fn add_container_entry(&self, parent_title: &str, child_title: &str) -> (String, String) { + let conn = self.conn(); + let n = self.si_counter.get(); + self.si_counter.set(n + 2); + let si_parent = database::upsert_source_identity( + &conn, "youtube", "playlist", Some(&format!("p-{n}")), None, &format!("yt:p:{n}"), + ).unwrap(); + let parent = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_parent, + archive_run_id: self.run_id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "youtube".to_string(), + entity_kind: "playlist".to_string(), + title: Some(parent_title.to_string()), + visibility: "public".to_string(), + representation_kind: "json".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + let si_child = database::upsert_source_identity( + &conn, "youtube", "video", Some(&format!("c-{n}")), None, &format!("yt:c:{n}"), + ).unwrap(); + let child = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si_child, + archive_run_id: self.run_id, + parent_entry_id: Some(parent.id), + root_entry_id: Some(parent.id), + created_by_user_id: self.user_id, + owned_by_user_id: self.user_id, + source_kind: "youtube".to_string(), + entity_kind: "video".to_string(), + title: Some(child_title.to_string()), + visibility: "public".to_string(), + representation_kind: "video".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + (parent.entry_uid, child.entry_uid) + } + } + + fn read_zip_entry(file: std::fs::File, suffix: &str) -> String { + let mut archive = zip::ZipArchive::new(file).unwrap(); + let names: Vec = archive.file_names().map(str::to_string).collect(); + let name = names + .iter() + .find(|n| n.ends_with(suffix)) + .cloned() + .unwrap_or_else(|| panic!("no entry ending with {suffix}; names: {names:?}")); + let mut entry = archive.by_name(&name).unwrap(); + let mut content = String::new(); + std::io::Read::read_to_string(&mut entry, &mut content).unwrap(); + content + } + + #[test] + fn test_html_credit_on() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("&test", "hello world"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid.clone()], &opts).unwrap(); + let (file, _, filename, _) = export.open().unwrap(); + assert!(filename.ends_with(".zip"), "filename: {filename}"); + let html = read_zip_entry(file, "index.html"); + assert!(html.contains("<b>&test"), "title should be HTML-escaped"); + assert!(html.contains("Preserved with"), "credit present"); + assert!(html.contains("github.com/thegeneralist01/archivr")); + assert!(!html.contains("/api/"), "no /api/ paths"); + assert!(!html.contains(&uid), "uid not in output"); + } + + #[test] + fn test_html_credit_off() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("My Entry", "body"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let html = read_zip_entry(file, "index.html"); + assert!(!html.to_lowercase().contains("archivr"), "no archivr mention when credit off"); + } + + #[test] + fn test_separate_layout() { + let ctx = TestCtx::new(); + let u1 = ctx.add_text_entry("Alpha", "a"); + let u2 = ctx.add_text_entry("Beta", "b"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Separate, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[u1, u2], &opts).unwrap(); + let (file, _, filename, _) = export.open().unwrap(); + assert!(filename.ends_with(".zip")); + let archive = zip::ZipArchive::new(file).unwrap(); + let names: Vec = archive.file_names().map(str::to_string).collect(); + assert!(names.iter().any(|n| n.contains("01-") && n.ends_with("index.html")), "01 missing; {names:?}"); + assert!(names.iter().any(|n| n.contains("02-") && n.ends_with("index.html")), "02 missing; {names:?}"); + } + + #[test] + fn test_markdown_entry() { + let ctx = TestCtx::new(); + let uid = ctx.add_text_entry("My Note", "# heading\n\nbody text"); + let opts = ExportOptions { + format: ExportFormat::Markdown, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + let export = export_entries(&ctx.paths, &[uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let md = read_zip_entry(file, "index.md"); + assert!(md.starts_with("# My Note"), "heading: {md}"); + assert!(md.contains("# heading\n\nbody text"), "body verbatim"); + } + + #[test] + fn test_parent_child_dedupe() { + let ctx = TestCtx::new(); + let (parent_uid, child_uid) = ctx.add_container_entry("Parent Playlist", "Child Video"); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: false, + caller_bits: u32::MAX, + }; + // Both UIDs requested; child should be dropped since parent is also selected. + let export = export_entries(&ctx.paths, &[parent_uid, child_uid], &opts).unwrap(); + let (file, _, _, _) = export.open().unwrap(); + let html = read_zip_entry(file, "index.html"); + let count = html.matches("Child Video").count(); + assert!(count <= 1, "child title at most once; found {count}"); + } + + #[test] + fn test_validation_empty() { + let ctx = TestCtx::new(); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let err = export_entries(&ctx.paths, &[], &opts).unwrap_err(); + assert!(err.to_string().contains("must not be empty")); + } + + #[test] + fn test_validation_too_many() { + let ctx = TestCtx::new(); + let uids: Vec = (0..101).map(|i| format!("uid-{i}")).collect(); + let opts = ExportOptions { + format: ExportFormat::Html, + layout: ExportLayout::Together, + include_credit: true, + caller_bits: u32::MAX, + }; + let err = export_entries(&ctx.paths, &uids, &opts).unwrap_err(); + assert!(err.to_string().contains("100 entries")); + } + + #[test] + fn test_slug() { + assert_eq!(entry_slug("Hello World!"), "hello-world"); + assert_eq!(entry_slug(" "), "entry"); + assert_eq!(entry_slug("日本語"), "entry"); + assert_eq!(entry_slug("my-entry"), "my-entry"); + } + + #[test] + fn test_merge_pdfs_page_count() { + use lopdf::{Dictionary, Document, Object, Stream}; + let make_doc = |content: &[u8]| -> Document { + let mut doc = Document::with_version("1.4"); + let stream_id = doc.add_object(Object::Stream(Stream::new(Dictionary::new(), content.to_vec()))); + let mut page_dict = Dictionary::new(); + page_dict.set("Type", Object::Name(b"Page".to_vec())); + page_dict.set("Contents", Object::Reference(stream_id)); + page_dict.set("MediaBox", Object::Array(vec![ + Object::Integer(0), Object::Integer(0), + Object::Integer(612), Object::Integer(792), + ])); + let page_id = doc.add_object(Object::Dictionary(page_dict)); + let mut pages_dict = Dictionary::new(); + pages_dict.set("Type", Object::Name(b"Pages".to_vec())); + pages_dict.set("Kids", Object::Array(vec![Object::Reference(page_id)])); + pages_dict.set("Count", Object::Integer(1)); + let pages_id = doc.add_object(Object::Dictionary(pages_dict)); + if let Some(Object::Dictionary(pd)) = doc.objects.get_mut(&page_id) { + pd.set("Parent", Object::Reference(pages_id)); + } + let mut catalog = Dictionary::new(); + catalog.set("Type", Object::Name(b"Catalog".to_vec())); + catalog.set("Pages", Object::Reference(pages_id)); + let catalog_id = doc.add_object(Object::Dictionary(catalog)); + doc.trailer.set("Root", Object::Reference(catalog_id)); + doc + }; + + let doc1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page one) Tj ET"); + let doc2_p1 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page two) Tj ET"); + let doc2_p2 = make_doc(b"BT /F1 12 Tf 100 700 Td (Page three) Tj ET"); + + let doc2 = merge_documents(vec![doc2_p1, doc2_p2]).unwrap(); + let mut merged = merge_documents(vec![doc1, doc2]).unwrap(); + let mut bytes: Vec = Vec::new(); + merged.save_to(&mut bytes).unwrap(); + let reloaded = lopdf::Document::load_mem(&bytes).unwrap(); + assert_eq!(reloaded.get_pages().len(), 3, "merged PDF should have 3 pages"); + } +} diff --git a/crates/archivr-core/src/export/model.rs b/crates/archivr-core/src/export/model.rs new file mode 100644 index 0000000..d4ea2d6 --- /dev/null +++ b/crates/archivr-core/src/export/model.rs @@ -0,0 +1,720 @@ +//! Data model for exports: loaded entries and their bodies. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use rusqlite::Connection; + +use crate::archive::{self, EntryArtifactSummary, EntrySummary}; +use crate::summarizer::article_parts; +use crate::twitter::parse_tweet_id; + +// --------------------------------------------------------------------------- +// Public types +// --------------------------------------------------------------------------- + +/// An asset file that will be written into the export bundle. +#[derive(Debug, Clone)] +pub(crate) struct Asset { + /// Absolute on-disk path (canonical store path or a work-dir poster path). + pub source: PathBuf, + /// Bundle-relative file name (e.g. `sha256abc.mp4`, `sha256abc-poster.jpg`). + pub name: String, + pub byte_size: u64, +} + +/// A resolved span in tweet body text. +#[derive(Debug, Clone)] +pub(crate) enum Span { + Text(String), + Link { text: String, href: String }, +} + +/// A single tweet / post. +#[derive(Debug, Clone)] +pub(crate) struct Post { + pub _id: String, + pub name: String, + pub handle: Option, + pub avatar: Option, + pub created_at_secs: Option, + pub spans: Vec, + /// `Some((title, body, cover))` for X article statuses. + pub article: Option<(Option, String, Option)>, + pub photos: Vec, + /// `(asset, animated_gif)`. + pub videos: Vec<(Asset, bool)>, + pub quote: Option>, + /// `https://x.com/{handle|i}/status/{id}`. + pub status_url: Option, +} + +/// The primary content of an exported entry. +#[derive(Debug)] +pub(crate) enum ExportBody { + Video(Asset), + Audio(Asset), + Image(Asset), + Pdf(Asset), + /// An HTML/HTM snapshot (SingleFile page). + Page(Asset), + Text { _mime_markdown: bool, text: String }, + /// Text file > 5 MiB: offer a download link only. + TextTooLarge(Asset), + File(Asset), + Posts(Vec), + Container(Vec), + Empty, +} + +/// A fully loaded entry, ready for rendering. +#[derive(Debug)] +pub(crate) struct ExportEntry { + pub summary: EntrySummary, + /// Subtitle `.vtt` assets in track order. + pub subtitles: Vec, + pub body: ExportBody, +} + +// --------------------------------------------------------------------------- +// Extension helpers +// --------------------------------------------------------------------------- + +const VIDEO_EXTS: &[&str] = &["mp4", "webm", "mov", "mkv", "avi", "m4v", "ogv"]; +const AUDIO_EXTS: &[&str] = &["mp3", "ogg", "m4a", "opus", "wav", "flac", "aac"]; +const IMAGE_EXTS: &[&str] = &["jpg", "jpeg", "png", "gif", "webp", "avif", "svg", "bmp"]; +const TEXT_EXTS: &[&str] = &["md", "markdown", "txt"]; +const TEXT_MAX_BYTES: u64 = 5 * 1024 * 1024; + +/// Extract the file name component of a store-relative path like +/// `raw/A/B/sha256.mp4`. +pub(crate) fn file_name_of(relpath: &str) -> String { + Path::new(relpath) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| relpath.to_string()) +} + +/// Lowercase file extension without the dot, or `""`. +pub(crate) fn ext_of_s(path: &str) -> String { + Path::new(path) + .extension() + .and_then(|e| e.to_str()) + .map(|e| e.to_lowercase()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Loading +// --------------------------------------------------------------------------- + +/// Load a single entry and all its required data from the DB. +/// +/// `depth` limits container recursion: pass `0` for top-level entries. +/// Containers found at depth ≥ 2 become `Empty`. +pub(crate) fn load_entry( + conn: &Connection, + store_path: &Path, + summary: EntrySummary, + caller_bits: u32, + depth: usize, +) -> Result { + let detail = archive::get_entry_detail(conn, &summary.entry_uid)?; + let detail = match detail { + Some(d) => d, + None => { + return Ok(ExportEntry { + summary, + subtitles: vec![], + body: ExportBody::Empty, + }); + } + }; + + // ----- build asset map from artifacts ----- + let mut asset_map: HashMap = HashMap::new(); + let mut primary_media_artifact: Option = None; + let mut subtitle_artifacts: Vec = Vec::new(); + let mut raw_json_artifacts: Vec = Vec::new(); + + for artifact in &detail.artifacts { + match artifact.artifact_role.as_str() { + "primary_media" => { + if artifact.relpath.to_lowercase().ends_with(".json") { + raw_json_artifacts.push(artifact.clone()); + } else { + primary_media_artifact = Some(artifact.clone()); + } + if let Ok(p) = archive::resolve_artifact_path(store_path, artifact) { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } else { + eprintln!("warn: export: artifact not found: {}", artifact.relpath); + } + } + "media" | "avatar" => { + match archive::resolve_artifact_path(store_path, artifact) { + Ok(p) => { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } + Err(e) => eprintln!("warn: export: artifact not found: {e:#}"), + } + } + "raw_tweet_json" => { + raw_json_artifacts.push(artifact.clone()); + if let Ok(p) = archive::resolve_artifact_path(store_path, artifact) { + asset_map.insert( + artifact.relpath.clone(), + Asset { + byte_size: artifact.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&artifact.relpath), + }, + ); + } + } + "subtitle" => subtitle_artifacts.push(artifact.clone()), + _ => {} // favicon, font, etc. + } + } + + // ----- subtitles (VTT only) ----- + let subtitles: Vec = subtitle_artifacts + .iter() + .filter(|a| a.relpath.to_lowercase().ends_with(".vtt")) + .filter_map(|a| { + archive::resolve_artifact_path(store_path, a) + .map(|p| Asset { + byte_size: a.byte_size.unwrap_or(0) as u64, + source: p, + name: file_name_of(&a.relpath), + }) + .map_err(|e| { + eprintln!("warn: export: subtitle not found: {e:#}"); + e + }) + .ok() + }) + .collect(); + + // ----- determine body ----- + let ek = summary.entity_kind.as_str(); + let sk = summary.source_kind.as_str(); + + let body = if summary.child_count > 0 { + if depth >= 2 { + ExportBody::Empty + } else { + let children = + archive::list_child_entries(conn, &summary.entry_uid, caller_bits)?; + let loaded: Vec = children + .into_iter() + .map(|child| load_entry(conn, store_path, child, caller_bits, depth + 1)) + .collect::>>()?; + ExportBody::Container(loaded) + } + } else if ek == "tweet" + || ek == "tweet_thread" + || (sk == "x" && ek == "post") + || (sk == "twitter" && ek == "post") + { + let posts = load_posts( + &detail.source_metadata_json, + &raw_json_artifacts, + store_path, + &asset_map, + ek, + ); + if posts.is_empty() { + body_from_primary_media(primary_media_artifact.as_ref(), &asset_map) + } else { + ExportBody::Posts(posts) + } + } else { + body_from_primary_media(primary_media_artifact.as_ref(), &asset_map) + }; + + Ok(ExportEntry { + summary, + subtitles, + body, + }) +} + +fn body_from_primary_media( + artifact: Option<&EntryArtifactSummary>, + asset_map: &HashMap, +) -> ExportBody { + let artifact = match artifact { + Some(a) => a, + None => return ExportBody::Empty, + }; + let relpath = &artifact.relpath; + let asset = match asset_map.get(relpath) { + Some(a) => a.clone(), + None => return ExportBody::Empty, + }; + let ext = ext_of_s(relpath); + let ext = ext.as_str(); + if VIDEO_EXTS.contains(&ext) { + ExportBody::Video(asset) + } else if AUDIO_EXTS.contains(&ext) { + ExportBody::Audio(asset) + } else if IMAGE_EXTS.contains(&ext) { + ExportBody::Image(asset) + } else if ext == "pdf" { + ExportBody::Pdf(asset) + } else if ext == "html" || ext == "htm" { + ExportBody::Page(asset) + } else if TEXT_EXTS.contains(&ext) { + if asset.byte_size > TEXT_MAX_BYTES { + ExportBody::TextTooLarge(asset) + } else { + match std::fs::read(&asset.source) { + Ok(bytes) => { + let text = String::from_utf8_lossy(&bytes).into_owned(); + let _mime_markdown = ext == "md" || ext == "markdown"; + ExportBody::Text { _mime_markdown, text } + } + Err(e) => { + eprintln!("warn: export: failed to read text artifact: {e:#}"); + ExportBody::TextTooLarge(asset) + } + } + } + } else { + ExportBody::File(asset) + } +} + +// --------------------------------------------------------------------------- +// Tweet / thread loading +// --------------------------------------------------------------------------- + +fn load_posts( + source_metadata_json: &str, + json_artifacts: &[EntryArtifactSummary], + store_path: &Path, + asset_map: &HashMap, + entity_kind: &str, +) -> Vec { + let seed_id: Option = serde_json::from_str::(source_metadata_json) + .ok() + .and_then(|v| v.get("tweet_id").and_then(|t| t.as_str()).map(str::to_string)); + + let mut statuses: Vec = Vec::new(); + for artifact in json_artifacts { + let path = match archive::resolve_artifact_path(store_path, artifact) { + Ok(p) => p, + Err(_) => continue, + }; + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) => { + eprintln!( + "warn: export: failed to read tweet JSON {}: {e:#}", + path.display() + ); + continue; + } + }; + let json: serde_json::Value = match serde_json::from_slice(&bytes) { + Ok(v) => v, + Err(_) => continue, + }; + let tweet_obj = json.get("tweet").cloned().unwrap_or(json); + if tweet_obj.get("id").is_some() || tweet_obj.get("id_str").is_some() { + statuses.push(tweet_obj); + } + } + + if statuses.is_empty() { + return vec![]; + } + + let status_map: HashMap = statuses + .iter() + .filter_map(|s| tweet_id(s).map(|id| (id, s.clone()))) + .collect(); + + if entity_kind == "tweet" { + let status = seed_id + .as_deref() + .and_then(|sid| status_map.get(sid)) + .or_else(|| statuses.first()) + .cloned(); + match status { + Some(s) => vec![parse_post(&s, asset_map, None)], + None => vec![], + } + } else { + build_thread(&statuses, &status_map, seed_id.as_deref(), asset_map) + } +} + +fn build_thread( + statuses: &[serde_json::Value], + status_map: &HashMap, + seed_id: Option<&str>, + asset_map: &HashMap, +) -> Vec { + if statuses.is_empty() { + return vec![]; + } + + let start_id = seed_id + .and_then(|id| status_map.get(id).map(|_| id.to_string())) + .or_else(|| statuses.last().and_then(tweet_id)) + .unwrap_or_default(); + + // Walk upward to find the root. + let mut root_id = start_id; + let mut visited: HashSet = HashSet::new(); + visited.insert(root_id.clone()); + loop { + let status = match status_map.get(&root_id) { + Some(s) => s, + None => break, + }; + match in_reply_to_id(status) { + Some(pid) if status_map.contains_key(&pid) && !visited.contains(&pid) => { + visited.insert(pid.clone()); + root_id = pid; + } + _ => break, + } + } + + // Build children map. + let mut children_map: HashMap> = HashMap::new(); + for status in statuses { + let id = match tweet_id(status) { + Some(id) => id, + None => continue, + }; + if let Some(parent) = in_reply_to_id(status) { + if status_map.contains_key(&parent) { + children_map.entry(parent).or_default().push(id); + } + } + } + + // Sort siblings by created_at then by id. + for children in children_map.values_mut() { + children.sort_by(|a, b| { + let ca = status_map + .get(a) + .and_then(|s| created_at_secs(s)) + .unwrap_or(0); + let cb = status_map + .get(b) + .and_then(|s| created_at_secs(s)) + .unwrap_or(0); + ca.cmp(&cb).then(a.cmp(b)) + }); + } + + let mut result = Vec::new(); + let mut conversation_ids: HashSet = HashSet::new(); + dfs( + &root_id, + status_map, + &children_map, + asset_map, + &mut result, + &mut conversation_ids, + ); + result +} + +fn dfs( + id: &str, + status_map: &HashMap, + children_map: &HashMap>, + asset_map: &HashMap, + out: &mut Vec, + conversation_ids: &mut HashSet, +) { + let status = match status_map.get(id) { + Some(s) => s, + None => return, + }; + conversation_ids.insert(id.to_string()); + let post = parse_post(status, asset_map, Some(conversation_ids)); + out.push(post); + if let Some(children) = children_map.get(id) { + for child_id in children.clone() { + dfs(&child_id, status_map, children_map, asset_map, out, conversation_ids); + } + } +} + +// --------------------------------------------------------------------------- +// Tweet parsing helpers +// --------------------------------------------------------------------------- + +fn tweet_id(status: &serde_json::Value) -> Option { + let id = status + .get("id_str") + .and_then(|v| v.as_str()) + .map(str::to_string) + .or_else(|| { + status.get("id").and_then(|v| { + if let Some(s) = v.as_str() { + Some(s.to_string()) + } else { + v.as_u64().map(|n| n.to_string()) + } + }) + })?; + if id.is_empty() { None } else { Some(id) } +} + +fn in_reply_to_id(status: &serde_json::Value) -> Option { + status + .get("in_reply_to_status_id_str") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty() && *s != "null") + .map(str::to_string) + .or_else(|| { + status + .get("in_reply_to_status_id") + .and_then(|v| v.as_u64()) + .map(|n| n.to_string()) + }) +} + +fn created_at_secs(status: &serde_json::Value) -> Option { + if let Some(n) = status.get("created_at_secs").and_then(|v| v.as_i64()) { + return Some(n); + } + if let Some(s) = status.get("created_at").and_then(|v| v.as_str()) { + use chrono::DateTime; + if let Ok(dt) = DateTime::parse_from_str(s, "%a %b %d %T %z %Y") { + return Some(dt.timestamp()); + } + if let Ok(dt) = DateTime::parse_from_rfc3339(s) { + return Some(dt.timestamp()); + } + } + None +} + +fn parse_post( + status: &serde_json::Value, + asset_map: &HashMap, + conversation_ids: Option<&HashSet>, +) -> Post { + let id = tweet_id(status).unwrap_or_default(); + + let author = status.get("author").or_else(|| status.get("user")); + let name = author + .and_then(|a| a.get("name").and_then(|v| v.as_str())) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .or_else(|| { + author + .and_then(|a| a.get("screen_name").and_then(|v| v.as_str())) + .map(str::to_string) + }) + .unwrap_or_else(|| "Unknown".to_string()); + let handle = author + .and_then(|a| a.get("screen_name").and_then(|v| v.as_str())) + .filter(|s| !s.is_empty()) + .map(str::to_string); + + let avatar_local = author + .and_then(|a| a.get("avatar_local_path").and_then(|v| v.as_str())) + .map(str::to_string); + let avatar = avatar_local.as_deref().and_then(|lp| asset_map.get(lp)).cloned(); + + let created_at_secs = created_at_secs(status); + + // Article. + let article = article_parts(status).map(|(title, body)| { + let cover_local = status + .pointer("/article/cover_media/local_path") + .and_then(|v| v.as_str()) + .map(str::to_string); + let cover = cover_local.as_deref().and_then(|lp| asset_map.get(lp)).cloned(); + (title, body, cover) + }); + + // Spans (only when no article). + let raw_spans = if article.is_some() { + vec![] + } else { + build_spans(status) + }; + + // Media. + let media_list = status + .get("extended_entities") + .or_else(|| status.get("entities")) + .and_then(|e| e.get("media")) + .and_then(|m| m.as_array()) + .cloned() + .unwrap_or_default(); + + let media_url_set: HashSet = media_list + .iter() + .filter_map(|m| m.get("url").and_then(|u| u.as_str())) + .map(str::to_string) + .collect(); + let spans = filter_spans(raw_spans, &media_url_set); + + let mut photos: Vec = Vec::new(); + let mut videos: Vec<(Asset, bool)> = Vec::new(); + for m in &media_list { + let local_path = m + .get("local_path") + .and_then(|v| v.as_str()) + .map(str::to_string); + let asset = match local_path.as_deref().and_then(|lp| asset_map.get(lp)).cloned() { + Some(a) => a, + None => continue, + }; + match m.get("type").and_then(|v| v.as_str()).unwrap_or("") { + "photo" => photos.push(asset), + "video" => videos.push((asset, false)), + "animated_gif" => videos.push((asset, true)), + _ => {} + } + } + + // Quote. + let quoted_id = status + .get("quoted_status_id_str") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let quote = quoted_id.as_deref().and_then(|qid| { + if conversation_ids.map_or(false, |c| c.contains(qid)) { + return None; + } + status + .get("quoted_status") + .map(|qs| Box::new(parse_post(qs, asset_map, None))) + }); + + // Status URL. + let status_url = parse_tweet_id(&id).map(|tid| { + handle + .as_deref() + .map(|h| format!("https://x.com/{h}/status/{tid}")) + .unwrap_or_else(|| format!("https://x.com/i/status/{tid}")) + }); + + Post { + _id: id, + name, + handle, + avatar, + created_at_secs, + spans, + article, + photos, + videos, + quote, + status_url, + } +} + +fn build_spans(status: &serde_json::Value) -> Vec { + let text = status + .get("full_text") + .or_else(|| status.get("text")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + + let url_entities = status + .pointer("/entities/urls") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + + let mut text = decode_html_entities(text); + + let mut replacements: Vec<(String, String, String)> = url_entities + .iter() + .filter_map(|e| { + let short = e.get("url").and_then(|v| v.as_str())?; + let display = e + .get("display_url") + .and_then(|v| v.as_str()) + .unwrap_or(short); + let expanded = e + .get("expanded_url") + .and_then(|v| v.as_str()) + .unwrap_or(short); + if short.is_empty() { + None + } else { + Some((short.to_string(), display.to_string(), expanded.to_string())) + } + }) + .collect(); + + if replacements.is_empty() { + let trimmed = text.trim().to_string(); + return if trimmed.is_empty() { vec![] } else { vec![Span::Text(trimmed)] }; + } + + let mut spans: Vec = Vec::new(); + loop { + let earliest = replacements + .iter() + .enumerate() + .filter_map(|(i, (short, _, _))| text.find(short.as_str()).map(|pos| (pos, i, short.len()))) + .min_by_key(|(pos, _, _)| *pos); + match earliest { + None => break, + Some((pos, idx, len)) => { + let (_, display_url, expanded_url) = replacements[idx].clone(); + if pos > 0 { + spans.push(Span::Text(text[..pos].to_string())); + } + spans.push(Span::Link { text: display_url, href: expanded_url }); + text = text[pos + len..].to_string(); + replacements.remove(idx); + } + } + } + let remainder = text.trim().to_string(); + if !remainder.is_empty() { + spans.push(Span::Text(remainder)); + } + spans +} + +fn filter_spans(spans: Vec, strip_set: &HashSet) -> Vec { + spans + .into_iter() + .filter(|span| match span { + Span::Link { href, .. } => !strip_set.contains(href), + Span::Text(t) => !strip_set.contains(t.as_str()), + }) + .collect() +} + +fn decode_html_entities(s: &str) -> String { + s.replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") +} diff --git a/crates/archivr-core/src/export/pdf.rs b/crates/archivr-core/src/export/pdf.rs new file mode 100644 index 0000000..39364c7 --- /dev/null +++ b/crates/archivr-core/src/export/pdf.rs @@ -0,0 +1,395 @@ +//! PDF generation via headless Chrome and lopdf merging. + +use std::collections::HashMap; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use lopdf::{Dictionary, Document, Object, ObjectId, Stream}; + +use crate::env_config::{env_or, env_timeout}; +use crate::export::brand; +use crate::export::html::{AssetMode, entry_title, render_document, source_label}; +use crate::export::model::{Asset, ExportBody, ExportEntry}; +use crate::process; + +// --------------------------------------------------------------------------- +// Chrome PDF printing +// --------------------------------------------------------------------------- + +/// Print an HTML file to PDF using headless Chrome. +pub(crate) fn print_pdf(html_path: &Path, out: &Path, profile_dir: &Path) -> Result<()> { + let chrome = env_or("ARCHIVR_CHROME", "chromium"); + let chrome_path = PathBuf::from(&chrome); + + let timeout_secs = env_timeout("ARCHIVR_EXPORT_PDF_TIMEOUT", 120); + + let extra_args: Vec = std::env::var("ARCHIVR_CHROME_ARGS") + .unwrap_or_default() + .split_whitespace() + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + + let html_url = percent_encode_path(html_path); + + let mut args: Vec = vec![ + "--headless=new".into(), + "--disable-gpu".into(), + "--no-first-run".into(), + "--no-default-browser-check".into(), + "--hide-scrollbars".into(), + format!("--user-data-dir={}", profile_dir.display()).into(), + "--no-pdf-header-footer".into(), + "--run-all-compositor-stages-before-draw".into(), + "--virtual-time-budget=15000".into(), + format!("--print-to-pdf={}", out.display()).into(), + ]; + for a in &extra_args { + args.push(a.into()); + } + args.push(html_url.into()); + + process::run_with_timeout(&chrome_path, &args, None, Duration::from_secs(timeout_secs)) + .with_context(|| "PDF export needs Chromium: set ARCHIVR_CHROME")?; + + if !out.exists() || out.metadata().map(|m| m.len()).unwrap_or(0) == 0 { + bail!( + "Chromium produced no PDF (set ARCHIVR_CHROME to a Chromium/Chrome binary); \ + tried: {chrome}" + ); + } + Ok(()) +} + +fn percent_encode_path(path: &Path) -> String { + let s = path.to_string_lossy(); + let mut out = String::with_capacity(s.len() + 7); + out.push_str("file://"); + for byte in s.as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b'.' | b'_' | b'-' | b'~' => { + out.push(*byte as char) + } + b => out.push_str(&format!("%{b:02X}")), + } + } + out +} + +// --------------------------------------------------------------------------- +// lopdf merging +// --------------------------------------------------------------------------- + +/// Merge PDF files on disk into a single output PDF. +pub(crate) fn merge_pdf_files(inputs: &[PathBuf], output: &Path) -> Result<()> { + if inputs.is_empty() { + bail!("merge_pdf_files: no inputs"); + } + if inputs.len() == 1 { + std::fs::copy(&inputs[0], output) + .with_context(|| format!("failed to copy PDF to {}", output.display()))?; + return Ok(()); + } + + let docs: Vec = inputs + .iter() + .map(|p| Document::load(p).with_context(|| format!("failed to load PDF: {}", p.display()))) + .collect::>>()?; + + let mut merged = merge_documents(docs)?; + merged + .save(output) + .with_context(|| format!("failed to save merged PDF to {}", output.display()))?; + Ok(()) +} + +/// Merge multiple `Document` values into one, appending pages in order. +/// +/// Follows the lopdf `examples/merge.rs` pattern: each source document's +/// object IDs are shifted by an offset so they do not collide, then all +/// objects are copied into a fresh document with a new Pages tree and Catalog. +pub(crate) fn merge_documents(docs: Vec) -> Result { + if docs.is_empty() { + bail!("merge_documents: no documents provided"); + } + if docs.len() == 1 { + return Ok(docs.into_iter().next().unwrap()); + } + + let mut merged = Document::with_version("1.5"); + let mut all_page_ids: Vec = Vec::new(); + // next_id tracks the next free object number so we can assign the Pages + // and Catalog objects after all source objects have been copied in. + let mut next_id: u32 = 0; + + for doc in docs { + let offset = next_id; + + // Collect pages in page-number order before we consume the doc. + let pages = doc.get_pages(); // BTreeMap + for (_page_num, page_oid) in &pages { + all_page_ids.push((page_oid.0 + offset, page_oid.1)); + } + + let doc_max = doc.objects.keys().map(|(n, _)| *n).max().unwrap_or(0); + + for (oid, obj) in &doc.objects { + let new_oid: ObjectId = (oid.0 + offset, oid.1); + let remapped = remap_refs(obj, offset); + merged.objects.insert(new_oid, remapped); + } + + next_id += doc_max + 1; + } + + // Build the Pages dictionary. + let pages_oid: ObjectId = (next_id, 0); + next_id += 1; + + // Point every collected page at the new Pages parent. + for page_id in &all_page_ids { + if let Some(Object::Dictionary(dict)) = merged.objects.get_mut(page_id) { + dict.set("Parent", Object::Reference(pages_oid)); + } + } + + let mut pages_dict = Dictionary::new(); + pages_dict.set("Type", Object::Name(b"Pages".to_vec())); + pages_dict.set( + "Kids", + Object::Array(all_page_ids.iter().map(|id| Object::Reference(*id)).collect()), + ); + pages_dict.set("Count", Object::Integer(all_page_ids.len() as i64)); + merged.objects.insert(pages_oid, Object::Dictionary(pages_dict)); + + // Build the Catalog. + let catalog_oid: ObjectId = (next_id, 0); + let mut catalog = Dictionary::new(); + catalog.set("Type", Object::Name(b"Catalog".to_vec())); + catalog.set("Pages", Object::Reference(pages_oid)); + merged.objects.insert(catalog_oid, Object::Dictionary(catalog)); + + merged.trailer.set("Root", Object::Reference(catalog_oid)); + merged.trailer.set("Size", Object::Integer((next_id + 1) as i64)); + merged.max_id = next_id; + + Ok(merged) +} + +/// Recursively remap all `Reference` object IDs by adding `offset` to the +/// object number component. +fn remap_refs(obj: &Object, offset: u32) -> Object { + match obj { + Object::Reference(id) => Object::Reference((id.0 + offset, id.1)), + Object::Array(arr) => Object::Array(arr.iter().map(|o| remap_refs(o, offset)).collect()), + Object::Dictionary(dict) => { + let mut new_dict = Dictionary::new(); + for (k, v) in dict.iter() { + new_dict.set(k.clone(), remap_refs(v, offset)); + } + Object::Dictionary(new_dict) + } + Object::Stream(stream) => { + let mut new_dict = Dictionary::new(); + for (k, v) in stream.dict.iter() { + new_dict.set(k.clone(), remap_refs(v, offset)); + } + Object::Stream(Stream::new(new_dict, stream.content.clone())) + } + other => other.clone(), + } +} + +// --------------------------------------------------------------------------- +// Per-entry PDF generation +// --------------------------------------------------------------------------- + +/// Generate a PDF for a single entry. Returns the path inside `work_dir`. +pub(crate) fn entry_pdf( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + posters: &HashMap, +) -> Result { + let profile_dir = work_dir.join("chrome-profile"); + std::fs::create_dir_all(&profile_dir)?; + + match &entry.body { + ExportBody::Page(asset) => { + entry_pdf_from_page(entry, index, with_credit, work_dir, &profile_dir, asset) + } + ExportBody::Pdf(asset) => { + entry_pdf_from_existing_pdf(entry, index, with_credit, work_dir, &profile_dir, asset) + } + _ => entry_pdf_from_html(entry, index, with_credit, work_dir, &profile_dir, posters), + } +} + +fn entry_pdf_from_html( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + posters: &HashMap, +) -> Result { + let html = render_document(std::slice::from_ref(entry), AssetMode::Print, posters, with_credit); + let html_path = work_dir.join(format!("print-{index}.html")); + std::fs::write(&html_path, &html) + .with_context(|| format!("failed to write print HTML: {}", html_path.display()))?; + let out = work_dir.join(format!("entry-{index}.pdf")); + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) +} + +fn entry_pdf_from_page( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + asset: &Asset, +) -> Result { + let snapshot_bytes = std::fs::read(&asset.source) + .with_context(|| format!("failed to read snapshot: {}", asset.source.display()))?; + let snapshot = String::from_utf8_lossy(&snapshot_bytes); + + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let masthead = build_masthead_div(&title, &label, &entry.summary.archived_at); + + let injected = inject_after_body_open(&snapshot, &masthead); + let injected = if with_credit { + inject_before_body_close(&injected, brand::CREDIT_INLINE_HTML) + } else { + injected + }; + + let html_path = work_dir.join(format!("print-page-{index}.html")); + std::fs::write(&html_path, injected.as_bytes()) + .with_context(|| format!("failed to write page HTML: {}", html_path.display()))?; + let out = work_dir.join(format!("entry-{index}.pdf")); + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) +} + +fn entry_pdf_from_existing_pdf( + entry: &ExportEntry, + index: usize, + with_credit: bool, + work_dir: &Path, + profile_dir: &Path, + asset: &Asset, +) -> Result { + // Print the masthead as its own page. + let title = entry_title(entry); + let label = source_label(&entry.summary.source_kind, &entry.summary.entity_kind); + let mhtml = build_masthead_page(&title, &label, &entry.summary.archived_at, with_credit); + let mhtml_path = work_dir.join(format!("masthead-{index}.html")); + std::fs::write(&mhtml_path, mhtml.as_bytes()).context("failed to write masthead HTML")?; + let mast_pdf_path = work_dir.join(format!("masthead-{index}.pdf")); + print_pdf(&mhtml_path, &mast_pdf_path, profile_dir)?; + + let out = work_dir.join(format!("entry-{index}.pdf")); + + match Document::load(&asset.source) { + Ok(orig_doc) => { + let mast_doc = Document::load(&mast_pdf_path).context("failed to reload masthead PDF")?; + let mut merged = merge_documents(vec![mast_doc, orig_doc])?; + merged.save(&out).context("failed to save merged PDF")?; + Ok(out) + } + Err(e) => { + eprintln!("warn: export: failed to load PDF artifact: {e:#}"); + // Fallback: render a plain HTML page for this entry. + let html = render_document( + std::slice::from_ref(entry), + AssetMode::Print, + &HashMap::new(), + with_credit, + ); + let html_path = work_dir.join(format!("print-{index}.html")); + std::fs::write(&html_path, &html)?; + print_pdf(&html_path, &out, profile_dir)?; + Ok(out) + } + } +} + +// --------------------------------------------------------------------------- +// Masthead injection helpers +// --------------------------------------------------------------------------- + +fn build_masthead_div(title: &str, label: &str, archived_at: &str) -> String { + use chrono::DateTime; + let date = DateTime::parse_from_rfc3339(archived_at) + .map(|dt| dt.format("%-d %B %Y").to_string()) + .unwrap_or_else(|_| archived_at.to_string()); + + format!( + r#"
+

{label}

+

{title}

+

Archived {date}

+
"#, + label = html_esc(label), + title = html_esc(title), + date = html_esc(&date), + ) +} + +fn build_masthead_page(title: &str, label: &str, archived_at: &str, with_credit: bool) -> String { + let masthead = build_masthead_div(title, label, archived_at); + let credit = if with_credit { brand::CREDIT_HTML } else { "" }; + format!( + r#" +
{masthead}
{credit}"#, + ) +} + +fn inject_after_body_open(html: &str, to_inject: &str) -> String { + let lower = html.to_lowercase(); + if let Some(body_start) = lower.find("') { + let insert_at = body_start + rel_end + 1; + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(&html[..insert_at]); + out.push('\n'); + out.push_str(to_inject); + out.push_str(&html[insert_at..]); + return out; + } + } + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(to_inject); + out.push('\n'); + out.push_str(html); + out +} + +fn inject_before_body_close(html: &str, to_inject: &str) -> String { + let lower = html.to_lowercase(); + if let Some(close_pos) = lower.rfind("") { + let mut out = String::with_capacity(html.len() + to_inject.len() + 1); + out.push_str(&html[..close_pos]); + out.push('\n'); + out.push_str(to_inject); + out.push_str(&html[close_pos..]); + return out; + } + let mut out = html.to_string(); + out.push('\n'); + out.push_str(to_inject); + out +} + +fn html_esc(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} diff --git a/crates/archivr-core/src/lib.rs b/crates/archivr-core/src/lib.rs index 55d70c1..340b87c 100644 --- a/crates/archivr-core/src/lib.rs +++ b/crates/archivr-core/src/lib.rs @@ -14,3 +14,4 @@ pub mod text_title; pub mod transcriber; pub(crate) mod env_config; pub(crate) mod process; +pub mod export; diff --git a/crates/archivr-core/src/summarizer.rs b/crates/archivr-core/src/summarizer.rs index 3b9db28..1dc1bd8 100644 --- a/crates/archivr-core/src/summarizer.rs +++ b/crates/archivr-core/src/summarizer.rs @@ -838,7 +838,11 @@ fn flatten_article_blocks(v: &serde_json::Value, out: &mut Vec) { } } -fn article_text(status: &serde_json::Value) -> Option { +/// Extract the article title and body from a tweet status object. +/// +/// Returns `Some((title, body))` when the status has an `article` object with +/// usable body text; `None` otherwise. +pub(crate) fn article_parts(status: &serde_json::Value) -> Option<(Option, String)> { let article = status.get("article")?; article.as_object()?; let title = nonempty_string(article, "title"); @@ -852,9 +856,12 @@ fn article_text(status: &serde_json::Value) -> Option { }) .or_else(|| nonempty_string(article, "preview_text")) .or_else(|| nonempty_string(article, "summary_text"))?; + Some((title, body)) +} - Some(match title.as_deref() { - Some(title) => format!("{title}\n\n{body}"), +fn article_text(status: &serde_json::Value) -> Option { + article_parts(status).map(|(title, body)| match title.as_deref() { + Some(t) => format!("{t}\n\n{body}"), None => body, }) } diff --git a/crates/archivr-server/Cargo.toml b/crates/archivr-server/Cargo.toml index 6371f8a..ac32531 100644 --- a/crates/archivr-server/Cargo.toml +++ b/crates/archivr-server/Cargo.toml @@ -24,6 +24,9 @@ regex.workspace = true reqwest.workspace = true uuid.workspace = true +tokio-util.workspace = true +zip.workspace = true + [dev-dependencies] tempfile.workspace = true tower.workspace = true diff --git a/crates/archivr-server/src/effective_config.rs b/crates/archivr-server/src/effective_config.rs index de10c8e..57f61f0 100644 --- a/crates/archivr-server/src/effective_config.rs +++ b/crates/archivr-server/src/effective_config.rs @@ -69,8 +69,9 @@ pub(crate) static ENV_VARS: &[EnvSpec] = &[ spec("ARCHIVR_DENO", "tools", None, "Pinned Deno binary offered to the JS runtime resolver."), spec("ARCHIVR_JS_RUNTIME", "tools", None, "Forced JS runtime for yt-dlp as RUNTIME[:ABS_PATH] (deno, node, bun, quickjs)."), spec("ARCHIVR_SINGLE_FILE", "tools", Some("single-file"), "single-file-cli binary for web page archiving."), - spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable passed to single-file."), + spec("ARCHIVR_CHROME", "tools", Some("chromium"), "Chromium executable used by single-file and PDF export."), spec("ARCHIVR_CHROME_ARGS", "tools", None, "Extra space-separated Chromium flags."), + spec("ARCHIVR_EXPORT_PDF_TIMEOUT", "tools", Some("120"), "Seconds allowed for each Chromium PDF render during entry export."), spec("ARCHIVR_UBLOCK", "tools", Some("true"), "Default for the uBlock extension toggle when no instance setting overrides it (false or 0 disables)."), spec("ARCHIVR_UBLOCK_EXT", "tools", None, "Directory of the unpacked uBlock extension."), spec("ARCHIVR_COOKIE_CONSENT", "tools", Some("true"), "Default for the cookie-consent extension toggle when no instance setting overrides it (false or 0 disables)."), diff --git a/crates/archivr-server/src/exports.rs b/crates/archivr-server/src/exports.rs new file mode 100644 index 0000000..07b5c1c --- /dev/null +++ b/crates/archivr-server/src/exports.rs @@ -0,0 +1,247 @@ +//! `GET /api/archives/:archive_id/export` — generate and stream an entry export. + +use axum::{ + Router, + body::Body, + extract::{Path, Query, State}, + http::{HeaderValue, header}, + response::{IntoResponse, Response}, + routing::get, +}; +use tokio_util::io::ReaderStream; + +use archivr_core::{archive, database, export}; + +use crate::routes::{ApiError, AppState, AuthUser, auth_to_caller_bits, ensure_entry_visible, mounted_archive}; + +pub fn routes() -> Router { + Router::new().route( + "/api/archives/:archive_id/export", + get(export_handler), + ) +} + +#[derive(Debug, serde::Deserialize)] +struct ExportQuery { + entries: String, + format: String, + layout: Option, + credit: Option, +} + +async fn export_handler( + State(state): State, + auth_user: AuthUser, + Path(archive_id): Path, + Query(q): Query, +) -> Result { + // 1. Require authentication. + if matches!(auth_user, AuthUser::Guest) { + return Err(ApiError::unauthorized("login required")); + } + + // 2. Parse format, layout, and credit. + let format = export::ExportFormat::parse(&q.format) + .ok_or_else(|| ApiError::bad_request("format must be html, pdf, or markdown"))?; + + let layout = match q.layout.as_deref().unwrap_or("together") { + "together" => export::ExportLayout::Together, + "separate" => export::ExportLayout::Separate, + _ => return Err(ApiError::bad_request("layout must be together or separate")), + }; + + let include_credit = q.credit.unwrap_or(true); + + // 3. Parse and validate entry UIDs. + let uids: Vec = q + .entries + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + + if uids.is_empty() { + return Err(ApiError::bad_request("entries must not be empty")); + } + if uids.len() > export::MAX_EXPORT_ENTRIES { + return Err(ApiError::bad_request("select at most 100 entries")); + } + + // 4. Resolve archive and verify entry visibility. + let mounted = mounted_archive(&state, &archive_id)?; + let conn = database::open_or_initialize(&mounted.archive_path)?; + for uid in &uids { + ensure_entry_visible(&conn, &auth_user, uid)?; + database::entry_id_for_uid(&conn, uid)? + .ok_or_else(|| ApiError::not_found("entry not found"))?; + } + drop(conn); // don't hold a connection across the blocking task + + let paths = archive::read_archive_paths(&mounted.archive_path)?; + let caller_bits = auth_to_caller_bits(&auth_user); + let options = export::ExportOptions { + format, + layout, + include_credit, + caller_bits, + }; + + // 5. Run the (synchronous) export in a blocking thread. + let export_file = tokio::task::spawn_blocking(move || { + export::export_entries(&paths, &uids, &options) + }) + .await + .map_err(|e| { + eprintln!("warn: export: task panicked: {e:#}"); + ApiError::internal("export task failed") + })? + .map_err(|e| { + eprintln!("warn: export: {e:#}"); + ApiError::internal(&format!("{e:#}")) + })?; + + // 6. Stream the file. + let (std_file, len, filename, content_type) = export_file.open().map_err(|e| { + eprintln!("warn: export: failed to open result: {e:#}"); + ApiError::internal("failed to open export file") + })?; + let async_file = tokio::fs::File::from_std(std_file); + let stream = ReaderStream::new(async_file); + let body = Body::from_stream(stream); + + let disposition = format!("attachment; filename=\"{filename}\""); + let response = Response::builder() + .header(header::CONTENT_TYPE, content_type) + .header(header::CONTENT_LENGTH, len) + .header(header::CACHE_CONTROL, "no-store") + .header( + header::CONTENT_DISPOSITION, + HeaderValue::from_str(&disposition) + .unwrap_or_else(|_| HeaderValue::from_static("attachment")), + ) + .body(body) + .map_err(|_| ApiError::internal("failed to build response"))?; + + Ok(response) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use archivr_core::{archive, database}; + use axum::http::StatusCode; + + use crate::test_support::{fixture, make_test_session, send}; + + /// Insert a minimal text entry and return its `entry_uid`. + fn seed_entry(archive_path: &std::path::Path) -> String { + let paths = archive::read_archive_paths(archive_path).unwrap(); + let conn = database::open_or_initialize(archive_path).unwrap(); + let user_id = database::ensure_default_user(&conn).unwrap(); + let run = database::create_archive_run(&conn, user_id, 1).unwrap(); + let si = database::upsert_source_identity( + &conn, "text", "document", Some("te1"), None, "text:e:1", + ).unwrap(); + let entry = database::create_archived_entry( + &conn, + &database::NewEntry { + source_identity_id: si, + archive_run_id: run.id, + parent_entry_id: None, + root_entry_id: None, + created_by_user_id: user_id, + owned_by_user_id: user_id, + source_kind: "text".to_string(), + entity_kind: "document".to_string(), + title: Some("Export Test".to_string()), + visibility: "public".to_string(), + representation_kind: "text".to_string(), + source_metadata_json: "{}".to_string(), + display_metadata_json: None, + }, + ).unwrap(); + let relpath = "raw/e/1/export_test.txt".to_string(); + let fpath = paths.store_path.join(&relpath); + std::fs::create_dir_all(fpath.parent().unwrap()).unwrap(); + std::fs::write(&fpath, b"hello export").unwrap(); + database::add_entry_artifact( + &conn, + &database::NewArtifact { + entry_id: entry.id, + artifact_role: "primary_media".to_string(), + storage_area: "raw".to_string(), + relpath, + blob_id: None, + logical_path: None, + metadata_json: None, + }, + ).unwrap(); + entry.entry_uid + } + + #[tokio::test] + async fn no_cookie_returns_401() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=html"), + None, + None, + ).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + #[tokio::test] + async fn visible_entry_returns_zip() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let cookie = make_test_session(&f.auth_path); + let (status, bytes) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=html"), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::OK, "expected 200; body: {:?}", String::from_utf8_lossy(&bytes)); + let cursor = std::io::Cursor::new(bytes); + zip::ZipArchive::new(cursor).expect("response should be a valid ZIP"); + } + + #[tokio::test] + async fn invalid_format_returns_400() { + let f = fixture(); + let uid = seed_entry(&f.archive_path); + let cookie = make_test_session(&f.auth_path); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={uid}&format=docx"), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn too_many_entries_returns_400() { + let f = fixture(); + let cookie = make_test_session(&f.auth_path); + let entries: Vec = (0..101).map(|i| format!("uid-{i}")).collect(); + let (status, _) = send( + &f.router, + "GET", + &format!("/api/archives/test/export?entries={}&format=html", entries.join(",")), + Some(&cookie), + None, + ).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } +} diff --git a/crates/archivr-server/src/main.rs b/crates/archivr-server/src/main.rs index fbdbcf6..d90f46a 100644 --- a/crates/archivr-server/src/main.rs +++ b/crates/archivr-server/src/main.rs @@ -6,6 +6,7 @@ mod effective_config; mod entry_access; mod guards; mod jobs; +mod exports; mod registry; mod routes; #[cfg(test)] @@ -150,6 +151,10 @@ async fn main() -> Result<()> { if let Ok(paths) = archivr_core::archive::read_archive_paths(&archive.archive_path) { let uploads_dir = paths.store_path.join("temp").join("uploads"); prune_stale_upload_dirs(&uploads_dir, prune_cutoff, true); + archivr_core::export::prune_stale_export_dirs( + &paths.store_path, + std::time::Duration::from_secs(6 * 60 * 60), + ); } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 6612472..836464f 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -436,6 +436,7 @@ pub fn app_with_state(state: AppState) -> Router { .merge(crate::admin_users::routes()) .merge(crate::credentials::routes()) .merge(crate::jobs::routes()) + .merge(crate::exports::routes()) .merge(crate::effective_config::routes()) .fallback_service(ServeDir::new(&static_dir).not_found_service(ServeFile::new(static_dir.join("index.html")))) .layer(axum::middleware::from_fn_with_state( diff --git a/frontend/src/api.js b/frontend/src/api.js index 42a6f31..5b97a55 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -737,6 +737,34 @@ export async function deleteUpload(archiveId, locator) { } catch {} } +// Builds the export on the server and returns { blob, filename }. +// Errors carry the server's {error} text. +export async function downloadEntryExport(archiveId, { entryUids, format, layout, credit }) { + const params = new URLSearchParams({ + entries: entryUids.join(','), + format, + layout, + credit: String(credit), + }); + const res = await fetch(`/api/archives/${archiveId}/export?${params}`, { + credentials: 'same-origin', + }); + if (!res.ok) { + const detail = await res.text(); + let message = detail.trim(); + try { + message = JSON.parse(detail).error || message; + } catch { + // non-JSON body + } + throw new Error(message || `Export failed (${res.status} ${res.statusText})`); + } + const disposition = res.headers.get('Content-Disposition') || ''; + const filename = /filename="([^"]+)"/.exec(disposition)?.[1] || 'export'; + return { blob: await res.blob(), filename }; +} + + // ── 401 interceptor ─────────────────────────────────────────────────────────── const _origFetch = window.fetch; window.fetch = async (...args) => { diff --git a/frontend/src/api.test.js b/frontend/src/api.test.js index e889ebb..4d9ea69 100644 --- a/frontend/src/api.test.js +++ b/frontend/src/api.test.js @@ -69,3 +69,27 @@ describe('token and session API calls', () => { expect(calls[0].method).toBe('DELETE') }) }) + +describe('downloadEntryExport', () => { + test('builds correct query string', async () => { + const fakeBlob = new Blob(['zip-content'], { type: 'application/zip' }) + const headers = new Headers({ 'Content-Disposition': 'attachment; filename="my-export.zip"' }) + const calls = mockFetch(new Response(fakeBlob, { status: 200, headers })) + const result = await api.downloadEntryExport('a', { + entryUids: ['u1', 'u2'], + format: 'pdf', + layout: 'separate', + credit: false, + }) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('/api/archives/a/export?entries=u1%2Cu2&format=pdf&layout=separate&credit=false') + expect(result.filename).toBe('my-export.zip') + }) + + test('throws the server error text on failure', async () => { + mockFetch(new Response(JSON.stringify({ error: 'select at most 100 entries' }), { status: 400 })) + await expect( + api.downloadEntryExport('a', { entryUids: ['u1'], format: 'html', layout: 'together', credit: true }) + ).rejects.toThrow('select at most 100 entries') + }) +}) diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index 3bd0efb..3c2f685 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -1,5 +1,6 @@ import { useState, useEffect, useLayoutEffect, useRef } from 'react' import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, fetchTranscriptionEngines } from '../api' +import ExportDialog from './ExportDialog' import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils' const VIS_LABEL = { 0: 'Private', 1: 'Public', 2: 'Users only', 3: 'Public' } @@ -46,8 +47,26 @@ const ExternalIcon = () => ( ) +/// Returns UIDs in the DOM order of `rows`, then any UIDs in `selectedUids` +/// not found in `rows` in Set iteration order. +function orderedSelection(rows, selectedUids) { + const seen = new Set() + const result = [] + for (const uid of rows) { + if (selectedUids.has(uid) && !seen.has(uid)) { + seen.add(uid) + result.push(uid) + } + } + for (const uid of selectedUids) { + if (!seen.has(uid)) result.push(uid) + } + return result +} + export default function ContextRail({ archiveId, selectedEntry, selectedUids, selectedEntries, detail, onTagFilterSet, tagNodes, onTagsRefresh, onEntryTitleChange, onEntryDeleted, onBulkDeleted, humanizeTags, onDetailRefresh, onOpenPreview, onPlay, isPublicSession }) { const [tags, setTags] = useState([]) + const [exportOpen, setExportOpen] = useState(false) const [assignInput, setAssignInput] = useState('') const [entryCollections, setEntryCollections] = useState([]) const [assignError, setAssignError] = useState('') @@ -677,6 +696,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se )} +
+

Export

+ +
+
+ )} {(() => { // Public sessions get read-only treatment: the completed text if the @@ -1058,6 +1092,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
)} + { + if (!isBulk) return detail ? [detail.summary.entry_uid] : [] + const rows = Array.from(document.querySelectorAll('#entries-body [data-entry-uid]')).map(el => el.dataset.entryUid) + return orderedSelection(rows, selectedUids) + })()} + onClose={() => setExportOpen(false)} + /> ) } diff --git a/frontend/src/components/ExportDialog.jsx b/frontend/src/components/ExportDialog.jsx new file mode 100644 index 0000000..236ab75 --- /dev/null +++ b/frontend/src/components/ExportDialog.jsx @@ -0,0 +1,176 @@ +import { useRef, useEffect, useState } from 'react' +import { downloadEntryExport } from '../api' + +export default function ExportDialog({ open, archiveId, entryUids, onClose }) { + const dialogRef = useRef(null) + + const [format, setFormat] = useState('html') + const [together, setTogether] = useState(true) + const [credit, setCredit] = useState(true) + const [status, setStatus] = useState('idle') // 'idle' | 'running' | 'error' + const [error, setError] = useState(null) + + // Sync open state with the native dialog. + useEffect(() => { + const dialog = dialogRef.current + if (!dialog) return + if (open) { + if (!dialog.open) dialog.showModal() + } else { + if (dialog.open) dialog.close() + } + }, [open]) + + // Wire the native close event (Escape key, etc.) back to onClose. + useEffect(() => { + const dialog = dialogRef.current + if (!dialog) return + const handler = () => onClose() + dialog.addEventListener('close', handler) + return () => dialog.removeEventListener('close', handler) + }, [onClose]) + + // Reset state each time the dialog opens. + useEffect(() => { + if (open) { + setFormat('html') + setTogether(true) + setCredit(true) + setStatus('idle') + setError(null) + } + }, [open]) + + const n = entryUids?.length ?? 0 + const title = n === 1 ? 'Export entry' : `Export ${n} entries` + + async function handleSubmit(e) { + e.preventDefault() + setStatus('running') + setError(null) + try { + const { blob, filename } = await downloadEntryExport(archiveId, { + entryUids, + format, + layout: together ? 'together' : 'separate', + credit, + }) + // Trigger browser download via a temporary anchor. + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = filename + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + setTimeout(() => URL.revokeObjectURL(url), 1000) + dialogRef.current?.close() + } catch (err) { + setStatus('error') + setError(err.message || 'Export failed') + } + } + + return ( + +
+
+

{title}

+ +
+ +
+
+ + {/* Format selector */} + + + {/* Combine toggle — only when ≥2 entries */} + {n >= 2 && ( + + )} + + {/* Credit toggle */} + + +
+ + {status === 'error' && error && ( +

{error}

+ )} + +
+ + +
+
+
+
+ ) +} diff --git a/frontend/src/components/ExportDialog.test.jsx b/frontend/src/components/ExportDialog.test.jsx new file mode 100644 index 0000000..cc19a6e --- /dev/null +++ b/frontend/src/components/ExportDialog.test.jsx @@ -0,0 +1,42 @@ +import { describe, expect, test } from 'bun:test' +import { renderToStaticMarkup } from 'react-dom/server' + +// Shim window.fetch so api.js can install its 401 interceptor at import time. +const originalWindow = globalThis.window +globalThis.window = { fetch: globalThis.fetch } +const { default: ExportDialog } = await import('./ExportDialog') +globalThis.window = originalWindow + +describe('ExportDialog', () => { + test('with one uid, no "Combine" toggle is rendered', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).not.toContain('Combine into one document') + expect(markup).toContain('Export entry') + }) + + test('with two uids, the "Combine" toggle is rendered', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).toContain('Combine into one document') + expect(markup).toContain('Export 2 entries') + }) + + test('"Include Archivr credit" toggle is checked by default', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + expect(markup).toContain('Include Archivr credit') + expect(markup).toContain('aria-checked="true"') + }) + + test('closed dialog does not render modal content', () => { + const markup = renderToStaticMarkup( + {}} /> + ) + // The dialog element is still in the DOM (native dialog hides itself). + expect(markup).toContain('export-dialog') + }) +}) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 7be7355..51386d0 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -3629,3 +3629,7 @@ body.has-audio-bar { padding-bottom: 56px; } letter-spacing: .04em; text-align: right; } + +/* ── Export ───────────────────────────────────────────────────────────────── */ +.rail-export-btn { margin-top: 6px; } +.export-dialog .export-format { width: 100%; margin: 4px 0 14px; }