1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

feat: entry export (HTML / PDF / Markdown) with quiet Archivr credit

Adds a self-contained export feature across core, server, CLI, and frontend.
Users can export one or more archived entries as a shareable bundle without
exposing the Archivr instance. A small 'Preserved with archivr' credit is
included by default and can be toggled off per export.

Core (crates/archivr-core/src/export/):
- brand.rs   — export CSS (palette from style-guide), CREDIT_HTML,
               CREDIT_INLINE_HTML (for snapshot injection)
- model.rs   — ExportEntry / ExportBody / Asset loading; tweet thread
               reconstruction (reply-graph DFS, sibling ordering)
- html.rs    — full HTML document renderer: all body kinds, AssetMode
               Bundle vs Print, render_cover for PDF cover pages
- markdown.rs — Markdown renderer with poster-linked video, blockquoted
               quote tweets, credit sub-tag
- bundle.rs  — ZIP writer (Deflated for text, Stored for binary,
               large_file for >= 4 GiB assets)
- pdf.rs     — print_pdf (headless Chrome), merge_documents (lopdf
               ID-offset merge), entry_pdf (snapshot injection,
               PDF-merge, HTML fallback)
- mod.rs     — export_entries, prune_stale_export_dirs, ExportFile,
               ffmpeg poster generation, full assembly dispatch

summarizer.rs: extract pub(crate) article_parts so the export module
reuses the article title/body logic without duplication.

Server (crates/archivr-server/src/exports.rs):
- GET /api/archives/:archive_id/export?entries=&format=&layout=&credit=
- Auth required (guests -> 401); per-UID ensure_entry_visible check
- Blocking spawn_blocking task; streaming response via ReaderStream
- ARCHIVR_EXPORT_PDF_TIMEOUT added to ENV_VARS (default 120 s)
- ARCHIVR_CHROME description updated to mention PDF export
- prune_stale_export_dirs called at startup (6 h TTL)

CLI (crates/archivr-cli/src/main.rs):
  archivr export <UIDs...> [--format html|pdf|markdown]
                           [--separate] [--no-credit] [-o DIR]

Frontend:
- api.js: downloadEntryExport (blob + filename from Content-Disposition)
- ExportDialog.jsx: native <dialog>; format selector; Combine toggle
  (>= 2 entries); credit toggle (on by default); error display
- ContextRail.jsx: single-entry Export... button after Preview; bulk
  Export N entries... section before delete zone; orderedSelection
  helper for DOM-order UIDs; ExportDialog mounted once per rail
- styles.css: .rail-export-btn, .export-dialog .export-format rules

Tests:
- 9 new cargo tests in export/mod.rs (HTML, Markdown, PDF merge,
  parent-child dedupe, separate layout, credit on/off, validation)
- 4 new cargo tests in exports.rs (401 no-auth, 200 ZIP, 400 bad
  format, 400 too many entries)
- 4 new bun tests in ExportDialog.test.jsx (single/multi uid, credit
  default, closed state)
- 2 new bun tests in api.test.js (query string, error propagation)

All 247 Rust tests and 50 frontend tests pass.

MCP follow-up: archivr-mcp export_entries tool (GET /api/.../export,
read-scope tokens accepted) — not built here.
This commit is contained in:
TheGeneralist 2026-10-12 19:51:15 +02:00
parent 64ef4ca313
commit e40312734d
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
24 changed files with 4453 additions and 34 deletions

409
Cargo.lock generated
View file

@ -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]]

View file

@ -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"] }

View file

@ -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<String>,
/// 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<ExportFormatArg> 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(),

View file

@ -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"

View file

