From baca561f06b55b4ed985addb16bb4c2578399f4a Mon Sep 17 00:00:00 2001 From: mutantmonkey Date: Tue, 29 Sep 2015 20:12:50 -0700 Subject: [PATCH] fix torrent creation for binary data and refactor --- torrent.go | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/torrent.go b/torrent.go index 33714cb..5235c35 100644 --- a/torrent.go +++ b/torrent.go @@ -20,7 +20,7 @@ const ( type TorrentInfo struct { PieceLength int `bencode:"piece length"` - Pieces []byte `bencode:"pieces"` + Pieces string `bencode:"pieces"` Name string `bencode:"name"` Length int `bencode:"length"` } @@ -31,10 +31,23 @@ type Torrent struct { UrlList []string `bencode:"url-list"` } +func hashPiece(piece []byte) []byte { + h := sha1.New() + h.Write(piece) + return h.Sum(nil) +} + func CreateTorrent(fileName string, filePath string) ([]byte, error) { chunk := make([]byte, TORRENT_PIECE_LENGTH) - var pieces []byte - length := 0 + + torrent := Torrent{ + Encoding: "UTF-8", + Info: TorrentInfo{ + PieceLength: TORRENT_PIECE_LENGTH, + Name: fileName, + }, + UrlList: []string{fmt.Sprintf("%sselif/%s", Config.siteURL, fileName)}, + } f, err := os.Open(filePath) if err != nil { @@ -49,27 +62,13 @@ func CreateTorrent(fileName string, filePath string) ([]byte, error) { return []byte{}, err } - length += n - - h := sha1.New() - h.Write(chunk) - pieces = append(pieces, h.Sum(nil)...) + torrent.Info.Length += n + torrent.Info.Pieces += string(hashPiece(chunk[:n])) } f.Close() - torrent := &Torrent{ - Encoding: "UTF-8", - Info: TorrentInfo{ - PieceLength: TORRENT_PIECE_LENGTH, - Pieces: pieces, - Name: fileName, - Length: length, - }, - UrlList: []string{fmt.Sprintf("%sselif/%s", Config.siteURL, fileName)}, - } - - data, err := bencode.EncodeBytes(torrent) + data, err := bencode.EncodeBytes(&torrent) if err != nil { return []byte{}, err }