]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video.ts
fabfce588d541a67b6c915599b6368bcddc72ec1
[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-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) {
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')
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')
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 return 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')
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 Promise.all(tasks)
829 .catch(err => {
830 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
831 })
832
833 return undefined
834 }
835
836 static listLocal (): Promise<MVideo[]> {
837 const query = {
838 where: {
839 remote: false
840 }
841 }
842
843 return VideoModel.findAll(query)
844 }
845
846 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
847 function getRawQuery (select: string) {
848 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
849 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
850 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
851 'WHERE "Account"."actorId" = ' + actorId
852 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
853 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
854 'WHERE "VideoShare"."actorId" = ' + actorId
855
856 return `(${queryVideo}) UNION (${queryVideoShare})`
857 }
858
859 const rawQuery = getRawQuery('"Video"."id"')
860 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
861
862 const query = {
863 distinct: true,
864 offset: start,
865 limit: count,
866 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
867 where: {
868 id: {
869 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
870 },
871 [Op.or]: getPrivaciesForFederation()
872 },
873 include: [
874 {
875 attributes: [ 'filename', 'language', 'fileUrl' ],
876 model: VideoCaptionModel.unscoped(),
877 required: false
878 },
879 {
880 attributes: [ 'id', 'url' ],
881 model: VideoShareModel.unscoped(),
882 required: false,
883 // We only want videos shared by this actor
884 where: {
885 [Op.and]: [
886 {
887 id: {
888 [Op.not]: null
889 }
890 },
891 {
892 actorId
893 }
894 ]
895 },
896 include: [
897 {
898 attributes: [ 'id', 'url' ],
899 model: ActorModel.unscoped()
900 }
901 ]
902 },
903 {
904 model: VideoChannelModel.unscoped(),
905 required: true,
906 include: [
907 {
908 attributes: [ 'name' ],
909 model: AccountModel.unscoped(),
910 required: true,
911 include: [
912 {
913 attributes: [ 'id', 'url', 'followersUrl' ],
914 model: ActorModel.unscoped(),
915 required: true
916 }
917 ]
918 },
919 {
920 attributes: [ 'id', 'url', 'followersUrl' ],
921 model: ActorModel.unscoped(),
922 required: true
923 }
924 ]
925 },
926 {
927 model: VideoStreamingPlaylistModel.unscoped(),
928 required: false,
929 include: [
930 {
931 model: VideoFileModel,
932 required: false
933 }
934 ]
935 },
936 VideoLiveModel.unscoped(),
937 VideoFileModel,
938 TagModel
939 ]
940 }
941
942 return Bluebird.all([
943 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
944 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
945 ]).then(([ rows, totals ]) => {
946 // totals: totalVideos + totalVideoShares
947 let totalVideos = 0
948 let totalVideoShares = 0
949 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
950 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
951
952 const total = totalVideos + totalVideoShares
953 return {
954 data: rows,
955 total: total
956 }
957 })
958 }
959
960 static async listPublishedLiveUUIDs () {
961 const options = {
962 attributes: [ 'uuid' ],
963 where: {
964 isLive: true,
965 remote: false,
966 state: VideoState.PUBLISHED
967 }
968 }
969
970 const result = await VideoModel.findAll(options)
971
972 return result.map(v => v.uuid)
973 }
974
975 static listUserVideosForApi (options: {
976 accountId: number
977 start: number
978 count: number
979 sort: string
980 isLive?: boolean
981 search?: string
982 }) {
983 const { accountId, start, count, sort, search, isLive } = options
984
985 function buildBaseQuery (): FindOptions {
986 const where: WhereOptions = {}
987
988 if (search) {
989 where.name = {
990 [Op.iLike]: '%' + search + '%'
991 }
992 }
993
994 if (isLive) {
995 where.isLive = isLive
996 }
997
998 const baseQuery = {
999 offset: start,
1000 limit: count,
1001 where,
1002 order: getVideoSort(sort),
1003 include: [
1004 {
1005 model: VideoChannelModel,
1006 required: true,
1007 include: [
1008 {
1009 model: AccountModel,
1010 where: {
1011 id: accountId
1012 },
1013 required: true
1014 }
1015 ]
1016 }
1017 ]
1018 }
1019
1020 return baseQuery
1021 }
1022
1023 const countQuery = buildBaseQuery()
1024 const findQuery = buildBaseQuery()
1025
1026 const findScopes: (string | ScopeOptions)[] = [
1027 ScopeNames.WITH_SCHEDULED_UPDATE,
1028 ScopeNames.WITH_BLACKLISTED,
1029 ScopeNames.WITH_THUMBNAILS
1030 ]
1031
1032 return Promise.all([
1033 VideoModel.count(countQuery),
1034 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1035 ]).then(([ count, rows ]) => {
1036 return {
1037 data: rows,
1038 total: count
1039 }
1040 })
1041 }
1042
1043 static async listForApi (options: {
1044 start: number
1045 count: number
1046 sort: string
1047
1048 nsfw: boolean
1049 filter?: VideoFilter
1050 isLive?: boolean
1051
1052 includeLocalVideos: boolean
1053 withFiles: boolean
1054
1055 categoryOneOf?: number[]
1056 licenceOneOf?: number[]
1057 languageOneOf?: string[]
1058 tagsOneOf?: string[]
1059 tagsAllOf?: string[]
1060
1061 accountId?: number
1062 videoChannelId?: number
1063
1064 followerActorId?: number
1065
1066 videoPlaylistId?: number
1067
1068 trendingDays?: number
1069
1070 user?: MUserAccountId
1071 historyOfUser?: MUserId
1072
1073 countVideos?: boolean
1074
1075 search?: string
1076 }) {
1077 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1078 throw new Error('Try to filter all-local but no user has not the see all videos right')
1079 }
1080
1081 const trendingDays = options.sort.endsWith('trending')
1082 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1083 : undefined
1084 let trendingAlgorithm
1085 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1086 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1087
1088 const serverActor = await getServerActor()
1089
1090 // followerActorId === null has a meaning, so just check undefined
1091 const followerActorId = options.followerActorId !== undefined
1092 ? options.followerActorId
1093 : serverActor.id
1094
1095 const queryOptions = {
1096 start: options.start,
1097 count: options.count,
1098 sort: options.sort,
1099 followerActorId,
1100 serverAccountId: serverActor.Account.id,
1101 nsfw: options.nsfw,
1102 isLive: options.isLive,
1103 categoryOneOf: options.categoryOneOf,
1104 licenceOneOf: options.licenceOneOf,
1105 languageOneOf: options.languageOneOf,
1106 tagsOneOf: options.tagsOneOf,
1107 tagsAllOf: options.tagsAllOf,
1108 filter: options.filter,
1109 withFiles: options.withFiles,
1110 accountId: options.accountId,
1111 videoChannelId: options.videoChannelId,
1112 videoPlaylistId: options.videoPlaylistId,
1113 includeLocalVideos: options.includeLocalVideos,
1114 user: options.user,
1115 historyOfUser: options.historyOfUser,
1116 trendingDays,
1117 trendingAlgorithm,
1118 search: options.search
1119 }
1120
1121 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1122 }
1123
1124 static async searchAndPopulateAccountAndServer (options: {
1125 includeLocalVideos: boolean
1126 search?: string
1127 start?: number
1128 count?: number
1129 sort?: string
1130 startDate?: string // ISO 8601
1131 endDate?: string // ISO 8601
1132 originallyPublishedStartDate?: string
1133 originallyPublishedEndDate?: string
1134 nsfw?: boolean
1135 isLive?: boolean
1136 categoryOneOf?: number[]
1137 licenceOneOf?: number[]
1138 languageOneOf?: string[]
1139 tagsOneOf?: string[]
1140 tagsAllOf?: string[]
1141 durationMin?: number // seconds
1142 durationMax?: number // seconds
1143 user?: MUserAccountId
1144 filter?: VideoFilter
1145 }) {
1146 const serverActor = await getServerActor()
1147
1148 const queryOptions = {
1149 followerActorId: serverActor.id,
1150 serverAccountId: serverActor.Account.id,
1151
1152 includeLocalVideos: options.includeLocalVideos,
1153 nsfw: options.nsfw,
1154 isLive: options.isLive,
1155
1156 categoryOneOf: options.categoryOneOf,
1157 licenceOneOf: options.licenceOneOf,
1158 languageOneOf: options.languageOneOf,
1159
1160 tagsOneOf: options.tagsOneOf,
1161 tagsAllOf: options.tagsAllOf,
1162
1163 user: options.user,
1164 filter: options.filter,
1165
1166 start: options.start,
1167 count: options.count,
1168 sort: options.sort,
1169
1170 startDate: options.startDate,
1171 endDate: options.endDate,
1172
1173 originallyPublishedStartDate: options.originallyPublishedStartDate,
1174 originallyPublishedEndDate: options.originallyPublishedEndDate,
1175
1176 durationMin: options.durationMin,
1177 durationMax: options.durationMax,
1178
1179 search: options.search
1180 }
1181
1182 return VideoModel.getAvailableForApi(queryOptions)
1183 }
1184
1185 static countLocalLives () {
1186 const options = {
1187 where: {
1188 remote: false,
1189 isLive: true,
1190 state: {
1191 [Op.ne]: VideoState.LIVE_ENDED
1192 }
1193 }
1194 }
1195
1196 return VideoModel.count(options)
1197 }
1198
1199 static countVideosUploadedByUserSince (userId: number, since: Date) {
1200 const options = {
1201 include: [
1202 {
1203 model: VideoChannelModel.unscoped(),
1204 required: true,
1205 include: [
1206 {
1207 model: AccountModel.unscoped(),
1208 required: true,
1209 include: [
1210 {
1211 model: UserModel.unscoped(),
1212 required: true,
1213 where: {
1214 id: userId
1215 }
1216 }
1217 ]
1218 }
1219 ]
1220 }
1221 ],
1222 where: {
1223 createdAt: {
1224 [Op.gte]: since
1225 }
1226 }
1227 }
1228
1229 return VideoModel.unscoped().count(options)
1230 }
1231
1232 static countLivesOfAccount (accountId: number) {
1233 const options = {
1234 where: {
1235 remote: false,
1236 isLive: true,
1237 state: {
1238 [Op.ne]: VideoState.LIVE_ENDED
1239 }
1240 },
1241 include: [
1242 {
1243 required: true,
1244 model: VideoChannelModel.unscoped(),
1245 where: {
1246 accountId
1247 }
1248 }
1249 ]
1250 }
1251
1252 return VideoModel.count(options)
1253 }
1254
1255 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1256 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1257
1258 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1259 }
1260
1261 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1262 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1263
1264 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1265 }
1266
1267 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1268 const fun = () => {
1269 const query = {
1270 where: buildWhereIdOrUUID(id),
1271 transaction: t
1272 }
1273
1274 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1275 }
1276
1277 return ModelCache.Instance.doCache({
1278 cacheType: 'load-video-immutable-id',
1279 key: '' + id,
1280 deleteKey: 'video',
1281 fun
1282 })
1283 }
1284
1285 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1286 const fun = () => {
1287 const query: FindOptions = {
1288 where: {
1289 url
1290 },
1291 transaction
1292 }
1293
1294 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1295 }
1296
1297 return ModelCache.Instance.doCache({
1298 cacheType: 'load-video-immutable-url',
1299 key: url,
1300 deleteKey: 'video',
1301 fun
1302 })
1303 }
1304
1305 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1306 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1307
1308 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1309 }
1310
1311 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1312 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1313
1314 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1315 }
1316
1317 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1318 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1319
1320 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1321 }
1322
1323 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1324 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1325
1326 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1327 }
1328
1329 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1330 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1331
1332 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1333 }
1334
1335 static loadForGetAPI (parameters: {
1336 id: number | string
1337 transaction?: Transaction
1338 userId?: number
1339 }): Promise<MVideoDetails> {
1340 const { id, transaction, userId } = parameters
1341 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1342
1343 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1344 }
1345
1346 static async getStats () {
1347 const totalLocalVideos = await VideoModel.count({
1348 where: {
1349 remote: false
1350 }
1351 })
1352
1353 let totalLocalVideoViews = await VideoModel.sum('views', {
1354 where: {
1355 remote: false
1356 }
1357 })
1358
1359 // Sequelize could return null...
1360 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1361
1362 const { total: totalVideos } = await VideoModel.listForApi({
1363 start: 0,
1364 count: 0,
1365 sort: '-publishedAt',
1366 nsfw: buildNSFWFilter(),
1367 includeLocalVideos: true,
1368 withFiles: false
1369 })
1370
1371 return {
1372 totalLocalVideos,
1373 totalLocalVideoViews,
1374 totalVideos
1375 }
1376 }
1377
1378 static incrementViews (id: number, views: number) {
1379 return VideoModel.increment('views', {
1380 by: views,
1381 where: {
1382 id
1383 }
1384 })
1385 }
1386
1387 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1388 const field = type === 'like'
1389 ? 'likes'
1390 : 'dislikes'
1391
1392 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1393 '(' +
1394 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1395 ') ' +
1396 'WHERE "video"."id" = :videoId'
1397
1398 return AccountVideoRateModel.sequelize.query(rawQuery, {
1399 transaction: t,
1400 replacements: { videoId, rateType: type },
1401 type: QueryTypes.UPDATE
1402 })
1403 }
1404
1405 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1406 // Instances only share videos
1407 const query = 'SELECT 1 FROM "videoShare" ' +
1408 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1409 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1410 'LIMIT 1'
1411
1412 const options = {
1413 type: QueryTypes.SELECT as QueryTypes.SELECT,
1414 bind: { followerActorId, videoId },
1415 raw: true
1416 }
1417
1418 return VideoModel.sequelize.query(query, options)
1419 .then(results => results.length === 1)
1420 }
1421
1422 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1423 const options = {
1424 where: {
1425 channelId: ofChannel.id
1426 },
1427 transaction: t
1428 }
1429
1430 return VideoModel.update({ support: ofChannel.support }, options)
1431 }
1432
1433 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1434 const query = {
1435 attributes: [ 'id' ],
1436 where: {
1437 channelId: videoChannel.id
1438 }
1439 }
1440
1441 return VideoModel.findAll(query)
1442 .then(videos => videos.map(v => v.id))
1443 }
1444
1445 // threshold corresponds to how many video the field should have to be returned
1446 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1447 const serverActor = await getServerActor()
1448 const followerActorId = serverActor.id
1449
1450 const queryOptions: BuildVideosListQueryOptions = {
1451 attributes: [ `"${field}"` ],
1452 group: `GROUP BY "${field}"`,
1453 having: `HAVING COUNT("${field}") >= ${threshold}`,
1454 start: 0,
1455 sort: 'random',
1456 count,
1457 serverAccountId: serverActor.Account.id,
1458 followerActorId,
1459 includeLocalVideos: true
1460 }
1461
1462 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1463
1464 return queryBuilder.queryVideoIds(queryOptions)
1465 .then(rows => rows.map(r => r[field]))
1466 }
1467
1468 static buildTrendingQuery (trendingDays: number) {
1469 return {
1470 attributes: [],
1471 subQuery: false,
1472 model: VideoViewModel,
1473 required: false,
1474 where: {
1475 startDate: {
1476 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1477 }
1478 }
1479 }
1480 }
1481
1482 private static async getAvailableForApi (
1483 options: BuildVideosListQueryOptions,
1484 countVideos = true
1485 ): Promise<ResultList<VideoModel>> {
1486 function getCount () {
1487 if (countVideos !== true) return Promise.resolve(undefined)
1488
1489 const countOptions = Object.assign({}, options, { isCount: true })
1490 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1491
1492 return queryBuilder.countVideoIds(countOptions)
1493 }
1494
1495 function getModels () {
1496 if (options.count === 0) return Promise.resolve([])
1497
1498 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1499
1500 return queryBuilder.queryVideos(options)
1501 }
1502
1503 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1504
1505 return {
1506 data: rows,
1507 total: count
1508 }
1509 }
1510
1511 isBlacklisted () {
1512 return !!this.VideoBlacklist
1513 }
1514
1515 isBlocked () {
1516 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1517 }
1518
1519 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1520 // We first transcode to WebTorrent format, so try this array first
1521 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1522 const file = fun(this.VideoFiles, file => file.resolution)
1523
1524 return Object.assign(file, { Video: this })
1525 }
1526
1527 // No webtorrent files, try with streaming playlist files
1528 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1529 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1530
1531 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1532 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1533 }
1534
1535 return undefined
1536 }
1537
1538 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1539 return this.getQualityFileBy(maxBy)
1540 }
1541
1542 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1543 return this.getQualityFileBy(minBy)
1544 }
1545
1546 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1547 if (Array.isArray(this.VideoFiles) === false) return undefined
1548
1549 const file = this.VideoFiles.find(f => f.resolution === resolution)
1550 if (!file) return undefined
1551
1552 return Object.assign(file, { Video: this })
1553 }
1554
1555 hasWebTorrentFiles () {
1556 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1557 }
1558
1559 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1560 thumbnail.videoId = this.id
1561
1562 const savedThumbnail = await thumbnail.save({ transaction })
1563
1564 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1565
1566 // Already have this thumbnail, skip
1567 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1568
1569 this.Thumbnails.push(savedThumbnail)
1570 }
1571
1572 getMiniature () {
1573 if (Array.isArray(this.Thumbnails) === false) return undefined
1574
1575 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1576 }
1577
1578 hasPreview () {
1579 return !!this.getPreview()
1580 }
1581
1582 getPreview () {
1583 if (Array.isArray(this.Thumbnails) === false) return undefined
1584
1585 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1586 }
1587
1588 isOwned () {
1589 return this.remote === false
1590 }
1591
1592 getWatchStaticPath () {
1593 return '/w/' + this.uuid
1594 }
1595
1596 getEmbedStaticPath () {
1597 return '/videos/embed/' + this.uuid
1598 }
1599
1600 getMiniatureStaticPath () {
1601 const thumbnail = this.getMiniature()
1602 if (!thumbnail) return null
1603
1604 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1605 }
1606
1607 getPreviewStaticPath () {
1608 const preview = this.getPreview()
1609 if (!preview) return null
1610
1611 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1612 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1613 }
1614
1615 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1616 return videoModelToFormattedJSON(this, options)
1617 }
1618
1619 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1620 return videoModelToFormattedDetailsJSON(this)
1621 }
1622
1623 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1624 let files: VideoFile[] = []
1625
1626 if (Array.isArray(this.VideoFiles)) {
1627 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1628 files = files.concat(result)
1629 }
1630
1631 for (const p of (this.VideoStreamingPlaylists || [])) {
1632 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1633 files = files.concat(result)
1634 }
1635
1636 return files
1637 }
1638
1639 toActivityPubObject (this: MVideoAP): VideoObject {
1640 return videoModelToActivityPubObject(this)
1641 }
1642
1643 getTruncatedDescription () {
1644 if (!this.description) return null
1645
1646 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1647 return peertubeTruncate(this.description, { length: maxLength })
1648 }
1649
1650 getMaxQualityResolution () {
1651 const file = this.getMaxQualityFile()
1652 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1653 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1654
1655 return getVideoFileResolution(originalFilePath)
1656 }
1657
1658 getDescriptionAPIPath () {
1659 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1660 }
1661
1662 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1663 if (!this.VideoStreamingPlaylists) return undefined
1664
1665 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1666 playlist.Video = this
1667
1668 return playlist
1669 }
1670
1671 setHLSPlaylist (playlist: MStreamingPlaylist) {
1672 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1673
1674 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1675 this.VideoStreamingPlaylists = toAdd
1676 return
1677 }
1678
1679 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1680 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1681 .concat(toAdd)
1682 }
1683
1684 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1685 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1686 return remove(filePath)
1687 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1688 }
1689
1690 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1691 const directoryPath = getHLSDirectory(this, isRedundancy)
1692
1693 await remove(directoryPath)
1694
1695 if (isRedundancy !== true) {
1696 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1697 streamingPlaylistWithFiles.Video = this
1698
1699 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1700 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1701 }
1702
1703 // Remove physical files and torrents
1704 await Promise.all(
1705 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1706 )
1707 }
1708 }
1709
1710 isOutdated () {
1711 if (this.isOwned()) return false
1712
1713 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1714 }
1715
1716 hasPrivacyForFederation () {
1717 return isPrivacyForFederation(this.privacy)
1718 }
1719
1720 hasStateForFederation () {
1721 return isStateForFederation(this.state)
1722 }
1723
1724 isNewVideo (newPrivacy: VideoPrivacy) {
1725 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1726 }
1727
1728 setAsRefreshed () {
1729 return setAsUpdated('video', this.id)
1730 }
1731
1732 requiresAuth () {
1733 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1734 }
1735
1736 setPrivacy (newPrivacy: VideoPrivacy) {
1737 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1738 this.publishedAt = new Date()
1739 }
1740
1741 this.privacy = newPrivacy
1742 }
1743
1744 isConfidential () {
1745 return this.privacy === VideoPrivacy.PRIVATE ||
1746 this.privacy === VideoPrivacy.UNLISTED ||
1747 this.privacy === VideoPrivacy.INTERNAL
1748 }
1749
1750 async publishIfNeededAndSave (t: Transaction) {
1751 if (this.state !== VideoState.PUBLISHED) {
1752 this.state = VideoState.PUBLISHED
1753 this.publishedAt = new Date()
1754 await this.save({ transaction: t })
1755
1756 return true
1757 }
1758
1759 return false
1760 }
1761
1762 getBandwidthBits (videoFile: MVideoFile) {
1763 return Math.ceil((videoFile.size * 8) / this.duration)
1764 }
1765
1766 getTrackerUrls () {
1767 if (this.isOwned()) {
1768 return [
1769 WEBSERVER.URL + '/tracker/announce',
1770 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1771 ]
1772 }
1773
1774 return this.Trackers.map(t => t.url)
1775 }
1776 }