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 { uuidToShort } from '@server/helpers/uuid'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live/live-manager'
31 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
32 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
33 import { VideoPathManager } from '@server/lib/video-path-manager'
34 import { getServerActor } from '@server/models/application/application'
35 import { ModelCache } from '@server/models/model-cache'
36 import { AttributesOnly, buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
37 import { VideoInclude } from '@shared/models'
38 import { VideoFile } from '@shared/models/videos/video-file.model'
39 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoRateType, VideoStorage } from '../../../shared/models/videos'
42 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
43 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
44 import { peertubeTruncate } from '../../helpers/core-utils'
45 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
46 import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
56 import { logger } from '../../helpers/logger'
57 import { CONFIG } from '../../initializers/config'
58 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
59 import { sendDeleteVideo } from '../../lib/activitypub/send'
62 MChannelAccountDefault,
65 MStreamingPlaylistFilesVideo,
70 MVideoAccountLightBlacklistAllFiles,
75 MVideoFormattableDetails,
81 MVideoThumbnailBlacklist,
84 } from '../../types/models'
85 import { MThumbnail } from '../../types/models/video/thumbnail'
86 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
87 import { VideoAbuseModel } from '../abuse/video-abuse'
88 import { AccountModel } from '../account/account'
89 import { AccountVideoRateModel } from '../account/account-video-rate'
90 import { ActorModel } from '../actor/actor'
91 import { ActorImageModel } from '../actor/actor-image'
92 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
93 import { ServerModel } from '../server/server'
94 import { TrackerModel } from '../server/tracker'
95 import { VideoTrackerModel } from '../server/video-tracker'
96 import { setAsUpdated } from '../shared'
97 import { UserModel } from '../user/user'
98 import { UserVideoHistoryModel } from '../user/user-video-history'
99 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
101 videoFilesModelToFormattedJSON,
102 VideoFormattingJSONOptions,
103 videoModelToActivityPubObject,
104 videoModelToFormattedDetailsJSON,
105 videoModelToFormattedJSON
106 } from './formatter/video-format-utils'
107 import { ScheduleVideoUpdateModel } from './schedule-video-update'
108 import { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
109 import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
110 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
111 import { TagModel } from './tag'
112 import { ThumbnailModel } from './thumbnail'
113 import { VideoBlacklistModel } from './video-blacklist'
114 import { VideoCaptionModel } from './video-caption'
115 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
116 import { VideoCommentModel } from './video-comment'
117 import { VideoFileModel } from './video-file'
118 import { VideoImportModel } from './video-import'
119 import { VideoJobInfoModel } from './video-job-info'
120 import { VideoLiveModel } from './video-live'
121 import { VideoPlaylistElementModel } from './video-playlist-element'
122 import { VideoShareModel } from './video-share'
123 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
124 import { VideoTagModel } from './video-tag'
125 import { VideoViewModel } from './video-view'
127 export enum ScopeNames {
129 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
130 WITH_TAGS = 'WITH_TAGS',
131 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
132 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
133 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
134 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
135 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
136 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
137 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
140 export type ForAPIOptions = {
143 videoPlaylistId?: number
145 withAccountBlockerIds?: number[]
149 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
150 attributes: [ 'id', 'url', 'uuid', 'remote' ]
152 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
153 const include: Includeable[] = [
155 model: VideoChannelModel.scope({
157 VideoChannelScopeNames.SUMMARY, {
159 withAccountBlockerIds: options.withAccountBlockerIds
166 attributes: [ 'type', 'filename' ],
167 model: ThumbnailModel,
172 const query: FindOptions = {}
182 if (options.videoPlaylistId) {
184 model: VideoPlaylistElementModel.unscoped(),
187 videoPlaylistId: options.videoPlaylistId
192 query.include = include
196 [ScopeNames.WITH_THUMBNAILS]: {
199 model: ThumbnailModel,
204 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
207 model: VideoChannelModel.unscoped(),
212 exclude: [ 'privateKey', 'publicKey' ]
214 model: ActorModel.unscoped(),
218 attributes: [ 'host' ],
219 model: ServerModel.unscoped(),
223 model: ActorImageModel.unscoped(),
230 model: AccountModel.unscoped(),
234 model: ActorModel.unscoped(),
236 exclude: [ 'privateKey', 'publicKey' ]
241 attributes: [ 'host' ],
242 model: ServerModel.unscoped(),
246 model: ActorImageModel.unscoped(),
258 [ScopeNames.WITH_TAGS]: {
259 include: [ TagModel ]
261 [ScopeNames.WITH_BLACKLISTED]: {
264 attributes: [ 'id', 'reason', 'unfederated' ],
265 model: VideoBlacklistModel,
270 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
271 let subInclude: any[] = []
273 if (withRedundancies === true) {
276 attributes: [ 'fileUrl' ],
277 model: VideoRedundancyModel.unscoped(),
286 model: VideoFileModel,
294 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
295 const subInclude: IncludeOptions[] = [
297 model: VideoFileModel,
302 if (withRedundancies === true) {
304 attributes: [ 'fileUrl' ],
305 model: VideoRedundancyModel.unscoped(),
313 model: VideoStreamingPlaylistModel.unscoped(),
321 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
324 model: ScheduleVideoUpdateModel.unscoped(),
329 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
333 attributes: [ 'currentTime' ],
334 model: UserVideoHistoryModel.unscoped(),
347 buildTrigramSearchIndex('video_name_trigram', 'name'),
349 { fields: [ 'createdAt' ] },
352 { name: 'publishedAt', order: 'DESC' },
353 { name: 'id', order: 'ASC' }
356 { fields: [ 'duration' ] },
359 { name: 'views', order: 'DESC' },
360 { name: 'id', order: 'ASC' }
363 { fields: [ 'channelId' ] },
365 fields: [ 'originallyPublishedAt' ],
367 originallyPublishedAt: {
373 fields: [ 'category' ], // We don't care videos with an unknown category
381 fields: [ 'licence' ], // We don't care videos with an unknown licence
389 fields: [ 'language' ], // We don't care videos with an unknown language
397 fields: [ 'nsfw' ], // Most of the videos are not NSFW
403 fields: [ 'remote' ], // Only index local videos
418 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
421 @Default(DataType.UUIDV4)
423 @Column(DataType.UUID)
427 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
443 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
447 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
449 privacy: VideoPrivacy
452 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
458 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
459 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
464 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
465 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
469 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
504 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
505 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
510 commentsEnabled: boolean
514 downloadEnabled: boolean
518 waitTranscoding: boolean
522 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
533 @Default(DataType.NOW)
540 originallyPublishedAt: Date
542 @ForeignKey(() => VideoChannelModel)
546 @BelongsTo(() => VideoChannelModel, {
552 VideoChannel: VideoChannelModel
554 @BelongsToMany(() => TagModel, {
555 foreignKey: 'videoId',
556 through: () => VideoTagModel,
561 @BelongsToMany(() => TrackerModel, {
562 foreignKey: 'videoId',
563 through: () => VideoTrackerModel,
566 Trackers: TrackerModel[]
568 @HasMany(() => ThumbnailModel, {
576 Thumbnails: ThumbnailModel[]
578 @HasMany(() => VideoPlaylistElementModel, {
585 VideoPlaylistElements: VideoPlaylistElementModel[]
587 @HasMany(() => VideoAbuseModel, {
594 VideoAbuses: VideoAbuseModel[]
596 @HasMany(() => VideoFileModel, {
604 VideoFiles: VideoFileModel[]
606 @HasMany(() => VideoStreamingPlaylistModel, {
614 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
616 @HasMany(() => VideoShareModel, {
623 VideoShares: VideoShareModel[]
625 @HasMany(() => AccountVideoRateModel, {
632 AccountVideoRates: AccountVideoRateModel[]
634 @HasMany(() => VideoCommentModel, {
642 VideoComments: VideoCommentModel[]
644 @HasMany(() => VideoViewModel, {
651 VideoViews: VideoViewModel[]
653 @HasMany(() => UserVideoHistoryModel, {
660 UserVideoHistories: UserVideoHistoryModel[]
662 @HasOne(() => ScheduleVideoUpdateModel, {
669 ScheduleVideoUpdate: ScheduleVideoUpdateModel
671 @HasOne(() => VideoBlacklistModel, {
678 VideoBlacklist: VideoBlacklistModel
680 @HasOne(() => VideoLiveModel, {
687 VideoLive: VideoLiveModel
689 @HasOne(() => VideoImportModel, {
696 VideoImport: VideoImportModel
698 @HasMany(() => VideoCaptionModel, {
705 ['separate' as any]: true
707 VideoCaptions: VideoCaptionModel[]
709 @HasOne(() => VideoJobInfoModel, {
716 VideoJobInfo: VideoJobInfoModel
719 static async sendDelete (instance: MVideoAccountLight, options) {
720 if (!instance.isOwned()) return undefined
722 // Lazy load channels
723 if (!instance.VideoChannel) {
724 instance.VideoChannel = await instance.$get('VideoChannel', {
729 transaction: options.transaction
730 }) as MChannelAccountDefault
733 return sendDeleteVideo(instance, options.transaction)
737 static async removeFiles (instance: VideoModel, options) {
738 const tasks: Promise<any>[] = []
740 logger.info('Removing files of video %s.', instance.url)
742 if (instance.isOwned()) {
743 if (!Array.isArray(instance.VideoFiles)) {
744 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
747 // Remove physical files and torrents
748 instance.VideoFiles.forEach(file => {
749 tasks.push(instance.removeFileAndTorrent(file))
752 // Remove playlists file
753 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
754 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
757 for (const p of instance.VideoStreamingPlaylists) {
758 tasks.push(instance.removeStreamingPlaylistFiles(p))
762 // Do not wait video deletion because we could be in a transaction
765 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
772 static stopLiveIfNeeded (instance: VideoModel) {
773 if (!instance.isLive) return
775 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
777 LiveManager.Instance.stopSessionOf(instance.id)
781 static invalidateCache (instance: VideoModel) {
782 ModelCache.Instance.invalidateCache('video', instance.id)
786 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
787 const tasks: Promise<any>[] = []
789 if (!Array.isArray(instance.VideoAbuses)) {
790 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
792 if (instance.VideoAbuses.length === 0) return undefined
795 logger.info('Saving video abuses details of video %s.', instance.url)
797 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
798 const details = instance.toFormattedDetailsJSON()
800 for (const abuse of instance.VideoAbuses) {
801 abuse.deletedVideo = details
802 tasks.push(abuse.save({ transaction: options.transaction }))
805 await Promise.all(tasks)
808 static listLocal (): Promise<MVideo[]> {
815 return VideoModel.findAll(query)
818 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
819 function getRawQuery (select: string) {
820 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
821 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
822 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
823 'WHERE "Account"."actorId" = ' + actorId
824 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
825 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
826 'WHERE "VideoShare"."actorId" = ' + actorId
828 return `(${queryVideo}) UNION (${queryVideoShare})`
831 const rawQuery = getRawQuery('"Video"."id"')
832 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
838 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
841 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
843 [Op.or]: getPrivaciesForFederation()
847 attributes: [ 'filename', 'language', 'fileUrl' ],
848 model: VideoCaptionModel.unscoped(),
852 attributes: [ 'id', 'url' ],
853 model: VideoShareModel.unscoped(),
855 // We only want videos shared by this actor
870 attributes: [ 'id', 'url' ],
871 model: ActorModel.unscoped()
876 model: VideoChannelModel.unscoped(),
880 attributes: [ 'name' ],
881 model: AccountModel.unscoped(),
885 attributes: [ 'id', 'url', 'followersUrl' ],
886 model: ActorModel.unscoped(),
892 attributes: [ 'id', 'url', 'followersUrl' ],
893 model: ActorModel.unscoped(),
899 model: VideoStreamingPlaylistModel.unscoped(),
903 model: VideoFileModel,
908 VideoLiveModel.unscoped(),
914 return Bluebird.all([
915 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
916 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
917 ]).then(([ rows, totals ]) => {
918 // totals: totalVideos + totalVideoShares
920 let totalVideoShares = 0
921 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
922 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
924 const total = totalVideos + totalVideoShares
932 static async listPublishedLiveUUIDs () {
934 attributes: [ 'uuid' ],
938 state: VideoState.PUBLISHED
942 const result = await VideoModel.findAll(options)
944 return result.map(v => v.uuid)
947 static listUserVideosForApi (options: {
957 const { accountId, channelId, start, count, sort, search, isLive } = options
959 function buildBaseQuery (): FindOptions {
960 const where: WhereOptions = {}
964 [Op.iLike]: '%' + search + '%'
968 if (exists(isLive)) {
969 where.isLive = isLive
972 const channelWhere = channelId
980 order: getVideoSort(sort),
983 model: VideoChannelModel,
1002 const countQuery = buildBaseQuery()
1003 const findQuery = buildBaseQuery()
1005 const findScopes: (string | ScopeOptions)[] = [
1006 ScopeNames.WITH_SCHEDULED_UPDATE,
1007 ScopeNames.WITH_BLACKLISTED,
1008 ScopeNames.WITH_THUMBNAILS
1011 return Promise.all([
1012 VideoModel.count(countQuery),
1013 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1014 ]).then(([ count, rows ]) => {
1022 static async listForApi (options: {
1030 include?: VideoInclude
1032 hasFiles?: boolean // default false
1033 hasWebtorrentFiles?: boolean
1034 hasHLSFiles?: boolean
1036 categoryOneOf?: number[]
1037 licenceOneOf?: number[]
1038 languageOneOf?: string[]
1039 tagsOneOf?: string[]
1040 tagsAllOf?: string[]
1043 videoChannelId?: number
1045 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1047 videoPlaylistId?: number
1049 trendingDays?: number
1051 user?: MUserAccountId
1052 historyOfUser?: MUserId
1054 countVideos?: boolean
1058 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1060 const trendingDays = options.sort.endsWith('trending')
1061 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1064 let trendingAlgorithm: string
1065 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1066 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1068 const serverActor = await getServerActor()
1070 const queryOptions = {
1084 'displayOnlyForFollower',
1092 'hasWebtorrentFiles',
1096 serverAccountIdForBlock: serverActor.Account.id,
1101 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1104 static async searchAndPopulateAccountAndServer (options: {
1112 include?: VideoInclude
1114 categoryOneOf?: number[]
1115 licenceOneOf?: number[]
1116 languageOneOf?: string[]
1117 tagsOneOf?: string[]
1118 tagsAllOf?: string[]
1120 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1122 user?: MUserAccountId
1124 hasWebtorrentFiles?: boolean
1125 hasHLSFiles?: boolean
1130 startDate?: string // ISO 8601
1131 endDate?: string // ISO 8601
1132 originallyPublishedStartDate?: string
1133 originallyPublishedEndDate?: string
1135 durationMin?: number // seconds
1136 durationMax?: number // seconds
1139 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1141 const serverActor = await getServerActor()
1143 const queryOptions = {
1161 'originallyPublishedStartDate',
1162 'originallyPublishedEndDate',
1166 'hasWebtorrentFiles',
1169 'displayOnlyForFollower'
1171 serverAccountIdForBlock: serverActor.Account.id
1174 return VideoModel.getAvailableForApi(queryOptions)
1177 static countLocalLives () {
1183 [Op.ne]: VideoState.LIVE_ENDED
1188 return VideoModel.count(options)
1191 static countVideosUploadedByUserSince (userId: number, since: Date) {
1195 model: VideoChannelModel.unscoped(),
1199 model: AccountModel.unscoped(),
1203 model: UserModel.unscoped(),
1221 return VideoModel.unscoped().count(options)
1224 static countLivesOfAccount (accountId: number) {
1230 [Op.ne]: VideoState.LIVE_ENDED
1236 model: VideoChannelModel.unscoped(),
1244 return VideoModel.count(options)
1247 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1248 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1250 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1253 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1254 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1256 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1259 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1262 where: buildWhereIdOrUUID(id),
1266 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1269 return ModelCache.Instance.doCache({
1270 cacheType: 'load-video-immutable-id',
1277 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1279 const query: FindOptions = {
1286 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1289 return ModelCache.Instance.doCache({
1290 cacheType: 'load-video-immutable-url',
1297 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1298 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1300 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1303 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1304 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1306 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1309 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1310 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1312 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1315 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1316 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1318 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1321 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1322 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1324 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1327 static loadForGetAPI (parameters: {
1329 transaction?: Transaction
1331 }): Promise<MVideoDetails> {
1332 const { id, transaction, userId } = parameters
1333 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1335 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1338 static async getStats () {
1339 const totalLocalVideos = await VideoModel.count({
1345 let totalLocalVideoViews = await VideoModel.sum('views', {
1351 // Sequelize could return null...
1352 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1354 const serverActor = await getServerActor()
1356 const { total: totalVideos } = await VideoModel.listForApi({
1359 sort: '-publishedAt',
1360 nsfw: buildNSFWFilter(),
1361 displayOnlyForFollower: {
1362 actorId: serverActor.id,
1369 totalLocalVideoViews,
1374 static incrementViews (id: number, views: number) {
1375 return VideoModel.increment('views', {
1383 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1384 const field = type === 'like'
1388 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1390 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1392 'WHERE "video"."id" = :videoId'
1394 return AccountVideoRateModel.sequelize.query(rawQuery, {
1396 replacements: { videoId, rateType: type },
1397 type: QueryTypes.UPDATE
1401 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1402 // Instances only share videos
1403 const query = 'SELECT 1 FROM "videoShare" ' +
1404 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1405 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1409 type: QueryTypes.SELECT as QueryTypes.SELECT,
1410 bind: { followerActorId, videoId },
1414 return VideoModel.sequelize.query(query, options)
1415 .then(results => results.length === 1)
1418 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1421 channelId: ofChannel.id
1426 return VideoModel.update({ support: ofChannel.support }, options)
1429 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1431 attributes: [ 'id' ],
1433 channelId: videoChannel.id
1437 return VideoModel.findAll(query)
1438 .then(videos => videos.map(v => v.id))
1441 // threshold corresponds to how many video the field should have to be returned
1442 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1443 const serverActor = await getServerActor()
1445 const queryOptions: BuildVideosListQueryOptions = {
1446 attributes: [ `"${field}"` ],
1447 group: `GROUP BY "${field}"`,
1448 having: `HAVING COUNT("${field}") >= ${threshold}`,
1452 serverAccountIdForBlock: serverActor.Account.id,
1453 displayOnlyForFollower: {
1454 actorId: serverActor.id,
1459 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1461 return queryBuilder.queryVideoIds(queryOptions)
1462 .then(rows => rows.map(r => r[field]))
1465 static buildTrendingQuery (trendingDays: number) {
1469 model: VideoViewModel,
1473 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1479 private static async getAvailableForApi (
1480 options: BuildVideosListQueryOptions,
1482 ): Promise<ResultList<VideoModel>> {
1483 function getCount () {
1484 if (countVideos !== true) return Promise.resolve(undefined)
1486 const countOptions = Object.assign({}, options, { isCount: true })
1487 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1489 return queryBuilder.countVideoIds(countOptions)
1492 function getModels () {
1493 if (options.count === 0) return Promise.resolve([])
1495 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1497 return queryBuilder.queryVideos(options)
1500 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1508 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1509 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1510 throw new Error('Try to filter all-local but no user has not the see all videos right')
1514 private static isPrivateInclude (include: VideoInclude) {
1515 return include & VideoInclude.BLACKLISTED ||
1516 include & VideoInclude.BLOCKED_OWNER ||
1517 include & VideoInclude.HIDDEN_PRIVACY ||
1518 include & VideoInclude.NOT_PUBLISHED_STATE
1522 return !!this.VideoBlacklist
1526 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1529 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1530 // We first transcode to WebTorrent format, so try this array first
1531 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1532 const file = fun(this.VideoFiles, file => file.resolution)
1534 return Object.assign(file, { Video: this })
1537 // No webtorrent files, try with streaming playlist files
1538 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1539 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1541 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1542 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1548 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1549 return this.getQualityFileBy(maxBy)
1552 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1553 return this.getQualityFileBy(minBy)
1556 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1557 if (Array.isArray(this.VideoFiles) === false) return undefined
1559 const file = this.VideoFiles.find(f => f.resolution === resolution)
1560 if (!file) return undefined
1562 return Object.assign(file, { Video: this })
1565 hasWebTorrentFiles () {
1566 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1569 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1570 thumbnail.videoId = this.id
1572 const savedThumbnail = await thumbnail.save({ transaction })
1574 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1576 // Already have this thumbnail, skip
1577 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1579 this.Thumbnails.push(savedThumbnail)
1583 if (Array.isArray(this.Thumbnails) === false) return undefined
1585 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1589 return !!this.getPreview()
1593 if (Array.isArray(this.Thumbnails) === false) return undefined
1595 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1599 return this.remote === false
1602 getWatchStaticPath () {
1603 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1606 getEmbedStaticPath () {
1607 return buildVideoEmbedPath(this)
1610 getMiniatureStaticPath () {
1611 const thumbnail = this.getMiniature()
1612 if (!thumbnail) return null
1614 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1617 getPreviewStaticPath () {
1618 const preview = this.getPreview()
1619 if (!preview) return null
1621 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1622 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1625 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1626 return videoModelToFormattedJSON(this, options)
1629 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1630 return videoModelToFormattedDetailsJSON(this)
1633 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1634 let files: VideoFile[] = []
1636 if (Array.isArray(this.VideoFiles)) {
1637 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1638 files = files.concat(result)
1641 for (const p of (this.VideoStreamingPlaylists || [])) {
1642 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1643 files = files.concat(result)
1649 toActivityPubObject (this: MVideoAP): VideoObject {
1650 return videoModelToActivityPubObject(this)
1653 getTruncatedDescription () {
1654 if (!this.description) return null
1656 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1657 return peertubeTruncate(this.description, { length: maxLength })
1660 getMaxQualityResolution () {
1661 const file = this.getMaxQualityFile()
1662 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1664 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => {
1665 return getVideoFileResolution(originalFilePath)
1669 getDescriptionAPIPath () {
1670 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1673 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1674 if (!this.VideoStreamingPlaylists) return undefined
1676 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1677 playlist.Video = this
1682 setHLSPlaylist (playlist: MStreamingPlaylist) {
1683 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1685 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1686 this.VideoStreamingPlaylists = toAdd
1690 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1691 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1695 removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1696 const filePath = isRedundancy
1697 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1698 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1700 const promises: Promise<any>[] = [ remove(filePath) ]
1701 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1703 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1704 promises.push(removeWebTorrentObjectStorage(videoFile))
1707 return Promise.all(promises)
1710 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1711 const directoryPath = isRedundancy
1712 ? getHLSRedundancyDirectory(this)
1713 : getHLSDirectory(this)
1715 await remove(directoryPath)
1717 if (isRedundancy !== true) {
1718 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1719 streamingPlaylistWithFiles.Video = this
1721 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1722 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1725 // Remove physical files and torrents
1727 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1730 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1731 await removeHLSObjectStorage(streamingPlaylist, this)
1737 if (this.isOwned()) return false
1739 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1742 hasPrivacyForFederation () {
1743 return isPrivacyForFederation(this.privacy)
1746 hasStateForFederation () {
1747 return isStateForFederation(this.state)
1750 isNewVideo (newPrivacy: VideoPrivacy) {
1751 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1755 return setAsUpdated('video', this.id)
1759 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1762 setPrivacy (newPrivacy: VideoPrivacy) {
1763 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1764 this.publishedAt = new Date()
1767 this.privacy = newPrivacy
1771 return this.privacy === VideoPrivacy.PRIVATE ||
1772 this.privacy === VideoPrivacy.UNLISTED ||
1773 this.privacy === VideoPrivacy.INTERNAL
1776 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1777 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1779 this.state = newState
1781 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1782 this.publishedAt = new Date()
1785 await this.save({ transaction })
1788 getBandwidthBits (videoFile: MVideoFile) {
1789 return Math.ceil((videoFile.size * 8) / this.duration)
1793 if (this.isOwned()) {
1795 WEBSERVER.URL + '/tracker/announce',
1796 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1800 return this.Trackers.map(t => t.url)