1 import 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'
26 } from 'sequelize-typescript'
27 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
28 import { LiveManager } from '@server/lib/live/live-manager'
29 import { removeHLSFileObjectStorageByFilename, removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
30 import { tracer } from '@server/lib/opentelemetry/tracing'
31 import { getHLSDirectory, getHLSRedundancyDirectory, getHlsResolutionPlaylistFilename } from '@server/lib/paths'
32 import { VideoPathManager } from '@server/lib/video-path-manager'
33 import { isVideoInPrivateDirectory } from '@server/lib/video-privacy'
34 import { getServerActor } from '@server/models/application/application'
35 import { ModelCache } from '@server/models/shared/model-cache'
36 import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
37 import { ffprobePromise, getAudioStream, hasAudioStream, uuidToShort } from '@shared/extra-utils'
51 VideoStreamingPlaylistType
52 } from '@shared/models'
53 import { AttributesOnly } from '@shared/typescript-utils'
54 import { peertubeTruncate } from '../../helpers/core-utils'
55 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
56 import { exists, isBooleanValid, isUUIDValid } from '../../helpers/custom-validators/misc'
58 isVideoDescriptionValid,
64 } from '../../helpers/custom-validators/videos'
65 import { getVideoStreamDimensionsInfo } from '../../helpers/ffmpeg'
66 import { logger } from '../../helpers/logger'
67 import { CONFIG } from '../../initializers/config'
68 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
69 import { sendDeleteVideo } from '../../lib/activitypub/send'
72 MChannelAccountDefault,
75 MStreamingPlaylistFilesVideo,
80 MVideoAccountLightBlacklistAllFiles,
85 MVideoFormattableDetails,
91 MVideoThumbnailBlacklist,
94 } from '../../types/models'
95 import { MThumbnail } from '../../types/models/video/thumbnail'
96 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
97 import { VideoAbuseModel } from '../abuse/video-abuse'
98 import { AccountModel } from '../account/account'
99 import { AccountVideoRateModel } from '../account/account-video-rate'
100 import { ActorModel } from '../actor/actor'
101 import { ActorImageModel } from '../actor/actor-image'
102 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
103 import { ServerModel } from '../server/server'
104 import { TrackerModel } from '../server/tracker'
105 import { VideoTrackerModel } from '../server/video-tracker'
106 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, setAsUpdated, throwIfNotValid } from '../shared'
107 import { UserModel } from '../user/user'
108 import { UserVideoHistoryModel } from '../user/user-video-history'
109 import { VideoViewModel } from '../view/video-view'
111 videoFilesModelToFormattedJSON,
112 VideoFormattingJSONOptions,
113 videoModelToActivityPubObject,
114 videoModelToFormattedDetailsJSON,
115 videoModelToFormattedJSON
116 } from './formatter/video-format-utils'
117 import { ScheduleVideoUpdateModel } from './schedule-video-update'
119 BuildVideosListQueryOptions,
120 DisplayOnlyForFollowerOptions,
121 VideoModelGetQueryBuilder,
122 VideosIdListQueryBuilder,
123 VideosModelListQueryBuilder
125 import { TagModel } from './tag'
126 import { ThumbnailModel } from './thumbnail'
127 import { VideoBlacklistModel } from './video-blacklist'
128 import { VideoCaptionModel } from './video-caption'
129 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
130 import { VideoCommentModel } from './video-comment'
131 import { VideoFileModel } from './video-file'
132 import { VideoImportModel } from './video-import'
133 import { VideoJobInfoModel } from './video-job-info'
134 import { VideoLiveModel } from './video-live'
135 import { VideoPlaylistElementModel } from './video-playlist-element'
136 import { VideoShareModel } from './video-share'
137 import { VideoSourceModel } from './video-source'
138 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
139 import { VideoTagModel } from './video-tag'
140 import { Hooks } from '@server/lib/plugins/hooks'
142 export enum ScopeNames {
144 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
145 WITH_TAGS = 'WITH_TAGS',
146 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
147 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
148 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
149 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
150 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
151 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
152 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
155 export type ForAPIOptions = {
158 videoPlaylistId?: number
160 withAccountBlockerIds?: number[]
164 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
165 attributes: [ 'id', 'url', 'uuid', 'remote' ]
167 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
168 const include: Includeable[] = [
170 model: VideoChannelModel.scope({
172 VideoChannelScopeNames.SUMMARY, {
174 withAccountBlockerIds: options.withAccountBlockerIds
181 attributes: [ 'type', 'filename' ],
182 model: ThumbnailModel,
187 const query: FindOptions = {}
197 if (options.videoPlaylistId) {
199 model: VideoPlaylistElementModel.unscoped(),
202 videoPlaylistId: options.videoPlaylistId
207 query.include = include
211 [ScopeNames.WITH_THUMBNAILS]: {
214 model: ThumbnailModel,
219 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
222 model: VideoChannelModel.unscoped(),
227 exclude: [ 'privateKey', 'publicKey' ]
229 model: ActorModel.unscoped(),
233 attributes: [ 'host' ],
234 model: ServerModel.unscoped(),
238 model: ActorImageModel,
245 model: AccountModel.unscoped(),
249 model: ActorModel.unscoped(),
251 exclude: [ 'privateKey', 'publicKey' ]
256 attributes: [ 'host' ],
257 model: ServerModel.unscoped(),
261 model: ActorImageModel,
273 [ScopeNames.WITH_TAGS]: {
274 include: [ TagModel ]
276 [ScopeNames.WITH_BLACKLISTED]: {
279 attributes: [ 'id', 'reason', 'unfederated' ],
280 model: VideoBlacklistModel,
285 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
286 let subInclude: any[] = []
288 if (withRedundancies === true) {
291 attributes: [ 'fileUrl' ],
292 model: VideoRedundancyModel.unscoped(),
301 model: VideoFileModel,
309 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
310 const subInclude: IncludeOptions[] = [
312 model: VideoFileModel,
317 if (withRedundancies === true) {
319 attributes: [ 'fileUrl' ],
320 model: VideoRedundancyModel.unscoped(),
328 model: VideoStreamingPlaylistModel.unscoped(),
336 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
339 model: ScheduleVideoUpdateModel.unscoped(),
344 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
348 attributes: [ 'currentTime' ],
349 model: UserVideoHistoryModel.unscoped(),
362 buildTrigramSearchIndex('video_name_trigram', 'name'),
364 { fields: [ 'createdAt' ] },
367 { name: 'publishedAt', order: 'DESC' },
368 { name: 'id', order: 'ASC' }
371 { fields: [ 'duration' ] },
374 { name: 'views', order: 'DESC' },
375 { name: 'id', order: 'ASC' }
378 { fields: [ 'channelId' ] },
380 fields: [ 'originallyPublishedAt' ],
382 originallyPublishedAt: {
388 fields: [ 'category' ], // We don't care videos with an unknown category
396 fields: [ 'licence' ], // We don't care videos with an unknown licence
404 fields: [ 'language' ], // We don't care videos with an unknown language
412 fields: [ 'nsfw' ], // Most of the videos are not NSFW
418 fields: [ 'remote' ], // Only index local videos
433 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
436 @Default(DataType.UUIDV4)
438 @Column(DataType.UUID)
442 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
458 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
462 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
464 privacy: VideoPrivacy
467 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
473 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
474 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
479 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
480 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
484 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
519 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
520 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
525 commentsEnabled: boolean
529 downloadEnabled: boolean
533 waitTranscoding: boolean
537 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
548 @Default(DataType.NOW)
555 originallyPublishedAt: Date
557 @ForeignKey(() => VideoChannelModel)
561 @BelongsTo(() => VideoChannelModel, {
567 VideoChannel: VideoChannelModel
569 @BelongsToMany(() => TagModel, {
570 foreignKey: 'videoId',
571 through: () => VideoTagModel,
576 @BelongsToMany(() => TrackerModel, {
577 foreignKey: 'videoId',
578 through: () => VideoTrackerModel,
581 Trackers: TrackerModel[]
583 @HasMany(() => ThumbnailModel, {
591 Thumbnails: ThumbnailModel[]
593 @HasMany(() => VideoPlaylistElementModel, {
600 VideoPlaylistElements: VideoPlaylistElementModel[]
602 @HasOne(() => VideoSourceModel, {
609 VideoSource: VideoSourceModel
611 @HasMany(() => VideoAbuseModel, {
618 VideoAbuses: VideoAbuseModel[]
620 @HasMany(() => VideoFileModel, {
628 VideoFiles: VideoFileModel[]
630 @HasMany(() => VideoStreamingPlaylistModel, {
638 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
640 @HasMany(() => VideoShareModel, {
647 VideoShares: VideoShareModel[]
649 @HasMany(() => AccountVideoRateModel, {
656 AccountVideoRates: AccountVideoRateModel[]
658 @HasMany(() => VideoCommentModel, {
666 VideoComments: VideoCommentModel[]
668 @HasMany(() => VideoViewModel, {
675 VideoViews: VideoViewModel[]
677 @HasMany(() => UserVideoHistoryModel, {
684 UserVideoHistories: UserVideoHistoryModel[]
686 @HasOne(() => ScheduleVideoUpdateModel, {
693 ScheduleVideoUpdate: ScheduleVideoUpdateModel
695 @HasOne(() => VideoBlacklistModel, {
702 VideoBlacklist: VideoBlacklistModel
704 @HasOne(() => VideoLiveModel, {
712 VideoLive: VideoLiveModel
714 @HasOne(() => VideoImportModel, {
721 VideoImport: VideoImportModel
723 @HasMany(() => VideoCaptionModel, {
730 ['separate' as any]: true
732 VideoCaptions: VideoCaptionModel[]
734 @HasOne(() => VideoJobInfoModel, {
741 VideoJobInfo: VideoJobInfoModel
744 static async sendDelete (instance: MVideoAccountLight, options) {
745 if (!instance.isOwned()) return undefined
747 // Lazy load channels
748 if (!instance.VideoChannel) {
749 instance.VideoChannel = await instance.$get('VideoChannel', {
754 transaction: options.transaction
755 }) as MChannelAccountDefault
758 return sendDeleteVideo(instance, options.transaction)
762 static async removeFiles (instance: VideoModel, options) {
763 const tasks: Promise<any>[] = []
765 logger.info('Removing files of video %s.', instance.url)
767 if (instance.isOwned()) {
768 if (!Array.isArray(instance.VideoFiles)) {
769 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
772 // Remove physical files and torrents
773 instance.VideoFiles.forEach(file => {
774 tasks.push(instance.removeWebTorrentFile(file))
777 // Remove playlists file
778 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
779 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
782 for (const p of instance.VideoStreamingPlaylists) {
783 tasks.push(instance.removeStreamingPlaylistFiles(p))
787 // Do not wait video deletion because we could be in a transaction
789 .then(() => logger.info('Removed files of video %s.', instance.url))
790 .catch(err => logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }))
796 static stopLiveIfNeeded (instance: VideoModel) {
797 if (!instance.isLive) return
799 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
801 LiveManager.Instance.stopSessionOf(instance.id, null)
805 static invalidateCache (instance: VideoModel) {
806 ModelCache.Instance.invalidateCache('video', instance.id)
810 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
811 const tasks: Promise<any>[] = []
813 if (!Array.isArray(instance.VideoAbuses)) {
814 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
816 if (instance.VideoAbuses.length === 0) return undefined
819 logger.info('Saving video abuses details of video %s.', instance.url)
821 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
822 const details = instance.toFormattedDetailsJSON()
824 for (const abuse of instance.VideoAbuses) {
825 abuse.deletedVideo = details
826 tasks.push(abuse.save({ transaction: options.transaction }))
829 await Promise.all(tasks)
832 static listLocalIds (): Promise<number[]> {
834 attributes: [ 'id' ],
841 return VideoModel.findAll(query)
842 .then(rows => rows.map(r => r.id))
845 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
846 function getRawQuery (select: string) {
847 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
848 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
849 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
850 'WHERE "Account"."actorId" = ' + actorId
851 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
852 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
853 'WHERE "VideoShare"."actorId" = ' + actorId
855 return `(${queryVideo}) UNION (${queryVideoShare})`
858 const rawQuery = getRawQuery('"Video"."id"')
859 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
865 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
868 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
870 [Op.or]: getPrivaciesForFederation()
874 attributes: [ 'filename', 'language', 'fileUrl' ],
875 model: VideoCaptionModel.unscoped(),
879 attributes: [ 'id', 'url' ],
880 model: VideoShareModel.unscoped(),
882 // We only want videos shared by this actor
897 attributes: [ 'id', 'url' ],
898 model: ActorModel.unscoped()
903 model: VideoChannelModel.unscoped(),
907 attributes: [ 'name' ],
908 model: AccountModel.unscoped(),
912 attributes: [ 'id', 'url', 'followersUrl' ],
913 model: ActorModel.unscoped(),
919 attributes: [ 'id', 'url', 'followersUrl' ],
920 model: ActorModel.unscoped(),
926 model: VideoStreamingPlaylistModel.unscoped(),
930 model: VideoFileModel,
935 VideoLiveModel.unscoped(),
941 return Bluebird.all([
942 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
943 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
944 ]).then(([ rows, totals ]) => {
945 // totals: totalVideos + totalVideoShares
947 let totalVideoShares = 0
948 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
949 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
951 const total = totalVideos + totalVideoShares
959 static async listPublishedLiveUUIDs () {
961 attributes: [ 'uuid' ],
965 state: VideoState.PUBLISHED
969 const result = await VideoModel.findAll(options)
971 return result.map(v => v.uuid)
974 static listUserVideosForApi (options: {
984 const { accountId, channelId, start, count, sort, search, isLive } = options
986 function buildBaseQuery (forCount: boolean): FindOptions {
987 const where: WhereOptions = {}
991 [Op.iLike]: '%' + search + '%'
995 if (exists(isLive)) {
996 where.isLive = isLive
999 const channelWhere = channelId
1007 order: getVideoSort(sort),
1011 ? VideoChannelModel.unscoped()
1012 : VideoChannelModel,
1014 where: channelWhere,
1018 ? AccountModel.unscoped()
1033 const countQuery = buildBaseQuery(true)
1034 const findQuery = buildBaseQuery(false)
1036 const findScopes: (string | ScopeOptions)[] = [
1037 ScopeNames.WITH_SCHEDULED_UPDATE,
1038 ScopeNames.WITH_BLACKLISTED,
1039 ScopeNames.WITH_THUMBNAILS
1042 return Promise.all([
1043 VideoModel.count(countQuery),
1044 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1045 ]).then(([ count, rows ]) => {
1053 static async listForApi (options: {
1061 include?: VideoInclude
1063 hasFiles?: boolean // default false
1064 hasWebtorrentFiles?: boolean
1065 hasHLSFiles?: boolean
1067 categoryOneOf?: number[]
1068 licenceOneOf?: number[]
1069 languageOneOf?: string[]
1070 tagsOneOf?: string[]
1071 tagsAllOf?: string[]
1072 privacyOneOf?: VideoPrivacy[]
1075 videoChannelId?: number
1077 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1079 videoPlaylistId?: number
1081 trendingDays?: number
1083 user?: MUserAccountId
1084 historyOfUser?: MUserId
1086 countVideos?: boolean
1090 excludeAlreadyWatched?: boolean
1092 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1093 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1095 const trendingDays = options.sort.endsWith('trending')
1096 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1099 let trendingAlgorithm: string
1100 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1101 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1103 const serverActor = await getServerActor()
1105 const queryOptions = {
1120 'displayOnlyForFollower',
1128 'hasWebtorrentFiles',
1130 'excludeAlreadyWatched'
1133 serverAccountIdForBlock: serverActor.Account.id,
1138 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1141 static async searchAndPopulateAccountAndServer (options: {
1149 include?: VideoInclude
1151 categoryOneOf?: number[]
1152 licenceOneOf?: number[]
1153 languageOneOf?: string[]
1154 tagsOneOf?: string[]
1155 tagsAllOf?: string[]
1156 privacyOneOf?: VideoPrivacy[]
1158 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1160 user?: MUserAccountId
1162 hasWebtorrentFiles?: boolean
1163 hasHLSFiles?: boolean
1168 startDate?: string // ISO 8601
1169 endDate?: string // ISO 8601
1170 originallyPublishedStartDate?: string
1171 originallyPublishedEndDate?: string
1173 durationMin?: number // seconds
1174 durationMax?: number // seconds
1177 excludeAlreadyWatched?: boolean
1179 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1180 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1182 const serverActor = await getServerActor()
1184 const queryOptions = {
1203 'originallyPublishedStartDate',
1204 'originallyPublishedEndDate',
1208 'hasWebtorrentFiles',
1211 'displayOnlyForFollower',
1212 'excludeAlreadyWatched'
1214 serverAccountIdForBlock: serverActor.Account.id
1217 return VideoModel.getAvailableForApi(queryOptions)
1220 static countLives (options: {
1222 mode: 'published' | 'not-ended'
1226 remote: options.remote,
1228 state: options.mode === 'not-ended'
1229 ? { [Op.ne]: VideoState.LIVE_ENDED }
1230 : { [Op.eq]: VideoState.PUBLISHED }
1234 return VideoModel.count(query)
1237 static countVideosUploadedByUserSince (userId: number, since: Date) {
1241 model: VideoChannelModel.unscoped(),
1245 model: AccountModel.unscoped(),
1249 model: UserModel.unscoped(),
1267 return VideoModel.unscoped().count(options)
1270 static countLivesOfAccount (accountId: number) {
1276 [Op.ne]: VideoState.LIVE_ENDED
1282 model: VideoChannelModel.unscoped(),
1290 return VideoModel.count(options)
1293 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1294 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1296 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1299 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1300 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1302 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1305 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1308 where: buildWhereIdOrUUID(id),
1312 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1315 return ModelCache.Instance.doCache({
1316 cacheType: 'load-video-immutable-id',
1323 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1325 const query: FindOptions = {
1332 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1335 return ModelCache.Instance.doCache({
1336 cacheType: 'load-video-immutable-url',
1343 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1344 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1346 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1349 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1350 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1352 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1355 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1356 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1358 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1361 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1362 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1364 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1367 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1368 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1370 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
1373 static loadForGetAPI (parameters: {
1375 transaction?: Transaction
1377 }): Promise<MVideoDetails> {
1378 const { id, transaction, userId } = parameters
1379 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1381 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1384 static async getStats () {
1385 const serverActor = await getServerActor()
1387 let totalLocalVideoViews = await VideoModel.sum('views', {
1393 // Sequelize could return null...
1394 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1396 const baseOptions = {
1399 sort: '-publishedAt',
1401 displayOnlyForFollower: {
1402 actorId: serverActor.id,
1407 const { total: totalLocalVideos } = await VideoModel.listForApi({
1413 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1417 totalLocalVideoViews,
1422 static incrementViews (id: number, views: number) {
1423 return VideoModel.increment('views', {
1431 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1432 const field = type === 'like'
1436 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1438 return AccountVideoRateModel.sequelize.query(rawQuery, {
1440 replacements: { videoId, rateType: type, count },
1441 type: QueryTypes.UPDATE
1445 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
1446 const field = type === 'like'
1450 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1452 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1454 'WHERE "video"."id" = :videoId'
1456 return AccountVideoRateModel.sequelize.query(rawQuery, {
1458 replacements: { videoId, rateType: type },
1459 type: QueryTypes.UPDATE
1463 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1464 // Instances only share videos
1465 const query = 'SELECT 1 FROM "videoShare" ' +
1466 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1467 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1469 'SELECT 1 FROM "video" ' +
1470 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
1471 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
1472 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "account"."actorId" ' +
1473 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "video"."id" = $videoId ' +
1477 type: QueryTypes.SELECT as QueryTypes.SELECT,
1478 bind: { followerActorId, videoId },
1482 return VideoModel.sequelize.query(query, options)
1483 .then(results => results.length === 1)
1486 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1489 channelId: ofChannel.id
1494 return VideoModel.update({ support: ofChannel.support }, options)
1497 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1499 attributes: [ 'id' ],
1501 channelId: videoChannel.id
1505 return VideoModel.findAll(query)
1506 .then(videos => videos.map(v => v.id))
1509 // threshold corresponds to how many video the field should have to be returned
1510 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1511 const serverActor = await getServerActor()
1513 const queryOptions: BuildVideosListQueryOptions = {
1514 attributes: [ `"${field}"` ],
1515 group: `GROUP BY "${field}"`,
1516 having: `HAVING COUNT("${field}") >= ${threshold}`,
1520 serverAccountIdForBlock: serverActor.Account.id,
1521 displayOnlyForFollower: {
1522 actorId: serverActor.id,
1527 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1529 return queryBuilder.queryVideoIds(queryOptions)
1530 .then(rows => rows.map(r => r[field]))
1533 static buildTrendingQuery (trendingDays: number) {
1537 model: VideoViewModel,
1542 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1548 private static async getAvailableForApi (
1549 options: BuildVideosListQueryOptions,
1551 ): Promise<ResultList<VideoModel>> {
1552 const span = tracer.startSpan('peertube.VideoModel.getAvailableForApi')
1554 function getCount () {
1555 if (countVideos !== true) return Promise.resolve(undefined)
1557 const countOptions = Object.assign({}, options, { isCount: true })
1558 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1560 return queryBuilder.countVideoIds(countOptions)
1563 function getModels () {
1564 if (options.count === 0) return Promise.resolve([])
1566 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1568 return queryBuilder.queryVideos(options)
1571 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1581 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1582 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1583 throw new Error('Try to filter all-local but user cannot see all videos')
1587 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1588 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1589 throw new Error('Try to choose video privacies but user cannot see all videos')
1593 private static isPrivateInclude (include: VideoInclude) {
1594 return include & VideoInclude.BLACKLISTED ||
1595 include & VideoInclude.BLOCKED_OWNER ||
1596 include & VideoInclude.NOT_PUBLISHED_STATE
1600 return !!this.VideoBlacklist
1604 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1607 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1608 const files = this.getAllFiles()
1609 const file = fun(files, file => file.resolution)
1610 if (!file) return undefined
1613 return Object.assign(file, { Video: this })
1616 if (file.videoStreamingPlaylistId) {
1617 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1619 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1622 throw new Error('File is not associated to a video of a playlist')
1625 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1626 return this.getQualityFileBy(maxBy)
1629 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1630 return this.getQualityFileBy(minBy)
1633 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1634 if (Array.isArray(this.VideoFiles) === false) return undefined
1636 const file = this.VideoFiles.find(f => f.resolution === resolution)
1637 if (!file) return undefined
1639 return Object.assign(file, { Video: this })
1642 hasWebTorrentFiles () {
1643 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1646 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1647 thumbnail.videoId = this.id
1649 const savedThumbnail = await thumbnail.save({ transaction })
1651 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1653 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1654 this.Thumbnails.push(savedThumbnail)
1658 if (Array.isArray(this.Thumbnails) === false) return undefined
1660 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1664 return !!this.getPreview()
1668 if (Array.isArray(this.Thumbnails) === false) return undefined
1670 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1674 return this.remote === false
1677 getWatchStaticPath () {
1678 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1681 getEmbedStaticPath () {
1682 return buildVideoEmbedPath(this)
1685 getMiniatureStaticPath () {
1686 const thumbnail = this.getMiniature()
1687 if (!thumbnail) return null
1689 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1692 getPreviewStaticPath () {
1693 const preview = this.getPreview()
1694 if (!preview) return null
1696 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1697 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1700 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1701 return videoModelToFormattedJSON(this, options)
1704 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1705 return videoModelToFormattedDetailsJSON(this)
1708 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1709 let files: VideoFile[] = []
1711 if (Array.isArray(this.VideoFiles)) {
1712 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, { includeMagnet })
1713 files = files.concat(result)
1716 for (const p of (this.VideoStreamingPlaylists || [])) {
1717 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, { includeMagnet })
1718 files = files.concat(result)
1724 toActivityPubObject (this: MVideoAP): Promise<VideoObject> {
1725 return Hooks.wrapObject(
1726 videoModelToActivityPubObject(this),
1727 'filter:activity-pub.video.json-ld.build.result',
1732 getTruncatedDescription () {
1733 if (!this.description) return null
1735 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1736 return peertubeTruncate(this.description, { length: maxLength })
1740 let files: MVideoFile[] = []
1742 if (Array.isArray(this.VideoFiles)) {
1743 files = files.concat(this.VideoFiles)
1746 if (Array.isArray(this.VideoStreamingPlaylists)) {
1747 for (const p of this.VideoStreamingPlaylists) {
1748 if (Array.isArray(p.VideoFiles)) {
1749 files = files.concat(p.VideoFiles)
1757 probeMaxQualityFile () {
1758 const file = this.getMaxQualityFile()
1759 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1761 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1762 const probe = await ffprobePromise(originalFilePath)
1764 const { audioStream } = await getAudioStream(originalFilePath, probe)
1765 const hasAudio = await hasAudioStream(originalFilePath, probe)
1771 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
1776 getDescriptionAPIPath () {
1777 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1780 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1781 if (!this.VideoStreamingPlaylists) return undefined
1783 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1784 if (!playlist) return undefined
1786 return playlist.withVideo(this)
1789 setHLSPlaylist (playlist: MStreamingPlaylist) {
1790 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1792 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1793 this.VideoStreamingPlaylists = toAdd
1797 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1798 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1802 removeWebTorrentFile (videoFile: MVideoFile, isRedundancy = false) {
1803 const filePath = isRedundancy
1804 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1805 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1807 const promises: Promise<any>[] = [ remove(filePath) ]
1808 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1810 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1811 promises.push(removeWebTorrentObjectStorage(videoFile))
1814 return Promise.all(promises)
1817 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1818 const directoryPath = isRedundancy
1819 ? getHLSRedundancyDirectory(this)
1820 : getHLSDirectory(this)
1822 await remove(directoryPath)
1824 if (isRedundancy !== true) {
1825 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1826 streamingPlaylistWithFiles.Video = this
1828 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1829 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1832 // Remove physical files and torrents
1834 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1837 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1838 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1843 async removeStreamingPlaylistVideoFile (streamingPlaylist: MStreamingPlaylist, videoFile: MVideoFile) {
1844 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, videoFile.filename)
1845 await videoFile.removeTorrent()
1846 await remove(filePath)
1848 const resolutionFilename = getHlsResolutionPlaylistFilename(videoFile.filename)
1849 await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
1851 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1852 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
1853 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
1857 async removeStreamingPlaylistFile (streamingPlaylist: MStreamingPlaylist, filename: string) {
1858 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, filename)
1859 await remove(filePath)
1861 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1862 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
1867 if (this.isOwned()) return false
1869 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1872 hasPrivacyForFederation () {
1873 return isPrivacyForFederation(this.privacy)
1876 hasStateForFederation () {
1877 return isStateForFederation(this.state)
1880 isNewVideo (newPrivacy: VideoPrivacy) {
1881 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1884 setAsRefreshed (transaction?: Transaction) {
1885 return setAsUpdated({ sequelize: this.sequelize, table: 'video', id: this.id, transaction })
1888 // ---------------------------------------------------------------------------
1890 requiresAuth (options: {
1892 checkBlacklist: boolean
1894 const { urlParamId, checkBlacklist } = options
1896 if (this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL) {
1900 if (this.privacy === VideoPrivacy.UNLISTED) {
1901 if (urlParamId && !isUUIDValid(urlParamId)) return true
1906 if (checkBlacklist && this.VideoBlacklist) return true
1908 if (this.privacy !== VideoPrivacy.PUBLIC) {
1909 throw new Error(`Unknown video privacy ${this.privacy} to know if the video requires auth`)
1915 hasPrivateStaticPath () {
1916 return isVideoInPrivateDirectory(this.privacy)
1919 // ---------------------------------------------------------------------------
1921 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1922 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1924 this.state = newState
1926 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1927 this.publishedAt = new Date()
1930 await this.save({ transaction })
1933 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1934 if (!this.duration) throw new Error(`Cannot get bandwidth bits because video ${this.url} has duration of 0`)
1936 return Math.ceil((videoFile.size * 8) / this.duration)
1940 if (this.isOwned()) {
1942 WEBSERVER.URL + '/tracker/announce',
1943 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1947 return this.Trackers.map(t => t.url)