Compare commits

...

3 Commits

Author SHA1 Message Date
a3609696c7 feat: finsih qbit adapter 2025-04-05 14:24:47 +08:00
b0c12acbc6 fix: fix paths 2025-04-05 10:40:48 +08:00
3dfcf2a536 fix: add testing-torrents params 2025-04-05 09:20:51 +08:00
12 changed files with 2673 additions and 1734 deletions

View File

@ -23,8 +23,7 @@ where
&self,
selector: Self::Selector,
) -> Result<Self::IdSelector, DownloaderError> {
let hashes =
<Self as TorrentDownloaderTrait>::query_torrent_hashes(&self, selector).await?;
let hashes = <Self as TorrentDownloaderTrait>::query_torrent_hashes(self, selector).await?;
self.pause_torrents(hashes).await
}
@ -32,16 +31,14 @@ where
&self,
selector: Self::Selector,
) -> Result<Self::IdSelector, DownloaderError> {
let hashes =
<Self as TorrentDownloaderTrait>::query_torrent_hashes(&self, selector).await?;
let hashes = <Self as TorrentDownloaderTrait>::query_torrent_hashes(self, selector).await?;
self.resume_torrents(hashes).await
}
async fn remove_downloads(
&self,
selector: Self::Selector,
) -> Result<Self::IdSelector, DownloaderError> {
let hashes =
<Self as TorrentDownloaderTrait>::query_torrent_hashes(&self, selector).await?;
let hashes = <Self as TorrentDownloaderTrait>::query_torrent_hashes(self, selector).await?;
self.remove_torrents(hashes).await
}

View File

