Skip to content

Commit

Permalink
fix: clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
kinkard committed Jun 3, 2024
1 parent 356305f commit aba494b
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 27 deletions.
13 changes: 7 additions & 6 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::Write;

use poise::CreateReply;
use serenity::builder::{CreateEmbed, CreateMessage};
use smallvec::{smallvec, SmallVec};
Expand Down Expand Up @@ -101,7 +103,6 @@ pub(crate) async fn play(ctx: Context<'_>, query: String) -> Result<(), anyhow::
};

let mut vc = vc.lock().await;

for (metadata, input) in resolved_items {
let track_handle = vc.enqueue(input.into()).await;

Expand All @@ -115,8 +116,9 @@ pub(crate) async fn play(ctx: Context<'_>, query: String) -> Result<(), anyhow::
ctx.author().name.clone(),
));
}

let queue_info = form_currently_played(&vc.queue().current_queue()).await;
drop(vc);

if let Err(err) = ctx
.send(CreateReply::default().embed(queue_info.clone()))
.await
Expand Down Expand Up @@ -154,10 +156,10 @@ pub(crate) async fn skip(ctx: Context<'_>) -> Result<(), anyhow::Error> {
// and form the embed with tracks after the current one via `get(1..)`
let queue_info =
form_currently_played(vc.queue().current_queue().get(1..).unwrap_or_default()).await;
ctx.send(CreateReply::default().embed(queue_info)).await?;

let _ = vc.queue().skip();
drop(vc);

ctx.send(CreateReply::default().embed(queue_info)).await?;
Ok(())
}

Expand All @@ -179,7 +181,7 @@ pub(crate) async fn stop(ctx: Context<'_>) -> Result<(), anyhow::Error> {
}

