chore: Update dependencies and fix auth (#27)

This commit is contained in:
Guillem Castro 2025-06-22 01:55:06 +02:00 committed by GitHub
parent afafa36263
commit dcedaa0d7e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 1998 additions and 746 deletions

2396
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[package] [package]
name = "spotify-dl" name = "spotify-dl"
version = "0.5.4" version = "0.6.0"
authors = ["Guillem Castro <guillemcastro4@gmail.com>"] authors = ["Guillem Castro <guillemcastro4@gmail.com>"]
edition = "2021" edition = "2021"
readme = "README.md" readme = "README.md"
@ -11,23 +11,25 @@ description = "A command-line utility to download songs and playlists from Spoti
[dependencies] [dependencies]
structopt = { version = "0.3", default-features = false } structopt = { version = "0.3", default-features = false }
rpassword = "7.0" indicatif = "0.17.11"
indicatif = "0.17" librespot = { version = "0.6.0", default-features = false }
librespot = { version = "0.4.2", default-features = false } librespot-oauth = "0.6.0"
tokio = { version = "1", features = ["full", "tracing"] } tokio = { version = "1", features = ["full", "tracing"] }
flacenc = { version = "0.4" } flacenc = { version = "0.4" }
audiotags = "0.5" audiotags = "0.5"
regex = "1.7.1" regex = "1.11.1"
machine-uid = "0.5.1" machine-uid = "0.5.3"
anyhow = "1" anyhow = "1"
tracing = "0.1" tracing = "0.1.41"
tracing-subscriber = { version = "0.3", features = ["env-filter", "registry"] } tracing-subscriber = { version = "0.3.19", features = ["env-filter", "registry"] }
lazy_static = "1.4" lazy_static = "1.5"
async-trait = "0.1" async-trait = "0.1.88"
dirs = "5.0" dirs = "6.0"
mp3lame-encoder = { version = "0.1.5", optional = true } mp3lame-encoder = { version = "0.2.1", optional = true }
futures = "0.3" futures = "0.3.31"
rayon = "1.10" rayon = "1.10"
bytes = "1.10.1"
id3 = "1.16.3"
[features] [features]
default = ["mp3"] default = ["mp3"]

View file

@ -3,6 +3,10 @@ use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use anyhow::Result; use anyhow::Result;
use audiotags::Picture;
use audiotags::Tag;
use audiotags::TagType;
use bytes::Bytes;
use futures::StreamExt; use futures::StreamExt;
use futures::TryStreamExt; use futures::TryStreamExt;
use indicatif::MultiProgress; use indicatif::MultiProgress;
@ -16,9 +20,9 @@ use librespot::playback::mixer::VolumeGetter;
use librespot::playback::player::Player; use librespot::playback::player::Player;
use crate::channel_sink::ChannelSink; use crate::channel_sink::ChannelSink;
use crate::channel_sink::SinkEvent;
use crate::encoder::Format; use crate::encoder::Format;
use crate::encoder::Samples; use crate::encoder::Samples;
use crate::channel_sink::SinkEvent;
use crate::track::Track; use crate::track::Track;
use crate::track::TrackMetadata; use crate::track::TrackMetadata;
@ -37,14 +41,19 @@ pub struct DownloadOptions {
} }
impl DownloadOptions { impl DownloadOptions {
pub fn new(destination: Option<String>, compression: Option<u32>, parallel: usize, format: Format) -> Self { pub fn new(
destination: Option<String>,
compression: Option<u32>,
parallel: usize,
format: Format,
) -> Self {
let destination = let destination =
destination.map_or_else(|| std::env::current_dir().unwrap(), PathBuf::from); destination.map_or_else(|| std::env::current_dir().unwrap(), PathBuf::from);
DownloadOptions { DownloadOptions {
destination, destination,
compression, compression,
parallel, parallel,
format format,
} }
} }
} }
@ -64,9 +73,7 @@ impl Downloader {
options: &DownloadOptions, options: &DownloadOptions,
) -> Result<()> { ) -> Result<()> {
futures::stream::iter(tracks) futures::stream::iter(tracks)
.map(|track| { .map(|track| self.download_track(track, options))
self.download_track(track, options)
})
.buffer_unordered(options.parallel) .buffer_unordered(options.parallel)
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
.await?; .await?;
@ -77,7 +84,7 @@ impl Downloader {
#[tracing::instrument(name = "download_track", skip(self))] #[tracing::instrument(name = "download_track", skip(self))]
async fn download_track(&self, track: Track, options: &DownloadOptions) -> Result<()> { async fn download_track(&self, track: Track, options: &DownloadOptions) -> Result<()> {
let metadata = track.metadata(&self.session).await?; let metadata = track.metadata(&self.session).await?;
tracing::info!("Downloading track: {:?}", metadata); tracing::info!("Downloading track: {:?}", metadata.track_name);
let file_name = self.get_file_name(&metadata); let file_name = self.get_file_name(&metadata);
let path = options let path = options
@ -88,11 +95,11 @@ impl Downloader {
.ok_or(anyhow::anyhow!("Could not set the output path"))? .ok_or(anyhow::anyhow!("Could not set the output path"))?
.to_string(); .to_string();
let (sink, mut sink_channel) = ChannelSink::new(metadata); let (sink, mut sink_channel) = ChannelSink::new(metadata.clone());
let file_size = sink.get_approximate_size(); let file_size = sink.get_approximate_size();
let (mut player, _) = Player::new( let player = Player::new(
self.player_config.clone(), self.player_config.clone(),
self.session.clone(), self.session.clone(),
self.volume_getter(), self.volume_getter(),
@ -117,7 +124,11 @@ impl Downloader {
while let Some(event) = sink_channel.recv().await { while let Some(event) = sink_channel.recv().await {
match event { match event {
SinkEvent::Write { bytes, total, mut content } => { SinkEvent::Write {
bytes,
total,
mut content,
} => {
tracing::trace!("Written {} bytes out of {}", bytes, total); tracing::trace!("Written {} bytes out of {}", bytes, total);
pb.set_position(bytes as u64); pb.set_position(bytes as u64);
samples.append(&mut content); samples.append(&mut content);
@ -139,6 +150,8 @@ impl Downloader {
tracing::info!("Writing track: {:?} to file: {}", file_name, &path); tracing::info!("Writing track: {:?} to file: {}", file_name, &path);
stream.write_to_file(&path).await?; stream.write_to_file(&path).await?;
self.store_tags(path, &metadata, options).await?;
pb.finish_with_message(format!("Downloaded {}", &file_name)); pb.finish_with_message(format!("Downloaded {}", &file_name));
Ok(()) Ok(())
} }
@ -186,4 +199,49 @@ impl Downloader {
} }
clean clean
} }
async fn store_tags(
&self,
path: String,
metadata: &TrackMetadata,
options: &DownloadOptions,
) -> Result<()> {
let tag_type = match options.format {
Format::Mp3 => TagType::Id3v2,
Format::Flac => TagType::Flac,
};
if options.format == Format::Mp3 {
let tag = id3::Tag::new();
tag.write_to_path(&path, id3::Version::Id3v24)?;
}
let mut tag = Tag::new().with_tag_type(tag_type).read_from_path(&path)?;
tag.set_title(&metadata.track_name);
let artists: String = metadata.artists.first()
.map(|artist| artist.name.clone())
.unwrap_or_default();
tag.set_artist(&artists);
tag.set_album_title(&metadata.album.name);
tag.set_album_cover(Picture::new(
self.get_cover_image(&metadata).await?.as_ref(),
audiotags::MimeType::Jpeg,
));
tag.write_to_path(&path)?;
Ok(())
}
async fn get_cover_image(&self, metadata: &TrackMetadata) -> Result<Bytes> {
match metadata.album.cover {
Some(ref cover) => self
.session
.spclient()
.get_image(&cover.id)
.await
.map_err(|e| anyhow::anyhow!("{:?}", e)),
None => Err(anyhow::anyhow!("No cover art!")),
}
}
} }

View file

@ -26,7 +26,7 @@ impl Mp3Encoder {
anyhow::anyhow!("Failed to set number of channels for mp3 encoder: {}", e) anyhow::anyhow!("Failed to set number of channels for mp3 encoder: {}", e)
})?; })?;
builder builder
.set_brate(mp3lame_encoder::Birtate::Kbps160) .set_brate(mp3lame_encoder::Birtate::Kbps320)
.map_err(|e| anyhow::anyhow!("Failed to set bitrate for mp3 encoder: {}", e))?; .map_err(|e| anyhow::anyhow!("Failed to set bitrate for mp3 encoder: {}", e))?;
builder builder

View file

@ -1,146 +0,0 @@
use std::path::Path;
use audiotags::Tag;
use audiotags::TagType;
use flacenc::component::BitRepr;
use flacenc::error::Verify;
use librespot::playback::audio_backend::Sink;
use librespot::playback::audio_backend::SinkError;
use librespot::playback::convert::Converter;
use librespot::playback::decoder::AudioPacket;
use crate::encoder::get_encoder;
use crate::encoder::Samples;
use crate::track::TrackMetadata;
pub enum SinkEvent {
Written { bytes: usize, total: usize },
Finished,
}
pub type SinkEventChannel = tokio::sync::mpsc::UnboundedReceiver<SinkEvent>;
pub struct FileSink {
sink: String,
content: Vec<i32>,
metadata: TrackMetadata,
compression: u32,
event_sender: tokio::sync::mpsc::UnboundedSender<SinkEvent>,
}
impl FileSink {
pub fn set_compression(&mut self, compression: u32) {
self.compression = compression;
}
pub fn new(path: String, track: TrackMetadata) -> (Self, SinkEventChannel) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
(
FileSink {
sink: path,
content: Vec::new(),
metadata: track,
compression: 4,
event_sender: tx,
},
rx,
)
}
pub fn get_approximate_size(&self) -> usize {
self.convert_track_duration_to_size()
}
fn convert_track_duration_to_size(&self) -> usize {
let duration = self.metadata.duration / 1000;
let sample_rate = 44100;
let channels = 2;
let bits_per_sample = 16;
let bytes_per_sample = bits_per_sample / 8;
(duration as usize) * sample_rate * channels * bytes_per_sample * 2
}
}
impl Sink for FileSink {
fn start(&mut self) -> Result<(), SinkError> {
Ok(())
}
fn stop(&mut self) -> Result<(), SinkError> {
tracing::info!("Writing to file: {:?}", &self.sink);
// let config = flacenc::config::Encoder::default()
// .into_verified()
// .map_err(|_| SinkError::OnWrite("Failed to create flac encoder".to_string()))?;
// let source = flacenc::source::MemSource::from_samples(&self.content, 2, 16, 44100);
// let flac_stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
// .map_err(|_| SinkError::OnWrite("Failed to encode flac".to_string()))?;
// let mut sink = flacenc::bitsink::ByteSink::new();
// flac_stream
// .write(&mut sink)
// .map_err(|_| SinkError::OnWrite("Failed to write flac to sink".to_string()))?;
// std::fs::write(&self.sink, sink.as_slice())
// .map_err(|_| SinkError::OnWrite("Failed to write flac to file".to_string()))?;
let flac_enc = get_encoder(crate::encoder::Format::Flac)
.map_err(|_| SinkError::OnWrite("Failed to get flac encoder".to_string()))?;
let mp3_enc = get_encoder(crate::encoder::Format::Mp3)
.map_err(|_| SinkError::OnWrite("Failed to get mp3 encoder".to_string()))?;
let flac_stream = flac_enc.encode(Samples::new(
self.content.clone(),
44100,
2,
16,
))
.map_err(|_| SinkError::OnWrite("Failed to encode flac".to_string()))?;
let mp3_stream = mp3_enc.encode(Samples::new(
self.content.clone(),
44100,
2,
16,
))
.map_err(|_| SinkError::OnWrite("Failed to encode mp3".to_string()))?;
flac_stream.write_to_file(&self.sink)
.map_err(|_| SinkError::OnWrite("Failed to write flac to file".to_string()))?;
mp3_stream.write_to_file(&self.sink)
.map_err(|_| SinkError::OnWrite("Failed to write mp3 to file".to_string()))?;
let mut tag = Tag::new()
.with_tag_type(TagType::Flac)
.read_from_path(Path::new(&self.sink))
.map_err(|_| SinkError::OnWrite("Failed to read metadata".to_string()))?;
tag.set_album_title(&self.metadata.album.name);
for artist in &self.metadata.artists {
tag.add_artist(&artist.name);
}
tag.set_title(&self.metadata.track_name);
tag.write_to_path(&self.sink)
.map_err(|_| SinkError::OnWrite("Failed to write metadata".to_string()))?;
self.event_sender
.send(SinkEvent::Finished)
.map_err(|_| SinkError::OnWrite("Failed to send finished event".to_string()))?;
Ok(())
}
fn write(&mut self, packet: AudioPacket, converter: &mut Converter) -> Result<(), SinkError> {
let data = converter.f64_to_s16(
packet
.samples()
.map_err(|_| SinkError::OnWrite("Failed to get samples".to_string()))?,
);
let mut data32: Vec<i32> = data.iter().map(|el| i32::from(*el)).collect();
self.content.append(&mut data32);
self.event_sender
.send(SinkEvent::Written {
bytes: self.content.len() * std::mem::size_of::<i32>(),
total: self.convert_track_duration_to_size(),
})
.map_err(|_| SinkError::OnWrite("Failed to send event".to_string()))?;
Ok(())
}
}

View file

@ -18,10 +18,6 @@ struct Opt {
required = true required = true
)] )]
tracks: Vec<String>, tracks: Vec<String>,
#[structopt(short = "u", long = "username", help = "Your Spotify username")]
username: String,
#[structopt(short = "p", long = "password", help = "Your Spotify password")]
password: Option<String>,
#[structopt( #[structopt(
short = "d", short = "d",
long = "destination", long = "destination",
@ -84,7 +80,7 @@ async fn main() -> anyhow::Result<()> {
eprintln!("Compression level is not supported yet. It will be ignored."); eprintln!("Compression level is not supported yet. It will be ignored.");
} }
let session = create_session(opt.username, opt.password).await?; let session = create_session().await?;
let track = get_tracks(opt.tracks, &session).await?; let track = get_tracks(opt.tracks, &session).await?;

