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 { loadLanguages, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants'
11 import { VideoDetails, VideoPrivacy } from '../../models/videos'
12 import { buildAbsoluteFixturePath, buildServerDirectory, dateIsValid, immutableAssign, testImage, webtorrentAdd } from '../miscs/miscs'
13 import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests'
14 import { waitJobs } from '../server/jobs'
15 import { ServerInfo } from '../server/servers'
16 import { getMyUserInformation } from '../users/users'
20 type VideoAttributes = {
26 commentsEnabled?: boolean
27 downloadEnabled?: boolean
28 waitTranscoding?: boolean
30 originallyPublishedAt?: string
33 privacy?: VideoPrivacy
35 thumbnailfile?: string
39 privacy?: VideoPrivacy
43 function getVideoCategories (url: string) {
44 const path = '/api/v1/videos/categories'
46 return makeGetRequest({
49 statusCodeExpected: 200
53 function getVideoLicences (url: string) {
54 const path = '/api/v1/videos/licences'
56 return makeGetRequest({
59 statusCodeExpected: 200
63 function getVideoLanguages (url: string) {
64 const path = '/api/v1/videos/languages'
66 return makeGetRequest({
69 statusCodeExpected: 200
73 function getVideoPrivacies (url: string) {
74 const path = '/api/v1/videos/privacies'
76 return makeGetRequest({
79 statusCodeExpected: 200
83 function getVideo (url: string, id: number | string, expectedStatus = 200) {
84 const path = '/api/v1/videos/' + id
88 .set('Accept', 'application/json')
89 .expect(expectedStatus)
92 async function getVideoIdFromUUID (url: string, uuid: string) {
93 const res = await getVideo(url, uuid)
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 removeAllVideos (server: ServerInfo) {
308 const resVideos = await getVideosList(server.url)
310 for (const v of resVideos.body.data) {
311 await removeVideo(server.url, server.accessToken, v.id)
315 async function checkVideoFilesWereRemoved (
317 serverNumber: number,
325 join('playlists', 'hls'),
326 join('redundancy', 'hls')
329 for (const directory of directories) {
330 const directoryPath = buildServerDirectory({ internalServerNumber: serverNumber }, directory)
332 const directoryExists = await pathExists(directoryPath)
333 if (directoryExists === false) continue
335 const files = await readdir(directoryPath)
336 for (const file of files) {
337 expect(file).to.not.contain(videoUUID)
342 async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = 200) {
343 const path = '/api/v1/videos/upload'
344 let defaultChannelId = '1'
347 const res = await getMyUserInformation(url, accessToken)
348 defaultChannelId = res.body.videoChannels[0].id
349 } catch (e) { /* empty */ }
351 // Override default attributes
352 const attributes = Object.assign({
353 name: 'my super video',
357 channelId: defaultChannelId,
359 waitTranscoding: false,
360 description: 'my super description',
361 support: 'my super support text',
363 privacy: VideoPrivacy.PUBLIC,
364 commentsEnabled: true,
365 downloadEnabled: true,
366 fixture: 'video_short.webm'
367 }, videoAttributesArg)
369 const req = request(url)
371 .set('Accept', 'application/json')
372 .set('Authorization', 'Bearer ' + accessToken)
373 .field('name', attributes.name)
374 .field('nsfw', JSON.stringify(attributes.nsfw))
375 .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled))
376 .field('downloadEnabled', JSON.stringify(attributes.downloadEnabled))
377 .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding))
378 .field('privacy', attributes.privacy.toString())
379 .field('channelId', attributes.channelId)
381 if (attributes.support !== undefined) {
382 req.field('support', attributes.support)
385 if (attributes.description !== undefined) {
386 req.field('description', attributes.description)
388 if (attributes.language !== undefined) {
389 req.field('language', attributes.language.toString())
391 if (attributes.category !== undefined) {
392 req.field('category', attributes.category.toString())
394 if (attributes.licence !== undefined) {
395 req.field('licence', attributes.licence.toString())
398 const tags = attributes.tags || []
399 for (let i = 0; i < tags.length; i++) {
400 req.field('tags[' + i + ']', attributes.tags[i])
403 if (attributes.thumbnailfile !== undefined) {
404 req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile))
406 if (attributes.previewfile !== undefined) {
407 req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile))
410 if (attributes.scheduleUpdate) {
411 req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt)
413 if (attributes.scheduleUpdate.privacy) {
414 req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy)
418 if (attributes.originallyPublishedAt !== undefined) {
419 req.field('originallyPublishedAt', attributes.originallyPublishedAt)
422 return req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture))
423 .expect(specialStatus)
426 function updateVideo (url: string, accessToken: string, id: number | string, attributes: VideoAttributes, statusCodeExpected = 204) {
427 const path = '/api/v1/videos/' + id
430 if (attributes.name) body['name'] = attributes.name
431 if (attributes.category) body['category'] = attributes.category
432 if (attributes.licence) body['licence'] = attributes.licence
433 if (attributes.language) body['language'] = attributes.language
434 if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw)
435 if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled)
436 if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled)
437 if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt
438 if (attributes.description) body['description'] = attributes.description
439 if (attributes.tags) body['tags'] = attributes.tags
440 if (attributes.privacy) body['privacy'] = attributes.privacy
441 if (attributes.channelId) body['channelId'] = attributes.channelId
442 if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate
445 if (attributes.thumbnailfile || attributes.previewfile) {
446 const attaches: any = {}
447 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
448 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
450 return makeUploadRequest({
461 return makePutBodyRequest({
470 function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = 204) {
471 const path = '/api/v1/videos/' + id + '/rate'
475 .set('Accept', 'application/json')
476 .set('Authorization', 'Bearer ' + accessToken)
478 .expect(specialStatus)
481 function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) {
482 return new Promise<any>((res, rej) => {
483 const torrentName = videoUUID + '-' + resolution + '.torrent'
484 const torrentPath = buildServerDirectory(server, join('torrents', torrentName))
486 readFile(torrentPath, (err, data) => {
487 if (err) return rej(err)
489 return res(parseTorrent(data))
494 async function completeVideoCheck (
503 commentsEnabled: boolean
504 downloadEnabled: boolean
508 originallyPublishedAt?: string
530 thumbnailfile?: string
534 if (!attributes.likes) attributes.likes = 0
535 if (!attributes.dislikes) attributes.dislikes = 0
537 expect(video.name).to.equal(attributes.name)
538 expect(video.category.id).to.equal(attributes.category)
539 expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc')
540 expect(video.licence.id).to.equal(attributes.licence)
541 expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown')
542 expect(video.language.id).to.equal(attributes.language)
543 expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown')
544 expect(video.privacy.id).to.deep.equal(attributes.privacy)
545 expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy])
546 expect(video.nsfw).to.equal(attributes.nsfw)
547 expect(video.description).to.equal(attributes.description)
548 expect(video.account.id).to.be.a('number')
549 expect(video.account.host).to.equal(attributes.account.host)
550 expect(video.account.name).to.equal(attributes.account.name)
551 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
552 expect(video.channel.name).to.equal(attributes.channel.name)
553 expect(video.likes).to.equal(attributes.likes)
554 expect(video.dislikes).to.equal(attributes.dislikes)
555 expect(video.isLocal).to.equal(attributes.isLocal)
556 expect(video.duration).to.equal(attributes.duration)
557 expect(dateIsValid(video.createdAt)).to.be.true
558 expect(dateIsValid(video.publishedAt)).to.be.true
559 expect(dateIsValid(video.updatedAt)).to.be.true
561 if (attributes.publishedAt) {
562 expect(video.publishedAt).to.equal(attributes.publishedAt)
565 if (attributes.originallyPublishedAt) {
566 expect(video.originallyPublishedAt).to.equal(attributes.originallyPublishedAt)
568 expect(video.originallyPublishedAt).to.be.null
571 const res = await getVideo(url, video.uuid)
572 const videoDetails: VideoDetails = res.body
574 expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
575 expect(videoDetails.tags).to.deep.equal(attributes.tags)
576 expect(videoDetails.account.name).to.equal(attributes.account.name)
577 expect(videoDetails.account.host).to.equal(attributes.account.host)
578 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
579 expect(video.channel.name).to.equal(attributes.channel.name)
580 expect(videoDetails.channel.host).to.equal(attributes.account.host)
581 expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal)
582 expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true
583 expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true
584 expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled)
585 expect(videoDetails.downloadEnabled).to.equal(attributes.downloadEnabled)
587 for (const attributeFile of attributes.files) {
588 const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution)
589 expect(file).not.to.be.undefined
591 let extension = extname(attributes.fixture)
592 // Transcoding enabled: extension will always be .mp4
593 if (attributes.files.length > 1) extension = '.mp4'
595 expect(file.magnetUri).to.have.lengthOf.above(2)
596 expect(file.torrentUrl).to.equal(`http://${attributes.account.host}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
597 expect(file.fileUrl).to.equal(`http://${attributes.account.host}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`)
598 expect(file.resolution.id).to.equal(attributeFile.resolution)
599 expect(file.resolution.label).to.equal(attributeFile.resolution + 'p')
601 const minSize = attributeFile.size - ((10 * attributeFile.size) / 100)
602 const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100)
605 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')'
606 ).to.be.above(minSize).and.below(maxSize)
608 const torrent = await webtorrentAdd(file.magnetUri, true)
609 expect(torrent.files).to.be.an('array')
610 expect(torrent.files.length).to.equal(1)
611 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
614 await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath)
616 if (attributes.previewfile) {
617 await testImage(url, attributes.previewfile, videoDetails.previewPath)
621 async function videoUUIDToId (url: string, id: number | string) {
622 if (validator.isUUID('' + id) === false) return id
624 const res = await getVideo(url, id)
628 async function uploadVideoAndGetId (options: {
632 privacy?: VideoPrivacy
635 const videoAttrs: any = { name: options.videoName }
636 if (options.nsfw) videoAttrs.nsfw = options.nsfw
637 if (options.privacy) videoAttrs.privacy = options.privacy
639 const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs)
641 return { id: res.body.video.id, uuid: res.body.video.uuid }
644 async function getLocalIdByUUID (url: string, uuid: string) {
645 const res = await getVideo(url, uuid)
650 // serverNumber starts from 1
651 async function uploadRandomVideoOnServers (servers: ServerInfo[], serverNumber: number, additionalParams: any = {}) {
652 const server = servers.find(s => s.serverNumber === serverNumber)
653 const res = await uploadRandomVideo(server, false, additionalParams)
655 await waitJobs(servers)
660 async function uploadRandomVideo (server: ServerInfo, wait = true, additionalParams: any = {}) {
661 const prefixName = additionalParams.prefixName || ''
662 const name = prefixName + uuidv4()
664 const data = Object.assign({ name }, additionalParams)
665 const res = await uploadVideo(server.url, server.accessToken, data)
667 if (wait) await waitJobs([ server ])
669 return { uuid: res.body.video.uuid, name }
672 // ---------------------------------------------------------------------------
684 getVideoChannelVideos,
686 getVideoFileMetadataUrl,
690 getVideosListPagination,
693 getVideosListWithToken,
695 getVideosWithFilters,
696 uploadRandomVideoOnServers,
703 checkVideoFilesWereRemoved,