Compare commits

...

4 commits

Author SHA1 Message Date
5d3c22aaad album list stream 2024-11-07 19:53:57 +01:00
62d9f74a39 Revert "don't print auth token on mpv logs"
This reverts commit e52adda2ed.

guilty
2024-11-07 11:41:41 +01:00
0cbf091b91 property limits etc 2024-11-07 10:05:26 +01:00
2b9b6ee6c7 cover art api 2024-11-07 10:01:28 +01:00
7 changed files with 188 additions and 99 deletions

View file

@ -27,8 +27,6 @@ mod imp {
#[property(get, set)]
track: Cell<i64>,
#[property(get, set)]
cover_art_url: RefCell<String>,
#[property(get, set)]
stream_url: RefCell<String>,
@ -83,8 +81,7 @@ impl Song {
.property("album", &song.album)
.property("genre", &song.genre)
.property("duration", song.duration as i64)
//.property("track", song.track)
.property("cover-art-url", api.cover_art_url(&song.id, 0).as_str())
.property("track", song.track.map(i64::from).unwrap_or(-1))
.property("stream-url", api.stream_url(&song.id).as_str())
.build();
@ -96,7 +93,7 @@ impl Song {
.thumbnail_loading
.replace(Some(glib::spawn_future_local(async move {
let bytes = api
.cover_art(&id, 50) // TODO: constify thumbnail size, maybe take dpi into account etc
.cover_art(&id, Some(50)) // TODO: WidgetExt::scale_factor
.await
.unwrap();
let song = match song_weak.upgrade() {

View file

@ -1,5 +1,8 @@
pub mod schema;
mod album_list;
pub use album_list::AlbumListType;
use bytes::Bytes;
use md5::Digest;
use rand::Rng;
@ -49,13 +52,13 @@ impl From<reqwest::Error> for Error {
}
}
#[derive(Clone)]
pub struct Client {
client: reqwest::Client,
base_url: reqwest::Url,
token: String,
}
fn get_random_salt(length: usize) -> String {
fn random_salt(length: usize) -> String {
let mut rng = rand::thread_rng();
std::iter::repeat(())
// 0.9: s/distributions/distr
@ -70,7 +73,7 @@ impl Client {
const SALT_BYTES: usize = 8;
// subsonic docs say to generate a salt per request, but that's completely unnecessary
let salt_hex = get_random_salt(SALT_BYTES);
let salt_hex = random_salt(SALT_BYTES);
let mut hasher = md5::Md5::new();
hasher.update(password);
@ -104,14 +107,9 @@ impl Client {
.user_agent(crate::USER_AGENT)
.build()?,
base_url,
token: token.to_string(),
})
}
pub fn strip_token(&self, string: &str) -> String {
string.replace(&self.token, "[authentication token]")
}
async fn send<T: serde::de::DeserializeOwned + Send + 'static>(
&self,
request: reqwest::RequestBuilder,
@ -153,10 +151,51 @@ impl Client {
}
}
async fn send_bytes(&self, request: reqwest::RequestBuilder) -> Result<Bytes, Error> {
fn url(&self, path: &[&str], query: &[(&str, &str)]) -> url::Url {
let mut url = self.base_url.clone();
url.path_segments_mut()
// literally can't fail
.unwrap_or_else(|_| unsafe { std::hint::unreachable_unchecked() })
.extend(path);
url.query_pairs_mut().extend_pairs(query);
url
}
async fn get<T: serde::de::DeserializeOwned + Send + 'static>(
&self,
path: &[&str],
query: &[(&str, &str)],
) -> Result<T, Error> {
self.send(self.client.get(self.url(path, query))).await
}
pub async fn ping(&self) -> Result<(), Error> {
self.get(&["rest", "ping"], &[]).await
}
pub async fn random_songs(&self, size: u32) -> Result<Vec<schema::Child>, Error> {
self.get::<schema::RandomSongsOuter>(
&["rest", "getRandomSongs"],
&[("size", &size.to_string())],
)
.await
.map(|response| response.random_songs.song)
}
pub fn cover_art_url(&self, id: &str, size: Option<u32>) -> url::Url {
match size {
None => self.url(&["rest", "getCoverArt"], &[("id", id)]),
Some(size) => self.url(
&["rest", "getCoverArt"],
&[("id", id), ("size", &size.to_string())],
),
}
}
pub async fn cover_art(&self, id: &str, size: Option<u32>) -> Result<Bytes, Error> {
let (sender, receiver) = async_channel::bounded(1);
let future = request.send();
let future = self.client.get(self.cover_art_url(id, size)).send();
runtime().spawn(async move {
async fn perform(
response: Result<reqwest::Response, reqwest::Error>,
@ -197,53 +236,6 @@ impl Client {
.expect("could not receive cover art bytes from tokio")
}
fn url(&self, path: &[&str], query: &[(&str, &str)]) -> url::Url {
let mut url = self.base_url.clone();
url.path_segments_mut()
// literally can't fail
.unwrap_or_else(|_| unsafe { std::hint::unreachable_unchecked() })
.extend(path);
url.query_pairs_mut().extend_pairs(query);
url
}
async fn get<T: serde::de::DeserializeOwned + Send + 'static>(
&self,
path: &[&str],
query: &[(&str, &str)],
) -> Result<T, Error> {
self.send(self.client.get(self.url(path, query))).await
}
pub async fn ping(&self) -> Result<(), Error> {
self.get(&["rest", "ping"], &[]).await
}
pub async fn get_random_songs(&self, size: u32) -> Result<Vec<schema::Child>, Error> {
self.get::<schema::RandomSongsOuter>(
&["rest", "getRandomSongs"],
&[("size", &size.to_string())],
)
.await
.map(|response| response.random_songs.song)
}
pub fn cover_art_url(&self, id: &str, size: u32) -> url::Url {
if size == 0 {
self.url(&["rest", "getCoverArt"], &[("id", id)])
} else {
self.url(
&["rest", "getCoverArt"],
&[("id", id), ("size", &size.to_string())],
)
}
}
pub async fn cover_art(&self, id: &str, size: u32) -> Result<Bytes, Error> {
self.send_bytes(self.client.get(self.cover_art_url(id, size)))
.await
}
pub fn stream_url(&self, id: &str) -> url::Url {
self.url(&["rest", "stream"], &[("id", id)])
}

View file

@ -0,0 +1,67 @@
use super::{schema, Client, Error};
use futures::{Stream, TryStreamExt};
#[derive(Clone, Debug)]
pub enum AlbumListType {
Random,
Newest,
Highest,
Frequent,
Recent,
AlphabeticalByName,
AlphabeticalByArtist,
ByYear { from: u32, to: u32 },
ByGenre(String),
}
impl Client {
pub async fn album_list(
&self,
type_: &AlbumListType,
size: u32,
offset: u32,
) -> Result<Vec<schema::AlbumID3>, Error> {
match type_ {
AlbumListType::Newest => {
self.get::<schema::AlbumList2Outer>(
&["rest", "getAlbumList2"],
&[
("type", "newest"),
("size", &size.to_string()),
("offset", &offset.to_string()),
],
)
.await
}
_ => todo!("{type_:?}"),
}
.map(|response| match response.album_list2.album {
Some(albums) => albums,
None => vec![],
})
}
pub fn album_list_full(
&self,
type_: AlbumListType,
) -> impl Stream<Item = Result<schema::AlbumID3, Error>> + use<'_> {
futures::stream::try_unfold(0usize, move |offset| {
let type_ = type_.clone();
async move {
match self.album_list(&type_, 500, offset as u32).await {
Ok(albums) if albums.len() == 0 => Ok(None),
Ok(albums) => {
let next_offset = offset + albums.len();
Ok(Some((
futures::stream::iter(albums.into_iter().map(Result::Ok)),
next_offset,
)))
}
Err(err) => Err(err),
}
}
})
.try_flatten()
}
}

View file

@ -1,3 +1,4 @@
use chrono::{offset::Utc, DateTime};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
@ -44,10 +45,40 @@ pub struct Child {
pub artist: String,
pub track: Option<u32>,
pub year: Option<u32>,
pub starred: Option<chrono::DateTime<chrono::offset::Utc>>, // TODO: check which is best
pub starred: Option<DateTime<Utc>>, // TODO: check which is best
// applicable
pub duration: u64,
pub duration: u32,
//pub play_count: Option<u32>,
pub genre: Option<String>,
pub cover_art: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlbumList2Outer {
pub album_list2: AlbumList2,
}
#[derive(Debug, Deserialize)]
pub struct AlbumList2 {
pub album: Option<Vec<AlbumID3>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlbumID3 {
pub id: String,
pub name: String,
pub artist: Option<String>,
pub artist_id: Option<String>,
pub cover_art: Option<String>,
pub song_count: u32,
pub duration: u32,
pub play_count: Option<u32>,
pub created: DateTime<Utc>,
pub starred: Option<DateTime<Utc>>,
pub year: Option<u32>,
pub genre: Option<String>,
pub played: Option<DateTime<Utc>>,
// TODO: opensubsonic extensions?
}

View file

@ -8,7 +8,7 @@ mod imp {
#[template(resource = "/eu/callcc/audrey/play_queue_song.ui")]
#[properties(wrapper_type = super::Song)]
pub struct Song {
#[property(type = i32, set = Self::set_playlist_pos)]
#[property(type = i64, set = Self::set_playlist_pos)]
_playlist_pos: (),
#[property(set, get)]
@ -167,9 +167,9 @@ mod imp {
true
}
fn set_playlist_pos(&self, playlist_pos: i32) {
fn set_playlist_pos(&self, playlist_pos: i64) {
self.obj()
.set_current(playlist_pos == self.position.get() as i32);
.set_current(playlist_pos == self.position.get() as i64);
}
}
}

View file

@ -95,7 +95,7 @@ mod imp {
#[template_callback]
fn on_skip_forward_clicked(&self) {
if self.window().playlist_pos() + 1 < self.window().playlist_count() as i32 {
if self.window().playlist_pos() + 1 < self.window().playlist_count() {
self.window().playlist_next();
} else {
self.window().playlist_play_index(None);

View file

@ -38,13 +38,13 @@ mod imp {
#[property(get)]
playlist_model: gio::ListStore,
#[property(type = u32, get = Self::volume, set = Self::set_volume)]
#[property(type = i64, get = Self::volume, set = Self::set_volume, minimum = 0, maximum = 100)]
_volume: (),
#[property(type = bool, get = Self::mute, set = Self::set_mute)]
_mute: (),
#[property(type = bool, get = Self::pause, set = Self::set_pause)]
_pause: (),
#[property(type = i32, get = Self::playlist_pos)]
#[property(type = i64, get = Self::playlist_pos)]
_playlist_pos: (),
#[property(type = f64, get = Self::time_pos)]
_time_pos: (),
@ -52,7 +52,7 @@ mod imp {
_duration: (), // as reported by mpv, compare with song.duration
#[property(type = bool, get = Self::idle_active)]
_idle_active: (),
#[property(type = u32, get = Self::playlist_count)]
#[property(type = i64, get = Self::playlist_count)]
_playlist_count: (),
pub(super) queued_seek: Cell<Option<f64>>,
@ -275,7 +275,7 @@ mod imp {
let api = self.api.borrow();
Rc::clone(api.as_ref().unwrap())
};
for song in api.get_random_songs(10).await.unwrap().into_iter() {
for song in api.random_songs(10).await.unwrap().into_iter() {
let song = Song::from_child(&api, &song, true);
self.mpv
.command(["loadfile", &song.stream_url(), "append-play"])
@ -290,7 +290,7 @@ mod imp {
self.setup.present(Some(self.obj().as_ref()));
}
fn volume(&self) -> u32 {
fn volume(&self) -> i64 {
self.mpv
.get_property::<i64>("volume")
.unwrap()
@ -298,7 +298,7 @@ mod imp {
.unwrap()
}
fn set_volume(&self, volume: u32) {
fn set_volume(&self, volume: i64) {
self.mpv.set_property("volume", volume as i64).unwrap();
}
@ -318,12 +318,8 @@ mod imp {
self.mpv.set_property("pause", pause).unwrap();
}
fn playlist_pos(&self) -> i32 {
self.mpv
.get_property::<i64>("playlist-pos")
.unwrap()
.try_into()
.unwrap()
fn playlist_pos(&self) -> i64 {
self.mpv.get_property("playlist-pos").unwrap()
}
fn time_pos(&self) -> f64 {
@ -368,7 +364,7 @@ mod imp {
self.mpv.get_property("idle-active").unwrap()
}
fn playlist_count(&self) -> u32 {
fn playlist_count(&self) -> i64 {
self.mpv
.get_property::<i64>("playlist-count")
.unwrap()
@ -377,16 +373,16 @@ mod imp {
}
fn song(&self) -> Option<Song> {
match self.obj().playlist_pos() {
playlist_pos if playlist_pos < 0 => None,
playlist_pos => Some(
match self.obj().playlist_pos().try_into() {
Ok(playlist_pos) => Some(
self.obj()
.playlist_model()
.item(playlist_pos as u32)
.item(playlist_pos)
.unwrap()
.dynamic_cast()
.unwrap(),
),
Err(_) => None,
}
}
@ -482,7 +478,7 @@ mod imp {
.replace(Some(glib::spawn_future_local(async move {
let api = window.imp().api.borrow().as_ref().unwrap().clone();
let bytes = api
.cover_art(&song_id, 0) // 0: full size
.cover_art(&song_id, None) // full size
.await
.expect("could not load cover art for song {song_id}");
@ -522,29 +518,22 @@ mod imp {
fn on_log_message(&self, event: crate::mpv::event::LogMessageEvent) {
let span = span!(Level::DEBUG, "mpv_log", prefix = event.prefix);
let _guard = span.enter();
let event_text = event.text.trim_end_matches("\n"); // trim training newline
let event_text = match self.api.borrow().as_ref() {
None => event_text.to_string(),
Some(api) => api.strip_token(event_text), // hide auth token if printing url
};
match event.log_level {
// level has to be 'static so this sux
l if l <= 20 => {
event!(target: "mpv_event", Level::ERROR, "{}", event_text)
event!(target: "mpv_event", Level::ERROR, "{}", event.text.trim())
}
l if l <= 30 => {
event!(target: "mpv_event", Level::WARN, "{}", event_text)
event!(target: "mpv_event", Level::WARN, "{}", event.text.trim())
}
l if l <= 40 => {
event!(target: "mpv_event", Level::INFO, "{}", event_text)
event!(target: "mpv_event", Level::INFO, "{}", event.text.trim())
}
l if l <= 60 => {
event!(target: "mpv_event", Level::DEBUG, "{}", event_text)
event!(target: "mpv_event", Level::DEBUG, "{}", event.text.trim())
}
l if l <= 70 => {
event!(target: "mpv_event", Level::TRACE, "{}", event_text)
event!(target: "mpv_event", Level::TRACE, "{}", event.text.trim())
}
// should be unused
_ => event!(
@ -552,7 +541,7 @@ mod imp {
Level::DEBUG,
log_level = event.log_level,
"{}",
event_text,
event.text.trim(),
),
};
}
@ -667,6 +656,19 @@ impl Window {
pub fn setup_connected(&self, api: crate::subsonic::Client) {
self.imp().api.replace(Some(Rc::new(api)));
self.set_can_click_shuffle_all(true);
let api = Rc::clone(self.imp().api.borrow().as_ref().unwrap());
glib::spawn_future_local(async move {
use futures::TryStreamExt;
let mut count = 0;
let mut albums =
std::pin::pin!(api.album_list_full(crate::subsonic::AlbumListType::Newest));
while let Some(_) = albums.try_next().await.unwrap() {
count += 1;
}
println!("gathered {count} albums");
});
}
pub fn playlist_next(&self) {