@ -131,7 +131,7 @@ impl TorrentFileSource {
.boxed()
.and_then(|s| {
s.path_segments()
.and_then(|p| p.last())
.and_then(|mut p| p.next_back())
.map(String::from)
.ok_or_else(|| anyhow::anyhow!("invalid url"))
.to_dyn_boxed()

View File

@ -2,7 +2,6 @@ use std::{
borrow::Cow,
collections::{HashMap, HashSet},
fmt::Debug,
io,
sync::{Arc, Weak},
time::Duration,
};
@ -167,6 +166,7 @@ impl TorrentTaskTrait for QBittorrentTask {
.as_deref()
.unwrap_or("")
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(Cow::Borrowed)
}
@ -209,6 +209,7 @@ pub struct QBittorrentDownloaderCreation {
pub save_path: String,
pub subscriber_id: i32,
pub downloader_id: i32,
pub wait_sync_timeout: Option<Duration>,
}
pub type QBittorrentHashSelector = DownloadIdSelector<QBittorrentTask>;
@ -354,7 +355,9 @@ impl QBittorrentDownloader {
endpoint_url,
subscriber_id: creation.subscriber_id,
save_path: creation.save_path.into(),
wait_sync_timeout: Duration::from_millis(10000),
wait_sync_timeout: creation
.wait_sync_timeout
.unwrap_or(Duration::from_secs(10)),
downloader_id: creation.downloader_id,
sync_watch: watch::channel(Utc::now()).0,
sync_data: Arc::new(RwLock::new(QBittorrentSyncData::default())),
@ -430,8 +433,12 @@ impl QBittorrentDownloader {
category: &str,
) -> Result<(), DownloaderError> {
{
let sync_data = self.sync_data.read().await;
if !sync_data.categories.contains_key(category) {
let category_no_exists = {
let sync_data = self.sync_data.read().await;
!sync_data.categories.contains_key(category)
};
if category_no_exists {
self.add_category(category).await?;
}
}
@ -492,49 +499,6 @@ impl QBittorrentDownloader {
Ok(())
}
#[instrument(level = "debug", skip(self, replacer))]
pub async fn move_torrent_contents<F: FnOnce(String) -> String>(
&self,
hash: &str,
replacer: F,
) -> Result<(), DownloaderError> {
let old_path = {
let sync_data = self.sync_data.read().await;
sync_data
.torrents
.get(hash)
.and_then(|t| t.content_path.as_deref())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"no torrent or torrent does not contain content path",
)
})?
.to_string()
};
let new_path = replacer(old_path.clone());
self.client
.rename_file(hash, old_path.clone(), new_path.to_string())
.await?;
self.wait_sync_until(
|sync_data| {
let torrents = &sync_data.torrents;
torrents.get(hash).is_some_and(|t| {
t.content_path.as_deref().is_some_and(|p| {
path_equals_as_file_url(p, &new_path)
.inspect_err(|error| {
tracing::warn!(name = "path_equals_as_file_url", error = ?error);
})
.unwrap_or(false)
})
})
},
None,
)
.await?;
Ok(())
}
#[instrument(level = "debug", skip(self))]
pub async fn move_torrents(
&self,
@ -584,6 +548,7 @@ impl QBittorrentDownloader {
Ok(torrent.save_path.take())
}
#[instrument(level = "debug", skip(self))]
async fn sync_data(&self) -> Result<(), DownloaderError> {
let rid = { self.sync_data.read().await.rid };
let sync_data_patch = self.client.sync(Some(rid)).await?;
@ -604,17 +569,23 @@ impl QBittorrentDownloader {
where
S: Fn(&QBittorrentSyncData) -> bool,
{
{
let sync_data = &self.sync_data.read().await;
if stop_wait_fn(sync_data) {
return Ok(());
}
}
let timeout = timeout.unwrap_or(self.wait_sync_timeout);
let start_time = Utc::now();
let mut receiver = self.sync_watch.subscribe();
while let Ok(()) = receiver.changed().await {
let has_timeout = {
let sync_time = receiver.borrow().clone();
sync_time
.signed_duration_since(start_time)
.num_milliseconds()
> timeout.as_millis() as i64
let sync_time = *receiver.borrow();
let diff_time = sync_time - start_time;
diff_time.num_milliseconds() > timeout.as_millis() as i64
};
if has_timeout {
tracing::warn!(name = "wait_until timeout", timeout = ?timeout);
@ -625,7 +596,7 @@ impl QBittorrentDownloader {
}
{
let sync_data = &self.sync_data.read().await;
if stop_wait_fn(&sync_data) {
if stop_wait_fn(sync_data) {
break;
}
}
@ -646,7 +617,7 @@ impl DownloaderTrait for QBittorrentDownloader {
&self,
creation: Self::Creation,
) -> Result<HashSet<Self::Id>, DownloaderError> {
let tag = {
let tags = {
let mut tags = vec![TORRENT_TAG_NAME.to_string()];
tags.extend(creation.tags);
Some(tags.into_iter().filter(|s| !s.is_empty()).join(","))
@ -655,7 +626,7 @@ impl DownloaderTrait for QBittorrentDownloader {
let save_path = Some(creation.save_path.into_string());
let sources = creation.sources;
let ids = HashSet::from_iter(sources.iter().map(|s| s.hash_info().to_string()));
let hashes = HashSet::from_iter(sources.iter().map(|s| s.hash_info().to_string()));
let (urls_source, files_source) = {
let mut urls = vec![];
let mut files = vec![];
@ -688,7 +659,20 @@ impl DownloaderTrait for QBittorrentDownloader {
)
};
let category = TORRENT_TAG_NAME.to_string();
let category = creation.category;
if let Some(category) = category.as_deref() {
let has_caetgory = {
self.sync_data
.read()
.await
.categories
.contains_key(category)
};
if !has_caetgory {
self.add_category(category).await?;
}
}
if let Some(source) = urls_source {
self.client
@ -696,8 +680,8 @@ impl DownloaderTrait for QBittorrentDownloader {
source,
savepath: save_path.clone(),
auto_torrent_management: Some(false),
category: Some(category.clone()),
tags: tag.clone(),
category: category.clone(),
tags: tags.clone(),
..Default::default()
})
.await?;
@ -707,10 +691,10 @@ impl DownloaderTrait for QBittorrentDownloader {
self.client
.add_torrent(AddTorrentArg {
source,
savepath: save_path.clone(),
savepath: save_path,
auto_torrent_management: Some(false),
category: Some(category.clone()),
tags: tag,
category,
tags,
..Default::default()
})
.await?;
@ -718,12 +702,12 @@ impl DownloaderTrait for QBittorrentDownloader {
self.wait_sync_until(
|sync_data| {
let torrents = &sync_data.torrents;
ids.iter().all(|id| torrents.contains_key(id))
hashes.iter().all(|hash| torrents.contains_key(hash))
},
None,
)
.await?;
Ok(ids)
Ok(hashes)
}
async fn pause_downloads(
@ -766,6 +750,7 @@ impl DownloaderTrait for QBittorrentDownloader {
}
}))
.await?;
let tasks = torrent_list
.into_iter()
.zip(torrent_contents)
@ -827,6 +812,8 @@ impl Debug for QBittorrentDownloader {
#[cfg(test)]
pub mod tests {
use serde::{Deserialize, Serialize};
use super::*;
use crate::{
downloader::core::DownloadIdSelectorTrait,
@ -842,27 +829,47 @@ pub mod tests {
}
}
#[derive(Serialize)]
struct MockFileItem {
path: String,
size: u64,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct MockRequest {
id: String,
file_list: Vec<MockFileItem>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct MockResponse {
torrent_url: String,
magnet_url: String,
hash: String,
}
#[cfg(feature = "testcontainers")]
pub async fn create_torrents_testcontainers()
-> RResult<testcontainers::ContainerRequest<testcontainers::GenericImage>> {
use testcontainers::{
GenericImage,
core::{
ContainerPort,
// ReuseDirective,
WaitFor,
},
core::{ContainerPort, WaitFor},
};
use testcontainers_modules::testcontainers::ImageExt;
use crate::test_utils::testcontainers::ContainerRequestEnhancedExt;
let container = GenericImage::new("ghcr.io/dumtruck/konobangu-testing-torrents", "latest")
.with_exposed_port()
.with_wait_for(WaitFor::message_on_stderr("Connection to localhost"))
.with_wait_for(WaitFor::message_on_stdout("Listening on"))
.with_mapped_port(6080, ContainerPort::Tcp(6080))
.with_mapped_port(6081, ContainerPort::Tcp(6081))
.with_mapped_port(6082, ContainerPort::Tcp(6082))
// .with_reuse(ReuseDirective::Always)
.with_default_log_consumer()
.with_prune_existed_label("qbit-downloader", true, true)
.with_prune_existed_label("konobangu-testing-torrents", true, true)
.await?;
Ok(container)
@ -917,13 +924,36 @@ pub mod tests {
.with_test_writer()
.init();
let image = create_qbit_testcontainers().await?;
let torrents_image = create_torrents_testcontainers().await?;
let _torrents_container = torrents_image.start().await?;
let container = image.start().await?;
let torrents_req = MockRequest {
id: "f10ebdda-dd2e-43f8-b80c-bf0884d071c4".into(),
file_list: vec![MockFileItem {
path: "[Nekomoe kissaten&LoliHouse] Boku no Kokoro no Yabai Yatsu - 20 [WebRip \
1080p HEVC-10bit AAC ASSx2].mkv"
.into(),
size: 1024,
}],
};
let torrent_res: MockResponse = reqwest::Client::new()
.post("http://127.0.0.1:6080/api/torrents/mock")
.json(&torrents_req)
.send()
.await?
.json()
.await?;
let qbit_image = create_qbit_testcontainers().await?;
let qbit_container = qbit_image.start().await?;
let mut logs = String::new();
container.stdout(false).read_to_string(&mut logs).await?;
qbit_container
.stdout(false)
.read_to_string(&mut logs)
.await?;
let username = logs
.lines()
@ -940,7 +970,7 @@ pub mod tests {
let password = logs
.lines()
.find_map(|line| {
if line.contains("A temporary password is provided for this session") {
if line.contains("A temporary password is provided for") {
line.split_whitespace().last()
} else {
None
@ -951,7 +981,13 @@ pub mod tests {
tracing::info!(username, password);
test_qbittorrent_downloader_impl(Some(username), Some(password)).await?;
test_qbittorrent_downloader_impl(
torrent_res.torrent_url,
torrent_res.hash,
Some(username),
Some(password),
)
.await?;
Ok(())
}
@ -965,31 +1001,25 @@ pub mod tests {
let http_client = build_testing_http_client()?;
let base_save_path = Path::new(get_tmp_qbit_test_folder());
let hash = "47ee2d69e7f19af783ad896541a07b012676f858".to_string();
let mut downloader = QBittorrentDownloader::from_creation(QBittorrentDownloaderCreation {
let downloader = QBittorrentDownloader::from_creation(QBittorrentDownloaderCreation {
endpoint: "http://127.0.0.1:8080".to_string(),
password: password.unwrap_or_default().to_string(),
username: username.unwrap_or_default().to_string(),
subscriber_id: 0,
save_path: base_save_path.to_string(),
downloader_id: 0,
wait_sync_timeout: Some(Duration::from_secs(3)),
})
.await?;
downloader.wait_sync_timeout = Duration::from_secs(3);
downloader.check_connection().await?;
downloader
.remove_torrents(vec![hash.clone()].into())
.remove_torrents(vec![torrent_hash.clone()].into())
.await?;
let torrent_source = HashTorrentSource::from_url_and_http_client(
&http_client,
format!("https://mikanani.me/Download/20240301/{}.torrent", &hash),
)
.await?;
let torrent_source =
HashTorrentSource::from_url_and_http_client(&http_client, torrent_url).await?;
let folder_name = format!("torrent_test_{}", Utc::now().timestamp());
let save_path = base_save_path.join(&folder_name);
@ -1006,13 +1036,13 @@ pub mod tests {
let get_torrent = async || -> Result<QBittorrentTask, DownloaderError> {
let torrent_infos = downloader
.query_downloads(QBittorrentSelector::Hash(QBittorrentHashSelector::from_id(
hash.clone(),
torrent_hash.clone(),
)))
.await?;
let result = torrent_infos
.into_iter()
.find(|t| t.hash_info() == hash)
.find(|t| t.hash_info() == torrent_hash)
.whatever_context::<_, DownloaderError>("no bittorrent")?;
Ok(result)
@ -1021,18 +1051,18 @@ pub mod tests {
let target_torrent = get_torrent().await?;
let files = target_torrent.contents;
assert!(!files.is_empty());
let first_file = files.first().expect("should have first file");
assert_eq!(
&first_file.name,
r#"[Nekomoe kissaten&LoliHouse] Boku no Kokoro no Yabai Yatsu - 20 [WebRip 1080p HEVC-10bit AAC ASSx2].mkv"#
assert!(
&first_file.name.ends_with(r#"[Nekomoe kissaten&LoliHouse] Boku no Kokoro no Yabai Yatsu - 20 [WebRip 1080p HEVC-10bit AAC ASSx2].mkv"#)
);
let test_tag = format!("test_tag_{}", Utc::now().timestamp());
let test_tag = "test_tag".to_string();
downloader
.add_torrent_tags(vec![hash.clone()], vec![test_tag.clone()])
.add_torrent_tags(vec![torrent_hash.clone()], vec![test_tag.clone()])
.await?;
let target_torrent = get_torrent().await?;
@ -1042,7 +1072,7 @@ pub mod tests {
let test_category = format!("test_category_{}", Utc::now().timestamp());
downloader
.set_torrents_category(vec![hash.clone()], &test_category)
.set_torrents_category(vec![torrent_hash.clone()], &test_category)
.await?;
let target_torrent = get_torrent().await?;
@ -1055,7 +1085,7 @@ pub mod tests {
let moved_torrent_path = base_save_path.join(format!("moved_{}", Utc::now().timestamp()));
downloader
.move_torrents(vec![hash.clone()], moved_torrent_path.as_str())
.move_torrents(vec![torrent_hash.clone()], moved_torrent_path.as_str())
.await?;
let target_torrent = get_torrent().await?;
@ -1073,30 +1103,7 @@ pub mod tests {
);
downloader
.move_torrent_contents(&hash, |f| {
f.replace(&folder_name, &format!("moved_{}", &folder_name))
})
.await?;
let target_torrent = get_torrent().await?;
let actual_content_path = &target_torrent
.torrent
.content_path
.expect("failed to get actual content path");
assert!(
path_equals_as_file_url(
actual_content_path,
base_save_path.join(actual_content_path)
)
.whatever_context::<_, RError>(
"failed to compare actual content path and found expected content path"
)?
);
downloader
.remove_torrents(vec![hash.clone()].into())
.remove_torrents(vec![torrent_hash.clone()].into())
.await?;
let torrent_infos1 = downloader
@ -1109,6 +1116,8 @@ pub mod tests {
assert!(torrent_infos1.is_empty());
tracing::info!("test finished");
Ok(())
}
}

View File

@ -79,7 +79,9 @@ where
.await
.map_err(|error| TestcontainersError::Other(Box::new(error)))?;
tracing::warn!(name = "stop running containers", result = ?remove_containers);
if !remove_containers.is_empty() {
tracing::warn!(name = "stop running containers", result = ?remove_containers);
}
}
let result = client
@ -87,7 +89,13 @@ where
.await
.map_err(|err| TestcontainersError::Other(Box::new(err)))?;
tracing::warn!(name = "prune existed containers", result = ?result);
if result
.containers_deleted
.as_ref()
.is_some_and(|c| !c.is_empty())
{
tracing::warn!(name = "prune existed containers", result = ?result);
}
}
let result = self.with_labels([

View File

@ -8,11 +8,14 @@ FROM nodebt AS deps
RUN mkdir -p /app/workspace
WORKDIR /app
COPY package.json /app/
RUN pnpm approve-builds utf-8-validate node-datachannel utp-native
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --no-frozen-lockfile
FROM deps AS app
COPY main.ts /app/
EXPOSE 6080
EXPOSE 6081
EXPOSE 6082
CMD [ "npm", "start" ]

View File

@ -1,5 +1,11 @@
# Konobangu Testing Torrents Container
## Development
```bash
pnpm install --ignore-workspace
```
## Build
```bash
@ -9,7 +15,7 @@ docker buildx build --platform linux/amd64 --tag konobangu-testing-torrents:late
## Run
```bash
docker run --network_mode=host --name konobangu-testing-torrents konobangu-testing-torrents:latest
docker run -p 6080:6080 -p 6081:6081 -p 6082:6082 --name konobangu-testing-torrents konobangu-testing-torrents:latest
```
## Publish
@ -17,4 +23,4 @@ docker run --network_mode=host --name konobangu-testing-torrents konobangu-testi
```bash
docker tag konobangu-testing-torrents:latest ghcr.io/dumtruck/konobangu-testing-torrents:latest
docker push ghcr.io/dumtruck/konobangu-testing-torrents:latest
```
```

View File

@ -1,5 +1,8 @@
services:
konobangu-testing-torrents:
build: .
network_mode: host
container_name: konobangu-testing-torrents
konobangu-testing-torrents:
build: .
ports:
- 6080:6080
- 6081:6081
- 6082:6082
container_name: konobangu-testing-torrents

View File

@ -6,7 +6,6 @@ import fsp from 'node:fs/promises';
import path from 'node:path';
// @ts-ignore
import TrackerServer from 'bittorrent-tracker/server';
import createTorrent from 'create-torrent';
import WebTorrent, { type Torrent } from 'webtorrent';
// Configuration
@ -17,7 +16,7 @@ const STATIC_API_PATH = '/api/static';
const LOCAL_IP = '127.0.0.1';
const WORKSPACE_PATH = 'workspace';
const TRACKER_URL = `http://${LOCAL_IP}:${TRACKER_PORT}/announce`;
const API_BASE_URL = `http://${LOCAL_IP}:${API_PORT}/${STATIC_API_PATH}/`;
const API_BASE_URL = `http://${LOCAL_IP}:${API_PORT}${STATIC_API_PATH}/`;
// Initialize Fastify instance
const app = Fastify({ logger: true });
@ -29,9 +28,9 @@ app.register(fastifyStatic, {
});
const tracker = new TrackerServer({
udp: true, // enable udp server? [default=true]
udp: false, // enable udp server? [default=true]
http: true, // enable http server? [default=true]
ws: true, // enable websocket server? [default=true]
ws: false, // enable websocket server? [default=true]
stats: true, // enable web-based statistics? [default=true]
trustProxy: true, // enable trusting x-forwarded-for header for remote IP [default=false]
});
@ -50,12 +49,13 @@ interface RequestSchema {
interface ResponseSchema {
torrentUrl: string;
magnetUrl: string;
hash: string;
}
// Start local Tracker
async function startTracker(): Promise<void> {
return new Promise<void>((resolve, reject) => {
tracker.listen(TRACKER_PORT, 'localhost', () => {
tracker.listen(TRACKER_PORT, '0.0.0.0', () => {
console.log(`Tracker listening on port ${TRACKER_PORT}`);
resolve();
});
@ -85,47 +85,26 @@ async function generateMockFile(filePath: string, size: number) {
await fsp.mkdir(dir, { recursive: true });
}
await fsp.writeFile(filePath, Buffer.alloc(0));
await fsp.truncate(filePath, size);
}
// Generate bittorrent file
function generateTorrent(folderPath: string, torrentPath: string) {
return new Promise<void>((resolve, reject) => {
createTorrent(
folderPath,
// Add bittorrent and seed
async function seedTorrent(
torrentPath: string,
contentFolder: string
): Promise<Torrent> {
return new Promise((resolve) => {
const torrent = webTorrent.seed(
contentFolder,
{
announceList: [[TRACKER_URL]], // Specify tracker URL
private: false,
createdBy: 'WebTorrent',
comment: 'Generated by WebTorrent server',
createdBy: 'Konobangu Testing Torrents',
urlList: [API_BASE_URL],
},
async (err, torrent) => {
if (err) {
reject(new Error(`Failed to create torrent: ${err}`));
return;
}
await fsp.writeFile(torrentPath, torrent);
if (!fs.existsSync(torrentPath)) {
reject(new Error(`Torrent file ${torrentPath} was not created`));
return;
}
console.log(`Generated torrent with tracker: ${TRACKER_URL}`);
resolve();
}
);
});
}
// Add bittorrent and seed
async function seedTorrent(torrentPath: string): Promise<Torrent> {
return new Promise((resolve) => {
const torrent = webTorrent.seed(
torrentPath,
{
announce: [TRACKER_URL],
},
(t) => {
async (t) => {
await fsp.writeFile(torrentPath, t.torrentFile);
resolve(t);
}
);
@ -154,14 +133,14 @@ app.post<{ Body: RequestSchema }>('/api/torrents/mock', async (req, _reply) => {
}
const torrentPath = path.join(WORKSPACE_PATH, `${id}.torrent`);
await generateTorrent(idFolder, torrentPath);
const torrent = await seedTorrent(torrentPath);
const torrent = await seedTorrent(torrentPath, idFolder);
const magnetUrl = `magnet:?xt=urn:btih:${torrent.infoHash}&tr=${TRACKER_URL}`;
return {
torrentUrl: `${API_BASE_URL}${id}.torrent`,
magnetUrl,
hash: torrent.infoHash,
} as ResponseSchema;
});
@ -169,7 +148,8 @@ app.post<{ Body: RequestSchema }>('/api/torrents/mock', async (req, _reply) => {
async function main() {
try {
await startTracker();
await app.listen({ port: API_PORT, host: LOCAL_IP });
const address = await app.listen({ port: API_PORT, host: '0.0.0.0' });
console.log('Listening on:', address);
} catch (err) {
console.error('Startup error:', err);
webTorrent.destroy();

View File

@ -10,7 +10,6 @@
"dependencies": {
"@fastify/static": "^8.1.1",
"bittorrent-tracker": "^11.2.1",
"create-torrent": "^6.1.0",
"fastify": "^5.2.2",
"tsx": "^4.19.2",
"webtorrent": "^2.5.19"
@ -18,5 +17,14 @@
"devDependencies": {
"@types/create-torrent": "^5.0.2",
"@types/webtorrent": "^0.110.0"
},
"pnpm": {
"onlyBuiltDependencies": [
"bufferutil",
"esbuild",
"node-datachannel",
"utf-8-validate",
"utp-native"
]
}
}

2458
packages/testing-torrents/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1567
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,11 @@
packages:
- packages/*
- apps/*
- packages/*
- apps/*
- '!packages/testing-torrents'
onlyBuiltDependencies:
- '@biomejs/biome'
- bufferutil
- core-js
- esbuild
- sharp
- utf-8-validate