1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package main

import (
	"context"
	"strings"
	"testing"
)

func TestBencodePrimitives(t *testing.T) {
	t.Run("integer", func(t *testing.T) {
		v, err := parseBencode([]byte("i42e"))
		if err != nil {
			t.Fatal(err)
		}
		if v.Int == nil || *v.Int != 42 {
			t.Errorf("got %+v, want 42", v)
		}
	})

	t.Run("negative integer", func(t *testing.T) {
		v, err := parseBencode([]byte("i-7e"))
		if err != nil {
			t.Fatal(err)
		}
		if v.Int == nil || *v.Int != -7 {
			t.Errorf("got %+v, want -7", v)
		}
	})

	t.Run("byte string", func(t *testing.T) {
		v, err := parseBencode([]byte("5:hello"))
		if err != nil {
			t.Fatal(err)
		}
		if string(v.Str) != "hello" {
			t.Errorf("got %q, want hello", v.Str)
		}
	})

	t.Run("empty byte string", func(t *testing.T) {
		v, err := parseBencode([]byte("0:"))
		if err != nil {
			t.Fatal(err)
		}
		if v.Str == nil || len(v.Str) != 0 {
			t.Errorf("got %+v, want an empty non-nil string", v)
		}
	})

	t.Run("binary byte string", func(t *testing.T) {
		// `pieces` is binary; a decoder that assumed UTF-8 would corrupt it.
		data := append([]byte("4:"), 0x00, 0xff, 0x80, 0x01)
		v, err := parseBencode(data)
		if err != nil {
			t.Fatal(err)
		}
		if len(v.Str) != 4 || v.Str[1] != 0xff {
			t.Errorf("binary data was corrupted: % x", v.Str)
		}
	})

	t.Run("list", func(t *testing.T) {
		v, err := parseBencode([]byte("li1ei2ee"))
		if err != nil {
			t.Fatal(err)
		}
		if len(v.List) != 2 {
			t.Fatalf("got %+v, want 2 elements", v.List)
		}
	})

	t.Run("empty list", func(t *testing.T) {
		v, err := parseBencode([]byte("le"))
		if err != nil {
			t.Fatal(err)
		}
		if v.List == nil || len(v.List) != 0 {
			t.Errorf("got %+v, want an empty non-nil list", v)
		}
	})

	t.Run("dict", func(t *testing.T) {
		v, err := parseBencode([]byte("d3:foo3:bare"))
		if err != nil {
			t.Fatal(err)
		}
		if string(v.Dict["foo"].Str) != "bar" {
			t.Errorf("got %+v", v.Dict)
		}
	})

	t.Run("nested", func(t *testing.T) {
		v, err := parseBencode([]byte("d4:infod4:name3:foo5:filesleee"))
		if err != nil {
			t.Fatal(err)
		}
		info := v.Dict["info"]
		if info.Dict == nil || string(info.Dict["name"].Str) != "foo" {
			t.Errorf("got %+v", v)
		}
	})
}

func TestBencodeRejectsMalformed(t *testing.T) {
	for _, in := range []string{
		"",             // empty
		"i42",          // unterminated integer
		"ixe",          // not a number
		"5:abc",        // string shorter than its length
		"-1:x",         // negative length
		"l i1e",        // unterminated list
		"d3:fooe",      // dict key without a value
		"di1ei2ee",     // non-string dict key
		"i1ei2e",       // trailing data
		"x",            // unknown type
		"999999999:ab", // length beyond input
	} {
		if _, err := parseBencode([]byte(in)); err == nil {
			t.Errorf("parseBencode(%q) should have failed", in)
		}
	}
}

