|
| 1 | +//! API handlers for the [`torrent`](crate::web::api::v1::contexts::torrent) API |
| 2 | +//! context. |
| 3 | +use std::io::{Cursor, Write}; |
| 4 | +use std::sync::Arc; |
| 5 | + |
| 6 | +use axum::extract::{Multipart, State}; |
| 7 | +use axum::response::{IntoResponse, Response}; |
| 8 | + |
| 9 | +use super::responses::new_torrent_response; |
| 10 | +use crate::common::AppData; |
| 11 | +use crate::errors::ServiceError; |
| 12 | +use crate::models::torrent::TorrentRequest; |
| 13 | +use crate::models::torrent_tag::TagId; |
| 14 | +use crate::routes::torrent::Create; |
| 15 | +use crate::utils::parse_torrent; |
| 16 | +use crate::web::api::v1::extractors::bearer_token::Extract; |
| 17 | + |
| 18 | +/// Upload a new torrent file to the Index |
| 19 | +/// |
| 20 | +/// # Errors |
| 21 | +/// |
| 22 | +/// This function will return an error if |
| 23 | +/// |
| 24 | +/// - The user does not have permission to upload the torrent file. |
| 25 | +/// - The submitted torrent file is not a valid torrent file. |
| 26 | +#[allow(clippy::unused_async)] |
| 27 | +pub async fn upload_torrent_handler( |
| 28 | + State(app_data): State<Arc<AppData>>, |
| 29 | + Extract(maybe_bearer_token): Extract, |
| 30 | + multipart: Multipart, |
| 31 | +) -> Response { |
| 32 | + let user_id = match app_data.auth.get_user_id_from_bearer_token(&maybe_bearer_token).await { |
| 33 | + Ok(user_id) => user_id, |
| 34 | + Err(err) => return err.into_response(), |
| 35 | + }; |
| 36 | + |
| 37 | + let torrent_request = match get_torrent_request_from_payload(multipart).await { |
| 38 | + Ok(torrent_request) => torrent_request, |
| 39 | + Err(err) => return err.into_response(), |
| 40 | + }; |
| 41 | + |
| 42 | + let info_hash = torrent_request.torrent.info_hash().clone(); |
| 43 | + |
| 44 | + match app_data.torrent_service.add_torrent(torrent_request, user_id).await { |
| 45 | + Ok(torrent_id) => new_torrent_response(torrent_id, &info_hash).into_response(), |
| 46 | + Err(error) => error.into_response(), |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// Extracts the [`TorrentRequest`] from the multipart form payload. |
| 51 | +async fn get_torrent_request_from_payload(mut payload: Multipart) -> Result<TorrentRequest, ServiceError> { |
| 52 | + let torrent_buffer = vec![0u8]; |
| 53 | + let mut torrent_cursor = Cursor::new(torrent_buffer); |
| 54 | + |
| 55 | + let mut title = String::new(); |
| 56 | + let mut description = String::new(); |
| 57 | + let mut category = String::new(); |
| 58 | + let mut tags: Vec<TagId> = vec![]; |
| 59 | + |
| 60 | + while let Some(mut field) = payload.next_field().await.unwrap() { |
| 61 | + let name = field.name().unwrap().clone(); |
| 62 | + |
| 63 | + match name { |
| 64 | + "title" => { |
| 65 | + let data = field.bytes().await.unwrap(); |
| 66 | + if data.is_empty() { |
| 67 | + continue; |
| 68 | + }; |
| 69 | + title = String::from_utf8(data.to_vec()).map_err(|_| ServiceError::BadRequest)?; |
| 70 | + } |
| 71 | + "description" => { |
| 72 | + let data = field.bytes().await.unwrap(); |
| 73 | + if data.is_empty() { |
| 74 | + continue; |
| 75 | + }; |
| 76 | + description = String::from_utf8(data.to_vec()).map_err(|_| ServiceError::BadRequest)?; |
| 77 | + } |
| 78 | + "category" => { |
| 79 | + let data = field.bytes().await.unwrap(); |
| 80 | + if data.is_empty() { |
| 81 | + continue; |
| 82 | + }; |
| 83 | + category = String::from_utf8(data.to_vec()).map_err(|_| ServiceError::BadRequest)?; |
| 84 | + } |
| 85 | + "tags" => { |
| 86 | + let data = field.bytes().await.unwrap(); |
| 87 | + if data.is_empty() { |
| 88 | + continue; |
| 89 | + }; |
| 90 | + let string_data = String::from_utf8(data.to_vec()).map_err(|_| ServiceError::BadRequest)?; |
| 91 | + tags = serde_json::from_str(&string_data).map_err(|_| ServiceError::BadRequest)?; |
| 92 | + } |
| 93 | + "torrent" => { |
| 94 | + let content_type = field.content_type().unwrap().clone(); |
| 95 | + |
| 96 | + if content_type != "application/x-bittorrent" { |
| 97 | + return Err(ServiceError::InvalidFileType); |
| 98 | + } |
| 99 | + |
| 100 | + while let Some(chunk) = field.chunk().await.map_err(|_| (ServiceError::BadRequest))? { |
| 101 | + torrent_cursor.write_all(&chunk)?; |
| 102 | + } |
| 103 | + } |
| 104 | + _ => {} |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + let fields = Create { |
| 109 | + title, |
| 110 | + description, |
| 111 | + category, |
| 112 | + tags, |
| 113 | + }; |
| 114 | + |
| 115 | + fields.verify()?; |
| 116 | + |
| 117 | + let position = usize::try_from(torrent_cursor.position()).map_err(|_| ServiceError::InvalidTorrentFile)?; |
| 118 | + let inner = torrent_cursor.get_ref(); |
| 119 | + |
| 120 | + let torrent = parse_torrent::decode_torrent(&inner[..position]).map_err(|_| ServiceError::InvalidTorrentFile)?; |
| 121 | + |
| 122 | + // Make sure that the pieces key has a length that is a multiple of 20 |
| 123 | + // code-review: I think we could put this inside the service. |
| 124 | + if let Some(pieces) = torrent.info.pieces.as_ref() { |
| 125 | + if pieces.as_ref().len() % 20 != 0 { |
| 126 | + return Err(ServiceError::InvalidTorrentPiecesLength); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + Ok(TorrentRequest { fields, torrent }) |
| 131 | +} |
0 commit comments