featadded database operations

This commit is contained in:
Nickiel12 2022-12-12 22:30:03 -08:00
parent b6a41c8fb2
commit 4e36010d13
4 changed files with 116 additions and 46 deletions

View file

@ -14,3 +14,5 @@ serde = { version = "1.0.143", features = ["derive"] }
serde_json = "1.0.83" serde_json = "1.0.83"
rusqlite = {version="0.28.0", features=["bundled"]} rusqlite = {version="0.28.0", features=["bundled"]}
scan_dir = "0.3.3" scan_dir = "0.3.3"
derive_more = "0.99.17"
id3 = "1.5.1"

63
src/db_operations.rs Normal file
View file

@ -0,0 +1,63 @@
use derive_more::From;
use rusqlite::{params, Connection, Params, Result};
use crate::file_operations::ItemTag;
#[derive(From, Debug)]
pub enum DatabaseCreationError {
RusqliteError(rusqlite::Error),
IoError(std::io::Error),
}
pub struct DBObject {
pub conn: Connection,
}
impl DBObject {
pub fn new(
db_filepath: &std::path::PathBuf,
in_memory: bool,
) -> Result<Self, DatabaseCreationError> {
let conn: Connection;
std::fs::create_dir_all(db_filepath.parent().unwrap())?;
if in_memory {
conn = Connection::open_in_memory()?;
} else {
conn = Connection::open(db_filepath)?;
}
// CREATE TABLE IF NOT EXISTS comment (
// id INTEGER PRIMARY KEY,
// email TEXT,
// author TEXT,
// text TEXT NOT NULL,
// timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
// content_id TEXT NOT NULL,
// parent INTEGER
// )
conn.execute(
"CREATE TABLE IF NOT EXISTS musicinfo (
path TEXT PRIMARY KEY,
title TEXT NOT NULL,
artist TEXT,
album TEXT,
album_artist TEXT
)",
params![],
)?;
Ok(DBObject { conn })
}
pub fn save_tag(self: &Self, tag: &ItemTag) -> Result<(), DatabaseCreationError> {
self.conn.execute(
"INSERT INTO musicinfo (path, title, artist, album, album_artist) VALUES ( ?1, ?2, ?3, ?4, ?5 )",
params![tag.path, tag.title, tag.artist, tag.album, tag.album_artist],
)?;
Ok(())
}
}

View file

@ -1,3 +1,4 @@
use id3::{Tag, TagLike};
use std::path::PathBuf; use std::path::PathBuf;
use scan_dir::ScanDir; use scan_dir::ScanDir;
@ -73,49 +74,45 @@ impl Iterator for MusicScanner {
} }
} }
/// Recursivly scans the given root directory for files pub struct ItemTag {
/// WIP Function! All it does is print the directories pub path: String,
/// pub title: String,
/// # Examples pub artist: String,
/// pub album: String,
/// ```rust pub album_artist: String,
/// scan_music_dir("/home/Documents/RustedBeats"); }
///
///>>> "I found a directory src at .../src" impl ItemTag {
///>>> "I found a directory debug at .../debug" pub fn new() -> Self {
///>>> "I found a file Cargo.toml at .../Cargo.toml" ItemTag {
///... path: String::new(),
/// ``` title: String::new(),
/// artist: String::new(),
pub fn scan_music_dir(root: String) -> Result<(), ()> { album: String::new(),
let mut directories = Vec::<PathBuf>::new(); album_artist: String::new(),
directories.push(root.into()); }
}
while directories.len() != 0 { }
let target = match directories.pop() {
Some(val) => val, pub fn get_tag(filepath: &PathBuf) -> Result<ItemTag, id3::Error> {
None => { let tag = Tag::read_from_path(filepath)?;
panic!("Whoa man this ai't right");
} let mut output_tag = ItemTag::new();
}; output_tag.path = filepath.to_string_lossy().into_owned();
ScanDir::dirs() // Get a bunch of frames...
.read(target.clone(), |iter| { if let Some(artist) = tag.artist() {
for (entry, name) in iter { output_tag.artist = artist.to_string();
directories.push(entry.path()); println!("artist: {}", artist);
println!("I found a director {:?} at path {:?}", name, entry.path()); }
} if let Some(title) = tag.title() {
}) output_tag.title = title.to_string();
.unwrap(); println!("title: {}", title);
}
ScanDir::files() if let Some(album) = tag.album() {
.read(target, |iter| { output_tag.album = album.to_string();
for (entry, name) in iter { println!("album: {}", album);
println!("found file {:?} at path {:?}", name, entry.path()); }
}
}) Ok(output_tag)
.unwrap();
}
Ok(())
} }

View file

@ -1,6 +1,9 @@
use std::path::PathBuf;
use clap::Parser; use clap::Parser;
use dirs_next; use dirs_next;
pub mod db_operations;
pub mod file_operations; pub mod file_operations;
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
@ -38,20 +41,25 @@ fn main() {
let music_dir: String; let music_dir: String;
if cli.root_directory.is_some() { if cli.root_directory.is_some() {
music_dir = cli.root_directory.clone().unwrap(); music_dir = cli.root_directory.clone().unwrap();
println!(
"Music directory is: {}",
cli.root_directory.clone().unwrap()
);
} else { } else {
music_dir = String::from(dirs_next::audio_dir().unwrap().to_str().unwrap()); music_dir = String::from(dirs_next::audio_dir().unwrap().to_str().unwrap());
println!("Music directory is: {:?}", dirs_next::audio_dir());
} }
let music_scanner = file_operations::MusicScanner::new(music_dir); let music_scanner = file_operations::MusicScanner::new(music_dir);
let mut db_path = PathBuf::new();
db_path.push("/home/nixolas/RustedBeats.db");
let dbo = db_operations::DBObject::new(&db_path, false).unwrap();
for file_batch in music_scanner { for file_batch in music_scanner {
for filepath in file_batch { for filepath in file_batch {
println!("{:?}", filepath); if filepath.to_string_lossy().ends_with(".wav") {
continue;
} else {
let tag = file_operations::get_tag(&filepath).unwrap();
dbo.save_tag(&tag).unwrap();
}
} }
} }