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