[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export

This commit is contained in:
2026-11-17 01:36:21 +01:00
parent 0b0e35d727
commit 8729119984
35 changed files with 7956 additions and 0 deletions
+311
View File
@@ -0,0 +1,311 @@
//! The `liber-export` format: one zip with `library.json` (the whole library), `books.csv`, `highlights/<book>.md`
//! and, on request, the original book files under `files/`. Importing `library.json` into an empty library gives
//! back exactly the same library (`ops_from`).
use crate::library::{Book, BookFile, Field, Library, Mark, Text};
use crate::{Event, Hlc, Op};
use liber_format::zip::ZipWriter;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::io::{self, Read, Write};
pub const FORMAT: &str = "liber-export";
pub const VERSION: u32 = 1;
pub const MAX_JSON: usize = 256 * 1024 * 1024;
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope {
format: String,
version: u32,
exported_at: String,
library: Library,
}
pub fn to_json(lib: &Library, exported_at: &str) -> String {
let env =
Envelope { format: FORMAT.into(), version: VERSION, exported_at: exported_at.into(), library: lib.clone() };
serde_json::to_string_pretty(&env).unwrap_or_default()
}
/// Reads `library.json`. The library it holds is checked by replaying it through events (`ops_from`), so whatever
/// the file says passes the same rules as every other change.
pub fn from_json(s: &str) -> Result<Library, String> {
if s.len() > MAX_JSON {
return Err("The export is larger than 256 MiB.".into());
}
let env: Envelope = serde_json::from_str(s).map_err(|e| format!("This is not a Liber export ({e})."))?;
if env.format != FORMAT || env.version != VERSION {
return Err(format!(
"This export is {} version {}; Liber reads {FORMAT} version {VERSION}.",
env.format, env.version
));
}
let events = events_from(&env.library, "restore", 0);
Ok(Library::from_events(&events))
}
/// The events that rebuild `lib` in an empty library, stamped from `device` starting at `wall`.
pub fn events_from(lib: &Library, device: &str, wall: u64) -> Vec<Event> {
ops_from(lib)
.into_iter()
.enumerate()
.map(|(i, op)| Event {
id: format!("{device}-{i}"),
hlc: Hlc { wall, logical: i as u32 },
device: device.into(),
op,
})
.collect()
}
fn text_ops(t: &Text, mut set: impl FnMut(String, Option<String>) -> Op) -> Vec<Op> {
match &t.conflict {
// The other version first, then the current one as a concurrent edit: the fold keeps both, as here.
Some(c) => vec![set(c.clone(), None), set(t.value.clone(), Some("restore-concurrent".into()))],
None if !t.value.is_empty() => vec![set(t.value.clone(), None)],
None => vec![],
}
}
pub fn ops_from(lib: &Library) -> Vec<Op> {
let mut ops = Vec::new();
for b in lib.books.values() {
let id = b.id.clone();
let set = |field: Field, value: serde_json::Value| Op::BookSet { book: id.clone(), field, value, base: None };
ops.push(Op::BookAdd { book: id.clone(), info: b.info.clone(), restore: true });
for f in &b.files {
ops.push(Op::BookFileAdd { book: id.clone(), file: f.clone() });
}
if b.paper {
ops.push(set(Field::Paper, json!(true)));
}
ops.push(set(Field::Possession, serde_json::to_value(&b.possession).unwrap_or_default()));
for s in &b.shelves {
ops.push(Op::ShelfAdd { book: id.clone(), shelf: s.clone() });
}
if let Some(r) = b.rating {
ops.push(set(Field::Rating, json!(r)));
}
ops.extend(text_ops(&b.review, |v, base| Op::BookSet {
book: id.clone(),
field: Field::Review,
value: json!(v),
base,
}));
ops.extend(text_ops(&b.notes, |v, base| Op::BookSet {
book: id.clone(),
field: Field::Notes,
value: json!(v),
base,
}));
if !b.moods.is_empty() {
ops.push(set(Field::Moods, json!(b.moods)));
}
if !b.tags.is_empty() {
ops.push(set(Field::Tags, json!(b.tags)));
}
if b.cover.is_some() {
ops.push(set(Field::Cover, json!(b.cover)));
}
for l in &b.loans {
ops.push(Op::Lend {
loan: l.id.clone(),
book: id.clone(),
person: l.person.clone(),
since: l.since.clone(),
due: l.due.clone(),
});
if let Some(d) = &l.returned {
ops.push(Op::Return { loan: l.id.clone(), date: d.clone() });
}
}
for r in &b.reads {
ops.push(Op::ReadStart { book: id.clone(), read: r.id.clone(), date: r.started.clone() });
if let Some(o) = r.outcome {
ops.push(Op::ReadEnd { read: r.id.clone(), date: r.finished.clone(), outcome: o });
}
}
if b.to_read {
ops.push(set(Field::ToRead, json!(true)));
}
let pos = |p: &crate::library::Position| Op::Position {
book: id.clone(),
cfi: p.cfi.clone(),
chapter: p.chapter,
progress: p.progress,
label: p.label.clone(),
};
if let Some(f) = &b.position {
ops.push(pos(f));
}
if let Some(l) = &b.last_position
&& Some(l) != b.position.as_ref()
{
ops.push(pos(l));
}
}
for h in lib.highlights.values() {
let (first, rest) = match &h.note.conflict {
Some(c) => (c.clone(), Some(h.note.value.clone())),
None => (h.note.value.clone(), None),
};
ops.push(Op::HighlightAdd {
id: h.id.clone(),
book: h.book.clone(),
kind: h.kind,
anchor: h.anchor.clone(),
colour: h.colour,
note: first,
created: h.created,
});
if let Some(v) = rest {
ops.push(Op::HighlightSet {
id: h.id.clone(),
colour: None,
note: Some(v),
base: Some("restore-concurrent".into()),
});
}
}
for s in lib.sessions.values() {
ops.push(Op::Session {
id: s.id.clone(),
book: s.book.clone(),
start: s.start,
end: s.end,
active_ms: s.active_ms,
pages: s.pages,
date: s.date.clone(),
});
}
for g in lib.goals.values() {
ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target });
}
ops
}
/// A spreadsheet cell that cannot run as a formula: a leading `= + - @`, tab or CR gets a `'`.
pub fn safe_cell(s: &str) -> String {
if s.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{s}") } else { s.to_owned() }
}
pub fn books_csv(lib: &Library) -> String {
let mut w = csv::Writer::from_writer(Vec::new());
let _ = w.write_record([
"id",
"title",
"authors",
"isbn13",
"status",
"possession",
"lent_to",
"shelves",
"rating_half_stars",
"pages",
"series",
"started",
"finished",
"moods",
"tags",
"review",
]);
for b in lib.books.values() {
let last = b.reads.last();
let possession = match &b.possession {
crate::Possession::Owned => "owned".to_owned(),
crate::Possession::Borrowed { from, .. } => format!("borrowed from {}", from.name),
crate::Possession::Wishlist => "wishlist".to_owned(),
crate::Possession::None => String::new(),
};
let row = [
b.id.clone(),
b.info.title.clone(),
b.info.authors.join("; "),
b.info.isbn13.clone().unwrap_or_default(),
serde_json::to_value(b.status()).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
possession,
b.lent_to().map(|l| l.person.name.clone()).unwrap_or_default(),
b.shelves.iter().cloned().collect::<Vec<_>>().join("; "),
b.rating.map(|r| r.to_string()).unwrap_or_default(),
b.info.pages.map(|p| p.to_string()).unwrap_or_default(),
b.info.series.as_ref().map(|s| s.name.clone()).unwrap_or_default(),
last.and_then(|r| r.started.clone()).unwrap_or_default(),
last.and_then(|r| r.finished.clone()).unwrap_or_default(),
b.moods.iter().cloned().collect::<Vec<_>>().join("; "),
b.tags.iter().cloned().collect::<Vec<_>>().join("; "),
b.review.value.clone(),
];
let _ = w.write_record(row.iter().map(|c| safe_cell(c)));
}
String::from_utf8(w.into_inner().unwrap_or_default()).unwrap_or_default()
}
/// A file name for a book: letters, digits, `-`, at most 60 characters, plus the id's start.
pub fn slug(b: &Book) -> String {
let mut s: String = b
.info
.title
.chars()
.map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
.collect::<String>()
.split('-')
.filter(|x| !x.is_empty())
.collect::<Vec<_>>()
.join("-");
s = s.chars().take(60).collect();
let id: String = b.id.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect();
if s.is_empty() { id } else { format!("{s}-{id}") }
}
pub fn highlights_markdown(lib: &Library, book: &str) -> String {
let Some(b) = lib.books.get(book) else { return String::new() };
let mut out = format!("# {}\n", b.info.title);
if !b.info.authors.is_empty() {
out.push_str(&format!("\n*{}*\n", b.info.authors.join(", ")));
}
let mut hs: Vec<_> = lib.highlights.values().filter(|h| h.book == b.id).collect();
hs.sort_by_key(|h| (h.anchor.get("chapter").and_then(|c| c.as_u64()).unwrap_or(0), h.created));
for h in hs {
let quote = h.anchor.pointer("/quote/exact").and_then(|q| q.as_str()).unwrap_or("");
out.push('\n');
match h.kind {
Mark::Bookmark => out.push_str("- Bookmark\n"),
_ if !quote.is_empty() => {
for line in quote.lines() {
out.push_str(&format!("> {line}\n"));
}
}
_ => {}
}
if !h.note.value.is_empty() {
out.push_str(&format!("\n{}\n", h.note.value));
}
if let Some(c) = &h.note.conflict {
out.push_str(&format!("\n(Other version: {c})\n"));
}
}
out
}
/// Gives a reader for a book file to include in the export, or `None` to leave it out.
pub type FileSource<'a> = dyn FnMut(&Book, &BookFile) -> Option<Box<dyn Read>> + 'a;
/// Writes the whole export. `file` returns a reader for a book file the person chose to include, or `None`.
pub fn write_zip<W: Write>(lib: &Library, w: W, exported_at: &str, file: &mut FileSource<'_>) -> io::Result<W> {
let mut z = ZipWriter::new(w);
z.add("library.json", to_json(lib, exported_at).as_bytes(), true)?;
z.add("books.csv", books_csv(lib).as_bytes(), true)?;
for b in lib.books.values() {
if lib.highlights.values().any(|h| h.book == b.id) {
z.add(&format!("highlights/{}.md", slug(b)), highlights_markdown(lib, &b.id).as_bytes(), true)?;
}
for f in &b.files {
if let Some(mut r) = file(b, f) {
let ext: String = f.format.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect();
z.add_stream(&format!("files/{}-{}.{ext}", slug(b), &f.sha256[..f.sha256.len().min(8)]), &mut r)?;
}
}
}
z.finish()
}