Fixed clippy lints

This commit is contained in:
Antoine Gersant 2018-10-06 16:29:46 -07:00
parent 0297b351bf
commit ec69a3568f
13 changed files with 93 additions and 108 deletions

View file

@ -54,8 +54,8 @@ where
Ok(misc.auth_secret.to_owned()) Ok(misc.auth_secret.to_owned())
} }
pub fn get_handler(db: Arc<DB>, index: Arc<Mutex<Sender<index::Command>>>) -> Result<Chain> { pub fn get_handler(db: &Arc<DB>, index: &Arc<Mutex<Sender<index::Command>>>) -> Result<Chain> {
let api_handler = get_endpoints(db.clone(), index); let api_handler = get_endpoints(&db.clone(), &index);
let mut api_chain = Chain::new(api_handler); let mut api_chain = Chain::new(api_handler);
let auth_secret = get_auth_secret(db.deref())?; let auth_secret = get_auth_secret(db.deref())?;
@ -72,7 +72,7 @@ pub fn get_handler(db: Arc<DB>, index: Arc<Mutex<Sender<index::Command>>>) -> Re
Ok(api_chain) Ok(api_chain)
} }
fn get_endpoints(db: Arc<DB>, index_channel: Arc<Mutex<Sender<index::Command>>>) -> Mount { fn get_endpoints(db: &Arc<DB>, index_channel: &Arc<Mutex<Sender<index::Command>>>) -> Mount {
let mut api_handler = Mount::new(); let mut api_handler = Mount::new();
{ {
@ -259,7 +259,7 @@ impl AroundMiddleware for AuthRequirement {
fn around(self, handler: Box<Handler>) -> Box<Handler> { fn around(self, handler: Box<Handler>) -> Box<Handler> {
Box::new(AuthHandler { Box::new(AuthHandler {
db: self.db, db: self.db,
handler: handler, handler,
}) as Box<Handler> }) as Box<Handler>
} }
} }
@ -272,12 +272,8 @@ struct AuthHandler {
impl Handler for AuthHandler { impl Handler for AuthHandler {
fn handle(&self, req: &mut Request) -> IronResult<Response> { fn handle(&self, req: &mut Request) -> IronResult<Response> {
{ {
let mut auth_success = false;
// Skip auth for first time setup // Skip auth for first time setup
if user::count(self.db.deref())? == 0 { let mut auth_success = user::count(self.db.deref())? == 0;
auth_success = true;
}
// Auth via Authorization header // Auth via Authorization header
if !auth_success { if !auth_success {
@ -317,7 +313,7 @@ impl AroundMiddleware for AdminRequirement {
fn around(self, handler: Box<Handler>) -> Box<Handler> { fn around(self, handler: Box<Handler>) -> Box<Handler> {
Box::new(AdminHandler { Box::new(AdminHandler {
db: self.db, db: self.db,
handler: handler, handler,
}) as Box<Handler> }) as Box<Handler>
} }
} }
@ -330,12 +326,8 @@ struct AdminHandler {
impl Handler for AdminHandler { impl Handler for AdminHandler {
fn handle(&self, req: &mut Request) -> IronResult<Response> { fn handle(&self, req: &mut Request) -> IronResult<Response> {
{ {
let mut auth_success = false;
// Skip auth for first time setup // Skip auth for first time setup
if user::count(self.db.deref())? == 0 { let mut auth_success = user::count(self.db.deref())? == 0;
auth_success = true;
}
if !auth_success { if !auth_success {
match req.extensions.get::<SessionKey>() { match req.extensions.get::<SessionKey>() {
@ -674,10 +666,10 @@ fn read_playlist(request: &mut Request, db: &DB) -> IronResult<Response> {
}; };
let params = request.extensions.get::<Router>().unwrap(); let params = request.extensions.get::<Router>().unwrap();
let ref playlist_name = match params.find("playlist_name") { let playlist_name = &(match params.find("playlist_name") {
Some(s) => s, Some(s) => s,
_ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()), _ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()),
}; });
let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() { let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() {
Ok(s) => s, Ok(s) => s,
@ -701,10 +693,10 @@ fn delete_playlist(request: &mut Request, db: &DB) -> IronResult<Response> {
}; };
let params = request.extensions.get::<Router>().unwrap(); let params = request.extensions.get::<Router>().unwrap();
let ref playlist_name = match params.find("playlist_name") { let playlist_name = &(match params.find("playlist_name") {
Some(s) => s, Some(s) => s,
_ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()), _ => return Err(Error::from(ErrorKind::MissingPlaylistName).into()),
}; });
let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() { let playlist_name = match percent_decode(playlist_name.as_bytes()).decode_utf8() {
Ok(s) => s, Ok(s) => s,

View file

@ -119,7 +119,7 @@ where
found_users found_users
.into_iter() .into_iter()
.map(|(name, admin)| ConfigUser { .map(|(name, admin)| ConfigUser {
name: name, name,
password: "".to_owned(), password: "".to_owned(),
admin: admin != 0, admin: admin != 0,
}).collect::<_>(), }).collect::<_>(),
@ -193,7 +193,7 @@ where
.find(|old_name| *old_name == &u.name) .find(|old_name| *old_name == &u.name)
.is_none() .is_none()
}).collect::<_>(); }).collect::<_>();
for ref config_user in insert_users { for config_user in &insert_users {
let new_user = User::new(&config_user.name, &config_user.password); let new_user = User::new(&config_user.name, &config_user.password);
diesel::insert_into(users::table) diesel::insert_into(users::table)
.values(&new_user) .values(&new_user)
@ -201,7 +201,7 @@ where
} }
// Update users // Update users
for ref user in config_users { for user in config_users.iter() {
// Update password if provided // Update password if provided
if !user.password.is_empty() { if !user.password.is_empty() {
let salt: Vec<u8> = users::table let salt: Vec<u8> = users::table
@ -282,8 +282,7 @@ fn _get_test_db(name: &str) -> DB {
fs::remove_file(&db_path).unwrap(); fs::remove_file(&db_path).unwrap();
} }
let db = DB::new(&db_path).unwrap(); DB::new(&db_path).unwrap()
db
} }
#[test] #[test]

View file

@ -13,7 +13,7 @@ mod schema;
pub use self::schema::*; pub use self::schema::*;
#[allow(dead_code)] #[allow(dead_code)]
const DB_MIGRATIONS_PATH: &'static str = "src/db/migrations"; const DB_MIGRATIONS_PATH: &str = "src/db/migrations";
embed_migrations!("src/db/migrations"); embed_migrations!("src/db/migrations");
pub trait ConnectionSource { pub trait ConnectionSource {

View file

@ -34,38 +34,38 @@ impl DDNSConfigSource for DB {
#[derive(Debug)] #[derive(Debug)]
enum DDNSError { enum DDNSError {
InternalError(errors::Error), Internal(errors::Error),
IoError(io::Error), Io(io::Error),
ReqwestError(reqwest::Error), Reqwest(reqwest::Error),
UpdateError(reqwest::StatusCode), Update(reqwest::StatusCode),
} }
impl From<io::Error> for DDNSError { impl From<io::Error> for DDNSError {
fn from(err: io::Error) -> DDNSError { fn from(err: io::Error) -> DDNSError {
DDNSError::IoError(err) DDNSError::Io(err)
} }
} }
impl From<errors::Error> for DDNSError { impl From<errors::Error> for DDNSError {
fn from(err: errors::Error) -> DDNSError { fn from(err: errors::Error) -> DDNSError {
DDNSError::InternalError(err) DDNSError::Internal(err)
} }
} }
impl From<reqwest::Error> for DDNSError { impl From<reqwest::Error> for DDNSError {
fn from(err: reqwest::Error) -> DDNSError { fn from(err: reqwest::Error) -> DDNSError {
DDNSError::ReqwestError(err) DDNSError::Reqwest(err)
} }
} }
const DDNS_UPDATE_URL: &'static str = "https://ydns.io/api/v1/update/"; const DDNS_UPDATE_URL: &str = "https://ydns.io/api/v1/update/";
fn update_my_ip<T>(config_source: &T) -> Result<(), DDNSError> fn update_my_ip<T>(config_source: &T) -> Result<(), DDNSError>
where where
T: DDNSConfigSource, T: DDNSConfigSource,
{ {
let config = config_source.get_ddns_config()?; let config = config_source.get_ddns_config()?;
if config.host.len() == 0 || config.username.len() == 0 { if config.host.is_empty() || config.username.is_empty() {
info!("Skipping DDNS update because credentials are missing"); info!("Skipping DDNS update because credentials are missing");
return Ok(()); return Ok(());
} }
@ -78,7 +78,7 @@ where
let client = reqwest::Client::new()?; let client = reqwest::Client::new()?;
let res = client.get(full_url.as_str()).header(auth_header).send()?; let res = client.get(full_url.as_str()).header(auth_header).send()?;
if !res.status().is_success() { if !res.status().is_success() {
return Err(DDNSError::UpdateError(*res.status())); return Err(DDNSError::Update(*res.status()));
} }
Ok(()) Ok(())
} }

View file

@ -120,10 +120,10 @@ impl<'conn> IndexBuilder<'conn> {
new_songs.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE); new_songs.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE);
new_directories.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE); new_directories.reserve_exact(INDEX_BUILDING_INSERT_BUFFER_SIZE);
Ok(IndexBuilder { Ok(IndexBuilder {
new_songs: new_songs, new_songs,
new_directories: new_directories, new_directories,
connection: connection, connection,
album_art_pattern: album_art_pattern, album_art_pattern,
}) })
} }
@ -197,7 +197,7 @@ impl<'conn> IndexBuilder<'conn> {
let metadata = fs::metadata(path_string)?; let metadata = fs::metadata(path_string)?;
let created = metadata let created = metadata
.created() .created()
.or(metadata.modified())? .or_else(|_| metadata.modified())?
.duration_since(time::UNIX_EPOCH)? .duration_since(time::UNIX_EPOCH)?
.as_secs() as i32; .as_secs() as i32;
@ -237,17 +237,17 @@ impl<'conn> IndexBuilder<'conn> {
if tags.album.is_some() { if tags.album.is_some() {
inconsistent_directory_album |= inconsistent_directory_album |=
directory_album.is_some() && directory_album != tags.album; directory_album.is_some() && directory_album != tags.album;
directory_album = tags.album.as_ref().map(|a| a.clone()); directory_album = tags.album.as_ref().cloned();
} }
if tags.album_artist.is_some() { if tags.album_artist.is_some() {
inconsistent_directory_artist |= inconsistent_directory_artist |=
directory_artist.is_some() && directory_artist != tags.album_artist; directory_artist.is_some() && directory_artist != tags.album_artist;
directory_artist = tags.album_artist.as_ref().map(|a| a.clone()); directory_artist = tags.album_artist.as_ref().cloned();
} else if tags.artist.is_some() { } else if tags.artist.is_some() {
inconsistent_directory_artist |= inconsistent_directory_artist |=
directory_artist.is_some() && directory_artist != tags.artist; directory_artist.is_some() && directory_artist != tags.artist;
directory_artist = tags.artist.as_ref().map(|a| a.clone()); directory_artist = tags.artist.as_ref().cloned();
} }
let song = NewSong { let song = NewSong {
@ -261,7 +261,7 @@ impl<'conn> IndexBuilder<'conn> {
album_artist: tags.album_artist, album_artist: tags.album_artist,
album: tags.album, album: tags.album,
year: tags.year, year: tags.year,
artwork: artwork.as_ref().map(|s| s.to_owned()), artwork: artwork.as_ref().cloned(),
}; };
self.push_song(song)?; self.push_song(song)?;
@ -283,7 +283,7 @@ impl<'conn> IndexBuilder<'conn> {
let directory = NewDirectory { let directory = NewDirectory {
path: path_string.to_owned(), path: path_string.to_owned(),
parent: parent_string, parent: parent_string,
artwork: artwork, artwork,
album: directory_album, album: directory_album,
artist: directory_artist, artist: directory_artist,
year: directory_year, year: directory_year,
@ -373,7 +373,7 @@ where
let connection_mutex = db.get_connection_mutex(); let connection_mutex = db.get_connection_mutex();
let mut builder = IndexBuilder::new(connection_mutex.deref(), album_art_pattern)?; let mut builder = IndexBuilder::new(connection_mutex.deref(), album_art_pattern)?;
for (_, target) in mount_points { for target in mount_points.values() {
builder.populate_directory(None, target.as_path())?; builder.populate_directory(None, target.as_path())?;
} }
builder.flush_songs()?; builder.flush_songs()?;
@ -396,7 +396,7 @@ where
Ok(()) Ok(())
} }
pub fn update_loop<T>(db: &T, command_buffer: Receiver<Command>) pub fn update_loop<T>(db: &T, command_buffer: &Receiver<Command>)
where where
T: ConnectionSource + VFSSource, T: ConnectionSource + VFSSource,
{ {
@ -426,7 +426,7 @@ where
} }
} }
pub fn self_trigger<T>(db: &T, command_buffer: Arc<Mutex<Sender<Command>>>) pub fn self_trigger<T>(db: &T, command_buffer: &Arc<Mutex<Sender<Command>>>)
where where
T: ConnectionSource, T: ConnectionSource,
{ {
@ -503,7 +503,7 @@ where
output.extend( output.extend(
virtual_directories virtual_directories
.into_iter() .into_iter()
.map(|d| CollectionFile::Directory(d)), .map(CollectionFile::Directory),
); );
} else { } else {
// Browse sub-directory // Browse sub-directory
@ -517,7 +517,7 @@ where
let virtual_directories = real_directories let virtual_directories = real_directories
.into_iter() .into_iter()
.filter_map(|s| virtualize_directory(&vfs, s)); .filter_map(|s| virtualize_directory(&vfs, s));
output.extend(virtual_directories.map(|d| CollectionFile::Directory(d))); output.extend(virtual_directories.map(CollectionFile::Directory));
let real_songs: Vec<Song> = songs::table let real_songs: Vec<Song> = songs::table
.filter(songs::parent.eq(&real_path_string)) .filter(songs::parent.eq(&real_path_string))
@ -526,7 +526,7 @@ where
let virtual_songs = real_songs let virtual_songs = real_songs
.into_iter() .into_iter()
.filter_map(|s| virtualize_song(&vfs, s)); .filter_map(|s| virtualize_song(&vfs, s));
output.extend(virtual_songs.map(|s| CollectionFile::Song(s))); output.extend(virtual_songs.map(CollectionFile::Song));
} }
Ok(output) Ok(output)
@ -614,7 +614,7 @@ where
.into_iter() .into_iter()
.filter_map(|s| virtualize_directory(&vfs, s)); .filter_map(|s| virtualize_directory(&vfs, s));
output.extend(virtual_directories.map(|d| CollectionFile::Directory(d))); output.extend(virtual_directories.map(CollectionFile::Directory));
} }
// Find songs with matching title/album/artist and non-matching parent // Find songs with matching title/album/artist and non-matching parent
@ -634,7 +634,7 @@ where
.into_iter() .into_iter()
.filter_map(|s| virtualize_song(&vfs, s)); .filter_map(|s| virtualize_song(&vfs, s));
output.extend(virtual_songs.map(|s| CollectionFile::Song(s))); output.extend(virtual_songs.map(CollectionFile::Song));
} }
Ok(output) Ok(output)

View file

@ -53,9 +53,9 @@ where
{ {
let song = index::get_song(db, track)?; let song = index::get_song(db, track)?;
Ok(Scrobble::new( Ok(Scrobble::new(
song.artist.unwrap_or("".into()), song.artist.unwrap_or_else(|| "".into()),
song.title.unwrap_or("".into()), song.title.unwrap_or_else(|| "".into()),
song.album.unwrap_or("".into()), song.album.unwrap_or_else(|| "".into()),
)) ))
} }

View file

@ -218,22 +218,22 @@ fn run() -> Result<()> {
let db_ref = db.clone(); let db_ref = db.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let db = db_ref.deref(); let db = db_ref.deref();
index::update_loop(db, index_receiver); index::update_loop(db, &index_receiver);
}); });
// Trigger auto-indexing // Trigger auto-indexing
let db_ref = db.clone(); let db_ref = db.clone();
let sender_ref = index_sender.clone(); let sender_ref = index_sender.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
index::self_trigger(db_ref.deref(), sender_ref); index::self_trigger(db_ref.deref(), &sender_ref);
}); });
// Mount API // Mount API
let prefix_url = config.prefix_url.unwrap_or("".to_string()); let prefix_url = config.prefix_url.unwrap_or_else(|| "".to_string());
let api_url = format!("{}/api", &prefix_url); let api_url = format!("{}/api", &prefix_url);
info!("Mounting API on {}", api_url); info!("Mounting API on {}", api_url);
let mut mount = Mount::new(); let mut mount = Mount::new();
let handler = api::get_handler(db.clone(), index_sender)?; let handler = api::get_handler(&db.clone(), &index_sender)?;
mount.mount(&api_url, handler); mount.mount(&api_url, handler);
// Mount static files // Mount static files
@ -252,7 +252,7 @@ fn run() -> Result<()> {
info!("Starting up server"); info!("Starting up server");
let port: u16 = matches let port: u16 = matches
.opt_str("p") .opt_str("p")
.unwrap_or("5050".to_owned()) .unwrap_or_else(|| "5050".to_owned())
.parse() .parse()
.or(Err("invalid port number"))?; .or(Err("invalid port number"))?;

View file

@ -48,18 +48,18 @@ fn read_id3(path: &Path) -> Result<SongTags> {
let year = tag let year = tag
.year() .year()
.map(|y| y as i32) .map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year))) .or_else(|| tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year))); .or_else(|| tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags { Ok(SongTags {
artist: artist, artist,
album_artist: album_artist, album_artist,
album: album, album,
title: title, title,
duration: duration, duration,
disc_number: disc_number, disc_number,
track_number: track_number, track_number,
year: year, year,
}) })
} }
@ -101,14 +101,14 @@ fn read_ape(path: &Path) -> Result<SongTags> {
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y); let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y); let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags { Ok(SongTags {
artist: artist, artist,
album_artist: album_artist, album_artist,
album: album, album,
title: title, title,
duration: None, duration: None,
disc_number: disc_number, disc_number,
track_number: track_number, track_number,
year: year, year,
}) })
} }
@ -163,10 +163,10 @@ fn read_flac(path: &Path) -> Result<SongTags> {
album_artist: vorbis.album_artist().map(|v| v[0].clone()), album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()), album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()), title: vorbis.title().map(|v| v[0].clone()),
duration: duration, duration,
disc_number: disc_number, disc_number,
track_number: vorbis.track(), track_number: vorbis.track(),
year: year, year,
}) })
} }

