]>
Commit | Line | Data |
---|---|---|
d23dd9fb C |
1 | /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ |
2 | ||
3 | import { expect } from 'chai' | |
4 | import { createReadStream, stat } from 'fs-extra' | |
5 | import got, { Response as GotResponse } from 'got' | |
b033851f | 6 | import { omit } from 'lodash' |
d23dd9fb C |
7 | import validator from 'validator' |
8 | import { buildUUID } from '@server/helpers/uuid' | |
9 | import { loadLanguages } from '@server/initializers/constants' | |
b033851f | 10 | import { pick } from '@shared/core-utils' |
d23dd9fb | 11 | import { |
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' | |
24 | import { buildAbsoluteFixturePath, wait } from '../miscs' | |
25 | import { unwrapBody } from '../requests' | |
254d3579 | 26 | import { PeerTubeServer, waitJobs } from '../server' |
d23dd9fb C |
27 | import { AbstractCommand, OverrideCommandOptions } from '../shared' |
28 | ||
29 | export type VideoEdit = Partial<Omit<VideoCreate, 'thumbnailfile' | 'previewfile'>> & { | |
30 | fixture?: string | |
31 | thumbnailfile?: string | |
32 | previewfile?: string | |
33 | } | |
34 | ||
35 | export 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 | |
210 | } = {}) { | |
211 | const path = '/api/v1/users/me/videos' | |
212 | ||
213 | return this.getRequestBody<ResultList<Video>>({ | |
214 | ...options, | |
215 | ||
216 | path, | |
217 | query: pick(options, [ 'start', 'count', 'sort', 'search', 'isLive' ]), | |
218 | implicitToken: true, | |
219 | defaultExpectedStatus: HttpStatusCode.OK_200 | |
220 | }) | |
221 | } | |
222 | ||
223 | // --------------------------------------------------------------------------- | |
224 | ||
225 | list (options: OverrideCommandOptions & VideosCommonQuery = {}) { | |
226 | const path = '/api/v1/videos' | |
227 | ||
228 | const query = this.buildListQuery(options) | |
229 | ||
230 | return this.getRequestBody<ResultList<Video>>({ | |
231 | ...options, | |
232 | ||
233 | path, | |
234 | query: { sort: 'name', ...query }, | |
235 | implicitToken: false, | |
236 | defaultExpectedStatus: HttpStatusCode.OK_200 | |
237 | }) | |
238 | } | |
239 | ||
240 | listWithToken (options: OverrideCommandOptions & VideosCommonQuery = {}) { | |
241 | return this.list({ | |
242 | ...options, | |
243 | ||
244 | token: this.buildCommonRequestToken({ ...options, implicitToken: true }) | |
245 | }) | |
246 | } | |
247 | ||
248 | listByAccount (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { | |
c0e8b12e | 249 | handle: string |
d23dd9fb | 250 | }) { |
c0e8b12e C |
251 | const { handle, search } = options |
252 | const path = '/api/v1/accounts/' + handle + '/videos' | |
d23dd9fb C |
253 | |
254 | return this.getRequestBody<ResultList<Video>>({ | |
255 | ...options, | |
256 | ||
257 | path, | |
258 | query: { search, ...this.buildListQuery(options) }, | |
259 | implicitToken: true, | |
260 | defaultExpectedStatus: HttpStatusCode.OK_200 | |
261 | }) | |
262 | } | |
263 | ||
264 | listByChannel (options: OverrideCommandOptions & VideosWithSearchCommonQuery & { | |
c0e8b12e | 265 | handle: string |
d23dd9fb | 266 | }) { |
c0e8b12e C |
267 | const { handle } = options |
268 | const path = '/api/v1/video-channels/' + handle + '/videos' | |
d23dd9fb C |
269 | |
270 | return this.getRequestBody<ResultList<Video>>({ | |
271 | ...options, | |
272 | ||
273 | path, | |
274 | query: this.buildListQuery(options), | |
275 | implicitToken: true, | |
276 | defaultExpectedStatus: HttpStatusCode.OK_200 | |
277 | }) | |
278 | } | |
279 | ||
280 | // --------------------------------------------------------------------------- | |
281 | ||
4d029ef8 C |
282 | async find (options: OverrideCommandOptions & { |
283 | name: string | |
284 | }) { | |
285 | const { data } = await this.list(options) | |
286 | ||
287 | return data.find(v => v.name === options.name) | |
288 | } | |
289 | ||
290 | // --------------------------------------------------------------------------- | |
291 | ||
d23dd9fb C |
292 | update (options: OverrideCommandOptions & { |
293 | id: number | string | |
294 | attributes?: VideoEdit | |
295 | }) { | |
296 | const { id, attributes = {} } = options | |
297 | const path = '/api/v1/videos/' + id | |
298 | ||
299 | // Upload request | |
300 | if (attributes.thumbnailfile || attributes.previewfile) { | |
301 | const attaches: any = {} | |
302 | if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile | |
303 | if (attributes.previewfile) attaches.previewfile = attributes.previewfile | |
304 | ||
305 | return this.putUploadRequest({ | |
306 | ...options, | |
307 | ||
308 | path, | |
309 | fields: options.attributes, | |
310 | attaches: { | |
311 | thumbnailfile: attributes.thumbnailfile, | |
312 | previewfile: attributes.previewfile | |
313 | }, | |
314 | implicitToken: true, | |
315 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | |
316 | }) | |
317 | } | |
318 | ||
319 | return this.putBodyRequest({ | |
320 | ...options, | |
321 | ||
322 | path, | |
323 | fields: options.attributes, | |
324 | implicitToken: true, | |
325 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | |
326 | }) | |
327 | } | |
328 | ||
329 | remove (options: OverrideCommandOptions & { | |
330 | id: number | string | |
331 | }) { | |
332 | const path = '/api/v1/videos/' + options.id | |
333 | ||
c0e8b12e | 334 | return unwrapBody(this.deleteRequest({ |
d23dd9fb C |
335 | ...options, |
336 | ||
337 | path, | |
338 | implicitToken: true, | |
339 | defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204 | |
c0e8b12e | 340 | })) |
d23dd9fb C |
341 | } |
342 | ||
343 | async removeAll () { | |
344 | const { data } = await this.list() | |
345 | ||
346 | for (const v of data) { | |
347 | await this.remove({ id: v.id }) | |
348 | } | |
349 | } | |
350 | ||
351 | // --------------------------------------------------------------------------- | |
352 | ||
353 | async upload (options: OverrideCommandOptions & { | |
354 | attributes?: VideoEdit | |
355 | mode?: 'legacy' | 'resumable' // default legacy | |
356 | } = {}) { | |
4c7e60bc | 357 | const { mode = 'legacy' } = options |
d23dd9fb C |
358 | let defaultChannelId = 1 |
359 | ||
360 | try { | |
89d241a7 | 361 | const { videoChannels } = await this.server.users.getMyInfo({ token: options.token }) |
d23dd9fb C |
362 | defaultChannelId = videoChannels[0].id |
363 | } catch (e) { /* empty */ } | |
364 | ||
365 | // Override default attributes | |
366 | const attributes = { | |
367 | name: 'my super video', | |
368 | category: 5, | |
369 | licence: 4, | |
370 | language: 'zh', | |
371 | channelId: defaultChannelId, | |
372 | nsfw: true, | |
373 | waitTranscoding: false, | |
374 | description: 'my super description', | |
375 | support: 'my super support text', | |
376 | tags: [ 'tag' ], | |
377 | privacy: VideoPrivacy.PUBLIC, | |
378 | commentsEnabled: true, | |
379 | downloadEnabled: true, | |
380 | fixture: 'video_short.webm', | |
381 | ||
382 | ...options.attributes | |
383 | } | |
384 | ||
4c7e60bc | 385 | const created = mode === 'legacy' |
d23dd9fb C |
386 | ? await this.buildLegacyUpload({ ...options, attributes }) |
387 | : await this.buildResumeUpload({ ...options, attributes }) | |
388 | ||
389 | // Wait torrent generation | |
4c7e60bc | 390 | const expectedStatus = this.buildExpectedStatus({ ...options, defaultExpectedStatus: HttpStatusCode.OK_200 }) |
d23dd9fb C |
391 | if (expectedStatus === HttpStatusCode.OK_200) { |
392 | let video: VideoDetails | |
393 | ||
394 | do { | |
4c7e60bc | 395 | video = await this.getWithToken({ ...options, id: created.uuid }) |
d23dd9fb C |
396 | |
397 | await wait(50) | |
398 | } while (!video.files[0].torrentUrl) | |
399 | } | |
400 | ||
4c7e60bc | 401 | return created |
d23dd9fb C |
402 | } |
403 | ||
404 | async buildLegacyUpload (options: OverrideCommandOptions & { | |
405 | attributes: VideoEdit | |
406 | }): Promise<VideoCreateResult> { | |
407 | const path = '/api/v1/videos/upload' | |
408 | ||
409 | return unwrapBody<{ video: VideoCreateResult }>(this.postUploadRequest({ | |
410 | ...options, | |
411 | ||
412 | path, | |
413 | fields: this.buildUploadFields(options.attributes), | |
414 | attaches: this.buildUploadAttaches(options.attributes), | |
415 | implicitToken: true, | |
416 | defaultExpectedStatus: HttpStatusCode.OK_200 | |
417 | })).then(body => body.video || body as any) | |
418 | } | |
419 | ||
420 | async buildResumeUpload (options: OverrideCommandOptions & { | |
421 | attributes: VideoEdit | |
c0e8b12e | 422 | }): Promise<VideoCreateResult> { |
d23dd9fb C |
423 | const { attributes, expectedStatus } = options |
424 | ||
425 | let size = 0 | |
426 | let videoFilePath: string | |
427 | let mimetype = 'video/mp4' | |
428 | ||
429 | if (attributes.fixture) { | |
430 | videoFilePath = buildAbsoluteFixturePath(attributes.fixture) | |
431 | size = (await stat(videoFilePath)).size | |
432 | ||
433 | if (videoFilePath.endsWith('.mkv')) { | |
434 | mimetype = 'video/x-matroska' | |
435 | } else if (videoFilePath.endsWith('.webm')) { | |
436 | mimetype = 'video/webm' | |
437 | } | |
438 | } | |
439 | ||
c0e8b12e C |
440 | // Do not check status automatically, we'll check it manually |
441 | const initializeSessionRes = await this.prepareResumableUpload({ ...options, expectedStatus: null, attributes, size, mimetype }) | |
d23dd9fb C |
442 | const initStatus = initializeSessionRes.status |
443 | ||
444 | if (videoFilePath && initStatus === HttpStatusCode.CREATED_201) { | |
445 | const locationHeader = initializeSessionRes.header['location'] | |
446 | expect(locationHeader).to.not.be.undefined | |
447 | ||
448 | const pathUploadId = locationHeader.split('?')[1] | |
449 | ||
450 | const result = await this.sendResumableChunks({ ...options, pathUploadId, videoFilePath, size }) | |
451 | ||
c0e8b12e | 452 | return result.body?.video || result.body as any |
d23dd9fb C |
453 | } |
454 | ||
455 | const expectedInitStatus = expectedStatus === HttpStatusCode.OK_200 | |
456 | ? HttpStatusCode.CREATED_201 | |
457 | : expectedStatus | |
458 | ||
459 | expect(initStatus).to.equal(expectedInitStatus) | |
460 | ||
c0e8b12e | 461 | return initializeSessionRes.body.video || initializeSessionRes.body |
d23dd9fb C |
462 | } |
463 | ||
464 | async prepareResumableUpload (options: OverrideCommandOptions & { | |
465 | attributes: VideoEdit | |
466 | size: number | |
467 | mimetype: string | |
468 | }) { | |
469 | const { attributes, size, mimetype } = options | |
470 | ||
471 | const path = '/api/v1/videos/upload-resumable' | |
472 | ||
473 | return this.postUploadRequest({ | |
474 | ...options, | |
475 | ||
476 | path, | |
477 | headers: { | |
478 | 'X-Upload-Content-Type': mimetype, | |
479 | 'X-Upload-Content-Length': size.toString() | |
480 | }, | |
481 | fields: { filename: attributes.fixture, ...this.buildUploadFields(options.attributes) }, | |
c0e8b12e C |
482 | // Fixture will be sent later |
483 | attaches: this.buildUploadAttaches(omit(options.attributes, 'fixture')), | |
d23dd9fb | 484 | implicitToken: true, |
c0e8b12e | 485 | |
d23dd9fb C |
486 | defaultExpectedStatus: null |
487 | }) | |
488 | } | |
489 | ||
490 | sendResumableChunks (options: OverrideCommandOptions & { | |
491 | pathUploadId: string | |
492 | videoFilePath: string | |
493 | size: number | |
494 | contentLength?: number | |
495 | contentRangeBuilder?: (start: number, chunk: any) => string | |
496 | }) { | |
497 | const { pathUploadId, videoFilePath, size, contentLength, contentRangeBuilder, expectedStatus = HttpStatusCode.OK_200 } = options | |
498 | ||
499 | const path = '/api/v1/videos/upload-resumable' | |
500 | let start = 0 | |
501 | ||
502 | const token = this.buildCommonRequestToken({ ...options, implicitToken: true }) | |
503 | const url = this.server.url | |
504 | ||
505 | const readable = createReadStream(videoFilePath, { highWaterMark: 8 * 1024 }) | |
506 | return new Promise<GotResponse<{ video: VideoCreateResult }>>((resolve, reject) => { | |
507 | readable.on('data', async function onData (chunk) { | |
508 | readable.pause() | |
509 | ||
510 | const headers = { | |
511 | 'Authorization': 'Bearer ' + token, | |
512 | 'Content-Type': 'application/octet-stream', | |
513 | 'Content-Range': contentRangeBuilder | |
514 | ? contentRangeBuilder(start, chunk) | |
515 | : `bytes ${start}-${start + chunk.length - 1}/${size}`, | |
516 | 'Content-Length': contentLength ? contentLength + '' : chunk.length + '' | |
517 | } | |
518 | ||
519 | const res = await got<{ video: VideoCreateResult }>({ | |
520 | url, | |
521 | method: 'put', | |
522 | headers, | |
523 | path: path + '?' + pathUploadId, | |
524 | body: chunk, | |
525 | responseType: 'json', | |
526 | throwHttpErrors: false | |
527 | }) | |
528 | ||
529 | start += chunk.length | |
530 | ||
531 | if (res.statusCode === expectedStatus) { | |
532 | return resolve(res) | |
533 | } | |
534 | ||
535 | if (res.statusCode !== HttpStatusCode.PERMANENT_REDIRECT_308) { | |
536 | readable.off('data', onData) | |
537 | return reject(new Error('Incorrect transient behaviour sending intermediary chunks')) | |
538 | } | |
539 | ||
540 | readable.resume() | |
541 | }) | |
542 | }) | |
543 | } | |
544 | ||
545 | quickUpload (options: OverrideCommandOptions & { | |
546 | name: string | |
547 | nsfw?: boolean | |
548 | privacy?: VideoPrivacy | |
549 | fixture?: string | |
550 | }) { | |
551 | const attributes: VideoEdit = { name: options.name } | |
552 | if (options.nsfw) attributes.nsfw = options.nsfw | |
553 | if (options.privacy) attributes.privacy = options.privacy | |
554 | if (options.fixture) attributes.fixture = options.fixture | |
555 | ||
556 | return this.upload({ ...options, attributes }) | |
557 | } | |
558 | ||
559 | async randomUpload (options: OverrideCommandOptions & { | |
560 | wait?: boolean // default true | |
4c7e60bc | 561 | additionalParams?: VideoEdit & { prefixName?: string } |
d23dd9fb C |
562 | } = {}) { |
563 | const { wait = true, additionalParams } = options | |
564 | const prefixName = additionalParams?.prefixName || '' | |
565 | const name = prefixName + buildUUID() | |
566 | ||
4c7e60bc | 567 | const attributes = { name, ...additionalParams } |
d23dd9fb | 568 | |
d23dd9fb C |
569 | const result = await this.upload({ ...options, attributes }) |
570 | ||
c0e8b12e C |
571 | if (wait) await waitJobs([ this.server ]) |
572 | ||
d23dd9fb C |
573 | return { ...result, name } |
574 | } | |
575 | ||
576 | // --------------------------------------------------------------------------- | |
577 | ||
578 | private buildListQuery (options: VideosCommonQuery) { | |
579 | return pick(options, [ | |
580 | 'start', | |
581 | 'count', | |
582 | 'sort', | |
583 | 'nsfw', | |
584 | 'isLive', | |
585 | 'categoryOneOf', | |
586 | 'licenceOneOf', | |
587 | 'languageOneOf', | |
588 | 'tagsOneOf', | |
589 | 'tagsAllOf', | |
590 | 'filter', | |
591 | 'skipCount' | |
592 | ]) | |
593 | } | |
594 | ||
595 | private buildUploadFields (attributes: VideoEdit) { | |
c0e8b12e | 596 | return omit(attributes, [ 'fixture', 'thumbnailfile', 'previewfile' ]) |
d23dd9fb C |
597 | } |
598 | ||
599 | private buildUploadAttaches (attributes: VideoEdit) { | |
600 | const attaches: { [ name: string ]: string } = {} | |
601 | ||
602 | for (const key of [ 'thumbnailfile', 'previewfile' ]) { | |
603 | if (attributes[key]) attaches[key] = buildAbsoluteFixturePath(attributes[key]) | |
604 | } | |
605 | ||
606 | if (attributes.fixture) attaches.videofile = buildAbsoluteFixturePath(attributes.fixture) | |
607 | ||
608 | return attaches | |
609 | } | |
610 | } |