diff options
| author | Jakob L. Kreuze <zerodaysfordays@sdf.org> | 2020-05-17 22:52:42 -0400 |
|---|---|---|
| committer | Jakob L. Kreuze <zerodaysfordays@sdf.org> | 2020-05-17 22:52:42 -0400 |
| commit | 668606d9a584e6a55ba698ee5f6fb4892cf02a37 (patch) | |
| tree | c69bb15b2a726b4647502e39d3433434ea68add0 /src/main.rs | |
Initial commit.
Diffstat (limited to 'src/main.rs')
| -rw-r--r-- | src/main.rs | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..07cf4d6 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,82 @@ +extern crate rusqlite; + +use blake2::{Blake2b, Digest}; +use rusqlite::{params, Connection, Result}; +use std::io; +use std::path::Path; + +/// Return a hex-encoded string representing the contents of `hash`. +fn hexlify(hash: &[u8]) -> String { + hash.iter() + .map(|b| format!("{:x}", b)) + .collect::<Vec<String>>() + .join("") +} + +#[derive(Debug)] +struct TagBase { + conn: Connection, +} + +impl TagBase { + /// Instantiate a new `TagBase` whose backing database is at `path`. + fn new(path: &str) -> Result<Self> { + let conn = Connection::open(path)?; + conn.execute( + "CREATE TABLE IF NOT EXISTS images ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + blake2 TEXT NOT NULL, + filename TEXT NOT NULL, + orig_dir TEXT NOT NULL + )", + params![], + )?; + conn.execute( + "CREATE TABLE IF NOT EXISTS tags ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL + )", + params![], + )?; + conn.execute( + "CREATE TABLE IF NOT EXISTS mapping ( + image INTEGER NOT NULL, + tag INTEGER NOT NULL + )", + params![], + )?; + Ok(TagBase { conn }) + } + + // TODO: Return a proper error. + fn import_image(&self, path: &Path) -> Result<()> { + if path.is_dir() { + return Err(rusqlite::Error::InvalidQuery); + } + + let mut file = std::fs::File::open(path).unwrap(); + let mut hasher = Blake2b::new(); + let n = io::copy(&mut file, &mut hasher).unwrap(); + let hash = hexlify(&hasher.result()); + + let parsed_or_none = path.file_name().and_then(|os| os.to_str()); + if let (Some(path), Some(file_name)) = (path.to_str(), parsed_or_none) { + let split_index = path.len() - file_name.len(); + let parent_directory = &path[0..split_index]; + self.conn.execute( + "INSERT INTO images (sha256, filename, orig_dir) VALUES(?,?,?)", + params![0, file_name, parent_directory], + )?; + Ok(()) + } else { + Err(rusqlite::Error::InvalidQuery) + } + } +} + +fn main() { + let tb = TagBase::new("/tmp/test.db").unwrap(); + tb.import_image(Path::new("/home/jakob/Sync/06fc9ae71549eb4d.jpeg")) + .unwrap(); + println!("{:?}", tb); +} |