]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Basic support for serializing v2 torrent file (#968)
authorMivik <54128043+Mivik@users.noreply.github.com>
Mon, 26 Aug 2024 09:44:45 +0000 (17:44 +0800)
committerGitHub <noreply@github.com>
Mon, 26 Aug 2024 09:44:45 +0000 (19:44 +1000)
* Support marshalling FileTree

* Omit Pieces in torrent info if empty

Otherwise some BitTorrent client (e.g. libttorrent) will not be able to
parse v2 torrent file.

metainfo/file-tree.go
metainfo/info.go

index 2b651bd4464344bdd872bb61976c9e58766f8f43..6401b1ed4b73a6c61f128f744e0c7df29efa14bc 100644 (file)
@@ -49,6 +49,35 @@ func (ft *FileTree) UnmarshalBencode(bytes []byte) (err error) {
 
 var _ bencode.Unmarshaler = (*FileTree)(nil)
 
+func (ft *FileTree) MarshalBencode() (bytes []byte, err error) {
+       if ft.IsDir() {
+               dir := make(map[string]bencode.Bytes, len(ft.Dir))
+               for _, key := range ft.orderedKeys() {
+                       if key == FileTreePropertiesKey {
+                               continue
+                       }
+                       sub := g.MapMustGet(ft.Dir, key)
+                       subBytes, err := sub.MarshalBencode()
+                       if err != nil {
+                               return nil, err
+                       }
+                       dir[key] = subBytes
+               }
+               return bencode.Marshal(dir)
+       } else {
+               fileBytes, err := bencode.Marshal(ft.File)
+               if err != nil {
+                       return nil, err
+               }
+               res := map[string]bencode.Bytes{
+                       "": fileBytes,
+               }
+               return bencode.Marshal(res)
+       }
+}
+
+var _ bencode.Marshaler = (*FileTree)(nil)
+
 func (ft *FileTree) NumEntries() (num int) {
        num = len(ft.Dir)
        if g.MapContains(ft.Dir, FileTreePropertiesKey) {
index 5252e209f78db67fe77c1a19b892275ea3ea3e39..015876ed8b10776792e841f680c2d3b63e775bee 100644 (file)
@@ -13,9 +13,9 @@ import (
 
 // The info dictionary. See BEP 3 and BEP 52.
 type Info struct {
-       PieceLength int64  `bencode:"piece length"` // BEP3
-       Pieces      []byte `bencode:"pieces"`       // BEP3
-       Name        string `bencode:"name"`         // BEP3
+       PieceLength int64  `bencode:"piece length"`     // BEP3
+       Pieces      []byte `bencode:"pieces,omitempty"` // BEP3
+       Name        string `bencode:"name"`             // BEP3
        NameUtf8    string `bencode:"name.utf-8,omitempty"`
        Length      int64  `bencode:"length,omitempty"` // BEP3, mutually exclusive with Files
        ExtendedFileAttrs