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