use std::collections::HashMap;
use aria2_protocol::bittorrent::message::extension::ExtensionHandshake;
use tracing::{debug, trace, warn};
use super::{
DEFAULT_LOCAL_UT_METADATA_ID, DEFAULT_LOCAL_UT_PEX_ID, DEFAULT_REQQ, ExtensionRegistry,
};
impl ExtensionRegistry {
pub fn new() -> Self {
Self {
local_ut_metadata_id: DEFAULT_LOCAL_UT_METADATA_ID,
local_ut_pex_id: DEFAULT_LOCAL_UT_PEX_ID,
peer_id_to_name: HashMap::new(),
reqq: DEFAULT_REQQ,
}
}
pub fn update_from_peer_handshake(&mut self, handshake: &ExtensionHandshake) {
self.peer_id_to_name.clear();
for (name, value) in handshake.m_dict() {
if let Some(ext_id) = value.as_int().and_then(|i| u8::try_from(i).ok()) {
if ext_id == 0 {
warn!(
"Peer assigned ext_id=0 to extension {:?}, ignoring",
String::from_utf8_lossy(name)
);
continue;
}
trace!(
"Peer extension: {:?} -> ext_id={}",
String::from_utf8_lossy(name),
ext_id
);
self.peer_id_to_name
.insert(ext_id, name.clone().into_boxed_slice());
}
}
self.reqq = handshake.reqq();
debug!(
"Updated extension registry from peer handshake: ut_metadata={:?}, ut_pex={:?}, reqq={}",
self.peer_ut_metadata_id(),
self.peer_ut_pex_id(),
self.reqq
);
}
pub fn build_local_handshake(&self) -> ExtensionHandshake {
let mut hs = ExtensionHandshake::new();
hs.with_ut_metadata(self.local_ut_metadata_id());
hs.with_ut_pex(self.local_ut_pex_id());
hs.with_reqq(self.reqq);
hs
}
}