Merge "添加更新用户流量的方法,并定时跟新到所有用户"

Change-Id: I558ee7de6767ed1b78685883310a268ea51b198a
diff --git a/src/main/java/com/pt/service/TorrentService.java b/src/main/java/com/pt/service/TorrentService.java
index ad38622..3c9d28d 100644
--- a/src/main/java/com/pt/service/TorrentService.java
+++ b/src/main/java/com/pt/service/TorrentService.java
@@ -10,6 +10,7 @@
 import java.time.LocalDateTime;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 
 @Service
 public class TorrentService {
@@ -18,25 +19,17 @@
     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;
@@ -50,17 +43,23 @@
             }
             length = totalLength;
         }
-
         // 保存到数据库
-        TorrentMeta meta = new TorrentMeta();
-        meta.setFilename(name);
-        meta.setInfoHash(infoHash);
-        meta.setSize(length);
-        meta.setUploadTime(LocalDateTime.now());
-        meta.setTorrentData(torrentBytes);
+        Optional<TorrentMeta> existing = torrentMetaRepository.findByInfoHash(infoHash);
 
-        torrentMetaRepository.save(meta);
-        return meta;
+        if (existing.isPresent()) {
+            System.out.println("该种子已存在,跳过保存");
+            return existing.get();
+        } else {
+            TorrentMeta meta = new TorrentMeta();
+            meta.setFilename(name);
+            meta.setInfoHash(infoHash);
+            meta.setSize(length);
+            meta.setUploadTime(LocalDateTime.now());
+            meta.setTorrentData(torrentBytes);
+
+            return torrentMetaRepository.save(meta);
+        }
+
     }