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 async function getVideoIdFromUUID (url: string, uuid: string) {
99 const res = await getVideo(url, uuid)
104 function getVideoFileMetadataUrl (url: string) {
107 .set('Accept', 'application/json')
109 .expect('Content-Type', /json/)
112 function viewVideo (url: string, id: number | string, expectedStatus = 204, xForwardedFor?: string) {
113 const path = '/api/v1/videos/' + id + '/views'
115 const req = request(url)
117 .set('Accept', 'application/json')
120 req.set('X-Forwarded-For', xForwardedFor)
123 return req.expect(expectedStatus)
126 function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = 200) {
127 const path = '/api/v1/videos/' + id
131 .set('Authorization', 'Bearer ' + token)
132 .set('Accept', 'application/json')
133 .expect(expectedStatus)
136 function getVideoDescription (url: string, descriptionPath: string) {
138 .get(descriptionPath)
139 .set('Accept', 'application/json')
141 .expect('Content-Type', /json/)
144 function getVideosList (url: string) {
145 const path = '/api/v1/videos'
149 .query({ sort: 'name' })
150 .set('Accept', 'application/json')
152 .expect('Content-Type', /json/)
155 function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) {
156 const path = '/api/v1/videos'
160 .set('Authorization', 'Bearer ' + token)
161 .query(immutableAssign(query, { sort: 'name' }))
162 .set('Accept', 'application/json')
164 .expect('Content-Type', /json/)
167 function getLocalVideos (url: string) {
168 const path = '/api/v1/videos'
172 .query({ sort: 'name', filter: 'local' })
173 .set('Accept', 'application/json')
175 .expect('Content-Type', /json/)
178 function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string, search?: string) {
179 const path = '/api/v1/users/me/videos'
181 const req = request(url)
183 .query({ start: start })
184 .query({ count: count })
185 .query({ search: search })
187 if (sort) req.query({ sort })
189 return req.set('Accept', 'application/json')
190 .set('Authorization', 'Bearer ' + accessToken)
192 .expect('Content-Type', /json/)
195 function getAccountVideos (
202 query: { nsfw?: boolean } = {}
204 const path = '/api/v1/accounts/' + accountName + '/videos'
206 return makeGetRequest({
209 query: immutableAssign(query, {
215 statusCodeExpected: 200
219 function getVideoChannelVideos (
222 videoChannelName: string,
226 query: { nsfw?: boolean } = {}
228 const path = '/api/v1/video-channels/' + videoChannelName + '/videos'
230 return makeGetRequest({
233 query: immutableAssign(query, {
239 statusCodeExpected: 200
243 function getPlaylistVideos (
246 playlistId: number | string,
249 query: { nsfw?: boolean } = {}
251 const path = '/api/v1/video-playlists/' + playlistId + '/videos'
253 return makeGetRequest({
256 query: immutableAssign(query, {
261 statusCodeExpected: 200
265 function getVideosListPagination (url: string, start: number, count: number, sort?: string, skipCount?: boolean) {
266 const path = '/api/v1/videos'
268 const req = request(url)
270 .query({ start: start })
271 .query({ count: count })
273 if (sort) req.query({ sort })
274 if (skipCount) req.query({ skipCount })
276 return req.set('Accept', 'application/json')
278 .expect('Content-Type', /json/)
281 function getVideosListSort (url: string, sort: string) {
282 const path = '/api/v1/videos'
286 .query({ sort: sort })
287 .set('Accept', 'application/json')
289 .expect('Content-Type', /json/)
292 function getVideosWithFilters (url: string, query: { tagsAllOf: string[], categoryOneOf: number[] | number }) {
293 const path = '/api/v1/videos'
298 .set('Accept', 'application/json')
300 .expect('Content-Type', /json/)
303 function removeVideo (url: string, token: string, id: number | string, expectedStatus = 204) {
304 const path = '/api/v1/videos'
307 .delete(path + '/' + id)
308 .set('Accept', 'application/json')
309 .set('Authorization', 'Bearer ' + token)
310 .expect(expectedStatus)
313 async function checkVideoFilesWereRemoved (
315 serverNumber: number,
323 join('playlists', 'hls'),
324 join('redundancy', 'hls')
327 for (const directory of directories) {
328 const directoryPath = buildServerDirectory(serverNumber, directory)
330 const directoryExists = await pathExists(directoryPath)
331 if (directoryExists === false) continue
333 const files = await readdir(directoryPath)
334 for (const file of files) {
335 expect(file).to.not.contain(videoUUID)
340 async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = 200) {
341 const path = '/api/v1/videos/upload'
342 let defaultChannelId = '1'
345 const res = await getMyUserInformation(url, accessToken)
346 defaultChannelId = res.body.videoChannels[0].id
347 } catch (e) { /* empty */ }
349 // Override default attributes
350 const attributes = Object.assign({
351 name: 'my super video',
355 channelId: defaultChannelId,
357 waitTranscoding: false,
358 description: 'my super description',
359 support: 'my super support text',
361 privacy: VideoPrivacy.PUBLIC,
362 commentsEnabled: true,
363 downloadEnabled: true,
364 fixture: 'video_short.webm'
365 }, videoAttributesArg)
367 const req = request(url)
369 .set('Accept', 'application/json')
370 .set('Authorization', 'Bearer ' + accessToken)
371 .field('name', attributes.name)
372 .field('nsfw', JSON.stringify(attributes.nsfw))
373 .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled))
374 .field('downloadEnabled', JSON.stringify(attributes.downloadEnabled))
375 .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding))
376 .field('privacy', attributes.privacy.toString())
377 .field('channelId', attributes.channelId)
379 if (attributes.support !== undefined) {
380 req.field('support', attributes.support)
383 if (attributes.description !== undefined) {
384 req.field('description', attributes.description)
386 if (attributes.language !== undefined) {
387 req.field('language', attributes.language.toString())
389 if (attributes.category !== undefined) {
390 req.field('category', attributes.category.toString())
392 if (attributes.licence !== undefined) {
393 req.field('licence', attributes.licence.toString())
396 const tags = attributes.tags || []
397 for (let i = 0; i < tags.length; i++) {
398 req.field('tags[' + i + ']', attributes.tags[i])
401 if (attributes.thumbnailfile !== undefined) {
402 req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile))
404 if (attributes.previewfile !== undefined) {
405 req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile))
408 if (attributes.scheduleUpdate) {
409 req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt)
411 if (attributes.scheduleUpdate.privacy) {
412 req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy)
416 if (attributes.originallyPublishedAt !== undefined) {
417 req.field('originallyPublishedAt', attributes.originallyPublishedAt)
420 return req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture))
421 .expect(specialStatus)
424 function updateVideo (url: string, accessToken: string, id: number | string, attributes: VideoAttributes, statusCodeExpected = 204) {
425 const path = '/api/v1/videos/' + id
428 if (attributes.name) body['name'] = attributes.name
429 if (attributes.category) body['category'] = attributes.category
430 if (attributes.licence) body['licence'] = attributes.licence
431 if (attributes.language) body['language'] = attributes.language
432 if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw)
433 if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled)
434 if (attributes.downloadEnabled !== undefined) body['downloadEnabled'] = JSON.stringify(attributes.downloadEnabled)
435 if (attributes.originallyPublishedAt !== undefined) body['originallyPublishedAt'] = attributes.originallyPublishedAt
436 if (attributes.description) body['description'] = attributes.description
437 if (attributes.tags) body['tags'] = attributes.tags
438 if (attributes.privacy) body['privacy'] = attributes.privacy
439 if (attributes.channelId) body['channelId'] = attributes.channelId
440 if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate
443 if (attributes.thumbnailfile || attributes.previewfile) {
444 const attaches: any = {}
445 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
446 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
448 return makeUploadRequest({
459 return makePutBodyRequest({
468 function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = 204) {
469 const path = '/api/v1/videos/' + id + '/rate'
473 .set('Accept', 'application/json')
474 .set('Authorization', 'Bearer ' + accessToken)
476 .expect(specialStatus)
479 function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) {
480 return new Promise<any>((res, rej) => {
481 const torrentName = videoUUID + '-' + resolution + '.torrent'
482 const torrentPath = join(root(), 'test' + server.internalServerNumber, 'torrents', torrentName)
483 readFile(torrentPath, (err, data) => {
484 if (err) return rej(err)
486 return res(parseTorrent(data))
491 async function completeVideoCheck (
500 commentsEnabled: boolean
501 downloadEnabled: boolean
505 originallyPublishedAt?: string
527 thumbnailfile?: string
531 if (!attributes.likes) attributes.likes = 0
532 if (!attributes.dislikes) attributes.dislikes = 0
534 expect(video.name).to.equal(attributes.name)
535 expect(video.category.id).to.equal(attributes.category)
536 expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc')
537 expect(video.licence.id).to.equal(attributes.licence)
538 expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown')
539 expect(video.language.id).to.equal(attributes.language)
540 expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown')
541 expect(video.privacy.id).to.deep.equal(attributes.privacy)
542 expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy])
543 expect(video.nsfw).to.equal(attributes.nsfw)
544 expect(video.description).to.equal(attributes.description)
545 expect(video.account.id).to.be.a('number')
546 expect(video.account.host).to.equal(attributes.account.host)
547 expect(video.account.name).to.equal(attributes.account.name)
548 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
549 expect(video.channel.name).to.equal(attributes.channel.name)
550 expect(video.likes).to.equal(attributes.likes)
551 expect(video.dislikes).to.equal(attributes.dislikes)
552 expect(video.isLocal).to.equal(attributes.isLocal)
553 expect(video.duration).to.equal(attributes.duration)
554 expect(dateIsValid(video.createdAt)).to.be.true
555 expect(dateIsValid(video.publishedAt)).to.be.true
556 expect(dateIsValid(video.updatedAt)).to.be.true
558 if (attributes.publishedAt) {
559 expect(video.publishedAt).to.equal(attributes.publishedAt)
562 if (attributes.originallyPublishedAt) {
563 expect(video.originallyPublishedAt).to.equal(attributes.originallyPublishedAt)
565 expect(video.originallyPublishedAt).to.be.null
568 const res = await getVideo(url, video.uuid)
569 const videoDetails: VideoDetails = res.body
571 expect(videoDetails.files).to.have.lengthOf(attributes.files.length)
572 expect(videoDetails.tags).to.deep.equal(attributes.tags)
573 expect(videoDetails.account.name).to.equal(attributes.account.name)
574 expect(videoDetails.account.host).to.equal(attributes.account.host)
575 expect(video.channel.displayName).to.equal(attributes.channel.displayName)
576 expect(video.channel.name).to.equal(attributes.channel.name)
577 expect(videoDetails.channel.host).to.equal(attributes.account.host)
578 expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal)
579 expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true
580 expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true
581 expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled)
582 expect(videoDetails.downloadEnabled).to.equal(attributes.downloadEnabled)
584 for (const attributeFile of attributes.files) {
585 const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution)
586 expect(file).not.to.be.undefined
588 let extension = extname(attributes.fixture)
589 // Transcoding enabled: extension will always be .mp4
590 if (attributes.files.length > 1) extension = '.mp4'
592 expect(file.magnetUri).to.have.lengthOf.above(2)
593 expect(file.torrentUrl).to.equal(`http://${attributes.account.host}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`)
594 expect(file.fileUrl).to.equal(`http://${attributes.account.host}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`)
595 expect(file.resolution.id).to.equal(attributeFile.resolution)
596 expect(file.resolution.label).to.equal(attributeFile.resolution + 'p')
598 const minSize = attributeFile.size - ((10 * attributeFile.size) / 100)
599 const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100)
602 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')'
603 ).to.be.above(minSize).and.below(maxSize)
605 const torrent = await webtorrentAdd(file.magnetUri, true)
606 expect(torrent.files).to.be.an('array')
607 expect(torrent.files.length).to.equal(1)
608 expect(torrent.files[0].path).to.exist.and.to.not.equal('')
611 await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath)
613 if (attributes.previewfile) {
614 await testImage(url, attributes.previewfile, videoDetails.previewPath)
618 async function videoUUIDToId (url: string, id: number | string) {
619 if (validator.isUUID('' + id) === false) return id
621 const res = await getVideo(url, id)
625 async function uploadVideoAndGetId (options: {
629 privacy?: VideoPrivacy
632 const videoAttrs: any = { name: options.videoName }
633 if (options.nsfw) videoAttrs.nsfw = options.nsfw
634 if (options.privacy) videoAttrs.privacy = options.privacy
636 const res = await uploadVideo(options.server.url, options.token || options.server.accessToken, videoAttrs)
638 return { id: res.body.video.id, uuid: res.body.video.uuid }
641 async function getLocalIdByUUID (url: string, uuid: string) {
642 const res = await getVideo(url, uuid)
647 // ---------------------------------------------------------------------------
658 getVideoChannelVideos,
660 getVideoFileMetadataUrl,
663 getVideosListPagination,
666 getVideosListWithToken,
668 getVideosWithFilters,
675 checkVideoFilesWereRemoved,