From 3c9e4fa540fed16aaa823b1bb813bb73faebb575 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Mon, 4 Jul 2016 12:17:40 +0200 Subject: wip --- meta/torrent.go | 31 +++++++++++++++++++++++++++++++ meta/torrent_test.go | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/meta/torrent.go b/meta/torrent.go index 002480c..9720b34 100644 --- a/meta/torrent.go +++ b/meta/torrent.go @@ -19,6 +19,11 @@ type File struct { Path []string `bencode:"path"` } +type Piece struct { + Length int + CheckSum [sha1.Size]byte +} + type Info struct { Files []File `bencode:"files"` Length int `bencode:"length"` @@ -29,6 +34,27 @@ type Info struct { Private bool `bencode:"private"` } +func (i Info) pieces() []Piece { + for _, f := range i.Files { + i.Length += f.Length + } + n := i.Length / i.PieceLength + l := i.Length % i.PieceLength + if l > 0 { + n++ + } + p := make([]Piece, n) + for k := 0; k < n; k++ { + p[k].Length = i.PieceLength + if k+1 == n && l > 0 { + p[k].Length = l + } + off := k * sha1.Size + copy(p[k].CheckSum[:], i.Pieces[off:off+sha1.Size]) + } + return p +} + func (i Info) NPieces() int { return len(i.Pieces) / sha1.Size } @@ -152,6 +178,11 @@ func (i Info) isSingleFile() bool { // PieceCount returns count of full pieces and size of last piece func (i Info) PieceCount() (int, int) { + if i.Length == 0 { + for _, f := range i.Files { + i.Length += f.Length + } + } return i.Length / i.PieceLength, i.Length % i.PieceLength } diff --git a/meta/torrent_test.go b/meta/torrent_test.go index 5f304d5..df629d3 100644 --- a/meta/torrent_test.go +++ b/meta/torrent_test.go @@ -1,5 +1,12 @@ package meta +import ( + "io/ioutil" + "testing" + + "dim13.org/btget/bencode" +) + var tors = map[string]string{ "bsd": "OpenBSD_5.9_amd64_install59.iso-2016-03-29-0449.torrent", "ogg": "OpenBSD_songs_ogg-2016-03-25-0127.torrent", @@ -7,7 +14,19 @@ var tors = map[string]string{ "mul": "multi.torrent", } -/* +func Open(fname string) (Torrent, error) { + var tor Torrent + body, err := ioutil.ReadFile(fname) + if err != nil { + return Torrent{}, err + } + err = bencode.Unmarshal(body, &tor) + if err != nil { + return Torrent{}, err + } + return tor, nil +} + func TestPieces(t *testing.T) { tor, err := Open("../examples/" + tors["mul"]) if err != nil { @@ -18,4 +37,13 @@ func TestPieces(t *testing.T) { t.Log(n, off) } } -*/ + +func TestPieces2(t *testing.T) { + tor, err := Open("../examples/" + tors["mul"]) + if err != nil { + t.Error(err) + } + for i, p := range tor.Info.pieces() { + t.Logf("%d %x\n", i, p) + } +} -- cgit v1.2.3