22301115 | 90135d7 | 2025-06-03 17:11:40 +0800 | [diff] [blame^] | 1 | package com.example.myproject.config; |
| 2 | |
| 3 | import com.turn.ttorrent.tracker.TrackedTorrent; |
| 4 | import com.turn.ttorrent.tracker.Tracker; |
| 5 | import org.springframework.beans.factory.annotation.Value; |
| 6 | import org.springframework.context.annotation.Bean; |
| 7 | import org.springframework.context.annotation.Configuration; |
| 8 | import javax.annotation.PreDestroy; |
| 9 | import java.io.File; |
| 10 | import java.io.IOException; |
| 11 | import java.net.InetAddress; |
| 12 | |
| 13 | @Configuration |
| 14 | public 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 | } |