mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
Merge pull request #42 from thegeneralist01/entry-export
feat: entry export (HTML/PDF/Markdown), shared capture progress, and __Host- cookie fix
This commit is contained in:
commit
1c8abddf93
33 changed files with 4110 additions and 103 deletions
6
Cargo.lock
generated
6
Cargo.lock
generated
|
|
@ -141,10 +141,12 @@ dependencies = [
|
|||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"toml",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"uuid",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -276,9 +278,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"
|
||||
|
|
|
|||
|
|
@ -35,3 +35,4 @@ 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"
|
||||
tokio-util = { version = "0.7", features = ["io"] }
|
||||
|
|
|
|||
|
|
@ -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 or Markdown bundle
|
||||
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,21 @@ enum Command {
|
|||
},
|
||||
}
|
||||
|
||||
#[derive(clap::ValueEnum, Debug, Clone, Copy)]
|
||||
enum ExportFormatArg {
|
||||
Html,
|
||||
Markdown,
|
||||
}
|
||||
|
||||
impl From<ExportFormatArg> for ExportFormat {
|
||||
fn from(a: ExportFormatArg) -> Self {
|
||||
match a {
|
||||
ExportFormatArg::Html => ExportFormat::Html,
|
||||
ExportFormatArg::Markdown => ExportFormat::Markdown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum YtDlpCmd {
|
||||
/// Download the latest yt-dlp zipapp and Deno into archivr's state directory
|
||||
|
|
@ -125,6 +158,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(),
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ uuid.workspace = true
|
|||
reqwest = { workspace = true }
|
||||
base64.workspace = true
|
||||
zip.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -53,6 +53,38 @@ pub fn list_capture_jobs(
|
|||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Lists `pending` and `running` capture jobs, ordered oldest-first.
|
||||
/// `created_by = Some(uid)` limits the result to that user's jobs.
|
||||
pub fn list_active_capture_jobs(
|
||||
conn: &Connection,
|
||||
created_by: Option<&str>,
|
||||
) -> Result<Vec<CaptureJobSummary>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT job_uid, archive_id, run_uid, status, error_text, notes_json,
|
||||
created_at, updated_at, created_by
|
||||
FROM capture_jobs
|
||||
WHERE status IN ('pending', 'running')
|
||||
AND (?1 IS NULL OR created_by = ?1)
|
||||
ORDER BY created_at ASC, id ASC",
|
||||
)?;
|
||||
let rows = stmt
|
||||
.query_map([created_by], |row| {
|
||||
Ok(CaptureJobSummary {
|
||||
job_uid: row.get(0)?,
|
||||
archive_id: row.get(1)?,
|
||||
run_uid: row.get(2)?,
|
||||
status: row.get(3)?,
|
||||
error_text: row.get(4)?,
|
||||
notes_json: row.get(5)?,
|
||||
created_at: row.get(6)?,
|
||||
updated_at: row.get(7)?,
|
||||
created_by: row.get(8)?,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// One `archive_run_items` row of a job's run.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct JobItem {
|
||||
|
|
|
|||
|
|
@ -1789,6 +1789,16 @@ pub fn link_capture_job_run(conn: &Connection, job_uid: &str, run_uid: &str) ->
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets (or overwrites) the `notes_json` field of a capture job.
|
||||
/// Used to store a display locator immediately after job creation.
|
||||
pub fn update_capture_job_notes(conn: &Connection, job_uid: &str, notes_json: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE capture_jobs SET notes_json = ?1, updated_at = ?2 WHERE job_uid = ?3",
|
||||
params![notes_json, now_timestamp(), job_uid],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a capture job by uid.
|
||||
pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result<Option<CaptureJobRecord>> {
|
||||
conn.query_row(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use std::{collections::HashMap, io::Write, path::Path};
|
||||
use serde_json::json;
|
||||
|
||||
/// Writes a Netscape-format HTTP cookie file suitable for yt-dlp `--cookies` and
|
||||
/// single-file `--browser-cookies-file`. The file is created with mode 0o600
|
||||
|
|
@ -38,6 +39,84 @@ pub fn write_netscape_cookie_file(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes a JSON-format cookie file for single-file `--browser-cookies-file`.
|
||||
///
|
||||
/// Single-file accepts both Netscape text and JSON; JSON gives us per-cookie
|
||||
/// field control, which is required for `__Host-`/`__Secure-` cookies.
|
||||
///
|
||||
/// - `__Host-` cookies: Chrome CDP `Network.setCookies` rejects these when a
|
||||
/// `domain` attribute is present. They must be set via `url` (no `domain`),
|
||||
/// `path: "/"`, and `secure: true`.
|
||||
/// - `__Secure-` cookies: require `secure: true`; `domain` is still fine.
|
||||
/// - All other cookies: use `domain` as before; `secure` left false because
|
||||
/// we have no per-cookie scheme information from the user's input map.
|
||||
///
|
||||
/// The file is created 0o600 (owner read/write only) to protect cookie secrets.
|
||||
pub fn write_json_cookie_file(
|
||||
cookies: &HashMap<String, String>,
|
||||
domain: &str,
|
||||
page_url: &str,
|
||||
path: &Path,
|
||||
) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
let mut f = {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)?
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let mut f = std::fs::File::create(path)?;
|
||||
|
||||
// Build a canonical https root URL for __Host- cookies (must be https).
|
||||
// If the page_url itself is https we use it directly; otherwise synthesise one.
|
||||
let host_url = if page_url.starts_with("https://") {
|
||||
page_url.to_string()
|
||||
} else {
|
||||
format!("https://{}/", domain)
|
||||
};
|
||||
|
||||
let entries: Vec<serde_json::Value> = cookies
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
if name.starts_with("__Host-") {
|
||||
// No `domain` field — Chrome rejects __Host- cookies that carry one.
|
||||
json!({
|
||||
"name": name,
|
||||
"value": value,
|
||||
"url": host_url,
|
||||
"path": "/",
|
||||
"secure": true
|
||||
})
|
||||
} else if name.starts_with("__Secure-") {
|
||||
json!({
|
||||
"name": name,
|
||||
"value": value,
|
||||
"domain": domain,
|
||||
"path": "/",
|
||||
"secure": true
|
||||
})
|
||||
} else {
|
||||
json!({
|
||||
"name": name,
|
||||
"value": value,
|
||||
"domain": domain,
|
||||
"path": "/"
|
||||
})
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let json_str = serde_json::to_string(&entries)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
|
||||
f.write_all(json_str.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
/// Extracts the exact hostname from a URL, suitable for use as the Netscape
|
||||
/// cookie domain.
|
||||
///
|
||||
|
|
@ -64,3 +143,93 @@ pub fn cookies_to_header(cookies: &HashMap<String, String>) -> String {
|
|||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
fn read_json(f: &NamedTempFile) -> Vec<serde_json::Value> {
|
||||
let s = std::fs::read_to_string(f.path()).unwrap();
|
||||
serde_json::from_str(&s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_prefix_cookie_has_no_domain_uses_url() {
|
||||
let mut cookies = HashMap::new();
|
||||
cookies.insert("__Host-session".to_string(), "abc123".to_string());
|
||||
let f = NamedTempFile::new().unwrap();
|
||||
write_json_cookie_file(
|
||||
&cookies,
|
||||
"example.com",
|
||||
"https://example.com/page",
|
||||
f.path(),
|
||||
)
|
||||
.unwrap();
|
||||
let entries = read_json(&f);
|
||||
assert_eq!(entries.len(), 1);
|
||||
let c = &entries[0];
|
||||
assert_eq!(c["name"], "__Host-session");
|
||||
assert_eq!(c["value"], "abc123");
|
||||
assert!(c.get("domain").is_none(), "__Host- must not have domain field");
|
||||
assert_eq!(c["url"], "https://example.com/page");
|
||||
assert_eq!(c["path"], "/");
|
||||
assert_eq!(c["secure"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_prefix_cookie_has_domain_and_secure_true() {
|
||||
let mut cookies = HashMap::new();
|
||||
cookies.insert("__Secure-token".to_string(), "xyz".to_string());
|
||||
let f = NamedTempFile::new().unwrap();
|
||||
write_json_cookie_file(
|
||||
&cookies,
|
||||
"example.com",
|
||||
"https://example.com/",
|
||||
f.path(),
|
||||
)
|
||||
.unwrap();
|
||||
let entries = read_json(&f);
|
||||
let c = &entries[0];
|
||||
assert_eq!(c["domain"], "example.com");
|
||||
assert_eq!(c["secure"], true);
|
||||
assert!(c.get("url").is_none(), "__Secure- should not carry url field");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regular_cookie_uses_domain_no_secure() {
|
||||
let mut cookies = HashMap::new();
|
||||
cookies.insert("cf_bm".to_string(), "val".to_string());
|
||||
let f = NamedTempFile::new().unwrap();
|
||||
write_json_cookie_file(
|
||||
&cookies,
|
||||
"example.com",
|
||||
"https://example.com/",
|
||||
f.path(),
|
||||
)
|
||||
.unwrap();
|
||||
let entries = read_json(&f);
|
||||
let c = &entries[0];
|
||||
assert_eq!(c["domain"], "example.com");
|
||||
assert!(c.get("secure").map(|v| v != true).unwrap_or(true), "regular cookie should not be forced secure");
|
||||
assert!(c.get("url").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_prefix_falls_back_to_https_url_when_page_url_is_http() {
|
||||
let mut cookies = HashMap::new();
|
||||
cookies.insert("__Host-x".to_string(), "1".to_string());
|
||||
let f = NamedTempFile::new().unwrap();
|
||||
write_json_cookie_file(
|
||||
&cookies,
|
||||
"marketing.creativedirector.net",
|
||||
"http://marketing.creativedirector.net/course",
|
||||
f.path(),
|
||||
)
|
||||
.unwrap();
|
||||
let entries = read_json(&f);
|
||||
let c = &entries[0];
|
||||
assert!(c["url"].as_str().unwrap().starts_with("https://"), "must use https url for __Host- even when page is http");
|
||||
assert!(c.get("domain").is_none());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use std::{
|
|||
process::Command,
|
||||
};
|
||||
|
||||
use crate::downloader::cookies::{domain_from_url, write_netscape_cookie_file};
|
||||
use crate::downloader::cookies::{domain_from_url, write_json_cookie_file};
|
||||
use crate::hash::hash_file;
|
||||
|
||||
/// Combined reader-mode script: Readability.js (Apache 2.0) bundled with the
|
||||
|
|
@ -611,9 +611,9 @@ fn save_with(
|
|||
|
||||
// Write cookie file (secrets must never appear in process args).
|
||||
let cookie_file: Option<PathBuf> = if !cookies.is_empty() {
|
||||
let cf = temp_dir.join("cookies.txt");
|
||||
let cf = temp_dir.join("cookies.json");
|
||||
let domain = domain_from_url(url);
|
||||
write_netscape_cookie_file(cookies, &domain, &cf)
|
||||
write_json_cookie_file(cookies, &domain, url, &cf)
|
||||
.context("failed to write single-file cookie file")?;
|
||||
Some(cf)
|
||||
} else {
|
||||
|
|
|
|||
50
crates/archivr-core/src/export/brand.rs
Normal file
50
crates/archivr-core/src/export/brand.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
//! 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>"#;
|
||||
|
||||
166
crates/archivr-core/src/export/bundle.rs
Normal file
166
crates/archivr-core/src/export/bundle.rs
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
//! 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(())
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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
|
||||
}
|
||||
589
crates/archivr-core/src/export/html.rs
Normal file
589
crates/archivr-core/src/export/html.rs
Normal file
|
|
@ -0,0 +1,589 @@
|
|||
//! 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,
|
||||
}
|
||||
|
||||
pub(crate) fn asset_src(mode: AssetMode, asset: &Asset) -> String {
|
||||
match mode {
|
||||
AssetMode::Bundle => format!("assets/{}", asset.name),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// HTML-escape `& < > " '`.
|
||||
pub(crate) fn esc(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for ch in s.chars() {
|
||||
match ch {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Returns `Some(s)` only for `http://` and `https://` URLs.
|
||||
fn safe_href(s: &str) -> Option<&str> {
|
||||
if s.starts_with("http://") || s.starts_with("https://") {
|
||||
Some(s)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Format `archived_at` (RFC 3339) as `"%-d %B %Y"`.
|
||||
fn fmt_date(archived_at: &str) -> String {
|
||||
use chrono::DateTime;
|
||||
if let Ok(dt) = DateTime::parse_from_rfc3339(archived_at) {
|
||||
dt.format("%-d %B %Y").to_string()
|
||||
} else {
|
||||
archived_at.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Format Unix seconds as `"%-d %B %Y"`.
|
||||
fn fmt_timestamp(secs: i64) -> String {
|
||||
use chrono::{DateTime, Utc};
|
||||
let dt = DateTime::<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
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
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()
|
||||
// SRT files stay in the ZIP, but HTML video tracks require WebVTT.
|
||||
.filter(|sub| ext_of_s(&sub.name) == "vtt")
|
||||
.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),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_audio(asset: &Asset, mode: AssetMode) -> String {
|
||||
let src = asset_src(mode, asset);
|
||||
format!(r#"<audio controls preload="metadata" src="{}"></audio>"#, esc(&src))
|
||||
}
|
||||
|
||||
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 {
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_page(asset: &Asset, mode: AssetMode, title: &str) -> String {
|
||||
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),
|
||||
)
|
||||
}
|
||||
|
||||
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 {
|
||||
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)
|
||||
));
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn video_tracks_use_vtt_only_even_when_srt_precedes_it() {
|
||||
let asset = |name: &str| Asset {
|
||||
source: PathBuf::new(),
|
||||
name: name.to_string(),
|
||||
byte_size: 0,
|
||||
};
|
||||
let html = render_video(
|
||||
&asset("video.mp4"),
|
||||
AssetMode::Bundle,
|
||||
&std::collections::HashMap::new(),
|
||||
&[asset("captions.srt"), asset("captions.vtt")],
|
||||
);
|
||||
|
||||
assert_eq!(html.matches("<track ").count(), 1);
|
||||
assert!(html.contains("src=\"assets/captions.vtt\""));
|
||||
assert!(html.contains(" default>"));
|
||||
assert!(!html.contains("captions.srt"));
|
||||
}
|
||||
}
|
||||
300
crates/archivr-core/src/export/markdown.rs
Normal file
300
crates/archivr-core/src/export/markdown.rs
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
//! 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()
|
||||
}
|
||||
|
||||
fn fenced_plain_text(text: &str) -> String {
|
||||
let mut longest_run = 0;
|
||||
let mut run = 0;
|
||||
for byte in text.bytes() {
|
||||
if byte == b'`' {
|
||||
run += 1;
|
||||
longest_run = longest_run.max(run);
|
||||
} else {
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
let fence = "`".repeat((longest_run + 1).max(3));
|
||||
let trailing_newline = if text.ends_with('\n') { "" } else { "\n" };
|
||||
format!("{fence}\n{text}{trailing_newline}{fence}\n")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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_ref})\n")
|
||||
} else {
|
||||
format!("[Video file]({video_ref})\n")
|
||||
}
|
||||
}
|
||||
ExportBody::Audio(asset) => format!("[Audio file]({})\n", asset_ref(asset)),
|
||||
ExportBody::Image(asset) => {
|
||||
format!("\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 { mime_markdown, text } => {
|
||||
if *mime_markdown {
|
||||
format!("{text}\n")
|
||||
} else {
|
||||
fenced_plain_text(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_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
|
||||
}
|
||||
1198
crates/archivr-core/src/export/mod.rs
Normal file
1198
crates/archivr-core/src/export/mod.rs
Normal file
File diff suppressed because it is too large
Load diff
772
crates/archivr-core/src/export/model.rs
Normal file
772
crates/archivr-core/src/export/model.rs
Normal file
|
|
@ -0,0 +1,772 @@
|
|||
//! 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` and `.srt` assets in track order.
|
||||
pub subtitles: Vec<Asset>,
|
||||
/// Fonts extracted from a captured page.
|
||||
pub fonts: 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![],
|
||||
fonts: 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 font_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()),
|
||||
"font" => font_artifacts.push(artifact.clone()),
|
||||
_ => {} // favicon, etc.
|
||||
}
|
||||
}
|
||||
|
||||
// ----- subtitles -----
|
||||
let subtitles: Vec<Asset> = subtitle_artifacts
|
||||
.iter()
|
||||
.filter(|a| matches!(ext_of_s(&a.relpath).as_str(), "vtt" | "srt"))
|
||||
.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();
|
||||
|
||||
let fonts: Vec<Asset> = font_artifacts
|
||||
.iter()
|
||||
.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: font 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,
|
||||
fonts,
|
||||
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,
|
||||
};
|
||||
if !conversation_ids.insert(id.to_string()) {
|
||||
return;
|
||||
}
|
||||
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("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"")
|
||||
.replace("'", "'")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn thread_export_visits_each_post_once_when_replies_cycle() {
|
||||
for statuses in [
|
||||
vec![json!({"id_str": "1", "in_reply_to_status_id_str": "1"})],
|
||||
vec![
|
||||
json!({"id_str": "1", "in_reply_to_status_id_str": "2"}),
|
||||
json!({"id_str": "2", "in_reply_to_status_id_str": "1"}),
|
||||
],
|
||||
] {
|
||||
let status_map: HashMap<String, serde_json::Value> = statuses
|
||||
.iter()
|
||||
.map(|status| (tweet_id(status).unwrap(), status.clone()))
|
||||
.collect();
|
||||
let posts = build_thread(&statuses, &status_map, Some("1"), &HashMap::new());
|
||||
let unique_ids: HashSet<&str> = posts.iter().map(|post| post._id.as_str()).collect();
|
||||
|
||||
assert_eq!(posts.len(), statuses.len());
|
||||
assert_eq!(unique_ids.len(), statuses.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -14,3 +14,4 @@ pub mod text_title;
|
|||
pub mod transcriber;
|
||||
pub(crate) mod env_config;
|
||||
pub(crate) mod process;
|
||||
pub mod export;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ 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 captures."),
|
||||
spec("ARCHIVR_CHROME_ARGS", "tools", None, "Extra space-separated Chromium flags."),
|
||||
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."),
|
||||
|
|
|
|||
247
crates/archivr-server/src/exports.rs
Normal file
247
crates/archivr-server/src/exports.rs
Normal 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 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -68,10 +68,11 @@ async fn list_capture_jobs_handler(
|
|||
) -> Result<Json<Vec<archive::CaptureJobSummary>>, ApiError> {
|
||||
auth.require_role(ROLE_USER)?;
|
||||
if let Some(status) = q.status.as_deref()
|
||||
&& status != "active"
|
||||
&& !capture_jobs::JOB_STATUSES.contains(&status)
|
||||
{
|
||||
return Err(ApiError::bad_request(
|
||||
"invalid status: must be pending, running, completed, or failed",
|
||||
"invalid status: must be pending, running, completed, failed, or active",
|
||||
));
|
||||
}
|
||||
let limit = parse_int_param("limit", q.limit.as_deref())?
|
||||
|
|
@ -96,6 +97,12 @@ async fn list_capture_jobs_handler(
|
|||
};
|
||||
|
||||
let conn = database::open_or_initialize(&mounted.archive_path)?;
|
||||
if q.status.as_deref() == Some("active") {
|
||||
return Ok(Json(capture_jobs::list_active_capture_jobs(
|
||||
&conn,
|
||||
owner.as_deref(),
|
||||
)?));
|
||||
}
|
||||
Ok(Json(capture_jobs::list_capture_jobs(
|
||||
&conn,
|
||||
q.status.as_deref(),
|
||||
|
|
@ -725,4 +732,69 @@ mod tests {
|
|||
.unwrap();
|
||||
assert_eq!(body_json(resp).await[0]["archive_path"], expected.as_str());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_status_keeps_job_metadata_scoped_to_creator() {
|
||||
let f = fixture();
|
||||
let alice = make_role_session(&f.auth_path, "alice", &["user"]);
|
||||
let bob = make_role_session(&f.auth_path, "bob", &["user"]);
|
||||
let admin = admin_session(&f.auth_path);
|
||||
let alice_uid = user_uid(&f.auth_path, "alice");
|
||||
let bob_uid = user_uid(&f.auth_path, "bob");
|
||||
let base = "/api/archives/test/capture_jobs";
|
||||
|
||||
// Create active jobs for both users and a legacy job without a creator.
|
||||
let (alice_pending, bob_running, alice_completed, legacy_pending) = {
|
||||
let conn = database::open_or_initialize(&f.archive_path).unwrap();
|
||||
let a = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap();
|
||||
let b = database::create_capture_job_as(&conn, "test", Some(&bob_uid)).unwrap();
|
||||
let c = database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap();
|
||||
let legacy = database::create_capture_job(&conn, "test").unwrap();
|
||||
database::update_capture_job_status(&conn, &b, "running", None, None, None).unwrap();
|
||||
database::update_capture_job_status(&conn, &c, "completed", Some("run-x"), None, None).unwrap();
|
||||
database::update_capture_job_notes(
|
||||
&conn,
|
||||
&b,
|
||||
r#"{"locator":"https://private.example/?token=hidden"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
(a, b, c, legacy)
|
||||
};
|
||||
|
||||
// Alice cannot see Bob's locator or even his active job's existence.
|
||||
let (s, list) = get(&f.router, &format!("{base}?status=active"), Some(&alice)).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
assert_eq!(uids(&list), vec![alice_pending.clone()]);
|
||||
assert!(!list.to_string().contains("private.example"));
|
||||
|
||||
// Bob sees his own active job and its notes.
|
||||
let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&bob)).await;
|
||||
assert_eq!(uids(&list), vec![bob_running.clone()]);
|
||||
assert!(list.to_string().contains("private.example"));
|
||||
|
||||
// Explicit filters obey the same rule; admins can see all active jobs.
|
||||
let (s, _) = get(
|
||||
&f.router,
|
||||
&format!("{base}?status=active&created_by={bob_uid}"),
|
||||
Some(&alice),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::FORBIDDEN);
|
||||
let (_, list) = get(&f.router, &format!("{base}?status=active&created_by=all"), Some(&alice)).await;
|
||||
assert_eq!(uids(&list), vec![alice_pending.clone()]);
|
||||
let (_, list) = get(&f.router, &format!("{base}?status=active"), Some(&admin)).await;
|
||||
let visible = uids(&list);
|
||||
assert!(visible.contains(&alice_pending));
|
||||
assert!(visible.contains(&bob_running));
|
||||
assert!(visible.contains(&legacy_pending));
|
||||
assert!(!visible.contains(&alice_completed));
|
||||
|
||||
// Regular (non-active) status=pending still scopes to own jobs only.
|
||||
let (_, list) = get(&f.router, &format!("{base}?status=pending"), Some(&alice)).await;
|
||||
assert_eq!(uids(&list), vec![alice_pending]);
|
||||
|
||||
// Regular listing without status filter still scopes to own jobs only.
|
||||
let (_, list) = get(&f.router, base, Some(&bob)).await;
|
||||
assert_eq!(uids(&list), vec![bob_running]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
@ -1720,6 +1721,8 @@ async fn capture_handler(
|
|||
let conn = database::open_or_initialize(&mounted.archive_path)?;
|
||||
let created_by = jobs::caller_user_uid(&state, &auth_user)?;
|
||||
let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?;
|
||||
let locator_notes = serde_json::json!({"locator": locator}).to_string();
|
||||
database::update_capture_job_notes(&conn, &job_uid, &locator_notes).ok();
|
||||
drop(conn);
|
||||
// Load cookie rules and global uBlock / cookie-ext settings from the auth DB.
|
||||
let (cookie_rules, global_ublock, global_cookie_ext, global_modal_closer) = {
|
||||
|
|
@ -1887,6 +1890,8 @@ async fn capture_text_handler(
|
|||
let conn = database::open_or_initialize(&mounted.archive_path)?;
|
||||
let created_by = jobs::caller_user_uid(&state, &auth_user)?;
|
||||
let job_uid = database::create_capture_job_as(&conn, &archive_id, created_by.as_deref())?;
|
||||
let text_notes = serde_json::json!({"locator": format!("text:{}", body.title.trim())}).to_string();
|
||||
database::update_capture_job_notes(&conn, &job_uid, &text_notes).ok();
|
||||
drop(conn);
|
||||
|
||||
// Spawn background text capture.
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -6,8 +6,8 @@
|
|||
<title>Archivr</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||
<script type="module" crossorigin src="/assets/index-CKGxin5o.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CQKWq7vB.css">
|
||||
<script type="module" crossorigin src="/assets/index-B0u5xO9w.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-nzHmFByy.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useState, useEffect, useCallback, useRef, useMemo, createContext } from 'react'
|
||||
import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections } from './api'
|
||||
import { fetchArchives, fetchEntries, searchEntries, fetchRuns, fetchTags, checkSetup, fetchMe, fetchEntryDetail, listCollections, listActiveCaptureJobs } from './api'
|
||||
import LoginPage from './components/LoginPage.jsx'
|
||||
import SetupPage from './components/SetupPage.jsx'
|
||||
|
||||
|
|
@ -167,6 +167,48 @@ export default function App() {
|
|||
sessionStorage.setItem('pendingCaptures', JSON.stringify(pendingCaptures))
|
||||
}, [pendingCaptures])
|
||||
|
||||
// Active jobs this session didn't submit: other tabs for users, any user for admins.
|
||||
// Poll every 3 s so their in-progress skeletons stay visible here too.
|
||||
const [foreignCaptures, setForeignCaptures] = useState([])
|
||||
const pendingCapturesRef = useRef(pendingCaptures)
|
||||
useEffect(() => { pendingCapturesRef.current = pendingCaptures }, [pendingCaptures])
|
||||
const handleCapturedRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!archiveId || !currentUser) {
|
||||
setForeignCaptures([])
|
||||
return
|
||||
}
|
||||
// Track which foreign job UIDs were active on the last successful poll so we can
|
||||
// detect when they settle (disappear from the active list) and refresh entries.
|
||||
let prevForeignUids = new Set()
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const activeJobs = await listActiveCaptureJobs(archiveId)
|
||||
// Exclude jobs the current session is already tracking locally.
|
||||
const ownJobUids = new Set(pendingCapturesRef.current.map(c => c.jobUid))
|
||||
const foreign = activeJobs
|
||||
.filter(job => !ownJobUids.has(job.job_uid))
|
||||
.map(job => {
|
||||
let locator = ''
|
||||
try { locator = JSON.parse(job.notes_json || '{}').locator || '' } catch {}
|
||||
return { id: job.job_uid, jobUid: job.job_uid, locator, archiveId: job.archive_id }
|
||||
})
|
||||
setForeignCaptures(foreign)
|
||||
// If any previously-active foreign job no longer appears → it settled; refresh.
|
||||
const newUids = new Set(foreign.map(j => j.jobUid))
|
||||
const hadSettled = [...prevForeignUids].some(uid => !newUids.has(uid))
|
||||
if (hadSettled) handleCapturedRef.current?.()
|
||||
prevForeignUids = newUids
|
||||
} catch {}
|
||||
}
|
||||
|
||||
poll()
|
||||
const timer = setInterval(poll, 3000)
|
||||
return () => { clearInterval(timer); setForeignCaptures([]) }
|
||||
}, [archiveId, currentUser])
|
||||
|
||||
const [ublockWarningIgnored, setUblockWarningIgnored] = useState(
|
||||
() => sessionStorage.getItem('ublockWarningIgnored') === 'true'
|
||||
)
|
||||
|
|
@ -647,6 +689,7 @@ export default function App() {
|
|||
fetchRuns(archiveId).then(setRuns),
|
||||
])
|
||||
}, [archiveId, searchQuery, tagFilter, selectedCollectionUid, loadEntries])
|
||||
useEffect(() => { handleCapturedRef.current = handleCaptured }, [handleCaptured])
|
||||
|
||||
const handleToast = useCallback((text, locator, type = 'error', headline = null) => {
|
||||
// Only suppress per-item ublock/cookie warnings (those carry a locator).
|
||||
|
|
@ -798,6 +841,7 @@ export default function App() {
|
|||
onRowClick={handleRowClick}
|
||||
archiveId={archiveId}
|
||||
pendingCaptures={pendingCaptures}
|
||||
foreignCaptures={foreignCaptures}
|
||||
deletedUids={deletedUids}
|
||||
renamedTitles={renamedTitles}
|
||||
isPublicSession={!currentUser}
|
||||
|
|
|
|||
|
|
@ -334,6 +334,10 @@ export async function pollCaptureJob(archiveId, jobUid) {
|
|||
return getJson(`/api/archives/${archiveId}/capture_jobs/${jobUid}`);
|
||||
}
|
||||
|
||||
export async function listActiveCaptureJobs(archiveId) {
|
||||
return getJson(`/api/archives/${archiveId}/capture_jobs?status=active`);
|
||||
}
|
||||
|
||||
// ── Auth helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function checkSetup() {
|
||||
|
|
@ -733,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) => {
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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,17 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
</div>
|
||||
)}
|
||||
|
||||
<div className="rail-section">
|
||||
<div className="rail-section-heading">Actions</div>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
onClick={() => setExportOpen(true)}
|
||||
>
|
||||
{`Export ${selectedUids.size} entr${selectedUids.size === 1 ? 'y' : 'ies'}\u2026`}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="rail-delete-zone">
|
||||
<button
|
||||
className="rail-delete-btn"
|
||||
|
|
@ -1013,43 +1043,52 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
</div>
|
||||
)}
|
||||
|
||||
{detail && (detail.summary.entity_kind === 'tweet' || detail.summary.entity_kind === 'tweet_thread') && (
|
||||
<div className="rail-section">
|
||||
<div className="rail-section-heading">Actions</div>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
onClick={handleRearchive}
|
||||
disabled={rearchiveState === 'running'}
|
||||
>
|
||||
{rearchiveState === 'running' ? 'Re-archiving\u2026' : 'Re-archive'}
|
||||
</button>
|
||||
{rearchiveState === 'done' && (
|
||||
<p className="form-msg form-msg--ok" style={{ marginTop: '6px' }}>Re-archived successfully.</p>
|
||||
)}
|
||||
{rearchiveState === 'error' && (
|
||||
<p className="form-msg form-msg--err" style={{ marginTop: '6px' }}>{rearchiveError}</p>
|
||||
)}
|
||||
{detail.summary.entity_kind === 'tweet_thread' && (
|
||||
<>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
style={{ marginTop: '8px' }}
|
||||
onClick={handleGenerateThreadTitle}
|
||||
disabled={titleGenState === 'running'}
|
||||
title={`Names this thread with a small model via ${PROVIDER_LABEL[summaryProvider] || summaryProvider} (the Summary provider)`}
|
||||
>
|
||||
{titleGenState === 'running' ? 'Generating title\u2026' : 'Generate title'}
|
||||
</button>
|
||||
{titleGenState === 'done' && (
|
||||
<p className="form-msg form-msg--ok" style={{ marginTop: '6px' }}>Title updated.</p>
|
||||
)}
|
||||
{titleGenState === 'error' && (
|
||||
<p className="form-msg form-msg--err" style={{ marginTop: '6px' }}>{titleGenError}</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="rail-section">
|
||||
<div className="rail-section-heading">Actions</div>
|
||||
{detail && (detail.summary.entity_kind === 'tweet' || detail.summary.entity_kind === 'tweet_thread') && (
|
||||
<>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
onClick={handleRearchive}
|
||||
disabled={rearchiveState === 'running'}
|
||||
>
|
||||
{rearchiveState === 'running' ? 'Re-archiving\u2026' : 'Re-archive'}
|
||||
</button>
|
||||
{rearchiveState === 'done' && (
|
||||
<p className="form-msg form-msg--ok" style={{ marginTop: '6px' }}>Re-archived successfully.</p>
|
||||
)}
|
||||
{rearchiveState === 'error' && (
|
||||
<p className="form-msg form-msg--err" style={{ marginTop: '6px' }}>{rearchiveError}</p>
|
||||
)}
|
||||
{detail.summary.entity_kind === 'tweet_thread' && (
|
||||
<>
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
style={{ marginTop: '8px' }}
|
||||
onClick={handleGenerateThreadTitle}
|
||||
disabled={titleGenState === 'running'}
|
||||
title={`Names this thread with a small model via ${PROVIDER_LABEL[summaryProvider] || summaryProvider} (the Summary provider)`}
|
||||
>
|
||||
{titleGenState === 'running' ? 'Generating title\u2026' : 'Generate title'}
|
||||
</button>
|
||||
{titleGenState === 'done' && (
|
||||
<p className="form-msg form-msg--ok" style={{ marginTop: '6px' }}>Title updated.</p>
|
||||
)}
|
||||
{titleGenState === 'error' && (
|
||||
<p className="form-msg form-msg--err" style={{ marginTop: '6px' }}>{titleGenError}</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
className="rail-rearchive-btn"
|
||||
style={{ marginTop: detail && (detail.summary.entity_kind === 'tweet' || detail.summary.entity_kind === 'tweet_thread') ? '8px' : undefined }}
|
||||
onClick={() => setExportOpen(true)}
|
||||
>
|
||||
{'Export\u2026'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="rail-delete-zone">
|
||||
<button className="rail-delete-btn" onClick={handleDeleteEntry}>
|
||||
|
|
@ -1058,6 +1097,16 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se
|
|||
</div>
|
||||
</>
|
||||
)}
|
||||
<ExportDialog
|
||||
open={exportOpen && !isPublicSession}
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import SkeletonEntryRow from './SkeletonEntryRow';
|
|||
|
||||
import EntryRow from './EntryRow';
|
||||
|
||||
export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) {
|
||||
export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], foreignCaptures = [], deletedUids, renamedTitles, isPublicSession, canReorder = false, onChildReorderError }) {
|
||||
return (
|
||||
<section id="archive-view" className="view is-active">
|
||||
<div className="entry-table">
|
||||
|
|
@ -18,6 +18,9 @@ export default function EntriesView({ entries, selectedUids, onRowClick, archive
|
|||
{pendingCaptures.filter(c => c.archiveId === archiveId).reverse().map(cap => (
|
||||
<SkeletonEntryRow key={cap.id} locator={cap.locator} />
|
||||
))}
|
||||
{foreignCaptures.filter(c => c.archiveId === archiveId).map(cap => (
|
||||
<SkeletonEntryRow key={cap.id} locator={cap.locator} />
|
||||
))}
|
||||
{entries.map((entry, idx) => (
|
||||
<EntryRow
|
||||
key={entry.entry_uid}
|
||||
|
|
|
|||
175
frontend/src/components/ExportDialog.jsx
Normal file
175
frontend/src/components/ExportDialog.jsx
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
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="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>
|
||||
)
|
||||
}
|
||||
42
frontend/src/components/ExportDialog.test.jsx
Normal file
42
frontend/src/components/ExportDialog.test.jsx
Normal 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')
|
||||
})
|
||||
})
|
||||
|
|
@ -3629,3 +3629,6 @@ body.has-audio-bar { padding-bottom: 56px; }
|
|||
letter-spacing: .04em;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* ── Export ───────────────────────────────────────────────────────────────── */
|
||||
.export-dialog .export-format { width: 100%; margin: 4px 0 14px; }
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue