blob: ad386223236894fbbf4002712c433c7e8a5aa01c [file] [log] [blame]
package com.pt.service;
import com.pt.entity.TorrentMeta;
import com.pt.repository.TorrentMetaRepository;
import com.pt.utils.BencodeCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Service
public class TorrentService {
@Autowired
private TorrentMetaRepository torrentMetaRepository;
public TorrentMeta parseAndSaveTorrent(byte[] torrentBytes) throws Exception {
System.out.println("111");
for (byte b : torrentBytes) {
System.out.println(b);
}
Map<String, Object> torrentDict = (Map<String, Object>) BencodeCodec.decode(torrentBytes);
if (!torrentDict.containsKey("info")) {
throw new IllegalArgumentException("Invalid torrent file: missing 'info' dictionary");
}
Map<String, Object> infoDict = (Map<String, Object>) torrentDict.get("info");
System.out.println(222);
// 计算 info_hash
byte[] infoEncoded = BencodeCodec.encode(infoDict);
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
byte[] infoHashBytes = sha1.digest(infoEncoded);
String infoHash = bytesToHex(infoHashBytes);
System.out.println(333);
// 获取文件名,大小等
String name = (String) infoDict.get("name");
long length = 0;
if (infoDict.containsKey("length")) {
length = ((Number) infoDict.get("length")).longValue();
} else if (infoDict.containsKey("files")) {
long totalLength = 0;
List<Map<String, Object>> files = (List<Map<String, Object>>) infoDict.get("files");
for (Map<String, Object> file : files) {
totalLength += ((Number) file.get("length")).longValue();
}
length = totalLength;
}
// 保存到数据库
TorrentMeta meta = new TorrentMeta();
meta.setFilename(name);
meta.setInfoHash(infoHash);
meta.setSize(length);
meta.setUploadTime(LocalDateTime.now());
meta.setTorrentData(torrentBytes);
torrentMetaRepository.save(meta);
return meta;
}
private String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}