@ -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#"<footer class="ax-colophon"><a class="ax-credit" href="https://github.com/thegeneralist01/archivr" rel="noopener">
<span class="ax-mark" aria-hidden="true">A</span><span>Preserved with <span class="ax-wordmark">archivr</span></span></a></footer>"#;
/// 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#"<div style="all:initial;display:block;max-width:760px;margin:48px auto 0;padding:22px 28px 56px;border-top:1px solid #d2c6b5;text-align:center;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif">
<a style="display:inline-flex;align-items:center;gap:8px;font-size:11px;letter-spacing:.08em;color:#6b6f66;text-decoration:none" href="https://github.com/thegeneralist01/archivr" rel="noopener">
<span style="display:inline-grid;place-items:center;width:16px;height:16px;border-radius:2.5px;background:#8d3f30;color:#f4ead8;font:600 12px/1 Georgia,serif" aria-hidden="true">A</span>
<span>Preserved with <span style="font:600 15px/1 Georgia,serif;letter-spacing:.01em;color:#20251f">archivr</span></span></a></div>"#;

View file

@ -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 `<folder_name>/index.{ext}` plus
/// `<folder_name>/assets/<name>` per asset.
/// `ext` is `"html"` or `"md"`.
pub(crate) fn write_zip_multi(
zip_path: &Path,
folders: &[(String, String, Vec<Asset>)],
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<String> = 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 `<folder>/assets/`.
pub(crate) fn write_zip_multi_with_extra(
zip_path: &Path,
folders: &[(String, String, Vec<Asset>)],
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<String> = 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: `<folder>/<NN>-<slug>.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
}

View file

@ -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/<name>` — for ZIP bundles.
Bundle,
/// `file://<percent-encoded absolute path>` — 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("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
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::<Utc>::from_timestamp(secs, 0)
.unwrap_or_else(|| DateTime::<Utc>::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<String> {
// 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/<name>`) or absolute `file://` URLs for PDF printing.
pub(crate) fn render_document(
entries: &[ExportEntry],
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
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#"<meta name="generator" content="Archivr">"#
} else {
""
};
let mut html = format!(
r#"<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
{generator_meta}
<title>{title}</title><style>{css}</style></head>
<body><main class="ax-doc">
"#,
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("</main>");
if include_credit {
html.push('\n');
html.push_str(brand::CREDIT_HTML);
html.push('\n');
}
html.push_str("</body></html>\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#"<meta name="generator" content="Archivr">"#
} else {
""
};
let mut html = format!(
r#"<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
{generator_meta}
<title>{n} archived entries</title><style>{css}</style></head>
<body><main class="ax-doc">
"#,
n = entries.len(),
css = brand::EXPORT_CSS,
generator_meta = generator_meta,
);
html.push_str(&format!(
r#"<header class="ax-collection"><p class="ax-eyebrow">Collection</p><h1 class="ax-title">{n} archived entries</h1>
<ol class="ax-toc">"#,
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#"<li>{title} <span class="ax-muted">{label}</span></li>"#,
title = esc(&title),
label = esc(&label),
));
}
html.push_str("</ol></header>\n");
html.push_str("</main>");
if include_credit {
html.push('\n');
html.push_str(brand::CREDIT_HTML);
html.push('\n');
}
html.push_str("</body></html>\n");
html
}
fn render_collection_header(entries: &[ExportEntry]) -> String {
let mut s = format!(
r#"<header class="ax-collection"><p class="ax-eyebrow">Collection</p><h1 class="ax-title">{n} archived entries</h1>
<ol class="ax-toc">"#,
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!(
"<li><a href=\"#entry-{i}\">{title}</a> <span class=\"ax-muted\">{label}</span></li>",
title = esc(&title),
label = esc(&label),
));
}
s.push_str("</ol></header>\n");
s
}
fn render_entry(
entry: &ExportEntry,
index: usize,
together: bool,
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
) -> 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#" · <a href="{url}" rel="noopener noreferrer">{host}</a>"#,
url = esc(url),
host = esc(&host),
)
}
_ => String::new(),
};
let mut s = format!(
r#"<article class="ax-entry"{id_attr}>
<header class="ax-masthead"><p class="ax-eyebrow">{label}</p>
<{heading} class="ax-title">{title}</{heading}>
<p class="ax-meta">Archived <time datetime="{dt}">{date}</time>{url_part}</p></header>
<div class="ax-body">"#,
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("</div></article>\n");
s
}
fn render_body(
body: &ExportBody,
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
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#"<div class="ax-text">{}</div>"#, 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#"<p class="ax-empty">No archived content is available for this entry.</p>"#
.to_string()
}
}
}
fn render_video(
asset: &Asset,
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
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#"<track kind="subtitles" src="{sub_src}" label="{label}"{srclang_attr}{default_attr}>"#,
label = esc(&label),
)
})
.collect();
format!(
r#"<figure class="ax-media"><video controls preload="metadata" playsinline{poster_attr} src="{src}">{tracks}</video></figure>"#,
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#"<figure class="ax-media"><img src="{poster_src}" alt=""><figcaption>Video · {name}</figcaption></figure>"#,
poster_src = esc(&poster_src),
name = esc(&name),
)
} else {
format!(
r#"<div class="ax-placeholder">Video · {}</div>"#,
esc(&asset.name)
)
}
}
}
}
fn render_audio(asset: &Asset, mode: AssetMode) -> String {
match mode {
AssetMode::Bundle => {
let src = asset_src(mode, asset);
format!(r#"<audio controls preload="metadata" src="{}"></audio>"#, esc(&src))
}
AssetMode::Print => {
format!(
r#"<div class="ax-placeholder">Audio · {}</div>"#,
esc(&asset.name)
)
}
}
}
fn render_image(asset: &Asset, mode: AssetMode, title: &str) -> String {
let src = asset_src(mode, asset);
format!(
r#"<figure class="ax-media"><img src="{src}" alt="{alt}" loading="lazy"></figure>"#,
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#"<object class="ax-frame" data="{src}" type="application/pdf"></object>
<p class="ax-aside"><a href="{src}">Open the PDF</a></p>"#,
src = esc(&src),
)
}
AssetMode::Print => {
// Handled separately in pdf.rs: the PDF asset is merged directly.
format!(r#"<p class="ax-aside">{}</p>"#, esc(title))
}
}
}
fn render_page(asset: &Asset, mode: AssetMode, title: &str) -> String {
match mode {
AssetMode::Bundle => {
let src = asset_src(mode, asset);
format!(
r#"<iframe class="ax-frame" src="{src}" title="{title}" sandbox="allow-same-origin allow-popups" referrerpolicy="no-referrer" loading="lazy"></iframe>
<p class="ax-aside"><a href="{src}">Open the archived page on its own</a></p>"#,
src = esc(&src),
title = esc(title),
)
}
AssetMode::Print => {
// Handled in pdf.rs: the snapshot gets masthead/colophon injected.
format!(r#"<p class="ax-aside">{}</p>"#, 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#"<p class="ax-aside"><a href="{src}" download>Download {ext} file</a> · {size}</p>"#,
src = esc(&src),
ext = esc(&ext),
)
}
fn render_posts(
posts: &[Post],
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
) -> String {
let mut s = String::from(r#"<div class="ax-thread">"#);
for post in posts {
s.push_str(&render_post(post, mode, posters, false));
}
s.push_str("</div>");
s
}
fn render_post(
post: &Post,
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
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#"<img class="ax-avatar" src="{src}" alt="">"#, 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}">
<header class="ax-post-head">{avatar_html}<span class="ax-post-name">{name}</span> <span class="ax-muted">{handle_html}</span></header>
"#,
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#"<h3 class="ax-article-title">{}</h3>"#,
esc(title)
));
}
if let Some(cover) = cover {
let src = asset_src(mode, cover);
s.push_str(&format!(
r#"<img class="ax-article-cover" src="{}" alt="">"#,
esc(&src)
));
}
for para in body.split("\n\n") {
let trimmed = para.trim();
if !trimmed.is_empty() {
s.push_str(&format!("<p>{}</p>", esc(trimmed)));
}
}
} else if !post.spans.is_empty() {
s.push_str(r#"<div class="ax-post-text">"#);
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#"<a href="{h}" rel="noopener noreferrer">{text}</a>"#,
h = esc(h),
text = esc(text),
));
} else {
s.push_str(&esc(text));
}
}
}
}
s.push_str("</div>");
}
// Photos and videos.
if !post.photos.is_empty() || !post.videos.is_empty() {
s.push_str(r#"<div class="ax-post-media">"#);
for photo in &post.photos {
let src = asset_src(mode, photo);
s.push_str(&format!(
r#"<img src="{src}" alt="" loading="lazy">"#,
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#"<video autoplay loop muted playsinline src="{src}"></video>"#,
src = esc(&src)
));
} else {
s.push_str(&format!(
r#"<video controls src="{src}"></video>"#,
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#"<img src="{poster_src}" alt="" loading="lazy">"#,
poster_src = esc(&poster_src)
));
} else {
s.push_str(&format!(
r#"<div class="ax-placeholder">Video · {}</div>"#,
esc(&video.name)
));
}
}
}
}
s.push_str("</div>");
}
// 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#"<a class="ax-post-link" href="{url}" rel="noopener noreferrer">View on X</a>"#,
url = esc(url)
));
}
s.push_str(&format!("</{tag}>"));
s
}
fn render_container(
children: &[ExportEntry],
mode: AssetMode,
posters: &std::collections::HashMap<String, PathBuf>,
depth: usize,
) -> String {
let mut s = String::from(r#"<ol class="ax-children">"#);
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#"<li><article class="ax-entry ax-entry--child">
<header class="ax-masthead"><h3 class="ax-title">{title}</h3>
<p class="ax-meta"><time datetime="{dt}">{date}</time></p></header>
<div class="ax-body">{child_body}</div>
</article></li>"#,
title = esc(&title),
dt = esc(&child.summary.archived_at),
));
}
s.push_str("</ol>");
s
}

