]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/videos/videos-command.ts
Add channel filters for my videos/followers
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / videos / videos-command.ts
CommitLineData
d23dd9fb
C
1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3import { expect } from 'chai'
4import { createReadStream, stat } from 'fs-extra'
5import got, { Response as GotResponse } from 'got'
b033851f 6import { omit } from 'lodash'
d23dd9fb
C
7import validator from 'validator'
8import { buildUUID } from '@server/helpers/uuid'
9import { loadLanguages } from '@server/initializers/constants'
b033851f 10import { pick } from '@shared/core-utils'
d23dd9fb 11import {
4c7e60bc 12 HttpStatusCode,
d23dd9fb
C
13 ResultList,
14 UserVideoRateType,
15 Video,
16 VideoCreate,
17 VideoCreateResult,
18 VideoDetails,
19 VideoFileMetadata,
20 VideoPrivacy,
21 VideosCommonQuery,
22 VideosWithSearchCommonQuery
23} from '@shared/models'
24import { buildAbsoluteFixturePath, wait } from '../miscs'
25import { unwrapBody } from '../requests'
254d3579 26import { PeerTubeServer, waitJobs } from '../server'
d23dd9fb
C
27import { AbstractCommand, OverrideCommandOptions } from '../shared'
28
29export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & {
30 fixture?: string
31 thumbnailfile?: string
32 previewfile?: string
33}
34
35export class VideosCommand extends AbstractCommand {
36
254d3579 37 constructor (server: PeerTubeServer) {
d23dd9fb
C
38 super(server)
39
40 loadLanguages()
41 }
42
43 getCategories (options: OverrideCommandOptions = {}) {
44 const path = '/api/v1/videos/categories'
45
46 return this.getRequestBody<{ [id: number]: string }>({
47 ...options,
48 path,
49
50 implicitToken: false,
51 defaultExpectedStatus: HttpStatusCode.OK_200
52 })
53 }
54
55 getLicences (options: OverrideCommandOptions = {}) {
56 const path = '/api/v1/videos/licences'
57
58 return this.getRequestBody<{ [id: number]: string }>({
59 ...options,
60 path,
61
62 implicitToken: false,
63 defaultExpectedStatus: HttpStatusCode.OK_200
64 })
65 }
66
67 getLanguages (options: OverrideCommandOptions = {}) {
68 const path = '/api/v1/videos/languages'
69
70 return this.getRequestBody<{ [id: string]: string }>({
71 ...options,
72 path,
73
74 implicitToken: false,
75 defaultExpectedStatus: HttpStatusCode.OK_200
76 })
77 }
78
79 getPrivacies (options: OverrideCommandOptions = {}) {
80 const path = '/api/v1/videos/privacies'
81
82 return this.getRequestBody<{ [id in VideoPrivacy]: string }>({
83 ...options,
84 path,
85
86 implicitToken: false,
87 defaultExpectedStatus: HttpStatusCode.OK_200
88 })
89 }
90
91 // ---------------------------------------------------------------------------
92
93 getDescription (options: OverrideCommandOptions & {
94 descriptionPath: string
95 }) {
96 return this.getRequestBody<{ description: string }>({
97 ...options,
98 path: options.descriptionPath,
99
100 implicitToken: false,
101 defaultExpectedStatus: HttpStatusCode.OK_200
102 })
103 }
104
105 getFileMetadata (options: OverrideCommandOptions & {
106 url: string
107 }) {
108 return unwrapBody<VideoFileMetadata>(this.getRawRequest({
109 ...options,
110
111 url: options.url,
112 implicitToken: false,
113 defaultExpectedStatus: HttpStatusCode.OK_200
114 }))
115 }
116
117 // ---------------------------------------------------------------------------
118
119 view (options: OverrideCommandOptions & {
120 id: number | string
121 xForwardedFor?: string
122 }) {
123 const { id, xForwardedFor } = options
124 const path = '/api/v1/videos/' + id + '/views'
125
126 return this.postBodyRequest({
127 ...options,
128
129 path,
130 xForwardedFor,
131 implicitToken: false,
132 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
133 })
134 }
135
136 rate (options: OverrideCommandOptions & {
137 id: number | string
138 rating: UserVideoRateType
139 }) {
140 const { id, rating } = options
141 const path = '/api/v1/videos/' + id + '/rate'
142
143 return this.putBodyRequest({
144 ...options,
145
146 path,
147 fields: { rating },
148 implicitToken: true,
149 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
150 })
151 }
152
153 // ---------------------------------------------------------------------------
154
155 get (options: OverrideCommandOptions & {
156 id: number | string
157 }) {
158 const path = '/api/v1/videos/' + options.id
159
160 return this.getRequestBody<VideoDetails>({
161 ...options,
162
163 path,
164 implicitToken: false,
165 defaultExpectedStatus: HttpStatusCode.OK_200
166 })
167 }
168
169 getWithToken (options: OverrideCommandOptions & {
170 id: number | string
171 }) {
172 return this.get({
173 ...options,
174
175 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
176 })
177 }
178
179 async getId (options: OverrideCommandOptions & {
180 uuid: number | string
181 }) {
182 const { uuid } = options
183
184 if (validator.isUUID('' + uuid) === false) return uuid as number
185
186 const { id } = await this.get({ ...options, id: uuid })
187
188 return id
189 }
190
0305db28
JB
191 async listFiles (options: OverrideCommandOptions & {
192 id: number | string
193 }) {
194 const video = await this.get(options)
195
196 const files = video.files || []
197 const hlsFiles = video.streamingPlaylists[0]?.files || []
198
199 return files.concat(hlsFiles)
200 }
201
d23dd9fb
C
202 // ---------------------------------------------------------------------------
203
204 listMyVideos (options: OverrideCommandOptions & {
205 start?: number
206 count?: number
207 sort?: string
208 search?: string
209 isLive?: boolean
978c87e7 210 channelId?: number
d23dd9fb
C
211 } = {}) {
212 const path = '/api/v1/users/me/videos'
213
214 return this.getRequestBody<ResultList<Video>>({
215 ...options,
216
217 path,
978c87e7 218 query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive', 'channelId' ]),
d23dd9fb
C
219 implicitToken: true,
220 defaultExpectedStatus: HttpStatusCode.OK_200
221 })
222 }
223
224 // ---------------------------------------------------------------------------
225
226 list (options: OverrideCommandOptions & VideosCommonQuery = {}) {
227 const path = '/api/v1/videos'
228
229 const query = this.buildListQuery(options)
230
231 return this.getRequestBody<ResultList<Video>>({
232 ...options,
233
234 path,
235 query: { sort: 'name', ...query },
236 implicitToken: false,
237 defaultExpectedStatus: HttpStatusCode.OK_200
238 })
239 }
240
241 listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) {
242 return this.list({
243 ...options,
244
245 token: this.buildCommonRequestToken({ ...options, implicitToken: true })
246 })
247 }
248
249 listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
c0e8b12e 250 handle: string
d23dd9fb 251 }) {
c0e8b12e
C
252 const { handle, search } = options
253 const path = '/api/v1/accounts/' + handle + '/videos'
d23dd9fb
C
254
255 return this.getRequestBody<ResultList<Video>>({
256 ...options,
257
258 path,
259 query: { search, ...this.buildListQuery(options) },
260 implicitToken: true,
261 defaultExpectedStatus: HttpStatusCode.OK_200
262 })
263 }
264
265 listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & {
c0e8b12e 266 handle: string
d23dd9fb 267 }) {
c0e8b12e
C
268 const { handle } = options
269 const path = '/api/v1/video-channels/' + handle + '/videos'
d23dd9fb
C
270
271 return this.getRequestBody<ResultList<Video>>({
272 ...options,
273
274 path,
275 query: this.buildListQuery(options),
276 implicitToken: true,
277 defaultExpectedStatus: HttpStatusCode.OK_200
278 })
279 }
280
281 // ---------------------------------------------------------------------------
282
4d029ef8
C
283 async find (options: OverrideCommandOptions & {
284 name: string
285 }) {
286 const { data } = await this.list(options)
287
288 return data.find(v => v.name === options.name)
289 }
290
291 // ---------------------------------------------------------------------------
292
d23dd9fb
C
293 update (options: OverrideCommandOptions & {
294 id: number | string
295 attributes?: VideoEdit
296 }) {
297 const { id, attributes = {} } = options
298 const path = '/api/v1/videos/' + id
299
300 // Upload request
301 if (attributes.thumbnailfile || attributes.previewfile) {
302 const attaches: any = {}
303 if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile
304 if (attributes.previewfile) attaches.previewfile = attributes.previewfile
305
306 return this.putUploadRequest({
307 ...options,
308
309 path,
310 fields: options.attributes,
311 attaches: {
312 thumbnailfile: attributes.thumbnailfile,
313 previewfile: attributes.previewfile
314 },
315 implicitToken: true,
316 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
317 })
318 }
319
320 return this.putBodyRequest({
321 ...options,
322
323 path,
324 fields: options.attributes,
325 implicitToken: true,
326 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
327 })
328 }
329
330 remove (options: OverrideCommandOptions & {
331 id: number | string
332 }) {
333 const path = '/api/v1/videos/' + options.id
334
c0e8b12e 335 return unwrapBody(this.deleteRequest({
d23dd9fb
C
336 ...options,
337
338 path,
339 implicitToken: true,
340 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
c0e8b12e 341 }))
d23dd9fb
C
342 }
343
344 async removeAll () {
345 const { data } = await this.list()
346
347 for (const v of data) {
348 await this.remove({ id: v.id })
349 }
350 }
351
352 // ---------------------------------------------------------------------------
353
354 async upload (options: OverrideCommandOptions & {
355 attributes?: VideoEdit
356 mode?: 'legacy' | 'resumable' // default legacy
357 } = {}) {
4c7e60bc 358 const { mode = 'legacy' } = options
d23dd9fb
C
359 let defaultChannelId = 1
360
361 try {
89d241a7 362 const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
d23dd9fb
C
363 defaultChannelId = videoChannels[0].id
364 } catch (e) { /* empty */ }
365
366 // Override default attributes
367 const attributes = {
368 name: 'my super video',
369 category: 5,
370 licence: 4,
371 language: 'zh',
372 channelId: defaultChannelId,
373 nsfw: true,
374 waitTranscoding: false,
375 description: 'my super description',
376 support: 'my super support text',
377 tags: [ 'tag' ],
378 privacy: VideoPrivacy.PUBLIC,
379 commentsEnabled: true,
380 downloadEnabled: true,
381 fixture: 'video_short.webm',
382
383 ...options.attributes
384 }
385
4c7e60bc 386 const created = mode === 'legacy'
d23dd9fb
C
387 ? await this.buildLegacyUpload({ ...options, attributes })
388 : await this.buildResumeUpload({ ...options, attributes })
389
390 // Wait torrent generation
4c7e60bc 391 const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 })
d23dd9fb
C
392 if (expectedStatus === HttpStatusCode.OK_200) {
393 let video: VideoDetails
394
395 do {
4c7e60bc 396 video = await this.getWithToken({ ...options, id: created.uuid })
d23dd9fb
C
397
398 await wait(50)
399 } while (!video.files[0].torrentUrl)
400 }
401
4c7e60bc 402 return created
d23dd9fb
C
403 }
404
405 async buildLegacyUpload (options: OverrideCommandOptions & {
406 attributes: VideoEdit
407 }): Promise<VideoCreateResult> {
408 const path = '/api/v1/videos/upload'
409
410 return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({
411 ...options,
412
413 path,
414 fields: this.buildUploadFields(options.attributes),
415 attaches: this.buildUploadAttaches(options.attributes),
416 implicitToken: true,
417 defaultExpectedStatus: HttpStatusCode.OK_200
418 })).then(body => body.video || body as any)
419 }
420
421 async buildResumeUpload (options: OverrideCommandOptions & {
422 attributes: VideoEdit
c0e8b12e 423 }): Promise<VideoCreateResult> {
d23dd9fb
C
424 const { attributes, expectedStatus } = options
425
426 let size = 0
427 let videoFilePath: string
428 let mimetype = 'video/mp4'
429
430 if (attributes.fixture) {
431 videoFilePath = buildAbsoluteFixturePath(attributes.fixture)
432 size = (await stat(videoFilePath)).size
433
434 if (videoFilePath.endsWith('.mkv')) {
435 mimetype = 'video/x-matroska'
436 } else if (videoFilePath.endsWith('.webm')) {
437 mimetype = 'video/webm'
438 }
439 }
440
c0e8b12e
C
441 // Do not check status automatically, we'll check it manually
442 const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype })
d23dd9fb
C
443 const initStatus = initializeSessionRes.status
444
445 if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) {
446 const locationHeader = initializeSessionRes.header['location']
447 expect(locationHeader).to.not.be.undefined
448
449 const pathUploadId = locationHeader.split('?')[1]
450
451 const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size })
452
8de589b9
C
453 if (result.statusCode === HttpStatusCode.OK_200) {
454 await this.endResumableUpload({ ...options, expectedStatus: HttpStatusCode.NO_CONTENT_204, pathUploadId })
455 }
790c2837 456
c0e8b12e 457 return result.body?.video || result.body as any
d23dd9fb
C
458 }
459
460 const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200
461 ? HttpStatusCode.CREATED_201
462 : expectedStatus
463
464 expect(initStatus).to.equal(expectedInitStatus)
465
c0e8b12e 466 return initializeSessionRes.body.video || initializeSessionRes.body
d23dd9fb
C
467 }
468
469 async prepareResumableUpload (options: OverrideCommandOptions & {
470 attributes: VideoEdit
471 size: number
472 mimetype: string
473 }) {
474 const { attributes, size, mimetype } = options
475
476 const path = '/api/v1/videos/upload-resumable'
477
478 return this.postUploadRequest({
479 ...options,
480
481 path,
482 headers: {
483 'X-Upload-Content-Type': mimetype,
484 'X-Upload-Content-Length': size.toString()
485 },
486 fields: { filename: attributes.fixture, ...this.buildUploadFields(options.attributes) },
c0e8b12e
C
487 // Fixture will be sent later
488 attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')),
d23dd9fb 489 implicitToken: true,
c0e8b12e 490
d23dd9fb
C
491 defaultExpectedStatus: null
492 })
493 }
494
495 sendResumableChunks (options: OverrideCommandOptions & {
496 pathUploadId: string
497 videoFilePath: string
498 size: number
499 contentLength?: number
500 contentRangeBuilder?: (start: number, chunk: any) => string
501 }) {
502 const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options
503
504 const path = '/api/v1/videos/upload-resumable'
505 let start = 0
506
507 const token = this.buildCommonRequestToken({ ...options, implicitToken: true })
508 const url = this.server.url
509
510 const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 })
511 return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => {
512 readable.on('data', async function onData (chunk) {
513 readable.pause()
514
515 const headers = {
516 'Authorization': 'Bearer ' + token,
517 'Content-Type': 'application/octet-stream',
518 'Content-Range': contentRangeBuilder
519 ? contentRangeBuilder(start, chunk)
520 : `bytes ${start}-${start + chunk.length - 1}/${size}`,
521 'Content-Length': contentLength ? contentLength + '' : chunk.length + ''
522 }
523
524 const res = await got<{ video: VideoCreateResult }>({
525 url,
526 method: 'put',
527 headers,
528 path: path + '?' + pathUploadId,
529 body: chunk,
530 responseType: 'json',
531 throwHttpErrors: false
532 })
533
534 start += chunk.length
535
536 if (res.statusCode === expectedStatus) {
537 return resolve(res)
538 }
539
540 if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) {
541 readable.off('data', onData)
542 return reject(new Error('Incorrect transient behaviour sending intermediary chunks'))
543 }
544
545 readable.resume()
546 })
547 })
548 }
549
790c2837
C
550 endResumableUpload (options: OverrideCommandOptions & {
551 pathUploadId: string
552 }) {
553 return this.deleteRequest({
554 ...options,
555
556 path: '/api/v1/videos/upload-resumable',
557 rawQuery: options.pathUploadId,
558 implicitToken: true,
559 defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
560 })
561 }
562
d23dd9fb
C
563 quickUpload (options: OverrideCommandOptions & {
564 name: string
565 nsfw?: boolean
566 privacy?: VideoPrivacy
567 fixture?: string
568 }) {
569 const attributes: VideoEdit = { name: options.name }
570 if (options.nsfw) attributes.nsfw = options.nsfw
571 if (options.privacy) attributes.privacy = options.privacy
572 if (options.fixture) attributes.fixture = options.fixture
573
574 return this.upload({ ...options, attributes })
575 }
576
577 async randomUpload (options: OverrideCommandOptions & {
578 wait?: boolean // default true
4c7e60bc 579 additionalParams?: VideoEdit & { prefixName?: string }
d23dd9fb
C
580 } = {}) {
581 const { wait = true, additionalParams } = options
582 const prefixName = additionalParams?.prefixName || ''
583 const name = prefixName + buildUUID()
584
4c7e60bc 585 const attributes = { name, ...additionalParams }
d23dd9fb 586
d23dd9fb
C
587 const result = await this.upload({ ...options, attributes })
588
c0e8b12e
C
589 if (wait) await waitJobs([ this.server ])
590
d23dd9fb
C
591 return { ...result, name }
592 }
593
594 // ---------------------------------------------------------------------------
595
596 private buildListQuery (options: VideosCommonQuery) {
597 return pick(options, [
598 'start',
599 'count',
600 'sort',
601 'nsfw',
602 'isLive',
603 'categoryOneOf',
604 'licenceOneOf',
605 'languageOneOf',
606 'tagsOneOf',
607 'tagsAllOf',
608 'filter',
609 'skipCount'
610 ])
611 }
612
613 private buildUploadFields (attributes: VideoEdit) {
c0e8b12e 614 return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ])
d23dd9fb
C
615 }
616
617 private buildUploadAttaches (attributes: VideoEdit) {
618 const attaches: { [ name: string ]: string } = {}
619
620 for (const key of [ 'thumbnailfile', 'previewfile' ]) {
621 if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key])
622 }
623
624 if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture)
625
626 return attaches
627 }
628}