1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
3 import { expect } from 'chai'
4 import { createReadStream, stat } from 'fs-extra'
5 import got, { Response as GotResponse } from 'got'
6 import { omit } from 'lodash'
7 import validator from 'validator'
8 import { buildAbsoluteFixturePath, buildUUID, pick, wait } from '@shared/core-utils'
20 VideoTranscodingCreate
21 } from '@shared/models'
22 import { unwrapBody } from '../requests'
23 import { waitJobs } from '../server'
24 import { AbstractCommand, OverrideCommandOptions } from '../shared'
26 export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
28 thumbnailfile?: string
32 export class VideosCommand extends AbstractCommand {
33 getCategories (options: OverrideCommandOptions = {}) {
34 const path = '/api/v1/videos/categories'
36 return this.getRequestBody<{ [id: number]: string }>({
41 defaultExpectedStatus: HttpStatusCode.OK_200
45 getLicences (options: OverrideCommandOptions = {}) {
46 const path = '/api/v1/videos/licences'
48 return this.getRequestBody<{ [id: number]: string }>({
53 defaultExpectedStatus: HttpStatusCode.OK_200
57 getLanguages (options: OverrideCommandOptions = {}) {
58 const path = '/api/v1/videos/languages'
60 return this.getRequestBody<{ [id: string]: string }>({
65 defaultExpectedStatus: HttpStatusCode.OK_200
69 getPrivacies (options: OverrideCommandOptions = {}) {
70 const path = '/api/v1/videos/privacies'
72 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
77 defaultExpectedStatus: HttpStatusCode.OK_200
81 // ---------------------------------------------------------------------------
83 getDescription (options: OverrideCommandOptions & {
84 descriptionPath: string
86 return this.getRequestBody<{ description: string }>({
88 path: options.descriptionPath,
91 defaultExpectedStatus: HttpStatusCode.OK_200
95 getFileMetadata (options: OverrideCommandOptions & {
98 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
102 implicitToken: false,
103 defaultExpectedStatus: HttpStatusCode.OK_200
107 // ---------------------------------------------------------------------------
109 view (options: OverrideCommandOptions & {
111 xForwardedFor?: string
113 const { id, xForwardedFor } = options
114 const path = '/api/v1/videos/' + id + '/views'
116 return this.postBodyRequest({
121 implicitToken: false,
122 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
126 rate (options: OverrideCommandOptions & {
128 rating: UserVideoRateType
130 const { id, rating } = options
131 const path = '/api/v1/videos/' + id + '/rate'
133 return this.putBodyRequest({
139 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
143 // ---------------------------------------------------------------------------
145 get (options: OverrideCommandOptions & {
148 const path = '/api/v1/videos/' + options.id
150 return this.getRequestBody<VideoDetails>({
154 implicitToken: false,
155 defaultExpectedStatus: HttpStatusCode.OK_200
159 getWithToken (options: OverrideCommandOptions & {
165 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
169 async getId (options: OverrideCommandOptions & {
170 uuid: number | string
172 const { uuid } = options
174 if (validator.isUUID('' + uuid) === false) return uuid as number
176 const { id } = await this.get({ ...options, id: uuid })
181 async listFiles (options: OverrideCommandOptions & {
184 const video = await this.get(options)
186 const files = video.files || []
187 const hlsFiles = video.streamingPlaylists[0]?.files || []
189 return files.concat(hlsFiles)
192 // ---------------------------------------------------------------------------
194 listMyVideos (options: OverrideCommandOptions & {
202 const path = '/api/v1/users/me/videos'
204 return this.getRequestBody<ResultList<Video>>({
208 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
210 defaultExpectedStatus: HttpStatusCode.OK_200
214 // ---------------------------------------------------------------------------
216 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
217 const path = '/api/v1/videos'
219 const query = this.buildListQuery(options)
221 return this.getRequestBody<ResultList<Video>>({
225 query: { sort: 'name', ...query },
226 implicitToken: false,
227 defaultExpectedStatus: HttpStatusCode.OK_200
231 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
235 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
239 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
242 const { handle, search } = options
243 const path = '/api/v1/accounts/' + handle + '/videos'
245 return this.getRequestBody<ResultList<Video>>({
249 query: { search, ...this.buildListQuery(options) },
251 defaultExpectedStatus: HttpStatusCode.OK_200
255 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
258 const { handle } = options
259 const path = '/api/v1/video-channels/' + handle + '/videos'
261 return this.getRequestBody<ResultList<Video>>({
265 query: this.buildListQuery(options),
267 defaultExpectedStatus: HttpStatusCode.OK_200
271 // ---------------------------------------------------------------------------
273 async find (options: OverrideCommandOptions & {
276 const { data } = await this.list(options)
278 return data.find(v => v.name === options.name)
281 // ---------------------------------------------------------------------------
283 update (options: OverrideCommandOptions & {
285 attributes?: VideoEdit
287 const { id, attributes = {} } = options
288 const path = '/api/v1/videos/' + id
291 if (attributes.thumbnailfile || attributes.previewfile) {
292 const attaches: any = {}
293 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
294 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
296 return this.putUploadRequest({
300 fields: options.attributes,
302 thumbnailfile: attributes.thumbnailfile,
303 previewfile: attributes.previewfile
306 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
310 return this.putBodyRequest({
314 fields: options.attributes,
316 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
320 remove (options: OverrideCommandOptions & {
323 const path = '/api/v1/videos/' + options.id
325 return unwrapBody(this.deleteRequest({
330 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
335 const { data } = await this.list()
337 for (const v of data) {
338 await this.remove({ id: v.id })
342 // ---------------------------------------------------------------------------
344 async upload (options: OverrideCommandOptions & {
345 attributes?: VideoEdit
346 mode?: 'legacy' | 'resumable' // default legacy
348 const { mode = 'legacy' } = options
349 let defaultChannelId = 1
352 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
353 defaultChannelId = videoChannels[0].id
354 } catch (e) { /* empty */ }
356 // Override default attributes
358 name: 'my super video',
362 channelId: defaultChannelId,
364 waitTranscoding: false,
365 description: 'my super description',
366 support: 'my super support text',
368 privacy: VideoPrivacy.PUBLIC,
369 commentsEnabled: true,
370 downloadEnabled: true,
371 fixture: 'video_short.webm',
373 ...options.attributes
376 const created = mode === 'legacy'
377 ? await this.buildLegacyUpload({ ...options, attributes })
378 : await this.buildResumeUpload({ ...options, attributes })
380 // Wait torrent generation
381 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
382 if (expectedStatus === HttpStatusCode.OK_200) {
383 let video: VideoDetails
386 video = await this.getWithToken({ ...options, id: created.uuid })
389 } while (!video.files[0].torrentUrl)
395 async buildLegacyUpload (options: OverrideCommandOptions & {
396 attributes: VideoEdit
397 }): Promise<VideoCreateResult> {
398 const path = '/api/v1/videos/upload'
400 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
404 fields: this.buildUploadFields(options.attributes),
405 attaches: this.buildUploadAttaches(options.attributes),
407 defaultExpectedStatus: HttpStatusCode.OK_200
408 })).then(body => body.video || body as any)
411 async buildResumeUpload (options: OverrideCommandOptions & {
412 attributes: VideoEdit
413 }): Promise<VideoCreateResult> {
414 const { attributes, expectedStatus } = options
417 let videoFilePath: string
418 let mimetype = 'video/mp4'
420 if (attributes.fixture) {
421 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
422 size = (await stat(videoFilePath)).size
424 if (videoFilePath.endsWith('.mkv')) {
425 mimetype = 'video/x-matroska'
426 } else if (videoFilePath.endsWith('.webm')) {
427 mimetype = 'video/webm'
431 // Do not check status automatically, we'll check it manually
432 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
433 const initStatus = initializeSessionRes.status
435 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
436 const locationHeader = initializeSessionRes.header['location']
437 expect(locationHeader).to.not.be.undefined
439 const pathUploadId = locationHeader.split('?')[1]
441 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
443 if (result.statusCode === HttpStatusCode.OK_200) {
444 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
447 return result.body?.video || result.body as any
450 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
451 ? HttpStatusCode.CREATED_201
454 expect(initStatus).to.equal(expectedInitStatus)
456 return initializeSessionRes.body.video || initializeSessionRes.body
459 async prepareResumableUpload (options: OverrideCommandOptions & {
460 attributes: VideoEdit
464 originalName?: string
465 lastModified?: number
467 const { attributes, originalName, lastModified, size, mimetype } = options
469 const path = '/api/v1/videos/upload-resumable'
471 return this.postUploadRequest({
476 'X-Upload-Content-Type': mimetype,
477 'X-Upload-Content-Length': size.toString()
480 filename: attributes.fixture,
484 ...this.buildUploadFields(options.attributes)
487 // Fixture will be sent later
488 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
491 defaultExpectedStatus: null
495 sendResumableChunks (options: OverrideCommandOptions & {
497 videoFilePath: string
499 contentLength?: number
500 contentRangeBuilder?: (start: number, chunk: any) => string
502 const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options
504 const path = '/api/v1/videos/upload-resumable'
507 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
508 const url = this.server.url
510 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
511 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
512 readable.on('data', async function onData (chunk) {
516 'Authorization': 'Bearer ' + token,
517 'Content-Type': 'application/octet-stream',
518 'Content-Range': contentRangeBuilder
519 ? contentRangeBuilder(start, chunk)
520 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
521 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
524 const res = await got<{ video: VideoCreateResult }>({
528 path: path + '?' + pathUploadId,
530 responseType: 'json',
531 throwHttpErrors: false
534 start += chunk.length
536 if (res.statusCode === expectedStatus) {
540 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
541 readable.off('data', onData)
542 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
550 endResumableUpload (options: OverrideCommandOptions & {
553 return this.deleteRequest({
556 path: '/api/v1/videos/upload-resumable',
557 rawQuery: options.pathUploadId,
559 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
563 quickUpload (options: OverrideCommandOptions & {
566 privacy?: VideoPrivacy
569 const attributes: VideoEdit = { name: options.name }
570 if (options.nsfw) attributes.nsfw = options.nsfw
571 if (options.privacy) attributes.privacy = options.privacy
572 if (options.fixture) attributes.fixture = options.fixture
574 return this.upload({ ...options, attributes })
577 async randomUpload (options: OverrideCommandOptions & {
578 wait?: boolean // default true
579 additionalParams?: VideoEdit & { prefixName?: string }
581 const { wait = true, additionalParams } = options
582 const prefixName = additionalParams?.prefixName || ''
583 const name = prefixName + buildUUID()
585 const attributes = { name, ...additionalParams }
587 const result = await this.upload({ ...options, attributes })
589 if (wait) await waitJobs([ this.server ])
591 return { ...result, name }
594 // ---------------------------------------------------------------------------
596 removeHLSFiles (options: OverrideCommandOptions & {
597 videoId: number | string
599 const path = '/api/v1/videos/' + options.videoId + '/hls'
601 return this.deleteRequest({
606 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
610 removeWebTorrentFiles (options: OverrideCommandOptions & {
611 videoId: number | string
613 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
615 return this.deleteRequest({
620 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
624 runTranscoding (options: OverrideCommandOptions & {
625 videoId: number | string
626 transcodingType: 'hls' | 'webtorrent'
628 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
630 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
632 return this.postBodyRequest({
638 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
642 // ---------------------------------------------------------------------------
644 private buildListQuery (options: VideosCommonQuery) {
645 return pick(options, [
662 private buildUploadFields (attributes: VideoEdit) {
663 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
666 private buildUploadAttaches (attributes: VideoEdit) {
667 const attaches: { [ name: string ]: string } = {}
669 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
670 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
673 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)