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, {
711 VideoLive: VideoLiveModel
713 @HasOne(() => VideoImportModel, {
720 VideoImport: VideoImportModel
722 @HasMany(() => VideoCaptionModel, {
729 ['separate' as any]: true
731 VideoCaptions: VideoCaptionModel[]
733 @HasOne(() => VideoJobInfoModel, {
740 VideoJobInfo: VideoJobInfoModel
743 static async sendDelete (instance: MVideoAccountLight, options) {
744 if (!instance.isOwned()) return undefined
746 // Lazy load channels
747 if (!instance.VideoChannel) {
748 instance.VideoChannel = await instance.$get('VideoChannel', {
753 transaction: options.transaction
754 }) as MChannelAccountDefault
757 return sendDeleteVideo(instance, options.transaction)
761 static async removeFiles (instance: VideoModel, options) {
762 const tasks: Promise<any>[] = []
764 logger.info('Removing files of video %s.', instance.url)
766 if (instance.isOwned()) {
767 if (!Array.isArray(instance.VideoFiles)) {
768 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
771 // Remove physical files and torrents
772 instance.VideoFiles.forEach(file => {
773 tasks.push(instance.removeWebTorrentFile(file))
776 // Remove playlists file
777 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
778 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
781 for (const p of instance.VideoStreamingPlaylists) {
782 tasks.push(instance.removeStreamingPlaylistFiles(p))
786 // Do not wait video deletion because we could be in a transaction
788 .then(() => logger.info('Removed files of video %s.', instance.url))
789 .catch(err => logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }))
795 static stopLiveIfNeeded (instance: VideoModel) {
796 if (!instance.isLive) return
798 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
800 LiveManager.Instance.stopSessionOf(instance.id, null)
804 static invalidateCache (instance: VideoModel) {
805 ModelCache.Instance.invalidateCache('video', instance.id)
809 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
810 const tasks: Promise<any>[] = []
812 if (!Array.isArray(instance.VideoAbuses)) {
813 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
815 if (instance.VideoAbuses.length === 0) return undefined
818 logger.info('Saving video abuses details of video %s.', instance.url)
820 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
821 const details = instance.toFormattedDetailsJSON()
823 for (const abuse of instance.VideoAbuses) {
824 abuse.deletedVideo = details
825 tasks.push(abuse.save({ transaction: options.transaction }))
828 await Promise.all(tasks)
831 static listLocalIds (): Promise<number[]> {
833 attributes: [ 'id' ],
840 return VideoModel.findAll(query)
841 .then(rows => rows.map(r => r.id))
844 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
845 function getRawQuery (select: string) {
846 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
847 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
848 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
849 'WHERE "Account"."actorId" = ' + actorId
850 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
851 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
852 'WHERE "VideoShare"."actorId" = ' + actorId
854 return `(${queryVideo}) UNION (${queryVideoShare})`
857 const rawQuery = getRawQuery('"Video"."id"')
858 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
864 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
867 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
869 [Op.or]: getPrivaciesForFederation()
873 attributes: [ 'filename', 'language', 'fileUrl' ],
874 model: VideoCaptionModel.unscoped(),
878 attributes: [ 'id', 'url' ],
879 model: VideoShareModel.unscoped(),
881 // We only want videos shared by this actor
896 attributes: [ 'id', 'url' ],
897 model: ActorModel.unscoped()
902 model: VideoChannelModel.unscoped(),
906 attributes: [ 'name' ],
907 model: AccountModel.unscoped(),
911 attributes: [ 'id', 'url', 'followersUrl' ],
912 model: ActorModel.unscoped(),
918 attributes: [ 'id', 'url', 'followersUrl' ],
919 model: ActorModel.unscoped(),
925 model: VideoStreamingPlaylistModel.unscoped(),
929 model: VideoFileModel,
934 VideoLiveModel.unscoped(),
940 return Bluebird.all([
941 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
942 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
943 ]).then(([ rows, totals ]) => {
944 // totals: totalVideos + totalVideoShares
946 let totalVideoShares = 0
947 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
948 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
950 const total = totalVideos + totalVideoShares
958 static async listPublishedLiveUUIDs () {
960 attributes: [ 'uuid' ],
964 state: VideoState.PUBLISHED
968 const result = await VideoModel.findAll(options)
970 return result.map(v => v.uuid)
973 static listUserVideosForApi (options: {
983 const { accountId, channelId, start, count, sort, search, isLive } = options
985 function buildBaseQuery (forCount: boolean): FindOptions {
986 const where: WhereOptions = {}
990 [Op.iLike]: '%' + search + '%'
994 if (exists(isLive)) {
995 where.isLive = isLive
998 const channelWhere = channelId
1006 order: getVideoSort(sort),
1010 ? VideoChannelModel.unscoped()
1011 : VideoChannelModel,
1013 where: channelWhere,
1017 ? AccountModel.unscoped()
1032 const countQuery = buildBaseQuery(true)
1033 const findQuery = buildBaseQuery(false)
1035 const findScopes: (string | ScopeOptions)[] = [
1036 ScopeNames.WITH_SCHEDULED_UPDATE,
1037 ScopeNames.WITH_BLACKLISTED,
1038 ScopeNames.WITH_THUMBNAILS
1041 return Promise.all([
1042 VideoModel.count(countQuery),
1043 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1044 ]).then(([ count, rows ]) => {
1052 static async listForApi (options: {
1060 include?: VideoInclude
1062 hasFiles?: boolean // default false
1063 hasWebtorrentFiles?: boolean
1064 hasHLSFiles?: boolean
1066 categoryOneOf?: number[]
1067 licenceOneOf?: number[]
1068 languageOneOf?: string[]
1069 tagsOneOf?: string[]
1070 tagsAllOf?: string[]
1071 privacyOneOf?: VideoPrivacy[]
1074 videoChannelId?: number
1076 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1078 videoPlaylistId?: number
1080 trendingDays?: number
1082 user?: MUserAccountId
1083 historyOfUser?: MUserId
1085 countVideos?: boolean
1089 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1090 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1092 const trendingDays = options.sort.endsWith('trending')
1093 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1096 let trendingAlgorithm: string
1097 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1098 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1100 const serverActor = await getServerActor()
1102 const queryOptions = {
1117 'displayOnlyForFollower',
1125 'hasWebtorrentFiles',
1129 serverAccountIdForBlock: serverActor.Account.id,
1134 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1137 static async searchAndPopulateAccountAndServer (options: {
1145 include?: VideoInclude
1147 categoryOneOf?: number[]
1148 licenceOneOf?: number[]
1149 languageOneOf?: string[]
1150 tagsOneOf?: string[]
1151 tagsAllOf?: string[]
1152 privacyOneOf?: VideoPrivacy[]
1154 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1156 user?: MUserAccountId
1158 hasWebtorrentFiles?: boolean
1159 hasHLSFiles?: boolean
1164 startDate?: string // ISO 8601
1165 endDate?: string // ISO 8601
1166 originallyPublishedStartDate?: string
1167 originallyPublishedEndDate?: string
1169 durationMin?: number // seconds
1170 durationMax?: number // seconds
1173 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1174 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1176 const serverActor = await getServerActor()
1178 const queryOptions = {
1197 'originallyPublishedStartDate',
1198 'originallyPublishedEndDate',
1202 'hasWebtorrentFiles',
1205 'displayOnlyForFollower'
1207 serverAccountIdForBlock: serverActor.Account.id
1210 return VideoModel.getAvailableForApi(queryOptions)
1213 static countLives (options: {
1215 mode: 'published' | 'not-ended'
1219 remote: options.remote,
1221 state: options.mode === 'not-ended'
1222 ? { [Op.ne]: VideoState.LIVE_ENDED }
1223 : { [Op.eq]: VideoState.PUBLISHED }
1227 return VideoModel.count(query)
1230 static countVideosUploadedByUserSince (userId: number, since: Date) {
1234 model: VideoChannelModel.unscoped(),
1238 model: AccountModel.unscoped(),
1242 model: UserModel.unscoped(),
1260 return VideoModel.unscoped().count(options)
1263 static countLivesOfAccount (accountId: number) {
1269 [Op.ne]: VideoState.LIVE_ENDED
1275 model: VideoChannelModel.unscoped(),
1283 return VideoModel.count(options)
1286 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1287 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1289 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1292 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1293 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1295 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1298 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1301 where: buildWhereIdOrUUID(id),
1305 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1308 return ModelCache.Instance.doCache({
1309 cacheType: 'load-video-immutable-id',
1316 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1318 const query: FindOptions = {
1325 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1328 return ModelCache.Instance.doCache({
1329 cacheType: 'load-video-immutable-url',
1336 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1337 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1339 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1342 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1343 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1345 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1348 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1349 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1351 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1354 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1355 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1357 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1360 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1361 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1363 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
1366 static loadForGetAPI (parameters: {
1368 transaction?: Transaction
1370 }): Promise<MVideoDetails> {
1371 const { id, transaction, userId } = parameters
1372 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1374 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1377 static async getStats () {
1378 const serverActor = await getServerActor()
1380 let totalLocalVideoViews = await VideoModel.sum('views', {
1386 // Sequelize could return null...
1387 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1389 const baseOptions = {
1392 sort: '-publishedAt',
1394 displayOnlyForFollower: {
1395 actorId: serverActor.id,
1400 const { total: totalLocalVideos } = await VideoModel.listForApi({
1406 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1410 totalLocalVideoViews,
1415 static incrementViews (id: number, views: number) {
1416 return VideoModel.increment('views', {
1424 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1425 const field = type === 'like'
1429 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1431 return AccountVideoRateModel.sequelize.query(rawQuery, {
1433 replacements: { videoId, rateType: type, count },
1434 type: QueryTypes.UPDATE
1438 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
1439 const field = type === 'like'
1443 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1445 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1447 'WHERE "video"."id" = :videoId'
1449 return AccountVideoRateModel.sequelize.query(rawQuery, {
1451 replacements: { videoId, rateType: type },
1452 type: QueryTypes.UPDATE
1456 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1457 // Instances only share videos
1458 const query = 'SELECT 1 FROM "videoShare" ' +
1459 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1460 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1462 'SELECT 1 FROM "video" ' +
1463 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
1464 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
1465 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "account"."actorId" ' +
1466 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "video"."id" = $videoId ' +
1470 type: QueryTypes.SELECT as QueryTypes.SELECT,
1471 bind: { followerActorId, videoId },
1475 return VideoModel.sequelize.query(query, options)
1476 .then(results => results.length === 1)
1479 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1482 channelId: ofChannel.id
1487 return VideoModel.update({ support: ofChannel.support }, options)
1490 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1492 attributes: [ 'id' ],
1494 channelId: videoChannel.id
1498 return VideoModel.findAll(query)
1499 .then(videos => videos.map(v => v.id))
1502 // threshold corresponds to how many video the field should have to be returned
1503 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1504 const serverActor = await getServerActor()
1506 const queryOptions: BuildVideosListQueryOptions = {
1507 attributes: [ `"${field}"` ],
1508 group: `GROUP BY "${field}"`,
1509 having: `HAVING COUNT("${field}") >= ${threshold}`,
1513 serverAccountIdForBlock: serverActor.Account.id,
1514 displayOnlyForFollower: {
1515 actorId: serverActor.id,
1520 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1522 return queryBuilder.queryVideoIds(queryOptions)
1523 .then(rows => rows.map(r => r[field]))
1526 static buildTrendingQuery (trendingDays: number) {
1530 model: VideoViewModel,
1535 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1541 private static async getAvailableForApi (
1542 options: BuildVideosListQueryOptions,
1544 ): Promise<ResultList<VideoModel>> {
1545 const span = tracer.startSpan('peertube.VideoModel.getAvailableForApi')
1547 function getCount () {
1548 if (countVideos !== true) return Promise.resolve(undefined)
1550 const countOptions = Object.assign({}, options, { isCount: true })
1551 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1553 return queryBuilder.countVideoIds(countOptions)
1556 function getModels () {
1557 if (options.count === 0) return Promise.resolve([])
1559 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1561 return queryBuilder.queryVideos(options)
1564 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1574 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1575 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1576 throw new Error('Try to filter all-local but user cannot see all videos')
1580 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1581 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1582 throw new Error('Try to choose video privacies but user cannot see all videos')
1586 private static isPrivateInclude (include: VideoInclude) {
1587 return include & VideoInclude.BLACKLISTED ||
1588 include & VideoInclude.BLOCKED_OWNER ||
1589 include & VideoInclude.NOT_PUBLISHED_STATE
1593 return !!this.VideoBlacklist
1597 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1600 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1601 const files = this.getAllFiles()
1602 const file = fun(files, file => file.resolution)
1603 if (!file) return undefined
1606 return Object.assign(file, { Video: this })
1609 if (file.videoStreamingPlaylistId) {
1610 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1612 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1615 throw new Error('File is not associated to a video of a playlist')
1618 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1619 return this.getQualityFileBy(maxBy)
1622 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1623 return this.getQualityFileBy(minBy)
1626 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1627 if (Array.isArray(this.VideoFiles) === false) return undefined
1629 const file = this.VideoFiles.find(f => f.resolution === resolution)
1630 if (!file) return undefined
1632 return Object.assign(file, { Video: this })
1635 hasWebTorrentFiles () {
1636 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1639 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1640 thumbnail.videoId = this.id
1642 const savedThumbnail = await thumbnail.save({ transaction })
1644 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1646 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1647 this.Thumbnails.push(savedThumbnail)
1651 if (Array.isArray(this.Thumbnails) === false) return undefined
1653 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1657 return !!this.getPreview()
1661 if (Array.isArray(this.Thumbnails) === false) return undefined
1663 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1667 return this.remote === false
1670 getWatchStaticPath () {
1671 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1674 getEmbedStaticPath () {
1675 return buildVideoEmbedPath(this)
1678 getMiniatureStaticPath () {
1679 const thumbnail = this.getMiniature()
1680 if (!thumbnail) return null
1682 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1685 getPreviewStaticPath () {
1686 const preview = this.getPreview()
1687 if (!preview) return null
1689 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1690 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1693 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1694 return videoModelToFormattedJSON(this, options)
1697 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1698 return videoModelToFormattedDetailsJSON(this)
1701 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1702 let files: VideoFile[] = []
1704 if (Array.isArray(this.VideoFiles)) {
1705 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, { includeMagnet })
1706 files = files.concat(result)
1709 for (const p of (this.VideoStreamingPlaylists || [])) {
1710 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, { includeMagnet })
1711 files = files.concat(result)
1717 toActivityPubObject (this: MVideoAP): Promise<VideoObject> {
1718 return Hooks.wrapObject(
1719 videoModelToActivityPubObject(this),
1720 'filter:activity-pub.video.jsonld.build.result',
1725 getTruncatedDescription () {
1726 if (!this.description) return null
1728 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1729 return peertubeTruncate(this.description, { length: maxLength })
1733 let files: MVideoFile[] = []
1735 if (Array.isArray(this.VideoFiles)) {
1736 files = files.concat(this.VideoFiles)
1739 if (Array.isArray(this.VideoStreamingPlaylists)) {
1740 for (const p of this.VideoStreamingPlaylists) {
1741 if (Array.isArray(p.VideoFiles)) {
1742 files = files.concat(p.VideoFiles)
1750 probeMaxQualityFile () {
1751 const file = this.getMaxQualityFile()
1752 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1754 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1755 const probe = await ffprobePromise(originalFilePath)
1757 const { audioStream } = await getAudioStream(originalFilePath, probe)
1758 const hasAudio = await hasAudioStream(originalFilePath, probe)
1764 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
1769 getDescriptionAPIPath () {
1770 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1773 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1774 if (!this.VideoStreamingPlaylists) return undefined
1776 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1777 if (!playlist) return undefined
1779 return playlist.withVideo(this)
1782 setHLSPlaylist (playlist: MStreamingPlaylist) {
1783 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1785 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1786 this.VideoStreamingPlaylists = toAdd
1790 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1791 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1795 removeWebTorrentFile (videoFile: MVideoFile, isRedundancy = false) {
1796 const filePath = isRedundancy
1797 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1798 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1800 const promises: Promise<any>[] = [ remove(filePath) ]
1801 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1803 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1804 promises.push(removeWebTorrentObjectStorage(videoFile))
1807 return Promise.all(promises)
1810 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1811 const directoryPath = isRedundancy
1812 ? getHLSRedundancyDirectory(this)
1813 : getHLSDirectory(this)
1815 await remove(directoryPath)
1817 if (isRedundancy !== true) {
1818 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1819 streamingPlaylistWithFiles.Video = this
1821 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1822 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1825 // Remove physical files and torrents
1827 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1830 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1831 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1836 async removeStreamingPlaylistVideoFile (streamingPlaylist: MStreamingPlaylist, videoFile: MVideoFile) {
1837 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, videoFile.filename)
1838 await videoFile.removeTorrent()
1839 await remove(filePath)
1841 const resolutionFilename = getHlsResolutionPlaylistFilename(videoFile.filename)
1842 await remove(VideoPathManager.Instance.getFSHLSOutputPath(this, resolutionFilename))
1844 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1845 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), videoFile.filename)
1846 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), resolutionFilename)
1850 async removeStreamingPlaylistFile (streamingPlaylist: MStreamingPlaylist, filename: string) {
1851 const filePath = VideoPathManager.Instance.getFSHLSOutputPath(this, filename)
1852 await remove(filePath)
1854 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1855 await removeHLSFileObjectStorageByFilename(streamingPlaylist.withVideo(this), filename)
1860 if (this.isOwned()) return false
1862 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1865 hasPrivacyForFederation () {
1866 return isPrivacyForFederation(this.privacy)
1869 hasStateForFederation () {
1870 return isStateForFederation(this.state)
1873 isNewVideo (newPrivacy: VideoPrivacy) {
1874 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1877 setAsRefreshed (transaction?: Transaction) {
1878 return setAsUpdated({ sequelize: this.sequelize, table: 'video', id: this.id, transaction })
1881 // ---------------------------------------------------------------------------
1883 requiresAuth (options: {
1885 checkBlacklist: boolean
1887 const { urlParamId, checkBlacklist } = options
1889 if (this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL) {
1893 if (this.privacy === VideoPrivacy.UNLISTED) {
1894 if (urlParamId && !isUUIDValid(urlParamId)) return true
1899 if (checkBlacklist && this.VideoBlacklist) return true
1901 if (this.privacy !== VideoPrivacy.PUBLIC) {
1902 throw new Error(`Unknown video privacy ${this.privacy} to know if the video requires auth`)
1908 hasPrivateStaticPath () {
1909 return isVideoInPrivateDirectory(this.privacy)
1912 // ---------------------------------------------------------------------------
1914 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1915 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1917 this.state = newState
1919 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1920 this.publishedAt = new Date()
1923 await this.save({ transaction })
1926 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1927 if (!this.duration) throw new Error(`Cannot get bandwidth bits because video ${this.url} has duration of 0`)
1929 return Math.ceil((videoFile.size * 8) / this.duration)
1933 if (this.isOwned()) {
1935 WEBSERVER.URL + '/tracker/announce',
1936 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1940 return this.Trackers.map(t => t.url)