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 '@server/helpers/uuid'
9 import { loadLanguages } from '@server/initializers/constants'
10 import { pick } from '@shared/core-utils'
22 VideosWithSearchCommonQuery
23 } from '@shared/models'
24 import { buildAbsoluteFixturePath, wait } from '../miscs'
25 import { unwrapBody } from '../requests'
26 import { PeerTubeServer, waitJobs } from '../server'
27 import { AbstractCommand, OverrideCommandOptions } from '../shared'
29 export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
31 thumbnailfile?: string
35 export class VideosCommand extends AbstractCommand {
37 constructor (server: PeerTubeServer) {
43 getCategories (options: OverrideCommandOptions = {}) {
44 const path = '/api/v1/videos/categories'
46 return this.getRequestBody<{ [id: number]: string }>({
51 defaultExpectedStatus: HttpStatusCode.OK_200
55 getLicences (options: OverrideCommandOptions = {}) {
56 const path = '/api/v1/videos/licences'
58 return this.getRequestBody<{ [id: number]: string }>({
63 defaultExpectedStatus: HttpStatusCode.OK_200
67 getLanguages (options: OverrideCommandOptions = {}) {
68 const path = '/api/v1/videos/languages'
70 return this.getRequestBody<{ [id: string]: string }>({
75 defaultExpectedStatus: HttpStatusCode.OK_200
79 getPrivacies (options: OverrideCommandOptions = {}) {
80 const path = '/api/v1/videos/privacies'
82 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
87 defaultExpectedStatus: HttpStatusCode.OK_200
91 // ---------------------------------------------------------------------------
93 getDescription (options: OverrideCommandOptions & {
94 descriptionPath: string
96 return this.getRequestBody<{ description: string }>({
98 path: options.descriptionPath,
100 implicitToken: false,
101 defaultExpectedStatus: HttpStatusCode.OK_200
105 getFileMetadata (options: OverrideCommandOptions & {
108 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
112 implicitToken: false,
113 defaultExpectedStatus: HttpStatusCode.OK_200
117 // ---------------------------------------------------------------------------
119 view (options: OverrideCommandOptions & {
121 xForwardedFor?: string
123 const { id, xForwardedFor } = options
124 const path = '/api/v1/videos/' + id + '/views'
126 return this.postBodyRequest({
131 implicitToken: false,
132 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
136 rate (options: OverrideCommandOptions & {
138 rating: UserVideoRateType
140 const { id, rating } = options
141 const path = '/api/v1/videos/' + id + '/rate'
143 return this.putBodyRequest({
149 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
153 // ---------------------------------------------------------------------------
155 get (options: OverrideCommandOptions & {
158 const path = '/api/v1/videos/' + options.id
160 return this.getRequestBody<VideoDetails>({
164 implicitToken: false,
165 defaultExpectedStatus: HttpStatusCode.OK_200
169 getWithToken (options: OverrideCommandOptions & {
175 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
179 async getId (options: OverrideCommandOptions & {
180 uuid: number | string
182 const { uuid } = options
184 if (validator.isUUID('' + uuid) === false) return uuid as number
186 const { id } = await this.get({ ...options, id: uuid })
191 // ---------------------------------------------------------------------------
193 listMyVideos (options: OverrideCommandOptions & {
200 const path = '/api/v1/users/me/videos'
202 return this.getRequestBody<ResultList<Video>>({
206 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive' ]),
208 defaultExpectedStatus: HttpStatusCode.OK_200
212 // ---------------------------------------------------------------------------
214 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
215 const path = '/api/v1/videos'
217 const query = this.buildListQuery(options)
219 return this.getRequestBody<ResultList<Video>>({
223 query: { sort: 'name', ...query },
224 implicitToken: false,
225 defaultExpectedStatus: HttpStatusCode.OK_200
229 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
233 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
237 listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
240 const { handle, search } = options
241 const path = '/api/v1/accounts/' + handle + '/videos'
243 return this.getRequestBody<ResultList<Video>>({
247 query: { search, ...this.buildListQuery(options) },
249 defaultExpectedStatus: HttpStatusCode.OK_200
253 listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
256 const { handle } = options
257 const path = '/api/v1/video-channels/' + handle + '/videos'
259 return this.getRequestBody<ResultList<Video>>({
263 query: this.buildListQuery(options),
265 defaultExpectedStatus: HttpStatusCode.OK_200
269 // ---------------------------------------------------------------------------
271 async find (options: OverrideCommandOptions & {
274 const { data } = await this.list(options)
276 return data.find(v => v.name === options.name)
279 // ---------------------------------------------------------------------------
281 update (options: OverrideCommandOptions & {
283 attributes?: VideoEdit
285 const { id, attributes = {} } = options
286 const path = '/api/v1/videos/' + id
289 if (attributes.thumbnailfile || attributes.previewfile) {
290 const attaches: any = {}
291 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
292 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
294 return this.putUploadRequest({
298 fields: options.attributes,
300 thumbnailfile: attributes.thumbnailfile,
301 previewfile: attributes.previewfile
304 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
308 return this.putBodyRequest({
312 fields: options.attributes,
314 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
318 remove (options: OverrideCommandOptions & {
321 const path = '/api/v1/videos/' + options.id
323 return unwrapBody(this.deleteRequest({
328 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
333 const { data } = await this.list()
335 for (const v of data) {
336 await this.remove({ id: v.id })
340 // ---------------------------------------------------------------------------
342 async upload (options: OverrideCommandOptions & {
343 attributes?: VideoEdit
344 mode?: 'legacy' | 'resumable' // default legacy
346 const { mode = 'legacy' } = options
347 let defaultChannelId = 1
350 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
351 defaultChannelId = videoChannels[0].id
352 } catch (e) { /* empty */ }
354 // Override default attributes
356 name: 'my super video',
360 channelId: defaultChannelId,
362 waitTranscoding: false,
363 description: 'my super description',
364 support: 'my super support text',
366 privacy: VideoPrivacy.PUBLIC,
367 commentsEnabled: true,
368 downloadEnabled: true,
369 fixture: 'video_short.webm',
371 ...options.attributes
374 const created = mode === 'legacy'
375 ? await this.buildLegacyUpload({ ...options, attributes })
376 : await this.buildResumeUpload({ ...options, attributes })
378 // Wait torrent generation
379 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
380 if (expectedStatus === HttpStatusCode.OK_200) {
381 let video: VideoDetails
384 video = await this.getWithToken({ ...options, id: created.uuid })
387 } while (!video.files[0].torrentUrl)
393 async buildLegacyUpload (options: OverrideCommandOptions & {
394 attributes: VideoEdit
395 }): Promise<VideoCreateResult> {
396 const path = '/api/v1/videos/upload'
398 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
402 fields: this.buildUploadFields(options.attributes),
403 attaches: this.buildUploadAttaches(options.attributes),
405 defaultExpectedStatus: HttpStatusCode.OK_200
406 })).then(body => body.video || body as any)
409 async buildResumeUpload (options: OverrideCommandOptions & {
410 attributes: VideoEdit
411 }): Promise<VideoCreateResult> {
412 const { attributes, expectedStatus } = options
415 let videoFilePath: string
416 let mimetype = 'video/mp4'
418 if (attributes.fixture) {
419 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
420 size = (await stat(videoFilePath)).size
422 if (videoFilePath.endsWith('.mkv')) {
423 mimetype = 'video/x-matroska'
424 } else if (videoFilePath.endsWith('.webm')) {
425 mimetype = 'video/webm'
429 // Do not check status automatically, we'll check it manually
430 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
431 const initStatus = initializeSessionRes.status
433 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
434 const locationHeader = initializeSessionRes.header['location']
435 expect(locationHeader).to.not.be.undefined
437 const pathUploadId = locationHeader.split('?')[1]
439 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
441 return result.body?.video || result.body as any
444 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
445 ? HttpStatusCode.CREATED_201
448 expect(initStatus).to.equal(expectedInitStatus)
450 return initializeSessionRes.body.video || initializeSessionRes.body
453 async prepareResumableUpload (options: OverrideCommandOptions & {
454 attributes: VideoEdit
458 const { attributes, size, mimetype } = options
460 const path = '/api/v1/videos/upload-resumable'
462 return this.postUploadRequest({
467 'X-Upload-Content-Type': mimetype,
468 'X-Upload-Content-Length': size.toString()
470 fields: { filename: attributes.fixture, ...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 quickUpload (options: OverrideCommandOptions & {
537 privacy?: VideoPrivacy
540 const attributes: VideoEdit = { name: options.name }
541 if (options.nsfw) attributes.nsfw = options.nsfw
542 if (options.privacy) attributes.privacy = options.privacy
543 if (options.fixture) attributes.fixture = options.fixture
545 return this.upload({ ...options, attributes })
548 async randomUpload (options: OverrideCommandOptions & {
549 wait?: boolean // default true
550 additionalParams?: VideoEdit & { prefixName?: string }
552 const { wait = true, additionalParams } = options
553 const prefixName = additionalParams?.prefixName || ''
554 const name = prefixName + buildUUID()
556 const attributes = { name, ...additionalParams }
558 const result = await this.upload({ ...options, attributes })
560 if (wait) await waitJobs([ this.server ])
562 return { ...result, name }
565 // ---------------------------------------------------------------------------
567 private buildListQuery (options: VideosCommonQuery) {
568 return pick(options, [
584 private buildUploadFields (attributes: VideoEdit) {
585 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
588 private buildUploadAttaches (attributes: VideoEdit) {
589 const attaches: { [ name: string ]: string } = {}
591 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
592 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
595 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)