diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..654a781 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +data/assets +data/music +data/songs_dislike +data/songs_like +Cargo.lock diff --git a/.sync-exclude.lst b/.sync-exclude.lst new file mode 100644 index 0000000..c7f83c2 --- /dev/null +++ b/.sync-exclude.lst @@ -0,0 +1,2 @@ +target +.git diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4f23dcb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "stormripper" +version = "0.1.1" +edition = "2024" + +[dependencies] +iced = { version = "0.14.0", features = ["image", "smol"] } +reqwest = {version = "0.13.5", features = ["blocking", "json"]} +serde_json = "1.0.154" +url = "2.5.8" diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..b806396 --- /dev/null +++ b/build.sh @@ -0,0 +1,8 @@ +#!/usr/bin/bash + +# curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +# apk add musl-dev fontconfig ttf-dejavu + +cargo install --git https://github.com/qbus00/crabripper + +cargo run diff --git a/data/nocover.jpg b/data/nocover.jpg new file mode 100644 index 0000000..b817012 Binary files /dev/null and b/data/nocover.jpg differ diff --git a/src/bluefunc.rs b/src/bluefunc.rs new file mode 100644 index 0000000..853d7b5 --- /dev/null +++ b/src/bluefunc.rs @@ -0,0 +1,149 @@ + +/// Extracts the filename from a given path. +/// +/// Returns the filename: String if a filename exists and is valid UTF-8, +/// otherwise returns "". +/// +/// # Example +/// ``` +/// let song_title: String = bluefunc::get_filename(&song_path); +/// ``` +pub fn get_filename(path: &str) -> String { + std::path::Path::new(path) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("") + .to_string() +} +/// Extracts the filename without the extension from a given path. +/// +/// Returns `Some(filename)` if a filename exists and is valid UTF-8, +/// otherwise returns "". +/// +/// # Example +/// ``` +/// let song_title = bluefunc::get_filename_without_extension(&song_path); +/// ``` +pub fn get_filename_without_extension(path: &str) -> String { + std::path::Path::new(path) + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or("") + .to_string() +} +pub fn get_artist_and_title(song_path: &str) -> (String, String) { + let song_name_without_extension: String = get_filename_without_extension(&song_path); + let mut artist = String::new(); + let mut title = String::new(); + + //println!("song_name_without_extension: {}", &song_name_without_extension); + if song_name_without_extension.contains(" - ") { + artist = song_name_without_extension + .split(" - ") + .next() + .unwrap_or("") + .to_string(); + //println!("artist: {}", artist); + + title = song_name_without_extension + .split(" - ") + .last() + .unwrap_or("") + .to_string(); + //println!("title: {}", title); + } + + //println!("artist: {} title: {}", artist, title); + (artist, title) +} + +use std::collections::HashSet; +use std::fs::{File, OpenOptions}; +use std::io::{BufRead, BufReader, Write}; +use std::sync::RwLock; + +pub struct StringDatabase { + entries: RwLock>, + file: RwLock, +} + +impl StringDatabase { + pub fn open(path: &str) -> Self { + let file = OpenOptions::new() + .create(true) + .append(true) + .read(true) + .open(path) + .expect("Could not open database file"); + + let reader = BufReader::new( + File::open(path).expect("Could not read database") + ); + + let entries = reader + .lines() + .filter_map(Result::ok) + .collect::>(); + + Self { + entries: RwLock::new(entries), + file: RwLock::new(file), + } + } + + pub fn exists(&self, value: &str) -> bool { + self.entries.read().unwrap().contains(value) + } + + pub fn save(&self, value: &str) -> bool { + let mut entries = self.entries.write().unwrap(); + + if entries.contains(value) { + return false; + } + + let mut file = self.file.write().unwrap(); + + writeln!(file, "{}", value) + .expect("Could not write database"); + + entries.insert(value.to_string()); + + true + } +} + +pub fn search_cover(artist: &str, song: &str) -> Result> { + println!("search_cover({}, {})", artist, song); + let cover_path = format!("data/assets/{} - {}.jpg", artist, song); + + if std::path::Path::new(&cover_path).exists() { + //println!("File exists"); + Ok(cover_path) + } else { + let client = reqwest::blocking::Client::new(); + let term = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("term", &format!("{} {}", artist, song)) + .append_pair("entity", "song") + .append_pair("limit", "5") + .finish(); + let url = format!("https://itunes.apple.com/search?{}", term); + let response: serde_json::Value = client + .get(&url) + .send()? + .error_for_status()? + .json()?; + let Some(artwork) = response["results"][0]["artworkUrl100"].as_str() else { + return Ok("nocover.jpg".to_string()); + }; + let image = client + .get(artwork) + .send()? + .error_for_status()? + .bytes()?; + if std::fs::write(&cover_path, image).is_err() { + return Ok("data/nocover.jpg".to_string()); + } + Ok(cover_path) + } +} diff --git a/src/lib_mpv.rs b/src/lib_mpv.rs new file mode 100644 index 0000000..e3de90e --- /dev/null +++ b/src/lib_mpv.rs @@ -0,0 +1,98 @@ +use std::io::{BufRead, BufReader, Write}; +use std::os::unix::net::UnixStream; + +use serde_json::{json, Value}; + +// mpv --idle --input-ipc-server=/tmp/mpvsocket song.mp3 + + +//let mut mpv = Mpv::connect().unwrap(); +//seek(&mut mpv, 220.00); + + +pub struct Mpv { + stream: UnixStream, +} + +impl Mpv { + pub fn connect() -> std::io::Result { + let stream = UnixStream::connect("/tmp/mpvsocket")?; + Ok(Self { stream }) + } + + pub fn command(&mut self, args: Vec) -> std::io::Result { + let request = json!({ + "command": args + }); + + let message = format!("{}\n", request); + + self.stream.write_all(message.as_bytes())?; + self.stream.flush()?; + + let mut reader = BufReader::new(self.stream.try_clone()?); + let mut response = String::new(); + + reader.read_line(&mut response)?; + + Ok(serde_json::from_str(&response).unwrap_or(Value::Null)) + } +} + +pub fn play(mpv: &mut Mpv) { + mpv.command(vec![ + json!("set_property"), + json!("pause"), + json!(false) + ]).unwrap(); +} +pub fn pause(mpv: &mut Mpv) { + mpv.command(vec![ + json!("set_property"), + json!("pause"), + json!(true) + ]).unwrap(); +} +pub fn seek(mpv: &mut Mpv, time_sec: f64) { + mpv.command(vec![ + json!("seek"), + json!(time_sec), + json!("absolute") + ]).unwrap(); +} +pub fn get_duration(mpv: &mut Mpv) -> f64 { + let data = mpv.command(vec![ + json!("get_property"), + json!("duration") + ]).unwrap(); + println!("duration: {}", data["data"]); + let duration: f64 = data["data"].as_f64().unwrap_or(0.0); + duration +} +pub fn get_position(mpv: &mut Mpv) -> f64 { + let data = mpv.command(vec![ + json!("get_property"), + json!("time-pos") + ]).unwrap(); + println!("position: {}", data["data"]); + let position: f64 = data["data"].as_f64().unwrap_or(0.0); + position +} +pub fn get_title(mpv: &mut Mpv) -> f64 { + let data = mpv.command(vec![ + json!("get_property"), + json!("media-title") + ]).unwrap(); + println!("title: {}", data["data"]); + let title: f64 = data["data"].as_f64().unwrap_or(0.0); + title +} +pub fn get_filename(mpv: &mut Mpv) -> String { + let data = mpv.command(vec![ + json!("get_property"), + json!("filename") + ]).unwrap(); + println!("filename: {}", data["data"]); + let filename: String = data["data"].to_string(); + filename +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..94d1199 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,591 @@ +use iced::widget::{button, column, container, text, text_input, grid, scrollable, row, image, slider}; +use iced::{Background, Color, Element, Fill}; +//use iced::time::{self, Duration, Instant}; +//use iced::Subscription; + +#[allow(dead_code)] +mod bluefunc; +#[allow(dead_code)] +mod lib_mpv; + +#[derive(Debug, Clone)] +enum Message { + SwitchStreamripper1, + SwitchStreamripper2, + SwitchStreamripper3, + SwitchStreamripper4, + SearchNameChanged(String), + ReloadSongList(bool), + SongLike(String), + SongDislike(String), + SongSkip(String), + SongClicked(String), + SongStartStop(), + SongSeek(f64), + //Timer(Instant), +} + +//#[derive(Default)] +struct Data { + streamripper1_process: Option, + streamripper2_process: Option, + streamripper3_process: Option, + streamripper4_process: Option, + streamripper1_button_text: String, + streamripper2_button_text: String, + streamripper3_button_text: String, + streamripper4_button_text: String, + mpv_process: Option, + playing_song_path: String, + playing_song_artist: String, + playing_song_title: String, + playing_song_cover: String, + search_song: String, + songs: Vec, + radios: Vec, + seek: f64, + button_play_text: String, + //timer_enabled: bool, +} +impl Default for Data { + fn default() -> Self { + Self { + streamripper1_process: None, + streamripper2_process: None, + streamripper3_process: None, + streamripper4_process: None, + streamripper1_button_text: "▶ BRF".to_string(), + streamripper2_button_text: "▶ 1Live".to_string(), + streamripper3_button_text: "▶ Classic21".to_string(), + streamripper4_button_text: "▶ Vivacité".to_string(), + mpv_process: None, + playing_song_path: String::new(), + playing_song_artist: String::new(), + playing_song_title: String::new(), + playing_song_cover: String::new(), + search_song: String::new(), + songs: Vec::new(), + radios: Vec::new(), + seek: 0.0, + button_play_text: "▶".to_string(), + //timer_enabled: false, + } + } +} +impl Drop for Data { + fn drop(&mut self) { + if let Some(mut child) = self.streamripper1_process.take() { + let _ = child.kill(); + let _ = child.wait(); + } + if let Some(mut child) = self.streamripper2_process.take() { + let _ = child.kill(); + let _ = child.wait(); + } + if let Some(mut child) = self.streamripper3_process.take() { + let _ = child.kill(); + let _ = child.wait(); + } + if let Some(mut child) = self.mpv_process.take() { + let _ = child.kill(); + let _ = child.wait(); + } + // Delete incomplete Folders + let _stations = match std::fs::read_dir("./data/music/") { + Ok(stations) => { + for station in stations { + let station_name: String = station.unwrap().path().display().to_string(); + println!("station_name: {}", &station_name); + let _ = std::process::Command::new("rm") + .arg("-r") + .arg(format!("{}/incomplete", &station_name)) + .spawn(); + } + } + Err(e) => { + println!("Can't read ./data/music/ {}", e); + } + }; + } +} + +fn main() -> iced::Result { + println!("Starte..."); + iced::run(update, view) +} +/* +fn subscription(data: &Data) -> Subscription { + if data.timer_enabled { + time::every(Duration::from_secs(1)) + } else { + Subscription::none() + } +}*/ + +/* +fn subscription(data: &mut Data, message: Message) -> Subscription { + iced::time::every(std::time::Duration::from_secs(1)) + .map(Message::Timer) +}*/ + +fn update(data: &mut Data, message: Message) { + match message { + //Message::Timer(_instant) => { + // println!("Timer()"); + //} + Message::SongSeek(seek_value) => { + data.seek = seek_value; + println!("seek_value: {}", seek_value); + let mut mpv = lib_mpv::Mpv::connect().unwrap(); + lib_mpv::seek(&mut mpv, seek_value); + }, + Message::SongLike(song_path) => { + println!("SongLike({})", song_path); + let song_title = bluefunc::get_filename(&song_path); + println!("song_title: {}", song_title); + + if data.playing_song_path == song_path { + if let Some(mut child) = data.mpv_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.playing_song_path = String::new(); + } + } + + let _ = std::process::Command::new("mv") + .arg(&song_path) + .arg(format!("/home/kenny/Musik/{}", &song_title)) + .spawn(); + + let song_name_without_extension: String = bluefunc::get_filename_without_extension(&song_path); + //bluefunc::set_data(song_name_without_extension, "skip".to_string(), "./data/songs_db"); + let db = bluefunc::StringDatabase::open("data/songs_like"); + db.save(&song_name_without_extension); + + update(data, Message::ReloadSongList(true)); + }, + Message::SongDislike(song_path) => { + println!("SongDislike({})", song_path); + let song_title = bluefunc::get_filename(&song_path); + println!("song_title: {}", song_title); + + if data.playing_song_path == song_path { + if let Some(mut child) = data.mpv_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.playing_song_path = String::new(); + } + } + + let _ = std::process::Command::new("rm") + .arg(&song_path) + .spawn(); + + let song_name_without_extension: String = bluefunc::get_filename_without_extension(&song_path); + let db = bluefunc::StringDatabase::open("data/songs_dislike"); + db.save(&song_name_without_extension); + + update(data, Message::ReloadSongList(true)); + }, + Message::SongSkip(song_path) => { + println!("SongSkip({})", song_path); + + if data.playing_song_path == song_path { + if let Some(mut child) = data.mpv_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.playing_song_path = String::new(); + } + } + + let _ = std::process::Command::new("rm") + .arg(&song_path) + .spawn(); + + update(data, Message::ReloadSongList(true)) + }, + Message::SongClicked(song_path) => { + println!("SongClicked({})", song_path); + + let (artist, title) = bluefunc::get_artist_and_title(&song_path); + data.playing_song_artist = artist.clone(); + data.playing_song_title = title.clone(); + data.playing_song_cover = bluefunc::search_cover(&artist, &title).unwrap(); + data.playing_song_path = song_path.clone(); + update(data, Message::SongStartStop()); + }, + Message::SwitchStreamripper1 => { + println!("SwitchStreamripper1()"); + if data.streamripper1_process.is_none() { + match std::process::Command::new("crabripper") + .arg("https://streaming.brf.be/brf1-high.mp3") + .arg("-d") + .arg("./data/music/") + .spawn() + { + Ok(child) => { + data.streamripper1_process = Some(child); + data.streamripper1_button_text = "■ BRF".into(); + } + Err(e) => { + println!("Fehler: {e}"); + } + } + } else { + if let Some(mut child) = data.streamripper1_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.streamripper1_button_text = "▶ BRF".into(); + } + } + }, + Message::SwitchStreamripper2 => { + println!("SwitchStreamripper2()"); + if data.streamripper2_process.is_none() { + match std::process::Command::new("crabripper") + .arg("https://wdr-1live-live.icecastssl.wdr.de/wdr/1live/live/mp3/128/stream.mp3") + .arg("-d") + .arg("./data/music/") + .spawn() + { + Ok(child) => { + data.streamripper2_process = Some(child); + data.streamripper2_button_text = "■ 1Live".into(); + } + Err(e) => { + println!("Fehler: {e}"); + } + } + } else { + if let Some(mut child) = data.streamripper2_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.streamripper2_button_text = "▶ 1Live".into(); + } + } + }, + Message::SwitchStreamripper3 => { + println!("SwitchStreamripper3()"); + if data.streamripper3_process.is_none() { + match std::process::Command::new("crabripper") + .arg("http://radios.rtbf.be/classic21-128.mp3") + .arg("-d") + .arg("./data/music/") + .spawn() + { + Ok(child) => { + data.streamripper3_process = Some(child); + data.streamripper3_button_text = "■ Classic21".into(); + } + Err(e) => { + println!("Fehler: {e}"); + } + } + } else { + if let Some(mut child) = data.streamripper3_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.streamripper3_button_text = "▶ Classic21".into(); + } + } + }, + Message::SwitchStreamripper4 => { + println!("SwitchStreamripper4()"); + if data.streamripper4_process.is_none() { + match std::process::Command::new("crabripper") + .arg("https://radio.rtbf.be/viva-lg/mp3-160/me") + .arg("-d") + .arg("./data/music/") + .spawn() + { + Ok(child) => { + data.streamripper4_process = Some(child); + data.streamripper4_button_text = "■ Vivacité".into(); + } + Err(e) => { + println!("Fehler: {e}"); + } + } + } else { + if let Some(mut child) = data.streamripper4_process.take() { + let _ = child.kill(); + let _ = child.wait(); + data.streamripper4_button_text = "▶ Vivacité".into(); + } + } + }, + Message::SearchNameChanged(name) => { + println!("SearchNameChanged({})", name); + data.search_song = name.to_lowercase(); + update(data, Message::ReloadSongList(false)); + },/* + Message::SongStartStop(song_path) => { + println!("SongStartStop({})", song_path); + if let Some(mut child) = data.mpv_process.take() { + let _ = child.kill(); + let _ = child.wait(); + } + if data.playing_song_path == song_path { + println!("Stop playing Music"); + data.playing_song_path = String::new(); + data.button_play_text = "▶".to_string(); + } else { + data.playing_song_path = song_path.clone(); + data.button_play_text = "⏹".to_string(); + + match std::process::Command::new("mpv") + .arg("--input-ipc-server=/tmp/mpvsocket") + .arg("--no-video") + .arg("\"") + .arg(&song_path) + .arg("\"") + .spawn() + { + Ok(child) => { + data.mpv_process = Some(child); + println!("playing: {}", song_path); + } + Err(e) => { + println!("Fehler bei der wiedergabe von {}: {}", &song_path, e); + } + } + } + },*/ + Message::SongStartStop() => { + println!("SongStartStop()"); + if let Some(mut child) = data.mpv_process.take() { + // Stop + let _ = child.kill(); + let _ = child.wait(); + data.button_play_text = "▶".to_string(); + } else { + // Play + data.button_play_text = "⏹".to_string(); + match std::process::Command::new("mpv") + .arg("--input-ipc-server=/tmp/mpvsocket") + .arg("--no-video") + .arg("\"") + .arg(&data.playing_song_path) + .arg("\"") + .spawn() + { + Ok(child) => { + data.mpv_process = Some(child); + println!("playing: {}", &data.playing_song_path); + } + Err(e) => { + println!("Fehler bei der wiedergabe von {}: {}", &data.playing_song_path, e); + } + } + } + }, + Message::ReloadSongList(play_first) => { + println!("ReloadSongList({})", play_first); + data.songs.clear(); + data.radios.clear(); + + let db_like = bluefunc::StringDatabase::open("data/songs_like"); + let db_dislike = bluefunc::StringDatabase::open("data/songs_dislike"); + + let _radios = match std::fs::read_dir("./data/radio/") { + Ok(radios) => { + for radio in radios { + let radio_path: String = radio.unwrap().path().display().to_string(); + let radio_name: String = bluefunc::get_filename_without_extension(&radio_path); + //data.radios.push(radio_path.clone()); + data.radios.push(radio_name.clone()); + } + } + Err(e) => { + println!("Can't read radios: {}", e); + } + }; + + let _stations = match std::fs::read_dir("./data/music/") { + Ok(stations) => { + for station in stations { + let station_name: String = station.unwrap().path().display().to_string(); + + let _paths = match std::fs::read_dir(format!("{}/", &station_name)) { + Ok(paths) => { + for path in paths { + let song_path: String = path.unwrap().path().display().to_string(); + let song_name: String = bluefunc::get_filename_without_extension(&song_path); + let song_path_lowercase = song_path.to_lowercase(); + + if song_path_lowercase.contains(&data.search_song) { + if song_path_lowercase.contains("/incomplete") {} else { + if db_like.exists(&song_name) { + let _ = std::process::Command::new("rm") + .arg(&song_path) + .spawn(); + } else { + if db_dislike.exists(&song_name) { + let _ = std::process::Command::new("rm") + .arg(&song_path) + .spawn(); + } else { + //let (artist, title) = bluefunc::get_artist_and_title(&song_path); + //let _ = bluefunc::search_cover(&artist, &title); + + data.songs.push(song_path.clone()); + } + } + } + } + } + } + Err(e) => { + println!("Can't read station: {} - {}", &station_name, e); + } + }; + + } + } + Err(e) => { + println!("Can't read stations: {}", e); + } + }; + + if play_first { + if let Some(first) = data.songs.first() { + println!("{}", first); + update(data, Message::SongClicked(first.clone())); + } + } + } + } +} + +fn my_grid_item(song_path: &str) -> Element<'_, Message> { + let song_title: String = bluefunc::get_filename_without_extension(&song_path); + let (artist, title) = bluefunc::get_artist_and_title(&song_path); + let mut cover_path = format!("data/assets/{} - {}.jpg", artist, title); + if std::path::Path::new(&cover_path).exists() {} else { + cover_path = "data/nocover.jpg".to_string(); + }; + /* + stack![ + image("./cover.jpg") + .width(Fill) + .height(Fill), + + column![ + text("Hello World!"), + text("This is on top of the background.") + ] + .padding(20) + ] + .width(Fill) + .height(Fill) + .into() + */ + + button( + container( + column![ + text(song_title) + .center(), + image(cover_path).width(250).height(250), + ] + ) + .padding(15) + .width(Fill) + ) + .on_press(Message::SongClicked(song_path.to_string())) + .into() +} + +fn my_radio_item(radio_path: &str) -> Element<'_, Message> { + button( + text(radio_path) + .center(), + ) + .height(20) + .width(50) + //.on_press(Message::SongClicked(song_path.to_string())) + .into() +} + +fn view(data: &Data) -> Element<'_, Message> { + let items: Vec> = data.songs + .iter() + .map(|song_path| { + my_grid_item(song_path) + }) + .collect(); + + let radios: Vec> = data.radios + .iter() + .map(|radio_url| { + my_radio_item(radio_url) + }) + .collect(); + + container( + column![ + /* + row![ + button(text(&data.streamripper1_button_text)).on_press(Message::SwitchStreamripper1), + button(text(&data.streamripper2_button_text)).on_press(Message::SwitchStreamripper2), + button(text(&data.streamripper3_button_text)).on_press(Message::SwitchStreamripper3), + button(text(&data.streamripper4_button_text)).on_press(Message::SwitchStreamripper4), + ], + */ + scrollable( + grid(radios) + .columns(4) + .spacing(5) + ).height(25).width(Fill), + + row![ + text("New Music: "), + text_input("search song name or artist", &data.search_song) + .on_input(Message::SearchNameChanged), + ], + scrollable( + grid(items).columns(4).spacing(5) + ).height(500).width(Fill), + + row![ + image(data.playing_song_cover.clone()).width(200).height(200), + column![ + text!("{} - {}", &data.playing_song_artist, &data.playing_song_title), + row![ + button(text(&data.button_play_text)) + .on_press(Message::SongStartStop()), + slider(0.0..=100.0, data.seek, Message::SongSeek), + ].padding(10).spacing(10), + row![ + button("♥️ Like") + .on_press(Message::SongLike(data.playing_song_path.to_string())) + .style(|_theme, _status| button::Style { + background: Some(Background::Color(Color::from_rgb(0.0, 0.0, 1.0))), + text_color: Color::WHITE, + ..Default::default() + }), + button("⏭️ Skip") + .on_press(Message::SongSkip(data.playing_song_path.to_string())) + .style(|_theme, _status| button::Style { + background: Some(Background::Color(Color::from_rgb(1.0, 0.5, 0.0))), + text_color: Color::WHITE, + ..Default::default() + }), + button("👎 Dislike") + .on_press(Message::SongDislike(data.playing_song_path.to_string())) + .style(|_theme, _status| button::Style { + background: Some(Background::Color(Color::from_rgb(1.0, 0.0, 0.0))), + text_color: Color::WHITE, + ..Default::default() + }), + ].padding(10).spacing(10), + ].padding(10).spacing(10), + + ].height(300), + ] + .spacing(10) + .padding(5) + ) + .into() // Transform Widget into Element + +}