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'
27 export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
29 thumbnailfile?: string
33 export class VideosCommand extends AbstractCommand {
34 getCategories (options: OverrideCommandOptions = {}) {
35 const path = '/api/v1/videos/categories'
37 return this.getRequestBody<{ [id: number]: string }>({
42 defaultExpectedStatus: HttpStatusCode.OK_200
46 getLicences (options: OverrideCommandOptions = {}) {
47 const path = '/api/v1/videos/licences'
49 return this.getRequestBody<{ [id: number]: string }>({
54 defaultExpectedStatus: HttpStatusCode.OK_200
58 getLanguages (options: OverrideCommandOptions = {}) {
59 const path = '/api/v1/videos/languages'
61 return this.getRequestBody<{ [id: string]: string }>({
66 defaultExpectedStatus: HttpStatusCode.OK_200
70 getPrivacies (options: OverrideCommandOptions = {}) {
71 const path = '/api/v1/videos/privacies'
73 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
78 defaultExpectedStatus: HttpStatusCode.OK_200
82 // ---------------------------------------------------------------------------
84 getDescription (options: OverrideCommandOptions & {
85 descriptionPath: string
87 return this.getRequestBody<{ description: string }>({
89 path: options.descriptionPath,
92 defaultExpectedStatus: HttpStatusCode.OK_200
96 getFileMetadata (options: OverrideCommandOptions & {
99 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
103 implicitToken: false,
104 defaultExpectedStatus: HttpStatusCode.OK_200
108 // ---------------------------------------------------------------------------
110 rate (options: OverrideCommandOptions & {
112 rating: UserVideoRateType
114 const { id, rating } = options
115 const path = '/api/v1/videos/' + id + '/rate'
117 return this.putBodyRequest({
123 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
127 // ---------------------------------------------------------------------------
129 get (options: OverrideCommandOptions & {
132 const path = '/api/v1/videos/' + options.id
134 return this.getRequestBody<VideoDetails>({
138 implicitToken: false,
139 defaultExpectedStatus: HttpStatusCode.OK_200
143 getWithToken (options: OverrideCommandOptions & {
149 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
153 async getId (options: OverrideCommandOptions & {
154 uuid: number | string
156 const { uuid } = options
158 if (validator.isUUID('' + uuid) === false) return uuid as number
160 const { id } = await this.get({ ...options, id: uuid })
165 async listFiles (options: OverrideCommandOptions & {
168 const video = await this.get(options)
170 const files = video.files || []
171 const hlsFiles = video.streamingPlaylists[0]?.files || []
173 return files.concat(hlsFiles)
176 // ---------------------------------------------------------------------------
178 listMyVideos (options: OverrideCommandOptions & {
186 const path = '/api/v1/users/me/videos'
188 return this.getRequestBody<ResultList<Video>>({
192 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
194 defaultExpectedStatus: HttpStatusCode.OK_200
198 // ---------------------------------------------------------------------------
200 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
201 const path = '/api/v1/videos'
203 const query = this.buildListQuery(options)
205 return this.getRequestBody<ResultList<Video>>({
209 query: { sort: 'name', ...query },
210 implicitToken: false,
211 defaultExpectedStatus: HttpStatusCode.OK_200
215 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
219 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
223 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
226 const { handle, search } = options
227 const path = '/api/v1/accounts/' + handle + '/videos'
229 return this.getRequestBody<ResultList<Video>>({
233 query: { search, ...this.buildListQuery(options) },
235 defaultExpectedStatus: HttpStatusCode.OK_200
239 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
242 const { handle } = options
243 const path = '/api/v1/video-channels/' + handle + '/videos'
245 return this.getRequestBody<ResultList<Video>>({
249 query: this.buildListQuery(options),
251 defaultExpectedStatus: HttpStatusCode.OK_200
255 // ---------------------------------------------------------------------------
257 async find (options: OverrideCommandOptions & {
260 const { data } = await this.list(options)
262 return data.find(v => v.name === options.name)
265 // ---------------------------------------------------------------------------
267 update (options: OverrideCommandOptions & {
269 attributes?: VideoEdit
271 const { id, attributes = {} } = options
272 const path = '/api/v1/videos/' + id
275 if (attributes.thumbnailfile || attributes.previewfile) {
276 const attaches: any = {}
277 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
278 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
280 return this.putUploadRequest({
284 fields: options.attributes,
286 thumbnailfile: attributes.thumbnailfile,
287 previewfile: attributes.previewfile
290 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
294 return this.putBodyRequest({
298 fields: options.attributes,
300 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
304 remove (options: OverrideCommandOptions & {
307 const path = '/api/v1/videos/' + options.id
309 return unwrapBody(this.deleteRequest({
314 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
319 const { data } = await this.list()
321 for (const v of data) {
322 await this.remove({ id: v.id })
326 // ---------------------------------------------------------------------------
328 async upload (options: OverrideCommandOptions & {
329 attributes?: VideoEdit
330 mode?: 'legacy' | 'resumable' // default legacy
332 const { mode = 'legacy' } = options
333 let defaultChannelId = 1
336 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
337 defaultChannelId = videoChannels[0].id
338 } catch (e) { /* empty */ }
340 // Override default attributes
342 name: 'my super video',
346 channelId: defaultChannelId,
348 waitTranscoding: false,
349 description: 'my super description',
350 support: 'my super support text',
352 privacy: VideoPrivacy.PUBLIC,
353 commentsEnabled: true,
354 downloadEnabled: true,
355 fixture: 'video_short.webm',
357 ...options.attributes
360 const created = mode === 'legacy'
361 ? await this.buildLegacyUpload({ ...options, attributes })
362 : await this.buildResumeUpload({ ...options, attributes })
364 // Wait torrent generation
365 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
366 if (expectedStatus === HttpStatusCode.OK_200) {
367 let video: VideoDetails
370 video = await this.getWithToken({ ...options, id: created.uuid })
373 } while (!video.files[0].torrentUrl)
379 async buildLegacyUpload (options: OverrideCommandOptions & {
380 attributes: VideoEdit
381 }): Promise<VideoCreateResult> {
382 const path = '/api/v1/videos/upload'
384 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
388 fields: this.buildUploadFields(options.attributes),
389 attaches: this.buildUploadAttaches(options.attributes),
391 defaultExpectedStatus: HttpStatusCode.OK_200
392 })).then(body => body.video || body as any)
395 async buildResumeUpload (options: OverrideCommandOptions & {
396 attributes: VideoEdit
397 }): Promise<VideoCreateResult> {
398 const { attributes, expectedStatus } = options
401 let videoFilePath: string
402 let mimetype = 'video/mp4'
404 if (attributes.fixture) {
405 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
406 size = (await stat(videoFilePath)).size
408 if (videoFilePath.endsWith('.mkv')) {
409 mimetype = 'video/x-matroska'
410 } else if (videoFilePath.endsWith('.webm')) {
411 mimetype = 'video/webm'
415 // Do not check status automatically, we'll check it manually
416 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
417 const initStatus = initializeSessionRes.status
419 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
420 const locationHeader = initializeSessionRes.header['location']
421 expect(locationHeader).to.not.be.undefined
423 const pathUploadId = locationHeader.split('?')[1]
425 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
427 if (result.statusCode === HttpStatusCode.OK_200) {
428 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
431 return result.body?.video || result.body as any
434 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
435 ? HttpStatusCode.CREATED_201
438 expect(initStatus).to.equal(expectedInitStatus)
440 return initializeSessionRes.body.video || initializeSessionRes.body
443 async prepareResumableUpload (options: OverrideCommandOptions & {
444 attributes: VideoEdit
448 originalName?: string
449 lastModified?: number
451 const { attributes, originalName, lastModified, size, mimetype } = options
453 const path = '/api/v1/videos/upload-resumable'
455 return this.postUploadRequest({
460 'X-Upload-Content-Type': mimetype,
461 'X-Upload-Content-Length': size.toString()
464 filename: attributes.fixture,
468 ...this.buildUploadFields(options.attributes)
471 // Fixture will be sent later
472 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
475 defaultExpectedStatus: null
479 sendResumableChunks (options: OverrideCommandOptions & {
481 videoFilePath: string
483 contentLength?: number
484 contentRangeBuilder?: (start: number, chunk: any) => string
485 digestBuilder?: (chunk: any) => string
494 expectedStatus = HttpStatusCode.OK_200
497 const path = '/api/v1/videos/upload-resumable'
500 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
501 const url = this.server.url
503 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
504 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
505 readable.on('data', async function onData (chunk) {
509 'Authorization': 'Bearer ' + token,
510 'Content-Type': 'application/octet-stream',
511 'Content-Range': contentRangeBuilder
512 ? contentRangeBuilder(start, chunk)
513 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
514 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
518 Object.assign(headers, { digest: digestBuilder(chunk) })
521 const res = await got<{ video: VideoCreateResult }>({
525 path: path + '?' + pathUploadId,
527 responseType: 'json',
528 throwHttpErrors: false
531 start += chunk.length
533 if (res.statusCode === expectedStatus) {
537 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
538 readable.off('data', onData)
539 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
547 endResumableUpload (options: OverrideCommandOptions & {
550 return this.deleteRequest({
553 path: '/api/v1/videos/upload-resumable',
554 rawQuery: options.pathUploadId,
556 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
560 quickUpload (options: OverrideCommandOptions & {
563 privacy?: VideoPrivacy
566 const attributes: VideoEdit = { name: options.name }
567 if (options.nsfw) attributes.nsfw = options.nsfw
568 if (options.privacy) attributes.privacy = options.privacy
569 if (options.fixture) attributes.fixture = options.fixture
571 return this.upload({ ...options, attributes })
574 async randomUpload (options: OverrideCommandOptions & {
575 wait?: boolean // default true
576 additionalParams?: VideoEdit & { prefixName?: string }
578 const { wait = true, additionalParams } = options
579 const prefixName = additionalParams?.prefixName || ''
580 const name = prefixName + buildUUID()
582 const attributes = { name, ...additionalParams }
584 const result = await this.upload({ ...options, attributes })
586 if (wait) await waitJobs([ this.server ])
588 return { ...result, name }
591 // ---------------------------------------------------------------------------
593 removeHLSFiles (options: OverrideCommandOptions & {
594 videoId: number | string
596 const path = '/api/v1/videos/' + options.videoId + '/hls'
598 return this.deleteRequest({
603 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
607 removeWebTorrentFiles (options: OverrideCommandOptions & {
608 videoId: number | string
610 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
612 return this.deleteRequest({
617 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
621 runTranscoding (options: OverrideCommandOptions & {
622 videoId: number | string
623 transcodingType: 'hls' | 'webtorrent'
625 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
627 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
629 return this.postBodyRequest({
635 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
639 // ---------------------------------------------------------------------------
641 private buildListQuery (options: VideosCommonQuery) {
642 return pick(options, [
659 private buildUploadFields (attributes: VideoEdit) {
660 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
663 private buildUploadAttaches (attributes: VideoEdit) {
664 const attaches: { [ name: string ]: string } = {}
666 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
667 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
670 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)