rqbit/crates/librqbit/src/http_api.rs

619 lines
20 KiB
Rust
Raw Normal View History

2023-11-24 14:08:02 +00: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;
2023-11-24 14:19:39 +00:00
use axum::routing::{get, post};
2021-10-23 09:37:37 +01:00
use buffers::ByteString;
2023-11-24 14:29:05 +00:00
use 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;
use serde::{Deserialize, Serialize};
2021-10-10 09:57:21 +01:00
use std::net::SocketAddr;
use std::str::FromStr;
2021-10-10 09:57:21 +01:00
use std::sync::Arc;
2023-11-30 16:05:48 +00:00
use std::time::Duration;
use tokio::sync::mpsc::UnboundedSender;
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-30 16:05:48 +00:00
use crate::peer_connection::PeerConnectionOptions;
use crate::session::{
2023-11-24 14:08:02 +00:00
AddTorrent, AddTorrentOptions, AddTorrentResponse, ListOnlyResponse, Session, TorrentId,
2023-12-01 11:28:35 +00:00
SUPPORTED_SCHEMES,
};
use crate::torrent_state::peer::stats::snapshot::{PeerStatsFilter, PeerStatsSnapshot};
2023-11-25 10:11:40 +00:00
use crate::torrent_state::stats::{LiveStats, TorrentStats};
use crate::torrent_state::ManagedTorrentHandle;
2021-07-08 23:03:58 +01:00
2022-12-08 15:40:29 +00:00
// Public API
#[derive(Clone)]
pub struct HttpApi {
2023-12-01 18:08:41 +00:00
inner: Arc<Api>,
2022-12-08 09:28:01 +00:00
}
2022-12-08 15:40:29 +00:00
impl HttpApi {
pub fn new(session: Arc<Session>, rust_log_reload_tx: Option<UnboundedSender<String>>) -> Self {
2022-12-08 09:28:01 +00:00
Self {
2023-12-01 18:08:41 +00:00
inner: Arc::new(Api::new(session, rust_log_reload_tx)),
2022-12-08 09:28:01 +00:00
}
}
2022-12-08 11:06:29 +00:00
2023-11-25 11:21:45 +00:00
pub async fn make_http_api_and_run(
self,
addr: SocketAddr,
read_only: bool,
) -> anyhow::Result<()> {
2022-12-08 15:40:29 +00:00
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/v1": "Torrent stats",
2023-11-20 13:55:42 +00:00
"GET /torrents/{index}/peer_stats": "Per peer stats",
"POST /torrents/{index}/pause": "Pause torrent",
"POST /torrents/{index}/start": "Resume torrent",
"POST /torrents/{index}/forget": "Forget about the torrent, keep the files",
"POST /torrents/{index}/delete": "Forget about the torrent, remove the files",
2023-11-21 12:56:07 +00:00
"POST /torrents": "Add a torrent here. magnet: or http:// or a local file.",
"POST /rust_log": "Set RUST_LOG to this post launch (for debugging)",
2023-11-21 12:56:07 +00:00
"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> {
2023-12-01 11:28:35 +00:00
let is_url = params.is_url;
let opts = params.into_add_torrent_options();
2023-12-01 11:28:35 +00:00
let data = data.to_vec();
let add = match is_url {
Some(true) => AddTorrent::Url(
String::from_utf8(data)
.context("invalid utf-8 for passed URL")?
.into(),
),
Some(false) => AddTorrent::TorrentFileBytes(data.into()),
// Guess the format.
None if SUPPORTED_SCHEMES
.iter()
.any(|s| data.starts_with(s.as_bytes())) =>
{
AddTorrent::Url(
String::from_utf8(data)
.context("invalid utf-8 for passed URL")?
.into(),
)
}
_ => AddTorrent::TorrentFileBytes(data.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)
}
2023-11-24 15:04:36 +00:00
async fn torrent_stats_v0(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
2023-11-24 15:04:36 +00:00
state.api_stats_v0(idx).map(axum::Json)
}
async fn torrent_stats_v1(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_stats_v1(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-24 14:19:39 +00:00
async fn torrent_action_pause(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
2023-11-24 18:28:46 +00:00
state.api_torrent_action_pause(idx).map(axum::Json)
2023-11-24 14:19:39 +00:00
}
async fn torrent_action_start(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
2023-11-24 18:28:46 +00:00
state.api_torrent_action_start(idx).map(axum::Json)
}
async fn torrent_action_forget(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_torrent_action_forget(idx).map(axum::Json)
}
async fn torrent_action_delete(
State(state): State<ApiState>,
Path(idx): Path<usize>,
) -> Result<impl IntoResponse> {
state.api_torrent_action_delete(idx).map(axum::Json)
2023-11-24 14:19:39 +00:00
}
async fn set_rust_log(
State(state): State<ApiState>,
new_value: String,
) -> Result<impl IntoResponse> {
state.api_set_rust_log(new_value).map(axum::Json)
}
2023-11-20 20:15:40 +00:00
let mut app = Router::new()
.route("/", get(api_root))
2023-11-25 11:21:45 +00:00
.route("/rust_log", post(set_rust_log))
.route("/dht/stats", get(dht_stats))
.route("/dht/table", get(dht_table))
2023-11-25 11:21:45 +00:00
.route("/torrents", get(torrents_list))
.route("/torrents/:id", get(torrent_details))
.route("/torrents/:id/haves", get(torrent_haves))
2023-11-24 15:04:36 +00:00
.route("/torrents/:id/stats", get(torrent_stats_v0))
.route("/torrents/:id/stats/v1", get(torrent_stats_v1))
2023-11-25 11:21:45 +00:00
.route("/torrents/:id/peer_stats", get(peer_stats));
if !read_only {
app = app
.route("/torrents", post(torrents_post))
.route("/torrents/:id/pause", post(torrent_action_pause))
.route("/torrents/:id/start", post(torrent_action_start))
.route("/torrents/:id/forget", post(torrent_action_forget))
.route("/torrents/:id/delete", post(torrent_action_delete));
}
2023-11-20 20:15:40 +00:00
#[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(
2023-11-27 17:21:45 +00:00
"/assets/index.js",
2023-11-20 20:15:40 +00:00
get(|| async {
(
[("Content-Type", "application/javascript")],
2023-11-27 17:21:45 +00:00
include_str!("../webui/dist/assets/index.js"),
)
}),
)
.route(
"/assets/logo.svg",
get(|| async {
(
[("Content-Type", "image/svg+xml")],
include_str!("../webui/dist/assets/logo.svg"),
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);
use tokio::net::TcpListener;
let listener = TcpListener::bind(&addr)
.await
.with_context(|| format!("error binding to {addr}"))?;
axum::serve(listener, app).await?;
2022-12-08 15:40:29 +00:00
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)]
2023-12-01 18:08:41 +00:00
pub struct TorrentListResponseItem {
pub id: usize,
pub info_hash: String,
2021-07-08 23:03:58 +01:00
}
#[derive(Serialize)]
2023-12-01 18:08:41 +00:00
pub struct TorrentListResponse {
pub torrents: Vec<TorrentListResponseItem>,
2021-07-08 23:03:58 +01:00
}
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
}
2023-11-24 18:28:46 +00:00
#[derive(Default, Serialize)]
2023-12-01 18:08:41 +00:00
pub struct EmptyJsonResponse {}
2023-11-24 18:28:46 +00: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
}
2021-10-23 09:37:37 +01:00
#[derive(Serialize, Deserialize)]
pub struct ApiAddTorrentResponse {
pub id: Option<usize>,
pub details: TorrentDetailsResponse,
pub seen_peers: Option<Vec<SocketAddr>>,
2021-10-23 09:37:37 +01:00
}
2023-11-22 17:19:35 +00:00
pub struct OnlyFiles(Vec<usize>);
pub struct InitialPeers(pub Vec<SocketAddr>);
#[derive(Serialize, Deserialize, Default)]
pub struct TorrentAddQueryParams {
pub overwrite: Option<bool>,
pub output_folder: Option<String>,
pub sub_folder: Option<String>,
pub only_files_regex: Option<String>,
pub only_files: Option<OnlyFiles>,
pub peer_connect_timeout: Option<u64>,
pub peer_read_write_timeout: Option<u64>,
pub initial_peers: Option<InitialPeers>,
// Will force interpreting the content as a URL.
pub is_url: Option<bool>,
pub list_only: Option<bool>,
}
2023-11-22 17:19:35 +00:00
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
}
}
impl<'de> Deserialize<'de> for InitialPeers {
fn deserialize<D>(deserializer: D) -> std::prelude::v1::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
let string = String::deserialize(deserializer)?;
let mut addrs = Vec::new();
2023-12-01 10:28:20 +00:00
for addr_str in string.split(',').filter(|s| !s.is_empty()) {
addrs.push(SocketAddr::from_str(addr_str).map_err(D::Error::custom)?);
}
Ok(InitialPeers(addrs))
}
}
impl Serialize for InitialPeers {
fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0
.iter()
.map(|s| s.to_string())
.join(",")
.serialize(serializer)
}
}
2022-12-08 15:40:29 +00:00
impl TorrentAddQueryParams {
pub fn into_add_torrent_options(self) -> AddTorrentOptions {
2022-12-08 15:40:29 +00:00
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),
initial_peers: self.initial_peers.map(|i| i.0),
2023-11-30 16:05:48 +00:00
peer_opts: Some(PeerConnectionOptions {
connect_timeout: self.peer_connect_timeout.map(Duration::from_secs),
read_write_timeout: self.peer_read_write_timeout.map(Duration::from_secs),
..Default::default()
}),
2022-12-08 15:40:29 +00:00
..Default::default()
}
}
}
// Private HTTP API internals. Agnostic of web framework.
2023-12-01 18:08:41 +00:00
pub struct Api {
2022-12-08 15:40:29 +00:00
session: Arc<Session>,
rust_log_reload_tx: Option<UnboundedSender<String>>,
2022-12-08 15:40:29 +00:00
}
2023-12-01 18:08:41 +00:00
type ApiState = Arc<Api>;
2022-12-08 15:40:29 +00:00
2023-12-01 18:08:41 +00:00
impl Api {
pub fn new(session: Arc<Session>, rust_log_reload_tx: Option<UnboundedSender<String>>) -> Self {
2022-12-08 15:40:29 +00:00
Self {
session,
rust_log_reload_tx,
2022-12-08 15:40:29 +00:00
}
}
2023-12-01 18:08:41 +00:00
pub fn mgr_handle(&self, idx: TorrentId) -> Result<ManagedTorrentHandle> {
2023-11-24 14:08:02 +00:00
self.session
2022-12-08 09:28:01 +00:00
.get(idx)
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
2023-12-01 18:08:41 +00:00
pub fn api_torrent_list(&self) -> TorrentListResponse {
2023-11-24 14:08:02 +00:00
let items = self.session.with_torrents(|torrents| {
torrents
2021-07-08 23:03:58 +01:00
.map(|(id, mgr)| TorrentListResponseItem {
id,
info_hash: mgr.info().info_hash.as_string(),
2021-07-08 23:03:58 +01:00
})
2023-11-24 14:08:02 +00:00
.collect()
});
TorrentListResponse { torrents: items }
2021-07-08 23:03:58 +01:00
}
2023-12-01 18:08:41 +00:00
pub fn api_torrent_details(&self, idx: TorrentId) -> Result<TorrentDetailsResponse> {
2021-07-08 23:49:25 +01:00
let handle = self.mgr_handle(idx)?;
let info_hash = handle.info().info_hash;
2021-10-23 09:37:37 +01:00
let only_files = handle.only_files();
make_torrent_details(&info_hash, &handle.info().info, only_files.as_deref())
2021-07-08 23:49:25 +01:00
}
2023-12-01 18:08:41 +00:00
pub fn api_peer_stats(
&self,
idx: TorrentId,
filter: PeerStatsFilter,
) -> Result<PeerStatsSnapshot> {
2023-11-20 13:55:42 +00:00
let handle = self.mgr_handle(idx)?;
Ok(handle
.live()
.context("not live")?
.per_peer_stats_snapshot(filter))
2023-11-20 13:55:42 +00:00
}
2023-12-01 18:08:41 +00:00
pub fn api_torrent_action_pause(&self, idx: TorrentId) -> Result<EmptyJsonResponse> {
2023-11-24 14:19:39 +00:00
let handle = self.mgr_handle(idx)?;
handle
.pause()
.context("error pausing torrent")
2023-11-24 18:28:46 +00:00
.with_error_status_code(StatusCode::BAD_REQUEST)?;
Ok(Default::default())
2023-11-24 14:19:39 +00:00
}
2023-12-01 18:08:41 +00:00
pub fn api_torrent_action_start(&self, idx: TorrentId) -> Result<EmptyJsonResponse> {
2023-11-24 14:19:39 +00:00
let handle = self.mgr_handle(idx)?;
self.session
.unpause(&handle)
.context("error unpausing torrent")
2023-11-24 18:28:46 +00:00
.with_error_status_code(StatusCode::BAD_REQUEST)?;
Ok(Default::default())
}
2023-12-01 18:08:41 +00:00
pub fn api_torrent_action_forget(&self, idx: TorrentId) -> Result<EmptyJsonResponse> {
2023-11-25 00:24:32 +00:00
self.session
.delete(idx, false)
.context("error forgetting torrent")?;
2023-11-24 21:45:38 +00:00
Ok(Default::default())
2023-11-24 18:28:46 +00:00
}
2023-12-01 18:08:41 +00:00
pub fn api_torrent_action_delete(&self, idx: TorrentId) -> Result<EmptyJsonResponse> {
2023-11-25 00:24:32 +00:00
self.session
.delete(idx, true)
.context("error deleting torrent with files")?;
2023-11-24 21:45:38 +00:00
Ok(Default::default())
2023-11-24 14:19:39 +00:00
}
2023-12-01 18:08:41 +00:00
pub fn api_set_rust_log(&self, new_value: String) -> Result<EmptyJsonResponse> {
let tx = self
.rust_log_reload_tx
.as_ref()
.context("rust_log_reload_tx was not set")?;
tx.send(new_value)
.context("noone is listening to RUST_LOG changes")?;
Ok(Default::default())
}
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
{
2023-11-24 14:08:02 +00:00
AddTorrentResponse::AlreadyManaged(id, managed) => {
2022-12-08 15:40:29 +00:00
return Err(anyhow::anyhow!(
2023-11-24 14:08:02 +00:00
"{:?} is already managed, id={}, downloaded to {:?}",
managed.info_hash(),
2023-11-24 14:08:02 +00:00
id,
&managed.info().out_dir
2022-12-08 15:40:29 +00:00
))
.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,
seen_peers,
2021-10-25 16:46:30 +08:00
}) => ApiAddTorrentResponse {
2021-10-23 09:37:37 +01:00
id: None,
seen_peers: Some(seen_peers),
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
},
2023-11-24 14:08:02 +00:00
AddTorrentResponse::Added(id, handle) => {
2021-10-23 09:37:37 +01:00
let details = make_torrent_details(
&handle.info_hash(),
&handle.info().info,
handle.only_files().as_deref(),
2022-12-08 09:28:01 +00:00
)
.context("error making torrent details")?;
2021-10-23 09:37:37 +01:00
ApiAddTorrentResponse {
id: Some(id),
details,
seen_peers: None,
2021-10-23 09:37:37 +01:00
}
}
};
Ok(response)
2021-10-10 09:57:21 +01:00
}
2023-12-01 18:08:41 +00:00
pub fn api_dht_stats(&self) -> Result<DhtStats> {
2023-11-24 14:08:02 +00:00
self.session
.get_dht()
2022-12-08 15:40:29 +00:00
.as_ref()
.map(|d| d.stats())
.ok_or(ApiError::dht_disabled())
}
2023-12-01 18:08:41 +00:00
pub fn api_dht_table(&self) -> Result<impl Serialize> {
2023-11-24 14:08:02 +00:00
let dht = self.session.get_dht().ok_or(ApiError::dht_disabled())?;
2022-12-08 15:40:29 +00:00
Ok(dht.with_routing_table(|r| r.clone()))
2021-07-14 13:40:56 +01:00
}
2023-12-01 18:08:41 +00:00
pub fn api_stats_v0(&self, idx: TorrentId) -> Result<LiveStats> {
2023-11-24 15:04:36 +00:00
let mgr = self.mgr_handle(idx)?;
let live = mgr.live().context("torrent not live")?;
2023-11-25 10:11:40 +00:00
Ok(LiveStats::from(&*live))
2023-11-24 15:04:36 +00:00
}
2023-12-01 18:08:41 +00:00
pub fn api_stats_v1(&self, idx: TorrentId) -> Result<TorrentStats> {
2023-11-24 15:04:36 +00:00
let mgr = self.mgr_handle(idx)?;
2023-11-25 10:11:40 +00:00
Ok(mgr.stats())
2021-07-08 23:03:58 +01:00
}
2023-12-01 18:08:41 +00:00
pub fn api_dump_haves(&self, idx: usize) -> Result<String> {
2023-11-24 14:29:05 +00:00
let mgr = self.mgr_handle(idx)?;
Ok(mgr.with_chunk_tracker(|chunks| format!("{:?}", 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
}