View file

@ -3,34 +3,36 @@ use librespot::core::cache::Cache;
use librespot::core::config::SessionConfig; use librespot::core::config::SessionConfig;
use librespot::core::session::Session; use librespot::core::session::Session;
use librespot::discovery::Credentials; use librespot::discovery::Credentials;
use librespot_oauth::get_access_token;
pub async fn create_session(username: String, password: Option<String>) -> Result<Session> { const SPOTIFY_CLIENT_ID: &str = "65b708073fc0480ea92a077233ca87bd";
const SPOTIFY_REDIRECT_URI: &str = "http://127.0.0.1:8898/login";
pub async fn create_session() -> Result<Session> {
let credentials_store = dirs::home_dir().map(|p| p.join(".spotify-dl")); let credentials_store = dirs::home_dir().map(|p| p.join(".spotify-dl"));
let cache = Cache::new(credentials_store, None, None, None)?; let cache = Cache::new(credentials_store, None, None, None)?;
let session_config = SessionConfig::default(); let session_config = SessionConfig::default();
let credentials = get_credentials(username, password, &cache);
let credentials = match cache.credentials() {
Some(creds) => creds,
None => match load_credentials() {
Ok(creds) => creds,
Err(e) => return Err(e.into()),
},
};
cache.save_credentials(&credentials); cache.save_credentials(&credentials);
let (session, _) = Session::connect(session_config, credentials, Some(cache), false).await?; let session = Session::new(session_config, Some(cache));
session.connect(credentials, true).await?;
Ok(session) Ok(session)
} }
fn prompt_password() -> Result<String> { pub fn load_credentials() -> Result<Credentials> {
tracing::info!("Spotify password was not provided. Please enter your Spotify password below"); let token = match get_access_token(SPOTIFY_CLIENT_ID, SPOTIFY_REDIRECT_URI, vec!["streaming"]) {
rpassword::prompt_password("Password: ").map_err(|e| e.into()) Ok(token) => token,
} Err(e) => return Err(e.into()),
};
fn get_credentials(username: String, password: Option<String>, cache: &Cache) -> Credentials { Ok(Credentials::with_access_token(token.access_token))
match password { }
Some(password) => Credentials::with_password(username, password),
None => cache.credentials().unwrap_or_else(|| {
tracing::warn!("No credentials found in cache");
Credentials::with_password(
username,
prompt_password().unwrap_or_else(|_| panic!("Failed to get password")),
)
}),
}
}

