Parse image from API, trigger event

This commit is contained in:
Muaz Ahmad 2024-11-28 17:02:28 +05:00
parent c995653c62
commit ee4e024d31
2 changed files with 16 additions and 3 deletions

View file

@ -6,6 +6,7 @@ use std::{
thread, thread,
}; };
use image::DynamicImage;
use ratatui::DefaultTerminal; use ratatui::DefaultTerminal;
use crate::{ use crate::{
@ -17,6 +18,7 @@ use crate::{
pub enum PlayerEvent { pub enum PlayerEvent {
AddSongList(Vec<Song>), AddSongList(Vec<Song>),
UpdateCover(DynamicImage),
UserQuit, UserQuit,
PlayNext, PlayNext,
} }

View file

@ -1,3 +1,5 @@
use std::io::{BufReader, Read};
use reqwest::{ use reqwest::{
blocking::Response, blocking::Response,
header::{ACCEPT, CONTENT_TYPE}, header::{ACCEPT, CONTENT_TYPE},
@ -29,7 +31,7 @@ impl APIClient {
} }
fn get_cover_art(&mut self, cover_id: String) -> Result<PlayerEvent, Error> { fn get_cover_art(&mut self, cover_id: String) -> Result<PlayerEvent, Error> {
let response = self.request("/getCoverArt", Some(&[("id", cover_id)]))?; let mut response = self.request("/getCoverArt", Some(&[("id", cover_id)]))?;
if !response.status().is_success() { if !response.status().is_success() {
return Err(Box::new(APIError::StatusError( return Err(Box::new(APIError::StatusError(
response.status(), response.status(),
@ -37,8 +39,17 @@ impl APIClient {
))); )));
}; };
if response.headers()[CONTENT_TYPE].to_str()? == "application/json" { if response.headers()[CONTENT_TYPE].to_str()? == "application/json" {
self.validate(response, "/getCoverArt")?; // will never error self.validate(response, "/getCoverArt")?; // will never error if not image
}; } else {
let mut image = Vec::new();
response.read_to_end(&mut image)?;
let cover = image::load_from_memory_with_format(
&mut image,
image::ImageFormat::from_mime_type(response.headers()[CONTENT_TYPE].to_str()?)
.unwrap(),
)?;
return Ok(PlayerEvent::UpdateCover(cover));
}
unimplemented!() unimplemented!()
} }