rqbit/crates/librqbit/src/http_api.rs

517 lines
16 KiB
Rust
Raw Normal View History

2021-10-10 09:57:21 +01:00
use anyhow::Context;
use axum::body::Bytes;
2022-12-08 11:06:29 +00:00
use axum::extract::{Path, Query, State};
use axum::response::IntoResponse;
use axum::routing::get;
2021-10-23 09:37:37 +01:00
use buffers::ByteString;
2021-07-14 13:40:56 +01:00
use dht::{Dht, DhtStats};
2022-12-08 20:43:02 +00:00
use http::StatusCode;
2023-11-22 17:19:35 +00:00
use itertools::Itertools;
2021-10-23 09:37:37 +01:00
use librqbit_core::id20::Id20;
use librqbit_core::torrent_metainfo::TorrentMetaV1Info;
2021-07-08 00:09:00 +01:00
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
2021-10-10 09:57:21 +01:00
use std::net::SocketAddr;
use std::sync::Arc;
2021-07-08 23:03:58 +01:00
use std::time::{Duration, Instant};
2023-11-19 20:15:42 +00:00
use tracing::{info, warn};
2022-12-04 12:53:55 +00:00
use axum::Router;
2021-06-30 10:14:33 +01:00
use crate::http_api_error::{ApiError, ApiErrorExt};
2023-11-20 14:05:38 +00:00
use crate::peer_state::PeerStatsFilter;
use crate::session::{
AddTorrent, AddTorrentOptions, AddTorrentResponse, ListOnlyResponse, Session,
};
2021-07-08 00:09:00 +01:00
use crate::torrent_manager::TorrentManagerHandle;
2023-11-20 14:05:38 +00:00
use crate::torrent_state::StatsSnapshot;
2021-07-08 23:03:58 +01:00
2022-12-08 15:40:29 +00:00
// Public API
#[derive(Clone)]
pub struct HttpApi {
inner: Arc<ApiInternal>,
2022-12-08 09:28:01 +00:00
}
2022-12-08 15:40:29 +00:00
impl HttpApi {
pub fn new(session: Arc<Session>) -> Self {
2022-12-08 09:28:01 +00:00
Self {
2022-12-08 15:40:29 +00:00
inner: Arc::new(ApiInternal::new(session)),
2022-12-08 09:28:01 +00:00
}
}
2022-12-08 15:40:29 +00:00
pub fn add_torrent_handle(&self, handle: TorrentManagerHandle) -> usize {
self.inner.add_torrent_handle(handle)
2022-12-08 11:06:29 +00:00
}
2022-12-08 15:40:29 +00:00
pub async fn make_http_api_and_run(self, addr: SocketAddr) -> anyhow::Result<()> {
let state = self.inner;
async fn api_root() -> impl IntoResponse {
axum::Json(serde_json::json!({
"apis": {
"GET /": "list all available APIs",
"GET /dht/stats": "DHT stats",
"GET /dht/table": "DHT routing table",
"GET /torrents": "List torrents (default torrent is 0)",
"GET /torrents/{index}": "Torrent details",
"GET /torrents/{index}/haves": "The bitfield of have pieces",
"GET /torrents/{index}/stats": "Torrent stats",
2023-11-20 13:55:42 +00:00
"GET /torrents/{index}/peer_stats": "Per peer stats",
// This is kind of not secure as it just reads any local file that it has access to,
// or any URL, but whatever, ok for our purposes / threat model.
2023-11-21 12:56:07 +00:00
"POST /torrents": "Add a torrent here. magnet: or http:// or a local file.",
"GET /web/": "Web UI",
},
"server": "rqbit",
}))
}
async fn dht_stats(State(state): State<ApiState>) -> Result<impl IntoResponse> {
state.api_dht_stats().map(axum::Json)
}
async fn dht_table(State(state): State<ApiState>) -> Result<impl IntoResponse> {
state.api_dht_table().map(axum::Json)
}
async fn torrents_list(State(state): State<ApiState>) -> impl IntoResponse {
axum::Json(state.api_torrent_list())
}
async fn torrents_post(
State(state): State<ApiState>,
Query(params): Query<TorrentAddQueryParams>,
data: Bytes,
) -> Result<impl IntoResponse> {
let opts = params.into_add_torrent_options();
let add = match String::from_utf8(data.to_vec()) {
Ok(s) => AddTorrent::Url(s.into()),
Err(e) => AddTorrent::TorrentFileBytes(e.into_bytes().into()),
};
state.api_add_torrent(add, Some(opts)).await.map(axum::Json)
}
async fn torrent_details(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_torrent_details(idx).map(axum::Json)
}
async fn torrent_haves(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_dump_haves(idx)
}
async fn torrent_stats(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_stats(idx).map(axum::Json)
}
2022-12-08 09:28:01 +00:00
2023-11-20 13:55:42 +00:00
async fn peer_stats(
State(state): State<ApiState>,
Path(idx): Path<usize>,
Query(filter): Query<PeerStatsFilter>,
) -> Result<impl IntoResponse> {
state.api_peer_stats(idx, filter).map(axum::Json)
}
2023-11-20 22:10:01 +00:00
#[allow(unused_mut)]
2023-11-20 20:15:40 +00:00
let mut app = Router::new()
.route("/", get(api_root))
.route("/dht/stats", get(dht_stats))
.route("/dht/table", get(dht_table))
.route("/torrents", get(torrents_list).post(torrents_post))
.route("/torrents/:id", get(torrent_details))
.route("/torrents/:id/haves", get(torrent_haves))
.route("/torrents/:id/stats", get(torrent_stats))
2023-11-20 20:15:40 +00:00
.route("/torrents/:id/peer_stats", get(peer_stats));
#[cfg(feature = "webui")]
{
let webui_router = Router::new()
.route(
"/",
get(|| async {
(
[("Content-Type", "text/html")],
include_str!("../webui/dist/index.html"),
2023-11-20 20:15:40 +00:00
)
}),
)
.route(
"/app.js",
get(|| async {
(
[("Content-Type", "application/javascript")],
include_str!("../webui/dist/app.js"),
2023-11-20 20:15:40 +00:00
)
}),
);
2023-11-20 22:10:01 +00:00
// This is to develop webui by just doing "open index.html && tsc --watch"
let cors_layer = std::env::var("CORS_DEBUG")
.ok()
.map(|_| {
use tower_http::cors::{AllowHeaders, AllowOrigin};
warn!("CorsLayer: allowing everything because CORS_DEBUG is set");
2023-11-20 20:15:40 +00:00
tower_http::cors::CorsLayer::default()
.allow_origin(AllowOrigin::predicate(|_, _| true))
.allow_headers(AllowHeaders::any())
2023-11-20 22:10:01 +00:00
})
.unwrap_or_default();
2023-11-20 20:15:40 +00:00
app = app.nest("/web/", webui_router).layer(cors_layer);
}
let app = app
.layer(tower_http::trace::TraceLayer::new_for_http())
2023-11-20 20:15:40 +00:00
.with_state(state)
.into_make_service();
2022-12-08 09:28:01 +00:00
2023-11-19 12:50:11 +00:00
info!("starting HTTP server on {}", addr);
2022-12-08 15:40:29 +00:00
axum::Server::try_bind(&addr)
.with_context(|| format!("error binding to {addr}"))?
2023-11-20 20:15:40 +00:00
.serve(app)
2022-12-08 15:40:29 +00:00
.await?;
Ok(())
2022-12-08 09:28:01 +00:00
}
}
2022-12-08 15:40:29 +00:00
type Result<T> = std::result::Result<T, ApiError>;
2021-07-08 00:09:00 +01:00
2021-07-08 23:03:58 +01:00
#[derive(Serialize)]
struct Speed {
mbps: f64,
human_readable: String,
}
impl Speed {
fn new(mbps: f64) -> Self {
Self {
mbps,
2022-12-04 12:53:55 +00:00
human_readable: format!("{mbps:.2} MiB/s"),
2021-07-08 23:03:58 +01:00
}
}
}
impl From<f64> for Speed {
fn from(mbps: f64) -> Self {
Self::new(mbps)
}
}
#[derive(Serialize)]
struct TorrentListResponseItem {
id: usize,
info_hash: String,
}
#[derive(Serialize)]
struct TorrentListResponse {
torrents: Vec<TorrentListResponseItem>,
}
2021-10-23 09:37:37 +01:00
#[derive(Serialize, Deserialize)]
pub struct TorrentDetailsResponseFile {
pub name: String,
pub length: u64,
pub included: bool,
2021-07-08 23:49:25 +01:00
}
2021-10-23 09:37:37 +01:00
#[derive(Serialize, Deserialize)]
pub struct TorrentDetailsResponse {
pub info_hash: String,
pub files: Vec<TorrentDetailsResponseFile>,
2021-07-08 23:49:25 +01:00
}
struct DurationWithHumanReadable(Duration);
impl Serialize for DurationWithHumanReadable {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
#[derive(Serialize)]
struct Tmp {
duration: Duration,
human_readable: String,
}
Tmp {
duration: self.0,
human_readable: format!("{:?}", self.0),
}
.serialize(serializer)
}
}
2021-07-08 23:03:58 +01:00
#[derive(Serialize)]
struct StatsResponse {
snapshot: StatsSnapshot,
average_piece_download_time: Option<Duration>,
download_speed: Speed,
all_time_download_speed: Speed,
time_remaining: Option<DurationWithHumanReadable>,
2021-07-08 00:09:00 +01:00
}
2021-10-23 09:37:37 +01:00
#[derive(Serialize, Deserialize)]
pub struct ApiAddTorrentResponse {
pub id: Option<usize>,
pub details: TorrentDetailsResponse,
}
2023-11-22 17:19:35 +00:00
pub struct OnlyFiles(Vec<usize>);
impl Serialize for OnlyFiles {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let s = self.0.iter().map(|id| id.to_string()).join(",");
s.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for OnlyFiles {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let s = String::deserialize(deserializer)?;
let list = s
.split(',')
.try_fold(Vec::<usize>::new(), |mut acc, c| match c.parse() {
Ok(i) => {
acc.push(i);
Ok(acc)
}
Err(_) => Err(D::Error::custom(format!(
"only_files: failed to parse {:?} as integer",
c
))),
})?;
if list.is_empty() {
return Err(D::Error::custom(
"only_files: should contain at least one file id",
));
}
Ok(OnlyFiles(list))
2023-11-22 15:26:24 +00:00
}
}
2022-12-08 15:40:29 +00:00
#[derive(Serialize, Deserialize)]
pub struct TorrentAddQueryParams {
pub overwrite: Option<bool>,
pub output_folder: Option<String>,
pub sub_folder: Option<String>,
pub only_files_regex: Option<String>,
2023-11-22 17:19:35 +00:00
pub only_files: Option<OnlyFiles>,
2022-12-08 15:40:29 +00:00
pub list_only: Option<bool>,
2021-10-23 09:37:37 +01:00
}
2022-12-08 15:40:29 +00:00
impl TorrentAddQueryParams {
fn into_add_torrent_options(self) -> AddTorrentOptions {
AddTorrentOptions {
overwrite: self.overwrite.unwrap_or(false),
only_files_regex: self.only_files_regex,
2023-11-22 17:19:35 +00:00
only_files: self.only_files.map(|o| o.0),
2022-12-08 15:40:29 +00:00
output_folder: self.output_folder,
sub_folder: self.sub_folder,
list_only: self.list_only.unwrap_or(false),
..Default::default()
}
}
}
// Private HTTP API internals. Agnostic of web framework.
pub struct ApiInternal {
dht: Option<Dht>,
startup_time: Instant,
torrent_managers: RwLock<Vec<TorrentManagerHandle>>,
session: Arc<Session>,
}
type ApiState = Arc<ApiInternal>;
2021-07-13 14:59:44 +01:00
impl ApiInternal {
2023-05-07 13:12:57 +02:00
pub fn new(session: Arc<Session>) -> Self {
2022-12-08 15:40:29 +00:00
Self {
dht: session.get_dht(),
startup_time: Instant::now(),
torrent_managers: RwLock::new(Vec::new()),
session,
}
}
fn add_torrent_handle(&self, handle: TorrentManagerHandle) -> usize {
let mut g = self.torrent_managers.write();
let idx = g.len();
g.push(handle);
idx
}
2022-12-08 11:06:29 +00:00
fn mgr_handle(&self, idx: usize) -> Result<TorrentManagerHandle> {
2022-12-08 09:28:01 +00:00
self.torrent_managers
.read()
.get(idx)
.cloned()
2022-12-08 11:06:29 +00:00
.ok_or(ApiError::torrent_not_found(idx))
2021-07-08 00:09:00 +01:00
}
2021-07-08 23:03:58 +01:00
fn api_torrent_list(&self) -> TorrentListResponse {
TorrentListResponse {
torrents: self
.torrent_managers
.read()
.iter()
.enumerate()
.map(|(id, mgr)| TorrentListResponseItem {
id,
2021-07-13 09:18:45 +01:00
info_hash: mgr.torrent_state().info_hash().as_string(),
2021-07-08 23:03:58 +01:00
})
.collect(),
}
}
2022-12-08 11:06:29 +00:00
fn api_torrent_details(&self, idx: usize) -> Result<TorrentDetailsResponse> {
2021-07-08 23:49:25 +01:00
let handle = self.mgr_handle(idx)?;
2021-10-23 09:37:37 +01:00
let info_hash = handle.torrent_state().info_hash();
let only_files = handle.only_files();
2022-12-08 09:28:01 +00:00
make_torrent_details(&info_hash, handle.torrent_state().info(), only_files)
2021-07-08 23:49:25 +01:00
}
2023-11-20 13:55:42 +00:00
fn api_peer_stats(
&self,
idx: usize,
filter: PeerStatsFilter,
2023-11-20 14:05:38 +00:00
) -> Result<crate::peer_state::PeerStatsSnapshot> {
2023-11-20 13:55:42 +00:00
let handle = self.mgr_handle(idx)?;
Ok(handle.torrent_state().per_peer_stats_snapshot(filter))
}
2023-05-07 13:12:57 +02:00
pub async fn api_add_torrent(
&self,
add: AddTorrent<'_>,
opts: Option<AddTorrentOptions>,
2022-12-08 11:06:29 +00:00
) -> Result<ApiAddTorrentResponse> {
2021-10-23 09:37:37 +01:00
let response = match self
2021-10-10 09:57:21 +01:00
.session
.add_torrent(add, opts)
2021-10-10 09:57:21 +01:00
.await
2022-12-08 15:40:29 +00:00
.context("error adding torrent")
.with_error_status_code(StatusCode::BAD_REQUEST)?
2021-10-23 09:37:37 +01:00
{
2022-12-08 09:28:01 +00:00
AddTorrentResponse::AlreadyManaged(managed) => {
2022-12-08 15:40:29 +00:00
return Err(anyhow::anyhow!(
"{:?} is already managed, downloaded to {:?}",
managed.info_hash,
managed.output_folder
))
.with_error_status_code(StatusCode::CONFLICT);
2022-12-08 09:28:01 +00:00
}
2021-10-23 09:37:37 +01:00
AddTorrentResponse::ListOnly(ListOnlyResponse {
2021-10-25 16:46:30 +08:00
info_hash,
info,
only_files,
}) => ApiAddTorrentResponse {
2021-10-23 09:37:37 +01:00
id: None,
2022-12-08 09:28:01 +00:00
details: make_torrent_details(&info_hash, &info, only_files.as_deref())
.context("error making torrent details")?,
2021-10-23 09:37:37 +01:00
},
AddTorrentResponse::Added(handle) => {
let details = make_torrent_details(
&handle.torrent_state().info_hash(),
handle.torrent_state().info(),
handle.only_files(),
2022-12-08 09:28:01 +00:00
)
.context("error making torrent details")?;
2022-12-08 11:06:29 +00:00
let id = self.add_torrent_handle(handle);
2021-10-23 09:37:37 +01:00
ApiAddTorrentResponse {
id: Some(id),
details,
}
}
};
Ok(response)
2021-10-10 09:57:21 +01:00
}
2022-12-08 15:40:29 +00:00
fn api_dht_stats(&self) -> Result<DhtStats> {
self.dht
.as_ref()
.map(|d| d.stats())
.ok_or(ApiError::dht_disabled())
}
fn api_dht_table(&self) -> Result<impl Serialize> {
let dht = self.dht.as_ref().ok_or(ApiError::dht_disabled())?;
Ok(dht.with_routing_table(|r| r.clone()))
2021-07-14 13:40:56 +01:00
}
2022-12-08 11:06:29 +00:00
fn api_stats(&self, idx: usize) -> Result<StatsResponse> {
2021-07-08 23:03:58 +01:00
let mgr = self.mgr_handle(idx)?;
2023-11-20 01:19:24 +00:00
let snapshot = mgr.torrent_state().stats_snapshot();
2021-07-08 23:03:58 +01:00
let estimator = mgr.speed_estimator();
// Poor mans download speed computation
let elapsed = self.startup_time.elapsed();
let downloaded_bytes = snapshot.downloaded_and_checked_bytes;
let downloaded_mb = downloaded_bytes as f64 / 1024f64 / 1024f64;
2022-12-08 09:28:01 +00:00
Ok(StatsResponse {
2021-07-08 23:03:58 +01:00
average_piece_download_time: snapshot.average_piece_download_time(),
snapshot,
2021-10-25 18:11:46 +08:00
all_time_download_speed: (downloaded_mb / elapsed.as_secs_f64()).into(),
2021-07-08 23:03:58 +01:00
download_speed: estimator.download_mbps().into(),
time_remaining: estimator.time_remaining().map(DurationWithHumanReadable),
2021-07-08 23:03:58 +01:00
})
}
2022-12-08 11:06:29 +00:00
fn api_dump_haves(&self, idx: usize) -> Result<String> {
2021-07-08 23:03:58 +01:00
let mgr = self.mgr_handle(idx)?;
2022-12-08 09:28:01 +00:00
Ok(format!(
2021-07-08 23:03:58 +01:00
"{:?}",
2023-11-19 20:15:42 +00:00
mgr.torrent_state()
.lock_read("api_dump_haves")
.chunks
.get_have_pieces(),
2021-07-08 23:03:58 +01:00
))
}
2021-07-08 00:09:00 +01:00
}
2022-12-08 15:40:29 +00:00
fn make_torrent_details(
info_hash: &Id20,
info: &TorrentMetaV1Info<ByteString>,
only_files: Option<&[usize]>,
) -> Result<TorrentDetailsResponse> {
let files = info
.iter_filenames_and_lengths()
.context("error iterating filenames and lengths")?
.enumerate()
.map(|(idx, (filename_it, length))| {
let name = match filename_it.to_string() {
Ok(s) => s,
Err(err) => {
warn!("error reading filename: {:?}", err);
"<INVALID NAME>".to_string()
}
};
let included = only_files.map(|o| o.contains(&idx)).unwrap_or(true);
TorrentDetailsResponseFile {
name,
length,
included,
}
})
.collect();
Ok(TorrentDetailsResponse {
info_hash: info_hash.as_string(),
files,
})
2021-06-30 10:14:33 +01:00
}