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, pick } from 'lodash'
7 import validator from 'validator'
8 import { buildUUID } from '@server/helpers/uuid'
9 import { loadLanguages } from '@server/initializers/constants'
21 VideosWithSearchCommonQuery
22 } from '@shared/models'
23 import { buildAbsoluteFixturePath, wait } from '../miscs'
24 import { unwrapBody } from '../requests'
25 import { PeerTubeServer, 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 {
36 constructor (server: PeerTubeServer) {
42 getCategories (options: OverrideCommandOptions = {}) {
43 const path = '/api/v1/videos/categories'
45 return this.getRequestBody<{ [id: number]: string }>({
50 defaultExpectedStatus: HttpStatusCode.OK_200
54 getLicences (options: OverrideCommandOptions = {}) {
55 const path = '/api/v1/videos/licences'
57 return this.getRequestBody<{ [id: number]: string }>({
62 defaultExpectedStatus: HttpStatusCode.OK_200
66 getLanguages (options: OverrideCommandOptions = {}) {
67 const path = '/api/v1/videos/languages'
69 return this.getRequestBody<{ [id: string]: string }>({
74 defaultExpectedStatus: HttpStatusCode.OK_200
78 getPrivacies (options: OverrideCommandOptions = {}) {
79 const path = '/api/v1/videos/privacies'
81 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
86 defaultExpectedStatus: HttpStatusCode.OK_200
90 // ---------------------------------------------------------------------------
92 getDescription (options: OverrideCommandOptions & {
93 descriptionPath: string
95 return this.getRequestBody<{ description: string }>({
97 path: options.descriptionPath,
100 defaultExpectedStatus: HttpStatusCode.OK_200
104 getFileMetadata (options: OverrideCommandOptions & {
107 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
111 implicitToken: false,
112 defaultExpectedStatus: HttpStatusCode.OK_200
116 // ---------------------------------------------------------------------------
118 view (options: OverrideCommandOptions & {
120 xForwardedFor?: string
122 const { id, xForwardedFor } = options
123 const path = '/api/v1/videos/' + id + '/views'
125 return this.postBodyRequest({
130 implicitToken: false,
131 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
135 rate (options: OverrideCommandOptions & {
137 rating: UserVideoRateType
139 const { id, rating } = options
140 const path = '/api/v1/videos/' + id + '/rate'
142 return this.putBodyRequest({
148 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
152 // ---------------------------------------------------------------------------
154 get (options: OverrideCommandOptions & {
157 const path = '/api/v1/videos/' + options.id
159 return this.getRequestBody<VideoDetails>({
163 implicitToken: false,
164 defaultExpectedStatus: HttpStatusCode.OK_200
168 getWithToken (options: OverrideCommandOptions & {
174 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
178 async getId (options: OverrideCommandOptions & {
179 uuid: number | string
181 const { uuid } = options
183 if (validator.isUUID('' + uuid) === false) return uuid as number
185 const { id } = await this.get({ ...options, id: uuid })
190 // ---------------------------------------------------------------------------
192 listMyVideos (options: OverrideCommandOptions & {
199 const path = '/api/v1/users/me/videos'
201 return this.getRequestBody<ResultList<Video>>({
205 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive' ]),
207 defaultExpectedStatus: HttpStatusCode.OK_200
211 // ---------------------------------------------------------------------------
213 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
214 const path = '/api/v1/videos'
216 const query = this.buildListQuery(options)
218 return this.getRequestBody<ResultList<Video>>({
222 query: { sort: 'name', ...query },
223 implicitToken: false,
224 defaultExpectedStatus: HttpStatusCode.OK_200
228 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
232 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
236 listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
239 const { handle, search } = options
240 const path = '/api/v1/accounts/' + handle + '/videos'
242 return this.getRequestBody<ResultList<Video>>({
246 query: { search, ...this.buildListQuery(options) },
248 defaultExpectedStatus: HttpStatusCode.OK_200
252 listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
255 const { handle } = options
256 const path = '/api/v1/video-channels/' + handle + '/videos'
258 return this.getRequestBody<ResultList<Video>>({
262 query: this.buildListQuery(options),
264 defaultExpectedStatus: HttpStatusCode.OK_200
268 // ---------------------------------------------------------------------------
270 async find (options: OverrideCommandOptions & {
273 const { data } = await this.list(options)
275 return data.find(v => v.name === options.name)
278 // ---------------------------------------------------------------------------
280 update (options: OverrideCommandOptions & {
282 attributes?: VideoEdit
284 const { id, attributes = {} } = options
285 const path = '/api/v1/videos/' + id
288 if (attributes.thumbnailfile || attributes.previewfile) {
289 const attaches: any = {}
290 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
291 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
293 return this.putUploadRequest({
297 fields: options.attributes,
299 thumbnailfile: attributes.thumbnailfile,
300 previewfile: attributes.previewfile
303 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
307 return this.putBodyRequest({
311 fields: options.attributes,
313 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
317 remove (options: OverrideCommandOptions & {
320 const path = '/api/v1/videos/' + options.id
322 return unwrapBody(this.deleteRequest({
327 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
332 const { data } = await this.list()
334 for (const v of data) {
335 await this.remove({ id: v.id })
339 // ---------------------------------------------------------------------------
341 async upload (options: OverrideCommandOptions & {
342 attributes?: VideoEdit
343 mode?: 'legacy' | 'resumable' // default legacy
345 const { mode = 'legacy' } = options
346 let defaultChannelId = 1
349 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
350 defaultChannelId = videoChannels[0].id
351 } catch (e) { /* empty */ }
353 // Override default attributes
355 name: 'my super video',
359 channelId: defaultChannelId,
361 waitTranscoding: false,
362 description: 'my super description',
363 support: 'my super support text',
365 privacy: VideoPrivacy.PUBLIC,
366 commentsEnabled: true,
367 downloadEnabled: true,
368 fixture: 'video_short.webm',
370 ...options.attributes
373 const created = mode === 'legacy'
374 ? await this.buildLegacyUpload({ ...options, attributes })
375 : await this.buildResumeUpload({ ...options, attributes })
377 // Wait torrent generation
378 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
379 if (expectedStatus === HttpStatusCode.OK_200) {
380 let video: VideoDetails
383 video = await this.getWithToken({ ...options, id: created.uuid })
386 } while (!video.files[0].torrentUrl)
392 async buildLegacyUpload (options: OverrideCommandOptions & {
393 attributes: VideoEdit
394 }): Promise<VideoCreateResult> {
395 const path = '/api/v1/videos/upload'
397 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
401 fields: this.buildUploadFields(options.attributes),
402 attaches: this.buildUploadAttaches(options.attributes),
404 defaultExpectedStatus: HttpStatusCode.OK_200
405 })).then(body => body.video || body as any)
408 async buildResumeUpload (options: OverrideCommandOptions & {
409 attributes: VideoEdit
410 }): Promise<VideoCreateResult> {
411 const { attributes, expectedStatus } = options
414 let videoFilePath: string
415 let mimetype = 'video/mp4'
417 if (attributes.fixture) {
418 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
419 size = (await stat(videoFilePath)).size
421 if (videoFilePath.endsWith('.mkv')) {
422 mimetype = 'video/x-matroska'
423 } else if (videoFilePath.endsWith('.webm')) {
424 mimetype = 'video/webm'
428 // Do not check status automatically, we'll check it manually
429 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
430 const initStatus = initializeSessionRes.status
432 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
433 const locationHeader = initializeSessionRes.header['location']
434 expect(locationHeader).to.not.be.undefined
436 const pathUploadId = locationHeader.split('?')[1]
438 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
440 return result.body?.video || result.body as any
443 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
444 ? HttpStatusCode.CREATED_201
447 expect(initStatus).to.equal(expectedInitStatus)
449 return initializeSessionRes.body.video || initializeSessionRes.body
452 async prepareResumableUpload (options: OverrideCommandOptions & {
453 attributes: VideoEdit
457 const { attributes, size, mimetype } = options
459 const path = '/api/v1/videos/upload-resumable'
461 return this.postUploadRequest({
466 'X-Upload-Content-Type': mimetype,
467 'X-Upload-Content-Length': size.toString()
469 fields: { filename: attributes.fixture, ...this.buildUploadFields(options.attributes) },
470 // Fixture will be sent later
471 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
474 defaultExpectedStatus: null
478 sendResumableChunks (options: OverrideCommandOptions & {
480 videoFilePath: string
482 contentLength?: number
483 contentRangeBuilder?: (start: number, chunk: any) => string
485 const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options
487 const path = '/api/v1/videos/upload-resumable'
490 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
491 const url = this.server.url
493 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
494 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
495 readable.on('data', async function onData (chunk) {
499 'Authorization': 'Bearer ' + token,
500 'Content-Type': 'application/octet-stream',
501 'Content-Range': contentRangeBuilder
502 ? contentRangeBuilder(start, chunk)
503 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
504 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
507 const res = await got<{ video: VideoCreateResult }>({
511 path: path + '?' + pathUploadId,
513 responseType: 'json',
514 throwHttpErrors: false
517 start += chunk.length
519 if (res.statusCode === expectedStatus) {
523 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
524 readable.off('data', onData)
525 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
533 quickUpload (options: OverrideCommandOptions & {
536 privacy?: VideoPrivacy
539 const attributes: VideoEdit = { name: options.name }
540 if (options.nsfw) attributes.nsfw = options.nsfw
541 if (options.privacy) attributes.privacy = options.privacy
542 if (options.fixture) attributes.fixture = options.fixture
544 return this.upload({ ...options, attributes })
547 async randomUpload (options: OverrideCommandOptions & {
548 wait?: boolean // default true
549 additionalParams?: VideoEdit & { prefixName?: string }
551 const { wait = true, additionalParams } = options
552 const prefixName = additionalParams?.prefixName || ''
553 const name = prefixName + buildUUID()
555 const attributes = { name, ...additionalParams }
557 const result = await this.upload({ ...options, attributes })
559 if (wait) await waitJobs([ this.server ])
561 return { ...result, name }
564 // ---------------------------------------------------------------------------
566 private buildListQuery (options: VideosCommonQuery) {
567 return pick(options, [
583 private buildUploadFields (attributes: VideoEdit) {
584 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
587 private buildUploadAttaches (attributes: VideoEdit) {
588 const attaches: { [ name: string ]: string } = {}
590 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
591 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
594 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)