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 validator from 'validator'
7 import { buildAbsoluteFixturePath, getAllPrivacies, omit, pick, wait } from '@shared/core-utils'
8 import { buildUUID } from '@shared/extra-utils'
21 VideoTranscodingCreate
22 } from '@shared/models'
23 import { VideoSource } from '@shared/models/videos/video-source'
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 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 listAllForAdmin (options: OverrideCommandOptions & VideosCommonQuery = {}) {
239 const include = VideoInclude.NOT_PUBLISHED_STATE | VideoInclude.BLACKLISTED | VideoInclude.BLOCKED_OWNER
241 const privacyOneOf = getAllPrivacies()
250 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
254 listByAccount (options: OverrideCommandOptions & VideosCommonQuery & {
257 const { handle, search } = options
258 const path = '/api/v1/accounts/' + handle + '/videos'
260 return this.getRequestBody<ResultList<Video>>({
264 query: { search, ...this.buildListQuery(options) },
266 defaultExpectedStatus: HttpStatusCode.OK_200
270 listByChannel (options: OverrideCommandOptions & VideosCommonQuery & {
273 const { handle } = options
274 const path = '/api/v1/video-channels/' + handle + '/videos'
276 return this.getRequestBody<ResultList<Video>>({
280 query: this.buildListQuery(options),
282 defaultExpectedStatus: HttpStatusCode.OK_200
286 // ---------------------------------------------------------------------------
288 async find (options: OverrideCommandOptions & {
291 const { data } = await this.list(options)
293 return data.find(v => v.name === options.name)
296 // ---------------------------------------------------------------------------
298 update (options: OverrideCommandOptions & {
300 attributes?: VideoEdit
302 const { id, attributes = {} } = options
303 const path = '/api/v1/videos/' + id
306 if (attributes.thumbnailfile || attributes.previewfile) {
307 const attaches: any = {}
308 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
309 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
311 return this.putUploadRequest({
315 fields: options.attributes,
317 thumbnailfile: attributes.thumbnailfile,
318 previewfile: attributes.previewfile
321 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
325 return this.putBodyRequest({
329 fields: options.attributes,
331 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
335 remove (options: OverrideCommandOptions & {
338 const path = '/api/v1/videos/' + options.id
340 return unwrapBody(this.deleteRequest({
345 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
350 const { data } = await this.list()
352 for (const v of data) {
353 await this.remove({ id: v.id })
357 // ---------------------------------------------------------------------------
359 async upload (options: OverrideCommandOptions & {
360 attributes?: VideoEdit
361 mode?: 'legacy' | 'resumable' // default legacy
362 waitTorrentGeneration?: boolean // default true
364 const { mode = 'legacy', waitTorrentGeneration = true } = options
365 let defaultChannelId = 1
368 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
369 defaultChannelId = videoChannels[0].id
370 } catch (e) { /* empty */ }
372 // Override default attributes
374 name: 'my super video',
378 channelId: defaultChannelId,
380 waitTranscoding: false,
381 description: 'my super description',
382 support: 'my super support text',
384 privacy: VideoPrivacy.PUBLIC,
385 commentsEnabled: true,
386 downloadEnabled: true,
387 fixture: 'video_short.webm',
389 ...options.attributes
392 const created = mode === 'legacy'
393 ? await this.buildLegacyUpload({ ...options, attributes })
394 : await this.buildResumeUpload({ ...options, attributes })
396 // Wait torrent generation
397 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
398 if (expectedStatus === HttpStatusCode.OK_200 && waitTorrentGeneration) {
399 let video: VideoDetails
402 video = await this.getWithToken({ ...options, id: created.uuid })
405 } while (!video.files[0].torrentUrl)
411 async buildLegacyUpload (options: OverrideCommandOptions & {
412 attributes: VideoEdit
413 }): Promise<VideoCreateResult> {
414 const path = '/api/v1/videos/upload'
416 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
420 fields: this.buildUploadFields(options.attributes),
421 attaches: this.buildUploadAttaches(options.attributes),
423 defaultExpectedStatus: HttpStatusCode.OK_200
424 })).then(body => body.video || body as any)
427 async buildResumeUpload (options: OverrideCommandOptions & {
428 attributes: VideoEdit
429 }): Promise<VideoCreateResult> {
430 const { attributes, expectedStatus } = options
433 let videoFilePath: string
434 let mimetype = 'video/mp4'
436 if (attributes.fixture) {
437 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
438 size = (await stat(videoFilePath)).size
440 if (videoFilePath.endsWith('.mkv')) {
441 mimetype = 'video/x-matroska'
442 } else if (videoFilePath.endsWith('.webm')) {
443 mimetype = 'video/webm'
447 // Do not check status automatically, we'll check it manually
448 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
449 const initStatus = initializeSessionRes.status
451 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
452 const locationHeader = initializeSessionRes.header['location']
453 expect(locationHeader).to.not.be.undefined
455 const pathUploadId = locationHeader.split('?')[1]
457 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
459 if (result.statusCode === HttpStatusCode.OK_200) {
460 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
463 return result.body?.video || result.body as any
466 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
467 ? HttpStatusCode.CREATED_201
470 expect(initStatus).to.equal(expectedInitStatus)
472 return initializeSessionRes.body.video || initializeSessionRes.body
475 async prepareResumableUpload (options: OverrideCommandOptions & {
476 attributes: VideoEdit
480 originalName?: string
481 lastModified?: number
483 const { attributes, originalName, lastModified, size, mimetype } = options
485 const path = '/api/v1/videos/upload-resumable'
487 return this.postUploadRequest({
492 'X-Upload-Content-Type': mimetype,
493 'X-Upload-Content-Length': size.toString()
496 filename: attributes.fixture,
500 ...this.buildUploadFields(options.attributes)
503 // Fixture will be sent later
504 attaches: this.buildUploadAttaches(omit(options.attributes, [ 'fixture' ])),
507 defaultExpectedStatus: null
511 sendResumableChunks (options: OverrideCommandOptions & {
513 videoFilePath: string
515 contentLength?: number
516 contentRangeBuilder?: (start: number, chunk: any) => string
517 digestBuilder?: (chunk: any) => string
526 expectedStatus = HttpStatusCode.OK_200
529 const path = '/api/v1/videos/upload-resumable'
532 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
533 const url = this.server.url
535 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
536 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
537 readable.on('data', async function onData (chunk) {
541 'Authorization': 'Bearer ' + token,
542 'Content-Type': 'application/octet-stream',
543 'Content-Range': contentRangeBuilder
544 ? contentRangeBuilder(start, chunk)
545 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
546 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
550 Object.assign(headers, { digest: digestBuilder(chunk) })
553 const res = await got<{ video: VideoCreateResult }>({
557 path: path + '?' + pathUploadId,
559 responseType: 'json',
560 throwHttpErrors: false
563 start += chunk.length
565 if (res.statusCode === expectedStatus) {
569 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
570 readable.off('data', onData)
571 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
579 endResumableUpload (options: OverrideCommandOptions & {
582 return this.deleteRequest({
585 path: '/api/v1/videos/upload-resumable',
586 rawQuery: options.pathUploadId,
588 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
592 quickUpload (options: OverrideCommandOptions & {
595 privacy?: VideoPrivacy
598 const attributes: VideoEdit = { name: options.name }
599 if (options.nsfw) attributes.nsfw = options.nsfw
600 if (options.privacy) attributes.privacy = options.privacy
601 if (options.fixture) attributes.fixture = options.fixture
603 return this.upload({ ...options, attributes })
606 async randomUpload (options: OverrideCommandOptions & {
607 wait?: boolean // default true
608 additionalParams?: VideoEdit & { prefixName?: string }
610 const { wait = true, additionalParams } = options
611 const prefixName = additionalParams?.prefixName || ''
612 const name = prefixName + buildUUID()
614 const attributes = { name, ...additionalParams }
616 const result = await this.upload({ ...options, attributes })
618 if (wait) await waitJobs([ this.server ])
620 return { ...result, name }
623 // ---------------------------------------------------------------------------
625 removeHLSPlaylist (options: OverrideCommandOptions & {
626 videoId: number | string
628 const path = '/api/v1/videos/' + options.videoId + '/hls'
630 return this.deleteRequest({
635 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
639 removeHLSFile (options: OverrideCommandOptions & {
640 videoId: number | string
643 const path = '/api/v1/videos/' + options.videoId + '/hls/' + options.fileId
645 return this.deleteRequest({
650 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
654 removeAllWebTorrentFiles (options: OverrideCommandOptions & {
655 videoId: number | string
657 const path = '/api/v1/videos/' + options.videoId + '/webtorrent'
659 return this.deleteRequest({
664 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
668 removeWebTorrentFile (options: OverrideCommandOptions & {
669 videoId: number | string
672 const path = '/api/v1/videos/' + options.videoId + '/webtorrent/' + options.fileId
674 return this.deleteRequest({
679 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
683 runTranscoding (options: OverrideCommandOptions & {
684 videoId: number | string
685 transcodingType: 'hls' | 'webtorrent'
687 const path = '/api/v1/videos/' + options.videoId + '/transcoding'
689 const fields: VideoTranscodingCreate = pick(options, [ 'transcodingType' ])
691 return this.postBodyRequest({
697 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
701 // ---------------------------------------------------------------------------
703 private buildListQuery (options: VideosCommonQuery) {
704 return pick(options, [
722 private buildUploadFields (attributes: VideoEdit) {
723 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
726 private buildUploadAttaches (attributes: VideoEdit) {
727 const attaches: { [ name: string ]: string } = {}
729 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
730 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
733 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)