1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
3 import { expect } from 'chai'
4 import { pathExists, readdir, readFile } from 'fs-extra'
5 import * as parseTorrent from 'parse-torrent'
6 import { extname, join } from 'path'
7 import * as request from 'supertest'
9 buildAbsoluteFixturePath,
19 import validator from 'validator'
20 import { VideoDetails, VideoPrivacy } from '../../models/videos'
21 import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, loadLanguages, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants'
22 import { dateIsValid, webtorrentAdd, buildServerDirectory } from '../miscs/miscs'
26 type VideoAttributes = {
32 commentsEnabled?: boolean
33 downloadEnabled?: boolean
34 waitTranscoding?: boolean
36 originallyPublishedAt?: string
39 privacy?: VideoPrivacy
41 thumbnailfile?: string
45 privacy?: VideoPrivacy
49 function getVideoCategories (url: string) {
50 const path = '/api/v1/videos/categories'
52 return makeGetRequest({
55 statusCodeExpected: 200
59 function getVideoLicences (url: string) {
60 const path = '/api/v1/videos/licences'
62 return makeGetRequest({
65 statusCodeExpected: 200
69 function getVideoLanguages (url: string) {
70 const path = '/api/v1/videos/languages'
72 return makeGetRequest({
75 statusCodeExpected: 200
79 function getVideoPrivacies (url: string) {
80 const path = '/api/v1/videos/privacies'
82 return makeGetRequest({
85 statusCodeExpected: 200
89 function getVideo (url: string, id: number | string, expectedStatus = 200) {
90 const path = '/api/v1/videos/' + id
94 .set('Accept', 'application/json')
95 .expect(expectedStatus)
98 function getVideoFileMetadataUrl (url: string) {
101 .set('Accept', 'application/json')
103 .expect('Content-Type', /json/)
106 function viewVideo (url: string, id: number | string, expectedStatus = 204, xForwardedFor?: string) {
107 const path = '/api/v1/videos/' + id + '/views'
109 const req = request(url)
111 .set('Accept', 'application/json')
114 req.set('X-Forwarded-For', xForwardedFor)
117 return req.expect(expectedStatus)
120 function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = 200) {
121 const path = '/api/v1/videos/' + id
125 .set('Authorization', 'Bearer ' + token)
126 .set('Accept', 'application/json')
127 .expect(expectedStatus)
130 function getVideoDescription (url: string, descriptionPath: string) {
132 .get(descriptionPath)
133 .set('Accept', 'application/json')
135 .expect('Content-Type', /json/)
138 function getVideosList (url: string) {
139 const path = '/api/v1/videos'
143 .query({ sort: 'name' })
144 .set('Accept', 'application/json')
146 .expect('Content-Type', /json/)
149 function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) {
150 const path = '/api/v1/videos'
154 .set('Authorization', 'Bearer ' + token)
155 .query(immutableAssign(query, { sort: 'name' }))
156 .set('Accept', 'application/json')
158 .expect('Content-Type', /json/)
161 function getLocalVideos (url: string) {
162 const path = '/api/v1/videos'
166 .query({ sort: 'name', filter: 'local' })
167 .set('Accept', 'application/json')
169 .expect('Content-Type', /json/)
172 function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string, search?: string) {
173 const path = '/api/v1/users/me/videos'
175 const req = request(url)
177 .query({ start: start })
178 .query({ count: count })
179 .query({ search: search })
181 if (sort) req.query({ sort })
183 return req.set('Accept', 'application/json')
184 .set('Authorization', 'Bearer ' + accessToken)
186 .expect('Content-Type', /json/)
189 function getAccountVideos (
196 query: { nsfw?: boolean } = {}
198 const path = '/api/v1/accounts/' + accountName + '/videos'
200 return makeGetRequest({
203 query: immutableAssign(query, {
209 statusCodeExpected: 200
213 function getVideoChannelVideos (
216 videoChannelName: string,
220 query: { nsfw?: boolean } = {}
222 const path = '/api/v1/video-channels/' + videoChannelName + '/videos'
224 return makeGetRequest({
227 query: immutableAssign(query, {
233 statusCodeExpected: 200
237 function getPlaylistVideos (
240 playlistId: number | string,
243 query: { nsfw?: boolean } = {}
245 const path = '/api/v1/video-playlists/' + playlistId + '/videos'
247 return makeGetRequest({
250 query: immutableAssign(query, {
255 statusCodeExpected: 200
259 function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) {
260 const path = '/api/v1/videos'
262 const req = request(url)
264 .query({ start: start })
265 .query({ count: count })
267 if (sort) req.query({ sort })
268 if (skipCount) req.query({ skipCount })
270 return req.set('Accept', 'application/json')
272 .expect('Content-Type', /json/)
275 function getVideosListSort (url: string, sort: string) {
276 const path = '/api/v1/videos'
280 .query({ sort: sort })
281 .set('Accept', 'application/json')
283 .expect('Content-Type', /json/)
286 function getVideosWithFilters (url: string, query: { tagsAllOf: string[], categoryOneOf: number[] | number }) {
287 const path = '/api/v1/videos'
292 .set('Accept', 'application/json')
294 .expect('Content-Type', /json/)
297 function removeVideo (url: string, token: string, id: number | string, expectedStatus = 204) {
298 const path = '/api/v1/videos'
301 .delete(path + '/' + id)
302 .set('Accept', 'application/json')
303 .set('Authorization', 'Bearer ' + token)
304 .expect(expectedStatus)
307 async function checkVideoFilesWereRemoved (
309 serverNumber: number,
317 join('playlists', 'hls'),
318 join('redundancy', 'hls')
321 for (const directory of directories) {
322 const directoryPath = buildServerDirectory(serverNumber, directory)
324 const directoryExists = await pathExists(directoryPath)
325 if (directoryExists === false) continue
327 const files = await readdir(directoryPath)
328 for (const file of files) {
329 expect(file).to.not.contain(videoUUID)
334 async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = 200) {
335 const path = '/api/v1/videos/upload'
336 let defaultChannelId = '1'
339 const res = await getMyUserInformation(url, accessToken)
340 defaultChannelId = res.body.videoChannels[0].id
341 } catch (e) { /* empty */ }
343 // Override default attributes
344 const attributes = Object.assign({
345 name: 'my super video',
349 channelId: defaultChannelId,
351 waitTranscoding: false,
352 description: 'my super description',
353 support: 'my super support text',
355 privacy: VideoPrivacy.PUBLIC,
356 commentsEnabled: true,
357 downloadEnabled: true,
358 fixture: 'video_short.webm'
359 }, videoAttributesArg)
361 const req = request(url)
363 .set('Accept', 'application/json')
364 .set('Authorization', 'Bearer ' + accessToken)
365 .field('name', attributes.name)
366 .field('nsfw', JSON.stringify(attributes.nsfw))
367 .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled))
368 .field('downloadEnabled', JSON.stringify(attributes.downloadEnabled))
369 .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding))
370 .field('privacy', attributes.privacy.toString())
371 .field('channelId', attributes.channelId)
373 if (attributes.support !== undefined) {
374 req.field('support', attributes.support)
377 if (attributes.description !== undefined) {
378 req.field('description', attributes.description)
380 if (attributes.language !== undefined) {
381 req.field('language', attributes.language.toString())
383 if (attributes.category !== undefined) {
384 req.field('category', attributes.category.toString())
386 if (attributes.licence !== undefined) {
387 req.field('licence', attributes.licence.toString())
390 const tags = attributes.tags || []
391 for (let i = 0; i < tags.length; i++) {
392 req.field('tags[' + i + ']', attributes.tags[i])
395 if (attributes.thumbnailfile !== undefined) {
396 req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile))
398 if (attributes.previewfile !== undefined) {
399 req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile))
402 if (attributes.scheduleUpdate) {
403 req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt)
405 if (attributes.scheduleUpdate.privacy) {
406 req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy)
410 if (attributes.originallyPublishedAt !== undefined) {
411 req.field('originallyPublishedAt', attributes.originallyPublishedAt)
414 return req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture))
415 .expect(specialStatus)
418 function updateVideo (url: string, accessToken: string, id: number | string, attributes: VideoAttributes, statusCodeExpected = 204) {
419 const path = '/api/v1/videos/' + id
422 if (attributes.name) body['name'] = attributes.name
423 if (attributes.category) body['category'] = attributes.category
424 if (attributes.licence) body['licence'] = attributes.licence
425 if (attributes.language) body['language'] = attributes.language
426 if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw)
427 if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled)
428 if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled)
429 if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt
430 if (attributes.description) body['description'] = attributes.description
431 if (attributes.tags) body['tags'] = attributes.tags
432 if (attributes.privacy) body['privacy'] = attributes.privacy
433 if (attributes.channelId) body['channelId'] = attributes.channelId
434 if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate
437 if (attributes.thumbnailfile || attributes.previewfile) {
438 const attaches: any = {}
439 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
440 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
442 return makeUploadRequest({
453 return makePutBodyRequest({
462 function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = 204) {
463 const path = '/api/v1/videos/' + id + '/rate'
467 .set('Accept', 'application/json')
468 .set('Authorization', 'Bearer ' + accessToken)
470 .expect(specialStatus)
473 function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) {
474 return new Promise<any>((res, rej) => {
475 const torrentName = videoUUID + '-' + resolution + '.torrent'
476 const torrentPath = join(root(), 'test' + server.internalServerNumber, 'torrents', torrentName)
477 readFile(torrentPath, (err, data) => {
478 if (err) return rej(err)
480 return res(parseTorrent(data))
485 async function completeVideoCheck (
494 commentsEnabled: boolean
495 downloadEnabled: boolean
499 originallyPublishedAt?: string
521 thumbnailfile?: string
525 if (!attributes.likes) attributes.likes = 0
526 if (!attributes.dislikes) attributes.dislikes = 0
528 expect(video.name).to.equal(attributes.name)
529 expect(video.category.id).to.equal(attributes.category)
530 expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc')
531 expect(video.licence.id).to.equal(attributes.licence)
532 expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown')
533 expect(video.language.id).to.equal(attributes.language)
534 expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown')
535 expect(video.privacy.id).to.deep.equal(attributes.privacy)
536 expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy])
537 expect(video.nsfw).to.equal(attributes.nsfw)
538 expect(video.description).to.equal(attributes.description)
539 expect(video.account.id).to.be.a('number')
540 expect(video.account.host).to.equal(attributes.account.host)
541 expect(video.account.name).to.equal(attributes.account.name)
542 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
543 expect(video.channel.name).to.equal(attributes.channel.name)
544 expect(video.likes).to.equal(attributes.likes)
545 expect(video.dislikes).to.equal(attributes.dislikes)
546 expect(video.isLocal).to.equal(attributes.isLocal)
547 expect(video.duration).to.equal(attributes.duration)
548 expect(dateIsValid(video.createdAt)).to.be.true
549 expect(dateIsValid(video.publishedAt)).to.be.true
550 expect(dateIsValid(video.updatedAt)).to.be.true
552 if (attributes.publishedAt) {
553 expect(video.publishedAt).to.equal(attributes.publishedAt)
556 if (attributes.originallyPublishedAt) {
557 expect(video.originallyPublishedAt).to.equal(attributes.originallyPublishedAt)
559 expect(video.originallyPublishedAt).to.be.null
562 const res = await getVideo(url, video.uuid)
563 const videoDetails: VideoDetails = res.body
565 expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
566 expect(videoDetails.tags).to.deep.equal(attributes.tags)
567 expect(videoDetails.account.name).to.equal(attributes.account.name)
568 expect(videoDetails.account.host).to.equal(attributes.account.host)
569 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
570 expect(video.channel.name).to.equal(attributes.channel.name)
571 expect(videoDetails.channel.host).to.equal(attributes.account.host)
572 expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal)
573 expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true
574 expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true
575 expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled)
576 expect(videoDetails.downloadEnabled).to.equal(attributes.downloadEnabled)
578 for (const attributeFile of attributes.files) {
579 const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution)
580 expect(file).not.to.be.undefined
582 let extension = extname(attributes.fixture)
583 // Transcoding enabled: extension will always be .mp4
584 if (attributes.files.length > 1) extension = '.mp4'
586 expect(file.magnetUri).to.have.lengthOf.above(2)
587 expect(file.torrentUrl).to.equal(`http://${attributes.account.host}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
588 expect(file.fileUrl).to.equal(`http://${attributes.account.host}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`)
589 expect(file.resolution.id).to.equal(attributeFile.resolution)
590 expect(file.resolution.label).to.equal(attributeFile.resolution + 'p')
592 const minSize = attributeFile.size - ((10 * attributeFile.size) / 100)
593 const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100)
596 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')'
597 ).to.be.above(minSize).and.below(maxSize)
599 const torrent = await webtorrentAdd(file.magnetUri, true)
600 expect(torrent.files).to.be.an('array')
601 expect(torrent.files.length).to.equal(1)
602 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
605 await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath)
607 if (attributes.previewfile) {
608 await testImage(url, attributes.previewfile, videoDetails.previewPath)
612 async function videoUUIDToId (url: string, id: number | string) {
613 if (validator.isUUID('' + id) === false) return id
615 const res = await getVideo(url, id)
619 async function uploadVideoAndGetId (options: {
623 privacy?: VideoPrivacy
626 const videoAttrs: any = { name: options.videoName }
627 if (options.nsfw) videoAttrs.nsfw = options.nsfw
628 if (options.privacy) videoAttrs.privacy = options.privacy
630 const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs)
632 return { id: res.body.video.id, uuid: res.body.video.uuid }
635 async function getLocalIdByUUID (url: string, uuid: string) {
636 const res = await getVideo(url, uuid)
641 // ---------------------------------------------------------------------------
652 getVideoChannelVideos,
654 getVideoFileMetadataUrl,
657 getVideosListPagination,
660 getVideosListWithToken,
662 getVideosWithFilters,
669 checkVideoFilesWereRemoved,