Skip to content

Commit

Permalink
appease clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
Mattia Di Eleuterio authored and Mattia Di Eleuterio committed Nov 18, 2023
1 parent 7614fe8 commit 60901bb
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 66 deletions.
4 changes: 2 additions & 2 deletions src/configs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub fn conf() -> impl Conf {
}

pub trait Conf {
fn get(self: &Self, key: ConfName) -> eyre::Result<String>;
fn get(&self, key: ConfName) -> eyre::Result<String>;
}

pub enum ConfName {
Expand All @@ -27,7 +27,7 @@ pub enum ConfName {
struct EnvConf {}

impl Conf for EnvConf {
fn get(self: &Self, key: ConfName) -> eyre::Result<String> {
fn get(&self, key: ConfName) -> eyre::Result<String> {
match key {
ConfName::RedisAddress => {
Ok(std::env::var("REDIS_ADDRESS").unwrap_or_else(|_| "localhost".to_string()))
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ async fn flush_redis_on_new_version() -> eyre::Result<()> {
if let Some(ref cached_version) = cached_version {
if cached_version != app_version {
info!("detected version change ({cached_version} != {app_version}) flushing redis DB");
let _: () = redis::cmd("FLUSHDB").query_async(&mut con).await?;
redis::cmd("FLUSHDB").query_async(&mut con).await?;
}
}

let _: () = redis::cmd("SET")
redis::cmd("SET")
.arg("version")
.arg(app_version)
.query_async(&mut con)
Expand Down
9 changes: 6 additions & 3 deletions src/provider/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,20 @@ impl MediaProvider for GenericProvider {

fn get_generic_whitelist() -> Vec<Regex> {
let binding = conf().get(ConfName::ValidUrlDomains).unwrap();
let patterns: Vec<&str> = binding.split(",").filter(|e| e.trim().len() > 0).collect();
let patterns: Vec<&str> = binding
.split(',')
.filter(|e| !e.trim().is_empty())
.collect();

let mut regexes: Vec<Regex> = Vec::with_capacity(patterns.len() + 1);
for pattern in patterns {
regexes
.push(Regex::new(&pattern.to_string().replace(".", "\\.").replace("*", ".+")).unwrap())
.push(Regex::new(&pattern.to_string().replace('.', "\\.").replace('*', ".+")).unwrap())
}

let match_extensions = regex::Regex::new("^(https?://)?.+\\.(mp3|mp4|wav|avi|mov|flv|wmv|mkv|aac|ogg|webm|3gp|3g2|asf|m4a|mpg|mpeg|ts|m3u|m3u8|pls)$").unwrap();
regexes.push(match_extensions);

return regexes;
regexes
}

10 changes: 5 additions & 5 deletions src/provider/peertube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ impl MediaProvider for PeerTubeProvider {
let mut regexes: Vec<Regex> = Vec::with_capacity(hosts.len());
for host in hosts {
regexes
.push(Regex::new(&host.to_string().replace(".", "\\.").replace("*", ".+")).unwrap())
.push(Regex::new(&host.to_string().replace('.', "\\.").replace('*', ".+")).unwrap())
}

return regexes;
regexes
}
}

Expand Down Expand Up @@ -74,10 +74,10 @@ async fn find_api_url(media_url: &Url) -> eyre::Result<Url> {
fn get_peertube_hosts() -> Vec<String> {
let binding = conf().get(ConfName::PeerTubeValidHosts).unwrap();
let patterns: Vec<String> = binding
.split(",")
.filter(|e| e.trim().len() > 0)
.split(',')
.filter(|e| !e.trim().is_empty())
.map(|x| x.to_string())
.collect();
return patterns;
patterns
}

10 changes: 3 additions & 7 deletions src/provider/twitch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ async fn authorize(client_id: &str, client_secret: &str) -> eyre::Result<OAuthCr
oauth_expire_epoch,
};

let _: () = redis::cmd("SET")
redis::cmd("SET")
.arg(OAuthCredentials::key())
.arg(oauth_credentials.clone())
.query_async(&mut redis)
Expand Down Expand Up @@ -361,7 +361,7 @@ fn build_items_from_vods(vods: Vec<Video>, streams: Vec<Stream>) -> Vec<Item> {
vods.into_iter()
.filter(|v| {
!streams
.into_iter()
.iter()
.any(|s| v.stream_id.as_ref().is_some_and(|vid| *vid == s.id))
})
.map(vod_to_rss_item_converter)
Expand Down Expand Up @@ -393,11 +393,7 @@ fn vod_to_rss_item_converter(vod: Video) -> Item {
let itunes_item_extension = ITunesItemExtensionBuilder::default()
.summary(Some(description))
.duration(Some({
let duration_as_string = vod
.duration
.replace("h", ":")
.replace("m", ":")
.replace("s", "");
let duration_as_string = vod.duration.replace(['h', 'm'], ":").replace('s', "");

let duration_parts = duration_as_string
.split(':')
Expand Down
32 changes: 16 additions & 16 deletions src/provider/youtube.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ async fn fetch_from_api(id: IdType, api_key: String) -> eyre::Result<(Channel, V

let rss_items = build_channel_items_from_playlist(items, duration_map);

return Ok((rss_channel, rss_items));
Ok((rss_channel, rss_items))
}
IdType::Channel(id) => {
info!("fetching channel {}", id);
Expand All @@ -190,9 +190,9 @@ async fn fetch_from_api(id: IdType, api_key: String) -> eyre::Result<(Channel, V

let rss_items = build_channel_items_from_playlist(items, duration_map);

return Ok((rss_channel, rss_items));
Ok((rss_channel, rss_items))
}
};
}
}

macro_rules! get_thumb {
Expand Down Expand Up @@ -237,7 +237,7 @@ async fn fetch_channel(id: String, api_key: &str) -> eyre::Result<api::Channel>
.list(&vec!["snippet".into(), "contentDetails".into()])
.max_results(1)
.add_id(&id)
.param("key", &api_key);
.param("key", api_key);
let result = channel_request.doit().await?;
let channel = result
.1
Expand All @@ -259,7 +259,7 @@ async fn create_duration_url_map(
api_key: &str,
) -> Result<HashMap<String, VideoExtraInfo>, eyre::Error> {
let ids_batches = items.chunks(50).map(|c| {
c.into_iter()
c.iter()
.filter_map(|i| i.snippet.clone()?.resource_id?.video_id)
});

Expand All @@ -268,7 +268,7 @@ async fn create_duration_url_map(
let mut video_info_request = hub
.videos()
.list(&vec!["contentDetails".to_owned()])
.param("key", &api_key);
.param("key", api_key);

for video_id in batch {
video_info_request = video_info_request.add_id(&video_id);
Expand Down Expand Up @@ -329,7 +329,7 @@ fn build_channel_items_from_playlist(
item_builder.pub_date(
snippet
.published_at
.and_then(|pub_date| Some(pub_date.to_rfc2822().to_string())),
.map(|pub_date| pub_date.to_rfc2822().to_string()),
);
item_builder.author(snippet.channel_title.take());
let video_infos = videos_infos.get(&video_id).or_else(|| {
Expand Down Expand Up @@ -369,7 +369,7 @@ async fn fetch_playlist_items(
.playlist_items()
.list(&vec!["snippet".into()])
.playlist_id(playlist_id)
.param("key", &api_key)
.param("key", api_key)
.max_results(50);
if let Some(ref next_page_token) = next_page_token {
playlist_items_request = playlist_items_request.page_token(next_page_token.as_str());
Expand Down Expand Up @@ -424,7 +424,7 @@ async fn fetch_playlist(id: String, api_key: &String) -> Result<api::Playlist, e
.playlists()
.list(&vec!["snippet".into()])
.add_id(&id)
.param("key", &api_key);
.param("key", api_key);
let result = playlist_request.doit().await?;
let playlist = result
.1
Expand All @@ -444,8 +444,8 @@ fn get_youtube_hub() -> YouTube<hyper_rustls::HttpsConnector<hyper::client::Http
.enable_http1()
.build();
let client = hyper::Client::builder().build(connector);
let hub = YouTube::new(client, auth);
hub

YouTube::new(client, auth)
}

#[io_cached(
Expand Down Expand Up @@ -647,7 +647,7 @@ async fn get_youtube_video_duration_with_ytdlp(url: &Url) -> eyre::Result<Option
fn parse_duration(duration_str: &str) -> Result<Duration, String> {
let duration_parts: Vec<&str> = duration_str.split(':').rev().collect();

let seconds = match duration_parts.get(0) {
let seconds = match duration_parts.first() {
Some(sec_str) => sec_str.parse().map_err(|_| "Invalid format".to_string())?,
None => 0,
};
Expand Down Expand Up @@ -683,7 +683,7 @@ mod tests {
.unwrap();

println!("{:?}", items);
assert!(items.len() > 0)
assert!(!items.is_empty())
}

#[test(tokio::test)]
Expand All @@ -696,8 +696,8 @@ mod tests {
let channel = build_channel_from_playlist(playlist);

println!("{:?}", channel);
assert!(channel.description.len() > 0);
assert!(channel.title.len() > 0);
assert!(!channel.description.is_empty());
assert!(!channel.title.is_empty());
assert!(channel.itunes_ext.unwrap().image.is_some());
}

Expand Down Expand Up @@ -729,7 +729,7 @@ mod tests {
.await;
assert!(result.is_ok());

let channel = rss::Channel::read_from(&result.unwrap().as_bytes()[..]).unwrap();
let channel = rss::Channel::read_from(result.unwrap().as_bytes()).unwrap();
assert!(channel.items.len() > 50);
for item in &channel.items {
assert!(item.title.is_some());
Expand Down
13 changes: 6 additions & 7 deletions src/rss_transcodizer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn inject_vod2pod_customizations(
rss_body: String,
transcode_service_url: Option<Url>,
) -> eyre::Result<String> {
let mut injected_feed = Channel::read_from(&rss_body.as_bytes()[..])?;
let mut injected_feed = Channel::read_from(rss_body.as_bytes())?;
injected_feed.set_generator(Some("generated by vod2pod-rss".to_string()));
let mut namespaces = BTreeMap::new();
namespaces.insert(
Expand All @@ -29,8 +29,8 @@ pub fn inject_vod2pod_customizations(
injected_feed
.items_mut()
.iter_mut()
.map(|item| -> eyre::Result<_> {
let description = get_description(&item);
.try_for_each(|item| -> eyre::Result<_> {
let description = get_description(item);
item.set_description(description);
let bitrate: u64 = conf()
.get(ConfName::Mp3Bitrate)
Expand Down Expand Up @@ -69,8 +69,7 @@ pub fn inject_vod2pod_customizations(
item.set_enclosure(Some(enclosure));
}
Ok(())
})
.collect::<eyre::Result<_>>()?;
})?;

Ok(injected_feed.to_string())
}
Expand Down Expand Up @@ -105,13 +104,13 @@ fn get_description(item: &Item) -> String {
"<br><br><a href=\"{}\"><p>link to original</p><img src=\"{}\"></a>",
url, img
);
return format!("{}{}{}", description, original_link, FOOTER);
format!("{}{}{}", description, original_link, FOOTER)
}

fn parse_duration(duration_str: &str) -> Result<Duration, String> {
let duration_parts: Vec<&str> = duration_str.split(':').rev().collect();

let seconds = match duration_parts.get(0) {
let seconds = match duration_parts.first() {
Some(sec_str) => sec_str.parse().map_err(|_| "Invalid format".to_string())?,
None => 0,
};
Expand Down
10 changes: 5 additions & 5 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ async fn transcodize_rss(
return HttpResponse::BadRequest().finish();
};

let transcode_service_url = req.url_for("transcode_mp3", &[""]).unwrap();
let transcode_service_url = req.url_for("transcode_mp3", [""]).unwrap();

let parsed_url = match Url::parse(url) {
Ok(x) => x,
Expand All @@ -92,7 +92,7 @@ async fn transcodize_rss(
if !provider
.domain_whitelist_regexes()
.iter()
.any(|r| r.is_match(&parsed_url.to_string()))
.any(|r| r.is_match(parsed_url.as_ref()))
{
error!("supplied url ({parsed_url}) not in whitelist (whitelist is needed to prevent SSRF attack)");
return HttpResponse::Forbidden().body("scheme and host not in whitelist");
Expand Down Expand Up @@ -129,7 +129,7 @@ async fn transcodize_rss(
// rewrite urls in feed
let injected_feed = rss_transcodizer::inject_vod2pod_customizations(
raw_rss,
should_transcode.then(|| transcode_service_url),
should_transcode.then_some(transcode_service_url),
);

let body = match injected_feed {
Expand Down Expand Up @@ -212,12 +212,12 @@ async fn transcode_to_mp3(req: HttpRequest, query: web::Query<TranscodizeQuery>)
}
}

let provider = provider::from(&stream_url);
let provider = provider::from(stream_url);

if !provider
.domain_whitelist_regexes()
.iter()
.any(|r| r.is_match(&stream_url.to_string()))
.any(|r| r.is_match(stream_url.as_ref()))
{
error!("supplied url ({stream_url}) not in whitelist (whitelist is needed to prevent SSRF attack)");
return HttpResponse::Forbidden().body("scheme and host not in whitelist");
Expand Down
11 changes: 5 additions & 6 deletions src/transcoder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,9 @@ impl Transcoder {
let mut out = child.stdout.take().expect("failed to open stdout");

let channel_size: usize = 10;
let (tx, mut rx): (
Sender<Result<Bytes, std::io::Error>>,
Receiver<Result<Bytes, std::io::Error>>,
) = channel(channel_size);
type ChannelBytes = Result<Bytes, std::io::Error>;
let (tx, mut rx): (Sender<ChannelBytes>, Receiver<ChannelBytes>) =
channel(channel_size);

let tx_stdout = tx.clone();
let tx_stderr = tx;
Expand Down Expand Up @@ -187,7 +186,7 @@ impl Transcoder {
sent_bytes_count += BUFFER_SIZE;
} else {
_ = tx_stdout.blocking_send(Ok(Bytes::copy_from_slice(
&NULL_BUFF[..padding_bytes.try_into().unwrap_or(0)],
&NULL_BUFF[..padding_bytes],
)));
sent_bytes_count += padding_bytes;
}
Expand Down Expand Up @@ -221,7 +220,7 @@ impl Transcoder {
};
}
warn!("read was interrupted, retrying in 1sec");
let _ = sleep(Duration::from_secs(1));
sleep(Duration::from_secs(1));
tries += 1;
}
_ => {
Expand Down
Loading

0 comments on commit 60901bb

Please sign in to comment.