-
Notifications
You must be signed in to change notification settings - Fork 106
/
pollingTracks.test.js
1256 lines (1109 loc) · 38.6 KB
/
pollingTracks.test.js
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const request = require('supertest')
const fs = require('fs')
const path = require('path')
const assert = require('assert')
const sinon = require('sinon')
const uuid = require('uuid/v4')
const proxyquire = require('proxyquire')
const _ = require('lodash')
const config = require('../src/config')
const defaultConfig = require('../default-config.json')
const BlacklistManager = require('../src/blacklistManager')
const TranscodingQueue = require('../src/TranscodingQueue')
const models = require('../src/models')
const DiskManager = require('../src/diskManager')
const FileManager = require('../src/fileManager')
const DBManager = require('../src/dbManager.js')
const { getApp } = require('./lib/app')
const {
createStarterCNodeUser,
testEthereumConstants
} = require('./lib/dataSeeds')
const { getLibsMock } = require('./lib/libsMock')
const { sortKeys } = require('../src/apiSigning')
const { saveFileToStorage, computeFilesHash } = require('./lib/helpers')
const testAudioFilePath = path.resolve(__dirname, 'testTrack.mp3')
const testAudioFileWrongFormatPath = path.resolve(
__dirname,
'testTrackWrongFormat.jpg'
)
const TestAudiusTrackFileNumSegments = 32
const TRACK_CONTENT_POLLING_ROUTE = '/track_content_async'
const logContext = {
logContext: {
requestID: uuid(),
requestMethod: 'POST',
requestHostname: '127.0.0.1',
requestUrl: TRACK_CONTENT_POLLING_ROUTE
}
}
// Create the req context for handleTrackContentRoute
function getReqObj(fileUUID, fileDir, session) {
return {
fileName: `${fileUUID}.mp3`,
fileDir,
fileDestination: fileDir,
cnodeUserUUID: session.cnodeUserUUID
}
}
/**
* Given index of segment, returns filepath of expected segment file in /test/test-segments/ dir
* TODO - instead of using ./test/test-segments, use ./test/testTrackUploadDir
*/
function _getTestSegmentFilePathAtIndex(index) {
let suffix = '000'
if (index >= 0 && index < 10) suffix += `0${index}`
else if (index >= 10 && index < 32) suffix += `${index}`
else throw new Error('Index must be [0, 32)')
return path.join(__dirname, 'test-segments', `segment${suffix}.ts`)
}
describe('test Polling Tracks with mocked IPFS', function () {
let app,
server,
libsMock,
handleTrackContentRoute
let session, userId, userWallet
const spId = 1
beforeEach(async () => {
libsMock = getLibsMock()
userId = 1
userWallet = testEthereumConstants.pubKey.toLowerCase()
const { getApp } = require('./lib/app')
const appInfo = await getApp(libsMock, BlacklistManager, null, spId)
await BlacklistManager.init()
app = appInfo.app
server = appInfo.server
session = await createStarterCNodeUser(userId, userWallet)
// Mock `generateNonImageCid()` in `handleTrackContentRoute()` to succeed
const mockCid = 'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
;({ handleTrackContentRoute } = proxyquire(
'../src/components/tracks/tracksComponentService.js',
{
'@audius/sdk': {
libs: {
Utils: {
fileHasher: {
generateNonImageCid: sinon.stub().returns(
new Promise((resolve) => {
return resolve(mockCid)
})
)
}
}
},
'@global': true
},
'../../fileManager': {
copyMultihashToFs: sinon
.stub(FileManager, 'copyMultihashToFs')
.returns(
new Promise((resolve) => {
const dstPath = DiskManager.computeFilePath(mockCid)
return resolve(dstPath)
})
),
'@global': true
}
}
))
})
afterEach(async () => {
sinon.restore()
await server.close()
})
// Testing middleware -- leave as /track_content_async
it('fails to upload when format is not accepted', async function () {
const file = fs.readFileSync(testAudioFileWrongFormatPath)
await request(app)
.post(TRACK_CONTENT_POLLING_ROUTE)
.attach('file', file, { filename: 'fname.jpg' })
.set('Content-Type', 'multipart/form-data')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.expect(400)
})
// Testing middleware -- leave as /track_content_async
it('fails to upload when maxAudioFileSizeBytes exceeded', async function () {
// Configure extremely small file size
process.env.maxAudioFileSizeBytes = 10
// Reset app
await server.close()
const appInfo = await getApp(libsMock, BlacklistManager, null, userId)
app = appInfo.app
server = appInfo.server
session = await createStarterCNodeUser(userId)
// Confirm max audio file size is respected by multer
const file = fs.readFileSync(testAudioFilePath)
await request(app)
.post(TRACK_CONTENT_POLLING_ROUTE)
.attach('file', file, { filename: 'fname.mp3' })
.set('Content-Type', 'multipart/form-data')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.expect(400)
// Reset max file limits
process.env.maxAudioFileSizeBytes = defaultConfig.maxAudioFileSizeBytes
})
it('fails to upload when maxMemoryFileSizeBytes exceeded', async function () {
// Configure extremely small file size
process.env.maxMemoryFileSizeBytes = 10
// Reset app
await server.close()
const appInfo = await getApp(libsMock, BlacklistManager, null, userId)
app = appInfo.app
server = appInfo.server
session = await createStarterCNodeUser(userId)
// Confirm max audio file size is respected by multer
const file = fs.readFileSync(testAudioFileWrongFormatPath)
await request(app)
.post('/image_upload')
.attach('file', file, { filename: 'fname.jpg' })
.set('Content-Type', 'multipart/form-data')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.expect(500)
// Reset max file limits
process.env.maxMemoryFileSizeBytes = defaultConfig.maxMemoryFileSizeBytes
})
it('uploads /track_content_async', async function () {
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const {
track_segments: trackSegments,
source_file: sourceFile,
transcodedTrackCID,
transcodedTrackUUID
} = resp
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
assert.deepStrictEqual(sourceFile.includes('.mp3'), true)
assert.deepStrictEqual(
transcodedTrackCID,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(typeof transcodedTrackUUID, 'string')
})
// depends on "uploads /track_content_async"
it('Confirm /users/clock_status works with user and track state', async function () {
const numExpectedFilesForUser = TestAudiusTrackFileNumSegments + 1 // numSegments + 320kbps copy
/** Upload track */
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
let resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const wallet = session.walletPublicKey
// Confirm /users/clock_status returns expected info
resp = await request(app).get(`/users/clock_status/${wallet}`).expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false
})
// Confirm /users/clock_status returns expected info with returnSkipInfo flag
resp = await request(app)
.get(`/users/clock_status/${wallet}?returnSkipInfo=true`)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
CIDSkipInfo: { numCIDs: numExpectedFilesForUser, numSkippedCIDs: 0 }
})
// Update track DB entries to be skipped
const numAffectedRows = (
await models.File.update(
{ skipped: true },
{
where: {
cnodeUserUUID: session.cnodeUserUUID,
type: 'track'
}
}
)
)[0]
assert.strictEqual(numAffectedRows, TestAudiusTrackFileNumSegments)
// Confirm /users/clock_status returns expected info with returnSkipInfo flag when some entries are skipped
resp = await request(app)
.get(`/users/clock_status/${wallet}?returnSkipInfo=true`)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
CIDSkipInfo: {
numCIDs: numExpectedFilesForUser,
numSkippedCIDs: TestAudiusTrackFileNumSegments
}
})
const files = await models.File.findAll({
where: { cnodeUserUUID: session.cnodeUserUUID }
})
const filesSorted = _.sortBy(files, ['clock'], ['asc'])
const multihashesSorted = filesSorted.map((file) => file.multihash)
// Confirm /users/clock_status returns expected info with `returnFilesHash` flag
const expectedFilesHashFull = computeFilesHash(multihashesSorted)
resp = await request(app)
.get(`/users/clock_status/${wallet}?returnFilesHash=true`)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull
})
/** Confirm /users/clock_status returns expected info with `returnsFilesHash` and clock range specified */
const clockMin = 3
const clockMax = 8
/** clockMin */
const expectedFilesHashClockMin = computeFilesHash(multihashesSorted
.slice(clockMin - 1))
resp = await request(app)
.get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMin=${clockMin}`
)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: expectedFilesHashClockMin
})
/** clockMax */
const expectedFilesHashClockMax = computeFilesHash(multihashesSorted
.slice(0, clockMax - 1))
resp = await request(app)
.get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMax=${clockMax}`
)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: expectedFilesHashClockMax
})
/** clockMin and clockMax */
let expectedFilesHashClockRange = computeFilesHash(multihashesSorted
.slice(clockMin - 1, clockMax - 1))
resp = await request(app)
.get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMin=${clockMin}&filesHashClockRangeMax=${clockMax}`
)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: expectedFilesHashClockRange
})
/** clockMinTooHigh */
const clockMinTooHigh = numExpectedFilesForUser + 5
resp = await request(app).get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMin=${clockMinTooHigh}`
)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: null
})
/** clockMaxTooLow */
const clockMaxTooLow = -5
resp = await request(app).get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMax=${clockMaxTooLow}`
)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: null
})
/** partially overlapping clockrange */
const clockMaxTooHigh = numExpectedFilesForUser + 5
expectedFilesHashClockRange = computeFilesHash(
multihashesSorted.slice(clockMin - 1, clockMaxTooHigh - 1)
)
resp = await request(app)
.get(
`/users/clock_status/${wallet}?returnFilesHash=true&filesHashClockRangeMin=${clockMin}&filesHashClockRangeMax=${clockMaxTooHigh}`
)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: numExpectedFilesForUser,
syncInProgress: false,
filesHash: expectedFilesHashFull,
filesHashForClockRange: expectedFilesHashClockRange
})
/** Non-existent user */
const invalidWallet = 'asdf'
resp = await request(app)
.get(`/users/clock_status/${invalidWallet}`)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: -1,
syncInProgress: false
})
/** Non-existent user, returnFilesHash = true */
resp = await request(app)
.get(`/users/clock_status/${invalidWallet}?returnFilesHash=true`)
.expect(200)
assert.deepStrictEqual(resp.body.data, {
clockValue: -1,
syncInProgress: false,
filesHash: null
})
})
it('Confirms /users/batch_clock_status works with user and track state for 2 users', async () => {
const numExpectedFilesForUser = TestAudiusTrackFileNumSegments + 1 // numSegments + 320kbps copy
/** Upload track for user 1 */
const { fileUUID: fileUUID1, fileDir: fileDir1 } =
saveFileToStorage(testAudioFilePath)
await handleTrackContentRoute(
logContext,
getReqObj(fileUUID1, fileDir1, session)
)
// Compute expected filesHash for user1
const expectedUser1FilesHash = await DBManager.fetchFilesHashFromDB({
lookupKey: { lookupWallet: userWallet }
})
// Create user 2
const userId2 = 2
const pubKey2 = '0xadD36bad12002f1097Cdb7eE24085C28e9random'
const session2 = await createStarterCNodeUser(userId2, pubKey2)
/** Upload track for user 2 */
const { fileUUID: fileUUID2, fileDir: fileDir2 } =
saveFileToStorage(testAudioFilePath)
await handleTrackContentRoute(
logContext,
getReqObj(fileUUID2, fileDir2, session2)
)
const expectedUser2FilesHash = await DBManager.fetchFilesHashFromDB({
lookupKey: { lookupWallet: pubKey2 }
})
// Confirm /users/batch_clock_status returns expected info
let resp = await request(app)
.post(`/users/batch_clock_status`)
.send({ walletPublicKeys: [userWallet, pubKey2] })
.expect(200)
assert.deepStrictEqual(resp.body.data, {
users: [
{ walletPublicKey: userWallet, clock: numExpectedFilesForUser },
{ walletPublicKey: pubKey2, clock: numExpectedFilesForUser }
]
})
// Requests with too many wallet keys should be rejected
const maxNumWallets = config.get('maxBatchClockStatusBatchSize')
const largeWalletPublicKeys = Array.from(
{ length: maxNumWallets + 1 },
(_, i) => i + 'a'
)
resp = await request(app)
.post(`/users/batch_clock_status`)
.send({ walletPublicKeys: largeWalletPublicKeys })
.expect(400, {
error: `Number of wallets must not exceed ${maxNumWallets} (reduce 'walletPublicKeys' field in request body).`
})
/** Non-existent user */
const invalidWallet = 'asdf'
resp = await request(app)
.post(`/users/batch_clock_status`)
.send({ walletPublicKeys: [userWallet, invalidWallet] })
.expect(200)
assert.deepStrictEqual(resp.body.data, {
users: [
{ walletPublicKey: userWallet, clock: numExpectedFilesForUser },
{ walletPublicKey: invalidWallet, clock: -1 }
]
})
/** returnFilesHash = true */
resp = await request(app)
.post(`/users/batch_clock_status?returnFilesHash=true`)
.send({ walletPublicKeys: [userWallet, pubKey2] })
.expect(200)
assert.deepStrictEqual(resp.body.data, {
users: [
{
walletPublicKey: userWallet,
clock: numExpectedFilesForUser,
filesHash: expectedUser1FilesHash
},
{
walletPublicKey: pubKey2,
clock: numExpectedFilesForUser,
filesHash: expectedUser2FilesHash
}
]
})
/** returnFilesHash = true, invalid user */
resp = await request(app)
.post(`/users/batch_clock_status?returnFilesHash=true`)
.send({ walletPublicKeys: [userWallet, invalidWallet] })
.expect(200)
assert.deepStrictEqual(resp.body.data, {
users: [
{
walletPublicKey: userWallet,
clock: numExpectedFilesForUser,
filesHash: expectedUser1FilesHash
},
{ walletPublicKey: invalidWallet, clock: -1, filesHash: null }
]
})
})
// depends on "uploads /track_content_async"; if that test fails, this test will fail to due to similarity
it('creates Audius track using application logic for /track_content_async', async function () {
libsMock.User.getUsers.exactly(2)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { track_segments: trackSegments, source_file: sourceFile } = resp
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
assert.deepStrictEqual(sourceFile.includes('.mp3'), true)
// creates Audius track
const metadata = {
test: 'field1',
owner_id: 1,
track_segments: trackSegments
}
const trackMetadataResp = await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata, sourceFile })
.expect(200)
assert.deepStrictEqual(
trackMetadataResp.body.data.metadataMultihash,
'QmYhusD7qFv7gxNqi9nyaoiqaRXYQvoCvVgXY75nSoydmy'
)
})
// depends on "uploads /track_content_async"
it('fails to create Audius track when segments not provided', async function () {
libsMock.User.getUsers.exactly(2)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { track_segments: trackSegments, source_file: sourceFile } = resp
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
assert.deepStrictEqual(sourceFile.includes('.mp3'), true)
// creates Audius track
const metadata = {
test: 'field1',
owner_id: 1
}
await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata, sourceFile })
.expect(400)
})
// depends on "uploads /track_content_async"
it('fails to create Audius track when invalid segment multihashes are provided', async function () {
libsMock.User.getUsers.exactly(2)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { track_segments: trackSegments, source_file: sourceFile } = resp
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
assert.deepStrictEqual(sourceFile.includes('.mp3'), true)
// creates Audius track
const metadata = {
test: 'field1',
track_segments: [{ multihash: 'incorrectCIDLink', duration: 1000 }],
owner_id: 1
}
await request(app)
.post('/tracks')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.send({ metadata, sourceFile })
.expect(400)
})
// depends on "uploads /track_content_async"
it('fails to create Audius track when owner_id is not provided', async function () {
libsMock.User.getUsers.exactly(2)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { source_file: sourceFile } = resp
// creates Audius track
const metadata = {
test: 'field1',
track_segments: [
{
multihash: 'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6',
duration: 1000
}
]
}
await request(app)
.post('/tracks')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.send({ metadata, sourceFile })
.expect(400)
})
// depends on "uploads /track_content_async" and "creates Audius track" tests
it('completes Audius track creation', async function () {
libsMock.User.getUsers.exactly(4)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const {
track_segments: trackSegments,
source_file: sourceFile,
transcodedTrackUUID
} = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const metadata = {
test: 'field1',
track_segments: trackSegments,
owner_id: 1
}
const trackMetadataResp = await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata, sourceFile })
.expect(200)
assert.deepStrictEqual(
trackMetadataResp.body.data.metadataMultihash,
'QmTWhw49RfSMSJJmfm8cMHFBptgWoBGpNwjAc5jy2qeJfs'
)
// Make chain recognize wallet as owner of track
const blockchainTrackId = 1
const getTrackStub = sinon.stub().callsFake((_, __, trackIds) => {
let trackOwnerId = -1
if (trackIds[0] === blockchainTrackId) {
trackOwnerId = userId
}
return [
{
blocknumber: 99999,
owner_id: trackOwnerId
}
]
})
libsMock.Track = { getTracks: getTrackStub }
await request(app)
.post('/tracks')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.send({
blockchainTrackId,
blockNumber: 10,
metadataFileUUID: trackMetadataResp.body.data.metadataFileUUID,
transcodedTrackUUID
})
.expect(200)
})
// depends on "uploads /track_content_async" and "creates Audius track" tests
it('fails Audius track creation when passing track ID that mismatches on-chain track ID', async function () {
libsMock.User.getUsers.exactly(4)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const {
track_segments: trackSegments,
source_file: sourceFile,
transcodedTrackUUID
} = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const metadata = {
test: 'field1',
track_segments: trackSegments,
owner_id: 1
}
const trackMetadataResp = await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata, sourceFile })
.expect(200)
assert.deepStrictEqual(
trackMetadataResp.body.data.metadataMultihash,
'QmTWhw49RfSMSJJmfm8cMHFBptgWoBGpNwjAc5jy2qeJfs'
)
// Make chain NOT recognize wallet as owner of track
const blockchainTrackId = 1
const getTrackStub = sinon.stub().resolves([
{
blocknumber: 0,
owner_id: -1
}
])
libsMock.Track = { getTracks: getTrackStub }
await request(app)
.post('/tracks')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.send({
blockchainTrackId,
blockNumber: 10,
metadataFileUUID: trackMetadataResp.body.data.metadataFileUUID,
transcodedTrackUUID
})
.expect(500)
})
// depends on "uploads /track_content_async"
it('fails to create downloadable track with no track_id and no source_id present', async function () {
libsMock.User.getUsers.exactly(2)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { track_segments: trackSegments } = resp
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
// creates a downloadable Audius track with no track_id and no source_file
const metadata = {
test: 'field1',
owner_id: 1,
track_segments: [
{
multihash: 'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6',
duration: 1000
}
],
download: {
is_downloadable: true,
requires_follow: false
}
}
await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata })
.expect(400)
})
// depends on "uploads /track_content_async" and "creates Audius track" tests
it('creates a downloadable track', async function () {
libsMock.User.getUsers.exactly(4)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const {
track_segments: trackSegments,
source_file: sourceFile,
transcodedTrackUUID
} = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
assert.deepStrictEqual(
trackSegments[0].multihash,
'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
)
assert.deepStrictEqual(trackSegments.length, 32)
assert.deepStrictEqual(sourceFile.includes('.mp3'), true)
// needs debugging as to why this 'cid' key is needed for test to work
const metadata = {
test: 'field1',
track_segments: trackSegments,
owner_id: 1,
download: {
is_downloadable: true,
requires_follow: false,
cid: 'QmYfSQCgCwhxwYcdEwCkFJHicDe6rzCAb7AtLz3GrHmuU6'
}
}
const trackMetadataResp = await request(app)
.post('/tracks/metadata')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.set('Enforce-Write-Quorum', false)
.send({ metadata, sourceFile })
.expect(200)
assert.deepStrictEqual(
trackMetadataResp.body.data.metadataMultihash,
'QmPjrvx9MBcvf495t43ZhiMpKWwu1JnqkcNUN3Z9EBWm49'
)
// Make chain recognize wallet as owner of track
const blockchainTrackId = 1
const getTrackStub = sinon.stub().callsFake((_, __, trackIds) => {
let trackOwnerId = -1
if (trackIds[0] === blockchainTrackId) {
trackOwnerId = userId
}
return [
{
blocknumber: 99999,
owner_id: trackOwnerId
}
]
})
libsMock.Track = { getTracks: getTrackStub }
await request(app)
.post('/tracks')
.set('X-Session-ID', session.sessionToken)
.set('User-Id', session.userId)
.send({
blockchainTrackId,
blockNumber: 10,
metadataFileUUID: trackMetadataResp.body.data.metadataFileUUID,
transcodedTrackUUID
})
.expect(200)
})
})
describe('test Polling Tracks with real files', function () {
let app2, server, session, libsMock, handleTrackContentRoute, userId
/** Inits libs mock, web server app, blacklist manager, and creates starter CNodeUser */
beforeEach(async () => {
libsMock = getLibsMock()
userId = 1
const { getApp } = require('./lib/app')
const appInfo = await getApp(libsMock, BlacklistManager, null, userId)
await BlacklistManager.init()
app2 = appInfo.app
server = appInfo.server
session = await createStarterCNodeUser(userId)
handleTrackContentRoute =
require('../src/components/tracks/tracksComponentService').handleTrackContentRoute
})
/** Reset sinon & close server */
afterEach(async () => {
sinon.restore()
await server.close()
})
// ~~~~~~~~~~~~~~~~~~~~~~~~~ /track_content_async TESTS ~~~~~~~~~~~~~~~~~~~~~~~~~
it('sends server error response if segmenting fails', async function () {
const { handleTrackContentRoute } = proxyquire(
'../src/components/tracks/tracksComponentService.js',
{
'../../TranscodingQueue': {
segment: sinon
.stub(TranscodingQueue, 'segment')
.rejects(new Error('failed to segment')),
'@global': true
}
}
)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
try {
await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
assert.fail('Should have thrown error if segmenting failed')
} catch (e) {
assert.ok(e.message.includes('failed to segment'))
}
})
it('sends server error response if transcoding fails', async function () {
const { handleTrackContentRoute } = proxyquire(
'../src/components/tracks/tracksComponentService.js',
{
'../../TranscodingQueue': {
transcode320: sinon
.stub(TranscodingQueue, 'transcode320')
.rejects(new Error('failed to transcode')),
'@global': true
}
}
)
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
try {
await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
assert.fail('Should have thrown error if transcoding failed')
} catch (e) {
assert.ok(e.message.includes('failed to transcode'))
}
})
it('should successfully upload track + transcode and prune upload artifacts when TranscodingQueue is available', async function () {
const { fileUUID, fileDir } = saveFileToStorage(testAudioFilePath)
const resp = await handleTrackContentRoute(
logContext,
getReqObj(fileUUID, fileDir, session)
)
const { track_segments: trackSegments, transcodedTrackCID } = resp
// check that the generated transcoded track is the same as the transcoded track in /tests
const transcodedTrackAssetPath = path.join(
__dirname,
'testTranscoded320Track.mp3'
)
const transcodedTrackAssetBuf = fs.readFileSync(transcodedTrackAssetPath)
const transcodedTrackPath = DiskManager.computeFilePath(transcodedTrackCID)
const transcodedTrackTestBuf = fs.readFileSync(transcodedTrackPath)
assert.deepStrictEqual(
transcodedTrackAssetBuf.compare(transcodedTrackTestBuf),
0
)
// Ensure 32 segments are returned, each segment has a corresponding file on disk,
// and each segment disk file is exactly as expected
// Note - The exact output of track segmentation is deterministic only for a given environment/ffmpeg version
// This test may break in the future but at that point we should re-generate the reference segment files.
assert.deepStrictEqual(trackSegments.length, TestAudiusTrackFileNumSegments)
trackSegments.map(function (cid, index) {
const cidPath = DiskManager.computeFilePath(cid.multihash)
// Ensure file exists
assert.ok(fs.existsSync(cidPath))