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'
8 import { v4 as uuidv4 } from 'uuid'
9 import validator from 'validator'
10 import { HttpStatusCode } from '@shared/core-utils'
11 import { VideosCommonQuery } from '@shared/models'
12 import { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants'
13 import { VideoDetails, VideoPrivacy } from '../../models/videos'
15 buildAbsoluteFixturePath,
22 } from '../miscs/miscs'
23 import { makeGetRequest, makePutBodyRequest, makeRawRequest, makeUploadRequest } from '../requests/requests'
24 import { waitJobs } from '../server/jobs'
25 import { ServerInfo } from '../server/servers'
26 import { getMyUserInformation } from '../users/users'
30 type VideoAttributes = {
36 commentsEnabled?: boolean
37 downloadEnabled?: boolean
38 waitTranscoding?: boolean
40 originallyPublishedAt?: string
43 privacy?: VideoPrivacy
45 thumbnailfile?: string
49 privacy?: VideoPrivacy
53 function getVideoCategories (url: string) {
54 const path = '/api/v1/videos/categories'
56 return makeGetRequest({
59 statusCodeExpected: HttpStatusCode.OK_200
63 function getVideoLicences (url: string) {
64 const path = '/api/v1/videos/licences'
66 return makeGetRequest({
69 statusCodeExpected: HttpStatusCode.OK_200
73 function getVideoLanguages (url: string) {
74 const path = '/api/v1/videos/languages'
76 return makeGetRequest({
79 statusCodeExpected: HttpStatusCode.OK_200
83 function getVideoPrivacies (url: string) {
84 const path = '/api/v1/videos/privacies'
86 return makeGetRequest({
89 statusCodeExpected: HttpStatusCode.OK_200
93 function getVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) {
94 const path = '/api/v1/videos/' + id
98 .set('Accept', 'application/json')
99 .expect(expectedStatus)
102 async function getVideoIdFromUUID (url: string, uuid: string) {
103 const res = await getVideo(url, uuid)
108 function getVideoFileMetadataUrl (url: string) {
111 .set('Accept', 'application/json')
112 .expect(HttpStatusCode.OK_200)
113 .expect('Content-Type', /json/)
116 function viewVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204, xForwardedFor?: string) {
117 const path = '/api/v1/videos/' + id + '/views'
119 const req = request(url)
121 .set('Accept', 'application/json')
124 req.set('X-Forwarded-For', xForwardedFor)
127 return req.expect(expectedStatus)
130 function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) {
131 const path = '/api/v1/videos/' + id
135 .set('Authorization', 'Bearer ' + token)
136 .set('Accept', 'application/json')
137 .expect(expectedStatus)
140 function getVideoDescription (url: string, descriptionPath: string) {
142 .get(descriptionPath)
143 .set('Accept', 'application/json')
144 .expect(HttpStatusCode.OK_200)
145 .expect('Content-Type', /json/)
148 function getVideosList (url: string) {
149 const path = '/api/v1/videos'
153 .query({ sort: 'name' })
154 .set('Accept', 'application/json')
155 .expect(HttpStatusCode.OK_200)
156 .expect('Content-Type', /json/)
159 function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) {
160 const path = '/api/v1/videos'
164 .set('Authorization', 'Bearer ' + token)
165 .query(immutableAssign(query, { sort: 'name' }))
166 .set('Accept', 'application/json')
167 .expect(HttpStatusCode.OK_200)
168 .expect('Content-Type', /json/)
171 function getLocalVideos (url: string) {
172 const path = '/api/v1/videos'
176 .query({ sort: 'name', filter: 'local' })
177 .set('Accept', 'application/json')
178 .expect(HttpStatusCode.OK_200)
179 .expect('Content-Type', /json/)
182 function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string, search?: string) {
183 const path = '/api/v1/users/me/videos'
185 const req = request(url)
187 .query({ start: start })
188 .query({ count: count })
189 .query({ search: search })
191 if (sort) req.query({ sort })
193 return req.set('Accept', 'application/json')
194 .set('Authorization', 'Bearer ' + accessToken)
195 .expect(HttpStatusCode.OK_200)
196 .expect('Content-Type', /json/)
199 function getMyVideosWithFilter (url: string, accessToken: string, query: { isLive?: boolean }) {
200 const path = '/api/v1/users/me/videos'
202 return makeGetRequest({
207 statusCodeExpected: HttpStatusCode.OK_200
211 function getAccountVideos (
223 const path = '/api/v1/accounts/' + accountName + '/videos'
225 return makeGetRequest({
228 query: immutableAssign(query, {
234 statusCodeExpected: HttpStatusCode.OK_200
238 function getVideoChannelVideos (
241 videoChannelName: string,
245 query: { nsfw?: boolean } = {}
247 const path = '/api/v1/video-channels/' + videoChannelName + '/videos'
249 return makeGetRequest({
252 query: immutableAssign(query, {
258 statusCodeExpected: HttpStatusCode.OK_200
262 function getPlaylistVideos (
265 playlistId: number | string,
268 query: { nsfw?: boolean } = {}
270 const path = '/api/v1/video-playlists/' + playlistId + '/videos'
272 return makeGetRequest({
275 query: immutableAssign(query, {
280 statusCodeExpected: HttpStatusCode.OK_200
284 function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) {
285 const path = '/api/v1/videos'
287 const req = request(url)
289 .query({ start: start })
290 .query({ count: count })
292 if (sort) req.query({ sort })
293 if (skipCount) req.query({ skipCount })
295 return req.set('Accept', 'application/json')
296 .expect(HttpStatusCode.OK_200)
297 .expect('Content-Type', /json/)
300 function getVideosListSort (url: string, sort: string) {
301 const path = '/api/v1/videos'
305 .query({ sort: sort })
306 .set('Accept', 'application/json')
307 .expect(HttpStatusCode.OK_200)
308 .expect('Content-Type', /json/)
311 function getVideosWithFilters (url: string, query: VideosCommonQuery) {
312 const path = '/api/v1/videos'
317 .set('Accept', 'application/json')
318 .expect(HttpStatusCode.OK_200)
319 .expect('Content-Type', /json/)
322 function removeVideo (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204) {
323 const path = '/api/v1/videos'
326 .delete(path + '/' + id)
327 .set('Accept', 'application/json')
328 .set('Authorization', 'Bearer ' + token)
329 .expect(expectedStatus)
332 async function removeAllVideos (server: ServerInfo) {
333 const resVideos = await getVideosList(server.url)
335 for (const v of resVideos.body.data) {
336 await removeVideo(server.url, server.accessToken, v.id)
340 async function checkVideoFilesWereRemoved (
342 serverNumber: number,
350 join('playlists', 'hls'),
351 join('redundancy', 'hls')
354 for (const directory of directories) {
355 const directoryPath = buildServerDirectory({ internalServerNumber: serverNumber }, directory)
357 const directoryExists = await pathExists(directoryPath)
358 if (directoryExists === false) continue
360 const files = await readdir(directoryPath)
361 for (const file of files) {
362 expect(file, `File ${file} should not exist in ${directoryPath}`).to.not.contain(videoUUID)
367 async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = HttpStatusCode.OK_200) {
368 const path = '/api/v1/videos/upload'
369 let defaultChannelId = '1'
372 const res = await getMyUserInformation(url, accessToken)
373 defaultChannelId = res.body.videoChannels[0].id
374 } catch (e) { /* empty */ }
376 // Override default attributes
377 const attributes = Object.assign({
378 name: 'my super video',
382 channelId: defaultChannelId,
384 waitTranscoding: false,
385 description: 'my super description',
386 support: 'my super support text',
388 privacy: VideoPrivacy.PUBLIC,
389 commentsEnabled: true,
390 downloadEnabled: true,
391 fixture: 'video_short.webm'
392 }, videoAttributesArg)
394 const req = request(url)
396 .set('Accept', 'application/json')
397 .set('Authorization', 'Bearer ' + accessToken)
398 .field('name', attributes.name)
399 .field('nsfw', JSON.stringify(attributes.nsfw))
400 .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled))
401 .field('downloadEnabled', JSON.stringify(attributes.downloadEnabled))
402 .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding))
403 .field('privacy', attributes.privacy.toString())
404 .field('channelId', attributes.channelId)
406 if (attributes.support !== undefined) {
407 req.field('support', attributes.support)
410 if (attributes.description !== undefined) {
411 req.field('description', attributes.description)
413 if (attributes.language !== undefined) {
414 req.field('language', attributes.language.toString())
416 if (attributes.category !== undefined) {
417 req.field('category', attributes.category.toString())
419 if (attributes.licence !== undefined) {
420 req.field('licence', attributes.licence.toString())
423 const tags = attributes.tags || []
424 for (let i = 0; i < tags.length; i++) {
425 req.field('tags[' + i + ']', attributes.tags[i])
428 if (attributes.thumbnailfile !== undefined) {
429 req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile))
431 if (attributes.previewfile !== undefined) {
432 req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile))
435 if (attributes.scheduleUpdate) {
436 req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt)
438 if (attributes.scheduleUpdate.privacy) {
439 req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy)
443 if (attributes.originallyPublishedAt !== undefined) {
444 req.field('originallyPublishedAt', attributes.originallyPublishedAt)
447 const res = await req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture))
448 .expect(specialStatus)
450 // Wait torrent generation
451 if (specialStatus === HttpStatusCode.OK_200) {
452 let video: VideoDetails
454 const resVideo = await getVideoWithToken(url, accessToken, res.body.video.uuid)
455 video = resVideo.body
458 } while (!video.files[0].torrentUrl)
464 function updateVideo (
468 attributes: VideoAttributes,
469 statusCodeExpected = HttpStatusCode.NO_CONTENT_204
471 const path = '/api/v1/videos/' + id
474 if (attributes.name) body['name'] = attributes.name
475 if (attributes.category) body['category'] = attributes.category
476 if (attributes.licence) body['licence'] = attributes.licence
477 if (attributes.language) body['language'] = attributes.language
478 if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw)
479 if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled)
480 if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled)
481 if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt
482 if (attributes.description) body['description'] = attributes.description
483 if (attributes.tags) body['tags'] = attributes.tags
484 if (attributes.privacy) body['privacy'] = attributes.privacy
485 if (attributes.channelId) body['channelId'] = attributes.channelId
486 if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate
489 if (attributes.thumbnailfile || attributes.previewfile) {
490 const attaches: any = {}
491 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
492 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
494 return makeUploadRequest({
505 return makePutBodyRequest({
514 function rateVideo (url: string, accessToken: string, id: number | string, rating: string, specialStatus = HttpStatusCode.NO_CONTENT_204) {
515 const path = '/api/v1/videos/' + id + '/rate'
519 .set('Accept', 'application/json')
520 .set('Authorization', 'Bearer ' + accessToken)
522 .expect(specialStatus)
525 function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) {
526 return new Promise<any>((res, rej) => {
527 const torrentName = videoUUID + '-' + resolution + '.torrent'
528 const torrentPath = buildServerDirectory(server, join('torrents', torrentName))
530 readFile(torrentPath, (err, data) => {
531 if (err) return rej(err)
533 return res(parseTorrent(data))
538 async function completeVideoCheck (
547 commentsEnabled: boolean
548 downloadEnabled: boolean
552 originallyPublishedAt?: string
574 thumbnailfile?: string
578 if (!attributes.likes) attributes.likes = 0
579 if (!attributes.dislikes) attributes.dislikes = 0
581 const host = new URL(url).host
582 const originHost = attributes.account.host
584 expect(video.name).to.equal(attributes.name)
585 expect(video.category.id).to.equal(attributes.category)
586 expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc')
587 expect(video.licence.id).to.equal(attributes.licence)
588 expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown')
589 expect(video.language.id).to.equal(attributes.language)
590 expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown')
591 expect(video.privacy.id).to.deep.equal(attributes.privacy)
592 expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy])
593 expect(video.nsfw).to.equal(attributes.nsfw)
594 expect(video.description).to.equal(attributes.description)
595 expect(video.account.id).to.be.a('number')
596 expect(video.account.host).to.equal(attributes.account.host)
597 expect(video.account.name).to.equal(attributes.account.name)
598 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
599 expect(video.channel.name).to.equal(attributes.channel.name)
600 expect(video.likes).to.equal(attributes.likes)
601 expect(video.dislikes).to.equal(attributes.dislikes)
602 expect(video.isLocal).to.equal(attributes.isLocal)
603 expect(video.duration).to.equal(attributes.duration)
604 expect(dateIsValid(video.createdAt)).to.be.true
605 expect(dateIsValid(video.publishedAt)).to.be.true
606 expect(dateIsValid(video.updatedAt)).to.be.true
608 if (attributes.publishedAt) {
609 expect(video.publishedAt).to.equal(attributes.publishedAt)
612 if (attributes.originallyPublishedAt) {
613 expect(video.originallyPublishedAt).to.equal(attributes.originallyPublishedAt)
615 expect(video.originallyPublishedAt).to.be.null
618 const res = await getVideo(url, video.uuid)
619 const videoDetails: VideoDetails = res.body
621 expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
622 expect(videoDetails.tags).to.deep.equal(attributes.tags)
623 expect(videoDetails.account.name).to.equal(attributes.account.name)
624 expect(videoDetails.account.host).to.equal(attributes.account.host)
625 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
626 expect(video.channel.name).to.equal(attributes.channel.name)
627 expect(videoDetails.channel.host).to.equal(attributes.account.host)
628 expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal)
629 expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true
630 expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true
631 expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled)
632 expect(videoDetails.downloadEnabled).to.equal(attributes.downloadEnabled)
634 for (const attributeFile of attributes.files) {
635 const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution)
636 expect(file).not.to.be.undefined
638 let extension = extname(attributes.fixture)
639 // Transcoding enabled: extension will always be .mp4
640 if (attributes.files.length > 1) extension = '.mp4'
642 expect(file.magnetUri).to.have.lengthOf.above(2)
644 expect(file.torrentDownloadUrl).to.equal(`http://${host}/download/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
645 expect(file.torrentUrl).to.equal(`http://${host}/lazy-static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
647 expect(file.fileUrl).to.equal(`http://${originHost}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`)
648 expect(file.fileDownloadUrl).to.equal(`http://${originHost}/download/videos/${videoDetails.uuid}-${file.resolution.id}${extension}`)
651 makeRawRequest(file.torrentUrl, 200),
652 makeRawRequest(file.torrentDownloadUrl, 200),
653 makeRawRequest(file.metadataUrl, 200),
654 // Backward compatibility
655 makeRawRequest(`http://${originHost}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`, 200)
658 expect(file.resolution.id).to.equal(attributeFile.resolution)
659 expect(file.resolution.label).to.equal(attributeFile.resolution + 'p')
661 const minSize = attributeFile.size - ((10 * attributeFile.size) / 100)
662 const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100)
665 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')'
666 ).to.be.above(minSize).and.below(maxSize)
668 const torrent = await webtorrentAdd(file.magnetUri, true)
669 expect(torrent.files).to.be.an('array')
670 expect(torrent.files.length).to.equal(1)
671 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
674 await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath)
676 if (attributes.previewfile) {
677 await testImage(url, attributes.previewfile, videoDetails.previewPath)
681 async function videoUUIDToId (url: string, id: number | string) {
682 if (validator.isUUID('' + id) === false) return id
684 const res = await getVideo(url, id)
688 async function uploadVideoAndGetId (options: {
692 privacy?: VideoPrivacy
696 const videoAttrs: any = { name: options.videoName }
697 if (options.nsfw) videoAttrs.nsfw = options.nsfw
698 if (options.privacy) videoAttrs.privacy = options.privacy
699 if (options.fixture) videoAttrs.fixture = options.fixture
701 const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs)
703 return { id: res.body.video.id, uuid: res.body.video.uuid }
706 async function getLocalIdByUUID (url: string, uuid: string) {
707 const res = await getVideo(url, uuid)
712 // serverNumber starts from 1
713 async function uploadRandomVideoOnServers (servers: ServerInfo[], serverNumber: number, additionalParams: any = {}) {
714 const server = servers.find(s => s.serverNumber === serverNumber)
715 const res = await uploadRandomVideo(server, false, additionalParams)
717 await waitJobs(servers)
722 async function uploadRandomVideo (server: ServerInfo, wait = true, additionalParams: any = {}) {
723 const prefixName = additionalParams.prefixName || ''
724 const name = prefixName + uuidv4()
726 const data = Object.assign({ name }, additionalParams)
727 const res = await uploadVideo(server.url, server.accessToken, data)
729 if (wait) await waitJobs([ server ])
731 return { uuid: res.body.video.uuid, name }
734 // ---------------------------------------------------------------------------
746 getVideoChannelVideos,
748 getVideoFileMetadataUrl,
752 getVideosListPagination,
755 getVideosListWithToken,
757 getVideosWithFilters,
758 uploadRandomVideoOnServers,
765 checkVideoFilesWereRemoved,
767 getMyVideosWithFilter,