rqbit/crates/dht/examples/dht.rs

65 lines
1.8 KiB
Rust
Raw Normal View History

2023-11-22 21:56:00 +00:00
use std::time::Duration;
2021-07-10 23:56:42 +01:00
2021-07-12 19:42:48 +01:00
use anyhow::Context;
2023-11-22 21:56:00 +00:00
use librqbit_core::magnet::Magnet;
2023-11-28 11:35:28 +00:00
use librqbit_dht::DhtBuilder;
2021-07-12 19:42:48 +01:00
use tokio_stream::StreamExt;
2023-11-19 12:50:11 +00:00
use tracing::info;
2021-07-10 23:56:42 +01:00
2021-07-12 11:56:26 +01:00
#[tokio::main]
async fn main() -> anyhow::Result<()> {
2023-11-22 21:56:00 +00:00
let magnet = std::env::args()
.nth(1)
.expect("first argument should be a magnet link");
let magnet = Magnet::parse(&magnet).unwrap();
2023-12-24 16:53:02 -06:00
let info_hash = magnet.as_id20().context("Supplied magnet link didn't contain a BTv1 infohash")?;
2023-11-22 21:56:00 +00:00
2023-11-19 22:48:19 +00:00
tracing_subscriber::fmt::init();
let dht = DhtBuilder::new().await.context("error initializing DHT")?;
2023-12-05 23:31:04 +00:00
let mut stream = dht.get_peers(info_hash, None)?;
2021-07-14 00:48:53 +01:00
2021-07-14 01:03:39 +01:00
let stats_printer = async {
2021-07-14 00:48:53 +01:00
loop {
tokio::time::sleep(Duration::from_secs(5)).await;
info!("DHT stats: {:?}", dht.stats());
}
2021-07-14 15:29:59 +01:00
#[allow(unreachable_code)]
2021-07-14 00:48:53 +01:00
Ok::<_, anyhow::Error>(())
};
2021-07-14 01:03:39 +01:00
let routing_table_dumper = async {
loop {
tokio::time::sleep(Duration::from_secs(15)).await;
dht.with_routing_table(|r| {
let filename = "/tmp/routing-table.json";
let mut f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
2021-07-14 01:03:39 +01:00
.open(filename)
.unwrap();
serde_json::to_writer_pretty(&mut f, r).unwrap();
info!("Dumped DHT routing table to {}", filename);
});
}
2021-07-14 15:29:59 +01:00
#[allow(unreachable_code)]
2021-07-14 01:03:39 +01:00
Ok::<_, anyhow::Error>(())
};
let peer_printer = async {
2021-07-14 00:48:53 +01:00
while let Some(peer) = stream.next().await {
2023-11-19 12:50:11 +00:00
info!("peer found: {}", peer)
2021-07-12 19:42:48 +01:00
}
2021-07-14 00:48:53 +01:00
Ok(())
};
let res = tokio::select! {
res = stats_printer => res,
res = peer_printer => res,
2021-07-14 01:03:39 +01:00
res = routing_table_dumper => res,
2021-07-14 00:48:53 +01:00
};
res
2021-07-10 23:56:42 +01:00
}