22301071 | 66504b7 | 2025-06-08 13:54:29 +0800 | [diff] [blame] | 1 | package com.example.g8backend.util; |
| 2 | |
| 3 | import com.example.g8backend.dto.AnnounceResponseDTO; |
| 4 | |
| 5 | import java.io.ByteArrayOutputStream; |
| 6 | import java.nio.charset.StandardCharsets; |
| 7 | import java.util.*; |
| 8 | |
| 9 | public class BencodeUtil { |
| 10 | public static byte[] encodeAnnounceResponse(AnnounceResponseDTO dto) { |
| 11 | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| 12 | try { |
| 13 | out.write('d'); // dictionary start |
| 14 | |
| 15 | writeString(out, "interval"); |
| 16 | writeInt(out, dto.getInterval()); |
| 17 | |
| 18 | writeString(out, "peers"); |
| 19 | out.write('l'); // list start |
| 20 | for (Map<String, Object> peer : dto.getPeers()) { |
| 21 | out.write('d'); |
| 22 | writeString(out, "ip"); |
| 23 | writeString(out, (String) peer.get("ip")); |
| 24 | writeString(out, "port"); |
| 25 | writeInt(out, ((Number) peer.get("port")).intValue()); |
| 26 | out.write('e'); |
| 27 | } |
| 28 | out.write('e'); // list end |
| 29 | |
| 30 | out.write('e'); // dictionary end |
| 31 | } catch (Exception e) { |
| 32 | throw new RuntimeException("Bencoding failed", e); |
| 33 | } |
| 34 | return out.toByteArray(); |
| 35 | } |
| 36 | |
| 37 | private static void writeString(ByteArrayOutputStream out, String str) throws Exception { |
| 38 | byte[] bytes = str.getBytes(StandardCharsets.UTF_8); |
| 39 | out.write(String.valueOf(bytes.length).getBytes(StandardCharsets.UTF_8)); |
| 40 | out.write(':'); |
| 41 | out.write(bytes); |
| 42 | } |
| 43 | |
| 44 | private static void writeInt(ByteArrayOutputStream out, int i) throws Exception { |
| 45 | out.write('i'); |
| 46 | out.write(String.valueOf(i).getBytes(StandardCharsets.UTF_8)); |
| 47 | out.write('e'); |
| 48 | } |
| 49 | } |