View file

@ -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::<Utc>::from_timestamp(secs, 0)
.unwrap_or_else(|| DateTime::<Utc>::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<String> {
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/<name>`.
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<String, PathBuf>,
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!(
"<a id=\"{}\"></a>\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\n<sub>Preserved with [archivr](https://github.com/thegeneralist01/archivr)</sub>\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, PathBuf>,
) -> 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<String, PathBuf>,
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, PathBuf>,
) -> String {
let mut parts: Vec<String> = 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, PathBuf>,
) -> 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, PathBuf>,
) -> 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
}

File diff suppressed because it is too large Load diff

View file

@ -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<String>,
pub avatar: Option<Asset>,
pub created_at_secs: Option<i64>,
pub spans: Vec<Span>,
/// `Some((title, body, cover))` for X article statuses.
pub article: Option<(Option<String>, String, Option<Asset>)>,
pub photos: Vec<Asset>,
/// `(asset, animated_gif)`.
pub videos: Vec<(Asset, bool)>,
pub quote: Option<Box<Post>>,
/// `https://x.com/{handle|i}/status/{id}`.
pub status_url: Option<String>,
}
/// 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<Post>),
Container(Vec<ExportEntry>),
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<Asset>,
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<ExportEntry> {
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<String, Asset> = HashMap::new();
let mut primary_media_artifact: Option<EntryArtifactSummary> = None;
let mut subtitle_artifacts: Vec<EntryArtifactSummary> = Vec::new();
let mut raw_json_artifacts: Vec<EntryArtifactSummary> = 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<Asset> = 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<ExportEntry> = children
.into_iter()
.map(|child| load_entry(conn, store_path, child, caller_bits, depth + 1))
.collect::<Result<Vec<_>>>()?;
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<String, Asset>,
) -> 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<String, Asset>,
entity_kind: &str,
) -> Vec<Post> {
let seed_id: Option<String> = serde_json::from_str::<serde_json::Value>(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<serde_json::Value> = 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<String, serde_json::Value> = 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<String, serde_json::Value>,
seed_id: Option<&str>,
asset_map: &HashMap<String, Asset>,
) -> Vec<Post> {
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<String> = 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<String, Vec<String>> = 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<String> = HashSet::new();
dfs(
&root_id,
status_map,
&children_map,
asset_map,
&mut result,
&mut conversation_ids,
);
result
}
fn dfs(
id: &str,
status_map: &HashMap<String, serde_json::Value>,
children_map: &HashMap<String, Vec<String>>,
asset_map: &HashMap<String, Asset>,
out: &mut Vec<Post>,
conversation_ids: &mut HashSet<String>,
) {
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<String> {
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<String> {
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<i64> {
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<String, Asset>,
conversation_ids: Option<&HashSet<String>>,
) -> 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<String> = 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<Asset> = 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<Span> {
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<Span> = 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<Span>, strip_set: &HashSet<String>) -> Vec<Span> {
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("&amp;", "&")
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&#39;", "'")
}

View file

@ -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<String> = 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<OsString> = 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<Document> = inputs
.iter()
.map(|p| Document::load(p).with_context(|| format!("failed to load PDF: {}", p.display())))
.collect::<Result<Vec<_>>>()?;
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<Document>) -> Result<Document> {
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<ObjectId> = 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<u32, ObjectId>
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<String, PathBuf>,
) -> Result<PathBuf> {
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<String, PathBuf>,
) -> Result<PathBuf> {
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<PathBuf> {
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<PathBuf> {
// 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#"<div style="all:initial;display:block;max-width:760px;margin:0 auto 28px;padding:0 0 22px;border-bottom:1px solid #d2c6b5;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif">
<p style="all:initial;display:block;margin:0 0 10px;font-size:10.5px;letter-spacing:.16em;text-transform:uppercase;color:#6b6f66">{label}</p>
<h1 style="all:initial;display:block;margin:0;font:600 38px/1.12 'Cormorant Garamond','Cormorant',Georgia,serif;letter-spacing:.005em;color:#20251f">{title}</h1>
<p style="all:initial;display:block;margin:12px 0 0;font-size:13px;color:#6b6f66">Archived {date}</p>
</div>"#,
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#"<!doctype html><html lang="en"><head><meta charset="utf-8"><style>body{{margin:0;font:17px/1.65 Georgia,serif;background:#f5f0e7;color:#20251f}}.ax-doc{{max-width:760px;margin:0 auto;padding:64px 28px 32px}}</style></head>
<body><main class="ax-doc">{masthead}</main>{credit}</body></html>"#,
)
}
fn inject_after_body_open(html: &str, to_inject: &str) -> String {
let lower = html.to_lowercase();
if let Some(body_start) = lower.find("<body") {
if let Some(rel_end) = lower[body_start..].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("</body>") {
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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}

View file

@ -14,3 +14,4 @@ pub mod text_title;
pub mod transcriber;
pub(crate) mod env_config;
pub(crate) mod process;
pub mod export;

View file

@ -838,7 +838,11 @@ fn flatten_article_blocks(v: &serde_json::Value, out: &mut Vec<String>) {
}
}
fn article_text(status: &serde_json::Value) -> Option<String> {
/// 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>, 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<String> {
})
.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<String> {
article_parts(status).map(|(title, body)| match title.as_deref() {
Some(t) => format!("{t}\n\n{body}"),
None => body,
})
}

View file

@ -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

View file

@ -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)."),

View file

@ -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<AppState> {
Router::new().route(
"/api/archives/:archive_id/export",
get(export_handler),
)
}
#[derive(Debug, serde::Deserialize)]
struct ExportQuery {
entries: String,
format: String,
layout: Option<String>,
credit: Option<bool>,
}
async fn export_handler(
State(state): State<AppState>,
auth_user: AuthUser,
Path(archive_id): Path<String>,
Query(q): Query<ExportQuery>,
) -> Result<impl IntoResponse, ApiError> {
// 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<String> = 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<String> = (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);
}
}

View file

@ -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),
);
}
}