func TestParseTorrentFileMultiFile(t *testing.T) {
	// A minimal but realistic multi-file torrent.
	data := []byte("d" +
		"8:announce20:https://example.org/" +
		"13:creation datei1600000000e" +
		"4:infod" +
		"5:filesl" +
		"d6:lengthi100e4:pathl9:01 a.flacee" +
		"d6:lengthi200e4:pathl3:art5:c.jpgee" +
		"e" +
		"4:name9:The Album" +
		"12:piece lengthi262144e" +
		"6:pieces4:aaaa" +
		"7:privatei1e" +
		"e" +
		"e")

	tf, err := parseTorrentFile(data)
	if err != nil {
		t.Fatal(err)
	}
	if tf.Announce != "https://example.org/" {
		t.Errorf("announce = %q", tf.Announce)
	}
	if tf.Info.Name != "The Album" {
		t.Errorf("name = %q", tf.Info.Name)
	}
	if len(tf.Info.Files) != 2 {
		t.Fatalf("got %d files, want 2", len(tf.Info.Files))
	}
	if tf.Info.Files[0].Length != 100 {
		t.Errorf("length = %d, want 100", tf.Info.Files[0].Length)
	}
	// Nested paths must keep their components, since they are joined against
	// the torrent name to address the file on disk.
	if len(tf.Info.Files[1].Path) != 2 || tf.Info.Files[1].Path[0] != "art" {
		t.Errorf("path = %v, want [art c.jpg]", tf.Info.Files[1].Path)
	}
	if tf.Info.PieceLength != 262144 {
		t.Errorf("piece length = %d", tf.Info.PieceLength)
	}
	if tf.Info.Private == nil || !*tf.Info.Private {
		t.Error("private should be true")
	}
	if tf.CreationDate == nil || tf.CreationDate.Unix() != 1600000000 {
		t.Errorf("creation date = %v", tf.CreationDate)
	}

	// The path used to fetch the file must include the torrent directory.
	if got := torrentEntryPath(tf, tf.Info.Files[1]); got != "The Album/art/c.jpg" {
		t.Errorf("torrentEntryPath = %q", got)
	}
}

func TestParseTorrentFileSingleFile(t *testing.T) {
	data := []byte("d8:announce4:http4:infod6:lengthi500e4:name7:one.mp3" +
		"12:piece lengthi16384e6:pieces4:bbbbee")
	tf, err := parseTorrentFile(data)
	if err != nil {
		t.Fatal(err)
	}
	if len(tf.Info.Files) != 1 {
		t.Fatalf("got %d files, want 1 synthesised entry", len(tf.Info.Files))
	}
	if tf.Info.Files[0].Length != 500 || tf.Info.Files[0].Path[0] != "one.mp3" {
		t.Errorf("got %+v", tf.Info.Files[0])
	}
}

func TestLenientText(t *testing.T) {
	// Torrent file names are often in a legacy encoding; they must not cause a
	// decode failure.
	got := lenientText([]byte{0xff, 0xfe, 'a'})
	if !strings.HasSuffix(got, "a") {
		t.Errorf("lenientText mangled the valid part: %q", got)
	}
	if lenientText(nil) != "" {
		t.Error("nil should decode to the empty string")
	}
}

func TestCoverArtPriority(t *testing.T) {
	// Conventional names beat everything.
	if got := findCoverArtInDirectory([]string{"back.jpg", "cover.jpg", "scan.png"}); got != "cover.jpg" {
		t.Errorf("got %q, want cover.jpg", got)
	}
	// "front" beats a bare "cover" mention.
	if got := findCoverArtInDirectory([]string{"albumcover.jpg", "cover-front.jpg"}); got != "cover-front.jpg" {
		t.Errorf("got %q, want cover-front.jpg", got)
	}
	// Any image is better than none.
	if got := findCoverArtInDirectory([]string{"booklet.png"}); got != "booklet.png" {
		t.Errorf("got %q, want booklet.png", got)
	}
	// Non-images are not cover art.
	if got := findCoverArtInDirectory([]string{"01.flac", "info.txt"}); got != "" {
		t.Errorf("got %q, want no cover art", got)
	}
	// Case does not matter.
	if got := findCoverArtInDirectory([]string{"COVER.JPG"}); got != "COVER.JPG" {
		t.Errorf("got %q", got)
	}
}

