use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use rusqlite::{Connection, params};
use crate::media::{self, Entry, Kind};
const SCHEMA: &str = "
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS source (
id INTEGER PRIMARY KEY,
path BLOB NOT NULL UNIQUE,
added INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS item (
id INTEGER PRIMARY KEY,
source_id INTEGER NOT NULL REFERENCES source(id) ON DELETE CASCADE,
path BLOB NOT NULL UNIQUE,
kind INTEGER NOT NULL,
size INTEGER NOT NULL,
mtime INTEGER NOT NULL,
-- 1 when the last scan did not find the file. Kept so playlists can
-- show it as missing instead of silently losing it.
missing INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS item_source ON item(source_id);
-- Folders inside a source that the user chose to hide (files untouched).
CREATE TABLE IF NOT EXISTS excluded (
path BLOB PRIMARY KEY
);
-- What rosier knows about each video: its length (read once in the
-- background, for the tiles) and where the user stopped watching it.
CREATE TABLE IF NOT EXISTS watch (
item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
duration REAL,
position REAL NOT NULL DEFAULT 0,
-- When the position was saved (seconds since the epoch).
at INTEGER NOT NULL DEFAULT 0
);
-- Seconds watched in each stretch of a video (little-endian f32s).
CREATE TABLE IF NOT EXISTS heat (
item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
bins BLOB NOT NULL
);
-- Stars the user gave a file (1 to 5; no row is unrated).
CREATE TABLE IF NOT EXISTS rating (
item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5)
);
-- When each picture was taken, read once from its Exif (seconds since 1970
-- on the camera's clock; 0: it has no date).
CREATE TABLE IF NOT EXISTS taken (
item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
at INTEGER NOT NULL
);
-- Book view per folder or book (crate::book::Layout as bits). A folder
-- without a row is shown one item at a time.
CREATE TABLE IF NOT EXISTS book_layout (
path BLOB PRIMARY KEY,
bits INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS playlist (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
created INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS playlist_item (
playlist_id INTEGER NOT NULL REFERENCES playlist(id) ON DELETE CASCADE,
item_id INTEGER NOT NULL REFERENCES item(id) ON DELETE CASCADE,
position INTEGER NOT NULL,
PRIMARY KEY (playlist_id, item_id)
);
";
pub fn default_path() -> PathBuf {
let base = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
.unwrap_or_else(std::env::temp_dir);
base.join("rosier").join("rosier.db")
}
pub fn open(path: &Path) -> Result<Connection> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
}
let conn = Connection::open(path).with_context(|| format!("opening {}", path.display()))?;
conn.execute_batch(SCHEMA)?;
Ok(conn)
}
fn now() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
}
fn path_blob(p: &Path) -> &[u8] {
p.as_os_str().as_encoded_bytes()
}
fn blob_path(b: Vec<u8>) -> PathBuf {
PathBuf::from(unsafe { std::ffi::OsString::from_encoded_bytes_unchecked(b) })
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Watch {
pub duration: Option<f64>,
pub position: f64,
pub at: i64,
}
#[derive(Debug, Clone)]
pub struct Source {
pub id: i64,
pub path: PathBuf,
}
pub fn sources(conn: &Connection) -> Result<Vec<Source>> {
let mut st = conn.prepare("SELECT id, path FROM source ORDER BY id")?;
let rows = st.query_map([], |r| Ok(Source { id: r.get(0)?, path: blob_path(r.get(1)?) }))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn add_source(conn: &Connection, path: &Path) -> Result<()> {
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if sources(conn)?.iter().any(|s| path.starts_with(&s.path)) {
return Ok(());
}
conn.execute("INSERT OR IGNORE INTO source (path, added) VALUES (?1, ?2)", params![path_blob(&path), now()])?;
Ok(())
}
pub fn present_items(conn: &Connection) -> Result<Vec<Entry>> {
let mut st = conn.prepare("SELECT id, path, kind, size, mtime FROM item WHERE missing = 0")?;
let rows = st.query_map([], |r| {
Ok(Entry {
id: r.get(0)?,
path: blob_path(r.get(1)?),
kind: match r.get::<_, i64>(2)? {
1 => Kind::Video,
2 => Kind::Book,
_ => Kind::Image,
},
size: r.get::<_, i64>(3)? as u64,
mtime: r.get::<_, i64>(4)? as u64,
})
})?;
let mut v: Vec<Entry> = rows.collect::<Result<_, _>>()?;
v.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
Ok(v)
}
pub fn visible_items(conn: &Connection) -> Result<Vec<Entry>> {
let hidden = excluded(conn)?;
let mut items = present_items(conn)?;
items.retain(|e| !hidden.iter().any(|x| e.path.starts_with(x)));
Ok(items)
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SyncStats {
pub added: usize,
pub changed: usize,
pub missing: usize,
}
impl SyncStats {
pub fn is_empty(&self) -> bool {
*self == SyncStats::default()
}
}
fn kind_code(kind: Kind) -> i64 {
match kind {
Kind::Image => 0,
Kind::Video => 1,
Kind::Book => 2,
}
}
pub fn add_file(conn: &Connection, path: &Path) -> Result<()> {
let Some(src) = sources(conn)?.into_iter().find(|s| path.starts_with(&s.path)) else { return Ok(()) };
let Some(e) = media::entry(path.to_path_buf(), || std::fs::metadata(path).ok()) else { return Ok(()) };
conn.execute(
"INSERT OR IGNORE INTO item (source_id, path, kind, size, mtime, missing) VALUES (?1, ?2, ?3, ?4, ?5, 0)",
params![src.id, path_blob(&e.path), kind_code(e.kind), e.size as i64, e.mtime as i64],
)?;
Ok(())
}
pub fn sync_source(conn: &mut Connection, src: &Source) -> Result<SyncStats> {
let scanned = media::scan(&src.path);
let mut known: HashMap<Vec<u8>, (i64, u64, u64, bool)> = HashMap::new();
{
let mut st = conn.prepare("SELECT id, path, size, mtime, missing FROM item WHERE source_id = ?1")?;
let rows = st.query_map([src.id], |r| {
Ok((
r.get::<_, Vec<u8>>(1)?,
(r.get(0)?, r.get::<_, i64>(2)? as u64, r.get::<_, i64>(3)? as u64, r.get::<_, i64>(4)? != 0),
))
})?;
for row in rows {
let (path, v) = row?;
known.insert(path, v);
}
}
let mut stats = SyncStats::default();
let tx = conn.transaction()?;
{
let mut insert = tx
.prepare("INSERT INTO item (source_id, path, kind, size, mtime, missing) VALUES (?1, ?2, ?3, ?4, ?5, 0)")?;
let mut update = tx.prepare("UPDATE item SET kind = ?2, size = ?3, mtime = ?4, missing = 0 WHERE id = ?1")?;
for e in &scanned {
let kind = kind_code(e.kind);
match known.remove(path_blob(&e.path)) {
None => {
insert.execute(params![src.id, path_blob(&e.path), kind, e.size as i64, e.mtime as i64])?;
stats.added += 1;
}
Some((id, size, mtime, missing)) => {
if size != e.size || mtime != e.mtime || missing {
update.execute(params![id, kind, e.size as i64, e.mtime as i64])?;
stats.changed += 1;
}
}
}
}
let mut gone = tx.prepare("UPDATE item SET missing = 1 WHERE id = ?1")?;
for (_, (id, _, _, missing)) in known {
if !missing {
gone.execute([id])?;
stats.missing += 1;
}
}
}
tx.commit()?;
Ok(stats)
}
const FAVORITES: &str = "favorites";
fn favorites_id(conn: &Connection) -> Result<i64> {
conn.execute("INSERT OR IGNORE INTO playlist (name, created) VALUES (?1, ?2)", params![FAVORITES, now()])?;
Ok(conn.query_row("SELECT id FROM playlist WHERE name = ?1", [FAVORITES], |r| r.get(0))?)
}
pub fn favorites(conn: &Connection) -> Result<Vec<i64>> {
let id = favorites_id(conn)?;
let mut st = conn.prepare("SELECT item_id FROM playlist_item WHERE playlist_id = ?1 ORDER BY position")?;
let rows = st.query_map([id], |r| r.get(0))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_favorite(conn: &Connection, item_id: i64, on: bool) -> Result<()> {
let id = favorites_id(conn)?;
if on {
conn.execute(
"INSERT OR IGNORE INTO playlist_item (playlist_id, item_id, position)
VALUES (?1, ?2, (SELECT COALESCE(MAX(position), 0) + 1 FROM playlist_item WHERE playlist_id = ?1))",
params![id, item_id],
)?;
} else {
conn.execute("DELETE FROM playlist_item WHERE playlist_id = ?1 AND item_id = ?2", params![id, item_id])?;
}
Ok(())
}
pub fn ratings(conn: &Connection) -> Result<HashMap<i64, u8>> {
let mut st = conn.prepare("SELECT item_id, stars FROM rating")?;
let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_rating(conn: &Connection, item_id: i64, stars: u8) -> Result<()> {
if stars == 0 {
conn.execute("DELETE FROM rating WHERE item_id = ?1", [item_id])?;
} else {
conn.execute(
"INSERT INTO rating (item_id, stars) VALUES (?1, ?2)
ON CONFLICT(item_id) DO UPDATE SET stars = excluded.stars",
params![item_id, stars.min(5)],
)?;
}
Ok(())
}
pub fn layouts(conn: &Connection) -> Result<HashMap<PathBuf, i64>> {
let mut st = conn.prepare("SELECT path, bits FROM book_layout")?;
let rows = st.query_map([], |r| Ok((blob_path(r.get(0)?), r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_layout(conn: &Connection, path: &Path, bits: Option<i64>) -> Result<()> {
match bits {
Some(b) => conn.execute(
"INSERT INTO book_layout (path, bits) VALUES (?1, ?2) ON CONFLICT(path) DO UPDATE SET bits = excluded.bits",
params![path_blob(path), b],
)?,
None => conn.execute("DELETE FROM book_layout WHERE path = ?1", [path_blob(path)])?,
};
Ok(())
}
pub fn taken(conn: &Connection) -> Result<HashMap<i64, i64>> {
let mut st = conn.prepare("SELECT item_id, at FROM taken")?;
let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_taken(conn: &Connection, item_id: i64, at: i64) -> Result<()> {
conn.execute(
"INSERT INTO taken (item_id, at) VALUES (?1, ?2) ON CONFLICT(item_id) DO UPDATE SET at = excluded.at",
params![item_id, at],
)?;
Ok(())
}
pub fn watch(conn: &Connection) -> Result<HashMap<i64, Watch>> {
let mut st = conn.prepare("SELECT item_id, duration, position, at FROM watch")?;
let rows =
st.query_map([], |r| Ok((r.get(0)?, Watch { duration: r.get(1)?, position: r.get(2)?, at: r.get(3)? })))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_duration(conn: &Connection, item_id: i64, duration: f64) -> Result<()> {
conn.execute(
"INSERT INTO watch (item_id, duration) VALUES (?1, ?2)
ON CONFLICT(item_id) DO UPDATE SET duration = excluded.duration",
params![item_id, duration],
)?;
Ok(())
}
pub fn set_position(conn: &Connection, item_id: i64, w: &Watch) -> Result<()> {
conn.execute(
"INSERT INTO watch (item_id, duration, position, at) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(item_id) DO UPDATE SET
duration = COALESCE(excluded.duration, watch.duration),
position = excluded.position, at = excluded.at",
params![item_id, w.duration, w.position, w.at],
)?;
Ok(())
}
pub fn heat(conn: &Connection) -> Result<HashMap<i64, Vec<f32>>> {
let mut st = conn.prepare("SELECT item_id, bins FROM heat")?;
let rows = st.query_map([], |r| {
let b: Vec<u8> = r.get(1)?;
let bins = b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect();
Ok((r.get(0)?, bins))
})?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_heat(conn: &Connection, item_id: i64, bins: &[f32]) -> Result<()> {
let b: Vec<u8> = bins.iter().flat_map(|v| v.to_le_bytes()).collect();
conn.execute("INSERT OR REPLACE INTO heat (item_id, bins) VALUES (?1, ?2)", params![item_id, b])?;
Ok(())
}
pub fn excluded(conn: &Connection) -> Result<Vec<PathBuf>> {
let mut st = conn.prepare("SELECT path FROM excluded ORDER BY path")?;
let rows = st.query_map([], |r| Ok(blob_path(r.get(0)?)))?;
Ok(rows.collect::<Result<_, _>>()?)
}
pub fn set_excluded(conn: &Connection, path: &Path, hidden: bool) -> Result<()> {
if hidden {
conn.execute("INSERT OR IGNORE INTO excluded (path) VALUES (?1)", [path_blob(path)])?;
} else {
conn.execute("DELETE FROM excluded WHERE path = ?1", [path_blob(path)])?;
}
Ok(())
}
pub fn remove_source(conn: &Connection, id: i64) -> Result<()> {
conn.execute("DELETE FROM source WHERE id = ?1", [id])?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn tmpdb() -> (tempdir::Dir, Connection) {
let d = tempdir::Dir::new();
let c = open(&d.0.join("t.db")).unwrap();
(d, c)
}
mod tempdir {
pub struct Dir(pub std::path::PathBuf);
impl Dir {
pub fn new() -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let p = std::env::temp_dir().join(format!(
"rosier-test-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).unwrap();
Dir(p)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[test]
fn sync_tracks_added_changed_and_missing_files() {
let (d, mut c) = tmpdb();
let media = d.0.join("media");
std::fs::create_dir_all(&media).unwrap();
std::fs::write(media.join("a.jpg"), b"x").unwrap();
std::fs::write(media.join("b.mp4"), b"y").unwrap();
add_source(&c, &media).unwrap();
let src = sources(&c).unwrap().remove(0);
assert_eq!(sync_source(&mut c, &src).unwrap(), SyncStats { added: 2, changed: 0, missing: 0 });
assert!(sync_source(&mut c, &src).unwrap().is_empty());
std::fs::remove_file(media.join("a.jpg")).unwrap();
assert_eq!(sync_source(&mut c, &src).unwrap().missing, 1);
assert_eq!(present_items(&c).unwrap().len(), 1);
std::fs::write(media.join("a.jpg"), b"x").unwrap();
let s = sync_source(&mut c, &src).unwrap();
assert_eq!((s.added, s.changed), (0, 1));
}
#[test]
fn a_file_added_ahead_is_in_the_index_before_the_scan_and_once_after() {
let (d, mut c) = tmpdb();
std::fs::create_dir_all(d.0.join("media/sub")).unwrap();
let media = d.0.join("media").canonicalize().unwrap();
std::fs::write(media.join("a.jpg"), b"x").unwrap();
std::fs::write(media.join("sub/b.jpg"), b"y").unwrap();
std::fs::write(media.join("notes.txt"), b"z").unwrap();
add_source(&c, &media).unwrap();
add_file(&c, &media.join("a.jpg")).unwrap();
add_file(&c, &media.join("notes.txt")).unwrap();
add_file(&c, &d.0.join("elsewhere.jpg")).unwrap();
let items = present_items(&c).unwrap();
assert_eq!(items.iter().map(|e| e.path.clone()).collect::<Vec<_>>(), vec![media.join("a.jpg")]);
let src = sources(&c).unwrap().remove(0);
assert_eq!(sync_source(&mut c, &src).unwrap(), SyncStats { added: 1, changed: 0, missing: 0 });
assert_eq!(present_items(&c).unwrap().len(), 2);
}
#[test]
fn excluded_folders_round_trip() {
let (_d, c) = tmpdb();
let p = std::path::Path::new("/media/x/sub");
set_excluded(&c, p, true).unwrap();
set_excluded(&c, p, true).unwrap();
assert_eq!(excluded(&c).unwrap(), vec![p.to_path_buf()]);
set_excluded(&c, p, false).unwrap();
assert!(excluded(&c).unwrap().is_empty());
}
#[test]
fn hidden_folders_drop_out_of_the_visible_items() {
let (d, mut c) = tmpdb();
let media = d.0.join("m");
std::fs::create_dir_all(media.join("keep")).unwrap();
std::fs::create_dir_all(media.join("hide/deep")).unwrap();
for n in ["keep/1.jpg", "hide/2.jpg", "hide/deep/3.png", "top.mp4"] {
std::fs::write(media.join(n), b"x").unwrap();
}
add_source(&c, &media).unwrap();
let src = sources(&c).unwrap().remove(0);
sync_source(&mut c, &src).unwrap();
set_excluded(&c, &src.path.join("hide"), true).unwrap();
let names: Vec<String> =
visible_items(&c).unwrap().iter().map(|e| e.path.file_name().unwrap().to_string_lossy().into()).collect();
assert_eq!(names, vec!["1.jpg", "top.mp4"]);
}
#[test]
fn favorites_keep_order_and_toggle() {
let (d, mut c) = tmpdb();
let media = d.0.join("m");
std::fs::create_dir_all(&media).unwrap();
for n in ["1.jpg", "2.jpg", "3.jpg"] {
std::fs::write(media.join(n), b"x").unwrap();
}
add_source(&c, &media).unwrap();
let src = sources(&c).unwrap().remove(0);
sync_source(&mut c, &src).unwrap();
let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
set_favorite(&c, ids[2], true).unwrap();
set_favorite(&c, ids[0], true).unwrap();
set_favorite(&c, ids[0], true).unwrap(); assert_eq!(favorites(&c).unwrap(), vec![ids[2], ids[0]]);
set_favorite(&c, ids[2], false).unwrap();
assert_eq!(favorites(&c).unwrap(), vec![ids[0]]);
remove_source(&c, src.id).unwrap();
assert!(favorites(&c).unwrap().is_empty());
}
#[test]
fn a_folder_inside_a_source_is_not_added_again() {
let (d, c) = tmpdb();
let inner = d.0.join("m/trip");
std::fs::create_dir_all(&inner).unwrap();
add_source(&c, &d.0.join("m")).unwrap();
add_source(&c, &inner).unwrap();
add_source(&c, &d.0.join("m")).unwrap();
assert_eq!(sources(&c).unwrap().len(), 1);
}
#[test]
fn ratings_are_set_changed_and_taken_away() {
let (d, mut c) = tmpdb();
let media = d.0.join("m");
std::fs::create_dir_all(&media).unwrap();
for n in ["1.jpg", "2.jpg"] {
std::fs::write(media.join(n), b"x").unwrap();
}
add_source(&c, &media).unwrap();
let src = sources(&c).unwrap().remove(0);
sync_source(&mut c, &src).unwrap();
let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
set_rating(&c, ids[0], 3).unwrap();
set_rating(&c, ids[1], 5).unwrap();
set_rating(&c, ids[0], 4).unwrap();
assert_eq!(ratings(&c).unwrap(), HashMap::from([(ids[0], 4), (ids[1], 5)]));
set_rating(&c, ids[1], 0).unwrap();
assert_eq!(ratings(&c).unwrap(), HashMap::from([(ids[0], 4)]));
remove_source(&c, src.id).unwrap();
assert!(ratings(&c).unwrap().is_empty());
}
#[test]
fn watch_keeps_length_and_position_apart() {
let (d, mut c) = tmpdb();
let media = d.0.join("m");
std::fs::create_dir_all(&media).unwrap();
for n in ["a.mp4", "b.mp4"] {
std::fs::write(media.join(n), b"x").unwrap();
}
add_source(&c, &media).unwrap();
let src = sources(&c).unwrap().remove(0);
sync_source(&mut c, &src).unwrap();
let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
set_duration(&c, ids[0], 120.0).unwrap();
set_position(&c, ids[0], &Watch { duration: None, position: 30.0, at: 7 }).unwrap();
set_position(&c, ids[1], &Watch { duration: Some(60.0), position: 12.5, at: 9 }).unwrap();
set_duration(&c, ids[1], 61.0).unwrap();
let w = watch(&c).unwrap();
assert_eq!(w[&ids[0]], Watch { duration: Some(120.0), position: 30.0, at: 7 });
assert_eq!(w[&ids[1]], Watch { duration: Some(61.0), position: 12.5, at: 9 });
set_heat(&c, ids[0], &[0.0, 1.5, 3.25]).unwrap();
assert_eq!(heat(&c).unwrap()[&ids[0]], vec![0.0, 1.5, 3.25]);
remove_source(&c, src.id).unwrap();
assert!(watch(&c).unwrap().is_empty(), "removing the source forgets its videos");
assert!(heat(&c).unwrap().is_empty());
}
}