Skip to content

Commit

Permalink
chore: format all code with rustfmt
Browse files Browse the repository at this point in the history
The new Rust edition comes with some new formatting defaults, which need
to be applied since the edition was increased.
  • Loading branch information
ThomasFrans committed Mar 6, 2025
1 parent 331cf51 commit 3dc5c72
Show file tree
Hide file tree
Showing 36 changed files with 190 additions and 161 deletions.
15 changes: 8 additions & 7 deletions src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,19 +159,20 @@ impl Application {
}

#[cfg(unix)]
let ipc = match utils::create_runtime_directory() { Ok(runtime_directory) => {
Some(
let ipc = match utils::create_runtime_directory() {
Ok(runtime_directory) => Some(
ipc::IpcSocket::new(
ASYNC_RUNTIME.get().unwrap().handle(),
runtime_directory.join("ncspot.sock"),
event_manager.clone(),
)
.map_err(|e| e.to_string())?,
)
} _ => {
error!("failed to create IPC socket: no suitable user runtime directory found");
None
}};
),
_ => {
error!("failed to create IPC socket: no suitable user runtime directory found");
None
}
};

let mut cmd_manager = CommandManager::new(
spotify.clone(),
Expand Down
2 changes: 1 addition & 1 deletion src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,7 @@ pub fn parse(input: &str) -> Result<Vec<Command>, CommandParseError> {
_ => {
return Err(E::NoSuchCommand {
cmd: command.into(),
})
});
}
};
commands.push(command);
Expand Down
68 changes: 38 additions & 30 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use std::time::Duration;

use crate::application::UserData;
use crate::command::{
parse, Command, GotoMode, JumpMode, MoveAmount, MoveMode, SeekDirection, ShiftMode, TargetMode,
Command, GotoMode, JumpMode, MoveAmount, MoveMode, SeekDirection, ShiftMode, TargetMode, parse,
};
use crate::config::{user_configuration_directory, Config};
use crate::config::{Config, user_configuration_directory};
use crate::events::EventManager;
use crate::ext_traits::CursiveExt;
use crate::library::Library;
Expand All @@ -20,10 +20,10 @@ use crate::ui::help::HelpView;
use crate::ui::layout::Layout;
use crate::ui::modal::Modal;
use crate::ui::search_results::SearchResultsView;
use cursive::Cursive;
use cursive::event::{Event, Key};
use cursive::traits::View;
use cursive::views::Dialog;
use cursive::Cursive;
use log::{debug, error, info};
use ncspot::CONFIGURATION_FILE_NAME;
use std::cell::RefCell;
Expand Down Expand Up @@ -332,33 +332,41 @@ impl CommandManager {
}

fn handle_callbacks(&self, s: &mut Cursive, cmd: &Command) -> Result<Option<String>, String> {
let local = match s.find_name::<ContextMenu>("contextmenu") { Some(mut contextmenu) => {
contextmenu.on_command(s, cmd)?
} _ => { match s.find_name::<AddToPlaylistMenu>("addtrackmenu") { Some(mut add_track_menu) => {
add_track_menu.on_command(s, cmd)?
} _ => { match s.find_name::<SelectArtistMenu>("selectartist") { Some(mut select_artist) => {
select_artist.on_command(s, cmd)?
} _ => { match s.find_name::<SelectArtistActionMenu>("selectartistaction")
{ Some(mut select_artist_action) => {
select_artist_action.on_command(s, cmd)?
} _ => {
s.on_layout(|siv, mut l| l.on_command(siv, cmd))?
}}}}}}}};

match local { CommandResult::Consumed(output) => {
Ok(output)
} _ => { match local { CommandResult::Modal(modal) => {
s.add_layer(modal);
Ok(None)
} _ => { match local { CommandResult::View(view) => {
s.call_on_name("main", move |v: &mut Layout| {
v.push_view(view);
});

Ok(None)
} _ => {
self.handle_default_commands(s, cmd)
}}}}}}
let local = match s.find_name::<ContextMenu>("contextmenu") {
Some(mut contextmenu) => contextmenu.on_command(s, cmd)?,
_ => match s.find_name::<AddToPlaylistMenu>("addtrackmenu") {
Some(mut add_track_menu) => add_track_menu.on_command(s, cmd)?,
_ => match s.find_name::<SelectArtistMenu>("selectartist") {
Some(mut select_artist) => select_artist.on_command(s, cmd)?,
_ => match s.find_name::<SelectArtistActionMenu>("selectartistaction") {
Some(mut select_artist_action) => {
select_artist_action.on_command(s, cmd)?
}
_ => s.on_layout(|siv, mut l| l.on_command(siv, cmd))?,
},
},
},
};

match local {
CommandResult::Consumed(output) => Ok(output),
_ => match local {
CommandResult::Modal(modal) => {
s.add_layer(modal);
Ok(None)
}
_ => match local {
CommandResult::View(view) => {
s.call_on_name("main", move |v: &mut Layout| {
v.push_view(view);
});

Ok(None)
}
_ => self.handle_default_commands(s, cmd),
},
},
}
}

