-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_test.go
More file actions
518 lines (474 loc) · 15.9 KB
/
client_test.go
File metadata and controls
518 lines (474 loc) · 15.9 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package scdl
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"fmt"
"io"
"net/http"
"os"
"strings"
"testing"
"github.com/bogem/id3v2/v2"
)
// mockTransport allows us to mock HTTP responses
type mockTransport struct {
RoundTripFunc func(req *http.Request) (*http.Response, error)
}
func (m *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return m.RoundTripFunc(req)
}
func TestGetStreamURL(t *testing.T) {
client := &Client{
clientID: "test-client-id",
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
// Check URL structure
if strings.Contains(req.URL.Path, "soundcloud:tracks:123456/ab-cd-ef/stream/hls") {
// Verify query params
q := req.URL.Query()
if q.Get("client_id") != "test-client-id" {
return &http.Response{StatusCode: 400, Body: io.NopCloser(strings.NewReader("bad client_id"))}, nil
}
if q.Get("track_authorization") != "auth-token" {
return &http.Response{StatusCode: 400, Body: io.NopCloser(strings.NewReader("bad auth"))}, nil
}
respJSON := `{"url": "https://cf-hls-media.sndcdn.com/playlist.m3u8"}`
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(respJSON)),
Header: make(http.Header),
}, nil
}
return &http.Response{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader("Not Found")),
}, nil
},
},
},
}
track := &Track{
ID: 123456,
TrackAuthorization: "auth-token",
HLSURL: "https://api-v2.soundcloud.com/media/soundcloud:tracks:123456/ab-cd-ef/stream/hls",
}
url, err := client.GetStreamURL(context.Background(), track)
if err != nil {
t.Fatalf("GetStreamURL() error = %v", err)
}
if url != "https://cf-hls-media.sndcdn.com/playlist.m3u8" {
t.Errorf("got URL %q, want %q", url, "https://cf-hls-media.sndcdn.com/playlist.m3u8")
}
}
func TestExtractClientID(t *testing.T) {
// Simulate:
// 1. GET soundcloud.com -> returns HTML with asset script src
// 2. GET asset script -> returns content with client_id:"xyz"
html := `<html><body><script src="https://a-v2.sndcdn.com/assets/app-123.js"></script></body></html>`
js := `(function(){ bla bla client_id:"my-client-id-123" bla bla })`
client := &Client{
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
if req.URL.String() == "https://soundcloud.com" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(html)),
}, nil
}
if req.URL.String() == "https://a-v2.sndcdn.com/assets/app-123.js" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(js)),
}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found"))}, nil
},
},
},
}
id, err := client.extractClientIDFrom(context.Background(), "https://soundcloud.com")
if err != nil {
t.Fatalf("extractClientID() error = %v", err)
}
if id != "my-client-id-123" {
t.Errorf("got clientID %q, want %q", id, "my-client-id-123")
}
}
func TestNewClient(t *testing.T) {
html := `<html><body><script src="https://a-v2.sndcdn.com/assets/app-123.js"></script></body></html>`
js := `(function(){ bla bla client_id:"my-client-id-123" bla bla })`
transport := &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
if req.URL.String() == "https://mock.com" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(html)),
}, nil
}
if req.URL.String() == "https://a-v2.sndcdn.com/assets/app-123.js" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(js)),
}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found"))}, nil
},
}
httpClient := &http.Client{Transport: transport}
client, err := newClient(context.Background(), "https://mock.com", httpClient)
if err != nil {
t.Fatalf("newClient() error = %v", err)
}
if client.clientID != "my-client-id-123" {
t.Errorf("got clientID %q, want %q", client.clientID, "my-client-id-123")
}
}
func TestNewClient_Direct(t *testing.T) {
// We just want coverage for the wrapper function.
// It's expected to fail in most environments without network.
_, _ = NewClient(context.Background())
}
func TestNewClient_Fail(t *testing.T) {
transport := &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("fail")
},
}
httpClient := &http.Client{Transport: transport}
_, err := newClient(context.Background(), "http://mock", httpClient)
if err == nil {
t.Error("expected error")
}
}
func TestGetError(t *testing.T) {
client := &Client{
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("network error")
},
},
},
}
_, err := client.get(context.Background(), "http://fail")
if err == nil {
t.Error("expected error for network failure")
}
client.httpClient.Transport = &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 500,
Body: io.NopCloser(strings.NewReader("internal error")),
}, nil
},
}
_, err = client.get(context.Background(), "http://500")
if err == nil {
t.Error("expected error for HTTP 500")
}
t.Run("NewRequestError", func(t *testing.T) {
_, err := client.get(context.Background(), ":")
if err == nil {
t.Error("expected error")
}
})
}
func TestExtractClientIDErrors(t *testing.T) {
t.Run("FetchMainFailed", func(t *testing.T) {
client := &Client{
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("fail")
},
},
},
}
_, err := client.extractClientIDFrom(context.Background(), "http://mock")
if err == nil {
t.Error("expected error")
}
})
t.Run("NoAssetsFound", func(t *testing.T) {
client := &Client{
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader("no assets here")),
}, nil
},
},
},
}
_, err := client.extractClientIDFrom(context.Background(), "http://mock")
if err == nil || !strings.Contains(err.Error(), "no asset URLs found") {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("AssetFetchFails", func(t *testing.T) {
html := `<html><body><script src="https://a-v2.sndcdn.com/assets/fail.js"></script></body></html>`
client := &Client{
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
if req.URL.String() == "http://mock" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(html)),
}, nil
}
return nil, fmt.Errorf("asset fail")
},
},
},
}
_, err := client.extractClientIDFrom(context.Background(), "http://mock")
if err == nil || !strings.Contains(err.Error(), "not found in any asset bundle") {
t.Errorf("unexpected error: %v", err)
}
})
}
func TestDownload(t *testing.T) {
// Setup encryption for mock segment
key := []byte("1234567890123456")
iv := make([]byte, 16) // zero IV
playlistContent := []byte("audio content")
// Pad
padding := aes.BlockSize - (len(playlistContent) % aes.BlockSize)
padded := append(playlistContent, bytes.Repeat([]byte{byte(padding)}, padding)...)
// Encrypt
ciphertext := make([]byte, len(padded))
block, _ := aes.NewCipher(key)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, padded)
// M3U8 content
m3u8Content := `#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-KEY:METHOD=AES-128,URI="http://mock/key",IV=0x00000000000000000000000000000000
#EXTINF:10.0,
http://mock/segment.ts
#EXT-X-ENDLIST`
client := &Client{
clientID: "test-client",
httpClient: &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
u := req.URL.String()
if strings.Contains(u, "/stream/hls") {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(`{"url": "http://mock/playlist.m3u8"}`)),
}, nil
}
if u == "http://mock/playlist.m3u8" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(m3u8Content)),
}, nil
}
if u == "http://mock/key" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(key)),
}, nil
}
if u == "http://mock/segment.ts" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(ciphertext)),
}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found: " + u))}, nil
},
},
},
}
track := &Track{
ID: 123,
Title: "MySong",
Artist: "MyArtist",
HLSURL: "https://api-v2.soundcloud.com/media/soundcloud:tracks:123/token/stream/hls",
TrackAuthorization: "auth",
}
outDir := t.TempDir()
outPath, err := client.Download(context.Background(), track, outDir, nil)
if err != nil {
t.Fatalf("Download() error = %v", err)
}
// Verify file name
expectedName := "MyArtist - MySong.mp3"
if !strings.HasSuffix(outPath, expectedName) {
t.Errorf("expected suffix %q, got path %q", expectedName, outPath)
}
// Verify content
content, err := os.ReadFile(outPath)
if err != nil {
t.Fatal(err)
}
// The file should contain "audio content" plus ID3 metadata appended/prepended.
if !bytes.Contains(content, playlistContent) {
t.Errorf("file content missing decrypted audio. Got size %d", len(content))
}
}
func TestDownload_Artwork(t *testing.T) {
// Setup encryption for mock segment (same as TestDownload)
key := []byte("1234567890123456")
iv := make([]byte, 16) // zero IV
playlistContent := []byte("audio content")
padding := aes.BlockSize - (len(playlistContent) % aes.BlockSize)
padded := append(playlistContent, bytes.Repeat([]byte{byte(padding)}, padding)...)
ciphertext := make([]byte, len(padded))
block, _ := aes.NewCipher(key)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, padded)
// M3U8 content
m3u8Content := `#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-KEY:METHOD=AES-128,URI="http://mock/key",IV=0x00000000000000000000000000000000
#EXTINF:10.0,
http://mock/segment.ts
#EXT-X-ENDLIST`
tests := []struct {
name string
artworkURL string
expectArtwork bool
mockTransportFunc func(req *http.Request) (*http.Response, error)
}{
{
name: "Artwork Success",
artworkURL: "http://mock/artwork-large.jpg",
expectArtwork: true,
mockTransportFunc: func(req *http.Request) (*http.Response, error) {
u := req.URL.String()
if u == "http://mock/artwork-t500x500.jpg" { // Replaced URL
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("fake image data"))),
}, nil
}
if strings.Contains(u, "artwork") {
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found"))}, nil
}
// Default handlers
if strings.Contains(u, "/stream/hls") {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"url": "http://mock/playlist.m3u8"}`))}, nil
}
if u == "http://mock/playlist.m3u8" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(m3u8Content))}, nil
}
if u == "http://mock/key" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(key))}, nil
}
if u == "http://mock/segment.ts" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(ciphertext))}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found: " + u))}, nil
},
},
{
name: "Artwork Failure Silent",
artworkURL: "http://mock/artwork-large.jpg",
expectArtwork: false, // Currently fails silently, so we expect NO artwork
mockTransportFunc: func(req *http.Request) (*http.Response, error) {
u := req.URL.String()
if strings.Contains(u, "artwork") {
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found"))}, nil
}
// Default handlers
if strings.Contains(u, "/stream/hls") {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"url": "http://mock/playlist.m3u8"}`))}, nil
}
if u == "http://mock/playlist.m3u8" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(m3u8Content))}, nil
}
if u == "http://mock/key" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(key))}, nil
}
if u == "http://mock/segment.ts" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(ciphertext))}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found: " + u))}, nil
},
},
{
name: "Fallback when Replacement Fails",
artworkURL: "http://mock/artwork-large.jpg",
expectArtwork: true,
mockTransportFunc: func(req *http.Request) (*http.Response, error) {
u := req.URL.String()
// The replaced URL will be tried first
if u == "http://mock/artwork-t500x500.jpg" {
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found"))}, nil
}
// The original URL SHOULD be tried as fallback and succeed
if u == "http://mock/artwork-large.jpg" {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("fake image data"))),
}, nil
}
// Default handlers
if strings.Contains(u, "/stream/hls") {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"url": "http://mock/playlist.m3u8"}`))}, nil
}
if u == "http://mock/playlist.m3u8" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(m3u8Content))}, nil
}
if u == "http://mock/key" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(key))}, nil
}
if u == "http://mock/segment.ts" {
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(ciphertext))}, nil
}
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader("Not Found: " + u))}, nil
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
client := &Client{
clientID: "test-client",
httpClient: &http.Client{
Transport: &mockTransport{RoundTripFunc: tc.mockTransportFunc},
},
}
track := &Track{
ID: 123,
Title: "MySong",
Artist: "MyArtist",
HLSURL: "https://api-v2.soundcloud.com/media/soundcloud:tracks:123/token/stream/hls",
TrackAuthorization: "auth",
ArtworkURL: tc.artworkURL,
}
outDir := t.TempDir()
outPath, err := client.Download(context.Background(), track, outDir, nil)
if err != nil {
t.Fatalf("Download() error = %v", err)
}
// Read tags
tag, err := id3v2.Open(outPath, id3v2.Options{Parse: true})
if err != nil {
t.Fatalf("Error opening tag: %v", err)
}
defer tag.Close()
hasPicture := false
if frames := tag.GetFrames(tag.CommonID("Attached picture")); len(frames) > 0 {
hasPicture = true
}
if tc.expectArtwork && !hasPicture {
t.Error("Expected artwork to be attached, but it was not")
}
if !tc.expectArtwork && hasPicture {
t.Error("Expected no artwork, but it was found")
}
})
}
}