diff --git a/cSpell.json b/cSpell.json index bb15b6d91..537ea65a5 100644 --- a/cSpell.json +++ b/cSpell.json @@ -26,6 +26,7 @@ "hlocalhost", "Hydranode", "incompletei", + "infohash", "infoschema", "intervali", "leecher", diff --git a/src/apis/routes.rs b/src/apis/routes.rs index 72be81ab0..9fedbc822 100644 --- a/src/apis/routes.rs +++ b/src/apis/routes.rs @@ -2,7 +2,8 @@ use std::str::FromStr; use std::sync::Arc; use axum::extract::{Path, State}; -use axum::response::Json; +use axum::response::{IntoResponse, Json, Response}; +use serde_json::json; use crate::api::resource::stats::Stats; use crate::api::resource::torrent::Torrent; @@ -17,11 +18,12 @@ pub async fn get_stats(State(tracker): State>) -> Json { /// # Panics /// -/// Will panic if the torrent does not exist. -pub async fn get_torrent(State(tracker): State>, Path(info_hash): Path) -> Json { - let info = get_torrent_info(tracker.clone(), &InfoHash::from_str(&info_hash).unwrap()) - .await - .unwrap(); - // todo: return "not found" if the torrent does not exist - Json(Torrent::from(info)) +/// Will panic if it can't parse the infohash in the request +pub async fn get_torrent(State(tracker): State>, Path(info_hash): Path) -> Response { + let optional_torrent_info = get_torrent_info(tracker.clone(), &InfoHash::from_str(&info_hash).unwrap()).await; + + match optional_torrent_info { + Some(info) => Json(Torrent::from(info)).into_response(), + None => Json(json!("torrent not known")).into_response(), + } } diff --git a/tests/tracker_api.rs b/tests/tracker_api.rs index 0a942ea45..bc5271c21 100644 --- a/tests/tracker_api.rs +++ b/tests/tracker_api.rs @@ -666,7 +666,7 @@ mod tracker_apis { use torrust_tracker::api::resource::torrent::Torrent; use torrust_tracker::protocol::info_hash::InfoHash; - use crate::api::asserts::{assert_token_not_valid, assert_unauthorized}; + use crate::api::asserts::{assert_token_not_valid, assert_torrent_not_known, assert_unauthorized}; use crate::api::client::Client; use crate::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::api::fixtures::sample_peer; @@ -700,6 +700,19 @@ mod tracker_apis { ); } + #[tokio::test] + async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { + let api_server = start_default_api(&Version::Axum).await; + + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); + + let response = Client::new(api_server.get_connection_info(), &Version::Axum) + .get_torrent(&info_hash.to_string()) + .await; + + assert_torrent_not_known(response).await; + } + #[tokio::test] async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let api_server = start_default_api(&Version::Axum).await;