View file

@ -73,7 +73,7 @@ pub fn list_playlists<T>(owner: &str, db: &T) -> Result<Vec<String>>
pub fn save_playlist<T>(playlist_name: &str, pub fn save_playlist<T>(playlist_name: &str,
owner: &str, owner: &str,
content: &Vec<String>, content: &[String],
db: &T) db: &T)
-> Result<()> -> Result<()>
where T: ConnectionSource + VFSSource where T: ConnectionSource + VFSSource
@ -124,7 +124,7 @@ pub fn save_playlist<T>(playlist_name: &str,
.and_then(|p| p.to_str().map(|s| s.to_owned())) { .and_then(|p| p.to_str().map(|s| s.to_owned())) {
new_songs.push(NewPlaylistSong { new_songs.push(NewPlaylistSong {
playlist: playlist.id, playlist: playlist.id,
path: real_path.into(), path: real_path,
ordering: i as i32, ordering: i as i32,
}); });
} }

View file

@ -27,7 +27,7 @@ pub fn deliver(path: &Path, range_header: Option<&Range>) -> IronResult<Response
}; };
let accept_range_header = Header(AcceptRanges(vec![RangeUnit::Bytes])); let accept_range_header = Header(AcceptRanges(vec![RangeUnit::Bytes]));
let range_header = range_header.map(|h| h.clone()); let range_header = range_header.cloned();
match range_header { match range_header {
None => Ok(Response::with((status::Ok, path, accept_range_header))), None => Ok(Response::with((status::Ok, path, accept_range_header))),
@ -85,8 +85,8 @@ impl PartialFile {
{ {
let range = range.into(); let range = range.into();
PartialFile { PartialFile {
file: file, file,
range: range, range,
} }
} }

View file

@ -12,7 +12,7 @@ use std::path::*;
use errors::*; use errors::*;
use utils; use utils;
const THUMBNAILS_PATH: &'static str = "thumbnails"; const THUMBNAILS_PATH: &str = "thumbnails";
fn hash(path: &Path, dimension: u32) -> u64 { fn hash(path: &Path, dimension: u32) -> u64 {
let path_string = path.to_string_lossy(); let path_string = path.to_string_lossy();

View file

@ -35,7 +35,7 @@ impl User {
} }
} }
pub fn hash_password(salt: &Vec<u8>, password: &str) -> Vec<u8> { pub fn hash_password(salt: &[u8], password: &str) -> Vec<u8> {
let mut hash: PasswordHash = [0; CREDENTIAL_LEN]; let mut hash: PasswordHash = [0; CREDENTIAL_LEN];
pbkdf2::derive( pbkdf2::derive(
DIGEST_ALG, DIGEST_ALG,

View file

@ -53,16 +53,13 @@ impl VFS {
pub fn real_to_virtual(&self, real_path: &Path) -> Result<PathBuf> { pub fn real_to_virtual(&self, real_path: &Path) -> Result<PathBuf> {
for (name, target) in &self.mount_points { for (name, target) in &self.mount_points {
match real_path.strip_prefix(target) { if let Ok(p) = real_path.strip_prefix(target) {
Ok(p) => { let mount_path = Path::new(&name);
let mount_path = Path::new(&name); return if p.components().count() == 0 {
return if p.components().count() == 0 { Ok(mount_path.to_path_buf())
Ok(mount_path.to_path_buf()) } else {
} else { Ok(mount_path.join(p))
Ok(mount_path.join(p)) };
};
}
Err(_) => (),
} }
} }
bail!("Real path has no match in VFS") bail!("Real path has no match in VFS")
@ -71,22 +68,19 @@ impl VFS {
pub fn virtual_to_real(&self, virtual_path: &Path) -> Result<PathBuf> { pub fn virtual_to_real(&self, virtual_path: &Path) -> Result<PathBuf> {
for (name, target) in &self.mount_points { for (name, target) in &self.mount_points {
let mount_path = Path::new(&name); let mount_path = Path::new(&name);
match virtual_path.strip_prefix(mount_path) { if let Ok(p) = virtual_path.strip_prefix(mount_path) {
Ok(p) => { return if p.components().count() == 0 {
return if p.components().count() == 0 { Ok(target.clone())
Ok(target.clone()) } else {
} else { Ok(target.join(p))
Ok(target.join(p)) };
};
}
Err(_) => (),
} }
} }
bail!("Virtual path has no match in VFS") bail!("Virtual path has no match in VFS")
} }
pub fn get_mount_points(&self) -> &HashMap<String, PathBuf> { pub fn get_mount_points(&self) -> &HashMap<String, PathBuf> {
return &self.mount_points; &self.mount_points
} }
} }