blob: 67522b7e83c04efbdee74061efb3421912c09c5b [file] [log] [blame]
YelinCuifdf4ed72025-05-26 11:49:36 +08001package com.example.myproject.config;
2
3import com.turn.ttorrent.tracker.TrackedTorrent;
4import com.turn.ttorrent.tracker.Tracker;
5import org.springframework.beans.factory.annotation.Value;
6import org.springframework.context.annotation.Bean;
7import org.springframework.context.annotation.Configuration;
8import javax.annotation.PreDestroy;
9import java.io.File;
10import java.io.IOException;
11import java.net.InetAddress;
12
13@Configuration
14public class TrackerConfig {
15 @Value("${pt.tracker.port}")
16 private int trackerPort;
17
18 @Value("${pt.tracker.torrent-dir}")
19 private String torrentDir;
20 @Value("${pt.tracker.announce-url}")
21 private String announceURL;
22
23 private Tracker tracker; // 存储 Tracker 实例
24
25 @Bean
26 public Tracker torrentTracker() throws IOException {
27 // 验证并创建目录
28 File dir = new File(torrentDir);
29 validateTorrentDirectory(dir);
30
31 // 初始化 Tracker
32 tracker = new Tracker(trackerPort, announceURL);
33 tracker.setAcceptForeignTorrents(false); // PT 站点必须关闭匿名模式
34 tracker.setAnnounceInterval(1800); // 30分钟 announce 间隔
35
36 // 加载种子文件
37 loadTorrents(tracker, dir);
38
39 // 启动 Tracker
40 tracker.start(true);
41 System.out.println("Tracker started on port " + trackerPort);
42 return tracker;
43 }
44
45 private void validateTorrentDirectory(File dir) throws IOException {
46 if (!dir.exists()) {
47 if (!dir.mkdirs()) {
48 throw new IOException("无法创建目录: " + dir.getAbsolutePath());
49 }
50 }
51 if (!dir.isDirectory()) {
52 throw new IllegalArgumentException("路径不是目录: " + dir.getAbsolutePath());
53 }
54 if (!dir.canRead() || !dir.canWrite()) {
55 throw new IOException("应用程序无权限访问目录: " + dir.getAbsolutePath());
56 }
57 }
58
59 private void loadTorrents(Tracker tracker, File dir) throws IOException {
60 if (!dir.exists() || !dir.isDirectory()) {
61 throw new IOException("无效的种子目录: " + dir.getAbsolutePath());
62 }
63
64 File[] torrentFiles = dir.listFiles((d, name) -> name.endsWith(".torrent"));
65 if (torrentFiles == null) {
66 throw new IOException("无法读取目录内容: " + dir.getAbsolutePath());
67 }
68
69 for (File f : torrentFiles) {
70 tracker.announce(TrackedTorrent.load(f));
71 }
72 }
73
74 @PreDestroy
75 public void stopTracker() {
76 if (tracker != null) {
77 tracker.stop();
78 System.out.println("Tracker stopped.");
79 }
80 }
81}