async fn form_currently_played(tracks: &[songbird::tracks::TrackHandle]) -> CreateEmbed {
let mut tracks = tracks.into_iter();
let mut tracks = tracks.iter();

// Use the first track in the queue to form the embed
let embed = if let Some(track) = tracks.next() {
Expand All @@ -200,7 +202,6 @@ async fn form_currently_played(tracks: &[songbird::tracks::TrackHandle]) -> Crea
let description = typemap.get::<track_info::TrackInfoKey>().unwrap();

let size = next_str.len();
use std::fmt::Write;
let _ = writeln!(next_str, "- {description}");

// Discord supports up to 1024 characters in embed body
Expand Down
3 changes: 1 addition & 2 deletions src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,7 @@ async fn user_left_vc(ctx: &Context, _data: &Data, guild_id: GuildId) {
voice_state
.member
.as_ref()
.map(|member| !member.user.bot)
.unwrap_or(false)
.is_some_and(|member| !member.user.bot)
})
.count()
== 0
Expand Down
24 changes: 13 additions & 11 deletions src/spotify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub(crate) struct Player {
}

impl Player {
pub(crate) async fn new(username: String, password: String) -> Result<Player, anyhow::Error> {
pub(crate) async fn new(username: String, password: String) -> Result<Self, anyhow::Error> {
let credentials = Credentials::with_password(username, password);
let session = Session::new(SessionConfig::default(), None);
session
Expand All @@ -60,7 +60,7 @@ impl Player {
move || Box::new(MediaSink::new(track_channels_rx)),
);

Ok(Player {
Ok(Self {
session,
player,
track_channels: track_channels_tx,
Expand All @@ -84,11 +84,11 @@ impl Player {
SpotifyItemType::Track => smallvec![id],
SpotifyItemType::Album => {
let album = metadata::Album::get(&self.session, &id).await.unwrap();
album.tracks().cloned().collect()
album.tracks().copied().collect()
}
SpotifyItemType::Playlist => {
let playlist = metadata::Playlist::get(&self.session, &id).await.unwrap();
playlist.tracks().cloned().collect()
playlist.tracks().copied().collect()
}
_ => Default::default(),
};
Expand Down Expand Up @@ -124,7 +124,7 @@ impl Drop for Player {
}

/// Byte stream input that receives audio packets from Spotify player.
/// To avoid a mess with multiple tracks, each track uses its own channel, initiated by [MediaStream::new()]
/// To avoid a mess with multiple tracks, each track uses its own channel, initiated by [`MediaStream::new()`]
struct MediaSink {
/// A channel to receive track channels
track_channels: flume::Receiver<ByteSink>,
Expand Down Expand Up @@ -184,7 +184,7 @@ impl audio_backend::Sink for MediaSink {
}
}

/// Byte stream output that sends audio packets to songbird. Works in pair with [MediaSink] with
/// Byte stream output that sends audio packets to songbird. Works in pair with [`MediaSink`] with
/// which it shares commnuication channel.
#[derive(Clone)]
struct MediaStream {
Expand All @@ -197,7 +197,7 @@ struct MediaStream {
}

impl MediaStream {
/// Establishes a new connection to the MediaSink and creates a new MediaStream if possible
/// Establishes a new connection to the [`MediaSink`] and creates a new `MediaStream` if possible
fn new(track_channels: &flume::Sender<ByteSink>) -> Option<Self> {
// Each track has its own channel to avoid messing up with packets from different tracks
let (byte_sink, byte_stream) = flume::bounded(16);
Expand All @@ -206,8 +206,10 @@ impl MediaStream {
// Send magic header with LE u32 sample reate and channels count to pass these values to symphonia
let mut header = Vec::with_capacity(16);
header.extend(b"SbirdRaw");
#[allow(clippy::unnecessary_cast)] // for better readability
header.extend((librespot::playback::SAMPLE_RATE as u32).to_le_bytes());
header.extend((librespot::playback::NUM_CHANNELS as u32).to_le_bytes());
assert_eq!(header.len(), 16);

Some(Self {
receiver: Some(byte_stream),
Expand Down Expand Up @@ -295,7 +297,7 @@ pub(crate) struct Track {

impl Track {
/// Provides track metadata
pub(crate) fn metadata(&self) -> &track_info::Metadata {
pub(crate) const fn metadata(&self) -> &track_info::Metadata {
&self.metadata
}
}
Expand Down Expand Up @@ -335,13 +337,13 @@ impl Compose for Track {
}
}

/// Parses Spotify URI or URL and returns SpotifyId if possible
/// Parses Spotify URI or URL and returns [`SpotifyId`] if possible
fn parse_spotify_id(src: &str) -> Option<SpotifyId> {
if let Some(remaining) = src.strip_prefix("https://open.spotify.com/") {
remaining.split_once('/').and_then(|(item_type, id)| {
// Remove query parameters if any
let id = id.split_once('?').map_or(id, |(id, _)| id);
let uri = format!("spotify:{}:{}", item_type, id);
let uri = format!("spotify:{item_type}:{id}");
SpotifyId::from_uri(&uri).ok()
})
} else {
Expand All @@ -362,7 +364,7 @@ fn extract_metadata(track: &metadata::Track) -> track_info::Metadata {
.covers
.iter()
.find(|image| image.size == ImageSize::DEFAULT)
.or(track.album.covers.first())
.or_else(|| track.album.covers.first())
.map(|image| format!("https://i.scdn.co/image/{}", image.id));

let artist = track
Expand Down
12 changes: 4 additions & 8 deletions src/yt_dlp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl YtDlp {
} else if let Some(url) = yt_dlp_output.webpage_url {
url
} else {
format!("https://www.youtube.com/results?search_query={}", query)
format!("https://www.youtube.com/results?search_query={query}")
}
.into_boxed_str();

Expand Down Expand Up @@ -107,7 +107,7 @@ impl YtDlp {
.await
.map_err(|e| {
AudioStreamError::Fail(if e.kind() == ErrorKind::NotFound {
format!("could not find executable '{}' on path", YOUTUBE_DL_COMMAND).into()
format!("could not find executable '{YOUTUBE_DL_COMMAND}' on path").into()
} else {
Box::new(e)
})
Expand All @@ -118,11 +118,9 @@ impl YtDlp {

Ok(yt_dlp_output)
}
}

impl YtDlp {
/// Provides track metadata
pub(crate) fn metadata(&self) -> &track_info::Metadata {
pub(crate) const fn metadata(&self) -> &track_info::Metadata {
&self.metadata
}
}
Expand Down Expand Up @@ -242,9 +240,7 @@ impl Resolver {
match cached_yt_dlp {
Some(yt_dlp) => Some(yt_dlp),
None => {
let Some(yt_dlp) = Self::fetch(self.http_client.clone(), query).await else {
return None;
};
let yt_dlp = Self::fetch(self.http_client.clone(), query).await?;

self.cache
.write()
Expand Down

0 comments on commit aba494b

Please sign in to comment.