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 { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
29 import { LiveManager } from '@server/lib/live/live-manager'
30 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
31 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
32 import { VideoPathManager } from '@server/lib/video-path-manager'
33 import { getServerActor } from '@server/models/application/application'
34 import { ModelCache } from '@server/models/model-cache'
35 import { buildVideoEmbedPath, buildVideoWatchPath, pick, uuidToShort } from '@shared/core-utils'
49 VideoStreamingPlaylistType
50 } from '@shared/models'
51 import { AttributesOnly } from '@shared/typescript-utils'
52 import { peertubeTruncate } from '../../helpers/core-utils'
53 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
54 import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
56 isVideoDescriptionValid,
62 } from '../../helpers/custom-validators/videos'
63 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
64 import { logger } from '../../helpers/logger'
65 import { CONFIG } from '../../initializers/config'
66 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 MChannelAccountDefault,
73 MStreamingPlaylistFilesVideo,
78 MVideoAccountLightBlacklistAllFiles,
83 MVideoFormattableDetails,
89 MVideoThumbnailBlacklist,
92 } from '../../types/models'
93 import { MThumbnail } from '../../types/models/video/thumbnail'
94 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
95 import { VideoAbuseModel } from '../abuse/video-abuse'
96 import { AccountModel } from '../account/account'
97 import { AccountVideoRateModel } from '../account/account-video-rate'
98 import { ActorModel } from '../actor/actor'
99 import { ActorImageModel } from '../actor/actor-image'
100 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
101 import { ServerModel } from '../server/server'
102 import { TrackerModel } from '../server/tracker'
103 import { VideoTrackerModel } from '../server/video-tracker'
104 import { setAsUpdated } from '../shared'
105 import { UserModel } from '../user/user'
106 import { UserVideoHistoryModel } from '../user/user-video-history'
107 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
109 videoFilesModelToFormattedJSON,
110 VideoFormattingJSONOptions,
111 videoModelToActivityPubObject,
112 videoModelToFormattedDetailsJSON,
113 videoModelToFormattedJSON
114 } from './formatter/video-format-utils'
115 import { ScheduleVideoUpdateModel } from './schedule-video-update'
116 import { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
117 import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
118 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
119 import { TagModel } from './tag'
120 import { ThumbnailModel } from './thumbnail'
121 import { VideoBlacklistModel } from './video-blacklist'
122 import { VideoCaptionModel } from './video-caption'
123 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
124 import { VideoCommentModel } from './video-comment'
125 import { VideoFileModel } from './video-file'
126 import { VideoImportModel } from './video-import'
127 import { VideoJobInfoModel } from './video-job-info'
128 import { VideoLiveModel } from './video-live'
129 import { VideoPlaylistElementModel } from './video-playlist-element'
130 import { VideoShareModel } from './video-share'
131 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
132 import { VideoTagModel } from './video-tag'
133 import { VideoViewModel } from './video-view'
135 export enum ScopeNames {
137 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
138 WITH_TAGS = 'WITH_TAGS',
139 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
140 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
141 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
142 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
143 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
144 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
145 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
148 export type ForAPIOptions = {
151 videoPlaylistId?: number
153 withAccountBlockerIds?: number[]
157 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
158 attributes: [ 'id', 'url', 'uuid', 'remote' ]
160 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
161 const include: Includeable[] = [
163 model: VideoChannelModel.scope({
165 VideoChannelScopeNames.SUMMARY, {
167 withAccountBlockerIds: options.withAccountBlockerIds
174 attributes: [ 'type', 'filename' ],
175 model: ThumbnailModel,
180 const query: FindOptions = {}
190 if (options.videoPlaylistId) {
192 model: VideoPlaylistElementModel.unscoped(),
195 videoPlaylistId: options.videoPlaylistId
200 query.include = include
204 [ScopeNames.WITH_THUMBNAILS]: {
207 model: ThumbnailModel,
212 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
215 model: VideoChannelModel.unscoped(),
220 exclude: [ 'privateKey', 'publicKey' ]
222 model: ActorModel.unscoped(),
226 attributes: [ 'host' ],
227 model: ServerModel.unscoped(),
231 model: ActorImageModel.unscoped(),
238 model: AccountModel.unscoped(),
242 model: ActorModel.unscoped(),
244 exclude: [ 'privateKey', 'publicKey' ]
249 attributes: [ 'host' ],
250 model: ServerModel.unscoped(),
254 model: ActorImageModel.unscoped(),
266 [ScopeNames.WITH_TAGS]: {
267 include: [ TagModel ]
269 [ScopeNames.WITH_BLACKLISTED]: {
272 attributes: [ 'id', 'reason', 'unfederated' ],
273 model: VideoBlacklistModel,
278 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
279 let subInclude: any[] = []
281 if (withRedundancies === true) {
284 attributes: [ 'fileUrl' ],
285 model: VideoRedundancyModel.unscoped(),
294 model: VideoFileModel,
302 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
303 const subInclude: IncludeOptions[] = [
305 model: VideoFileModel,
310 if (withRedundancies === true) {
312 attributes: [ 'fileUrl' ],
313 model: VideoRedundancyModel.unscoped(),
321 model: VideoStreamingPlaylistModel.unscoped(),
329 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
332 model: ScheduleVideoUpdateModel.unscoped(),
337 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
341 attributes: [ 'currentTime' ],
342 model: UserVideoHistoryModel.unscoped(),
355 buildTrigramSearchIndex('video_name_trigram', 'name'),
357 { fields: [ 'createdAt' ] },
360 { name: 'publishedAt', order: 'DESC' },
361 { name: 'id', order: 'ASC' }
364 { fields: [ 'duration' ] },
367 { name: 'views', order: 'DESC' },
368 { name: 'id', order: 'ASC' }
371 { fields: [ 'channelId' ] },
373 fields: [ 'originallyPublishedAt' ],
375 originallyPublishedAt: {
381 fields: [ 'category' ], // We don't care videos with an unknown category
389 fields: [ 'licence' ], // We don't care videos with an unknown licence
397 fields: [ 'language' ], // We don't care videos with an unknown language
405 fields: [ 'nsfw' ], // Most of the videos are not NSFW
411 fields: [ 'remote' ], // Only index local videos
426 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
429 @Default(DataType.UUIDV4)
431 @Column(DataType.UUID)
435 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
451 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
455 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
457 privacy: VideoPrivacy
460 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
466 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
467 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
472 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
473 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
477 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
512 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
513 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
518 commentsEnabled: boolean
522 downloadEnabled: boolean
526 waitTranscoding: boolean
530 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
541 @Default(DataType.NOW)
548 originallyPublishedAt: Date
550 @ForeignKey(() => VideoChannelModel)
554 @BelongsTo(() => VideoChannelModel, {
560 VideoChannel: VideoChannelModel
562 @BelongsToMany(() => TagModel, {
563 foreignKey: 'videoId',
564 through: () => VideoTagModel,
569 @BelongsToMany(() => TrackerModel, {
570 foreignKey: 'videoId',
571 through: () => VideoTrackerModel,
574 Trackers: TrackerModel[]
576 @HasMany(() => ThumbnailModel, {
584 Thumbnails: ThumbnailModel[]
586 @HasMany(() => VideoPlaylistElementModel, {
593 VideoPlaylistElements: VideoPlaylistElementModel[]
595 @HasMany(() => VideoAbuseModel, {
602 VideoAbuses: VideoAbuseModel[]
604 @HasMany(() => VideoFileModel, {
612 VideoFiles: VideoFileModel[]
614 @HasMany(() => VideoStreamingPlaylistModel, {
622 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
624 @HasMany(() => VideoShareModel, {
631 VideoShares: VideoShareModel[]
633 @HasMany(() => AccountVideoRateModel, {
640 AccountVideoRates: AccountVideoRateModel[]
642 @HasMany(() => VideoCommentModel, {
650 VideoComments: VideoCommentModel[]
652 @HasMany(() => VideoViewModel, {
659 VideoViews: VideoViewModel[]
661 @HasMany(() => UserVideoHistoryModel, {
668 UserVideoHistories: UserVideoHistoryModel[]
670 @HasOne(() => ScheduleVideoUpdateModel, {
677 ScheduleVideoUpdate: ScheduleVideoUpdateModel
679 @HasOne(() => VideoBlacklistModel, {
686 VideoBlacklist: VideoBlacklistModel
688 @HasOne(() => VideoLiveModel, {
695 VideoLive: VideoLiveModel
697 @HasOne(() => VideoImportModel, {
704 VideoImport: VideoImportModel
706 @HasMany(() => VideoCaptionModel, {
713 ['separate' as any]: true
715 VideoCaptions: VideoCaptionModel[]
717 @HasOne(() => VideoJobInfoModel, {
724 VideoJobInfo: VideoJobInfoModel
727 static async sendDelete (instance: MVideoAccountLight, options) {
728 if (!instance.isOwned()) return undefined
730 // Lazy load channels
731 if (!instance.VideoChannel) {
732 instance.VideoChannel = await instance.$get('VideoChannel', {
737 transaction: options.transaction
738 }) as MChannelAccountDefault
741 return sendDeleteVideo(instance, options.transaction)
745 static async removeFiles (instance: VideoModel, options) {
746 const tasks: Promise<any>[] = []
748 logger.info('Removing files of video %s.', instance.url)
750 if (instance.isOwned()) {
751 if (!Array.isArray(instance.VideoFiles)) {
752 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
755 // Remove physical files and torrents
756 instance.VideoFiles.forEach(file => {
757 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
760 // Remove playlists file
761 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
762 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
765 for (const p of instance.VideoStreamingPlaylists) {
766 tasks.push(instance.removeStreamingPlaylistFiles(p))
770 // Do not wait video deletion because we could be in a transaction
773 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
780 static stopLiveIfNeeded (instance: VideoModel) {
781 if (!instance.isLive) return
783 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
785 LiveManager.Instance.stopSessionOf(instance.id)
789 static invalidateCache (instance: VideoModel) {
790 ModelCache.Instance.invalidateCache('video', instance.id)
794 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
795 const tasks: Promise<any>[] = []
797 if (!Array.isArray(instance.VideoAbuses)) {
798 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
800 if (instance.VideoAbuses.length === 0) return undefined
803 logger.info('Saving video abuses details of video %s.', instance.url)
805 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
806 const details = instance.toFormattedDetailsJSON()
808 for (const abuse of instance.VideoAbuses) {
809 abuse.deletedVideo = details
810 tasks.push(abuse.save({ transaction: options.transaction }))
813 await Promise.all(tasks)
816 static listLocalIds (): Promise<number[]> {
818 attributes: [ 'id' ],
825 return VideoModel.findAll(query)
826 .then(rows => rows.map(r => r.id))
829 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
830 function getRawQuery (select: string) {
831 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
832 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
833 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
834 'WHERE "Account"."actorId" = ' + actorId
835 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
836 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
837 'WHERE "VideoShare"."actorId" = ' + actorId
839 return `(${queryVideo}) UNION (${queryVideoShare})`
842 const rawQuery = getRawQuery('"Video"."id"')
843 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
849 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
852 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
854 [Op.or]: getPrivaciesForFederation()
858 attributes: [ 'filename', 'language', 'fileUrl' ],
859 model: VideoCaptionModel.unscoped(),
863 attributes: [ 'id', 'url' ],
864 model: VideoShareModel.unscoped(),
866 // We only want videos shared by this actor
881 attributes: [ 'id', 'url' ],
882 model: ActorModel.unscoped()
887 model: VideoChannelModel.unscoped(),
891 attributes: [ 'name' ],
892 model: AccountModel.unscoped(),
896 attributes: [ 'id', 'url', 'followersUrl' ],
897 model: ActorModel.unscoped(),
903 attributes: [ 'id', 'url', 'followersUrl' ],
904 model: ActorModel.unscoped(),
910 model: VideoStreamingPlaylistModel.unscoped(),
914 model: VideoFileModel,
919 VideoLiveModel.unscoped(),
925 return Bluebird.all([
926 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
927 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
928 ]).then(([ rows, totals ]) => {
929 // totals: totalVideos + totalVideoShares
931 let totalVideoShares = 0
932 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
933 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
935 const total = totalVideos + totalVideoShares
943 static async listPublishedLiveUUIDs () {
945 attributes: [ 'uuid' ],
949 state: VideoState.PUBLISHED
953 const result = await VideoModel.findAll(options)
955 return result.map(v => v.uuid)
958 static listUserVideosForApi (options: {
968 const { accountId, channelId, start, count, sort, search, isLive } = options
970 function buildBaseQuery (): FindOptions {
971 const where: WhereOptions = {}
975 [Op.iLike]: '%' + search + '%'
979 if (exists(isLive)) {
980 where.isLive = isLive
983 const channelWhere = channelId
991 order: getVideoSort(sort),
994 model: VideoChannelModel,
1013 const countQuery = buildBaseQuery()
1014 const findQuery = buildBaseQuery()
1016 const findScopes: (string | ScopeOptions)[] = [
1017 ScopeNames.WITH_SCHEDULED_UPDATE,
1018 ScopeNames.WITH_BLACKLISTED,
1019 ScopeNames.WITH_THUMBNAILS
1022 return Promise.all([
1023 VideoModel.count(countQuery),
1024 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1025 ]).then(([ count, rows ]) => {
1033 static async listForApi (options: {
1041 include?: VideoInclude
1043 hasFiles?: boolean // default false
1044 hasWebtorrentFiles?: boolean
1045 hasHLSFiles?: boolean
1047 categoryOneOf?: number[]
1048 licenceOneOf?: number[]
1049 languageOneOf?: string[]
1050 tagsOneOf?: string[]
1051 tagsAllOf?: string[]
1052 privacyOneOf?: VideoPrivacy[]
1055 videoChannelId?: number
1057 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1059 videoPlaylistId?: number
1061 trendingDays?: number
1063 user?: MUserAccountId
1064 historyOfUser?: MUserId
1066 countVideos?: boolean
1070 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1071 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1073 const trendingDays = options.sort.endsWith('trending')
1074 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1077 let trendingAlgorithm: string
1078 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1079 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1081 const serverActor = await getServerActor()
1083 const queryOptions = {
1098 'displayOnlyForFollower',
1106 'hasWebtorrentFiles',
1110 serverAccountIdForBlock: serverActor.Account.id,
1115 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1118 static async searchAndPopulateAccountAndServer (options: {
1126 include?: VideoInclude
1128 categoryOneOf?: number[]
1129 licenceOneOf?: number[]
1130 languageOneOf?: string[]
1131 tagsOneOf?: string[]
1132 tagsAllOf?: string[]
1133 privacyOneOf?: VideoPrivacy[]
1135 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1137 user?: MUserAccountId
1139 hasWebtorrentFiles?: boolean
1140 hasHLSFiles?: boolean
1145 startDate?: string // ISO 8601
1146 endDate?: string // ISO 8601
1147 originallyPublishedStartDate?: string
1148 originallyPublishedEndDate?: string
1150 durationMin?: number // seconds
1151 durationMax?: number // seconds
1154 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1155 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1157 const serverActor = await getServerActor()
1159 const queryOptions = {
1178 'originallyPublishedStartDate',
1179 'originallyPublishedEndDate',
1183 'hasWebtorrentFiles',
1186 'displayOnlyForFollower'
1188 serverAccountIdForBlock: serverActor.Account.id
1191 return VideoModel.getAvailableForApi(queryOptions)
1194 static countLocalLives () {
1200 [Op.ne]: VideoState.LIVE_ENDED
1205 return VideoModel.count(options)
1208 static countVideosUploadedByUserSince (userId: number, since: Date) {
1212 model: VideoChannelModel.unscoped(),
1216 model: AccountModel.unscoped(),
1220 model: UserModel.unscoped(),
1238 return VideoModel.unscoped().count(options)
1241 static countLivesOfAccount (accountId: number) {
1247 [Op.ne]: VideoState.LIVE_ENDED
1253 model: VideoChannelModel.unscoped(),
1261 return VideoModel.count(options)
1264 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1265 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1267 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1270 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1271 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1273 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1276 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1279 where: buildWhereIdOrUUID(id),
1283 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1286 return ModelCache.Instance.doCache({
1287 cacheType: 'load-video-immutable-id',
1294 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1296 const query: FindOptions = {
1303 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1306 return ModelCache.Instance.doCache({
1307 cacheType: 'load-video-immutable-url',
1314 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1315 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1317 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1320 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1321 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1323 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1326 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1327 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1329 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1332 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1333 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1335 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1338 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1339 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1341 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1344 static loadForGetAPI (parameters: {
1346 transaction?: Transaction
1348 }): Promise<MVideoDetails> {
1349 const { id, transaction, userId } = parameters
1350 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1352 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1355 static async getStats () {
1356 const totalLocalVideos = await VideoModel.count({
1362 let totalLocalVideoViews = await VideoModel.sum('views', {
1368 // Sequelize could return null...
1369 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1371 const serverActor = await getServerActor()
1373 const { total: totalVideos } = await VideoModel.listForApi({
1376 sort: '-publishedAt',
1377 nsfw: buildNSFWFilter(),
1378 displayOnlyForFollower: {
1379 actorId: serverActor.id,
1386 totalLocalVideoViews,
1391 static incrementViews (id: number, views: number) {
1392 return VideoModel.increment('views', {
1400 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1401 const field = type === 'like'
1405 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1407 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1409 'WHERE "video"."id" = :videoId'
1411 return AccountVideoRateModel.sequelize.query(rawQuery, {
1413 replacements: { videoId, rateType: type },
1414 type: QueryTypes.UPDATE
1418 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1419 // Instances only share videos
1420 const query = 'SELECT 1 FROM "videoShare" ' +
1421 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1422 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1426 type: QueryTypes.SELECT as QueryTypes.SELECT,
1427 bind: { followerActorId, videoId },
1431 return VideoModel.sequelize.query(query, options)
1432 .then(results => results.length === 1)
1435 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1438 channelId: ofChannel.id
1443 return VideoModel.update({ support: ofChannel.support }, options)
1446 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1448 attributes: [ 'id' ],
1450 channelId: videoChannel.id
1454 return VideoModel.findAll(query)
1455 .then(videos => videos.map(v => v.id))
1458 // threshold corresponds to how many video the field should have to be returned
1459 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1460 const serverActor = await getServerActor()
1462 const queryOptions: BuildVideosListQueryOptions = {
1463 attributes: [ `"${field}"` ],
1464 group: `GROUP BY "${field}"`,
1465 having: `HAVING COUNT("${field}") >= ${threshold}`,
1469 serverAccountIdForBlock: serverActor.Account.id,
1470 displayOnlyForFollower: {
1471 actorId: serverActor.id,
1476 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1478 return queryBuilder.queryVideoIds(queryOptions)
1479 .then(rows => rows.map(r => r[field]))
1482 static buildTrendingQuery (trendingDays: number) {
1486 model: VideoViewModel,
1490 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1496 private static async getAvailableForApi (
1497 options: BuildVideosListQueryOptions,
1499 ): Promise<ResultList<VideoModel>> {
1500 function getCount () {
1501 if (countVideos !== true) return Promise.resolve(undefined)
1503 const countOptions = Object.assign({}, options, { isCount: true })
1504 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1506 return queryBuilder.countVideoIds(countOptions)
1509 function getModels () {
1510 if (options.count === 0) return Promise.resolve([])
1512 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1514 return queryBuilder.queryVideos(options)
1517 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1525 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1526 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1527 throw new Error('Try to filter all-local but user cannot see all videos')
1531 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1532 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1533 throw new Error('Try to choose video privacies but user cannot see all videos')
1537 private static isPrivateInclude (include: VideoInclude) {
1538 return include & VideoInclude.BLACKLISTED ||
1539 include & VideoInclude.BLOCKED_OWNER ||
1540 include & VideoInclude.NOT_PUBLISHED_STATE
1544 return !!this.VideoBlacklist
1548 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1551 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1552 // We first transcode to WebTorrent format, so try this array first
1553 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1554 const file = fun(this.VideoFiles, file => file.resolution)
1556 return Object.assign(file, { Video: this })
1559 // No webtorrent files, try with streaming playlist files
1560 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1561 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1563 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1564 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1570 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1571 return this.getQualityFileBy(maxBy)
1574 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1575 return this.getQualityFileBy(minBy)
1578 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1579 if (Array.isArray(this.VideoFiles) === false) return undefined
1581 const file = this.VideoFiles.find(f => f.resolution === resolution)
1582 if (!file) return undefined
1584 return Object.assign(file, { Video: this })
1587 hasWebTorrentFiles () {
1588 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1591 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1592 thumbnail.videoId = this.id
1594 const savedThumbnail = await thumbnail.save({ transaction })
1596 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1598 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1599 this.Thumbnails.push(savedThumbnail)
1603 if (Array.isArray(this.Thumbnails) === false) return undefined
1605 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1609 return !!this.getPreview()
1613 if (Array.isArray(this.Thumbnails) === false) return undefined
1615 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1619 return this.remote === false
1622 getWatchStaticPath () {
1623 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1626 getEmbedStaticPath () {
1627 return buildVideoEmbedPath(this)
1630 getMiniatureStaticPath () {
1631 const thumbnail = this.getMiniature()
1632 if (!thumbnail) return null
1634 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1637 getPreviewStaticPath () {
1638 const preview = this.getPreview()
1639 if (!preview) return null
1641 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1642 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1645 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1646 return videoModelToFormattedJSON(this, options)
1649 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1650 return videoModelToFormattedDetailsJSON(this)
1653 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1654 let files: VideoFile[] = []
1656 if (Array.isArray(this.VideoFiles)) {
1657 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1658 files = files.concat(result)
1661 for (const p of (this.VideoStreamingPlaylists || [])) {
1662 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1663 files = files.concat(result)
1669 toActivityPubObject (this: MVideoAP): VideoObject {
1670 return videoModelToActivityPubObject(this)
1673 getTruncatedDescription () {
1674 if (!this.description) return null
1676 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1677 return peertubeTruncate(this.description, { length: maxLength })
1680 getMaxQualityResolution () {
1681 const file = this.getMaxQualityFile()
1682 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1684 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), originalFilePath => {
1685 return getVideoFileResolution(originalFilePath)
1689 getDescriptionAPIPath () {
1690 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1693 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1694 if (!this.VideoStreamingPlaylists) return undefined
1696 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1697 if (!playlist) return undefined
1699 playlist.Video = this
1704 setHLSPlaylist (playlist: MStreamingPlaylist) {
1705 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1707 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1708 this.VideoStreamingPlaylists = toAdd
1712 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1713 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1717 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1718 const filePath = isRedundancy
1719 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1720 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1722 const promises: Promise<any>[] = [ remove(filePath) ]
1723 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1725 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1726 promises.push(removeWebTorrentObjectStorage(videoFile))
1729 return Promise.all(promises)
1732 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1733 const directoryPath = isRedundancy
1734 ? getHLSRedundancyDirectory(this)
1735 : getHLSDirectory(this)
1737 await remove(directoryPath)
1739 if (isRedundancy !== true) {
1740 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1741 streamingPlaylistWithFiles.Video = this
1743 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1744 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1747 // Remove physical files and torrents
1749 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1752 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1753 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1759 if (this.isOwned()) return false
1761 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1764 hasPrivacyForFederation () {
1765 return isPrivacyForFederation(this.privacy)
1768 hasStateForFederation () {
1769 return isStateForFederation(this.state)
1772 isNewVideo (newPrivacy: VideoPrivacy) {
1773 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1776 setAsRefreshed (transaction?: Transaction) {
1777 return setAsUpdated('video', this.id, transaction)
1781 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1784 setPrivacy (newPrivacy: VideoPrivacy) {
1785 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1786 this.publishedAt = new Date()
1789 this.privacy = newPrivacy
1793 return this.privacy === VideoPrivacy.PRIVATE ||
1794 this.privacy === VideoPrivacy.UNLISTED ||
1795 this.privacy === VideoPrivacy.INTERNAL
1798 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1799 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1801 this.state = newState
1803 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1804 this.publishedAt = new Date()
1807 await this.save({ transaction })
1810 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1811 return Math.ceil((videoFile.size * 8) / this.duration)
1815 if (this.isOwned()) {
1817 WEBSERVER.URL + '/tracker/announce',
1818 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1822 return this.Trackers.map(t => t.url)