1 import Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy } from 'lodash'
4 import { FindOptions, Includeable, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
28 } from 'sequelize-typescript'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { InternalEventEmitter } from '@server/lib/internal-event-emitter'
31 import { LiveManager } from '@server/lib/live/live-manager'
32 import { removeHLSFileObjectStorageByFilename, removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
33 import { tracer } from '@server/lib/opentelemetry/tracing'
34 import { getHLSDirectory, getHLSRedundancyDirectory, getHlsResolutionPlaylistFilename } from '@server/lib/paths'
35 import { Hooks } from '@server/lib/plugins/hooks'
36 import { VideoPathManager } from '@server/lib/video-path-manager'
37 import { isVideoInPrivateDirectory } from '@server/lib/video-privacy'
38 import { getServerActor } from '@server/models/application/application'
39 import { ModelCache } from '@server/models/shared/model-cache'
40 import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
41 import { uuidToShort } from '@shared/extra-utils'
42 import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS, hasAudioStream } from '@shared/ffmpeg'
56 VideoStreamingPlaylistType
57 } from '@shared/models'
58 import { AttributesOnly } from '@shared/typescript-utils'
59 import { peertubeTruncate } from '../../helpers/core-utils'
60 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
61 import { exists, isBooleanValid, isUUIDValid } from '../../helpers/custom-validators/misc'
63 isVideoDescriptionValid,
69 } from '../../helpers/custom-validators/videos'
70 import { logger } from '../../helpers/logger'
71 import { CONFIG } from '../../initializers/config'
72 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
73 import { sendDeleteVideo } from '../../lib/activitypub/send'
76 MChannelAccountDefault,
79 MStreamingPlaylistFilesVideo,
84 MVideoAccountLightBlacklistAllFiles,
89 MVideoFormattableDetails,
95 MVideoThumbnailBlacklist,
98 } from '../../types/models'
99 import { MThumbnail } from '../../types/models/video/thumbnail'
100 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
101 import { VideoAbuseModel } from '../abuse/video-abuse'
102 import { AccountModel } from '../account/account'
103 import { AccountVideoRateModel } from '../account/account-video-rate'
104 import { ActorModel } from '../actor/actor'
105 import { ActorImageModel } from '../actor/actor-image'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { TrackerModel } from '../server/tracker'
109 import { VideoTrackerModel } from '../server/video-tracker'
110 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, setAsUpdated, throwIfNotValid } from '../shared'
111 import { UserModel } from '../user/user'
112 import { UserVideoHistoryModel } from '../user/user-video-history'
113 import { VideoViewModel } from '../view/video-view'
115 videoFilesModelToFormattedJSON,
116 VideoFormattingJSONOptions,
117 videoModelToActivityPubObject,
118 videoModelToFormattedDetailsJSON,
119 videoModelToFormattedJSON
120 } from './formatter/video-format-utils'
121 import { ScheduleVideoUpdateModel } from './schedule-video-update'
123 BuildVideosListQueryOptions,
124 DisplayOnlyForFollowerOptions,
125 VideoModelGetQueryBuilder,
126 VideosIdListQueryBuilder,
127 VideosModelListQueryBuilder
129 import { TagModel } from './tag'
130 import { ThumbnailModel } from './thumbnail'
131 import { VideoBlacklistModel } from './video-blacklist'
132 import { VideoCaptionModel } from './video-caption'
133 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
134 import { VideoCommentModel } from './video-comment'
135 import { VideoFileModel } from './video-file'
136 import { VideoImportModel } from './video-import'
137 import { VideoJobInfoModel } from './video-job-info'
138 import { VideoLiveModel } from './video-live'
139 import { VideoPlaylistElementModel } from './video-playlist-element'
140 import { VideoShareModel } from './video-share'
141 import { VideoSourceModel } from './video-source'
142 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
143 import { VideoTagModel } from './video-tag'
145 export enum ScopeNames {
147 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
148 WITH_TAGS = 'WITH_TAGS',
149 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
150 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
151 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
152 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
153 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
154 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
155 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
158 export type ForAPIOptions = {
161 videoPlaylistId?: number
163 withAccountBlockerIds?: number[]
167 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
168 attributes: [ 'id', 'url', 'uuid', 'remote' ]
170 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
171 const include: Includeable[] = [
173 model: VideoChannelModel.scope({
175 VideoChannelScopeNames.SUMMARY, {
177 withAccountBlockerIds: options.withAccountBlockerIds
184 attributes: [ 'type', 'filename' ],
185 model: ThumbnailModel,
190 const query: FindOptions = {}
200 if (options.videoPlaylistId) {
202 model: VideoPlaylistElementModel.unscoped(),
205 videoPlaylistId: options.videoPlaylistId
210 query.include = include
214 [ScopeNames.WITH_THUMBNAILS]: {
217 model: ThumbnailModel,
222 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
225 model: VideoChannelModel.unscoped(),
230 exclude: [ 'privateKey', 'publicKey' ]
232 model: ActorModel.unscoped(),
236 attributes: [ 'host' ],
237 model: ServerModel.unscoped(),
241 model: ActorImageModel,
248 model: AccountModel.unscoped(),
252 model: ActorModel.unscoped(),
254 exclude: [ 'privateKey', 'publicKey' ]
259 attributes: [ 'host' ],
260 model: ServerModel.unscoped(),
264 model: ActorImageModel,
276 [ScopeNames.WITH_TAGS]: {
277 include: [ TagModel ]
279 [ScopeNames.WITH_BLACKLISTED]: {
282 attributes: [ 'id', 'reason', 'unfederated' ],
283 model: VideoBlacklistModel,
288 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
289 let subInclude: any[] = []
291 if (withRedundancies === true) {
294 attributes: [ 'fileUrl' ],
295 model: VideoRedundancyModel.unscoped(),
304 model: VideoFileModel,
312 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
313 const subInclude: IncludeOptions[] = [
315 model: VideoFileModel,
320 if (withRedundancies === true) {
322 attributes: [ 'fileUrl' ],
323 model: VideoRedundancyModel.unscoped(),
331 model: VideoStreamingPlaylistModel.unscoped(),
339 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
342 model: ScheduleVideoUpdateModel.unscoped(),
347 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
351 attributes: [ 'currentTime' ],
352 model: UserVideoHistoryModel.unscoped(),
365 buildTrigramSearchIndex('video_name_trigram', 'name'),
367 { fields: [ 'createdAt' ] },
370 { name: 'publishedAt', order: 'DESC' },
371 { name: 'id', order: 'ASC' }
374 { fields: [ 'duration' ] },
377 { name: 'views', order: 'DESC' },
378 { name: 'id', order: 'ASC' }
381 { fields: [ 'channelId' ] },
383 fields: [ 'originallyPublishedAt' ],
385 originallyPublishedAt: {
391 fields: [ 'category' ], // We don't care videos with an unknown category
399 fields: [ 'licence' ], // We don't care videos with an unknown licence
407 fields: [ 'language' ], // We don't care videos with an unknown language
415 fields: [ 'nsfw' ], // Most of the videos are not NSFW
421 fields: [ 'remote' ], // Only index local videos
436 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
439 @Default(DataType.UUIDV4)
441 @Column(DataType.UUID)
445 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
461 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
465 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
467 privacy: VideoPrivacy
470 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
476 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
477 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
482 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
483 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
487 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
522 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
523 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
528 commentsEnabled: boolean
532 downloadEnabled: boolean
536 waitTranscoding: boolean
540 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
551 @Default(DataType.NOW)
558 originallyPublishedAt: Date
560 @ForeignKey(() => VideoChannelModel)
564 @BelongsTo(() => VideoChannelModel, {
570 VideoChannel: VideoChannelModel
572 @BelongsToMany(() => TagModel, {
573 foreignKey: 'videoId',
574 through: () => VideoTagModel,
579 @BelongsToMany(() => TrackerModel, {
580 foreignKey: 'videoId',
581 through: () => VideoTrackerModel,
584 Trackers: TrackerModel[]
586 @HasMany(() => ThumbnailModel, {
594 Thumbnails: ThumbnailModel[]
596 @HasMany(() => VideoPlaylistElementModel, {
603 VideoPlaylistElements: VideoPlaylistElementModel[]
605 @HasOne(() => VideoSourceModel, {
612 VideoSource: VideoSourceModel
614 @HasMany(() => VideoAbuseModel, {
621 VideoAbuses: VideoAbuseModel[]
623 @HasMany(() => VideoFileModel, {
631 VideoFiles: VideoFileModel[]
633 @HasMany(() => VideoStreamingPlaylistModel, {
641 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
643 @HasMany(() => VideoShareModel, {
650 VideoShares: VideoShareModel[]
652 @HasMany(() => AccountVideoRateModel, {
659 AccountVideoRates: AccountVideoRateModel[]
661 @HasMany(() => VideoCommentModel, {
669 VideoComments: VideoCommentModel[]
671 @HasMany(() => VideoViewModel, {
678 VideoViews: VideoViewModel[]
680 @HasMany(() => UserVideoHistoryModel, {
687 UserVideoHistories: UserVideoHistoryModel[]
689 @HasOne(() => ScheduleVideoUpdateModel, {
696 ScheduleVideoUpdate: ScheduleVideoUpdateModel
698 @HasOne(() => VideoBlacklistModel, {
705 VideoBlacklist: VideoBlacklistModel
707 @HasOne(() => VideoLiveModel, {
715 VideoLive: VideoLiveModel
717 @HasOne(() => VideoImportModel, {
724 VideoImport: VideoImportModel
726 @HasMany(() => VideoCaptionModel, {
733 ['separate' as any]: true
735 VideoCaptions: VideoCaptionModel[]
737 @HasOne(() => VideoJobInfoModel, {
744 VideoJobInfo: VideoJobInfoModel
747 static notifyCreate (video: MVideo) {
748 InternalEventEmitter.Instance.emit('video-created', { video })
752 static notifyUpdate (video: MVideo) {
753 InternalEventEmitter.Instance.emit('video-updated', { video })
757 static notifyDestroy (video: MVideo) {
758 InternalEventEmitter.Instance.emit('video-deleted', { video })
762 static async sendDelete (instance: MVideoAccountLight, options: { transaction: Transaction }) {
763 if (!instance.isOwned()) return undefined
765 // Lazy load channels
766 if (!instance.VideoChannel) {
767 instance.VideoChannel = await instance.$get('VideoChannel', {
772 transaction: options.transaction
773 }) as MChannelAccountDefault
776 return sendDeleteVideo(instance, options.transaction)
780 static async removeFiles (instance: VideoModel, options) {
781 const tasks: Promise<any>[] = []
783 logger.info('Removing files of video %s.', instance.url)
785 if (instance.isOwned()) {
786 if (!Array.isArray(instance.VideoFiles)) {
787 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
790 // Remove physical files and torrents
791 instance.VideoFiles.forEach(file => {
792 tasks.push(instance.removeWebTorrentFile(file))
795 // Remove playlists file
796 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
797 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
800 for (const p of instance.VideoStreamingPlaylists) {
801 tasks.push(instance.removeStreamingPlaylistFiles(p))
805 // Do not wait video deletion because we could be in a transaction
807 .then(() => logger.info('Removed files of video %s.', instance.url))
808 .catch(err => logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }))
814 static stopLiveIfNeeded (instance: VideoModel) {
815 if (!instance.isLive) return
817 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
819 LiveManager.Instance.stopSessionOf(instance.uuid, null)
823 static invalidateCache (instance: VideoModel) {
824 ModelCache.Instance.invalidateCache('video', instance.id)
828 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
829 const tasks: Promise<any>[] = []
831 if (!Array.isArray(instance.VideoAbuses)) {
832 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
834 if (instance.VideoAbuses.length === 0) return undefined
837 logger.info('Saving video abuses details of video %s.', instance.url)
839 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
840 const details = instance.toFormattedDetailsJSON()
842 for (const abuse of instance.VideoAbuses) {
843 abuse.deletedVideo = details
844 tasks.push(abuse.save({ transaction: options.transaction }))
847 await Promise.all(tasks)
850 static listLocalIds (): Promise<number[]> {
852 attributes: [ 'id' ],
859 return VideoModel.findAll(query)
860 .then(rows => rows.map(r => r.id))
863 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
864 function getRawQuery (select: string) {
865 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
866 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
867 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
868 'WHERE "Account"."actorId" = ' + actorId
869 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
870 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
871 'WHERE "VideoShare"."actorId" = ' + actorId
873 return `(${queryVideo}) UNION (${queryVideoShare})`
876 const rawQuery = getRawQuery('"Video"."id"')
877 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
883 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
886 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
888 [Op.or]: getPrivaciesForFederation()
892 attributes: [ 'filename', 'language', 'fileUrl' ],
893 model: VideoCaptionModel.unscoped(),
897 attributes: [ 'id', 'url' ],
898 model: VideoShareModel.unscoped(),
900 // We only want videos shared by this actor
915 attributes: [ 'id', 'url' ],
916 model: ActorModel.unscoped()
921 model: VideoChannelModel.unscoped(),
925 attributes: [ 'name' ],
926 model: AccountModel.unscoped(),
930 attributes: [ 'id', 'url', 'followersUrl' ],
931 model: ActorModel.unscoped(),
937 attributes: [ 'id', 'url', 'followersUrl' ],
938 model: ActorModel.unscoped(),
944 model: VideoStreamingPlaylistModel.unscoped(),
948 model: VideoFileModel,
953 VideoLiveModel.unscoped(),
959 return Bluebird.all([
960 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
961 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
962 ]).then(([ rows, totals ]) => {
963 // totals: totalVideos + totalVideoShares
965 let totalVideoShares = 0
966 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
967 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
969 const total = totalVideos + totalVideoShares
977 static async listPublishedLiveUUIDs () {
979 attributes: [ 'uuid' ],
983 state: VideoState.PUBLISHED
987 const result = await VideoModel.findAll(options)
989 return result.map(v => v.uuid)
992 static listUserVideosForApi (options: {
1002 const { accountId, channelId, start, count, sort, search, isLive } = options
1004 function buildBaseQuery (forCount: boolean): FindOptions {
1005 const where: WhereOptions = {}
1009 [Op.iLike]: '%' + search + '%'
1013 if (exists(isLive)) {
1014 where.isLive = isLive
1017 const channelWhere = channelId
1025 order: getVideoSort(sort),
1029 ? VideoChannelModel.unscoped()
1030 : VideoChannelModel,
1032 where: channelWhere,
1036 ? AccountModel.unscoped()
1051 const countQuery = buildBaseQuery(true)
1052 const findQuery = buildBaseQuery(false)
1054 const findScopes: (string | ScopeOptions)[] = [
1055 ScopeNames.WITH_SCHEDULED_UPDATE,
1056 ScopeNames.WITH_BLACKLISTED,
1057 ScopeNames.WITH_THUMBNAILS
1060 return Promise.all([
1061 VideoModel.count(countQuery),
1062 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1063 ]).then(([ count, rows ]) => {
1071 static async listForApi (options: {
1079 include?: VideoInclude
1081 hasFiles?: boolean // default false
1082 hasWebtorrentFiles?: boolean
1083 hasHLSFiles?: boolean
1085 categoryOneOf?: number[]
1086 licenceOneOf?: number[]
1087 languageOneOf?: string[]
1088 tagsOneOf?: string[]
1089 tagsAllOf?: string[]
1090 privacyOneOf?: VideoPrivacy[]
1093 videoChannelId?: number
1095 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1097 videoPlaylistId?: number
1099 trendingDays?: number
1101 user?: MUserAccountId
1102 historyOfUser?: MUserId
1104 countVideos?: boolean
1108 excludeAlreadyWatched?: boolean
1110 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1111 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1113 const trendingDays = options.sort.endsWith('trending')
1114 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1117 let trendingAlgorithm: string
1118 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1119 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1121 const serverActor = await getServerActor()
1123 const queryOptions = {
1138 'displayOnlyForFollower',
1146 'hasWebtorrentFiles',
1148 'excludeAlreadyWatched'
1151 serverAccountIdForBlock: serverActor.Account.id,
1156 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1159 static async searchAndPopulateAccountAndServer (options: {
1167 include?: VideoInclude
1169 categoryOneOf?: number[]
1170 licenceOneOf?: number[]
1171 languageOneOf?: string[]
1172 tagsOneOf?: string[]
1173 tagsAllOf?: string[]
1174 privacyOneOf?: VideoPrivacy[]
1176 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1178 user?: MUserAccountId
1180 hasWebtorrentFiles?: boolean
1181 hasHLSFiles?: boolean
1186 startDate?: string // ISO 8601
1187 endDate?: string // ISO 8601
1188 originallyPublishedStartDate?: string
1189 originallyPublishedEndDate?: string
1191 durationMin?: number // seconds
1192 durationMax?: number // seconds
1195 excludeAlreadyWatched?: boolean
1197 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1198 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1200 const serverActor = await getServerActor()
1202 const queryOptions = {
1221 'originallyPublishedStartDate',
1222 'originallyPublishedEndDate',
1226 'hasWebtorrentFiles',
1229 'displayOnlyForFollower',
1230 'excludeAlreadyWatched'
1232 serverAccountIdForBlock: serverActor.Account.id
1235 return VideoModel.getAvailableForApi(queryOptions)
1238 static countLives (options: {
1240 mode: 'published' | 'not-ended'
1244 remote: options.remote,
1246 state: options.mode === 'not-ended'
1247 ? { [Op.ne]: VideoState.LIVE_ENDED }
1248 : { [Op.eq]: VideoState.PUBLISHED }
1252 return VideoModel.count(query)
1255 static countVideosUploadedByUserSince (userId: number, since: Date) {
1259 model: VideoChannelModel.unscoped(),
1263 model: AccountModel.unscoped(),
1267 model: UserModel.unscoped(),
1285 return VideoModel.unscoped().count(options)
1288 static countLivesOfAccount (accountId: number) {
1294 [Op.ne]: VideoState.LIVE_ENDED
1300 model: VideoChannelModel.unscoped(),
1308 return VideoModel.count(options)
1311 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1312 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1314 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1317 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1318 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1320 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1323 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1326 where: buildWhereIdOrUUID(id),
1330 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1333 return ModelCache.Instance.doCache({
1334 cacheType: 'load-video-immutable-id',
1341 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1343 const query: FindOptions = {
1350 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1353 return ModelCache.Instance.doCache({
1354 cacheType: 'load-video-immutable-url',
1361 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1362 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1364 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1367 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1368 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1370 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1373 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1374 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1376 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1379 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1380 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1382 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1385 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1386 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1388 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
1391 static loadForGetAPI (parameters: {
1393 transaction?: Transaction
1395 }): Promise<MVideoDetails> {
1396 const { id, transaction, userId } = parameters
1397 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1399 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1402 static async getStats () {
1403 const serverActor = await getServerActor()
1405 let totalLocalVideoViews = await VideoModel.sum('views', {
1411 // Sequelize could return null...
1412 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1414 const baseOptions = {
1417 sort: '-publishedAt',
1419 displayOnlyForFollower: {
1420 actorId: serverActor.id,
1425 const { total: totalLocalVideos } = await VideoModel.listForApi({
1431 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1435 totalLocalVideoViews,
1440 static incrementViews (id: number, views: number) {
1441 return VideoModel.increment('views', {
1449 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1450 const field = type === 'like'
1454 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1456 return AccountVideoRateModel.sequelize.query(rawQuery, {
1458 replacements: { videoId, rateType: type, count },
1459 type: QueryTypes.UPDATE
1463 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
1464 const field = type === 'like'
1468 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1470 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1472 'WHERE "video"."id" = :videoId'
1474 return AccountVideoRateModel.sequelize.query(rawQuery, {
1476 replacements: { videoId, rateType: type },
1477 type: QueryTypes.UPDATE
1481 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1482 // Instances only share videos
1483 const query = 'SELECT 1 FROM "videoShare" ' +
1484 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1485 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1487 'SELECT 1 FROM "video" ' +
1488 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
1489 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
1490 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "account"."actorId" ' +
1491 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "video"."id" = $videoId ' +
1495 type: QueryTypes.SELECT as QueryTypes.SELECT,
1496 bind: { followerActorId, videoId },
1500 return VideoModel.sequelize.query(query, options)
1501 .then(results => results.length === 1)
1504 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1507 channelId: ofChannel.id
1512 return VideoModel.update({ support: ofChannel.support }, options)
1515 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1517 attributes: [ 'id' ],
1519 channelId: videoChannel.id
1523 return VideoModel.findAll(query)
1524 .then(videos => videos.map(v => v.id))
1527 // threshold corresponds to how many video the field should have to be returned
1528 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1529 const serverActor = await getServerActor()
1531 const queryOptions: BuildVideosListQueryOptions = {
1532 attributes: [ `"${field}"` ],
1533 group: `GROUP BY "${field}"`,
1534 having: `HAVING COUNT("${field}") >= ${threshold}`,
1538 serverAccountIdForBlock: serverActor.Account.id,
1539 displayOnlyForFollower: {
1540 actorId: serverActor.id,
1545 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1547 return queryBuilder.queryVideoIds(queryOptions)
1548 .then(rows => rows.map(r => r[field]))
1551 static buildTrendingQuery (trendingDays: number) {
1555 model: VideoViewModel,
1560 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1566 private static async getAvailableForApi (
1567 options: BuildVideosListQueryOptions,
1569 ): Promise<ResultList<VideoModel>> {
1570 const span = tracer.startSpan('peertube.VideoModel.getAvailableForApi')
1572 function getCount () {
1573 if (countVideos !== true) return Promise.resolve(undefined)
1575 const countOptions = Object.assign({}, options, { isCount: true })
1576 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1578 return queryBuilder.countVideoIds(countOptions)
1581 function getModels () {
1582 if (options.count === 0) return Promise.resolve([])
1584 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1586 return queryBuilder.queryVideos(options)
1589 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1599 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1600 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1601 throw new Error('Try to filter all-local but user cannot see all videos')
1605 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1606 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1607 throw new Error('Try to choose video privacies but user cannot see all videos')
1611 private static isPrivateInclude (include: VideoInclude) {
1612 return include & VideoInclude.BLACKLISTED ||
1613 include & VideoInclude.BLOCKED_OWNER ||
1614 include & VideoInclude.NOT_PUBLISHED_STATE
1618 return !!this.VideoBlacklist
1622 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1625 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1626 const files = this.getAllFiles()
1627 const file = fun(files, file => file.resolution)
1628 if (!file) return undefined
1631 return Object.assign(file, { Video: this })
1634 if (file.videoStreamingPlaylistId) {
1635 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1637 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1640 throw new Error('File is not associated to a video of a playlist')
1643 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1644 return this.getQualityFileBy(maxBy)
1647 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1648 return this.getQualityFileBy(minBy)
1651 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1652 if (Array.isArray(this.VideoFiles) === false) return undefined
1654 const file = this.VideoFiles.find(f => f.resolution === resolution)
1655 if (!file) return undefined
1657 return Object.assign(file, { Video: this })
1660 hasWebTorrentFiles () {
1661 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1664 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1665 thumbnail.videoId = this.id
1667 const savedThumbnail = await thumbnail.save({ transaction })
1669 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1671 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1672 this.Thumbnails.push(savedThumbnail)
1676 if (Array.isArray(this.Thumbnails) === false) return undefined
1678 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1682 return !!this.getPreview()
1686 if (Array.isArray(this.Thumbnails) === false) return undefined
1688 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1692 return this.remote === false
1695 getWatchStaticPath () {
1696 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1699 getEmbedStaticPath () {
1700 return buildVideoEmbedPath(this)
1703 getMiniatureStaticPath () {
1704 const thumbnail = this.getMiniature()
1705 if (!thumbnail) return null
1707 return thumbnail.getLocalStaticPath()
1710 getPreviewStaticPath () {
1711 const preview = this.getPreview()
1712 if (!preview) return null
1714 return preview.getLocalStaticPath()
1717 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1718 return videoModelToFormattedJSON(this, options)
1721 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1722 return videoModelToFormattedDetailsJSON(this)
1725 getFormattedWebVideoFilesJSON (includeMagnet = true): VideoFile[] {
1726 return videoFilesModelToFormattedJSON(this, this.VideoFiles, { includeMagnet })
1729 getFormattedHLSVideoFilesJSON (includeMagnet = true): VideoFile[] {
1730 let acc: VideoFile[] = []
1732 for (const p of this.VideoStreamingPlaylists) {
1733 acc = acc.concat(videoFilesModelToFormattedJSON(this, p.VideoFiles, { includeMagnet }))
1739 getFormattedAllVideoFilesJSON (includeMagnet = true): VideoFile[] {
1740 let files: VideoFile[] = []
1742 if (Array.isArray(this.VideoFiles)) {
1743 files = files.concat(this.getFormattedWebVideoFilesJSON(includeMagnet))
1746 if (Array.isArray(this.VideoStreamingPlaylists)) {
1747 files = files.concat(this.getFormattedHLSVideoFilesJSON(includeMagnet))
1753 toActivityPubObject (this: MVideoAP): Promise<VideoObject> {
1754 return Hooks.wrapObject(
1755 videoModelToActivityPubObject(this),
1756 'filter:activity-pub.video.json-ld.build.result',
1761 getTruncatedDescription () {
1762 if (!this.description) return null
1764 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1765 return peertubeTruncate(this.description, { length: maxLength })
1769 let files: MVideoFile[] = []
1771 if (Array.isArray(this.VideoFiles)) {
1772 files = files.concat(this.VideoFiles)
1775 if (Array.isArray(this.VideoStreamingPlaylists)) {
1776 for (const p of this.VideoStreamingPlaylists) {
1777 if (Array.isArray(p.VideoFiles)) {
1778 files = files.concat(p.VideoFiles)
1786 probeMaxQualityFile () {
1787 const file = this.getMaxQualityFile()
1788 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1790 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1791 const probe = await ffprobePromise(originalFilePath)
1793 const { audioStream } = await getAudioStream(originalFilePath, probe)
1794 const hasAudio = await hasAudioStream(originalFilePath, probe)
1795 const fps = await getVideoStreamFPS(originalFilePath, probe)
1802 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
1807 getDescriptionAPIPath () {
1808 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1811 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1812 if (!this.VideoStreamingPlaylists) return undefined
1814 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1815 if (!playlist) return undefined
1817 return playlist.withVideo(this)
1820 setHLSPlaylist (playlist: MStreamingPlaylist) {
1821 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1823 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1824 this.VideoStreamingPlaylists = toAdd
1828 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1829 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1833 removeWebTorrentFile (videoFile: MVideoFile, isRedundancy = false) {
1834 const filePath = isRedundancy
1835 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1836 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1838 const promises: Promise<any>[] = [ remove(filePath) ]
1839 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1841 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1842 promises.push(removeWebTorrentObjectStorage(videoFile))
1845 return Promise.all(promises)
1848 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1849 const directoryPath = isRedundancy
1850 ? getHLSRedundancyDirectory(this)
1851 : getHLSDirectory(this)
1853 await remove(directoryPath)
1855 if (isRedundancy !== true) {
1856 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1857 streamingPlaylistWithFiles.Video = this
1859 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1860 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1863 // Remove physical files and torrents
1865 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1868 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1869 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1874 async removeStreamingPlaylistVideoFile (streamingPlaylist: MStreamingPlaylist, videoFile: MVideoFile) {
1875 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, videoFile.filename)
1876 await videoFile.removeTorrent()
1877 await remove(filePath)
1879 const resolutionFilename = getHlsResolutionPlaylistFilename(videoFile.filename)
1880 await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
1882 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1883 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
1884 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
1888 async removeStreamingPlaylistFile (streamingPlaylist: MStreamingPlaylist, filename: string) {
1889 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, filename)
1890 await remove(filePath)
1892 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1893 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
1898 if (this.isOwned()) return false
1900 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1903 hasPrivacyForFederation () {
1904 return isPrivacyForFederation(this.privacy)
1907 hasStateForFederation () {
1908 return isStateForFederation(this.state)
1911 isNewVideo (newPrivacy: VideoPrivacy) {
1912 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1915 setAsRefreshed (transaction?: Transaction) {
1916 return setAsUpdated({ sequelize: this.sequelize, table: 'video', id: this.id, transaction })
1919 // ---------------------------------------------------------------------------
1921 requiresAuth (options: {
1923 checkBlacklist: boolean
1925 const { urlParamId, checkBlacklist } = options
1927 if (this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL) {
1931 if (this.privacy === VideoPrivacy.UNLISTED) {
1932 if (urlParamId && !isUUIDValid(urlParamId)) return true
1937 if (checkBlacklist && this.VideoBlacklist) return true
1939 if (this.privacy !== VideoPrivacy.PUBLIC) {
1940 throw new Error(`Unknown video privacy ${this.privacy} to know if the video requires auth`)
1946 hasPrivateStaticPath () {
1947 return isVideoInPrivateDirectory(this.privacy)
1950 // ---------------------------------------------------------------------------
1952 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1953 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1955 this.state = newState
1957 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1958 this.publishedAt = new Date()
1961 await this.save({ transaction })
1964 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1965 if (!this.duration) throw new Error(`Cannot get bandwidth bits because video ${this.url} has duration of 0`)
1967 return Math.ceil((videoFile.size * 8) / this.duration)
1971 if (this.isOwned()) {
1973 WEBSERVER.URL + '/tracker/announce',
1974 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1978 return this.Trackers.map(t => t.url)