blob: 1fdb700140343735e4deea10c8d39ca6848a020a [file] [log] [blame]
22301102bc6da0a2025-06-02 17:47:29 +08001package com.pt.service;
2
3import com.pt.entity.TorrentMeta;
4import com.pt.repository.TorrentMetaRepository;
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +08005import com.pt.utils.BencodeCodec;
22301102bc6da0a2025-06-02 17:47:29 +08006import org.springframework.beans.factory.annotation.Autowired;
7import org.springframework.stereotype.Service;
8
22301102bc6da0a2025-06-02 17:47:29 +08009import java.security.MessageDigest;
10import java.time.LocalDateTime;
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +080011import java.util.List;
22301102bc6da0a2025-06-02 17:47:29 +080012import java.util.Map;
13
14@Service
15public class TorrentService {
16
22301102bc6da0a2025-06-02 17:47:29 +080017 @Autowired
18 private TorrentMetaRepository torrentMetaRepository;
19
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +080020 public TorrentMeta parseAndSaveTorrent(byte[] torrentBytes) throws Exception {
21 Map<String, Object> torrentDict = (Map<String, Object>) BencodeCodec.decode(torrentBytes);
22 if (!torrentDict.containsKey("info")) {
23 throw new IllegalArgumentException("Invalid torrent file: missing 'info' dictionary");
22301102bc6da0a2025-06-02 17:47:29 +080024 }
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +080025
26 Map<String, Object> infoDict = (Map<String, Object>) torrentDict.get("info");
27
28 // 计算 info_hash
29 byte[] infoEncoded = BencodeCodec.encode(infoDict);
30 MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
31 byte[] infoHashBytes = sha1.digest(infoEncoded);
32 String infoHash = bytesToHex(infoHashBytes);
33
34 // 获取文件名,大小等
35 String name = (String) infoDict.get("name");
36 long length = 0;
37 if (infoDict.containsKey("length")) {
38 length = ((Number) infoDict.get("length")).longValue();
39 } else if (infoDict.containsKey("files")) {
40 long totalLength = 0;
41 List<Map<String, Object>> files = (List<Map<String, Object>>) infoDict.get("files");
42 for (Map<String, Object> file : files) {
43 totalLength += ((Number) file.get("length")).longValue();
44 }
45 length = totalLength;
46 }
47
48 // 保存到数据库
49 TorrentMeta meta = new TorrentMeta();
50 meta.setFilename(name);
51 meta.setInfoHash(infoHash);
52 meta.setSize(length);
53 meta.setUploadTime(LocalDateTime.now());
54 meta.setTorrentData(torrentBytes);
55
56 torrentMetaRepository.save(meta);
57 return meta;
22301102bc6da0a2025-06-02 17:47:29 +080058 }
59
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +080060
22301102bc6da0a2025-06-02 17:47:29 +080061 private String bytesToHex(byte[] bytes) {
62 StringBuilder sb = new StringBuilder();
63 for (byte b : bytes) {
64 sb.append(String.format("%02x", b));
65 }
66 return sb.toString();
67 }
Edwardsamaxlf1bf7ad2025-06-03 23:52:16 +080068}