rqbit/crates/librqbit/src/http_api.rs

66 lines
2.2 KiB
Rust
Raw Normal View History

2021-06-30 10:14:33 +01:00
use std::sync::Arc;
2021-07-03 19:10:59 +01:00
use librqbit_core::speed_estimator::SpeedEstimator;
2021-06-30 10:31:30 +01:00
use std::io::Write;
2021-06-30 18:42:16 +01:00
use std::time::Instant;
2021-06-30 10:14:33 +01:00
use warp::Filter;
use crate::torrent_state::TorrentState;
2021-07-04 14:38:44 +01:00
// This is just a stub for debugging.
// A real http api would know about ALL torrents we are downloading, not just one.
2021-06-30 23:26:22 +01:00
pub async fn make_and_run_http_api(
state: Arc<TorrentState>,
estimator: Arc<SpeedEstimator>,
) -> anyhow::Result<()> {
2021-06-30 10:31:30 +01:00
let dump_haves = warp::path("haves").map({
let state = state.clone();
2021-07-04 14:38:44 +01:00
move || format!("{:?}", state.lock_read().chunks.get_have_pieces())
2021-06-30 10:31:30 +01:00
});
let dump_stats = warp::path("stats").map({
let state = state.clone();
let start_time = Instant::now();
2021-07-04 11:36:16 +01:00
let initial_downloaded_and_checked = state.stats_snapshot().downloaded_and_checked_bytes;
2021-06-30 10:31:30 +01:00
move || {
2021-07-04 11:36:16 +01:00
let snapshot = state.stats_snapshot();
2021-06-30 10:31:30 +01:00
let mut buf = Vec::new();
2021-06-30 23:26:22 +01:00
writeln!(buf, "{:#?}", state.stats_snapshot()).unwrap();
2021-06-30 10:31:30 +01:00
writeln!(
buf,
"Average download time: {:?}",
2021-07-04 11:36:16 +01:00
snapshot.average_piece_download_time()
2021-06-30 10:31:30 +01:00
)
.unwrap();
// Poor mans download speed computation
let elapsed = start_time.elapsed();
2021-07-04 11:36:16 +01:00
let downloaded_bytes =
snapshot.downloaded_and_checked_bytes - initial_downloaded_and_checked;
2021-06-30 10:31:30 +01:00
let downloaded_mb = downloaded_bytes as f64 / 1024f64 / 1024f64;
writeln!(
buf,
2021-06-30 23:26:22 +01:00
"Total download speed over all time: {:.2}Mbps",
2021-06-30 10:31:30 +01:00
downloaded_mb / elapsed.as_secs_f64()
)
.unwrap();
2021-06-30 23:26:22 +01:00
writeln!(buf, "Download speed: {:.2}Mbps", estimator.download_mbps()).unwrap();
match estimator.time_remaining() {
Some(time) => {
writeln!(buf, "Time remaining: {:?}", time).unwrap();
}
None => {
writeln!(buf, "Time remaining: unknown").unwrap();
}
}
2021-06-30 10:31:30 +01:00
buf
}
});
let router = dump_haves.or(dump_stats);
warp::serve(router).run(([127, 0, 0, 1], 3030)).await;
2021-06-30 10:14:33 +01:00
Ok(())
}