Add rating loop

This commit is contained in:
2024-03-25 14:15:43 +01:00
parent 3a1fbd48d9
commit f464d039d2
2 changed files with 86 additions and 9 deletions

View File

@@ -1,7 +1,6 @@
use std::i64;
use anyhow::Result;
use ratatui::widgets::block::title;
use sqlx::{Row, SqlitePool};
pub struct Database {
@@ -52,7 +51,24 @@ impl Database {
Ok(())
}
pub async fn add_user(&self, user_id: i64, name: &str) -> Result<i64> {
pub async fn add_user(&self, name: &str) -> Result<i64> {
let mut conn = self.pool.acquire().await?;
let id = sqlx::query(
r#"
INSERT INTO users (name)
VALUES (?1)
"#,
)
.bind(name)
.execute(&mut *conn)
.await?
.last_insert_rowid();
Ok(id)
}
pub async fn add_user_id(&self, user_id: i64, name: &str) -> Result<i64> {
let mut conn = self.pool.acquire().await?;
let id = sqlx::query(
@@ -70,6 +86,22 @@ impl Database {
Ok(id)
}
pub async fn users_empty(&self) -> Result<bool> {
let mut conn = self.pool.acquire().await?;
let record = sqlx::query(
r#"
SELECT count(id) FROM users
"#,
)
.fetch_one(&mut *conn)
.await?;
let id: i64 = record.try_get("count(id)")?;
Ok(id <= 0)
}
pub async fn user_exists(&self, user_id: i64) -> Result<i64> {
let mut conn = self.pool.acquire().await?;

View File

@@ -2,24 +2,69 @@ mod database;
mod player;
mod userinterface;
use std::env::args;
use tokio;
#[tokio::main]
async fn main() {
// Initialize the mpris player
let player = player::MprisPlayer::new().expect("Could not create player");
// Initialize the database
let db = database::Database::new()
.await
.expect("Could not create database");
// Create the tables on an empty database
db.create_tables().await.unwrap();
if args().len() > 1 {
// Add a new user
let username = args().nth(1).unwrap();
if args().len() == 3 {
match args().nth(2).unwrap().parse::<i64>() {
Ok(id) => {
let user_id = db
.add_user_id(id, &username)
.await
.expect("Could not add user");
println!("UserID for {username}: {user_id}");
}
Err(e) => eprintln!("{e}"),
}
} else {
let user_id = db.add_user(&username).await.expect("Could not add user");
println!("UserID for {username}: {user_id}");
}
return;
}
let is_empty = db
.users_empty()
.await
.expect("Could not read from database");
if is_empty {
println!("Add an user first. This can be achieved by using rate_music [name] [user_id]");
return;
}
loop {
let (usernumber, userrating) = userinterface::get_user_rating(&db).await.expect("Lala");
let (interpret, song) = player
.get_interpret_and_track()
.expect("Could not read track");
db.user_add_rating(usernumber, &interpret, &song, userrating)
match player.get_interpret_and_track() {
Ok((interpret, song)) => {
if let Err(e) = db
.user_add_rating(usernumber, &interpret, &song, userrating)
.await
.expect("Can not add rating");
{
eprintln!("{e}");
}
}
Err(e) => {
eprintln!("{e}");
continue;
}
}
}
}