| package com.example.myproject.config; |
| |
| import com.turn.ttorrent.tracker.TrackedTorrent; |
| import com.turn.ttorrent.tracker.Tracker; |
| import org.springframework.beans.factory.annotation.Value; |
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import javax.annotation.PreDestroy; |
| import java.io.File; |
| import java.io.IOException; |
| import java.net.InetAddress; |
| |
| @Configuration |
| public class TrackerConfig { |
| @Value("${pt.tracker.port}") |
| private int trackerPort; |
| |
| @Value("${pt.tracker.torrent-dir}") |
| private String torrentDir; |
| @Value("${pt.tracker.announce-url}") |
| private String announceURL; |
| |
| private Tracker tracker; // 存储 Tracker 实例 |
| |
| @Bean |
| public Tracker torrentTracker() throws IOException { |
| // 验证并创建目录 |
| File dir = new File(torrentDir); |
| validateTorrentDirectory(dir); |
| |
| // 初始化 Tracker |
| tracker = new Tracker(trackerPort, announceURL); |
| tracker.setAcceptForeignTorrents(false); // PT 站点必须关闭匿名模式 |
| tracker.setAnnounceInterval(1800); // 30分钟 announce 间隔 |
| |
| // 加载种子文件 |
| loadTorrents(tracker, dir); |
| |
| // 启动 Tracker |
| tracker.start(true); |
| System.out.println("Tracker started on port " + trackerPort); |
| return tracker; |
| } |
| |
| private void validateTorrentDirectory(File dir) throws IOException { |
| if (!dir.exists()) { |
| if (!dir.mkdirs()) { |
| throw new IOException("无法创建目录: " + dir.getAbsolutePath()); |
| } |
| } |
| if (!dir.isDirectory()) { |
| throw new IllegalArgumentException("路径不是目录: " + dir.getAbsolutePath()); |
| } |
| if (!dir.canRead() || !dir.canWrite()) { |
| throw new IOException("应用程序无权限访问目录: " + dir.getAbsolutePath()); |
| } |
| } |
| |
| private void loadTorrents(Tracker tracker, File dir) throws IOException { |
| if (!dir.exists() || !dir.isDirectory()) { |
| throw new IOException("无效的种子目录: " + dir.getAbsolutePath()); |
| } |
| |
| File[] torrentFiles = dir.listFiles((d, name) -> name.endsWith(".torrent")); |
| if (torrentFiles == null) { |
| throw new IOException("无法读取目录内容: " + dir.getAbsolutePath()); |
| } |
| |
| for (File f : torrentFiles) { |
| tracker.announce(TrackedTorrent.load(f)); |
| } |
| } |
| |
| @PreDestroy |
| public void stopTracker() { |
| if (tracker != null) { |
| tracker.stop(); |
| System.out.println("Tracker stopped."); |
| } |
| } |
| } |