feat: add testing-torrents

This commit is contained in:
2025-04-01 03:00:29 +08:00
parent 07ac7e3376
commit a0fc4c04d9
21 changed files with 2667 additions and 439 deletions

View File

@@ -0,0 +1,14 @@
FROM node:23-slim AS nodebt
FROM nodebt AS deps
RUN mkdir -p /app/workspace
WORKDIR /app
COPY package.json /app/
RUN npm install
FROM deps AS app
COPY main.ts /app/
CMD [ "npm", "start" ]

View File

@@ -0,0 +1,20 @@
# Konobangu Testing Torrents Container
## Build
```bash
docker buildx build --platform linux/amd64 --tag konobangu-testing-torrents:latest --load .
```
## Run
```bash
docker run --network_mode=host --name konobangu-testing-torrents konobangu-testing-torrents:latest
```
## Publish
```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

@@ -0,0 +1,5 @@
services:
konobangu-testing-torrents:
build: .
network_mode: host
container_name: konobangu-testing-torrents

View File

@@ -0,0 +1,181 @@
import Fastify from 'fastify';
import fastifyStatic from '@fastify/static';
import { join } from 'node:path';
import WebTorrent, { Torrent } from 'webtorrent';
import createTorrent from 'create-torrent'
// @ts-ignore
import TrackerServer from 'bittorrent-tracker/server'
import fs, { existsSync, mkdirSync, writeFileSync } from 'node:fs';
// Configuration
const API_PORT = 6080;
const TRACKER_PORT = 6081;
// Get local IP address for broader accessibility
const LOCAL_IP = '127.0.0.1';
const TRACKER_URL = `http://${LOCAL_IP}:${TRACKER_PORT}/announce`;
const API_BASE_URL = `http://${LOCAL_IP}:${API_PORT}/api/static/`;
// Initialize Fastify instance
const app = Fastify({ logger: true });
// Mount static file service, mapping ./workspace directory to /api/static route
app.register(fastifyStatic, {
root: join(process.cwd(), 'workspace'),
prefix: '/api/static',
});
const tracker = new TrackerServer({
udp: true, // enable udp server? [default=true]
http: true, // enable http server? [default=true]
ws: true, // 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]
});
// Define request and response type definitions
interface FileItem {
path: string;
size: number;
}
interface RequestSchema {
id: string;
fileList: FileItem[];
}
interface ResponseSchema {
torrentUrl: string;
magnetUrl: string;
}
// Start local Tracker
async function startTracker(): Promise<void> {
return new Promise<void>((resolve, reject) => {
tracker.listen(TRACKER_PORT, "localhost", () => {
console.log(`Tracker listening on port ${TRACKER_PORT}`);
resolve();
});
tracker.on('error', (err: any) => {
console.error(`Tracker error: ${err}`)
reject(`Tracker error: ${err}`);
});
tracker.on('warning', (warn: any) => console.warn(`Tracker warning: ${warn}`));
// Log tracked torrents
tracker.on('update', (addr: any, params: any) => {
console.log(`Tracker update: ${params.info_hash} from ${addr}`);
});
tracker.on('stop', function () {
reject(`Tracker stopped`);
})
});
}
// Tracker and WebTorrent client
const webTorrent = new WebTorrent({});
// Generate mock file
async function generateMockFile(filePath: string, size: number) {
const dir = join(filePath, '..');
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true })
};
fs.writeFileSync(filePath, 'w');
fs.truncateSync(filePath, size);
}
// Generate torrent file
function generateTorrent(folderPath: string, torrentPath: string): Promise<void> {
return new Promise((resolve, reject) => {
createTorrent(
folderPath,
{
announceList: [[TRACKER_URL]], // Specify tracker URL
private: false,
createdBy: 'WebTorrent',
comment: 'Generated by WebTorrent server',
urlList: [API_BASE_URL]
},
(err, torrent) => {
if (err) {
reject(new Error(`Failed to create torrent: ${err}`));
return;
}
writeFileSync(torrentPath, torrent);
if (!existsSync(torrentPath)) {
reject(new Error(`Torrent file ${torrentPath} was not created`));
return;
}
console.log(`Generated torrent with tracker: ${TRACKER_URL}`);
resolve();
}
);
});
}
// Add torrent and seed
async function seedTorrent(torrentPath: string): Promise<Torrent> {
return new Promise((resolve) => {
const torrent = webTorrent.seed(torrentPath, {
announce: [TRACKER_URL],
}, (t) => {
resolve(t);
});
torrent.on('error', (err) => console.error(`Torrent error: ${err}`));
torrent.on('wire', (wire) => console.log(`Connected to peer: ${wire.peerId}`));
torrent.on('done', () => console.log(`Torrent ${torrent.infoHash} fully seeded`));
})
}
// Handle POST request to /api/torrents/mock
app.post<{ Body: RequestSchema }>('/api/torrents/mock', async (req, _reply) => {
const { id, fileList } = req.body;
const idFolder = join('./workspace', id);
if (!existsSync(idFolder)) {
mkdirSync(idFolder, { recursive: true })
};
for (const fileItem of fileList) {
const filePath = join(idFolder, fileItem.path);
await generateMockFile(filePath, fileItem.size);
}
const torrentPath = join('./workspace', `${id}.torrent`);
await generateTorrent(idFolder, torrentPath);
const torrent = await seedTorrent(torrentPath);
const magnetUrl = `magnet:?xt=urn:btih:${torrent.infoHash}&tr=${TRACKER_URL}`;
return {
torrentUrl: `${API_BASE_URL}${id}.torrent`,
magnetUrl,
} as ResponseSchema;
});
// Main program entry
async function main() {
try {
await startTracker();
await app.listen({ port: API_PORT, host: '0.0.0.0' });
console.log(`Fastify running on http://0.0.0.0:${API_PORT}`);
} catch (err) {
console.error('Startup error:', err);
webTorrent.destroy();
tracker.close();
process.exit(1);
}
}
main();
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down...');
tracker.close();
webTorrent.destroy();
process.exit(0);
});

View File

@@ -0,0 +1,22 @@
{
"name": "@konobangu/testing-torrents",
"version": "0.0.1",
"description": "Kono bangumi? Testing Torrents",
"main": "main.ts",
"type": "commonjs",
"scripts": {
"start": "tsx main.ts"
},
"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"
},
"devDependencies": {
"@types/create-torrent": "^5.0.2",
"@types/webtorrent": "^0.110.0"
}
}