View file

@ -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(

View file

@ -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) => {

View file

@ -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')
})
})

View file

@ -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 = () => (
</svg>
)
/// 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
</div>
)}
<div className="rail-section">
<p className="rail-section-heading">Export</p>
<button
className="rail-rearchive-btn"
onClick={() => setExportOpen(true)}
>
{`Export ${selectedUids.size} entries\u2026`}
</button>
</div>
<div className="rail-delete-zone">
<button
className="rail-delete-btn"
@ -751,6 +780,11 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
Preview
</button>
)}
{!isPublicSession && (
<button className="rail-preview-btn rail-export-btn" onClick={() => setExportOpen(true)}>
Export\u2026
</button>
)}
{(() => {
// Public sessions get read-only treatment: the completed text if the
@ -1058,6 +1092,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
</div>
</>
)}
<ExportDialog
open={exportOpen}
archiveId={archiveId}
entryUids={(() => {
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)}
/>
</aside>
)
}

View file

@ -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 (
<dialog ref={dialogRef} className="capture-dialog export-dialog">
<div className="capture-dialog-inner">
<div className="capture-dialog-header">
<h2 className="capture-dialog-title">{title}</h2>
<button
type="button"
className="capture-dialog-close"
onClick={() => dialogRef.current?.close()}
aria-label="Close"
>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
<line x1="3" y1="3" x2="13" y2="13"/><line x1="13" y1="3" x2="3" y2="13"/>
</svg>
</button>
</div>
<form onSubmit={handleSubmit}>
<div className="capture-rows">
{/* Format selector */}
<label className="capture-ext-row" style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<span className="capture-ext-name">Format</span>
<select
className="capture-quality export-format"
value={format}
onChange={e => setFormat(e.target.value)}
disabled={status === 'running'}
>
<option value="html">Web page — HTML (.zip)</option>
<option value="pdf">PDF</option>
<option value="markdown">Markdown (.zip)</option>
</select>
</label>
{/* Combine toggle — only when ≥2 entries */}
{n >= 2 && (
<label className="capture-ext-row">
<span className="capture-ext-label">
<span className="capture-ext-name">Combine into one document</span>
<span className="capture-ext-desc">Off: each entry is exported on its own</span>
</span>
<button
type="button"
role="switch"
aria-checked={together}
className={`ext-toggle ext-toggle--sm${together ? ' ext-toggle--on' : ''}`}
onClick={() => setTogether(v => !v)}
aria-label="Toggle combine"
disabled={status === 'running'}
>
<span className="ext-toggle-knob" />
</button>
</label>
)}
{/* Credit toggle */}
<label className="capture-ext-row">
<span className="capture-ext-label">
<span className="capture-ext-name">Include Archivr credit</span>
<span className="capture-ext-desc">Adds a small "Preserved with archivr" line at the end</span>
</span>
<button
type="button"
role="switch"
aria-checked={credit}
className={`ext-toggle ext-toggle--sm${credit ? ' ext-toggle--on' : ''}`}
onClick={() => setCredit(v => !v)}
aria-label="Toggle Archivr credit"
disabled={status === 'running'}
>
<span className="ext-toggle-knob" />
</button>
</label>
</div>
{status === 'error' && error && (
<p className="form-msg form-msg--err">{error}</p>
)}
<div className="capture-actions">
<button
type="submit"
className="capture-submit"
disabled={status === 'running'}
>
{status === 'running' ? 'Exporting\u2026' : 'Export'}
</button>
<button
type="button"
className="capture-cancel"
onClick={() => dialogRef.current?.close()}
disabled={status === 'running'}
>
Cancel
</button>
</div>
</form>
</div>
</dialog>
)
}

View file

@ -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(
<ExportDialog open archiveId="a" entryUids={['u1']} onClose={() => {}} />
)
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(
<ExportDialog open archiveId="a" entryUids={['u1', 'u2']} onClose={() => {}} />
)
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(
<ExportDialog open archiveId="a" entryUids={['u1']} onClose={() => {}} />
)
expect(markup).toContain('Include Archivr credit')
expect(markup).toContain('aria-checked="true"')
})
test('closed dialog does not render modal content', () => {
const markup = renderToStaticMarkup(
<ExportDialog open={false} archiveId="a" entryUids={['u1']} onClose={() => {}} />
)
// The dialog element is still in the DOM (native dialog hides itself).
expect(markup).toContain('export-dialog')
})
})

View file

@ -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; }