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