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