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
486 const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options
488 const path = '/api/v1/videos/upload-resumable'
491 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
492 const url = this.server.url
494 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
495 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
496 readable.on('data', async function onData (chunk) {
500 'Authorization': 'Bearer ' + token,
501 'Content-Type': 'application/octet-stream',
502 'Content-Range': contentRangeBuilder
503 ? contentRangeBuilder(start, chunk)
504 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
505 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
508 const res = await got<{ video: VideoCreateResult }>({
512 path: path + '?' + pathUploadId,
514 responseType: 'json',
515 throwHttpErrors: false
518 start += chunk.length
520 if (res.statusCode === expectedStatus) {
524 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
525 readable.off('data', onData)
526 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
534 endResumableUpload (options: OverrideCommandOptions & {
537 return this.deleteRequest({
540 path: '/api/v1/videos/upload-resumable',
541 rawQuery: options.pathUploadId,
543 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
547 quickUpload (options: OverrideCommandOptions & {
550 privacy?: VideoPrivacy
553 const attributes: VideoEdit = { name: options.name }
554 if (options.nsfw) attributes.nsfw = options.nsfw
555 if (options.privacy) attributes.privacy = options.privacy
556 if (options.fixture) attributes.fixture = options.fixture
558 return this.upload({ ...options, attributes })
561 async randomUpload (options: OverrideCommandOptions & {
562 wait?: boolean // default true
563 additionalParams?: VideoEdit & { prefixName?: string }
565 const { wait = true, additionalParams } = options
566 const prefixName = additionalParams?.prefixName || ''
567 const name = prefixName + buildUUID()
569 const attributes = { name, ...additionalParams }
571 const result = await this.upload({ ...options, attributes })
573 if (wait) await waitJobs([ this.server ])
575 return { ...result, name }
578 // ---------------------------------------------------------------------------
580 removeHLSFiles (options: OverrideCommandOptions & {
581 videoId: number | string
583 const path = '/api/v1/videos/' + options.videoId + '/hls'
585 return this.deleteRequest({
590 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
594 removeWebTorrentFiles (options: OverrideCommandOptions & {
595 videoId: number | string
597 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
599 return this.deleteRequest({
604 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
608 runTranscoding (options: OverrideCommandOptions & {
609 videoId: number | string
610 transcodingType: 'hls' | 'webtorrent'
612 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
614 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
616 return this.postBodyRequest({
622 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
626 // ---------------------------------------------------------------------------
628 private buildListQuery (options: VideosCommonQuery) {
629 return pick(options, [
646 private buildUploadFields (attributes: VideoEdit) {
647 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
650 private buildUploadAttaches (attributes: VideoEdit) {
651 const attaches: { [ name: string ]: string } = {}
653 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
654 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
657 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)