View file

@ -2,6 +2,7 @@ use anyhow::Result;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use librespot::core::session::Session; use librespot::core::session::Session;
use librespot::core::spotify_id::SpotifyId; use librespot::core::spotify_id::SpotifyId;
use librespot::metadata::image::Image;
use librespot::metadata::Metadata; use librespot::metadata::Metadata;
use regex::Regex; use regex::Regex;
@ -16,17 +17,14 @@ pub async fn get_tracks(spotify_ids: Vec<String>, session: &Session) -> Result<V
for id in spotify_ids { for id in spotify_ids {
tracing::debug!("Getting tracks for: {}", id); tracing::debug!("Getting tracks for: {}", id);
let id = parse_uri_or_url(&id).ok_or(anyhow::anyhow!("Invalid track"))?; let id = parse_uri_or_url(&id).ok_or(anyhow::anyhow!("Invalid track"))?;
let new_tracks = match id.audio_type { let new_tracks = match id.item_type {
librespot::core::spotify_id::SpotifyAudioType::Track => vec![Track::from_id(id)], librespot::core::spotify_id::SpotifyItemType::Track => vec![Track::from_id(id)],
librespot::core::spotify_id::SpotifyAudioType::Podcast => vec![Track::from_id(id)], librespot::core::spotify_id::SpotifyItemType::Episode => vec![Track::from_id(id)],
librespot::core::spotify_id::SpotifyAudioType::NonPlayable => { librespot::core::spotify_id::SpotifyItemType::Album => Album::from_id(id).get_tracks(session).await,
if Album::is_album(id, session).await { librespot::core::spotify_id::SpotifyItemType::Playlist => Playlist::from_id(id).get_tracks(session).await,
Album::from_id(id).get_tracks(session).await _ => {
} else if Playlist::is_playlist(id, session).await { tracing::warn!("Unsupported item type: {:?}", id.item_type);
Playlist::from_id(id).get_tracks(session).await vec![]
} else {
vec![]
}
} }
}; };
tracks.extend(new_tracks); tracks.extend(new_tracks);
@ -62,7 +60,7 @@ pub struct Track {
lazy_static! { lazy_static! {
static ref SPOTIFY_URL_REGEX: Regex = static ref SPOTIFY_URL_REGEX: Regex =
Regex::new(r"https://open.spotify.com/(\w+)/(.*)\?").unwrap(); Regex::new(r"https://open\.spotify\.com(?:/intl-[a-z]{2})?/(\w+)/([a-zA-Z0-9]+)").unwrap();
} }
impl Track { impl Track {
@ -76,20 +74,20 @@ impl Track {
} }
pub async fn metadata(&self, session: &Session) -> Result<TrackMetadata> { pub async fn metadata(&self, session: &Session) -> Result<TrackMetadata> {
let metadata = librespot::metadata::Track::get(session, self.id) let metadata = librespot::metadata::Track::get(session, &self.id)
.await .await
.map_err(|_| anyhow::anyhow!("Failed to get metadata"))?; .map_err(|_| anyhow::anyhow!("Failed to get metadata"))?;
let mut artists = Vec::new(); let mut artists = Vec::new();
for artist in &metadata.artists { for artist in metadata.artists.iter() {
artists.push( artists.push(
librespot::metadata::Artist::get(session, *artist) librespot::metadata::Artist::get(session, &artist.id)
.await .await
.map_err(|_| anyhow::anyhow!("Failed to get artist"))?, .map_err(|_| anyhow::anyhow!("Failed to get artist"))?,
); );
} }
let album = librespot::metadata::Album::get(session, metadata.album) let album = librespot::metadata::Album::get(session, &metadata.album.id)
.await .await
.map_err(|_| anyhow::anyhow!("Failed to get album"))?; .map_err(|_| anyhow::anyhow!("Failed to get album"))?;
@ -119,19 +117,18 @@ impl Album {
} }
pub async fn is_album(id: SpotifyId, session: &Session) -> bool { pub async fn is_album(id: SpotifyId, session: &Session) -> bool {
librespot::metadata::Album::get(session, id).await.is_ok() librespot::metadata::Album::get(session, &id).await.is_ok()
} }
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl TrackCollection for Album { impl TrackCollection for Album {
async fn get_tracks(&self, session: &Session) -> Vec<Track> { async fn get_tracks(&self, session: &Session) -> Vec<Track> {
let album = librespot::metadata::Album::get(session, self.id) let album = librespot::metadata::Album::get(session, &self.id)
.await .await
.expect("Failed to get album"); .expect("Failed to get album");
album album
.tracks .tracks()
.iter()
.map(|track| Track::from_id(*track)) .map(|track| Track::from_id(*track))
.collect() .collect()
} }
@ -152,7 +149,7 @@ impl Playlist {
} }
pub async fn is_playlist(id: SpotifyId, session: &Session) -> bool { pub async fn is_playlist(id: SpotifyId, session: &Session) -> bool {
librespot::metadata::Playlist::get(session, id) librespot::metadata::Playlist::get(session, &id)
.await .await
.is_ok() .is_ok()
} }
@ -161,12 +158,11 @@ impl Playlist {
#[async_trait::async_trait] #[async_trait::async_trait]
impl TrackCollection for Playlist { impl TrackCollection for Playlist {
async fn get_tracks(&self, session: &Session) -> Vec<Track> { async fn get_tracks(&self, session: &Session) -> Vec<Track> {
let playlist = librespot::metadata::Playlist::get(session, self.id) let playlist = librespot::metadata::Playlist::get(session, &self.id)
.await .await
.expect("Failed to get playlist"); .expect("Failed to get playlist");
playlist playlist
.tracks .tracks()
.iter()
.map(|track| Track::from_id(*track)) .map(|track| Track::from_id(*track))
.collect() .collect()
} }
@ -217,12 +213,14 @@ impl From<librespot::metadata::Artist> for ArtistMetadata {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct AlbumMetadata { pub struct AlbumMetadata {
pub name: String, pub name: String,
pub cover: Option<Image>,
} }
impl From<librespot::metadata::Album> for AlbumMetadata { impl From<librespot::metadata::Album> for AlbumMetadata {
fn from(album: librespot::metadata::Album) -> Self { fn from(album: librespot::metadata::Album) -> Self {
AlbumMetadata { AlbumMetadata {
name: album.name.clone(), name: album.name.clone(),
cover: album.covers.first().cloned()
} }
} }
} }