[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
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "liber-library"
description = "Liber Domi: book identity, the library model, the event log and its merge, stats, CSV import, export"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
liber-format.workspace = true
sha2.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
csv.workspace = true
[dev-dependencies]
proptest.workspace = true
encoding_rs.workspace = true
+160
View File
@@ -0,0 +1,160 @@
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// A hybrid logical clock value: wall milliseconds, then a counter.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Hlc {
pub wall: u64,
pub logical: u32,
}
/// One device's clock. `now_ms` is always a parameter.
#[derive(Clone, Debug, Default)]
pub struct Clock {
last: Hlc,
}
impl Clock {
pub fn tick(&mut self, now_ms: u64) -> Hlc {
self.last = if now_ms > self.last.wall {
Hlc { wall: now_ms, logical: 0 }
} else {
Hlc { wall: self.last.wall, logical: self.last.logical + 1 }
};
self.last
}
/// Takes in a clock value seen on another device, so later local events order after it.
pub fn observe(&mut self, seen: Hlc) {
if seen > self.last {
self.last = seen;
}
}
pub fn last(&self) -> Hlc {
self.last
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Event {
/// Unique: made by the device (random, or derived from the device and a counter).
pub id: String,
pub hlc: Hlc,
pub device: String,
pub op: Op,
}
impl Event {
/// The total order: clock, then device, then id.
pub fn order(&self, other: &Event) -> Ordering {
(self.hlc, &self.device, &self.id).cmp(&(other.hlc, &other.device, &other.id))
}
}
/// Every change Liber records. Unknown fields are refused, so an event from a newer schema is rejected rather than
/// half-applied.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Op {
/// `restore`: from an export, where two books may share an identity on purpose: never merge.
BookAdd {
book: String,
info: BookInfo,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
restore: bool,
},
/// `base`: the id of the event whose value the editor saw (`Library::version`). For text fields, a different
/// base means a concurrent edit: both versions are kept.
BookSet {
book: String,
field: Field,
value: serde_json::Value,
base: Option<String>,
},
BookRemove {
book: String,
},
BookFileAdd {
book: String,
file: BookFile,
},
BookFileRemove {
book: String,
sha256: String,
},
ShelfAdd {
book: String,
shelf: String,
},
ShelfRemove {
book: String,
shelf: String,
},
ReadStart {
book: String,
read: String,
date: Option<String>,
},
ReadEnd {
read: String,
date: Option<String>,
outcome: Outcome,
},
ReadRemove {
read: String,
},
Lend {
loan: String,
book: String,
person: Person,
since: String,
due: Option<String>,
},
Return {
loan: String,
date: String,
},
Position {
book: String,
cfi: String,
chapter: u32,
progress: f64,
label: Option<String>,
},
HighlightAdd {
id: String,
book: String,
kind: Mark,
anchor: serde_json::Value,
colour: Colour,
note: String,
created: u64,
},
HighlightSet {
id: String,
colour: Option<Colour>,
note: Option<String>,
base: Option<String>,
},
HighlightRemove {
id: String,
},
Session {
id: String,
book: String,
start: u64,
end: u64,
active_ms: u64,
pages: u32,
date: String,
},
Goal {
year: i32,
kind: GoalKind,
target: u32,
},
}
+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()
}
+439
View File
@@ -0,0 +1,439 @@
//! Goodreads and StoryGraph CSV import. Every row is imported or listed with its reason; columns Liber does not
//! map are kept on the book (`import_extra`) and named in the report. The CSV is hostile: the input and each field
//! are capped, values are stored as text and never evaluated.
use crate::library::{BookInfo, Field, Library, Outcome, Possession};
use crate::{MOODS, Op, isbn13, parse_date};
use serde::Serialize;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
pub const MAX_INPUT: usize = 32 * 1024 * 1024;
pub const MAX_FIELD: usize = 64 * 1024;
pub const MAX_ROWS: usize = 100_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
Goodreads,
StoryGraph,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Report {
pub source: Source,
pub rows: usize,
pub imported: usize,
/// (row number, 1-based after the header; why)
pub skipped: Vec<(usize, String)>,
/// Columns Liber does not know: their values are kept on each book.
pub unknown_columns: Vec<String>,
/// Columns Liber knows but does not use (also kept on each book).
pub unused_columns: Vec<String>,
/// (row, column) of fields cut at 64 KiB.
pub truncated: Vec<(usize, String)>,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ImportError {
#[error("The file is larger than 32 MiB, which is too large for a reading-list export.")]
TooLarge,
#[error("This is not a Goodreads or StoryGraph export (the header is not one Liber knows).")]
UnknownFormat,
#[error("The file is not valid CSV: {0}")]
Csv(String),
#[error("The file has more than 100,000 rows.")]
TooManyRows,
}
const GOODREADS_USED: &[&str] = &[
"Title",
"Author",
"Additional Authors",
"ISBN",
"ISBN13",
"My Rating",
"Publisher",
"Binding",
"Number of Pages",
"Year Published",
"Original Publication Year",
"Date Read",
"Date Added",
"Bookshelves",
"Exclusive Shelf",
"My Review",
"Private Notes",
"Read Count",
"Owned Copies",
];
const GOODREADS_UNUSED: &[&str] = &["Book Id", "Author l-f", "Average Rating", "Bookshelves with positions", "Spoiler"];
const STORYGRAPH_USED: &[&str] = &[
"Title",
"Authors",
"ISBN/UID",
"Format",
"Read Status",
"Date Added",
"Last Date Read",
"Dates Read",
"Read Count",
"Moods",
"Star Rating",
"Review",
"Tags",
"Owned?",
];
const STORYGRAPH_UNUSED: &[&str] = &[
"Contributors",
"Pace",
"Character- or Plot-Driven?",
"Strong Character Development?",
"Loveable Characters?",
"Diverse Characters?",
"Flawed Characters?",
"Content Warnings",
"Content Warning Description",
];
/// Goodreads writes `="0441172717"` so spreadsheets keep leading zeros.
fn unwrap_excel(s: &str) -> &str {
s.trim().strip_prefix("=\"").and_then(|x| x.strip_suffix('"')).unwrap_or(s.trim())
}
fn ms_of(date: &str) -> Option<u64> {
let d = parse_date(date)?;
let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?);
let days = crate::days_from_civil(y, m, dd);
(days >= 0).then(|| days as u64 * 86_400_000)
}
/// Goodreads reviews are HTML with `<br/>`.
fn review_text(s: &str) -> String {
let s = s.replace("<br/>", "\n").replace("<br />", "\n").replace("<br>", "\n");
let mut out = String::new();
let mut tag = false;
for c in s.chars() {
match c {
'<' => tag = true,
'>' if tag => tag = false,
c if !tag => out.push(c),
_ => {}
}
}
out.trim().to_owned()
}
fn list(s: &str) -> Vec<String> {
s.split(',').map(|x| x.trim().to_owned()).filter(|x| !x.is_empty()).collect()
}
fn norm_key(title: &str, author: &str) -> String {
let f = |s: &str| s.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect::<String>();
format!("{}|{}", f(title), f(author))
}
struct Row<'a> {
cols: &'a [String],
vals: Vec<String>,
}
impl Row<'_> {
fn get(&self, c: &str) -> &str {
self.cols.iter().position(|x| x == c).and_then(|i| self.vals.get(i)).map(|s| s.trim()).unwrap_or("")
}
}
/// Parses an export into events. `new_id` makes ids (books, reads); `now_ms` is the fallback "added" time.
pub fn import_csv(
bytes: &[u8],
existing: &Library,
new_id: &mut dyn FnMut() -> String,
now_ms: u64,
) -> Result<(Vec<Op>, Report), ImportError> {
if bytes.len() > MAX_INPUT {
return Err(ImportError::TooLarge);
}
let (text, _) = liber_format::text::decode_text(bytes);
let mut rdr = csv::ReaderBuilder::new().flexible(true).has_headers(true).from_reader(text.as_bytes());
let cols: Vec<String> = rdr
.headers()
.map_err(|e| ImportError::Csv(e.to_string()))?
.iter()
.map(|h| h.trim().trim_start_matches('\u{feff}').to_owned())
.collect();
let has = |c: &str| cols.iter().any(|x| x == c);
let source = if has("Exclusive Shelf") && has("Title") {
Source::Goodreads
} else if has("Read Status") && has("Title") {
Source::StoryGraph
} else {
return Err(ImportError::UnknownFormat);
};
let (used, unused) = match source {
Source::Goodreads => (GOODREADS_USED, GOODREADS_UNUSED),
Source::StoryGraph => (STORYGRAPH_USED, STORYGRAPH_UNUSED),
};
let mut report = Report {
source,
rows: 0,
imported: 0,
skipped: vec![],
unknown_columns: cols
.iter()
.filter(|c| !c.is_empty() && !used.contains(&c.as_str()) && !unused.contains(&c.as_str()))
.cloned()
.collect(),
unused_columns: cols.iter().filter(|c| unused.contains(&c.as_str())).cloned().collect(),
truncated: vec![],
};
let mut seen: BTreeSet<String> = existing
.books
.values()
.map(|b| norm_key(&b.info.title, b.info.authors.first().map(String::as_str).unwrap_or("")))
.collect();
let mut seen_isbn: BTreeSet<String> = existing.books.values().filter_map(|b| b.info.isbn13.clone()).collect();
let mut ops = Vec::new();
for (i, rec) in rdr.records().enumerate() {
let n = i + 1;
if n > MAX_ROWS {
return Err(ImportError::TooManyRows);
}
report.rows += 1;
let rec = match rec {
Ok(r) => r,
Err(e) => {
report.skipped.push((n, format!("not valid CSV: {e}")));
continue;
}
};
let mut vals = Vec::with_capacity(rec.len());
for (ci, v) in rec.iter().enumerate() {
if v.len() > MAX_FIELD {
let mut end = MAX_FIELD;
while !v.is_char_boundary(end) {
end -= 1;
}
report.truncated.push((n, cols.get(ci).cloned().unwrap_or_default()));
vals.push(v[..end].to_owned());
} else {
vals.push(v.to_owned());
}
}
let row = Row { cols: &cols, vals };
let title = row.get("Title").to_owned();
if title.is_empty() {
report.skipped.push((n, "no title".into()));
continue;
}
let mut extra = BTreeMap::new();
for (ci, c) in cols.iter().enumerate() {
if !used.contains(&c.as_str()) && !c.is_empty() {
let v = row.vals.get(ci).map(|s| s.trim()).unwrap_or("");
if !v.is_empty() {
let prefix = match source {
Source::Goodreads => "goodreads",
Source::StoryGraph => "storygraph",
};
extra.insert(format!("{prefix}:{c}"), v.to_owned());
}
}
}
let r = match source {
Source::Goodreads => goodreads(&row, extra, now_ms),
Source::StoryGraph => storygraph(&row, extra, now_ms),
};
let author = r.info.authors.first().cloned().unwrap_or_default();
let key = norm_key(&r.info.title, &author);
if r.info.isbn13.as_ref().is_some_and(|i| seen_isbn.contains(i)) || seen.contains(&key) {
report.skipped.push((n, format!("“{}” is already in your library", r.info.title)));
continue;
}
seen.insert(key);
if let Some(i) = &r.info.isbn13 {
seen_isbn.insert(i.clone());
}
let book = new_id();
ops.push(Op::BookAdd { book: book.clone(), info: r.info, restore: false });
let set = |field: Field, value: serde_json::Value| Op::BookSet { book: book.clone(), field, value, base: None };
if let Some(rt) = r.rating {
ops.push(set(Field::Rating, json!(rt)));
}
if !r.review.is_empty() {
ops.push(set(Field::Review, json!(r.review)));
}
if !r.notes.is_empty() {
ops.push(set(Field::Notes, json!(r.notes)));
}
if r.owned {
ops.push(set(Field::Possession, serde_json::to_value(Possession::Owned).unwrap_or_default()));
}
if r.paper {
ops.push(set(Field::Paper, json!(true)));
}
if !r.moods.is_empty() {
ops.push(set(Field::Moods, json!(r.moods)));
}
if !r.tags.is_empty() {
ops.push(set(Field::Tags, json!(r.tags)));
}
if r.to_read {
ops.push(set(Field::ToRead, json!(true)));
}
for s in r.shelves {
ops.push(Op::ShelfAdd { book: book.clone(), shelf: s });
}
for (start, end, outcome) in r.reads {
let read = new_id();
ops.push(Op::ReadStart { book: book.clone(), read: read.clone(), date: start });
if let Some(o) = outcome {
ops.push(Op::ReadEnd { read, date: end, outcome: o });
}
}
report.imported += 1;
}
Ok((ops, report))
}
struct Parsed {
info: BookInfo,
rating: Option<u8>,
review: String,
notes: String,
owned: bool,
paper: bool,
moods: BTreeSet<String>,
tags: BTreeSet<String>,
to_read: bool,
shelves: Vec<String>,
/// (started, finished, outcome)
reads: Vec<(Option<String>, Option<String>, Option<Outcome>)>,
}
fn paper_binding(b: &str) -> bool {
let b = b.to_lowercase();
["paperback", "hardcover", "mass market", "hardback", "board book", "library binding", "leather", "spiral"]
.iter()
.any(|p| b.contains(p))
}
fn goodreads(row: &Row, extra: BTreeMap<String, String>, now_ms: u64) -> Parsed {
let mut authors = vec![row.get("Author").to_owned()];
authors.extend(list(row.get("Additional Authors")));
authors.retain(|a| !a.is_empty());
let isbn = isbn13(unwrap_excel(row.get("ISBN13"))).or_else(|| isbn13(unwrap_excel(row.get("ISBN"))));
let published = [row.get("Original Publication Year"), row.get("Year Published")]
.iter()
.find(|y| !y.is_empty())
.map(|y| y.to_string());
let rating: u8 = row.get("My Rating").parse().unwrap_or(0);
let exclusive = row.get("Exclusive Shelf").to_owned();
let mut shelves: Vec<String> = list(row.get("Bookshelves"))
.into_iter()
.filter(|s| !matches!(s.as_str(), "read" | "currently-reading" | "to-read"))
.collect();
let read_count: usize = row.get("Read Count").parse().unwrap_or(0);
let date_read = parse_date(row.get("Date Read"));
let mut reads = Vec::new();
let mut to_read = false;
match exclusive.as_str() {
"read" => {
for _ in 1..read_count.clamp(1, 50) {
reads.push((None, None, Some(Outcome::Read)));
}
reads.push((None, date_read.clone(), Some(Outcome::Read)));
}
"currently-reading" => reads.push((None, None, None)),
"to-read" => to_read = true,
other if !other.is_empty() && !shelves.iter().any(|s| s == other) => {
shelves.push(other.to_owned());
}
_ => {}
}
Parsed {
info: BookInfo {
title: row.get("Title").to_owned(),
authors,
isbn13: isbn,
publisher: Some(row.get("Publisher").to_owned()).filter(|s| !s.is_empty()),
published,
pages: row.get("Number of Pages").parse().ok().filter(|p| *p > 0),
added: ms_of(row.get("Date Added")).unwrap_or(now_ms),
import_extra: extra,
..BookInfo::default()
},
rating: (1..=5).contains(&rating).then_some(rating * 2),
review: review_text(row.get("My Review")),
notes: row.get("Private Notes").to_owned(),
owned: row.get("Owned Copies").parse::<u32>().unwrap_or(0) > 0,
paper: paper_binding(row.get("Binding")),
moods: BTreeSet::new(),
tags: BTreeSet::new(),
to_read,
shelves,
reads,
}
}
fn storygraph(row: &Row, extra: BTreeMap<String, String>, now_ms: u64) -> Parsed {
let uid = row.get("ISBN/UID");
let star: f64 = row.get("Star Rating").parse().unwrap_or(0.0);
let rating = (star > 0.0 && star <= 5.0).then(|| ((star * 2.0).round() as u8).clamp(1, 10));
let status = row.get("Read Status").to_lowercase();
let mut reads = Vec::new();
for range in list(row.get("Dates Read")) {
let (a, b) =
range.split_once('-').map(|(a, b)| (parse_date(a), parse_date(b))).unwrap_or((None, parse_date(&range)));
reads.push((a, b, Some(Outcome::Read)));
}
let mut to_read = false;
match status.as_str() {
"read" if reads.is_empty() => {
let n: usize = row.get("Read Count").parse().unwrap_or(1);
for i in 0..n.clamp(1, 50) {
let last = (i + 1 == n.max(1)).then(|| parse_date(row.get("Last Date Read"))).flatten();
reads.push((None, last, Some(Outcome::Read)));
}
}
"read" => {}
"currently-reading" | "paused" => reads.push((None, None, None)),
"did-not-finish" => reads.push((None, parse_date(row.get("Last Date Read")), Some(Outcome::DidNotFinish))),
"to-read" => to_read = true,
_ => {}
}
let mut moods = BTreeSet::new();
let mut tags: BTreeSet<String> = list(row.get("Tags")).into_iter().collect();
for m in list(row.get("Moods")) {
let l = m.to_lowercase();
if MOODS.contains(&l.as_str()) {
moods.insert(l);
} else {
tags.insert(m);
}
}
let mut info = BookInfo {
title: row.get("Title").to_owned(),
authors: list(row.get("Authors")),
isbn13: isbn13(uid),
added: ms_of(row.get("Date Added")).unwrap_or(now_ms),
import_extra: extra,
..BookInfo::default()
};
if info.isbn13.is_none() && !uid.is_empty() {
info.import_extra.insert("storygraph:ISBN/UID".into(), uid.to_owned());
}
let format = row.get("Format").to_lowercase();
Parsed {
info,
rating,
review: row.get("Review").to_owned(),
notes: String::new(),
owned: matches!(row.get("Owned?").to_lowercase().as_str(), "yes" | "true"),
paper: format.contains("paperback") || format.contains("hardcover"),
moods,
tags,
to_read,
shelves: vec![],
reads,
}
}
+84
View File
@@ -0,0 +1,84 @@
//! Liber's library (docs in the app repo, `docs/01_books.md`): the model, the event log and its merge, stats,
//! Goodreads/StoryGraph import and the `liber-export` format. Pure: time, ids and devices are parameters.
//!
//! Every change is an [`Event`]; the [`Library`] is a fold of the events in their total order
//! (hybrid logical clock, then device, then id). Two devices holding the same events hold the same library,
//! whatever order the events arrived in: that is the whole sync guarantee.
pub mod event;
pub mod export;
pub mod import;
pub mod library;
pub mod stats;
pub use event::{Clock, Event, Hlc, Op};
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
pub use liber_format::text::isbn13;
/// StoryGraph's moods: Liber's fixed mood list (own tags are separate).
pub const MOODS: &[&str] = &[
"adventurous",
"challenging",
"dark",
"emotional",
"funny",
"hopeful",
"informative",
"inspiring",
"lighthearted",
"mysterious",
"reflective",
"relaxing",
"sad",
"tense",
];
/// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm).
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (m as i64 + 9) % 12;
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// `YYYY-MM-DD` (or `YYYY/MM/DD`) → `YYYY-MM-DD`, checked.
pub fn parse_date(s: &str) -> Option<String> {
let s = s.trim();
let parts: Vec<&str> = s.split(['-', '/']).collect();
if parts.len() != 3 {
return None;
}
let y: i32 = parts[0].parse().ok()?;
let m: u32 = parts[1].parse().ok()?;
let d: u32 = parts[2].parse().ok()?;
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
let dim = [
31,
if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
if d > dim[(m - 1) as usize] {
return None;
}
Some(format!("{y:04}-{m:02}-{d:02}"))
}
/// The year of a `YYYY-MM-DD` date.
pub fn year_of(date: &str) -> Option<i32> {
date.get(..4)?.parse().ok()
}
+660
View File
@@ -0,0 +1,660 @@
//! The library as a fold of events (see `lib.rs`): books and their states, shelves, reads, loans, positions,
//! highlights, reading sessions and goals.
use crate::event::{Event, Op};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
/// Someone from the people directory (`id`), or a plain name until it is wired.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
pub id: Option<String>,
pub name: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Series {
pub name: String,
pub index: Option<f64>,
}
/// What is known about a book when it is added.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BookInfo {
pub title: String,
pub authors: Vec<String>,
pub isbn13: Option<String>,
/// The text fingerprint of an e-book (liber-format), for merging the same book from two sources.
pub fingerprint: Option<String>,
pub series: Option<Series>,
pub language: Option<String>,
pub publisher: Option<String>,
pub published: Option<String>,
pub description: Option<String>,
pub pages: Option<u32>,
pub genres: Vec<String>,
/// Unix ms, given by the device.
pub added: u64,
/// Columns an import did not map, kept rather than dropped.
pub import_extra: BTreeMap<String, String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookFile {
pub sha256: String,
pub format: String,
pub size: u64,
pub name: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Possession {
Owned,
Borrowed {
from: Person,
due: Option<String>,
},
Wishlist,
#[default]
None,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Read,
DidNotFinish,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReadStatus {
ToRead,
Reading,
Read,
DidNotFinish,
None,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Read {
pub id: String,
pub started: Option<String>,
pub finished: Option<String>,
pub outcome: Option<Outcome>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Loan {
pub id: String,
pub person: Person,
pub since: String,
pub due: Option<String>,
pub returned: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Position {
pub cfi: String,
pub chapter: u32,
pub progress: f64,
pub label: Option<String>,
}
/// A text field that may hold two versions after concurrent edits on two devices.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Text {
pub value: String,
/// The other version, shown with a marker until someone edits the field again.
pub conflict: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Field {
Title,
Authors,
Series,
Language,
Publisher,
Published,
Description,
Pages,
Isbn13,
Genres,
Paper,
Possession,
Rating,
Review,
Notes,
Moods,
Tags,
ToRead,
Cover,
}
impl Field {
fn key(self) -> &'static str {
match self {
Field::Title => "title",
Field::Authors => "authors",
Field::Series => "series",
Field::Language => "language",
Field::Publisher => "publisher",
Field::Published => "published",
Field::Description => "description",
Field::Pages => "pages",
Field::Isbn13 => "isbn13",
Field::Genres => "genres",
Field::Paper => "paper",
Field::Possession => "possession",
Field::Rating => "rating",
Field::Review => "review",
Field::Notes => "notes",
Field::Moods => "moods",
Field::Tags => "tags",
Field::ToRead => "to_read",
Field::Cover => "cover",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mark {
Highlight,
Note,
Bookmark,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Colour {
Yellow,
Green,
Blue,
Pink,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GoalKind {
Books,
Pages,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Book {
pub id: String,
pub info: BookInfo,
pub files: Vec<BookFile>,
pub paper: bool,
pub possession: Possession,
pub loans: Vec<Loan>,
pub reads: Vec<Read>,
pub to_read: bool,
pub shelves: BTreeSet<String>,
/// Half stars, 1–10.
pub rating: Option<u8>,
pub review: Text,
pub notes: Text,
pub moods: BTreeSet<String>,
pub tags: BTreeSet<String>,
/// A blob reference (the cover image's sha256).
pub cover: Option<String>,
/// The furthest position reached on any device.
pub position: Option<Position>,
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
pub last_position: Option<Position>,
}
impl Book {
fn new(id: &str, info: BookInfo) -> Book {
Book {
id: id.to_owned(),
info,
files: vec![],
paper: false,
possession: Possession::None,
loans: vec![],
reads: vec![],
to_read: false,
shelves: BTreeSet::new(),
rating: None,
review: Text::default(),
notes: Text::default(),
moods: BTreeSet::new(),
tags: BTreeSet::new(),
cover: None,
position: None,
last_position: None,
}
}
pub fn status(&self) -> ReadStatus {
match self.reads.last() {
Some(r) => match r.outcome {
None => ReadStatus::Reading,
Some(Outcome::Read) => ReadStatus::Read,
Some(Outcome::DidNotFinish) => ReadStatus::DidNotFinish,
},
None if self.to_read => ReadStatus::ToRead,
None => ReadStatus::None,
}
}
/// The loan that is out now.
pub fn lent_to(&self) -> Option<&Loan> {
self.loans.iter().find(|l| l.returned.is_none())
}
/// The position to offer "Jump back to …" for.
pub fn jump_back(&self) -> Option<&Position> {
let (Some(f), Some(l)) = (&self.position, &self.last_position) else { return None };
(l.progress + 1e-9 < f.progress).then_some(l)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Highlight {
pub id: String,
pub book: String,
pub kind: Mark,
/// A `liber_format::Anchor` (or a page for PDFs), opaque here.
pub anchor: serde_json::Value,
pub colour: Colour,
pub note: Text,
pub created: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Session {
pub id: String,
pub book: String,
pub start: u64,
pub end: u64,
pub active_ms: u64,
pub pages: u32,
/// The local day it counts for (`YYYY-MM-DD`, from the device).
pub date: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Goal {
pub year: i32,
pub kind: GoalKind,
pub target: u32,
}
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Library {
pub books: BTreeMap<String, Book>,
pub highlights: BTreeMap<String, Highlight>,
pub sessions: BTreeMap<String, Session>,
pub goals: BTreeMap<i32, Goal>,
#[serde(skip)]
aliases: BTreeMap<String, String>,
#[serde(skip)]
versions: BTreeMap<(String, &'static str), String>,
#[serde(skip)]
removed_books: BTreeSet<String>,
#[serde(skip)]
removed_highlights: BTreeSet<String>,
#[serde(skip)]
read_book: BTreeMap<String, String>,
#[serde(skip)]
loan_book: BTreeMap<String, String>,
}
impl PartialEq for Library {
fn eq(&self, o: &Library) -> bool {
self.books == o.books && self.highlights == o.highlights && self.sessions == o.sessions && self.goals == o.goals
}
}
/// Field values longer than this are cut (a review, a note).
pub const MAX_TEXT: usize = 64 * 1024;
fn clip(s: String) -> String {
if s.len() <= MAX_TEXT {
return s;
}
let mut end = MAX_TEXT;
while !s.is_char_boundary(end) {
end -= 1;
}
s[..end].to_owned()
}
impl Library {
/// Folds events in their total order.
pub fn from_events<'a>(events: impl IntoIterator<Item = &'a Event>) -> Library {
let mut v: Vec<&Event> = events.into_iter().collect();
v.sort_by(|a, b| a.order(b));
v.dedup_by(|a, b| a.id == b.id);
let mut lib = Library::default();
for e in v {
lib.apply(e);
}
lib
}
/// The canonical id of a book (after identity merges).
pub fn canonical(&self, id: &str) -> String {
let mut cur = id.to_owned();
for _ in 0..64 {
match self.aliases.get(&cur) {
Some(n) => cur = n.clone(),
None => break,
}
}
cur
}
/// The event id that last set a field (the `base` for the next edit).
pub fn version(&self, book: &str, field: Field) -> Option<&str> {
self.versions.get(&(self.canonical(book), field.key())).map(String::as_str)
}
pub fn highlight_version(&self, id: &str) -> Option<&str> {
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
}
/// An existing book with the same identity: ISBN-13, else text fingerprint.
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
if let Some(i) = isbn13
&& let Some(b) = self.books.values().find(|b| b.info.isbn13.as_deref() == Some(i))
{
return Some(b);
}
if let Some(f) = fingerprint {
return self.books.values().find(|b| b.info.fingerprint.as_deref() == Some(f));
}
None
}
fn book_mut(&mut self, id: &str) -> Option<&mut Book> {
let c = self.canonical(id);
self.books.get_mut(&c)
}
fn set_text(
versions: &mut BTreeMap<(String, &'static str), String>,
key: (String, &'static str),
t: &mut Text,
value: String,
base: &Option<String>,
event: &str,
) {
let current = versions.get(&key);
let concurrent = current.is_some() && base.as_deref() != current.map(String::as_str) && t.value != value;
if concurrent {
t.conflict = Some(std::mem::replace(&mut t.value, clip(value)));
} else {
t.value = clip(value);
t.conflict = None;
}
versions.insert(key, event.to_owned());
}
pub fn apply(&mut self, e: &Event) {
match &e.op {
Op::BookAdd { book, info, restore } => {
if self.removed_books.contains(book) || self.books.contains_key(book) || self.aliases.contains_key(book)
{
return;
}
let isbn = info.isbn13.as_deref().and_then(crate::isbn13);
let mut info = info.clone();
info.isbn13 = isbn;
info.title = clip(info.title);
info.description = info.description.map(clip);
let same = if *restore {
None
} else {
self.find_identity(info.isbn13.as_deref(), info.fingerprint.as_deref()).map(|b| b.id.clone())
};
match same {
Some(existing) => {
self.aliases.insert(book.clone(), existing.clone());
if let Some(b) = self.books.get_mut(&existing) {
let i = &mut b.info;
if i.isbn13.is_none() {
i.isbn13 = info.isbn13;
}
if i.fingerprint.is_none() {
i.fingerprint = info.fingerprint;
}
if i.pages.is_none() {
i.pages = info.pages;
}
if i.series.is_none() {
i.series = info.series;
}
for (k, v) in info.import_extra {
i.import_extra.entry(k).or_insert(v);
}
}
}
None => {
self.books.insert(book.clone(), Book::new(book, info));
}
}
}
Op::BookRemove { book } => {
let c = self.canonical(book);
self.books.remove(&c);
self.removed_books.insert(c.clone());
self.highlights.retain(|_, h| h.book != c);
}
Op::BookSet { book, field, value, base } => {
let c = self.canonical(book);
let key = (c.clone(), field.key());
let Some(b) = self.books.get_mut(&c) else { return };
let s = |v: &serde_json::Value| v.as_str().map(|s| clip(s.to_owned()));
let set_of = |v: &serde_json::Value| -> Option<BTreeSet<String>> {
serde_json::from_value::<BTreeSet<String>>(v.clone())
.ok()
.map(|s| s.into_iter().take(256).map(clip).collect())
};
let ok = match field {
Field::Review | Field::Notes => {
let Some(v) = s(value) else { return };
let t = if *field == Field::Review { &mut b.review } else { &mut b.notes };
Self::set_text(&mut self.versions, key, t, v, base, &e.id);
return;
}
Field::Title => s(value).filter(|t| !t.is_empty()).map(|t| b.info.title = t).is_some(),
Field::Authors => {
serde_json::from_value::<Vec<String>>(value.clone()).map(|a| b.info.authors = a).is_ok()
}
Field::Series => {
serde_json::from_value::<Option<Series>>(value.clone()).map(|v| b.info.series = v).is_ok()
}
Field::Language => serde_json::from_value(value.clone()).map(|v| b.info.language = v).is_ok(),
Field::Publisher => serde_json::from_value(value.clone()).map(|v| b.info.publisher = v).is_ok(),
Field::Published => serde_json::from_value(value.clone()).map(|v| b.info.published = v).is_ok(),
Field::Description => serde_json::from_value::<Option<String>>(value.clone())
.map(|v| b.info.description = v.map(clip))
.is_ok(),
Field::Pages => serde_json::from_value(value.clone()).map(|v| b.info.pages = v).is_ok(),
Field::Isbn13 => serde_json::from_value::<Option<String>>(value.clone())
.map(|v| b.info.isbn13 = v.as_deref().and_then(crate::isbn13))
.is_ok(),
Field::Genres => serde_json::from_value(value.clone()).map(|v| b.info.genres = v).is_ok(),
Field::Paper => value.as_bool().map(|v| b.paper = v).is_some(),
Field::Possession => serde_json::from_value(value.clone()).map(|v| b.possession = v).is_ok(),
Field::Rating => serde_json::from_value::<Option<u8>>(value.clone())
.ok()
.map(|v| b.rating = v.filter(|r| (1..=10).contains(r)))
.is_some(),
Field::Moods => set_of(value).map(|v| b.moods = v).is_some(),
Field::Tags => set_of(value).map(|v| b.tags = v).is_some(),
Field::ToRead => value.as_bool().map(|v| b.to_read = v).is_some(),
Field::Cover => serde_json::from_value(value.clone()).map(|v| b.cover = v).is_ok(),
};
if ok {
self.versions.insert(key, e.id.clone());
}
}
Op::BookFileAdd { book, file } => {
if let Some(b) = self.book_mut(book)
&& !b.files.iter().any(|f| f.sha256 == file.sha256)
{
b.files.push(file.clone());
}
}
Op::BookFileRemove { book, sha256 } => {
if let Some(b) = self.book_mut(book) {
b.files.retain(|f| f.sha256 != *sha256);
}
}
Op::ShelfAdd { book, shelf } => {
if let Some(b) = self.book_mut(book)
&& !shelf.trim().is_empty()
&& b.shelves.len() < 256
{
b.shelves.insert(clip(shelf.trim().to_owned()));
}
}
Op::ShelfRemove { book, shelf } => {
if let Some(b) = self.book_mut(book) {
b.shelves.remove(shelf.trim());
}
}
Op::ReadStart { book, read, date } => {
let c = self.canonical(book);
if self.read_book.contains_key(read) {
return;
}
if let Some(b) = self.books.get_mut(&c) {
b.reads.push(Read { id: read.clone(), started: date.clone(), finished: None, outcome: None });
b.to_read = false;
self.read_book.insert(read.clone(), c);
}
}
Op::ReadEnd { read, date, outcome } => {
if let Some(c) = self.read_book.get(read).cloned()
&& let Some(b) = self.books.get_mut(&c)
&& let Some(r) = b.reads.iter_mut().find(|r| r.id == *read)
{
r.finished = date.clone();
r.outcome = Some(*outcome);
}
}
Op::ReadRemove { read } => {
if let Some(c) = self.read_book.get(read).cloned()
&& let Some(b) = self.books.get_mut(&c)
{
b.reads.retain(|r| r.id != *read);
}
}
Op::Lend { loan, book, person, since, due } => {
let c = self.canonical(book);
if self.loan_book.contains_key(loan) {
return;
}
if let Some(b) = self.books.get_mut(&c) {
b.loans.push(Loan {
id: loan.clone(),
person: person.clone(),
since: since.clone(),
due: due.clone(),
returned: None,
});
self.loan_book.insert(loan.clone(), c);
}
}
Op::Return { loan, date } => {
if let Some(c) = self.loan_book.get(loan).cloned()
&& let Some(b) = self.books.get_mut(&c)
&& let Some(l) = b.loans.iter_mut().find(|l| l.id == *loan)
&& l.returned.is_none()
{
l.returned = Some(date.clone());
}
}
Op::Position { book, cfi, chapter, progress, label } => {
if !progress.is_finite() {
return;
}
let p = Position {
cfi: cfi.clone(),
chapter: *chapter,
progress: progress.clamp(0.0, 1.0),
label: label.clone(),
};
if let Some(b) = self.book_mut(book) {
if b.position.as_ref().is_none_or(|f| p.progress >= f.progress) {
b.position = Some(p.clone());
}
b.last_position = Some(p);
}
}
Op::HighlightAdd { id, book, kind, anchor, colour, note, created } => {
if self.removed_highlights.contains(id) || self.highlights.contains_key(id) {
return;
}
let c = self.canonical(book);
if !self.books.contains_key(&c) {
return;
}
self.highlights.insert(
id.clone(),
Highlight {
id: id.clone(),
book: c,
kind: *kind,
anchor: anchor.clone(),
colour: *colour,
note: Text { value: clip(note.clone()), conflict: None },
created: *created,
},
);
self.versions.insert((format!("hl:{id}"), "note"), e.id.clone());
}
Op::HighlightSet { id, colour, note, base } => {
let Some(h) = self.highlights.get_mut(id) else { return };
if let Some(c) = colour {
h.colour = *c;
}
if let Some(n) = note {
Self::set_text(
&mut self.versions,
(format!("hl:{id}"), "note"),
&mut h.note,
n.clone(),
base,
&e.id,
);
}
}
Op::HighlightRemove { id } => {
self.highlights.remove(id);
self.removed_highlights.insert(id.clone());
}
Op::Session { id, book, start, end, active_ms, pages, date } => {
let c = self.canonical(book);
if self.books.contains_key(&c) && end >= start {
self.sessions.entry(id.clone()).or_insert(Session {
id: id.clone(),
book: c,
start: *start,
end: *end,
active_ms: (*active_ms).min(end - start),
pages: *pages,
date: date.clone(),
});
}
}
Op::Goal { year, kind, target } => {
self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target });
}
}
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Reading stats per year and all time (no comparison with anyone).
use crate::library::{Goal, GoalKind, Library, Outcome};
use crate::year_of;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Stats {
/// `None`: all time.
pub year: Option<i32>,
pub books: u32,
pub did_not_finish: u32,
/// Pages of the books finished (from their page counts).
pub pages: u64,
pub active_minutes: u64,
/// Pages turned in sessions per active hour.
pub pace: Option<f64>,
pub moods: BTreeMap<String, u32>,
pub genres: BTreeMap<String, u32>,
/// (book id, pages)
pub longest: Option<(String, u32)>,
pub shortest: Option<(String, u32)>,
pub goal: Option<GoalProgress>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct GoalProgress {
pub kind: GoalKind,
pub target: u32,
pub done: u64,
}
/// Stats for one year (`Some(y)`, by finish date and session day) or all time (`None`).
pub fn stats(lib: &Library, year: Option<i32>) -> Stats {
let mut s = Stats { year, ..Stats::default() };
let in_year = |date: Option<&str>| match year {
None => true,
Some(y) => date.and_then(year_of) == Some(y),
};
for b in lib.books.values() {
for r in &b.reads {
let Some(outcome) = r.outcome else { continue };
if !in_year(r.finished.as_deref()) {
continue;
}
match outcome {
Outcome::DidNotFinish => s.did_not_finish += 1,
Outcome::Read => {
s.books += 1;
if let Some(p) = b.info.pages {
s.pages += p as u64;
if s.longest.as_ref().is_none_or(|(_, l)| p > *l) {
s.longest = Some((b.id.clone(), p));
}
if s.shortest.as_ref().is_none_or(|(_, l)| p < *l) {
s.shortest = Some((b.id.clone(), p));
}
}
for m in &b.moods {
*s.moods.entry(m.clone()).or_default() += 1;
}
for g in &b.info.genres {
*s.genres.entry(g.clone()).or_default() += 1;
}
}
}
}
}
let mut active_ms = 0u64;
let mut pages_turned = 0u64;
for x in lib.sessions.values() {
if in_year(Some(&x.date)) {
active_ms += x.active_ms;
pages_turned += x.pages as u64;
}
}
s.active_minutes = active_ms / 60_000;
if active_ms >= 60_000 {
s.pace = Some(pages_turned as f64 / (active_ms as f64 / 3_600_000.0));
}
if let Some(y) = year
&& let Some(Goal { kind, target, .. }) = lib.goals.get(&y)
{
let done = match kind {
GoalKind::Books => s.books as u64,
GoalKind::Pages => s.pages,
};
s.goal = Some(GoalProgress { kind: *kind, target: *target, done });
}
s
}
/// Active reading time for one page view (docs/01_books.md): the time on the page, at most two minutes.
pub const IDLE_CAP_MS: u64 = 2 * 60 * 1000;
pub fn active_ms(on_page_ms: u64) -> u64 {
on_page_ms.min(IDLE_CAP_MS)
}
+136
View File
@@ -0,0 +1,136 @@
#![allow(dead_code)]
//! A seeded generator of plausible operations from several devices.
use liber_library::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person, Possession, Series};
use liber_library::{Clock, Event, Op};
use serde_json::json;
pub struct Rng(pub u64);
impl Rng {
pub fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
pub fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
pub fn pick<'a, T>(&mut self, v: &'a [T]) -> &'a T {
&v[self.below(v.len() as u64) as usize]
}
}
pub const BOOKS: &[&str] = &["b-valka", "b-dune", "b-rur", "b-babicka"];
pub fn info(i: usize) -> BookInfo {
let titles = ["Válka s mloky", "Dune", "R.U.R.", "Babička"];
BookInfo {
title: titles[i].into(),
authors: vec![["Karel Čapek", "Frank Herbert", "Karel Čapek", "Božena Němcová"][i].into()],
isbn13: [Some("9788020712479"), Some("9780441172719"), None, None][i].map(str::to_owned),
fingerprint: [None, None, Some("fp-rur"), None][i].map(str::to_owned),
pages: Some([280, 604, 100, 320][i]),
series: (i == 1).then(|| Series { name: "Dune".into(), index: Some(1.0) }),
genres: vec!["classic".into()],
added: 1_700_000_000_000 + i as u64,
..BookInfo::default()
}
}
/// One random operation by `dev` (its own ids carry the device name, so they never collide).
pub fn op(r: &mut Rng, dev: &str, n: usize) -> Op {
let bi = r.below(BOOKS.len() as u64) as usize;
let book = BOOKS[bi].to_string();
let hl = format!("h-{dev}-{}", r.below(6));
let date = format!("2025-{:02}-{:02}", 1 + r.below(12), 1 + r.below(28));
match r.below(17) {
0 | 1 => Op::BookAdd { book, info: info(bi), restore: false },
2 => Op::BookSet { book, field: Field::Review, value: json!(format!("review {dev} {n}")), base: None },
3 => Op::BookSet { book, field: Field::Rating, value: json!(1 + r.below(10)), base: None },
4 => Op::ShelfAdd { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() },
5 => Op::ShelfRemove { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() },
6 => Op::Position {
book,
cfi: format!("epubcfi(/6/{}!/4/2/1:{})", 2 * (1 + r.below(5)), r.below(100)),
chapter: r.below(5) as u32,
progress: r.below(1000) as f64 / 1000.0,
label: Some(format!("{}", r.below(300))),
},
7 => Op::HighlightAdd {
id: hl,
book,
kind: *r.pick(&[Mark::Highlight, Mark::Note, Mark::Bookmark]),
anchor: json!({"chapter": r.below(5), "quote": {"exact": format!("quote {dev} {n}"), "prefix": "", "suffix": ""}}),
colour: *r.pick(&[Colour::Yellow, Colour::Green, Colour::Blue, Colour::Pink]),
note: format!("note {dev} {n}"),
created: 1_700_000_000_000 + n as u64,
},
8 => Op::HighlightSet { id: hl, colour: Some(Colour::Pink), note: Some(format!("edit {dev} {n}")), base: None },
9 => Op::HighlightRemove { id: hl },
10 => Op::ReadStart { book, read: format!("r-{dev}-{n}"), date: Some(date) },
11 => Op::ReadEnd {
read: format!("r-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)),
date: Some(date),
outcome: *r.pick(&[Outcome::Read, Outcome::DidNotFinish]),
},
12 => Op::Lend {
loan: format!("l-{dev}-{n}"),
book,
person: Person { id: None, name: "Jana".into() },
since: date,
due: None,
},
13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date },
14 => Op::Session {
id: format!("s-{dev}-{n}"),
book,
start: 1000,
end: 1000 + r.below(600_000),
active_ms: r.below(400_000),
pages: r.below(30) as u32,
date,
},
15 => Op::BookSet {
book,
field: Field::Possession,
value: serde_json::to_value(r.pick(&[
Possession::Owned,
Possession::Wishlist,
Possession::Borrowed {
from: Person { id: Some("p1".into()), name: "Petr".into() },
due: Some("2025-12-01".into()),
},
]))
.unwrap(),
base: None,
},
_ => match r.below(3) {
0 => Op::Goal { year: 2025, kind: GoalKind::Books, target: 10 + r.below(40) as u32 },
1 => Op::BookFileAdd {
book,
file: BookFile {
sha256: format!("{:064x}", r.below(4)),
format: "epub".into(),
size: 1000,
name: "x.epub".into(),
},
},
_ => Op::BookSet { book, field: Field::Notes, value: json!(format!("notes {dev} {n}")), base: None },
},
}
}
/// `count` events from device `dev`, its clock `skew_ms` off the shared timeline.
pub fn events(seed: u64, dev: &str, count: usize, skew_ms: i64) -> Vec<Event> {
let mut r = Rng(seed | 1);
let mut c = Clock::default();
let mut out = Vec::new();
let mut t: i64 = 1_750_000_000_000;
for n in 0..count {
t += r.below(5_000) as i64;
let hlc = c.tick((t + skew_ms) as u64);
out.push(Event { id: format!("{dev}-{n}"), hlc, device: dev.into(), op: op(&mut r, dev, n) });
}
out
}
+139
View File
@@ -0,0 +1,139 @@
//! Mandatory test 4: export, then import into an empty library, reproduces books, states, shelves, highlights and
//! stats exactly.
mod common;
use common::{events, info};
use liber_library::export::{from_json, to_json, write_zip};
use liber_library::library::{Colour, Field, Mark};
use liber_library::stats::stats;
use liber_library::{Clock, Event, Library, Op};
use proptest::prelude::*;
use serde_json::json;
use std::io::Read;
fn assert_round_trip(lib: &Library) {
let json = to_json(lib, "2026-11-17T10:00:00Z");
let back = from_json(&json).expect("import");
assert_eq!(&back, lib);
for y in [None, Some(2024), Some(2025), Some(2026)] {
assert_eq!(stats(&back, y), stats(lib, y), "stats {y:?}");
}
// Exporting the imported library gives the same file.
assert_eq!(to_json(&back, "2026-11-17T10:00:00Z"), json);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 150, ..ProptestConfig::default() })]
#[test]
fn random_libraries_round_trip(seed in any::<u64>(), n in 1usize..120) {
let mut all = events(seed, "phone", n, 0);
all.extend(events(seed ^ 0x5555, "desk", n / 2, 90_000));
let lib = Library::from_events(&all);
assert_round_trip(&lib);
}
}
#[test]
fn a_library_with_conflicts_round_trips() {
let mut c = Clock::default();
let mut d = Clock::default();
let mut e = |id: &str, dev: &str, t: u64, op: Op| {
let hlc = if dev == "a" { c.tick(t) } else { d.tick(t) };
Event { id: id.into(), hlc, device: dev.into(), op }
};
let evs = vec![
e("1", "a", 1, Op::BookAdd { book: "b".into(), info: info(0), restore: false }),
e("2", "a", 2, Op::BookSet { book: "b".into(), field: Field::Review, value: json!("A"), base: None }),
e(
"3",
"a",
3,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("B"), base: Some("2".into()) },
),
e(
"4",
"b",
3,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("C"), base: Some("2".into()) },
),
e(
"5",
"a",
4,
Op::HighlightAdd {
id: "h".into(),
book: "b".into(),
kind: Mark::Note,
anchor: json!({"quote": {"exact": "slovo"}}),
colour: Colour::Green,
note: "x".into(),
created: 4,
},
),
e(
"6",
"a",
5,
Op::HighlightSet { id: "h".into(), colour: None, note: Some("y".into()), base: Some("5".into()) },
),
e(
"7",
"b",
5,
Op::HighlightSet { id: "h".into(), colour: None, note: Some("z".into()), base: Some("5".into()) },
),
e("8", "a", 6, Op::BookAdd { book: "same-isbn".into(), info: info(1), restore: false }),
e(
"9",
"a",
7,
Op::BookSet { book: "b".into(), field: Field::Isbn13, value: json!("9780441172719"), base: None },
),
];
let lib = Library::from_events(&evs);
assert!(lib.books["b"].review.conflict.is_some());
assert!(lib.highlights["h"].note.conflict.is_some());
assert_eq!(lib.books.len(), 2, "two books share an ISBN after an edit; the export keeps both");
assert_round_trip(&lib);
}
#[test]
fn the_zip_holds_json_csv_markdown_and_files() {
let mut all = events(42, "phone", 200, 0);
all.push(Event {
id: "file".into(),
hlc: liber_library::Hlc { wall: u64::MAX / 2, logical: 0 },
device: "phone".into(),
op: Op::BookFileAdd {
book: "b-valka".into(),
file: liber_library::library::BookFile {
sha256: "ab".repeat(32),
format: "epub".into(),
size: 5,
name: "v.epub".into(),
},
},
});
let lib = Library::from_events(&all);
let bytes = write_zip(&lib, Vec::new(), "2026-11-17T10:00:00Z", &mut |_, f| {
(f.sha256 == "ab".repeat(32)).then(|| Box::new(&b"EPUB!"[..]) as Box<dyn Read>)
})
.unwrap();
let z = liber_format::zip::Zip::parse(&bytes, &liber_format::Limits::default()).unwrap();
let names: Vec<&str> = z.entries().iter().map(|e| e.name.as_str()).collect();
assert!(names.contains(&"library.json") && names.contains(&"books.csv"));
if !lib.highlights.is_empty() {
assert!(names.iter().any(|n| n.starts_with("highlights/") && n.ends_with(".md")));
}
let file = names.iter().find(|n| n.starts_with("files/")).expect("the book file");
assert_eq!(z.read_name(file).unwrap().unwrap(), b"EPUB!");
let json = String::from_utf8(z.read_name("library.json").unwrap().unwrap()).unwrap();
assert_eq!(from_json(&json).unwrap(), lib);
}
#[test]
fn a_foreign_or_newer_export_is_refused() {
assert!(from_json("{}").is_err());
assert!(from_json(r#"{"format":"liber-export","version":2,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}}}"#).is_err());
assert!(from_json(r#"{"format":"liber-export","version":1,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}},"extra":1}"#).is_err());
}
+152
View File
@@ -0,0 +1,152 @@
//! Mandatory test 3: Goodreads and StoryGraph CSVs (quotes, commas, Czech) import every row; unknown columns are
//! reported and kept; hostile CSVs (formula injection, a 100 MB line) are handled safely.
use liber_library::import::{ImportError, Source, import_csv};
use liber_library::{Clock, Event, Library, Op, ReadStatus};
pub const GOODREADS: &str = "\u{feff}Book Id,Title,Author,Author l-f,Additional Authors,ISBN,ISBN13,My Rating,Average Rating,Publisher,Binding,Number of Pages,Year Published,Original Publication Year,Date Read,Date Added,Bookshelves,Bookshelves with positions,Exclusive Shelf,My Review,Spoiler,Private Notes,Read Count,Owned Copies,My Custom Column\n\
1,\"Válka s mloky\",Karel Čapek,\"Čapek, Karel\",,\"=\"\"802071247X\"\"\",\"=\"\"\"\"\",5,4.10,\"Československý spisovatel\",Paperback,280,2004,1936,2023/05/14,2023/01/02,\"klasika, favourites\",\"klasika (#3), favourites (#1)\",read,\"Skvělé!<br/><br/>Mloci, \"\"lidé\"\" a obchod.\",,soukromá poznámka,2,1,custom value\n\
2,\"Dune, Part One\",Frank Herbert,\"Herbert, Frank\",\"Someone Else\",\"=\"\"0441172717\"\"\",\"=\"\"9780441172719\"\"\",0,4.25,Ace,Mass Market Paperback,604,1990,1965,,2024/02/03,to-read,to-read (#4),to-read,,,,0,0,\n\
3,R.U.R.,Karel Čapek,\"Čapek, Karel\",,,,3,3.80,,Kindle Edition,100,2010,1920,,2024/03/01,currently-reading,,currently-reading,,,,1,0,\n";
pub const STORYGRAPH: &str = "Title,Authors,Contributors,ISBN/UID,Format,Read Status,Date Added,Last Date Read,Dates Read,Read Count,Moods,Pace,Character- or Plot-Driven?,Strong Character Development?,Loveable Characters?,Diverse Characters?,Flawed Characters?,Star Rating,Review,Content Warnings,Content Warning Description,Tags,Owned?\n\
Babička,Božena Němcová,,9788020712479,paperback,read,2023/01/01,2023/02/10,\"2022/12/01-2022/12/20, 2023/01/15-2023/02/10\",2,\"reflective, emotional, cozy\",slow,Character,Yes,Yes,No,Yes,4.25,\"Krásná, \"\"klidná\"\" kniha.\",,,\"czech, classics\",Yes\n\
Neznámá kniha,\"A. Author, B. Author\",,abc-uid-123,digital,did-not-finish,2023/03/01,2023/03/05,,0,,,,,,,,0,,,,,No\n\
Další,C. Author,,,audio,to-read,2023/04/01,,,0,,,,,,,,,,,,,No\n";
fn ids() -> impl FnMut() -> String {
let mut n = 0;
move || {
n += 1;
format!("id{n:04}")
}
}
pub fn apply(lib_ops: Vec<Op>) -> Library {
let mut c = Clock::default();
let events: Vec<Event> = lib_ops
.into_iter()
.enumerate()
.map(|(i, op)| Event { id: format!("e{i}"), hlc: c.tick(1_700_000_000_000), device: "d".into(), op })
.collect();
Library::from_events(&events)
}
#[test]
fn goodreads_imports_every_row() {
let (ops, r) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.source, Source::Goodreads);
assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped);
assert_eq!(r.unknown_columns, vec!["My Custom Column"]);
assert!(r.unused_columns.contains(&"Average Rating".to_owned()));
let lib = apply(ops);
let valka = lib.books.values().find(|b| b.info.title == "Válka s mloky").unwrap();
assert_eq!(valka.info.isbn13.as_deref(), Some("9788020712479"));
assert_eq!(valka.info.authors, vec!["Karel Čapek"]);
assert_eq!(valka.info.publisher.as_deref(), Some("Československý spisovatel"));
assert_eq!(valka.info.published.as_deref(), Some("1936"));
assert_eq!(valka.rating, Some(10));
assert_eq!(valka.review.value, "Skvělé!\n\nMloci, \"lidé\" a obchod.");
assert_eq!(valka.notes.value, "soukromá poznámka");
assert_eq!(valka.status(), ReadStatus::Read);
assert_eq!(valka.reads.len(), 2, "read twice");
assert_eq!(valka.reads[1].finished.as_deref(), Some("2023-05-14"));
assert!(valka.paper);
assert_eq!(valka.shelves.iter().cloned().collect::<Vec<_>>(), vec!["favourites", "klasika"]);
assert_eq!(valka.info.import_extra.get("goodreads:My Custom Column").map(String::as_str), Some("custom value"));
assert_eq!(valka.info.import_extra.get("goodreads:Book Id").map(String::as_str), Some("1"));
let dune = lib.books.values().find(|b| b.info.title == "Dune, Part One").unwrap();
assert_eq!(dune.info.authors, vec!["Frank Herbert", "Someone Else"]);
assert_eq!(dune.status(), ReadStatus::ToRead);
assert_eq!(dune.rating, None);
let rur = lib.books.values().find(|b| b.info.title == "R.U.R.").unwrap();
assert_eq!(rur.status(), ReadStatus::Reading);
assert!(!rur.paper);
}
#[test]
fn storygraph_imports_every_row() {
let (ops, r) = import_csv(STORYGRAPH.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.source, Source::StoryGraph);
assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped);
assert!(r.unknown_columns.is_empty());
let lib = apply(ops);
let b = lib.books.values().find(|b| b.info.title == "Babička").unwrap();
assert_eq!(b.reads.len(), 2);
assert_eq!(b.reads[0].started.as_deref(), Some("2022-12-01"));
assert_eq!(b.reads[1].finished.as_deref(), Some("2023-02-10"));
assert_eq!(b.rating, Some(9), "4.25 stars rounds to 4.5");
assert_eq!(b.moods.iter().cloned().collect::<Vec<_>>(), vec!["emotional", "reflective"]);
assert!(b.tags.contains("cozy") && b.tags.contains("czech"));
assert_eq!(b.review.value, "Krásná, \"klidná\" kniha.");
assert_eq!(b.info.import_extra.get("storygraph:Pace").map(String::as_str), Some("slow"));
let n = lib.books.values().find(|b| b.info.title == "Neznámá kniha").unwrap();
assert_eq!(n.status(), ReadStatus::DidNotFinish);
assert_eq!(n.info.authors, vec!["A. Author", "B. Author"]);
assert_eq!(n.info.import_extra.get("storygraph:ISBN/UID").map(String::as_str), Some("abc-uid-123"));
}
#[test]
fn windows_1250_csv() {
let plain = GOODREADS.replace('\u{feff}', "");
let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(&plain);
let (ops, r) = import_csv(&bytes, &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 3);
assert!(apply(ops).books.values().any(|b| b.info.title == "Válka s mloky"));
}
#[test]
fn importing_twice_adds_nothing() {
let (ops, _) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
let lib = apply(ops);
let (ops2, r) = import_csv(GOODREADS.as_bytes(), &lib, &mut ids(), 0).unwrap();
assert!(ops2.is_empty());
assert_eq!(r.skipped.len(), 3);
}
#[test]
fn formula_injection_is_stored_as_text_and_exported_inert() {
let csv = "Title,Authors,ISBN/UID,Read Status,Review\n\"=HYPERLINK(\"\"http://evil\"\",\"\"x\"\")\",@SUM(A1),,to-read,+cmd|' /C calc'!A0\n";
let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 1);
let lib = apply(ops);
let b = lib.books.values().next().unwrap();
assert_eq!(b.info.title, "=HYPERLINK(\"http://evil\",\"x\")");
let out = liber_library::export::books_csv(&lib);
assert!(out.contains("'=HYPERLINK"), "{out}");
assert!(out.contains("'@SUM(A1)"));
assert!(out.contains("'+cmd"));
for line in out.lines().skip(1) {
for cell in line.split(',') {
let c = cell.trim_start_matches('"');
assert!(!c.starts_with(['=', '+', '@']), "{cell}");
}
}
}
#[test]
fn a_100_mb_line_is_refused_early_and_a_huge_field_is_cut() {
let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\n");
csv.push_str(&"x".repeat(100 * 1024 * 1024));
let t = std::time::Instant::now();
assert_eq!(import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap_err(), ImportError::TooLarge);
assert!(t.elapsed().as_secs() < 5);
let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\nBig,A,,read,\"");
csv.push_str(&"ř".repeat(5 * 1024 * 1024));
csv.push_str("\"\n");
let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 1);
assert_eq!(r.truncated, vec![(1, "Review".to_owned())]);
let lib = apply(ops);
assert!(lib.books.values().next().unwrap().review.value.len() <= 64 * 1024);
}
#[test]
fn not_an_export() {
assert_eq!(
import_csv(b"a,b,c\n1,2,3\n", &Library::default(), &mut ids(), 0).unwrap_err(),
ImportError::UnknownFormat
);
let junk: Vec<u8> = (0..50_000u32).map(|i| (i * 31 % 251) as u8).collect();
assert!(import_csv(&junk, &Library::default(), &mut ids(), 0).is_err());
}
+69
View File
@@ -0,0 +1,69 @@
mod common;
use common::info;
use liber_library::library::{GoalKind, Outcome};
use liber_library::stats::{active_ms, stats};
use liber_library::{Clock, Event, Library, Op};
use serde_json::json;
#[test]
fn yearly_and_all_time() {
let mut c = Clock::default();
let mut n = 0;
let mut e = |op: Op| {
n += 1;
Event { id: format!("e{n}"), hlc: c.tick(n), device: "d".into(), op }
};
let evs = vec![
e(Op::BookAdd { book: "a".into(), info: info(0), restore: false }),
e(Op::BookAdd { book: "b".into(), info: info(1), restore: false }),
e(Op::BookAdd { book: "c".into(), info: info(2), restore: false }),
e(Op::BookSet {
book: "a".into(),
field: liber_library::library::Field::Moods,
value: json!(["dark", "tense"]),
base: None,
}),
e(Op::ReadStart { book: "a".into(), read: "r1".into(), date: Some("2025-01-02".into()) }),
e(Op::ReadEnd { read: "r1".into(), date: Some("2025-02-01".into()), outcome: Outcome::Read }),
e(Op::ReadStart { book: "b".into(), read: "r2".into(), date: Some("2025-03-01".into()) }),
e(Op::ReadEnd { read: "r2".into(), date: Some("2025-04-01".into()), outcome: Outcome::Read }),
e(Op::ReadStart { book: "c".into(), read: "r3".into(), date: None }),
e(Op::ReadEnd { read: "r3".into(), date: Some("2024-05-01".into()), outcome: Outcome::DidNotFinish }),
e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }),
e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }),
e(Op::Session {
id: "s1".into(),
book: "a".into(),
start: 0,
end: 3_600_000,
active_ms: 1_800_000,
pages: 30,
date: "2025-01-10".into(),
}),
e(Op::Session {
id: "s2".into(),
book: "b".into(),
start: 0,
end: 3_600_000,
active_ms: 9_999_999_999,
pages: 60,
date: "2025-03-10".into(),
}),
e(Op::Goal { year: 2025, kind: GoalKind::Books, target: 12 }),
];
let lib = Library::from_events(&evs);
let s = stats(&lib, Some(2025));
assert_eq!((s.books, s.did_not_finish, s.pages), (2, 0, 280 + 604));
assert_eq!(s.active_minutes, 30 + 60, "a session's active time is capped at its length");
assert_eq!(s.pace, Some(60.0));
assert_eq!(s.longest, Some(("b".into(), 604)));
assert_eq!(s.shortest, Some(("a".into(), 280)));
assert_eq!(s.moods.get("dark"), Some(&1));
assert_eq!(s.genres.get("classic"), Some(&2));
let g = s.goal.unwrap();
assert_eq!((g.target, g.done), (12, 2));
let all = stats(&lib, None);
assert_eq!((all.books, all.did_not_finish), (3, 1), "a re-read counts again");
assert_eq!(stats(&lib, Some(2024)).did_not_finish, 1);
assert_eq!(active_ms(10 * 60_000), 2 * 60_000, "two minutes per page at most");
}
+192
View File
@@ -0,0 +1,192 @@
//! Mandatory test 5 (the core's half): devices with clock skew and dropped connections converge; highlights made
//! offline on both merge; positions keep the furthest with a "jump back" offer; concurrent text edits keep both.
//! (The app's `liber-store` tests the relay: ciphertext only on the wire.)
mod common;
use common::{Rng, events, info};
use liber_library::library::{Colour, Field, Mark};
use liber_library::{Clock, Event, Library, Op};
use proptest::prelude::*;
use serde_json::json;
fn shuffle(mut v: Vec<Event>, r: &mut Rng) -> Vec<Event> {
for i in (1..v.len()).rev() {
let j = r.below(i as u64 + 1) as usize;
v.swap(i, j);
}
v
}
proptest! {
#![proptest_config(ProptestConfig { cases: 200, ..ProptestConfig::default() })]
/// Two devices, skewed clocks, events delivered in random order, with duplicates, in several partial rounds
/// (dropped connections): once both hold every event, both hold the same library.
#[test]
fn devices_converge(seed in any::<u64>(), skew in -180_000i64..180_000, na in 1usize..60, nb in 1usize..60) {
let a = events(seed, "phone", na, 0);
let b = events(seed.rotate_left(17) ^ 0x9e37, "desk", nb, skew);
let mut r = Rng(seed ^ 0xabcdef | 1);
// Device A's view: its own events, then B's arriving in random batches, some twice.
let mut on_a = a.clone();
let mut incoming = shuffle(b.clone(), &mut r);
while !incoming.is_empty() {
let k = 1 + r.below(incoming.len() as u64) as usize;
let batch: Vec<Event> = incoming.drain(..k).collect();
on_a.extend(batch.iter().cloned());
if r.below(3) == 0 {
on_a.extend(batch); // a retried upload
}
// A partial library after each round never panics.
let _ = Library::from_events(&on_a);
}
let mut on_b = b.clone();
on_b.extend(shuffle(a.clone(), &mut r));
let la = Library::from_events(&on_a);
let lb = Library::from_events(&on_b);
prop_assert_eq!(&la, &lb);
// And the stats agree.
prop_assert_eq!(liber_library::stats::stats(&la, Some(2025)), liber_library::stats::stats(&lb, Some(2025)));
}
}
fn ev(id: &str, dev: &str, c: &mut Clock, t: u64, op: Op) -> Event {
Event { id: id.into(), hlc: c.tick(t), device: dev.into(), op }
}
fn add(book: &str) -> Op {
Op::BookAdd { book: book.into(), info: info(0), restore: false }
}
#[test]
fn highlights_made_offline_on_both_devices_merge() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let base = ev("p0", "phone", &mut pc, 1000, add("b"));
let hl = |id: &str, dev: &str, c: &mut Clock, t: u64, q: &str| {
ev(
&format!("{dev}-{id}"),
dev,
c,
t,
Op::HighlightAdd {
id: id.into(),
book: "b".into(),
kind: Mark::Highlight,
anchor: json!({"quote": {"exact": q}}),
colour: Colour::Yellow,
note: String::new(),
created: t,
},
)
};
let p = [base.clone(), hl("h1", "phone", &mut pc, 2000, "na telefonu")];
let d = [base, hl("h2", "desk", &mut dc, 1500, "na počítači")];
let all: Vec<Event> = p.iter().chain(d.iter()).cloned().collect();
let lib = Library::from_events(&all);
assert_eq!(lib.highlights.len(), 2);
// A deletion on one device and an edit on the other: the deletion wins, everywhere.
let mut more = all.clone();
more.push(ev("d-del", "desk", &mut dc, 3000, Op::HighlightRemove { id: "h1".into() }));
more.push(ev(
"p-edit",
"phone",
&mut pc,
3500,
Op::HighlightSet { id: "h1".into(), colour: Some(Colour::Blue), note: None, base: None },
));
let l = Library::from_events(&more);
assert!(!l.highlights.contains_key("h1"));
assert!(l.highlights.contains_key("h2"));
}
#[test]
fn positions_keep_the_furthest_and_offer_a_jump_back() {
let mut c = Clock::default();
let pos = |id: &str, c: &mut Clock, t: u64, p: f64| {
ev(
id,
"x",
c,
t,
Op::Position {
book: "b".into(),
cfi: format!("epubcfi(/6/2!/4/2/1:{})", (p * 100.0) as u32),
chapter: 0,
progress: p,
label: Some(format!("{}", (p * 300.0) as u32)),
},
)
};
let events = vec![ev("a", "x", &mut c, 1, add("b")), pos("p1", &mut c, 10, 0.6), pos("p2", &mut c, 20, 0.3)];
let l = Library::from_events(&events);
let b = &l.books["b"];
assert_eq!(b.position.as_ref().unwrap().progress, 0.6);
assert_eq!(b.jump_back().unwrap().progress, 0.3, "the newest position is behind: offer to jump back");
let mut ev2 = events.clone();
ev2.push(pos("p3", &mut c, 30, 0.7));
assert!(Library::from_events(&ev2).books["b"].jump_back().is_none());
}
#[test]
fn concurrent_text_edits_keep_both_versions() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let a = ev("a", "phone", &mut pc, 1, add("b"));
let r0 = ev(
"r0",
"phone",
&mut pc,
2,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("first"), base: None },
);
// Both devices saw r0, then edited offline.
let rp = ev(
"rp",
"phone",
&mut pc,
10,
Op::BookSet {
book: "b".into(),
field: Field::Review,
value: json!("phone's version"),
base: Some("r0".into()),
},
);
dc.observe(r0.hlc);
let rd = ev(
"rd",
"desk",
&mut dc,
9,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("desk's version"), base: Some("r0".into()) },
);
let l = Library::from_events(&[a.clone(), r0.clone(), rp.clone(), rd.clone()]);
let review = &l.books["b"].review;
let mut both = vec![review.value.clone(), review.conflict.clone().unwrap()];
both.sort();
assert_eq!(both, vec!["desk's version", "phone's version"]);
// The next edit, made seeing the merged state, clears the marker.
let v = l.version("b", Field::Review).map(str::to_owned);
let fix = ev(
"fix",
"desk",
&mut dc,
20,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("merged"), base: v },
);
let l = Library::from_events(&[a, r0, rp, rd, fix]);
assert_eq!(l.books["b"].review.value, "merged");
assert!(l.books["b"].review.conflict.is_none());
}
#[test]
fn the_same_book_added_on_two_devices_merges() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let p = ev("p", "phone", &mut pc, 5, Op::BookAdd { book: "phone-id".into(), info: info(1), restore: false });
let d = ev("d", "desk", &mut dc, 3, Op::BookAdd { book: "desk-id".into(), info: info(1), restore: false });
let s = ev("s", "phone", &mut pc, 6, Op::ShelfAdd { book: "phone-id".into(), shelf: "sci-fi".into() });
let l = Library::from_events(&[p, d, s]);
assert_eq!(l.books.len(), 1);
let b = l.books.values().next().unwrap();
assert_eq!(b.id, "desk-id", "the earlier add wins; the other id is an alias");
assert!(b.shelves.contains("sci-fi"));
}