use crate::prelude::*;
use flat_db::Hash;
use lava_torrent::torrent::v1::Torrent;
use qbittorrent_api::get_torrents::Torrent as QbitTorrent;
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize, Default)]
pub(crate) struct QueueItem {
pub name: String,
pub path: PathBuf,
pub hash: Hash<20>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub indexer: Option<Indexer>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub verify: Option<VerifyStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub spectrogram: Option<SpectrogramStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transcode: Option<TranscodeStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub upload: Option<UploadStatus>,
}
impl QueueItem {
#[must_use]
pub(crate) fn from_torrent(path: PathBuf, torrent: &Torrent) -> Self {
let comment = torrent.comment().unwrap_or_default();
let id = get_torrent_id_from_torrent_url(comment);
let info_hash = torrent.info_hash();
let indexer = torrent
.source()
.filter(|source| !source.is_empty())
.map(Indexer::from);
Self {
name: torrent.name.clone(),
path,
hash: Hash::from_string(&info_hash).expect("torrent hash should be valid"),
indexer,
id,
..Self::default()
}
}
#[must_use]
pub(crate) fn from_qbit_torrent(torrent: &QbitTorrent) -> Option<Self> {
let hash_string = torrent
.infohash_v1
.as_deref()
.filter(|h| !h.is_empty())
.unwrap_or(&torrent.hash);
let hash = match Hash::from_string(hash_string) {
Ok(hash) => hash,
Err(error) => {
warn!(
"{} torrent {}: invalid hash {}: {error}",
"Skipping".bold(),
torrent.name,
hash_string
);
return None;
}
};
let comment = torrent.comment.as_deref().unwrap_or_default();
let id = get_torrent_id_from_url(comment).ok();
let indexer = get_indexer_from_url(comment);
Some(Self {
name: torrent.name.clone(),
hash,
indexer,
id,
..Self::default()
})
}
}
impl Display for QueueItem {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
write!(formatter, "{}", self.name)
}
}