]>
Commit | Line | Data |
---|---|---|
1 | import * as Bluebird from 'bluebird' | |
2 | import { map, maxBy } from 'lodash' | |
3 | import * as magnetUtil from 'magnet-uri' | |
4 | import * as parseTorrent from 'parse-torrent' | |
5 | import { extname, join } from 'path' | |
6 | import * as Sequelize from 'sequelize' | |
7 | import { | |
8 | AllowNull, | |
9 | BeforeDestroy, | |
10 | BelongsTo, | |
11 | BelongsToMany, | |
12 | Column, | |
13 | CreatedAt, | |
14 | DataType, | |
15 | Default, | |
16 | ForeignKey, | |
17 | HasMany, | |
18 | HasOne, | |
19 | IFindOptions, | |
20 | Is, | |
21 | IsInt, | |
22 | IsUUID, | |
23 | Min, | |
24 | Model, | |
25 | Scopes, | |
26 | Table, | |
27 | UpdatedAt | |
28 | } from 'sequelize-typescript' | |
29 | import { VideoPrivacy, VideoResolution, VideoState } from '../../../shared' | |
30 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' | |
31 | import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos' | |
32 | import { VideoFilter } from '../../../shared/models/videos/video-query.type' | |
33 | import { | |
34 | copyFilePromise, | |
35 | createTorrentPromise, | |
36 | peertubeTruncate, | |
37 | renamePromise, | |
38 | statPromise, | |
39 | unlinkPromise, | |
40 | writeFilePromise | |
41 | } from '../../helpers/core-utils' | |
42 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' | |
43 | import { isBooleanValid } from '../../helpers/custom-validators/misc' | |
44 | import { | |
45 | isVideoCategoryValid, | |
46 | isVideoDescriptionValid, | |
47 | isVideoDurationValid, | |
48 | isVideoLanguageValid, | |
49 | isVideoLicenceValid, | |
50 | isVideoNameValid, | |
51 | isVideoPrivacyValid, | |
52 | isVideoStateValid, | |
53 | isVideoSupportValid | |
54 | } from '../../helpers/custom-validators/videos' | |
55 | import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils' | |
56 | import { logger } from '../../helpers/logger' | |
57 | import { getServerActor } from '../../helpers/utils' | |
58 | import { | |
59 | API_VERSION, | |
60 | CONFIG, | |
61 | CONSTRAINTS_FIELDS, | |
62 | PREVIEWS_SIZE, | |
63 | REMOTE_SCHEME, | |
64 | STATIC_DOWNLOAD_PATHS, | |
65 | STATIC_PATHS, | |
66 | THUMBNAILS_SIZE, | |
67 | VIDEO_CATEGORIES, | |
68 | VIDEO_EXT_MIMETYPE, | |
69 | VIDEO_LANGUAGES, | |
70 | VIDEO_LICENCES, | |
71 | VIDEO_PRIVACIES, | |
72 | VIDEO_STATES | |
73 | } from '../../initializers' | |
74 | import { | |
75 | getVideoCommentsActivityPubUrl, | |
76 | getVideoDislikesActivityPubUrl, | |
77 | getVideoLikesActivityPubUrl, | |
78 | getVideoSharesActivityPubUrl | |
79 | } from '../../lib/activitypub' | |
80 | import { sendDeleteVideo } from '../../lib/activitypub/send' | |
81 | import { AccountModel } from '../account/account' | |
82 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
83 | import { ActorModel } from '../activitypub/actor' | |
84 | import { AvatarModel } from '../avatar/avatar' | |
85 | import { ServerModel } from '../server/server' | |
86 | import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils' | |
87 | import { TagModel } from './tag' | |
88 | import { VideoAbuseModel } from './video-abuse' | |
89 | import { VideoChannelModel } from './video-channel' | |
90 | import { VideoCommentModel } from './video-comment' | |
91 | import { VideoFileModel } from './video-file' | |
92 | import { VideoShareModel } from './video-share' | |
93 | import { VideoTagModel } from './video-tag' | |
94 | import { ScheduleVideoUpdateModel } from './schedule-video-update' | |
95 | import { VideoCaptionModel } from './video-caption' | |
96 | ||
97 | // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation | |
98 | const indexes: Sequelize.DefineIndexesOptions[] = [ | |
99 | buildTrigramSearchIndex('video_name_trigram', 'name'), | |
100 | ||
101 | { fields: [ 'createdAt' ] }, | |
102 | { fields: [ 'publishedAt' ] }, | |
103 | { fields: [ 'duration' ] }, | |
104 | { fields: [ 'category' ] }, | |
105 | { fields: [ 'licence' ] }, | |
106 | { fields: [ 'nsfw' ] }, | |
107 | { fields: [ 'language' ] }, | |
108 | { fields: [ 'waitTranscoding' ] }, | |
109 | { fields: [ 'state' ] }, | |
110 | { fields: [ 'remote' ] }, | |
111 | { fields: [ 'views' ] }, | |
112 | { fields: [ 'likes' ] }, | |
113 | { fields: [ 'channelId' ] }, | |
114 | { | |
115 | fields: [ 'uuid' ], | |
116 | unique: true | |
117 | }, | |
118 | { | |
119 | fields: [ 'url'], | |
120 | unique: true | |
121 | } | |
122 | ] | |
123 | ||
124 | export enum ScopeNames { | |
125 | AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST', | |
126 | WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS', | |
127 | WITH_TAGS = 'WITH_TAGS', | |
128 | WITH_FILES = 'WITH_FILES', | |
129 | WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE' | |
130 | } | |
131 | ||
132 | type AvailableForListOptions = { | |
133 | actorId: number, | |
134 | filter?: VideoFilter, | |
135 | categoryOneOf?: number[], | |
136 | nsfw?: boolean, | |
137 | licenceOneOf?: number[], | |
138 | languageOneOf?: string[], | |
139 | tagsOneOf?: string[], | |
140 | tagsAllOf?: string[], | |
141 | withFiles?: boolean, | |
142 | accountId?: number, | |
143 | videoChannelId?: number | |
144 | } | |
145 | ||
146 | @Scopes({ | |
147 | [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => { | |
148 | const accountInclude = { | |
149 | attributes: [ 'id', 'name' ], | |
150 | model: AccountModel.unscoped(), | |
151 | required: true, | |
152 | where: {}, | |
153 | include: [ | |
154 | { | |
155 | attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ], | |
156 | model: ActorModel.unscoped(), | |
157 | required: true, | |
158 | where: VideoModel.buildActorWhereWithFilter(options.filter), | |
159 | include: [ | |
160 | { | |
161 | attributes: [ 'host' ], | |
162 | model: ServerModel.unscoped(), | |
163 | required: false | |
164 | }, | |
165 | { | |
166 | model: AvatarModel.unscoped(), | |
167 | required: false | |
168 | } | |
169 | ] | |
170 | } | |
171 | ] | |
172 | } | |
173 | ||
174 | const videoChannelInclude = { | |
175 | attributes: [ 'name', 'description', 'id' ], | |
176 | model: VideoChannelModel.unscoped(), | |
177 | required: true, | |
178 | where: {}, | |
179 | include: [ | |
180 | { | |
181 | attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ], | |
182 | model: ActorModel.unscoped(), | |
183 | required: true, | |
184 | include: [ | |
185 | { | |
186 | attributes: [ 'host' ], | |
187 | model: ServerModel.unscoped(), | |
188 | required: false | |
189 | }, | |
190 | { | |
191 | model: AvatarModel.unscoped(), | |
192 | required: false | |
193 | } | |
194 | ] | |
195 | }, | |
196 | accountInclude | |
197 | ] | |
198 | } | |
199 | ||
200 | // Force actorId to be a number to avoid SQL injections | |
201 | const actorIdNumber = parseInt(options.actorId.toString(), 10) | |
202 | ||
203 | // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it... | |
204 | const query: IFindOptions<VideoModel> = { | |
205 | where: { | |
206 | id: { | |
207 | [Sequelize.Op.notIn]: Sequelize.literal( | |
208 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
209 | ), | |
210 | [ Sequelize.Op.in ]: Sequelize.literal( | |
211 | '(' + | |
212 | 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' + | |
213 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
214 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
215 | ' UNION ' + | |
216 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
217 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
218 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
219 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
220 | 'WHERE "actor"."serverId" IS NULL ' + | |
221 | ' UNION ALL ' + | |
222 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
223 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
224 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
225 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
226 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' + | |
227 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
228 | ')' | |
229 | ) | |
230 | }, | |
231 | // Always list public videos | |
232 | privacy: VideoPrivacy.PUBLIC, | |
233 | // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding | |
234 | [ Sequelize.Op.or ]: [ | |
235 | { | |
236 | state: VideoState.PUBLISHED | |
237 | }, | |
238 | { | |
239 | [ Sequelize.Op.and ]: { | |
240 | state: VideoState.TO_TRANSCODE, | |
241 | waitTranscoding: false | |
242 | } | |
243 | } | |
244 | ] | |
245 | }, | |
246 | include: [ videoChannelInclude ] | |
247 | } | |
248 | ||
249 | if (options.withFiles === true) { | |
250 | query.include.push({ | |
251 | model: VideoFileModel.unscoped(), | |
252 | required: true | |
253 | }) | |
254 | } | |
255 | ||
256 | // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN() | |
257 | if (options.tagsAllOf || options.tagsOneOf) { | |
258 | const createTagsIn = (tags: string[]) => { | |
259 | return tags.map(t => VideoModel.sequelize.escape(t)) | |
260 | .join(', ') | |
261 | } | |
262 | ||
263 | if (options.tagsOneOf) { | |
264 | query.where['id'][Sequelize.Op.in] = Sequelize.literal( | |
265 | '(' + | |
266 | 'SELECT "videoId" FROM "videoTag" ' + | |
267 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
268 | 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' + | |
269 | ')' | |
270 | ) | |
271 | } | |
272 | ||
273 | if (options.tagsAllOf) { | |
274 | query.where['id'][Sequelize.Op.in] = Sequelize.literal( | |
275 | '(' + | |
276 | 'SELECT "videoId" FROM "videoTag" ' + | |
277 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
278 | 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' + | |
279 | 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length + | |
280 | ')' | |
281 | ) | |
282 | } | |
283 | } | |
284 | ||
285 | if (options.nsfw === true || options.nsfw === false) { | |
286 | query.where['nsfw'] = options.nsfw | |
287 | } | |
288 | ||
289 | if (options.categoryOneOf) { | |
290 | query.where['category'] = { | |
291 | [Sequelize.Op.or]: options.categoryOneOf | |
292 | } | |
293 | } | |
294 | ||
295 | if (options.licenceOneOf) { | |
296 | query.where['licence'] = { | |
297 | [Sequelize.Op.or]: options.licenceOneOf | |
298 | } | |
299 | } | |
300 | ||
301 | if (options.languageOneOf) { | |
302 | query.where['language'] = { | |
303 | [Sequelize.Op.or]: options.languageOneOf | |
304 | } | |
305 | } | |
306 | ||
307 | if (options.accountId) { | |
308 | accountInclude.where = { | |
309 | id: options.accountId | |
310 | } | |
311 | } | |
312 | ||
313 | if (options.videoChannelId) { | |
314 | videoChannelInclude.where = { | |
315 | id: options.videoChannelId | |
316 | } | |
317 | } | |
318 | ||
319 | return query | |
320 | }, | |
321 | [ScopeNames.WITH_ACCOUNT_DETAILS]: { | |
322 | include: [ | |
323 | { | |
324 | model: () => VideoChannelModel.unscoped(), | |
325 | required: true, | |
326 | include: [ | |
327 | { | |
328 | attributes: { | |
329 | exclude: [ 'privateKey', 'publicKey' ] | |
330 | }, | |
331 | model: () => ActorModel.unscoped(), | |
332 | required: true, | |
333 | include: [ | |
334 | { | |
335 | attributes: [ 'host' ], | |
336 | model: () => ServerModel.unscoped(), | |
337 | required: false | |
338 | }, | |
339 | { | |
340 | model: () => AvatarModel.unscoped(), | |
341 | required: false | |
342 | } | |
343 | ] | |
344 | }, | |
345 | { | |
346 | model: () => AccountModel.unscoped(), | |
347 | required: true, | |
348 | include: [ | |
349 | { | |
350 | model: () => ActorModel.unscoped(), | |
351 | attributes: { | |
352 | exclude: [ 'privateKey', 'publicKey' ] | |
353 | }, | |
354 | required: true, | |
355 | include: [ | |
356 | { | |
357 | attributes: [ 'host' ], | |
358 | model: () => ServerModel.unscoped(), | |
359 | required: false | |
360 | }, | |
361 | { | |
362 | model: () => AvatarModel.unscoped(), | |
363 | required: false | |
364 | } | |
365 | ] | |
366 | } | |
367 | ] | |
368 | } | |
369 | ] | |
370 | } | |
371 | ] | |
372 | }, | |
373 | [ScopeNames.WITH_TAGS]: { | |
374 | include: [ () => TagModel ] | |
375 | }, | |
376 | [ScopeNames.WITH_FILES]: { | |
377 | include: [ | |
378 | { | |
379 | model: () => VideoFileModel.unscoped(), | |
380 | required: true | |
381 | } | |
382 | ] | |
383 | }, | |
384 | [ScopeNames.WITH_SCHEDULED_UPDATE]: { | |
385 | include: [ | |
386 | { | |
387 | model: () => ScheduleVideoUpdateModel.unscoped(), | |
388 | required: false | |
389 | } | |
390 | ] | |
391 | } | |
392 | }) | |
393 | @Table({ | |
394 | tableName: 'video', | |
395 | indexes | |
396 | }) | |
397 | export class VideoModel extends Model<VideoModel> { | |
398 | ||
399 | @AllowNull(false) | |
400 | @Default(DataType.UUIDV4) | |
401 | @IsUUID(4) | |
402 | @Column(DataType.UUID) | |
403 | uuid: string | |
404 | ||
405 | @AllowNull(false) | |
406 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
407 | @Column | |
408 | name: string | |
409 | ||
410 | @AllowNull(true) | |
411 | @Default(null) | |
412 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category')) | |
413 | @Column | |
414 | category: number | |
415 | ||
416 | @AllowNull(true) | |
417 | @Default(null) | |
418 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence')) | |
419 | @Column | |
420 | licence: number | |
421 | ||
422 | @AllowNull(true) | |
423 | @Default(null) | |
424 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language')) | |
425 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max)) | |
426 | language: string | |
427 | ||
428 | @AllowNull(false) | |
429 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
430 | @Column | |
431 | privacy: number | |
432 | ||
433 | @AllowNull(false) | |
434 | @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean')) | |
435 | @Column | |
436 | nsfw: boolean | |
437 | ||
438 | @AllowNull(true) | |
439 | @Default(null) | |
440 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description')) | |
441 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) | |
442 | description: string | |
443 | ||
444 | @AllowNull(true) | |
445 | @Default(null) | |
446 | @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support')) | |
447 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max)) | |
448 | support: string | |
449 | ||
450 | @AllowNull(false) | |
451 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
452 | @Column | |
453 | duration: number | |
454 | ||
455 | @AllowNull(false) | |
456 | @Default(0) | |
457 | @IsInt | |
458 | @Min(0) | |
459 | @Column | |
460 | views: number | |
461 | ||
462 | @AllowNull(false) | |
463 | @Default(0) | |
464 | @IsInt | |
465 | @Min(0) | |
466 | @Column | |
467 | likes: number | |
468 | ||
469 | @AllowNull(false) | |
470 | @Default(0) | |
471 | @IsInt | |
472 | @Min(0) | |
473 | @Column | |
474 | dislikes: number | |
475 | ||
476 | @AllowNull(false) | |
477 | @Column | |
478 | remote: boolean | |
479 | ||
480 | @AllowNull(false) | |
481 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
482 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
483 | url: string | |
484 | ||
485 | @AllowNull(false) | |
486 | @Column | |
487 | commentsEnabled: boolean | |
488 | ||
489 | @AllowNull(false) | |
490 | @Column | |
491 | waitTranscoding: boolean | |
492 | ||
493 | @AllowNull(false) | |
494 | @Default(null) | |
495 | @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state')) | |
496 | @Column | |
497 | state: VideoState | |
498 | ||
499 | @CreatedAt | |
500 | createdAt: Date | |
501 | ||
502 | @UpdatedAt | |
503 | updatedAt: Date | |
504 | ||
505 | @AllowNull(false) | |
506 | @Default(Sequelize.NOW) | |
507 | @Column | |
508 | publishedAt: Date | |
509 | ||
510 | @ForeignKey(() => VideoChannelModel) | |
511 | @Column | |
512 | channelId: number | |
513 | ||
514 | @BelongsTo(() => VideoChannelModel, { | |
515 | foreignKey: { | |
516 | allowNull: true | |
517 | }, | |
518 | hooks: true | |
519 | }) | |
520 | VideoChannel: VideoChannelModel | |
521 | ||
522 | @BelongsToMany(() => TagModel, { | |
523 | foreignKey: 'videoId', | |
524 | through: () => VideoTagModel, | |
525 | onDelete: 'CASCADE' | |
526 | }) | |
527 | Tags: TagModel[] | |
528 | ||
529 | @HasMany(() => VideoAbuseModel, { | |
530 | foreignKey: { | |
531 | name: 'videoId', | |
532 | allowNull: false | |
533 | }, | |
534 | onDelete: 'cascade' | |
535 | }) | |
536 | VideoAbuses: VideoAbuseModel[] | |
537 | ||
538 | @HasMany(() => VideoFileModel, { | |
539 | foreignKey: { | |
540 | name: 'videoId', | |
541 | allowNull: false | |
542 | }, | |
543 | onDelete: 'cascade' | |
544 | }) | |
545 | VideoFiles: VideoFileModel[] | |
546 | ||
547 | @HasMany(() => VideoShareModel, { | |
548 | foreignKey: { | |
549 | name: 'videoId', | |
550 | allowNull: false | |
551 | }, | |
552 | onDelete: 'cascade' | |
553 | }) | |
554 | VideoShares: VideoShareModel[] | |
555 | ||
556 | @HasMany(() => AccountVideoRateModel, { | |
557 | foreignKey: { | |
558 | name: 'videoId', | |
559 | allowNull: false | |
560 | }, | |
561 | onDelete: 'cascade' | |
562 | }) | |
563 | AccountVideoRates: AccountVideoRateModel[] | |
564 | ||
565 | @HasMany(() => VideoCommentModel, { | |
566 | foreignKey: { | |
567 | name: 'videoId', | |
568 | allowNull: false | |
569 | }, | |
570 | onDelete: 'cascade', | |
571 | hooks: true | |
572 | }) | |
573 | VideoComments: VideoCommentModel[] | |
574 | ||
575 | @HasOne(() => ScheduleVideoUpdateModel, { | |
576 | foreignKey: { | |
577 | name: 'videoId', | |
578 | allowNull: false | |
579 | }, | |
580 | onDelete: 'cascade' | |
581 | }) | |
582 | ScheduleVideoUpdate: ScheduleVideoUpdateModel | |
583 | ||
584 | @HasMany(() => VideoCaptionModel, { | |
585 | foreignKey: { | |
586 | name: 'videoId', | |
587 | allowNull: false | |
588 | }, | |
589 | onDelete: 'cascade', | |
590 | hooks: true, | |
591 | ['separate' as any]: true | |
592 | }) | |
593 | VideoCaptions: VideoCaptionModel[] | |
594 | ||
595 | @BeforeDestroy | |
596 | static async sendDelete (instance: VideoModel, options) { | |
597 | if (instance.isOwned()) { | |
598 | if (!instance.VideoChannel) { | |
599 | instance.VideoChannel = await instance.$get('VideoChannel', { | |
600 | include: [ | |
601 | { | |
602 | model: AccountModel, | |
603 | include: [ ActorModel ] | |
604 | } | |
605 | ], | |
606 | transaction: options.transaction | |
607 | }) as VideoChannelModel | |
608 | } | |
609 | ||
610 | return sendDeleteVideo(instance, options.transaction) | |
611 | } | |
612 | ||
613 | return undefined | |
614 | } | |
615 | ||
616 | @BeforeDestroy | |
617 | static async removeFiles (instance: VideoModel) { | |
618 | const tasks: Promise<any>[] = [] | |
619 | ||
620 | logger.info('Removing files of video %s.', instance.url) | |
621 | ||
622 | tasks.push(instance.removeThumbnail()) | |
623 | ||
624 | if (instance.isOwned()) { | |
625 | if (!Array.isArray(instance.VideoFiles)) { | |
626 | instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[] | |
627 | } | |
628 | ||
629 | tasks.push(instance.removePreview()) | |
630 | ||
631 | // Remove physical files and torrents | |
632 | instance.VideoFiles.forEach(file => { | |
633 | tasks.push(instance.removeFile(file)) | |
634 | tasks.push(instance.removeTorrent(file)) | |
635 | }) | |
636 | } | |
637 | ||
638 | // Do not wait video deletion because we could be in a transaction | |
639 | Promise.all(tasks) | |
640 | .catch(err => { | |
641 | logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }) | |
642 | }) | |
643 | ||
644 | return undefined | |
645 | } | |
646 | ||
647 | static list () { | |
648 | return VideoModel.scope(ScopeNames.WITH_FILES).findAll() | |
649 | } | |
650 | ||
651 | static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) { | |
652 | function getRawQuery (select: string) { | |
653 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
654 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
655 | 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' + | |
656 | 'WHERE "Account"."actorId" = ' + actorId | |
657 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + | |
658 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
659 | 'WHERE "VideoShare"."actorId" = ' + actorId | |
660 | ||
661 | return `(${queryVideo}) UNION (${queryVideoShare})` | |
662 | } | |
663 | ||
664 | const rawQuery = getRawQuery('"Video"."id"') | |
665 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
666 | ||
667 | const query = { | |
668 | distinct: true, | |
669 | offset: start, | |
670 | limit: count, | |
671 | order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]), | |
672 | where: { | |
673 | id: { | |
674 | [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')') | |
675 | }, | |
676 | [Sequelize.Op.or]: [ | |
677 | { privacy: VideoPrivacy.PUBLIC }, | |
678 | { privacy: VideoPrivacy.UNLISTED } | |
679 | ] | |
680 | }, | |
681 | include: [ | |
682 | { | |
683 | attributes: [ 'language' ], | |
684 | model: VideoCaptionModel.unscoped(), | |
685 | required: false | |
686 | }, | |
687 | { | |
688 | attributes: [ 'id', 'url' ], | |
689 | model: VideoShareModel.unscoped(), | |
690 | required: false, | |
691 | // We only want videos shared by this actor | |
692 | where: { | |
693 | [Sequelize.Op.and]: [ | |
694 | { | |
695 | id: { | |
696 | [Sequelize.Op.not]: null | |
697 | } | |
698 | }, | |
699 | { | |
700 | actorId | |
701 | } | |
702 | ] | |
703 | }, | |
704 | include: [ | |
705 | { | |
706 | attributes: [ 'id', 'url' ], | |
707 | model: ActorModel.unscoped() | |
708 | } | |
709 | ] | |
710 | }, | |
711 | { | |
712 | model: VideoChannelModel.unscoped(), | |
713 | required: true, | |
714 | include: [ | |
715 | { | |
716 | attributes: [ 'name' ], | |
717 | model: AccountModel.unscoped(), | |
718 | required: true, | |
719 | include: [ | |
720 | { | |
721 | attributes: [ 'id', 'url', 'followersUrl' ], | |
722 | model: ActorModel.unscoped(), | |
723 | required: true | |
724 | } | |
725 | ] | |
726 | }, | |
727 | { | |
728 | attributes: [ 'id', 'url', 'followersUrl' ], | |
729 | model: ActorModel.unscoped(), | |
730 | required: true | |
731 | } | |
732 | ] | |
733 | }, | |
734 | VideoFileModel, | |
735 | TagModel | |
736 | ] | |
737 | } | |
738 | ||
739 | return Bluebird.all([ | |
740 | // FIXME: typing issue | |
741 | VideoModel.findAll(query as any), | |
742 | VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT }) | |
743 | ]).then(([ rows, totals ]) => { | |
744 | // totals: totalVideos + totalVideoShares | |
745 | let totalVideos = 0 | |
746 | let totalVideoShares = 0 | |
747 | if (totals[0]) totalVideos = parseInt(totals[0].total, 10) | |
748 | if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10) | |
749 | ||
750 | const total = totalVideos + totalVideoShares | |
751 | return { | |
752 | data: rows, | |
753 | total: total | |
754 | } | |
755 | }) | |
756 | } | |
757 | ||
758 | static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) { | |
759 | const query: IFindOptions<VideoModel> = { | |
760 | offset: start, | |
761 | limit: count, | |
762 | order: getSort(sort), | |
763 | include: [ | |
764 | { | |
765 | model: VideoChannelModel, | |
766 | required: true, | |
767 | include: [ | |
768 | { | |
769 | model: AccountModel, | |
770 | where: { | |
771 | id: accountId | |
772 | }, | |
773 | required: true | |
774 | } | |
775 | ] | |
776 | }, | |
777 | { | |
778 | model: ScheduleVideoUpdateModel, | |
779 | required: false | |
780 | } | |
781 | ] | |
782 | } | |
783 | ||
784 | if (withFiles === true) { | |
785 | query.include.push({ | |
786 | model: VideoFileModel.unscoped(), | |
787 | required: true | |
788 | }) | |
789 | } | |
790 | ||
791 | if (hideNSFW === true) { | |
792 | query.where = { | |
793 | nsfw: false | |
794 | } | |
795 | } | |
796 | ||
797 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { | |
798 | return { | |
799 | data: rows, | |
800 | total: count | |
801 | } | |
802 | }) | |
803 | } | |
804 | ||
805 | static async listForApi (options: { | |
806 | start: number, | |
807 | count: number, | |
808 | sort: string, | |
809 | nsfw: boolean, | |
810 | withFiles: boolean, | |
811 | categoryOneOf?: number[], | |
812 | licenceOneOf?: number[], | |
813 | languageOneOf?: string[], | |
814 | tagsOneOf?: string[], | |
815 | tagsAllOf?: string[], | |
816 | filter?: VideoFilter, | |
817 | accountId?: number, | |
818 | videoChannelId?: number | |
819 | }) { | |
820 | const query = { | |
821 | offset: options.start, | |
822 | limit: options.count, | |
823 | order: getSort(options.sort) | |
824 | } | |
825 | ||
826 | const serverActor = await getServerActor() | |
827 | const scopes = { | |
828 | method: [ | |
829 | ScopeNames.AVAILABLE_FOR_LIST, { | |
830 | actorId: serverActor.id, | |
831 | nsfw: options.nsfw, | |
832 | categoryOneOf: options.categoryOneOf, | |
833 | licenceOneOf: options.licenceOneOf, | |
834 | languageOneOf: options.languageOneOf, | |
835 | tagsOneOf: options.tagsOneOf, | |
836 | tagsAllOf: options.tagsAllOf, | |
837 | filter: options.filter, | |
838 | withFiles: options.withFiles, | |
839 | accountId: options.accountId, | |
840 | videoChannelId: options.videoChannelId | |
841 | } as AvailableForListOptions | |
842 | ] | |
843 | } | |
844 | ||
845 | return VideoModel.scope(scopes) | |
846 | .findAndCountAll(query) | |
847 | .then(({ rows, count }) => { | |
848 | return { | |
849 | data: rows, | |
850 | total: count | |
851 | } | |
852 | }) | |
853 | } | |
854 | ||
855 | static async searchAndPopulateAccountAndServer (options: { | |
856 | search?: string | |
857 | start?: number | |
858 | count?: number | |
859 | sort?: string | |
860 | startDate?: string // ISO 8601 | |
861 | endDate?: string // ISO 8601 | |
862 | nsfw?: boolean | |
863 | categoryOneOf?: number[] | |
864 | licenceOneOf?: number[] | |
865 | languageOneOf?: string[] | |
866 | tagsOneOf?: string[] | |
867 | tagsAllOf?: string[] | |
868 | durationMin?: number // seconds | |
869 | durationMax?: number // seconds | |
870 | }) { | |
871 | const whereAnd = [ ] | |
872 | ||
873 | if (options.startDate || options.endDate) { | |
874 | const publishedAtRange = { } | |
875 | ||
876 | if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate | |
877 | if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate | |
878 | ||
879 | whereAnd.push({ publishedAt: publishedAtRange }) | |
880 | } | |
881 | ||
882 | if (options.durationMin || options.durationMax) { | |
883 | const durationRange = { } | |
884 | ||
885 | if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin | |
886 | if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax | |
887 | ||
888 | whereAnd.push({ duration: durationRange }) | |
889 | } | |
890 | ||
891 | const attributesInclude = [] | |
892 | const escapedSearch = VideoModel.sequelize.escape(options.search) | |
893 | const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') | |
894 | if (options.search) { | |
895 | whereAnd.push( | |
896 | { | |
897 | id: { | |
898 | [ Sequelize.Op.in ]: Sequelize.literal( | |
899 | '(' + | |
900 | 'SELECT "video"."id" FROM "video" WHERE ' + | |
901 | 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' + | |
902 | 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' + | |
903 | 'UNION ALL ' + | |
904 | 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' + | |
905 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
906 | 'WHERE "tag"."name" = ' + escapedSearch + | |
907 | ')' | |
908 | ) | |
909 | } | |
910 | } | |
911 | ) | |
912 | ||
913 | attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search)) | |
914 | } | |
915 | ||
916 | // Cannot search on similarity if we don't have a search | |
917 | if (!options.search) { | |
918 | attributesInclude.push( | |
919 | Sequelize.literal('0 as similarity') | |
920 | ) | |
921 | } | |
922 | ||
923 | const query: IFindOptions<VideoModel> = { | |
924 | attributes: { | |
925 | include: attributesInclude | |
926 | }, | |
927 | offset: options.start, | |
928 | limit: options.count, | |
929 | order: getSort(options.sort), | |
930 | where: { | |
931 | [ Sequelize.Op.and ]: whereAnd | |
932 | } | |
933 | } | |
934 | ||
935 | const serverActor = await getServerActor() | |
936 | const scopes = { | |
937 | method: [ | |
938 | ScopeNames.AVAILABLE_FOR_LIST, { | |
939 | actorId: serverActor.id, | |
940 | nsfw: options.nsfw, | |
941 | categoryOneOf: options.categoryOneOf, | |
942 | licenceOneOf: options.licenceOneOf, | |
943 | languageOneOf: options.languageOneOf, | |
944 | tagsOneOf: options.tagsOneOf, | |
945 | tagsAllOf: options.tagsAllOf | |
946 | } as AvailableForListOptions | |
947 | ] | |
948 | } | |
949 | ||
950 | return VideoModel.scope(scopes) | |
951 | .findAndCountAll(query) | |
952 | .then(({ rows, count }) => { | |
953 | return { | |
954 | data: rows, | |
955 | total: count | |
956 | } | |
957 | }) | |
958 | } | |
959 | ||
960 | static load (id: number) { | |
961 | return VideoModel.findById(id) | |
962 | } | |
963 | ||
964 | static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) { | |
965 | const query: IFindOptions<VideoModel> = { | |
966 | where: { | |
967 | url | |
968 | } | |
969 | } | |
970 | ||
971 | if (t !== undefined) query.transaction = t | |
972 | ||
973 | return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query) | |
974 | } | |
975 | ||
976 | static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) { | |
977 | const query: IFindOptions<VideoModel> = { | |
978 | where: { | |
979 | [Sequelize.Op.or]: [ | |
980 | { uuid }, | |
981 | { url } | |
982 | ] | |
983 | } | |
984 | } | |
985 | ||
986 | if (t !== undefined) query.transaction = t | |
987 | ||
988 | return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query) | |
989 | } | |
990 | ||
991 | static loadAndPopulateAccountAndServerAndTags (id: number) { | |
992 | const options = { | |
993 | order: [ [ 'Tags', 'name', 'ASC' ] ] | |
994 | } | |
995 | ||
996 | return VideoModel | |
997 | .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ]) | |
998 | .findById(id, options) | |
999 | } | |
1000 | ||
1001 | static loadByUUID (uuid: string) { | |
1002 | const options = { | |
1003 | where: { | |
1004 | uuid | |
1005 | } | |
1006 | } | |
1007 | ||
1008 | return VideoModel | |
1009 | .scope([ ScopeNames.WITH_FILES ]) | |
1010 | .findOne(options) | |
1011 | } | |
1012 | ||
1013 | static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) { | |
1014 | const options = { | |
1015 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
1016 | where: { | |
1017 | uuid | |
1018 | }, | |
1019 | transaction: t | |
1020 | } | |
1021 | ||
1022 | return VideoModel | |
1023 | .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ]) | |
1024 | .findOne(options) | |
1025 | } | |
1026 | ||
1027 | static async getStats () { | |
1028 | const totalLocalVideos = await VideoModel.count({ | |
1029 | where: { | |
1030 | remote: false | |
1031 | } | |
1032 | }) | |
1033 | const totalVideos = await VideoModel.count() | |
1034 | ||
1035 | let totalLocalVideoViews = await VideoModel.sum('views', { | |
1036 | where: { | |
1037 | remote: false | |
1038 | } | |
1039 | }) | |
1040 | // Sequelize could return null... | |
1041 | if (!totalLocalVideoViews) totalLocalVideoViews = 0 | |
1042 | ||
1043 | return { | |
1044 | totalLocalVideos, | |
1045 | totalLocalVideoViews, | |
1046 | totalVideos | |
1047 | } | |
1048 | } | |
1049 | ||
1050 | private static buildActorWhereWithFilter (filter?: VideoFilter) { | |
1051 | if (filter && filter === 'local') { | |
1052 | return { | |
1053 | serverId: null | |
1054 | } | |
1055 | } | |
1056 | ||
1057 | return {} | |
1058 | } | |
1059 | ||
1060 | private static getCategoryLabel (id: number) { | |
1061 | return VIDEO_CATEGORIES[id] || 'Misc' | |
1062 | } | |
1063 | ||
1064 | private static getLicenceLabel (id: number) { | |
1065 | return VIDEO_LICENCES[id] || 'Unknown' | |
1066 | } | |
1067 | ||
1068 | private static getLanguageLabel (id: string) { | |
1069 | return VIDEO_LANGUAGES[id] || 'Unknown' | |
1070 | } | |
1071 | ||
1072 | private static getPrivacyLabel (id: number) { | |
1073 | return VIDEO_PRIVACIES[id] || 'Unknown' | |
1074 | } | |
1075 | ||
1076 | private static getStateLabel (id: number) { | |
1077 | return VIDEO_STATES[id] || 'Unknown' | |
1078 | } | |
1079 | ||
1080 | getOriginalFile () { | |
1081 | if (Array.isArray(this.VideoFiles) === false) return undefined | |
1082 | ||
1083 | // The original file is the file that have the higher resolution | |
1084 | return maxBy(this.VideoFiles, file => file.resolution) | |
1085 | } | |
1086 | ||
1087 | getVideoFilename (videoFile: VideoFileModel) { | |
1088 | return this.uuid + '-' + videoFile.resolution + videoFile.extname | |
1089 | } | |
1090 | ||
1091 | getThumbnailName () { | |
1092 | // We always have a copy of the thumbnail | |
1093 | const extension = '.jpg' | |
1094 | return this.uuid + extension | |
1095 | } | |
1096 | ||
1097 | getPreviewName () { | |
1098 | const extension = '.jpg' | |
1099 | return this.uuid + extension | |
1100 | } | |
1101 | ||
1102 | getTorrentFileName (videoFile: VideoFileModel) { | |
1103 | const extension = '.torrent' | |
1104 | return this.uuid + '-' + videoFile.resolution + extension | |
1105 | } | |
1106 | ||
1107 | isOwned () { | |
1108 | return this.remote === false | |
1109 | } | |
1110 | ||
1111 | createPreview (videoFile: VideoFileModel) { | |
1112 | return generateImageFromVideoFile( | |
1113 | this.getVideoFilePath(videoFile), | |
1114 | CONFIG.STORAGE.PREVIEWS_DIR, | |
1115 | this.getPreviewName(), | |
1116 | PREVIEWS_SIZE | |
1117 | ) | |
1118 | } | |
1119 | ||
1120 | createThumbnail (videoFile: VideoFileModel) { | |
1121 | return generateImageFromVideoFile( | |
1122 | this.getVideoFilePath(videoFile), | |
1123 | CONFIG.STORAGE.THUMBNAILS_DIR, | |
1124 | this.getThumbnailName(), | |
1125 | THUMBNAILS_SIZE | |
1126 | ) | |
1127 | } | |
1128 | ||
1129 | getTorrentFilePath (videoFile: VideoFileModel) { | |
1130 | return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1131 | } | |
1132 | ||
1133 | getVideoFilePath (videoFile: VideoFileModel) { | |
1134 | return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1135 | } | |
1136 | ||
1137 | async createTorrentAndSetInfoHash (videoFile: VideoFileModel) { | |
1138 | const options = { | |
1139 | // Keep the extname, it's used by the client to stream the file inside a web browser | |
1140 | name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`, | |
1141 | createdBy: 'PeerTube', | |
1142 | announceList: [ | |
1143 | [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ], | |
1144 | [ CONFIG.WEBSERVER.URL + '/tracker/announce' ] | |
1145 | ], | |
1146 | urlList: [ | |
1147 | CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
1148 | ] | |
1149 | } | |
1150 | ||
1151 | const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) | |
1152 | ||
1153 | const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1154 | logger.info('Creating torrent %s.', filePath) | |
1155 | ||
1156 | await writeFilePromise(filePath, torrent) | |
1157 | ||
1158 | const parsedTorrent = parseTorrent(torrent) | |
1159 | videoFile.infoHash = parsedTorrent.infoHash | |
1160 | } | |
1161 | ||
1162 | getEmbedStaticPath () { | |
1163 | return '/videos/embed/' + this.uuid | |
1164 | } | |
1165 | ||
1166 | getThumbnailStaticPath () { | |
1167 | return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()) | |
1168 | } | |
1169 | ||
1170 | getPreviewStaticPath () { | |
1171 | return join(STATIC_PATHS.PREVIEWS, this.getPreviewName()) | |
1172 | } | |
1173 | ||
1174 | toFormattedJSON (options?: { | |
1175 | additionalAttributes: { | |
1176 | state?: boolean, | |
1177 | waitTranscoding?: boolean, | |
1178 | scheduledUpdate?: boolean | |
1179 | } | |
1180 | }): Video { | |
1181 | const formattedAccount = this.VideoChannel.Account.toFormattedJSON() | |
1182 | const formattedVideoChannel = this.VideoChannel.toFormattedJSON() | |
1183 | ||
1184 | const videoObject: Video = { | |
1185 | id: this.id, | |
1186 | uuid: this.uuid, | |
1187 | name: this.name, | |
1188 | category: { | |
1189 | id: this.category, | |
1190 | label: VideoModel.getCategoryLabel(this.category) | |
1191 | }, | |
1192 | licence: { | |
1193 | id: this.licence, | |
1194 | label: VideoModel.getLicenceLabel(this.licence) | |
1195 | }, | |
1196 | language: { | |
1197 | id: this.language, | |
1198 | label: VideoModel.getLanguageLabel(this.language) | |
1199 | }, | |
1200 | privacy: { | |
1201 | id: this.privacy, | |
1202 | label: VideoModel.getPrivacyLabel(this.privacy) | |
1203 | }, | |
1204 | nsfw: this.nsfw, | |
1205 | description: this.getTruncatedDescription(), | |
1206 | isLocal: this.isOwned(), | |
1207 | duration: this.duration, | |
1208 | views: this.views, | |
1209 | likes: this.likes, | |
1210 | dislikes: this.dislikes, | |
1211 | thumbnailPath: this.getThumbnailStaticPath(), | |
1212 | previewPath: this.getPreviewStaticPath(), | |
1213 | embedPath: this.getEmbedStaticPath(), | |
1214 | createdAt: this.createdAt, | |
1215 | updatedAt: this.updatedAt, | |
1216 | publishedAt: this.publishedAt, | |
1217 | account: { | |
1218 | id: formattedAccount.id, | |
1219 | uuid: formattedAccount.uuid, | |
1220 | name: formattedAccount.name, | |
1221 | displayName: formattedAccount.displayName, | |
1222 | url: formattedAccount.url, | |
1223 | host: formattedAccount.host, | |
1224 | avatar: formattedAccount.avatar | |
1225 | }, | |
1226 | channel: { | |
1227 | id: formattedVideoChannel.id, | |
1228 | uuid: formattedVideoChannel.uuid, | |
1229 | name: formattedVideoChannel.name, | |
1230 | displayName: formattedVideoChannel.displayName, | |
1231 | url: formattedVideoChannel.url, | |
1232 | host: formattedVideoChannel.host, | |
1233 | avatar: formattedVideoChannel.avatar | |
1234 | } | |
1235 | } | |
1236 | ||
1237 | if (options) { | |
1238 | if (options.additionalAttributes.state === true) { | |
1239 | videoObject.state = { | |
1240 | id: this.state, | |
1241 | label: VideoModel.getStateLabel(this.state) | |
1242 | } | |
1243 | } | |
1244 | ||
1245 | if (options.additionalAttributes.waitTranscoding === true) { | |
1246 | videoObject.waitTranscoding = this.waitTranscoding | |
1247 | } | |
1248 | ||
1249 | if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) { | |
1250 | videoObject.scheduledUpdate = { | |
1251 | updateAt: this.ScheduleVideoUpdate.updateAt, | |
1252 | privacy: this.ScheduleVideoUpdate.privacy || undefined | |
1253 | } | |
1254 | } | |
1255 | } | |
1256 | ||
1257 | return videoObject | |
1258 | } | |
1259 | ||
1260 | toFormattedDetailsJSON (): VideoDetails { | |
1261 | const formattedJson = this.toFormattedJSON({ | |
1262 | additionalAttributes: { | |
1263 | scheduledUpdate: true | |
1264 | } | |
1265 | }) | |
1266 | ||
1267 | const detailsJson = { | |
1268 | support: this.support, | |
1269 | descriptionPath: this.getDescriptionPath(), | |
1270 | channel: this.VideoChannel.toFormattedJSON(), | |
1271 | account: this.VideoChannel.Account.toFormattedJSON(), | |
1272 | tags: map(this.Tags, 'name'), | |
1273 | commentsEnabled: this.commentsEnabled, | |
1274 | waitTranscoding: this.waitTranscoding, | |
1275 | state: { | |
1276 | id: this.state, | |
1277 | label: VideoModel.getStateLabel(this.state) | |
1278 | }, | |
1279 | files: [] | |
1280 | } | |
1281 | ||
1282 | // Format and sort video files | |
1283 | detailsJson.files = this.getFormattedVideoFilesJSON() | |
1284 | ||
1285 | return Object.assign(formattedJson, detailsJson) | |
1286 | } | |
1287 | ||
1288 | getFormattedVideoFilesJSON (): VideoFile[] { | |
1289 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
1290 | ||
1291 | return this.VideoFiles | |
1292 | .map(videoFile => { | |
1293 | let resolutionLabel = videoFile.resolution + 'p' | |
1294 | ||
1295 | return { | |
1296 | resolution: { | |
1297 | id: videoFile.resolution, | |
1298 | label: resolutionLabel | |
1299 | }, | |
1300 | magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs), | |
1301 | size: videoFile.size, | |
1302 | fps: videoFile.fps, | |
1303 | torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp), | |
1304 | torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp), | |
1305 | fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp), | |
1306 | fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp) | |
1307 | } as VideoFile | |
1308 | }) | |
1309 | .sort((a, b) => { | |
1310 | if (a.resolution.id < b.resolution.id) return 1 | |
1311 | if (a.resolution.id === b.resolution.id) return 0 | |
1312 | return -1 | |
1313 | }) | |
1314 | } | |
1315 | ||
1316 | toActivityPubObject (): VideoTorrentObject { | |
1317 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
1318 | if (!this.Tags) this.Tags = [] | |
1319 | ||
1320 | const tag = this.Tags.map(t => ({ | |
1321 | type: 'Hashtag' as 'Hashtag', | |
1322 | name: t.name | |
1323 | })) | |
1324 | ||
1325 | let language | |
1326 | if (this.language) { | |
1327 | language = { | |
1328 | identifier: this.language, | |
1329 | name: VideoModel.getLanguageLabel(this.language) | |
1330 | } | |
1331 | } | |
1332 | ||
1333 | let category | |
1334 | if (this.category) { | |
1335 | category = { | |
1336 | identifier: this.category + '', | |
1337 | name: VideoModel.getCategoryLabel(this.category) | |
1338 | } | |
1339 | } | |
1340 | ||
1341 | let licence | |
1342 | if (this.licence) { | |
1343 | licence = { | |
1344 | identifier: this.licence + '', | |
1345 | name: VideoModel.getLicenceLabel(this.licence) | |
1346 | } | |
1347 | } | |
1348 | ||
1349 | const url = [] | |
1350 | for (const file of this.VideoFiles) { | |
1351 | url.push({ | |
1352 | type: 'Link', | |
1353 | mimeType: VIDEO_EXT_MIMETYPE[file.extname], | |
1354 | href: this.getVideoFileUrl(file, baseUrlHttp), | |
1355 | width: file.resolution, | |
1356 | size: file.size | |
1357 | }) | |
1358 | ||
1359 | url.push({ | |
1360 | type: 'Link', | |
1361 | mimeType: 'application/x-bittorrent', | |
1362 | href: this.getTorrentUrl(file, baseUrlHttp), | |
1363 | width: file.resolution | |
1364 | }) | |
1365 | ||
1366 | url.push({ | |
1367 | type: 'Link', | |
1368 | mimeType: 'application/x-bittorrent;x-scheme-handler/magnet', | |
1369 | href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs), | |
1370 | width: file.resolution | |
1371 | }) | |
1372 | } | |
1373 | ||
1374 | // Add video url too | |
1375 | url.push({ | |
1376 | type: 'Link', | |
1377 | mimeType: 'text/html', | |
1378 | href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid | |
1379 | }) | |
1380 | ||
1381 | const subtitleLanguage = [] | |
1382 | for (const caption of this.VideoCaptions) { | |
1383 | subtitleLanguage.push({ | |
1384 | identifier: caption.language, | |
1385 | name: VideoCaptionModel.getLanguageLabel(caption.language) | |
1386 | }) | |
1387 | } | |
1388 | ||
1389 | return { | |
1390 | type: 'Video' as 'Video', | |
1391 | id: this.url, | |
1392 | name: this.name, | |
1393 | duration: this.getActivityStreamDuration(), | |
1394 | uuid: this.uuid, | |
1395 | tag, | |
1396 | category, | |
1397 | licence, | |
1398 | language, | |
1399 | views: this.views, | |
1400 | sensitive: this.nsfw, | |
1401 | waitTranscoding: this.waitTranscoding, | |
1402 | state: this.state, | |
1403 | commentsEnabled: this.commentsEnabled, | |
1404 | published: this.publishedAt.toISOString(), | |
1405 | updated: this.updatedAt.toISOString(), | |
1406 | mediaType: 'text/markdown', | |
1407 | content: this.getTruncatedDescription(), | |
1408 | support: this.support, | |
1409 | subtitleLanguage, | |
1410 | icon: { | |
1411 | type: 'Image', | |
1412 | url: this.getThumbnailUrl(baseUrlHttp), | |
1413 | mediaType: 'image/jpeg', | |
1414 | width: THUMBNAILS_SIZE.width, | |
1415 | height: THUMBNAILS_SIZE.height | |
1416 | }, | |
1417 | url, | |
1418 | likes: getVideoLikesActivityPubUrl(this), | |
1419 | dislikes: getVideoDislikesActivityPubUrl(this), | |
1420 | shares: getVideoSharesActivityPubUrl(this), | |
1421 | comments: getVideoCommentsActivityPubUrl(this), | |
1422 | attributedTo: [ | |
1423 | { | |
1424 | type: 'Person', | |
1425 | id: this.VideoChannel.Account.Actor.url | |
1426 | }, | |
1427 | { | |
1428 | type: 'Group', | |
1429 | id: this.VideoChannel.Actor.url | |
1430 | } | |
1431 | ] | |
1432 | } | |
1433 | } | |
1434 | ||
1435 | getTruncatedDescription () { | |
1436 | if (!this.description) return null | |
1437 | ||
1438 | const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max | |
1439 | return peertubeTruncate(this.description, maxLength) | |
1440 | } | |
1441 | ||
1442 | async optimizeOriginalVideofile () { | |
1443 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
1444 | const newExtname = '.mp4' | |
1445 | const inputVideoFile = this.getOriginalFile() | |
1446 | const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile)) | |
1447 | const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname) | |
1448 | ||
1449 | const transcodeOptions = { | |
1450 | inputPath: videoInputPath, | |
1451 | outputPath: videoTranscodedPath | |
1452 | } | |
1453 | ||
1454 | // Could be very long! | |
1455 | await transcode(transcodeOptions) | |
1456 | ||
1457 | try { | |
1458 | await unlinkPromise(videoInputPath) | |
1459 | ||
1460 | // Important to do this before getVideoFilename() to take in account the new file extension | |
1461 | inputVideoFile.set('extname', newExtname) | |
1462 | ||
1463 | const videoOutputPath = this.getVideoFilePath(inputVideoFile) | |
1464 | await renamePromise(videoTranscodedPath, videoOutputPath) | |
1465 | const stats = await statPromise(videoOutputPath) | |
1466 | const fps = await getVideoFileFPS(videoOutputPath) | |
1467 | ||
1468 | inputVideoFile.set('size', stats.size) | |
1469 | inputVideoFile.set('fps', fps) | |
1470 | ||
1471 | await this.createTorrentAndSetInfoHash(inputVideoFile) | |
1472 | await inputVideoFile.save() | |
1473 | ||
1474 | } catch (err) { | |
1475 | // Auto destruction... | |
1476 | this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err })) | |
1477 | ||
1478 | throw err | |
1479 | } | |
1480 | } | |
1481 | ||
1482 | async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) { | |
1483 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
1484 | const extname = '.mp4' | |
1485 | ||
1486 | // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed | |
1487 | const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile())) | |
1488 | ||
1489 | const newVideoFile = new VideoFileModel({ | |
1490 | resolution, | |
1491 | extname, | |
1492 | size: 0, | |
1493 | videoId: this.id | |
1494 | }) | |
1495 | const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile)) | |
1496 | ||
1497 | const transcodeOptions = { | |
1498 | inputPath: videoInputPath, | |
1499 | outputPath: videoOutputPath, | |
1500 | resolution, | |
1501 | isPortraitMode | |
1502 | } | |
1503 | ||
1504 | await transcode(transcodeOptions) | |
1505 | ||
1506 | const stats = await statPromise(videoOutputPath) | |
1507 | const fps = await getVideoFileFPS(videoOutputPath) | |
1508 | ||
1509 | newVideoFile.set('size', stats.size) | |
1510 | newVideoFile.set('fps', fps) | |
1511 | ||
1512 | await this.createTorrentAndSetInfoHash(newVideoFile) | |
1513 | ||
1514 | await newVideoFile.save() | |
1515 | ||
1516 | this.VideoFiles.push(newVideoFile) | |
1517 | } | |
1518 | ||
1519 | async importVideoFile (inputFilePath: string) { | |
1520 | const { videoFileResolution } = await getVideoFileResolution(inputFilePath) | |
1521 | const { size } = await statPromise(inputFilePath) | |
1522 | const fps = await getVideoFileFPS(inputFilePath) | |
1523 | ||
1524 | let updatedVideoFile = new VideoFileModel({ | |
1525 | resolution: videoFileResolution, | |
1526 | extname: extname(inputFilePath), | |
1527 | size, | |
1528 | fps, | |
1529 | videoId: this.id | |
1530 | }) | |
1531 | ||
1532 | const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution) | |
1533 | ||
1534 | if (currentVideoFile) { | |
1535 | // Remove old file and old torrent | |
1536 | await this.removeFile(currentVideoFile) | |
1537 | await this.removeTorrent(currentVideoFile) | |
1538 | // Remove the old video file from the array | |
1539 | this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile) | |
1540 | ||
1541 | // Update the database | |
1542 | currentVideoFile.set('extname', updatedVideoFile.extname) | |
1543 | currentVideoFile.set('size', updatedVideoFile.size) | |
1544 | currentVideoFile.set('fps', updatedVideoFile.fps) | |
1545 | ||
1546 | updatedVideoFile = currentVideoFile | |
1547 | } | |
1548 | ||
1549 | const outputPath = this.getVideoFilePath(updatedVideoFile) | |
1550 | await copyFilePromise(inputFilePath, outputPath) | |
1551 | ||
1552 | await this.createTorrentAndSetInfoHash(updatedVideoFile) | |
1553 | ||
1554 | await updatedVideoFile.save() | |
1555 | ||
1556 | this.VideoFiles.push(updatedVideoFile) | |
1557 | } | |
1558 | ||
1559 | getOriginalFileResolution () { | |
1560 | const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) | |
1561 | ||
1562 | return getVideoFileResolution(originalFilePath) | |
1563 | } | |
1564 | ||
1565 | getDescriptionPath () { | |
1566 | return `/api/${API_VERSION}/videos/${this.uuid}/description` | |
1567 | } | |
1568 | ||
1569 | removeThumbnail () { | |
1570 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName()) | |
1571 | return unlinkPromise(thumbnailPath) | |
1572 | } | |
1573 | ||
1574 | removePreview () { | |
1575 | // Same name than video thumbnail | |
1576 | return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName()) | |
1577 | } | |
1578 | ||
1579 | removeFile (videoFile: VideoFileModel) { | |
1580 | const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1581 | return unlinkPromise(filePath) | |
1582 | } | |
1583 | ||
1584 | removeTorrent (videoFile: VideoFileModel) { | |
1585 | const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1586 | return unlinkPromise(torrentPath) | |
1587 | } | |
1588 | ||
1589 | getActivityStreamDuration () { | |
1590 | // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration | |
1591 | return 'PT' + this.duration + 'S' | |
1592 | } | |
1593 | ||
1594 | private getBaseUrls () { | |
1595 | let baseUrlHttp | |
1596 | let baseUrlWs | |
1597 | ||
1598 | if (this.isOwned()) { | |
1599 | baseUrlHttp = CONFIG.WEBSERVER.URL | |
1600 | baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT | |
1601 | } else { | |
1602 | baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host | |
1603 | baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host | |
1604 | } | |
1605 | ||
1606 | return { baseUrlHttp, baseUrlWs } | |
1607 | } | |
1608 | ||
1609 | private getThumbnailUrl (baseUrlHttp: string) { | |
1610 | return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName() | |
1611 | } | |
1612 | ||
1613 | private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1614 | return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) | |
1615 | } | |
1616 | ||
1617 | private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1618 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile) | |
1619 | } | |
1620 | ||
1621 | private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1622 | return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
1623 | } | |
1624 | ||
1625 | private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1626 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile) | |
1627 | } | |
1628 | ||
1629 | private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { | |
1630 | const xs = this.getTorrentUrl(videoFile, baseUrlHttp) | |
1631 | const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
1632 | const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] | |
1633 | ||
1634 | const magnetHash = { | |
1635 | xs, | |
1636 | announce, | |
1637 | urlList, | |
1638 | infoHash: videoFile.infoHash, | |
1639 | name: this.name | |
1640 | } | |
1641 | ||
1642 | return magnetUtil.encode(magnetHash) | |
1643 | } | |
1644 | } |