Lint code

This commit is contained in:
oSumAtrIX 2021-10-18 04:29:23 +02:00
parent e81e0da7e6
commit 7a86351998
No known key found for this signature in database
GPG key ID: A9B3094ACDB604B4
5 changed files with 900 additions and 909 deletions

View file

@ -7,7 +7,7 @@ use crate::error::SpotifyError::{LameConverterError, InvalidFormat};
/// Converts audio to MP3 /// Converts audio to MP3
pub enum AudioConverter { pub enum AudioConverter {
OGG { Ogg {
decoder: OggStreamReader<ReadWrap>, decoder: OggStreamReader<ReadWrap>,
lame: lame::Lame, lame: lame::Lame,
lame_end: bool, lame_end: bool,
@ -48,10 +48,10 @@ impl AudioConverter {
}; };
match format { match format {
AudioFormat::AAC => todo!(), AudioFormat::Aac => todo!(),
AudioFormat::MP4 => todo!(), AudioFormat::Mp4 => todo!(),
// Lewton decoder // Lewton decoder
AudioFormat::OGG => { AudioFormat::Ogg => {
let decoder = OggStreamReader::new(ReadWrap::new(Box::new(read)))?; let decoder = OggStreamReader::new(ReadWrap::new(Box::new(read)))?;
let sample_rate = decoder.ident_hdr.audio_sample_rate; let sample_rate = decoder.ident_hdr.audio_sample_rate;
// Init lame // Init lame
@ -64,13 +64,13 @@ impl AudioConverter {
Err(_) => return Err(LameConverterError("Init".to_string())) Err(_) => return Err(LameConverterError("Init".to_string()))
}; };
Ok(AudioConverter::OGG { Ok(AudioConverter::Ogg {
lame, lame,
decoder, decoder,
lame_end: false, lame_end: false,
}) })
} }
AudioFormat::MP3 => panic!("No reencoding allowd!"), AudioFormat::Mp3 => panic!("No reencoding allowd!"),
_ => Err(InvalidFormat), _ => Err(InvalidFormat),
} }
} }
@ -79,7 +79,7 @@ impl AudioConverter {
impl Read for AudioConverter { impl Read for AudioConverter {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self { match self {
AudioConverter::OGG { AudioConverter::Ogg {
decoder, decoder,
lame, lame,
lame_end, lame_end,

View file

@ -413,7 +413,7 @@ impl DownloaderInternal {
let mime = res let mime = res
.headers() .headers()
.get("content-type") .get("content-type")
.ok_or(SpotifyError::Error("Missing cover mime!".into()))? .ok_or_else(|| SpotifyError::Error("Missing cover mime!".into()))?
.to_str() .to_str()
.unwrap() .unwrap()
.to_string(); .to_string();
@ -432,9 +432,8 @@ impl DownloaderInternal {
) -> Result<(), SpotifyError> { ) -> Result<(), SpotifyError> {
let mut tag_wrap = TagWrap::new(path, format)?; let mut tag_wrap = TagWrap::new(path, format)?;
// Format specific // Format specific
match &mut tag_wrap { if let TagWrap::Id3(id3) = &mut tag_wrap {
TagWrap::ID3(id3) => id3.use_id3_v24(config.id3v24), id3.use_id3_v24(config.id3v24)
_ => {}
} }
let tag = tag_wrap.get_tag(); let tag = tag_wrap.get_tag();
@ -521,7 +520,7 @@ impl DownloaderInternal {
quality, quality,
) )
.boxed(); .boxed();
audio_format = AudioFormat::MP3; audio_format = AudioFormat::Mp3;
s s
} }
false => DownloaderInternal::download_track_stream(path_clone, encrypted, key).boxed(), false => DownloaderInternal::download_track_stream(path_clone, encrypted, key).boxed(),
@ -570,7 +569,7 @@ impl DownloaderInternal {
// Custom reader loop for decrypting // Custom reader loop for decrypting
loop { loop {
// Blocking reader // Blocking reader
let (d, read, mut buf) = tokio::task::spawn_blocking(move || { let (d, read, buf) = tokio::task::spawn_blocking(move || {
let mut buf = vec![0; 1024 * 64]; let mut buf = vec![0; 1024 * 64];
match decrypted.read(&mut buf) { match decrypted.read(&mut buf) {
Ok(r) => Ok((decrypted, r, buf)), Ok(r) => Ok((decrypted, r, buf)),
@ -581,7 +580,7 @@ impl DownloaderInternal {
if read == 0 { if read == 0 {
break; break;
} }
file.write_all(&mut buf[0..read]).await?; file.write_all(&buf[0..read]).await?;
yield read; yield read;
} }
} }
@ -614,7 +613,7 @@ impl DownloaderInternal {
// Custom reader loop for decrypting // Custom reader loop for decrypting
loop { loop {
// Blocking reader // Blocking reader
let (d, read, mut buf) = tokio::task::spawn_blocking(move || { let (d, read, buf) = tokio::task::spawn_blocking(move || {
let mut buf = vec![0; 1024 * 64]; let mut buf = vec![0; 1024 * 64];
match decrypted.read(&mut buf) { match decrypted.read(&mut buf) {
Ok(r) => Ok((decrypted, r, buf)), Ok(r) => Ok((decrypted, r, buf)),
@ -625,7 +624,7 @@ impl DownloaderInternal {
if read == 0 { if read == 0 {
break; break;
} }
file.write_all(&mut buf[0..read]).await?; file.write_all(& buf[0..read]).await?;
yield read; yield read;
} }
} }
@ -634,10 +633,10 @@ impl DownloaderInternal {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum AudioFormat { pub enum AudioFormat {
OGG, Ogg,
AAC, Aac,
MP3, Mp3,
MP4, Mp4,
Unknown, Unknown,
} }
@ -645,10 +644,10 @@ impl AudioFormat {
/// Get extension /// Get extension
pub fn extension(&self) -> String { pub fn extension(&self) -> String {
match self { match self {
AudioFormat::OGG => "ogg", AudioFormat::Ogg => "ogg",
AudioFormat::AAC => "m4a", AudioFormat::Aac => "m4a",
AudioFormat::MP3 => "mp3", AudioFormat::Mp3 => "mp3",
AudioFormat::MP4 => "mp4", AudioFormat::Mp4 => "mp4",
AudioFormat::Unknown => "", AudioFormat::Unknown => "",
} }
.to_string() .to_string()
@ -658,19 +657,19 @@ impl AudioFormat {
impl From<FileFormat> for AudioFormat { impl From<FileFormat> for AudioFormat {
fn from(f: FileFormat) -> Self { fn from(f: FileFormat) -> Self {
match f { match f {
FileFormat::OGG_VORBIS_96 => Self::OGG, FileFormat::OGG_VORBIS_96 => Self::Ogg,
FileFormat::OGG_VORBIS_160 => Self::OGG, FileFormat::OGG_VORBIS_160 => Self::Ogg,
FileFormat::OGG_VORBIS_320 => Self::OGG, FileFormat::OGG_VORBIS_320 => Self::Ogg,
FileFormat::MP3_256 => Self::MP3, FileFormat::MP3_256 => Self::Mp3,
FileFormat::MP3_320 => Self::MP3, FileFormat::MP3_320 => Self::Mp3,
FileFormat::MP3_160 => Self::MP3, FileFormat::MP3_160 => Self::Mp3,
FileFormat::MP3_96 => Self::MP3, FileFormat::MP3_96 => Self::Mp3,
FileFormat::MP3_160_ENC => Self::MP3, FileFormat::MP3_160_ENC => Self::Mp3,
FileFormat::MP4_128_DUAL => Self::MP4, FileFormat::MP4_128_DUAL => Self::Mp4,
FileFormat::OTHER3 => Self::Unknown, FileFormat::OTHER3 => Self::Unknown,
FileFormat::AAC_160 => Self::AAC, FileFormat::AAC_160 => Self::Aac,
FileFormat::AAC_320 => Self::AAC, FileFormat::AAC_320 => Self::Aac,
FileFormat::MP4_128 => Self::MP4, FileFormat::MP4_128 => Self::Mp4,
FileFormat::OTHER5 => Self::Unknown, FileFormat::OTHER5 => Self::Unknown,
} }
} }
@ -737,13 +736,13 @@ pub struct Download {
pub state: DownloadState, pub state: DownloadState,
} }
impl Into<Download> for aspotify::Track { impl From<aspotify::Track> for Download {
fn into(self) -> Download { fn from(val: aspotify::Track) -> Self {
Download { Download {
id: 0, id: 0,
track_id: self.id.unwrap(), track_id: val.id.unwrap(),
title: self.name, title: val.name,
subtitle: self subtitle: val
.artists .artists
.first() .first()
.map(|a| a.name.to_owned()) .map(|a| a.name.to_owned())
@ -753,13 +752,13 @@ impl Into<Download> for aspotify::Track {
} }
} }
impl Into<Download> for aspotify::TrackSimplified { impl From<aspotify::TrackSimplified> for Download {
fn into(self) -> Download { fn from(val: aspotify::TrackSimplified) -> Self {
Download { Download {
id: 0, id: 0,
track_id: self.id.unwrap(), track_id: val.id.unwrap(),
title: self.name, title: val.name,
subtitle: self subtitle: val
.artists .artists
.first() .first()
.map(|a| a.name.to_owned()) .map(|a| a.name.to_owned())
@ -769,11 +768,11 @@ impl Into<Download> for aspotify::TrackSimplified {
} }
} }
impl Into<DownloadJob> for Download { impl From<Download> for DownloadJob {
fn into(self) -> DownloadJob { fn from(val: Download) -> Self {
DownloadJob { DownloadJob {
id: self.id, id: val.id,
track_id: self.track_id, track_id: val.track_id,
} }
} }
} }

View file

@ -1,5 +1,5 @@
use aspotify::{ use aspotify::{
Album, Client, ClientCredentials, Playlist, PlaylistItemType, Track, TrackSimplified, Artist Album, Artist, Client, ClientCredentials, Playlist, PlaylistItemType, Track, TrackSimplified,
}; };
use librespot::core::authentication::Credentials; use librespot::core::authentication::Credentials;
use librespot::core::config::SessionConfig; use librespot::core::config::SessionConfig;
@ -16,7 +16,6 @@ pub struct Spotify {
} }
impl Spotify { impl Spotify {
/// Create new instance /// Create new instance
pub async fn new( pub async fn new(
username: &str, username: &str,
@ -41,7 +40,7 @@ impl Spotify {
pub fn parse_uri(uri: &str) -> Result<String, SpotifyError> { pub fn parse_uri(uri: &str) -> Result<String, SpotifyError> {
// Already URI // Already URI
if uri.starts_with("spotify:") { if uri.starts_with("spotify:") {
if uri.split(':').collect::<Vec<&str>>().len() < 3 { if uri.split(':').count() < 3 {
return Err(SpotifyError::InvalidUri); return Err(SpotifyError::InvalidUri);
} }
return Ok(uri.to_string()); return Ok(uri.to_string());
@ -53,7 +52,7 @@ impl Spotify {
if url.host_str() == Some("open.spotify.com") { if url.host_str() == Some("open.spotify.com") {
let path = url let path = url
.path_segments() .path_segments()
.ok_or(SpotifyError::Error("Missing URL path".into()))? .ok_or_else(|| SpotifyError::Error("Missing URL path".into()))?
.collect::<Vec<&str>>(); .collect::<Vec<&str>>();
if path.len() < 2 { if path.len() < 2 {
return Err(SpotifyError::InvalidUri); return Err(SpotifyError::InvalidUri);
@ -104,16 +103,12 @@ impl Spotify {
.data .data
.items .items
.iter() .iter()
.filter_map(|i| { .filter_map(|i| -> Option<Track> {
if let Some(item) = &i.item { if let Some(PlaylistItemType::Track(t)) = &i.item {
if let PlaylistItemType::Track(t) = item {
Some(t.to_owned()) Some(t.to_owned())
} else { } else {
None None
} }
} else {
None
}
}) })
.collect(), .collect(),
); );
@ -157,10 +152,7 @@ impl Spotify {
.get_artist_albums(id, None, 50, offset, None) .get_artist_albums(id, None, 50, offset, None)
.await?; .await?;
for album in &mut page for album in &mut page.data.items.iter() {
.data
.items
.iter() {
items.append(&mut self.full_album(&album.id).await?) items.append(&mut self.full_album(&album.id).await?)
} }

View file

@ -5,22 +5,22 @@ use crate::downloader::AudioFormat;
use crate::error::SpotifyError; use crate::error::SpotifyError;
use self::id3::ID3Tag; use self::id3::ID3Tag;
use ogg::OGGTag; use ogg::OggTag;
mod id3; mod id3;
mod ogg; mod ogg;
pub enum TagWrap { pub enum TagWrap {
OGG(OGGTag), Ogg(OggTag),
ID3(ID3Tag), Id3(ID3Tag),
} }
impl TagWrap { impl TagWrap {
/// Load from file /// Load from file
pub fn new(path: impl AsRef<Path>, format: AudioFormat) -> Result<TagWrap, SpotifyError> { pub fn new(path: impl AsRef<Path>, format: AudioFormat) -> Result<TagWrap, SpotifyError> {
match format { match format {
AudioFormat::OGG => Ok(TagWrap::OGG(OGGTag::open(path)?)), AudioFormat::Ogg => Ok(TagWrap::Ogg(OggTag::open(path)?)),
AudioFormat::MP3 => Ok(TagWrap::ID3(ID3Tag::open(path)?)), AudioFormat::Mp3 => Ok(TagWrap::Id3(ID3Tag::open(path)?)),
_ => Err(SpotifyError::Error("Invalid format!".into())), _ => Err(SpotifyError::Error("Invalid format!".into())),
} }
} }
@ -28,8 +28,8 @@ impl TagWrap {
/// Get Tag trait /// Get Tag trait
pub fn get_tag(&mut self) -> Box<&mut dyn Tag> { pub fn get_tag(&mut self) -> Box<&mut dyn Tag> {
match self { match self {
TagWrap::OGG(tag) => Box::new(tag), TagWrap::Ogg(tag) => Box::new(tag),
TagWrap::ID3(tag) => Box::new(tag), TagWrap::Id3(tag) => Box::new(tag),
} }
} }
} }

View file

@ -6,24 +6,24 @@ use std::path::{Path, PathBuf};
use super::Field; use super::Field;
use crate::error::SpotifyError; use crate::error::SpotifyError;
pub struct OGGTag { pub struct OggTag {
path: PathBuf, path: PathBuf,
tag: CommentHeader, tag: CommentHeader,
} }
impl OGGTag { impl OggTag {
/// Load tag from file /// Load tag from file
pub fn open(path: impl AsRef<Path>) -> Result<OGGTag, SpotifyError> { pub fn open(path: impl AsRef<Path>) -> Result<OggTag, SpotifyError> {
let mut file = File::open(&path)?; let mut file = File::open(&path)?;
let tag = read_comment_header(&mut file); let tag = read_comment_header(&mut file);
Ok(OGGTag { Ok(OggTag {
path: path.as_ref().to_owned(), path: path.as_ref().to_owned(),
tag, tag,
}) })
} }
} }
impl super::Tag for OGGTag { impl super::Tag for OggTag {
fn set_separator(&mut self, _separator: &str) {} fn set_separator(&mut self, _separator: &str) {}
fn set_field(&mut self, field: Field, value: Vec<String>) { fn set_field(&mut self, field: Field, value: Vec<String>) {