Files
rate_music/src/main.rs
2026-03-21 22:01:34 +01:00

90 lines
2.7 KiB
Rust

mod database;
mod http_server;
mod player;
use std::{env::args, sync::Arc, time::Duration};
use tokio::{join, sync::watch};
#[tokio::main]
async fn main() {
// Initialize the database
let db = Arc::new(
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 {
// Check if the parameter is -l
if username == "-l" {
db.get_user_most_ratings()
.await
.expect("Could not get ratings");
return;
} 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 a new user first. This can be achieved by using rate_music [name] [user_id]");
return;
}
// Instantiate the mpris channel
// Channel size 1 makes sure we always have the correct song in the queue
let (mpris_tx, mut mpris_rx) = watch::channel((String::new(), String::new()));
let mpris_tx_http = mpris_tx.clone();
std::thread::spawn(move || {
let player = player::MprisPlayer::new().expect("Could not create player");
loop {
if let Ok((interpret, track)) = player.get_interpret_and_track() {
if let Err(e) = mpris_tx.send((interpret, track)) {
println!("Error sending interpret and track: {e}");
}
}
// Use the std sleep here to avoid an await which will requires player to be Send.
std::thread::sleep(Duration::from_millis(1000));
}
});
// Create the HTTP backend
let db_http = db.clone();
let http_handle = tokio::spawn(async move {
http_server::http_serve(&db_http, mpris_tx_http).await;
});
eprintln!("Servermode...");
let res = join!(http_handle);
if let Err(e) = res.0 {
eprintln!("{e}");
}
}