pub fn handle(&self, s: &mut Cursive, cmd: Command) {
Expand Down
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use platform_dirs::AppDirs;
use crate::command::{SortDirection, SortKey};
use crate::model::playable::Playable;
use crate::queue;
use crate::serialization::{Serializer, CBOR, TOML};
use crate::serialization::{CBOR, Serializer, TOML};

pub const CACHE_VERSION: u16 = 1;
pub const DEFAULT_COMMAND_KEY: char = ':';
Expand Down
2 changes: 1 addition & 1 deletion src/events.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crossbeam_channel::{unbounded, Receiver, Sender, TryIter};
use crossbeam_channel::{Receiver, Sender, TryIter, unbounded};
use cursive::{CbSink, Cursive};

use crate::queue::QueueEvent;
Expand Down
2 changes: 1 addition & 1 deletion src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use log::{debug, error, info};
use tokio::net::{UnixListener, UnixStream};
use tokio::runtime::Handle;
use tokio::sync::watch::{Receiver, Sender};
use tokio_stream::wrappers::WatchStream;
use tokio_stream::StreamExt;
use tokio_stream::wrappers::WatchStream;
use tokio_util::codec::{FramedRead, FramedWrite, LinesCodec};

use crate::events::{Event, EventManager};
Expand Down
19 changes: 11 additions & 8 deletions src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use std::thread;

use log::{debug, error, info};
use rspotify::model::Id;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::config::Config;
use crate::config::{self, CACHE_VERSION};
Expand Down Expand Up @@ -779,13 +779,16 @@ impl Library {

{
let mut store = self.artists.write().unwrap();
match store.iter().position(|a| a.id == artist.id) { Some(i) => {
store[i].is_followed = true;
} _ => {
let mut artist = artist.clone();
artist.is_followed = true;
store.push(artist);
}}
match store.iter().position(|a| a.id == artist.id) {
Some(i) => {
store[i].is_followed = true;
}
_ => {
let mut artist = artist.clone();
artist.is_followed = true;
store.push(artist);
}
}
}

self.populate_artists();
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ extern crate serde;

use std::{path::PathBuf, process::exit};

use application::{setup_logging, Application};
use application::{Application, setup_logging};
use config::set_configuration_base_path;
use log::error;
use ncspot::program_arguments;
Expand Down
2 changes: 1 addition & 1 deletion src/model/artist.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::fmt;
use std::sync::{Arc, RwLock};

use rspotify::model::artist::{FullArtist, SimplifiedArtist};
use rspotify::model::Id;
use rspotify::model::artist::{FullArtist, SimplifiedArtist};

use crate::library::Library;
use crate::model::playable::Playable;
Expand Down
2 changes: 1 addition & 1 deletion src/model/episode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use crate::queue::Queue;
use crate::traits::{ListItem, ViewExt};
use crate::utils::ms_to_hms;
use chrono::{DateTime, Utc};
use rspotify::model::show::{FullEpisode, SimplifiedEpisode};
use rspotify::model::Id;
use rspotify::model::show::{FullEpisode, SimplifiedEpisode};
use std::fmt;
use std::sync::Arc;

Expand Down
2 changes: 1 addition & 1 deletion src/model/playlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::{cmp::Ordering, iter::Iterator};
use rand::{rng, seq::IteratorRandom};

use log::{debug, warn};
use rspotify::model::playlist::{FullPlaylist, SimplifiedPlaylist};
use rspotify::model::Id;
use rspotify::model::playlist::{FullPlaylist, SimplifiedPlaylist};

use crate::model::playable::Playable;
use crate::model::track::Track;
Expand Down
2 changes: 1 addition & 1 deletion src/model/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::queue::Queue;
use crate::spotify::Spotify;
use crate::traits::{IntoBoxedViewExt, ListItem, ViewExt};
use crate::ui::show::ShowView;
use rspotify::model::show::{FullShow, SimplifiedShow};
use rspotify::model::Id;
use rspotify::model::show::{FullShow, SimplifiedShow};
use std::fmt;
use std::sync::Arc;

Expand Down
2 changes: 1 addition & 1 deletion src/model/track.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use std::sync::{Arc, RwLock};
use crate::config;
use crate::utils::ms_to_hms;
use chrono::{DateTime, Utc};
use rspotify::model::Id;
use rspotify::model::album::FullAlbum;
use rspotify::model::track::{FullTrack, SavedTrack, SimplifiedTrack};
use rspotify::model::Id;

use crate::library::Library;
use crate::model::album::Album;
Expand Down
2 changes: 1 addition & 1 deletion src/mpris.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use std::error::Error;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio_stream::StreamExt;
use tokio_stream::wrappers::UnboundedReceiverStream;
use zbus::object_server::SignalEmitter;
use zbus::zvariant::{ObjectPath, Value};
use zbus::{connection, interface};
Expand Down
24 changes: 13 additions & 11 deletions src/spotify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use librespot_playback::audio_backend;
use librespot_playback::audio_backend::SinkBuilder;
use librespot_playback::config::Bitrate;
use librespot_playback::config::PlayerConfig;
use librespot_playback::mixer::softmixer::SoftMixer;
use librespot_playback::mixer::MixerConfig;
use librespot_playback::mixer::softmixer::SoftMixer;
use librespot_playback::player::Player;
use log::{debug, error, info, warn};
use tokio::sync::mpsc;
Expand Down Expand Up @@ -167,11 +167,10 @@ impl Spotify {
credentials: Credentials,
) -> Result<Session, librespot_core::Error> {
let librespot_cache_path = config::cache_path("librespot");
let audio_cache_path = match cfg.values().audio_cache { Some(false) => {
None
} _ => {
Some(librespot_cache_path.join("files"))
}};
let audio_cache_path = match cfg.values().audio_cache {
Some(false) => None,
_ => Some(librespot_cache_path.join("files")),
};
let cache = Cache::new(
Some(librespot_cache_path.clone()),
Some(librespot_cache_path.join("volume")),
Expand Down Expand Up @@ -379,11 +378,14 @@ impl Spotify {
#[cfg(feature = "mpris")]
fn send_mpris(&self, cmd: MprisCommand) {
debug!("Sending mpris command: {:?}", cmd);
match self.mpris.lock().unwrap().as_ref() { Some(mpris_manager) => {
mpris_manager.send(cmd);
} _ => {
warn!("mpris context is unitialized");
}}
match self.mpris.lock().unwrap().as_ref() {
Some(mpris_manager) => {
mpris_manager.send(cmd);
}
_ => {
warn!("mpris context is unitialized");
}
}
}

/// Send a [WorkerCommand] to the worker thread.
Expand Down
67 changes: 38 additions & 29 deletions src/spotify_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rspotify::model::{
PlaylistResult, PrivateUser, Recommendations, SavedAlbum, SavedTrack, SearchResult, SearchType,
Show, ShowId, SimplifiedTrack, TrackId, UserId,
};
use rspotify::{prelude::*, AuthCodeSpotify, ClientError, ClientResult, Config, Token};
use rspotify::{AuthCodeSpotify, ClientError, ClientResult, Config, Token, prelude::*};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;

Expand Down Expand Up @@ -97,28 +97,38 @@ impl WebApi {

let (token_tx, token_rx) = std::sync::mpsc::channel();
let cmd = WorkerCommand::RequestToken(token_tx);
match self.worker_channel.read().unwrap().as_ref() { Some(channel) => {
channel.send(cmd).unwrap();
let api_token = self.api.token.clone();
let api_token_expiration = self.token_expiration.clone();
Some(ASYNC_RUNTIME.get().unwrap().spawn_blocking(move || {
match token_rx.recv() { Ok(Some(token)) => {
*api_token.lock().unwrap() = Some(Token {
access_token: token.access_token,
expires_in: chrono::Duration::from_std(token.expires_in).unwrap(),
scopes: HashSet::from_iter(token.scopes),
expires_at: None,
refresh_token: None,
});
*api_token_expiration.write().unwrap() =
Utc::now() + ChronoDuration::from_std(token.expires_in).unwrap();
} _ => {
error!("Failed to update token");
}}
}))
} _ => {
panic!("worker channel is not set");
}}
match self.worker_channel.read().unwrap().as_ref() {
Some(channel) => {
channel.send(cmd).unwrap();
let api_token = self.api.token.clone();
let api_token_expiration = self.token_expiration.clone();
Some(
ASYNC_RUNTIME
.get()
.unwrap()
.spawn_blocking(move || match token_rx.recv() {
Ok(Some(token)) => {
*api_token.lock().unwrap() = Some(Token {
access_token: token.access_token,
expires_in: chrono::Duration::from_std(token.expires_in)
.unwrap(),
scopes: HashSet::from_iter(token.scopes),
expires_at: None,
refresh_token: None,
});
*api_token_expiration.write().unwrap() = Utc::now()
+ ChronoDuration::from_std(token.expires_in).unwrap();
}
_ => {
error!("Failed to update token");
}
}),
)
}
_ => {
panic!("worker channel is not set");
}
}
}

/// Execute `api_call` and retry once if a rate limit occurs.
Expand All @@ -131,8 +141,8 @@ impl WebApi {
Ok(v) => Some(v),
Err(ClientError::Http(error)) => {
debug!("http error: {:?}", error);
match error.as_ref() { HttpError::StatusCode(response) => {
match response.status() {
match error.as_ref() {
HttpError::StatusCode(response) => match response.status() {
429 => {
let waiting_duration = response
.header("Retry-After")
Expand All @@ -150,10 +160,9 @@ impl WebApi {
error!("unhandled api error: {:?}", response);
None
}
}
} _ => {
None
}}
},
_ => None,
}
}
Err(e) => {
error!("unhandled api error: {}", e);
Expand Down
Loading

0 comments on commit 3dc5c72

Please sign in to comment.