69 lines
2.4 KiB
Rust
69 lines
2.4 KiB
Rust
use imdl::infohash::Infohash;
|
|
use imdl::input::Input;
|
|
use imdl::input_target::InputTarget;
|
|
use imdl::magnet_link::MagnetLink;
|
|
use imdl::metainfo::Metainfo;
|
|
use imdl::torrent_summary::TorrentSummary;
|
|
|
|
use std::path::Path;
|
|
|
|
/// Helper method for imdl functions which expect an imdl::Input type
|
|
pub fn input_path<T: AsRef<Path>>(path: T) -> Result<Input, std::io::Error> {
|
|
let path = path.as_ref();
|
|
let absolute = path.canonicalize()?;
|
|
let data = std::fs::read(absolute)?;
|
|
Ok(Input::new(
|
|
InputTarget::Path(path.to_path_buf()),
|
|
data
|
|
))
|
|
}
|
|
|
|
/// Extracts the infohash of a magnet link
|
|
pub fn magnet_hash<T: AsRef<str>>(magnet: T) -> String {
|
|
let magnet = MagnetLink::parse(magnet.as_ref()).expect("Parsing magnet failed");
|
|
//Ok(magnet.name.expect("Magnet link has no name!"))
|
|
//Ok(String::from_utf8_lossy(&magnet.infohash.inner.bytes).to_string())
|
|
let bytes = magnet.infohash.inner.bytes.clone();
|
|
let mut s = String::new();
|
|
for byte in bytes {
|
|
s.push_str(&format!("{:02x}", byte));
|
|
}
|
|
s
|
|
}
|
|
|
|
/// Extracts the name of a magnet link
|
|
pub fn magnet_name<T: AsRef<str>>(magnet: T) -> String {
|
|
let magnet = MagnetLink::parse(magnet.as_ref()).expect("Parsing magnet failed");
|
|
magnet.name.expect("Magnet link has no name!")
|
|
}
|
|
|
|
/// Extracts the infohash of a torrent file
|
|
pub fn torrent_hash<T: AsRef<Path>>(torrent: T) -> String {
|
|
let input = input_path(torrent).unwrap();
|
|
TorrentSummary::from_input(&input).expect("Parsing torrent file failed").torrent_summary_data().info_hash
|
|
}
|
|
|
|
/// Extracts the name of a torrent file
|
|
pub fn torrent_name<T: AsRef<Path>>(torrent: T) -> String {
|
|
let input = input_path(torrent).unwrap();
|
|
TorrentSummary::from_input(&input).expect("Parsing torrent file failed").torrent_summary_data().name
|
|
}
|
|
|
|
/// Turns a torrent file into a magnet link
|
|
pub fn torrent_to_magnet<T: AsRef<Path>>(torrent: T) -> String {
|
|
let input = input_path(torrent).expect("Failed to read torrent file");
|
|
let infohash = Infohash::from_input(&input).expect("Failed to parse infohash");
|
|
let metainfo = Metainfo::from_input(&input).expect("Failed to parse meta info");
|
|
|
|
let mut link = MagnetLink::with_infohash(infohash);
|
|
|
|
link.set_name(&metainfo.info.name);
|
|
|
|
for result in metainfo.trackers() {
|
|
link.add_tracker(result.expect("failed tracker in metainfo"));
|
|
}
|
|
|
|
link.to_url().to_string()
|
|
|
|
}
|