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, pick, wait } from '@shared/core-utils'
9 import { buildUUID } from '@shared/extra-utils'
21 VideoTranscodingCreate
22 } from '@shared/models'
23 import { unwrapBody } from '../requests'
24 import { waitJobs } from '../server'
25 import { AbstractCommand, OverrideCommandOptions } from '../shared'
26 import { VideoSource } from '@shared/models/videos/video-source'
28 export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
30 thumbnailfile?: string
34 export class VideosCommand extends AbstractCommand {
35 getCategories (options: OverrideCommandOptions = {}) {
36 const path = '/api/v1/videos/categories'
38 return this.getRequestBody<{ [id: number]: string }>({
43 defaultExpectedStatus: HttpStatusCode.OK_200
47 getLicences (options: OverrideCommandOptions = {}) {
48 const path = '/api/v1/videos/licences'
50 return this.getRequestBody<{ [id: number]: string }>({
55 defaultExpectedStatus: HttpStatusCode.OK_200
59 getLanguages (options: OverrideCommandOptions = {}) {
60 const path = '/api/v1/videos/languages'
62 return this.getRequestBody<{ [id: string]: string }>({
67 defaultExpectedStatus: HttpStatusCode.OK_200
71 getPrivacies (options: OverrideCommandOptions = {}) {
72 const path = '/api/v1/videos/privacies'
74 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
79 defaultExpectedStatus: HttpStatusCode.OK_200
83 // ---------------------------------------------------------------------------
85 getDescription (options: OverrideCommandOptions & {
86 descriptionPath: string
88 return this.getRequestBody<{ description: string }>({
90 path: options.descriptionPath,
93 defaultExpectedStatus: HttpStatusCode.OK_200
97 getFileMetadata (options: OverrideCommandOptions & {
100 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
104 implicitToken: false,
105 defaultExpectedStatus: HttpStatusCode.OK_200
109 // ---------------------------------------------------------------------------
111 rate (options: OverrideCommandOptions & {
113 rating: UserVideoRateType
115 const { id, rating } = options
116 const path = '/api/v1/videos/' + id + '/rate'
118 return this.putBodyRequest({
124 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
128 // ---------------------------------------------------------------------------
130 get (options: OverrideCommandOptions & {
133 const path = '/api/v1/videos/' + options.id
135 return this.getRequestBody<VideoDetails>({
139 implicitToken: false,
140 defaultExpectedStatus: HttpStatusCode.OK_200
144 getWithToken (options: OverrideCommandOptions & {
150 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
154 getSource (options: OverrideCommandOptions & {
157 const path = '/api/v1/videos/' + options.id + '/source'
159 return this.getRequestBody<VideoSource>({
164 defaultExpectedStatus: HttpStatusCode.OK_200
168 async getId (options: OverrideCommandOptions & {
169 uuid: number | string
171 const { uuid } = options
173 if (validator.isUUID('' + uuid) === false) return uuid as number
175 const { id } = await this.get({ ...options, id: uuid })
180 async listFiles (options: OverrideCommandOptions & {
183 const video = await this.get(options)
185 const files = video.files || []
186 const hlsFiles = video.streamingPlaylists[0]?.files || []
188 return files.concat(hlsFiles)
191 // ---------------------------------------------------------------------------
193 listMyVideos (options: OverrideCommandOptions & {
201 const path = '/api/v1/users/me/videos'
203 return this.getRequestBody<ResultList<Video>>({
207 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
209 defaultExpectedStatus: HttpStatusCode.OK_200
213 // ---------------------------------------------------------------------------
215 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
216 const path = '/api/v1/videos'
218 const query = this.buildListQuery(options)
220 return this.getRequestBody<ResultList<Video>>({
224 query: { sort: 'name', ...query },
225 implicitToken: false,
226 defaultExpectedStatus: HttpStatusCode.OK_200
230 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
234 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
238 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
241 const { handle, search } = options
242 const path = '/api/v1/accounts/' + handle + '/videos'
244 return this.getRequestBody<ResultList<Video>>({
248 query: { search, ...this.buildListQuery(options) },
250 defaultExpectedStatus: HttpStatusCode.OK_200
254 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
257 const { handle } = options
258 const path = '/api/v1/video-channels/' + handle + '/videos'
260 return this.getRequestBody<ResultList<Video>>({
264 query: this.buildListQuery(options),
266 defaultExpectedStatus: HttpStatusCode.OK_200
270 // ---------------------------------------------------------------------------
272 async find (options: OverrideCommandOptions & {
275 const { data } = await this.list(options)
277 return data.find(v => v.name === options.name)
280 // ---------------------------------------------------------------------------
282 update (options: OverrideCommandOptions & {
284 attributes?: VideoEdit
286 const { id, attributes = {} } = options
287 const path = '/api/v1/videos/' + id
290 if (attributes.thumbnailfile || attributes.previewfile) {
291 const attaches: any = {}
292 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
293 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
295 return this.putUploadRequest({
299 fields: options.attributes,
301 thumbnailfile: attributes.thumbnailfile,
302 previewfile: attributes.previewfile
305 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
309 return this.putBodyRequest({
313 fields: options.attributes,
315 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
319 remove (options: OverrideCommandOptions & {
322 const path = '/api/v1/videos/' + options.id
324 return unwrapBody(this.deleteRequest({
329 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
334 const { data } = await this.list()
336 for (const v of data) {
337 await this.remove({ id: v.id })
341 // ---------------------------------------------------------------------------
343 async upload (options: OverrideCommandOptions & {
344 attributes?: VideoEdit
345 mode?: 'legacy' | 'resumable' // default legacy
347 const { mode = 'legacy' } = options
348 let defaultChannelId = 1
351 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
352 defaultChannelId = videoChannels[0].id
353 } catch (e) { /* empty */ }
355 // Override default attributes
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',
372 ...options.attributes
375 const created = mode === 'legacy'
376 ? await this.buildLegacyUpload({ ...options, attributes })
377 : await this.buildResumeUpload({ ...options, attributes })
379 // Wait torrent generation
380 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
381 if (expectedStatus === HttpStatusCode.OK_200) {
382 let video: VideoDetails
385 video = await this.getWithToken({ ...options, id: created.uuid })
388 } while (!video.files[0].torrentUrl)
394 async buildLegacyUpload (options: OverrideCommandOptions & {
395 attributes: VideoEdit
396 }): Promise<VideoCreateResult> {
397 const path = '/api/v1/videos/upload'
399 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
403 fields: this.buildUploadFields(options.attributes),
404 attaches: this.buildUploadAttaches(options.attributes),
406 defaultExpectedStatus: HttpStatusCode.OK_200
407 })).then(body => body.video || body as any)
410 async buildResumeUpload (options: OverrideCommandOptions & {
411 attributes: VideoEdit
412 }): Promise<VideoCreateResult> {
413 const { attributes, expectedStatus } = options
416 let videoFilePath: string
417 let mimetype = 'video/mp4'
419 if (attributes.fixture) {
420 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
421 size = (await stat(videoFilePath)).size
423 if (videoFilePath.endsWith('.mkv')) {
424 mimetype = 'video/x-matroska'
425 } else if (videoFilePath.endsWith('.webm')) {
426 mimetype = 'video/webm'
430 // Do not check status automatically, we'll check it manually
431 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
432 const initStatus = initializeSessionRes.status
434 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
435 const locationHeader = initializeSessionRes.header['location']
436 expect(locationHeader).to.not.be.undefined
438 const pathUploadId = locationHeader.split('?')[1]
440 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
442 if (result.statusCode === HttpStatusCode.OK_200) {
443 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
446 return result.body?.video || result.body as any
449 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
450 ? HttpStatusCode.CREATED_201
453 expect(initStatus).to.equal(expectedInitStatus)
455 return initializeSessionRes.body.video || initializeSessionRes.body
458 async prepareResumableUpload (options: OverrideCommandOptions & {
459 attributes: VideoEdit
463 originalName?: string
464 lastModified?: number
466 const { attributes, originalName, lastModified, size, mimetype } = options
468 const path = '/api/v1/videos/upload-resumable'
470 return this.postUploadRequest({
475 'X-Upload-Content-Type': mimetype,
476 'X-Upload-Content-Length': size.toString()
479 filename: attributes.fixture,
483 ...this.buildUploadFields(options.attributes)
486 // Fixture will be sent later
487 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
490 defaultExpectedStatus: null
494 sendResumableChunks (options: OverrideCommandOptions & {
496 videoFilePath: string
498 contentLength?: number
499 contentRangeBuilder?: (start: number, chunk: any) => string
500 digestBuilder?: (chunk: any) => string
509 expectedStatus = HttpStatusCode.OK_200
512 const path = '/api/v1/videos/upload-resumable'
515 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
516 const url = this.server.url
518 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
519 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
520 readable.on('data', async function onData (chunk) {
524 'Authorization': 'Bearer ' + token,
525 'Content-Type': 'application/octet-stream',
526 'Content-Range': contentRangeBuilder
527 ? contentRangeBuilder(start, chunk)
528 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
529 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
533 Object.assign(headers, { digest: digestBuilder(chunk) })
536 const res = await got<{ video: VideoCreateResult }>({
540 path: path + '?' + pathUploadId,
542 responseType: 'json',
543 throwHttpErrors: false
546 start += chunk.length
548 if (res.statusCode === expectedStatus) {
552 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
553 readable.off('data', onData)
554 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
562 endResumableUpload (options: OverrideCommandOptions & {
565 return this.deleteRequest({
568 path: '/api/v1/videos/upload-resumable',
569 rawQuery: options.pathUploadId,
571 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
575 quickUpload (options: OverrideCommandOptions & {
578 privacy?: VideoPrivacy
581 const attributes: VideoEdit = { name: options.name }
582 if (options.nsfw) attributes.nsfw = options.nsfw
583 if (options.privacy) attributes.privacy = options.privacy
584 if (options.fixture) attributes.fixture = options.fixture
586 return this.upload({ ...options, attributes })
589 async randomUpload (options: OverrideCommandOptions & {
590 wait?: boolean // default true
591 additionalParams?: VideoEdit & { prefixName?: string }
593 const { wait = true, additionalParams } = options
594 const prefixName = additionalParams?.prefixName || ''
595 const name = prefixName + buildUUID()
597 const attributes = { name, ...additionalParams }
599 const result = await this.upload({ ...options, attributes })
601 if (wait) await waitJobs([ this.server ])
603 return { ...result, name }
606 // ---------------------------------------------------------------------------
608 removeHLSFiles (options: OverrideCommandOptions & {
609 videoId: number | string
611 const path = '/api/v1/videos/' + options.videoId + '/hls'
613 return this.deleteRequest({
618 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
622 removeWebTorrentFiles (options: OverrideCommandOptions & {
623 videoId: number | string
625 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
627 return this.deleteRequest({
632 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
636 runTranscoding (options: OverrideCommandOptions & {
637 videoId: number | string
638 transcodingType: 'hls' | 'webtorrent'
640 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
642 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
644 return this.postBodyRequest({
650 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
654 // ---------------------------------------------------------------------------
656 private buildListQuery (options: VideosCommonQuery) {
657 return pick(options, [
674 private buildUploadFields (attributes: VideoEdit) {
675 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
678 private buildUploadAttaches (attributes: VideoEdit) {
679 const attaches: { [ name: string ]: string } = {}
681 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
682 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
685 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)