1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
3 import { HttpStatusCode } from '@shared/core-utils'
4 import { expect } from 'chai'
5 import { pathExists, readdir, readFile } from 'fs-extra'
6 import * as parseTorrent from 'parse-torrent'
7 import { extname, join } from 'path'
8 import * as request from 'supertest'
9 import { v4 as uuidv4 } from 'uuid'
10 import validator from 'validator'
11 import { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants'
12 import { VideoDetails, VideoPrivacy } from '../../models/videos'
13 import { buildAbsoluteFixturePath, buildServerDirectory, dateIsValid, immutableAssign, testImage, webtorrentAdd } from '../miscs/miscs'
14 import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests'
15 import { waitJobs } from '../server/jobs'
16 import { ServerInfo } from '../server/servers'
17 import { getMyUserInformation } from '../users/users'
21 type VideoAttributes = {
27 commentsEnabled?: boolean
28 downloadEnabled?: boolean
29 waitTranscoding?: boolean
31 originallyPublishedAt?: string
34 privacy?: VideoPrivacy
36 thumbnailfile?: string
40 privacy?: VideoPrivacy
44 function getVideoCategories (url: string) {
45 const path = '/api/v1/videos/categories'
47 return makeGetRequest({
50 statusCodeExpected: HttpStatusCode.OK_200
54 function getVideoLicences (url: string) {
55 const path = '/api/v1/videos/licences'
57 return makeGetRequest({
60 statusCodeExpected: HttpStatusCode.OK_200
64 function getVideoLanguages (url: string) {
65 const path = '/api/v1/videos/languages'
67 return makeGetRequest({
70 statusCodeExpected: HttpStatusCode.OK_200
74 function getVideoPrivacies (url: string) {
75 const path = '/api/v1/videos/privacies'
77 return makeGetRequest({
80 statusCodeExpected: HttpStatusCode.OK_200
84 function getVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) {
85 const path = '/api/v1/videos/' + id
89 .set('Accept', 'application/json')
90 .expect(expectedStatus)
93 async function getVideoIdFromUUID (url: string, uuid: string) {
94 const res = await getVideo(url, uuid)
99 function getVideoFileMetadataUrl (url: string) {
102 .set('Accept', 'application/json')
103 .expect(HttpStatusCode.OK_200)
104 .expect('Content-Type', /json/)
107 function viewVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204, xForwardedFor?: string) {
108 const path = '/api/v1/videos/' + id + '/views'
110 const req = request(url)
112 .set('Accept', 'application/json')
115 req.set('X-Forwarded-For', xForwardedFor)
118 return req.expect(expectedStatus)
121 function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) {
122 const path = '/api/v1/videos/' + id
126 .set('Authorization', 'Bearer ' + token)
127 .set('Accept', 'application/json')
128 .expect(expectedStatus)
131 function getVideoDescription (url: string, descriptionPath: string) {
133 .get(descriptionPath)
134 .set('Accept', 'application/json')
135 .expect(HttpStatusCode.OK_200)
136 .expect('Content-Type', /json/)
139 function getVideosList (url: string) {
140 const path = '/api/v1/videos'
144 .query({ sort: 'name' })
145 .set('Accept', 'application/json')
146 .expect(HttpStatusCode.OK_200)
147 .expect('Content-Type', /json/)
150 function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) {
151 const path = '/api/v1/videos'
155 .set('Authorization', 'Bearer ' + token)
156 .query(immutableAssign(query, { sort: 'name' }))
157 .set('Accept', 'application/json')
158 .expect(HttpStatusCode.OK_200)
159 .expect('Content-Type', /json/)
162 function getLocalVideos (url: string) {
163 const path = '/api/v1/videos'
167 .query({ sort: 'name', filter: 'local' })
168 .set('Accept', 'application/json')
169 .expect(HttpStatusCode.OK_200)
170 .expect('Content-Type', /json/)
173 function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string, search?: string) {
174 const path = '/api/v1/users/me/videos'
176 const req = request(url)
178 .query({ start: start })
179 .query({ count: count })
180 .query({ search: search })
182 if (sort) req.query({ sort })
184 return req.set('Accept', 'application/json')
185 .set('Authorization', 'Bearer ' + accessToken)
186 .expect(HttpStatusCode.OK_200)
187 .expect('Content-Type', /json/)
190 function getAccountVideos (
202 const path = '/api/v1/accounts/' + accountName + '/videos'
204 return makeGetRequest({
207 query: immutableAssign(query, {
213 statusCodeExpected: HttpStatusCode.OK_200
217 function getVideoChannelVideos (
220 videoChannelName: string,
224 query: { nsfw?: boolean } = {}
226 const path = '/api/v1/video-channels/' + videoChannelName + '/videos'
228 return makeGetRequest({
231 query: immutableAssign(query, {
237 statusCodeExpected: HttpStatusCode.OK_200
241 function getPlaylistVideos (
244 playlistId: number | string,
247 query: { nsfw?: boolean } = {}
249 const path = '/api/v1/video-playlists/' + playlistId + '/videos'
251 return makeGetRequest({
254 query: immutableAssign(query, {
259 statusCodeExpected: HttpStatusCode.OK_200
263 function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) {
264 const path = '/api/v1/videos'
266 const req = request(url)
268 .query({ start: start })
269 .query({ count: count })
271 if (sort) req.query({ sort })
272 if (skipCount) req.query({ skipCount })
274 return req.set('Accept', 'application/json')
275 .expect(HttpStatusCode.OK_200)
276 .expect('Content-Type', /json/)
279 function getVideosListSort (url: string, sort: string) {
280 const path = '/api/v1/videos'
284 .query({ sort: sort })
285 .set('Accept', 'application/json')
286 .expect(HttpStatusCode.OK_200)
287 .expect('Content-Type', /json/)
290 function getVideosWithFilters (url: string, query: { tagsAllOf: string[], categoryOneOf: number[] | number }) {
291 const path = '/api/v1/videos'
296 .set('Accept', 'application/json')
297 .expect(HttpStatusCode.OK_200)
298 .expect('Content-Type', /json/)
301 function removeVideo (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204) {
302 const path = '/api/v1/videos'
305 .delete(path + '/' + id)
306 .set('Accept', 'application/json')
307 .set('Authorization', 'Bearer ' + token)
308 .expect(expectedStatus)
311 async function removeAllVideos (server: ServerInfo) {
312 const resVideos = await getVideosList(server.url)
314 for (const v of resVideos.body.data) {
315 await removeVideo(server.url, server.accessToken, v.id)
319 async function checkVideoFilesWereRemoved (
321 serverNumber: number,
329 join('playlists', 'hls'),
330 join('redundancy', 'hls')
333 for (const directory of directories) {
334 const directoryPath = buildServerDirectory({ internalServerNumber: serverNumber }, directory)
336 const directoryExists = await pathExists(directoryPath)
337 if (directoryExists === false) continue
339 const files = await readdir(directoryPath)
340 for (const file of files) {
341 expect(file).to.not.contain(videoUUID)
346 async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = HttpStatusCode.OK_200) {
347 const path = '/api/v1/videos/upload'
348 let defaultChannelId = '1'
351 const res = await getMyUserInformation(url, accessToken)
352 defaultChannelId = res.body.videoChannels[0].id
353 } catch (e) { /* empty */ }
355 // Override default attributes
356 const attributes = Object.assign({
357 name: 'my super video',
361 channelId: defaultChannelId,
363 waitTranscoding: false,
364 description: 'my super description',
365 support: 'my super support text',
367 privacy: VideoPrivacy.PUBLIC,
368 commentsEnabled: true,
369 downloadEnabled: true,
370 fixture: 'video_short.webm'
371 }, videoAttributesArg)
373 const req = request(url)
375 .set('Accept', 'application/json')
376 .set('Authorization', 'Bearer ' + accessToken)
377 .field('name', attributes.name)
378 .field('nsfw', JSON.stringify(attributes.nsfw))
379 .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled))
380 .field('downloadEnabled', JSON.stringify(attributes.downloadEnabled))
381 .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding))
382 .field('privacy', attributes.privacy.toString())
383 .field('channelId', attributes.channelId)
385 if (attributes.support !== undefined) {
386 req.field('support', attributes.support)
389 if (attributes.description !== undefined) {
390 req.field('description', attributes.description)
392 if (attributes.language !== undefined) {
393 req.field('language', attributes.language.toString())
395 if (attributes.category !== undefined) {
396 req.field('category', attributes.category.toString())
398 if (attributes.licence !== undefined) {
399 req.field('licence', attributes.licence.toString())
402 const tags = attributes.tags || []
403 for (let i = 0; i < tags.length; i++) {
404 req.field('tags[' + i + ']', attributes.tags[i])
407 if (attributes.thumbnailfile !== undefined) {
408 req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile))
410 if (attributes.previewfile !== undefined) {
411 req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile))
414 if (attributes.scheduleUpdate) {
415 req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt)
417 if (attributes.scheduleUpdate.privacy) {
418 req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy)
422 if (attributes.originallyPublishedAt !== undefined) {
423 req.field('originallyPublishedAt', attributes.originallyPublishedAt)
426 return req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture))
427 .expect(specialStatus)
430 function updateVideo (
434 attributes: VideoAttributes,
435 statusCodeExpected = HttpStatusCode.NO_CONTENT_204
437 const path = '/api/v1/videos/' + id
440 if (attributes.name) body['name'] = attributes.name
441 if (attributes.category) body['category'] = attributes.category
442 if (attributes.licence) body['licence'] = attributes.licence
443 if (attributes.language) body['language'] = attributes.language
444 if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw)
445 if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled)
446 if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled)
447 if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt
448 if (attributes.description) body['description'] = attributes.description
449 if (attributes.tags) body['tags'] = attributes.tags
450 if (attributes.privacy) body['privacy'] = attributes.privacy
451 if (attributes.channelId) body['channelId'] = attributes.channelId
452 if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate
455 if (attributes.thumbnailfile || attributes.previewfile) {
456 const attaches: any = {}
457 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
458 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
460 return makeUploadRequest({
471 return makePutBodyRequest({
480 function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = HttpStatusCode.NO_CONTENT_204) {
481 const path = '/api/v1/videos/' + id + '/rate'
485 .set('Accept', 'application/json')
486 .set('Authorization', 'Bearer ' + accessToken)
488 .expect(specialStatus)
491 function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) {
492 return new Promise<any>((res, rej) => {
493 const torrentName = videoUUID + '-' + resolution + '.torrent'
494 const torrentPath = buildServerDirectory(server, join('torrents', torrentName))
496 readFile(torrentPath, (err, data) => {
497 if (err) return rej(err)
499 return res(parseTorrent(data))
504 async function completeVideoCheck (
513 commentsEnabled: boolean
514 downloadEnabled: boolean
518 originallyPublishedAt?: string
540 thumbnailfile?: string
544 if (!attributes.likes) attributes.likes = 0
545 if (!attributes.dislikes) attributes.dislikes = 0
547 expect(video.name).to.equal(attributes.name)
548 expect(video.category.id).to.equal(attributes.category)
549 expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc')
550 expect(video.licence.id).to.equal(attributes.licence)
551 expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown')
552 expect(video.language.id).to.equal(attributes.language)
553 expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown')
554 expect(video.privacy.id).to.deep.equal(attributes.privacy)
555 expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy])
556 expect(video.nsfw).to.equal(attributes.nsfw)
557 expect(video.description).to.equal(attributes.description)
558 expect(video.account.id).to.be.a('number')
559 expect(video.account.host).to.equal(attributes.account.host)
560 expect(video.account.name).to.equal(attributes.account.name)
561 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
562 expect(video.channel.name).to.equal(attributes.channel.name)
563 expect(video.likes).to.equal(attributes.likes)
564 expect(video.dislikes).to.equal(attributes.dislikes)
565 expect(video.isLocal).to.equal(attributes.isLocal)
566 expect(video.duration).to.equal(attributes.duration)
567 expect(dateIsValid(video.createdAt)).to.be.true
568 expect(dateIsValid(video.publishedAt)).to.be.true
569 expect(dateIsValid(video.updatedAt)).to.be.true
571 if (attributes.publishedAt) {
572 expect(video.publishedAt).to.equal(attributes.publishedAt)
575 if (attributes.originallyPublishedAt) {
576 expect(video.originallyPublishedAt).to.equal(attributes.originallyPublishedAt)
578 expect(video.originallyPublishedAt).to.be.null
581 const res = await getVideo(url, video.uuid)
582 const videoDetails: VideoDetails = res.body
584 expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
585 expect(videoDetails.tags).to.deep.equal(attributes.tags)
586 expect(videoDetails.account.name).to.equal(attributes.account.name)
587 expect(videoDetails.account.host).to.equal(attributes.account.host)
588 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
589 expect(video.channel.name).to.equal(attributes.channel.name)
590 expect(videoDetails.channel.host).to.equal(attributes.account.host)
591 expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal)
592 expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true
593 expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true
594 expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled)
595 expect(videoDetails.downloadEnabled).to.equal(attributes.downloadEnabled)
597 for (const attributeFile of attributes.files) {
598 const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution)
599 expect(file).not.to.be.undefined
601 let extension = extname(attributes.fixture)
602 // Transcoding enabled: extension will always be .mp4
603 if (attributes.files.length > 1) extension = '.mp4'
605 expect(file.magnetUri).to.have.lengthOf.above(2)
606 expect(file.torrentUrl).to.equal(`http://${attributes.account.host}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
607 expect(file.fileUrl).to.equal(`http://${attributes.account.host}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`)
608 expect(file.resolution.id).to.equal(attributeFile.resolution)
609 expect(file.resolution.label).to.equal(attributeFile.resolution + 'p')
611 const minSize = attributeFile.size - ((10 * attributeFile.size) / 100)
612 const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100)
615 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')'
616 ).to.be.above(minSize).and.below(maxSize)
618 const torrent = await webtorrentAdd(file.magnetUri, true)
619 expect(torrent.files).to.be.an('array')
620 expect(torrent.files.length).to.equal(1)
621 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
624 await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath)
626 if (attributes.previewfile) {
627 await testImage(url, attributes.previewfile, videoDetails.previewPath)
631 async function videoUUIDToId (url: string, id: number | string) {
632 if (validator.isUUID('' + id) === false) return id
634 const res = await getVideo(url, id)
638 async function uploadVideoAndGetId (options: {
642 privacy?: VideoPrivacy
646 const videoAttrs: any = { name: options.videoName }
647 if (options.nsfw) videoAttrs.nsfw = options.nsfw
648 if (options.privacy) videoAttrs.privacy = options.privacy
649 if (options.fixture) videoAttrs.fixture = options.fixture
651 const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs)
653 return { id: res.body.video.id, uuid: res.body.video.uuid }
656 async function getLocalIdByUUID (url: string, uuid: string) {
657 const res = await getVideo(url, uuid)
662 // serverNumber starts from 1
663 async function uploadRandomVideoOnServers (servers: ServerInfo[], serverNumber: number, additionalParams: any = {}) {
664 const server = servers.find(s => s.serverNumber === serverNumber)
665 const res = await uploadRandomVideo(server, false, additionalParams)
667 await waitJobs(servers)
672 async function uploadRandomVideo (server: ServerInfo, wait = true, additionalParams: any = {}) {
673 const prefixName = additionalParams.prefixName || ''
674 const name = prefixName + uuidv4()
676 const data = Object.assign({ name }, additionalParams)
677 const res = await uploadVideo(server.url, server.accessToken, data)
679 if (wait) await waitJobs([ server ])
681 return { uuid: res.body.video.uuid, name }
684 // ---------------------------------------------------------------------------
696 getVideoChannelVideos,
698 getVideoFileMetadataUrl,
702 getVideosListPagination,
705 getVideosListWithToken,
707 getVideosWithFilters,
708 uploadRandomVideoOnServers,
715 checkVideoFilesWereRemoved,