func TestFindAudioFiles(t *testing.T) {
	files := []torrentFileEntry{
		{Path: []string{"cover.jpg"}},
		{Path: []string{"01 - song.FLAC"}},
		{Path: []string{"notes.txt"}},
		{Path: []string{"disc2", "02 - song.mp3"}},
	}
	audio := findAudioFiles(files)
	if len(audio) != 2 {
		t.Fatalf("got %d audio files, want 2", len(audio))
	}
	// The index must be the position in the full file list, because it is the
	// file id used by the streaming endpoint.
	if audio[0].Index != 1 || audio[1].Index != 3 {
		t.Errorf("indices = %d, %d; want 1, 3", audio[0].Index, audio[1].Index)
	}
}

func TestPercentage(t *testing.T) {
	for _, c := range []struct {
		in   float64
		want int
	}{
		{0, 0},
		{1, 100},
		{0.5, 50},
		{0.001, 1},   // any progress at all must not display as 0%
		{0.999, 100}, // ...but rounding up must not exceed 100
		{-1, 0},
		{2, 100},
	} {
		if got := percentage(c.in); got != c.want {
			t.Errorf("percentage(%v) = %d, want %d", c.in, got, c.want)
		}
	}
}

// TestBencodeAgainstRealTorrents decodes every .torrent stored in the
// development database.
//
// This is the real test of the decoder: these files were produced by the
// tracker and include the encoding quirks that synthetic tests do not have.
func TestBencodeAgainstRealTorrents(t *testing.T) {
	ctx := context.Background()
	pool, err := connectDB(ctx, devDSN(t))
	if err != nil {
		t.Fatal(err)
	}
	defer pool.Close()

	rows, err := pool.Query(ctx, `
		SELECT torrent_id, torrent_file
		FROM redacted.torrents_json
		WHERE torrent_file IS NOT NULL`)
	if err != nil {
		t.Fatal(err)
	}
	defer rows.Close()

	var checked, withCover, withAudio int
	for rows.Next() {
		var id int
		var raw []byte
		if err := rows.Scan(&id, &raw); err != nil {
			t.Fatal(err)
		}
		tf, err := parseTorrentFile(raw)
		if err != nil {
			t.Errorf("torrent %d: %v", id, err)
			continue
		}
		checked++

		if tf.Info.Name == "" {
			t.Errorf("torrent %d: empty name", id)
		}
		if len(tf.Info.Files) == 0 {
			t.Errorf("torrent %d (%s): no files", id, tf.Info.Name)
		}
		// pieces is a concatenation of 20-byte SHA-1 hashes; a length that is
		// not a multiple of 20 means the byte-string handling is wrong.
		if len(tf.Info.Pieces)%20 != 0 {
			t.Errorf("torrent %d: pieces length %d is not a multiple of 20",
				id, len(tf.Info.Pieces))
		}

		var topLevel []string
		for _, f := range tf.Info.Files {
			if len(f.Path) == 1 {
				topLevel = append(topLevel, f.Path[0])
			}
		}
		if findCoverArtInDirectory(topLevel) != "" {
			withCover++
		}
		if len(findAudioFiles(tf.Info.Files)) > 0 {
			withAudio++
		}
	}
	if err := rows.Err(); err != nil {
		t.Fatal(err)
	}

	if checked == 0 {
		t.Skip("no torrent files in the development database")
	}
	t.Logf("decoded %d real torrent files: %d with cover art, %d with audio",
		checked, withCover, withAudio)

	// Every torrent here came from a music tracker, so a torrent with no audio
	// file would mean findAudioFiles is missing an extension.
	if withAudio != checked {
		t.Errorf("%d of %d torrents had no recognised audio file", checked-withAudio, checked)
	}
}