mirror of
https://gitverse.ru/ot/DownOnSpot
synced 2025-12-19 09:54:19 +00:00
Lint code
This commit is contained in:
parent
e81e0da7e6
commit
7a86351998
5 changed files with 900 additions and 909 deletions
|
|
@ -7,7 +7,7 @@ use crate::error::SpotifyError::{LameConverterError, InvalidFormat};
|
|||
|
||||
/// Converts audio to MP3
|
||||
pub enum AudioConverter {
|
||||
OGG {
|
||||
Ogg {
|
||||
decoder: OggStreamReader<ReadWrap>,
|
||||
lame: lame::Lame,
|
||||
lame_end: bool,
|
||||
|
|
@ -48,10 +48,10 @@ impl AudioConverter {
|
|||
};
|
||||
|
||||
match format {
|
||||
AudioFormat::AAC => todo!(),
|
||||
AudioFormat::MP4 => todo!(),
|
||||
AudioFormat::Aac => todo!(),
|
||||
AudioFormat::Mp4 => todo!(),
|
||||
// Lewton decoder
|
||||
AudioFormat::OGG => {
|
||||
AudioFormat::Ogg => {
|
||||
let decoder = OggStreamReader::new(ReadWrap::new(Box::new(read)))?;
|
||||
let sample_rate = decoder.ident_hdr.audio_sample_rate;
|
||||
// Init lame
|
||||
|
|
@ -64,13 +64,13 @@ impl AudioConverter {
|
|||
Err(_) => return Err(LameConverterError("Init".to_string()))
|
||||
};
|
||||
|
||||
Ok(AudioConverter::OGG {
|
||||
Ok(AudioConverter::Ogg {
|
||||
lame,
|
||||
decoder,
|
||||
lame_end: false,
|
||||
})
|
||||
}
|
||||
AudioFormat::MP3 => panic!("No reencoding allowd!"),
|
||||
AudioFormat::Mp3 => panic!("No reencoding allowd!"),
|
||||
_ => Err(InvalidFormat),
|
||||
}
|
||||
}
|
||||
|
|
@ -79,7 +79,7 @@ impl AudioConverter {
|
|||
impl Read for AudioConverter {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
match self {
|
||||
AudioConverter::OGG {
|
||||
AudioConverter::Ogg {
|
||||
decoder,
|
||||
lame,
|
||||
lame_end,
|
||||
|
|
|
|||
1397
src/downloader.rs
1397
src/downloader.rs
File diff suppressed because it is too large
Load diff
322
src/spotify.rs
322
src/spotify.rs
|
|
@ -1,5 +1,5 @@
|
|||
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::config::SessionConfig;
|
||||
|
|
@ -10,191 +10,183 @@ use url::Url;
|
|||
use crate::error::SpotifyError;
|
||||
|
||||
pub struct Spotify {
|
||||
// librespotify sessopm
|
||||
pub session: Session,
|
||||
pub spotify: Client,
|
||||
// librespotify sessopm
|
||||
pub session: Session,
|
||||
pub spotify: Client,
|
||||
}
|
||||
|
||||
impl Spotify {
|
||||
/// Create new instance
|
||||
pub async fn new(
|
||||
username: &str,
|
||||
password: &str,
|
||||
client_id: &str,
|
||||
client_secret: &str,
|
||||
) -> Result<Spotify, SpotifyError> {
|
||||
// librespot
|
||||
let credentials = Credentials::with_password(username, password);
|
||||
let session = Session::connect(SessionConfig::default(), credentials, None).await?;
|
||||
//aspotify
|
||||
let credentials = ClientCredentials {
|
||||
id: client_id.to_string(),
|
||||
secret: client_secret.to_string(),
|
||||
};
|
||||
let spotify = Client::new(credentials);
|
||||
|
||||
/// Create new instance
|
||||
pub async fn new(
|
||||
username: &str,
|
||||
password: &str,
|
||||
client_id: &str,
|
||||
client_secret: &str,
|
||||
) -> Result<Spotify, SpotifyError> {
|
||||
// librespot
|
||||
let credentials = Credentials::with_password(username, password);
|
||||
let session = Session::connect(SessionConfig::default(), credentials, None).await?;
|
||||
//aspotify
|
||||
let credentials = ClientCredentials {
|
||||
id: client_id.to_string(),
|
||||
secret: client_secret.to_string(),
|
||||
};
|
||||
let spotify = Client::new(credentials);
|
||||
Ok(Spotify { session, spotify })
|
||||
}
|
||||
|
||||
Ok(Spotify { session, spotify })
|
||||
}
|
||||
/// Parse URI or URL into URI
|
||||
pub fn parse_uri(uri: &str) -> Result<String, SpotifyError> {
|
||||
// Already URI
|
||||
if uri.starts_with("spotify:") {
|
||||
if uri.split(':').count() < 3 {
|
||||
return Err(SpotifyError::InvalidUri);
|
||||
}
|
||||
return Ok(uri.to_string());
|
||||
}
|
||||
|
||||
/// Parse URI or URL into URI
|
||||
pub fn parse_uri(uri: &str) -> Result<String, SpotifyError> {
|
||||
// Already URI
|
||||
if uri.starts_with("spotify:") {
|
||||
if uri.split(':').collect::<Vec<&str>>().len() < 3 {
|
||||
return Err(SpotifyError::InvalidUri);
|
||||
}
|
||||
return Ok(uri.to_string());
|
||||
}
|
||||
// Parse URL
|
||||
let url = Url::parse(uri)?;
|
||||
// Spotify Web Player URL
|
||||
if url.host_str() == Some("open.spotify.com") {
|
||||
let path = url
|
||||
.path_segments()
|
||||
.ok_or_else(|| SpotifyError::Error("Missing URL path".into()))?
|
||||
.collect::<Vec<&str>>();
|
||||
if path.len() < 2 {
|
||||
return Err(SpotifyError::InvalidUri);
|
||||
}
|
||||
return Ok(format!("spotify:{}:{}", path[0], path[1]));
|
||||
}
|
||||
Err(SpotifyError::InvalidUri)
|
||||
}
|
||||
|
||||
// Parse URL
|
||||
let url = Url::parse(uri)?;
|
||||
// Spotify Web Player URL
|
||||
if url.host_str() == Some("open.spotify.com") {
|
||||
let path = url
|
||||
.path_segments()
|
||||
.ok_or(SpotifyError::Error("Missing URL path".into()))?
|
||||
.collect::<Vec<&str>>();
|
||||
if path.len() < 2 {
|
||||
return Err(SpotifyError::InvalidUri);
|
||||
}
|
||||
return Ok(format!("spotify:{}:{}", path[0], path[1]));
|
||||
}
|
||||
Err(SpotifyError::InvalidUri)
|
||||
}
|
||||
/// Fetch data for URI
|
||||
pub async fn resolve_uri(&self, uri: &str) -> Result<SpotifyItem, SpotifyError> {
|
||||
let parts = uri.split(':').skip(1).collect::<Vec<&str>>();
|
||||
let id = parts[1];
|
||||
match parts[0] {
|
||||
"track" => {
|
||||
let track = self.spotify.tracks().get_track(id, None).await?;
|
||||
Ok(SpotifyItem::Track(track.data))
|
||||
}
|
||||
"playlist" => {
|
||||
let playlist = self.spotify.playlists().get_playlist(id, None).await?;
|
||||
Ok(SpotifyItem::Playlist(playlist.data))
|
||||
}
|
||||
"album" => {
|
||||
let album = self.spotify.albums().get_album(id, None).await?;
|
||||
Ok(SpotifyItem::Album(album.data))
|
||||
}
|
||||
"artist" => {
|
||||
let artist = self.spotify.artists().get_artist(id).await?;
|
||||
Ok(SpotifyItem::Artist(artist.data))
|
||||
}
|
||||
// Unsupported / Unimplemented
|
||||
_ => Ok(SpotifyItem::Other(uri.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch data for URI
|
||||
pub async fn resolve_uri(&self, uri: &str) -> Result<SpotifyItem, SpotifyError> {
|
||||
let parts = uri.split(':').skip(1).collect::<Vec<&str>>();
|
||||
let id = parts[1];
|
||||
match parts[0] {
|
||||
"track" => {
|
||||
let track = self.spotify.tracks().get_track(id, None).await?;
|
||||
Ok(SpotifyItem::Track(track.data))
|
||||
}
|
||||
"playlist" => {
|
||||
let playlist = self.spotify.playlists().get_playlist(id, None).await?;
|
||||
Ok(SpotifyItem::Playlist(playlist.data))
|
||||
}
|
||||
"album" => {
|
||||
let album = self.spotify.albums().get_album(id, None).await?;
|
||||
Ok(SpotifyItem::Album(album.data))
|
||||
}
|
||||
"artist" => {
|
||||
let artist = self.spotify.artists().get_artist(id).await?;
|
||||
Ok(SpotifyItem::Artist(artist.data))
|
||||
}
|
||||
// Unsupported / Unimplemented
|
||||
_ => Ok(SpotifyItem::Other(uri.to_string())),
|
||||
}
|
||||
}
|
||||
/// Get all tracks from playlist
|
||||
pub async fn full_playlist(&self, id: &str) -> Result<Vec<Track>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.playlists()
|
||||
.get_playlists_items(id, 100, offset, None)
|
||||
.await?;
|
||||
items.append(
|
||||
&mut page
|
||||
.data
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| -> Option<Track> {
|
||||
if let Some(PlaylistItemType::Track(t)) = &i.item {
|
||||
Some(t.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
|
||||
/// Get all tracks from playlist
|
||||
pub async fn full_playlist(&self, id: &str) -> Result<Vec<Track>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.playlists()
|
||||
.get_playlists_items(id, 100, offset, None)
|
||||
.await?;
|
||||
items.append(
|
||||
&mut page
|
||||
.data
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| {
|
||||
if let Some(item) = &i.item {
|
||||
if let PlaylistItemType::Track(t) = item {
|
||||
Some(t.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Get all tracks from album
|
||||
pub async fn full_album(&self, id: &str) -> Result<Vec<TrackSimplified>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.albums()
|
||||
.get_album_tracks(id, 50, offset, None)
|
||||
.await?;
|
||||
items.append(&mut page.data.items.to_vec());
|
||||
|
||||
/// Get all tracks from album
|
||||
pub async fn full_album(&self, id: &str) -> Result<Vec<TrackSimplified>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.albums()
|
||||
.get_album_tracks(id, 50, offset, None)
|
||||
.await?;
|
||||
items.append(&mut page.data.items.to_vec());
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get all tracks from artist
|
||||
pub async fn full_artist(&self, id: &str) -> Result<Vec<TrackSimplified>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.artists()
|
||||
.get_artist_albums(id, None, 50, offset, None)
|
||||
.await?;
|
||||
|
||||
for album in &mut page
|
||||
.data
|
||||
.items
|
||||
.iter() {
|
||||
items.append(&mut self.full_album(&album.id).await?)
|
||||
}
|
||||
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Get all tracks from artist
|
||||
pub async fn full_artist(&self, id: &str) -> Result<Vec<TrackSimplified>, SpotifyError> {
|
||||
let mut items = vec![];
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self
|
||||
.spotify
|
||||
.artists()
|
||||
.get_artist_albums(id, None, 50, offset, None)
|
||||
.await?;
|
||||
|
||||
for album in &mut page.data.items.iter() {
|
||||
items.append(&mut self.full_album(&album.id).await?)
|
||||
}
|
||||
|
||||
// End
|
||||
offset += page.data.items.len();
|
||||
if page.data.total == offset {
|
||||
return Ok(items);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Spotify {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
session: self.session.clone(),
|
||||
spotify: Client::new(self.spotify.credentials.clone()),
|
||||
}
|
||||
}
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
session: self.session.clone(),
|
||||
spotify: Client::new(self.spotify.credentials.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Basic debug implementation so can be used in other structs
|
||||
impl fmt::Debug for Spotify {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "<Spotify Instance>")
|
||||
}
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "<Spotify Instance>")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SpotifyItem {
|
||||
Track(Track),
|
||||
Album(Album),
|
||||
Playlist(Playlist),
|
||||
Artist(Artist),
|
||||
/// Unimplemented
|
||||
Other(String),
|
||||
Track(Track),
|
||||
Album(Album),
|
||||
Playlist(Playlist),
|
||||
Artist(Artist),
|
||||
/// Unimplemented
|
||||
Other(String),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,53 +5,53 @@ use crate::downloader::AudioFormat;
|
|||
use crate::error::SpotifyError;
|
||||
|
||||
use self::id3::ID3Tag;
|
||||
use ogg::OGGTag;
|
||||
use ogg::OggTag;
|
||||
|
||||
mod id3;
|
||||
mod ogg;
|
||||
|
||||
pub enum TagWrap {
|
||||
OGG(OGGTag),
|
||||
ID3(ID3Tag),
|
||||
Ogg(OggTag),
|
||||
Id3(ID3Tag),
|
||||
}
|
||||
|
||||
impl TagWrap {
|
||||
/// Load from file
|
||||
pub fn new(path: impl AsRef<Path>, format: AudioFormat) -> Result<TagWrap, SpotifyError> {
|
||||
match format {
|
||||
AudioFormat::OGG => Ok(TagWrap::OGG(OGGTag::open(path)?)),
|
||||
AudioFormat::MP3 => Ok(TagWrap::ID3(ID3Tag::open(path)?)),
|
||||
_ => Err(SpotifyError::Error("Invalid format!".into())),
|
||||
}
|
||||
}
|
||||
/// Load from file
|
||||
pub fn new(path: impl AsRef<Path>, format: AudioFormat) -> Result<TagWrap, SpotifyError> {
|
||||
match format {
|
||||
AudioFormat::Ogg => Ok(TagWrap::Ogg(OggTag::open(path)?)),
|
||||
AudioFormat::Mp3 => Ok(TagWrap::Id3(ID3Tag::open(path)?)),
|
||||
_ => Err(SpotifyError::Error("Invalid format!".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get Tag trait
|
||||
pub fn get_tag(&mut self) -> Box<&mut dyn Tag> {
|
||||
match self {
|
||||
TagWrap::OGG(tag) => Box::new(tag),
|
||||
TagWrap::ID3(tag) => Box::new(tag),
|
||||
}
|
||||
}
|
||||
/// Get Tag trait
|
||||
pub fn get_tag(&mut self) -> Box<&mut dyn Tag> {
|
||||
match self {
|
||||
TagWrap::Ogg(tag) => Box::new(tag),
|
||||
TagWrap::Id3(tag) => Box::new(tag),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Tag {
|
||||
// Set tag values separator
|
||||
fn set_separator(&mut self, separator: &str);
|
||||
fn set_raw(&mut self, tag: &str, value: Vec<String>);
|
||||
fn set_field(&mut self, field: Field, value: Vec<String>);
|
||||
fn set_release_date(&mut self, date: NaiveDate);
|
||||
fn add_cover(&mut self, mime: &str, data: Vec<u8>);
|
||||
fn save(&mut self) -> Result<(), SpotifyError>;
|
||||
// Set tag values separator
|
||||
fn set_separator(&mut self, separator: &str);
|
||||
fn set_raw(&mut self, tag: &str, value: Vec<String>);
|
||||
fn set_field(&mut self, field: Field, value: Vec<String>);
|
||||
fn set_release_date(&mut self, date: NaiveDate);
|
||||
fn add_cover(&mut self, mime: &str, data: Vec<u8>);
|
||||
fn save(&mut self) -> Result<(), SpotifyError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Field {
|
||||
Title,
|
||||
Artist,
|
||||
Album,
|
||||
TrackNumber,
|
||||
DiscNumber,
|
||||
AlbumArtist,
|
||||
Genre,
|
||||
Label,
|
||||
Title,
|
||||
Artist,
|
||||
Album,
|
||||
TrackNumber,
|
||||
DiscNumber,
|
||||
AlbumArtist,
|
||||
Genre,
|
||||
Label,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,24 +6,24 @@ use std::path::{Path, PathBuf};
|
|||
use super::Field;
|
||||
use crate::error::SpotifyError;
|
||||
|
||||
pub struct OGGTag {
|
||||
pub struct OggTag {
|
||||
path: PathBuf,
|
||||
tag: CommentHeader,
|
||||
}
|
||||
|
||||
impl OGGTag {
|
||||
impl OggTag {
|
||||
/// 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 tag = read_comment_header(&mut file);
|
||||
Ok(OGGTag {
|
||||
Ok(OggTag {
|
||||
path: path.as_ref().to_owned(),
|
||||
tag,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Tag for OGGTag {
|
||||
impl super::Tag for OggTag {
|
||||
fn set_separator(&mut self, _separator: &str) {}
|
||||
|
||||
fn set_field(&mut self, field: Field, value: Vec<String>) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue