chore: bump dependencies, switch to rspotify #6

Merged
polpetta merged 1 commits from issue/#5 into 0.3.x 2022-03-18 11:02:12 +01:00
4 changed files with 136 additions and 53 deletions

View File

@ -1,13 +1,13 @@
[package] [package]
name = "songlify" name = "songlify"
version = "0.2.2" version = "0.2.3"
edition = "2018" edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
teloxide = { version = "0.5", features = ["auto-send", "macros"] } teloxide = { version = "0.7.1", features = ["auto-send", "macros"] }
log = "0.4" log = "0.4.14"
pretty_env_logger = "0.4.0" pretty_env_logger = "0.4.0"
tokio = { version = "1.8", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.17.0", features = ["rt-multi-thread", "macros"] }
aspotify = "0.7.0" rspotify = { version = "0.11.4", features = ["default"]}

View File

@ -1,4 +1,4 @@
FROM rust:1.56.1-slim-bullseye as builder FROM rust:1.59.0-slim-bullseye as builder
WORKDIR /build WORKDIR /build

View File

@ -1,9 +1,9 @@
use teloxide::prelude::*; use teloxide::prelude::*;
use crate::spotify::TrackInfo; use crate::spotify::{PlayableKind, TrackInfo};
use spotify::SpotifyKind::Track; use spotify::SpotifyKind::Track;
use crate::spotify::SpotifyKind::{Album, Playlist}; use crate::spotify::SpotifyKind::{Album, Episode, Playlist, Podcast};
use crate::utils::{human_readable_duration, truncate_with_dots}; use crate::utils::{human_readable_duration, truncate_with_dots};
mod spotify; mod spotify;
@ -21,7 +21,7 @@ async fn main() {
let text = message.update.text().and_then(spotify::get_entry_kind); let text = message.update.text().and_then(spotify::get_entry_kind);
match text { match text {
Some(spotify) => { Some(spotify) => {
let spotify_client = spotify::get_client(); let spotify_client = spotify::get_client().await;
match spotify { match spotify {
Track(id) => { Track(id) => {
log::debug!("Parsing spotify song: {}", id); log::debug!("Parsing spotify song: {}", id);
@ -85,12 +85,20 @@ async fn main() {
); );
Some( Some(
message message
.reply_to(add_track_section(info.tracks, reply)) .reply_to(add_track_section_for_playlist(info.tracks, reply))
.await?, .await?,
) )
} }
None => None, None => None,
} }
},
Episode(id) => {
log::warn!("Support for episodes ({}) has not be implemented yet!", id);
None
}
Podcast(id) => {
log::warn!("Support for podcasts ({}) has not be implemented yet!", id);
None
} }
} }
} }
@ -103,6 +111,22 @@ async fn main() {
log::info!("Exiting..."); log::info!("Exiting...");
} }
fn add_track_section_for_playlist(tracks: Vec<PlayableKind>, reply: String) -> String {
if !tracks.is_empty() {
let songs = tracks
.iter()
.map(|x| match x {
PlayableKind::Track(t) => t.name.clone(),
PlayableKind::Podcast(e) => e.name.clone()
} + "\n")
.collect::<String>();
reply
.clone()
.push_str(format!("\n🎶 {} Track(s): {}", tracks.len(), songs).as_str())
}
reply
}
fn add_track_section(tracks: Vec<TrackInfo>, reply: String) -> String { fn add_track_section(tracks: Vec<TrackInfo>, reply: String) -> String {
if !tracks.is_empty() { if !tracks.is_empty() {
let songs = tracks let songs = tracks

View File

@ -1,12 +1,20 @@
use std::time::Duration; use std::time::Duration;
use rspotify::{ClientCredsSpotify, Credentials};
use aspotify::PlaylistItemType::{Episode, Track}; use rspotify::model::{AlbumId, FullTrack, PlaylistId, TrackId};
use aspotify::{Client, ClientCredentials, TrackSimplified}; use rspotify::model::PlayableItem::{Episode, Track};
use rspotify::prelude::*;
pub enum SpotifyKind { pub enum SpotifyKind {
Track(String), Track(String),
Album(String), Album(String),
Playlist(String), Playlist(String),
Podcast(String),
Episode(String)
}
pub enum PlayableKind {
Track(TrackInfo),
Podcast(EpisodeInfo)
} }
pub struct TrackInfo { pub struct TrackInfo {
@ -15,6 +23,15 @@ pub struct TrackInfo {
pub(crate) duration: Duration, pub(crate) duration: Duration,
} }
pub struct EpisodeInfo {
pub(crate) name: String,
pub(crate) show: String,
pub(crate) duration: Duration,
pub(crate) description: String,
pub(crate) languages: Vec<String>,
pub(crate) release_date: String
}
pub struct AlbumInfo { pub struct AlbumInfo {
pub(crate) name: String, pub(crate) name: String,
pub(crate) artists: Vec<String>, pub(crate) artists: Vec<String>,
@ -25,7 +42,7 @@ pub struct AlbumInfo {
pub struct PlaylistInfo { pub struct PlaylistInfo {
pub(crate) name: String, pub(crate) name: String,
pub(crate) artists: Vec<String>, pub(crate) artists: Vec<String>,
pub(crate) tracks: Vec<TrackInfo>, pub(crate) tracks: Vec<PlayableKind>,
} }
fn get_id_in_url(url: &str) -> Option<&str> { fn get_id_in_url(url: &str) -> Option<&str> {
@ -35,7 +52,7 @@ fn get_id_in_url(url: &str) -> Option<&str> {
.and_then(|x| x.split('?').next()) .and_then(|x| x.split('?').next())
} }
fn extract_artists_from_tracks(tracks: Vec<TrackSimplified>) -> Vec<String> { fn extract_artists_from_tracks(tracks: Vec<FullTrack>) -> Vec<String> {
tracks tracks
.iter() .iter()
.flat_map(|t| t.artists.iter().map(|a| a.name.clone())) .flat_map(|t| t.artists.iter().map(|a| a.name.clone()))
@ -64,35 +81,58 @@ pub fn get_entry_kind(url: &str) -> Option<SpotifyKind> {
None => None, None => None,
}; };
} }
if url.contains("https://open.spotify.com/show/") {
let playlist_id = get_id_in_url(url);
return match playlist_id {
Some(id) => Some(SpotifyKind::Podcast(id.to_string())),
None => None,
};
}
if url.contains("https://open.spotify.com/episode/") {
let playlist_id = get_id_in_url(url);
return match playlist_id {
Some(id) => Some(SpotifyKind::Episode(id.to_string())),
None => None,
};
}
return None; return None;
} }
pub fn get_client() -> Box<Client> { pub async fn get_client() -> Box<ClientCredsSpotify> {
let spotify_creds = let spotify_creds = Credentials::from_env().expect("RSPOTIFY_CLIENT_ID and RSPOTIFY_CLIENT_SECRET not found.");
ClientCredentials::from_env().expect("CLIENT_ID and CLIENT_SECRET not found."); let mut spotify = ClientCredsSpotify::new(spotify_creds);
let spotify_client = Box::new(Client::new(spotify_creds)); spotify.request_token().await.unwrap();
spotify_client Box::new(spotify)
} }
pub async fn get_track(spotify: Box<Client>, id: &String) -> Option<TrackInfo> { pub async fn get_track(spotify: Box<ClientCredsSpotify>, id: &String) -> Option<TrackInfo> {
match spotify.tracks().get_track(id.as_str(), None).await { let track_id = match TrackId::from_id(id.as_str()) {
Ok(track) => Some(TrackInfo { Ok(track) => track,
name: track.data.name, Err(_e) => return None
artists: track.data.artists.iter().map(|x| x.name.clone()).collect(), };
duration: track.data.duration,
match spotify.track(&track_id).await {
Ok(track) => Some(TrackInfo{
name: track.name,
artists: track.artists.iter().map(|x| x.name.clone()).collect(),
duration: track.duration,
}), }),
Err(_e) => None, Err(_e) => None
} }
} }
pub async fn get_album(spotify: Box<Client>, id: &String) -> Option<AlbumInfo> { pub async fn get_album(spotify: Box<ClientCredsSpotify>, id: &String) -> Option<AlbumInfo> {
match spotify.albums().get_album(id.as_str(), None).await { let album_id = match AlbumId::from_id(id.as_str()) {
Ok(album) => album,
Err(_e) => return None
};
match spotify.album(&album_id).await {
Ok(album) => Some(AlbumInfo { Ok(album) => Some(AlbumInfo {
name: album.data.name, name: album.name,
artists: album.data.artists.iter().map(|x| x.name.clone()).collect(), artists: album.artists.iter().map(|x| x.name.clone()).collect(),
genres: album.data.genres, genres: album.genres,
tracks: album tracks: album
.data
.tracks .tracks
.items .items
.iter() .iter()
@ -107,37 +147,56 @@ pub async fn get_album(spotify: Box<Client>, id: &String) -> Option<AlbumInfo> {
} }
} }
pub async fn get_playlist(spotify: Box<Client>, id: &String) -> Option<PlaylistInfo> { pub async fn get_playlist(spotify: Box<ClientCredsSpotify>, id: &String) -> Option<PlaylistInfo> {
match spotify.playlists().get_playlist(id.as_str(), None).await { let playlist_id = match PlaylistId::from_id(id.as_str()) {
Ok(playlist) => playlist,
Err(_e) => return None
};
match spotify.playlist(&playlist_id, None, None).await {
Ok(playlist) => Some(PlaylistInfo { Ok(playlist) => Some(PlaylistInfo {
name: playlist.data.name, name: playlist.name,
artists: playlist artists: playlist
.data
.tracks .tracks
.items .items
.iter() .iter()
.flat_map(|p| { .flat_map(|p| {
p.item.as_ref().map_or(Vec::new(), |x| match x { match &p.track {
Track(t) => extract_artists_from_tracks(vec![t.clone().simplify()]), Some(t) => match t {
Episode(_e) => Vec::new(), Track(t) => t.artists.iter().map(|a| {
}) a.name.clone()
}) }).collect(),
.collect(), Episode(e) => vec![e.show.publisher.clone()]
}
None => Vec::new(),
}.into_iter()
}).collect(),
tracks: playlist tracks: playlist
.data
.tracks .tracks
.items .items
.iter() .iter()
.flat_map(|p| { .map(|p| {
p.item.as_ref().map_or(None, |x| match x { match &p.track {
Track(t) => Some(TrackInfo { Some(t) => match t {
name: t.name.clone(), Track(t) => Some(PlayableKind::Track(TrackInfo{
artists: extract_artists_from_tracks(vec![t.clone().simplify()]), name: t.name.clone(),
duration: t.duration, artists: t.artists.iter().map(|a| a.name.clone()).collect(),
}), duration: t.duration
Episode(_e) => None, })),
}) Episode(e) => Some(PlayableKind::Podcast(EpisodeInfo{
name: e.name.clone(),
show: e.show.name.clone(),
duration: e.duration,
description: e.description.clone(),
languages: e.languages.clone(),
release_date: e.release_date.clone()
}))
},
None => None
}
}) })
.filter(|i| i.is_some())
.map(|i| i.unwrap())
.collect(), .collect(),
}), }),
Err(_e) => None, Err(_e) => None,