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
);
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)]
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());
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: if r.get::<_, i64>(2)? == 1 { Kind::Video } else { 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()
}
}
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 = matches!(e.kind, Kind::Video) as i64;
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 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 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());
}
}