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 { buildUUID } from '@shared/core-utils/uuid'
9 import { pick } from '@shared/core-utils'
21 VideoTranscodingCreate
22 } from '@shared/models'
23 import { buildAbsoluteFixturePath, wait } from '../miscs'
24 import { unwrapBody } from '../requests'
25 import { waitJobs } from '../server'
26 import { AbstractCommand, OverrideCommandOptions } from '../shared'
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 view (options: OverrideCommandOptions & {
113 xForwardedFor?: string
115 const { id, xForwardedFor } = options
116 const path = '/api/v1/videos/' + id + '/views'
118 return this.postBodyRequest({
123 implicitToken: false,
124 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
128 rate (options: OverrideCommandOptions & {
130 rating: UserVideoRateType
132 const { id, rating } = options
133 const path = '/api/v1/videos/' + id + '/rate'
135 return this.putBodyRequest({
141 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
145 // ---------------------------------------------------------------------------
147 get (options: OverrideCommandOptions & {
150 const path = '/api/v1/videos/' + options.id
152 return this.getRequestBody<VideoDetails>({
156 implicitToken: false,
157 defaultExpectedStatus: HttpStatusCode.OK_200
161 getWithToken (options: OverrideCommandOptions & {
167 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
171 async getId (options: OverrideCommandOptions & {
172 uuid: number | string
174 const { uuid } = options
176 if (validator.isUUID('' + uuid) === false) return uuid as number
178 const { id } = await this.get({ ...options, id: uuid })
183 async listFiles (options: OverrideCommandOptions & {
186 const video = await this.get(options)
188 const files = video.files || []
189 const hlsFiles = video.streamingPlaylists[0]?.files || []
191 return files.concat(hlsFiles)
194 // ---------------------------------------------------------------------------
196 listMyVideos (options: OverrideCommandOptions & {
204 const path = '/api/v1/users/me/videos'
206 return this.getRequestBody<ResultList<Video>>({
210 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
212 defaultExpectedStatus: HttpStatusCode.OK_200
216 // ---------------------------------------------------------------------------
218 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
219 const path = '/api/v1/videos'
221 const query = this.buildListQuery(options)
223 return this.getRequestBody<ResultList<Video>>({
227 query: { sort: 'name', ...query },
228 implicitToken: false,
229 defaultExpectedStatus: HttpStatusCode.OK_200
233 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
237 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
241 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
244 const { handle, search } = options
245 const path = '/api/v1/accounts/' + handle + '/videos'
247 return this.getRequestBody<ResultList<Video>>({
251 query: { search, ...this.buildListQuery(options) },
253 defaultExpectedStatus: HttpStatusCode.OK_200
257 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
260 const { handle } = options
261 const path = '/api/v1/video-channels/' + handle + '/videos'
263 return this.getRequestBody<ResultList<Video>>({
267 query: this.buildListQuery(options),
269 defaultExpectedStatus: HttpStatusCode.OK_200
273 // ---------------------------------------------------------------------------
275 async find (options: OverrideCommandOptions & {
278 const { data } = await this.list(options)
280 return data.find(v => v.name === options.name)
283 // ---------------------------------------------------------------------------
285 update (options: OverrideCommandOptions & {
287 attributes?: VideoEdit
289 const { id, attributes = {} } = options
290 const path = '/api/v1/videos/' + id
293 if (attributes.thumbnailfile || attributes.previewfile) {
294 const attaches: any = {}
295 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
296 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
298 return this.putUploadRequest({
302 fields: options.attributes,
304 thumbnailfile: attributes.thumbnailfile,
305 previewfile: attributes.previewfile
308 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
312 return this.putBodyRequest({
316 fields: options.attributes,
318 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
322 remove (options: OverrideCommandOptions & {
325 const path = '/api/v1/videos/' + options.id
327 return unwrapBody(this.deleteRequest({
332 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
337 const { data } = await this.list()
339 for (const v of data) {
340 await this.remove({ id: v.id })
344 // ---------------------------------------------------------------------------
346 async upload (options: OverrideCommandOptions & {
347 attributes?: VideoEdit
348 mode?: 'legacy' | 'resumable' // default legacy
350 const { mode = 'legacy' } = options
351 let defaultChannelId = 1
354 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
355 defaultChannelId = videoChannels[0].id
356 } catch (e) { /* empty */ }
358 // Override default attributes
360 name: 'my super video',
364 channelId: defaultChannelId,
366 waitTranscoding: false,
367 description: 'my super description',
368 support: 'my super support text',
370 privacy: VideoPrivacy.PUBLIC,
371 commentsEnabled: true,
372 downloadEnabled: true,
373 fixture: 'video_short.webm',
375 ...options.attributes
378 const created = mode === 'legacy'
379 ? await this.buildLegacyUpload({ ...options, attributes })
380 : await this.buildResumeUpload({ ...options, attributes })
382 // Wait torrent generation
383 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
384 if (expectedStatus === HttpStatusCode.OK_200) {
385 let video: VideoDetails
388 video = await this.getWithToken({ ...options, id: created.uuid })
391 } while (!video.files[0].torrentUrl)
397 async buildLegacyUpload (options: OverrideCommandOptions & {
398 attributes: VideoEdit
399 }): Promise<VideoCreateResult> {
400 const path = '/api/v1/videos/upload'
402 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
406 fields: this.buildUploadFields(options.attributes),
407 attaches: this.buildUploadAttaches(options.attributes),
409 defaultExpectedStatus: HttpStatusCode.OK_200
410 })).then(body => body.video || body as any)
413 async buildResumeUpload (options: OverrideCommandOptions & {
414 attributes: VideoEdit
415 }): Promise<VideoCreateResult> {
416 const { attributes, expectedStatus } = options
419 let videoFilePath: string
420 let mimetype = 'video/mp4'
422 if (attributes.fixture) {
423 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
424 size = (await stat(videoFilePath)).size
426 if (videoFilePath.endsWith('.mkv')) {
427 mimetype = 'video/x-matroska'
428 } else if (videoFilePath.endsWith('.webm')) {
429 mimetype = 'video/webm'
433 // Do not check status automatically, we'll check it manually
434 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
435 const initStatus = initializeSessionRes.status
437 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
438 const locationHeader = initializeSessionRes.header['location']
439 expect(locationHeader).to.not.be.undefined
441 const pathUploadId = locationHeader.split('?')[1]
443 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
445 if (result.statusCode === HttpStatusCode.OK_200) {
446 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
449 return result.body?.video || result.body as any
452 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
453 ? HttpStatusCode.CREATED_201
456 expect(initStatus).to.equal(expectedInitStatus)
458 return initializeSessionRes.body.video || initializeSessionRes.body
461 async prepareResumableUpload (options: OverrideCommandOptions & {
462 attributes: VideoEdit
466 originalName?: string
467 lastModified?: number
469 const { attributes, originalName, lastModified, size, mimetype } = options
471 const path = '/api/v1/videos/upload-resumable'
473 return this.postUploadRequest({
478 'X-Upload-Content-Type': mimetype,
479 'X-Upload-Content-Length': size.toString()
482 filename: attributes.fixture,
486 ...this.buildUploadFields(options.attributes)
489 // Fixture will be sent later
490 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
493 defaultExpectedStatus: null
497 sendResumableChunks (options: OverrideCommandOptions & {
499 videoFilePath: string
501 contentLength?: number
502 contentRangeBuilder?: (start: number, chunk: any) => string
504 const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options
506 const path = '/api/v1/videos/upload-resumable'
509 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
510 const url = this.server.url
512 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
513 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
514 readable.on('data', async function onData (chunk) {
518 'Authorization': 'Bearer ' + token,
519 'Content-Type': 'application/octet-stream',
520 'Content-Range': contentRangeBuilder
521 ? contentRangeBuilder(start, chunk)
522 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
523 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
526 const res = await got<{ video: VideoCreateResult }>({
530 path: path + '?' + pathUploadId,
532 responseType: 'json',
533 throwHttpErrors: false
536 start += chunk.length
538 if (res.statusCode === expectedStatus) {
542 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
543 readable.off('data', onData)
544 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
552 endResumableUpload (options: OverrideCommandOptions & {
555 return this.deleteRequest({
558 path: '/api/v1/videos/upload-resumable',
559 rawQuery: options.pathUploadId,
561 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
565 quickUpload (options: OverrideCommandOptions & {
568 privacy?: VideoPrivacy
571 const attributes: VideoEdit = { name: options.name }
572 if (options.nsfw) attributes.nsfw = options.nsfw
573 if (options.privacy) attributes.privacy = options.privacy
574 if (options.fixture) attributes.fixture = options.fixture
576 return this.upload({ ...options, attributes })
579 async randomUpload (options: OverrideCommandOptions & {
580 wait?: boolean // default true
581 additionalParams?: VideoEdit & { prefixName?: string }
583 const { wait = true, additionalParams } = options
584 const prefixName = additionalParams?.prefixName || ''
585 const name = prefixName + buildUUID()
587 const attributes = { name, ...additionalParams }
589 const result = await this.upload({ ...options, attributes })
591 if (wait) await waitJobs([ this.server ])
593 return { ...result, name }
596 // ---------------------------------------------------------------------------
598 removeHLSFiles (options: OverrideCommandOptions & {
599 videoId: number | string
601 const path = '/api/v1/videos/' + options.videoId + '/hls'
603 return this.deleteRequest({
608 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
612 removeWebTorrentFiles (options: OverrideCommandOptions & {
613 videoId: number | string
615 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
617 return this.deleteRequest({
622 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
626 runTranscoding (options: OverrideCommandOptions & {
627 videoId: number | string
628 transcodingType: 'hls' | 'webtorrent'
630 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
632 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
634 return this.postBodyRequest({
640 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
644 // ---------------------------------------------------------------------------
646 private buildListQuery (options: VideosCommonQuery) {
647 return pick(options, [
664 private buildUploadFields (attributes: VideoEdit) {
665 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
668 private buildUploadAttaches (attributes: VideoEdit) {
669 const attaches: { [ name: string ]: string } = {}
671 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
672 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
675 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)