1 import * as 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 { setAsUpdated } from '@server/helpers/database-utils'
28 import { buildNSFWFilter } from '@server/helpers/express-utils'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live/live-manager'
31 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { AttributesOnly } from '@shared/core-utils'
35 import { VideoFile } from '@shared/models/videos/video-file.model'
36 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
37 import { VideoObject } from '../../../shared/models/activitypub/objects'
38 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
39 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
42 import { peertubeTruncate } from '../../helpers/core-utils'
43 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
44 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
52 } from '../../helpers/custom-validators/videos'
53 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
54 import { logger } from '../../helpers/logger'
55 import { CONFIG } from '../../initializers/config'
56 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
57 import { sendDeleteVideo } from '../../lib/activitypub/send'
60 MChannelAccountDefault,
63 MStreamingPlaylistFilesVideo,
68 MVideoAccountLightBlacklistAllFiles,
73 MVideoFormattableDetails,
79 MVideoThumbnailBlacklist,
82 } from '../../types/models'
83 import { MThumbnail } from '../../types/models/video/thumbnail'
84 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
85 import { VideoAbuseModel } from '../abuse/video-abuse'
86 import { AccountModel } from '../account/account'
87 import { AccountVideoRateModel } from '../account/account-video-rate'
88 import { ActorModel } from '../actor/actor'
89 import { ActorImageModel } from '../actor/actor-image'
90 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
91 import { ServerModel } from '../server/server'
92 import { TrackerModel } from '../server/tracker'
93 import { VideoTrackerModel } from '../server/video-tracker'
94 import { UserModel } from '../user/user'
95 import { UserVideoHistoryModel } from '../user/user-video-history'
96 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
98 videoFilesModelToFormattedJSON,
99 VideoFormattingJSONOptions,
100 videoModelToActivityPubObject,
101 videoModelToFormattedDetailsJSON,
102 videoModelToFormattedJSON
103 } from './formatter/video-format-utils'
104 import { ScheduleVideoUpdateModel } from './schedule-video-update'
105 import { VideosModelGetQueryBuilder } from './sql/video-model-get-query-builder'
106 import { BuildVideosListQueryOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
107 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
108 import { TagModel } from './tag'
109 import { ThumbnailModel } from './thumbnail'
110 import { VideoBlacklistModel } from './video-blacklist'
111 import { VideoCaptionModel } from './video-caption'
112 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
113 import { VideoCommentModel } from './video-comment'
114 import { VideoFileModel } from './video-file'
115 import { VideoImportModel } from './video-import'
116 import { VideoLiveModel } from './video-live'
117 import { VideoPlaylistElementModel } from './video-playlist-element'
118 import { VideoShareModel } from './video-share'
119 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
120 import { VideoTagModel } from './video-tag'
121 import { VideoViewModel } from './video-view'
123 export enum ScopeNames {
125 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
126 WITH_TAGS = 'WITH_TAGS',
127 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
128 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
129 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
130 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
131 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
132 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
133 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
136 export type ForAPIOptions = {
139 videoPlaylistId?: number
141 withAccountBlockerIds?: number[]
144 export type AvailableForListIDsOptions = {
145 serverAccountId: number
146 followerActorId: number
147 includeLocalVideos: boolean
149 attributesType?: 'none' | 'id' | 'all'
152 categoryOneOf?: number[]
154 licenceOneOf?: number[]
155 languageOneOf?: string[]
162 videoChannelId?: number
164 videoPlaylistId?: number
166 trendingDays?: number
167 user?: MUserAccountId
168 historyOfUser?: MUserId
170 baseWhere?: WhereOptions[]
174 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
175 attributes: [ 'id', 'url', 'uuid', 'remote' ]
177 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
178 const include: Includeable[] = [
180 model: VideoChannelModel.scope({
182 VideoChannelScopeNames.SUMMARY, {
184 withAccountBlockerIds: options.withAccountBlockerIds
191 attributes: [ 'type', 'filename' ],
192 model: ThumbnailModel,
197 const query: FindOptions = {}
207 if (options.videoPlaylistId) {
209 model: VideoPlaylistElementModel.unscoped(),
212 videoPlaylistId: options.videoPlaylistId
217 query.include = include
221 [ScopeNames.WITH_THUMBNAILS]: {
224 model: ThumbnailModel,
229 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
232 model: VideoChannelModel.unscoped(),
237 exclude: [ 'privateKey', 'publicKey' ]
239 model: ActorModel.unscoped(),
243 attributes: [ 'host' ],
244 model: ServerModel.unscoped(),
248 model: ActorImageModel.unscoped(),
255 model: AccountModel.unscoped(),
259 model: ActorModel.unscoped(),
261 exclude: [ 'privateKey', 'publicKey' ]
266 attributes: [ 'host' ],
267 model: ServerModel.unscoped(),
271 model: ActorImageModel.unscoped(),
283 [ScopeNames.WITH_TAGS]: {
284 include: [ TagModel ]
286 [ScopeNames.WITH_BLACKLISTED]: {
289 attributes: [ 'id', 'reason', 'unfederated' ],
290 model: VideoBlacklistModel,
295 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
296 let subInclude: any[] = []
298 if (withRedundancies === true) {
301 attributes: [ 'fileUrl' ],
302 model: VideoRedundancyModel.unscoped(),
311 model: VideoFileModel,
319 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
320 const subInclude: IncludeOptions[] = [
322 model: VideoFileModel,
327 if (withRedundancies === true) {
329 attributes: [ 'fileUrl' ],
330 model: VideoRedundancyModel.unscoped(),
338 model: VideoStreamingPlaylistModel.unscoped(),
346 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
349 model: ScheduleVideoUpdateModel.unscoped(),
354 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
358 attributes: [ 'currentTime' ],
359 model: UserVideoHistoryModel.unscoped(),
372 buildTrigramSearchIndex('video_name_trigram', 'name'),
374 { fields: [ 'createdAt' ] },
377 { name: 'publishedAt', order: 'DESC' },
378 { name: 'id', order: 'ASC' }
381 { fields: [ 'duration' ] },
384 { name: 'views', order: 'DESC' },
385 { name: 'id', order: 'ASC' }
388 { fields: [ 'channelId' ] },
390 fields: [ 'originallyPublishedAt' ],
392 originallyPublishedAt: {
398 fields: [ 'category' ], // We don't care videos with an unknown category
406 fields: [ 'licence' ], // We don't care videos with an unknown licence
414 fields: [ 'language' ], // We don't care videos with an unknown language
422 fields: [ 'nsfw' ], // Most of the videos are not NSFW
428 fields: [ 'remote' ], // Only index local videos
443 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
446 @Default(DataType.UUIDV4)
448 @Column(DataType.UUID)
452 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
468 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
472 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
474 privacy: VideoPrivacy
477 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
483 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
484 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
489 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
490 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
494 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
529 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
530 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
535 commentsEnabled: boolean
539 downloadEnabled: boolean
543 waitTranscoding: boolean
547 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
558 @Default(DataType.NOW)
565 originallyPublishedAt: Date
567 @ForeignKey(() => VideoChannelModel)
571 @BelongsTo(() => VideoChannelModel, {
577 VideoChannel: VideoChannelModel
579 @BelongsToMany(() => TagModel, {
580 foreignKey: 'videoId',
581 through: () => VideoTagModel,
586 @BelongsToMany(() => TrackerModel, {
587 foreignKey: 'videoId',
588 through: () => VideoTrackerModel,
591 Trackers: TrackerModel[]
593 @HasMany(() => ThumbnailModel, {
601 Thumbnails: ThumbnailModel[]
603 @HasMany(() => VideoPlaylistElementModel, {
610 VideoPlaylistElements: VideoPlaylistElementModel[]
612 @HasMany(() => VideoAbuseModel, {
619 VideoAbuses: VideoAbuseModel[]
621 @HasMany(() => VideoFileModel, {
629 VideoFiles: VideoFileModel[]
631 @HasMany(() => VideoStreamingPlaylistModel, {
639 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
641 @HasMany(() => VideoShareModel, {
648 VideoShares: VideoShareModel[]
650 @HasMany(() => AccountVideoRateModel, {
657 AccountVideoRates: AccountVideoRateModel[]
659 @HasMany(() => VideoCommentModel, {
667 VideoComments: VideoCommentModel[]
669 @HasMany(() => VideoViewModel, {
676 VideoViews: VideoViewModel[]
678 @HasMany(() => UserVideoHistoryModel, {
685 UserVideoHistories: UserVideoHistoryModel[]
687 @HasOne(() => ScheduleVideoUpdateModel, {
694 ScheduleVideoUpdate: ScheduleVideoUpdateModel
696 @HasOne(() => VideoBlacklistModel, {
703 VideoBlacklist: VideoBlacklistModel
705 @HasOne(() => VideoLiveModel, {
712 VideoLive: VideoLiveModel
714 @HasOne(() => VideoImportModel, {
721 VideoImport: VideoImportModel
723 @HasMany(() => VideoCaptionModel, {
730 ['separate' as any]: true
732 VideoCaptions: VideoCaptionModel[]
735 static async sendDelete (instance: MVideoAccountLight, options) {
736 if (!instance.isOwned()) return undefined
738 // Lazy load channels
739 if (!instance.VideoChannel) {
740 instance.VideoChannel = await instance.$get('VideoChannel', {
745 transaction: options.transaction
746 }) as MChannelAccountDefault
749 return sendDeleteVideo(instance, options.transaction)
753 static async removeFiles (instance: VideoModel, options) {
754 const tasks: Promise<any>[] = []
756 logger.info('Removing files of video %s.', instance.url)
758 if (instance.isOwned()) {
759 if (!Array.isArray(instance.VideoFiles)) {
760 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
763 // Remove physical files and torrents
764 instance.VideoFiles.forEach(file => {
765 tasks.push(instance.removeFileAndTorrent(file))
768 // Remove playlists file
769 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
770 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
773 for (const p of instance.VideoStreamingPlaylists) {
774 tasks.push(instance.removeStreamingPlaylistFiles(p))
778 // Do not wait video deletion because we could be in a transaction
781 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
788 static stopLiveIfNeeded (instance: VideoModel) {
789 if (!instance.isLive) return
791 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
793 LiveManager.Instance.stopSessionOf(instance.id)
797 static invalidateCache (instance: VideoModel) {
798 ModelCache.Instance.invalidateCache('video', instance.id)
802 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
803 const tasks: Promise<any>[] = []
805 if (!Array.isArray(instance.VideoAbuses)) {
806 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
808 if (instance.VideoAbuses.length === 0) return undefined
811 logger.info('Saving video abuses details of video %s.', instance.url)
813 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
814 const details = instance.toFormattedDetailsJSON()
816 for (const abuse of instance.VideoAbuses) {
817 abuse.deletedVideo = details
818 tasks.push(abuse.save({ transaction: options.transaction }))
821 await Promise.all(tasks)
824 static listLocal (): Promise<MVideo[]> {
831 return VideoModel.findAll(query)
834 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
835 function getRawQuery (select: string) {
836 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
837 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
838 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
839 'WHERE "Account"."actorId" = ' + actorId
840 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
841 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
842 'WHERE "VideoShare"."actorId" = ' + actorId
844 return `(${queryVideo}) UNION (${queryVideoShare})`
847 const rawQuery = getRawQuery('"Video"."id"')
848 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
854 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
857 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
859 [Op.or]: getPrivaciesForFederation()
863 attributes: [ 'filename', 'language', 'fileUrl' ],
864 model: VideoCaptionModel.unscoped(),
868 attributes: [ 'id', 'url' ],
869 model: VideoShareModel.unscoped(),
871 // We only want videos shared by this actor
886 attributes: [ 'id', 'url' ],
887 model: ActorModel.unscoped()
892 model: VideoChannelModel.unscoped(),
896 attributes: [ 'name' ],
897 model: AccountModel.unscoped(),
901 attributes: [ 'id', 'url', 'followersUrl' ],
902 model: ActorModel.unscoped(),
908 attributes: [ 'id', 'url', 'followersUrl' ],
909 model: ActorModel.unscoped(),
915 model: VideoStreamingPlaylistModel.unscoped(),
919 model: VideoFileModel,
924 VideoLiveModel.unscoped(),
930 return Bluebird.all([
931 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
932 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
933 ]).then(([ rows, totals ]) => {
934 // totals: totalVideos + totalVideoShares
936 let totalVideoShares = 0
937 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
938 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
940 const total = totalVideos + totalVideoShares
948 static async listPublishedLiveUUIDs () {
950 attributes: [ 'uuid' ],
954 state: VideoState.PUBLISHED
958 const result = await VideoModel.findAll(options)
960 return result.map(v => v.uuid)
963 static listUserVideosForApi (options: {
971 const { accountId, start, count, sort, search, isLive } = options
973 function buildBaseQuery (): FindOptions {
974 const where: WhereOptions = {}
978 [Op.iLike]: '%' + search + '%'
983 where.isLive = isLive
990 order: getVideoSort(sort),
993 model: VideoChannelModel,
1011 const countQuery = buildBaseQuery()
1012 const findQuery = buildBaseQuery()
1014 const findScopes: (string | ScopeOptions)[] = [
1015 ScopeNames.WITH_SCHEDULED_UPDATE,
1016 ScopeNames.WITH_BLACKLISTED,
1017 ScopeNames.WITH_THUMBNAILS
1020 return Promise.all([
1021 VideoModel.count(countQuery),
1022 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1023 ]).then(([ count, rows ]) => {
1031 static async listForApi (options: {
1037 filter?: VideoFilter
1040 includeLocalVideos: boolean
1043 categoryOneOf?: number[]
1044 licenceOneOf?: number[]
1045 languageOneOf?: string[]
1046 tagsOneOf?: string[]
1047 tagsAllOf?: string[]
1050 videoChannelId?: number
1052 followerActorId?: number
1054 videoPlaylistId?: number
1056 trendingDays?: number
1058 user?: MUserAccountId
1059 historyOfUser?: MUserId
1061 countVideos?: boolean
1065 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1066 throw new Error('Try to filter all-local but no user has not the see all videos right')
1069 const trendingDays = options.sort.endsWith('trending')
1070 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1072 let trendingAlgorithm
1073 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1074 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1076 const serverActor = await getServerActor()
1078 // followerActorId === null has a meaning, so just check undefined
1079 const followerActorId = options.followerActorId !== undefined
1080 ? options.followerActorId
1083 const queryOptions = {
1084 start: options.start,
1085 count: options.count,
1088 serverAccountId: serverActor.Account.id,
1090 isLive: options.isLive,
1091 categoryOneOf: options.categoryOneOf,
1092 licenceOneOf: options.licenceOneOf,
1093 languageOneOf: options.languageOneOf,
1094 tagsOneOf: options.tagsOneOf,
1095 tagsAllOf: options.tagsAllOf,
1096 filter: options.filter,
1097 withFiles: options.withFiles,
1098 accountId: options.accountId,
1099 videoChannelId: options.videoChannelId,
1100 videoPlaylistId: options.videoPlaylistId,
1101 includeLocalVideos: options.includeLocalVideos,
1103 historyOfUser: options.historyOfUser,
1106 search: options.search
1109 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1112 static async searchAndPopulateAccountAndServer (options: {
1113 includeLocalVideos: boolean
1118 startDate?: string // ISO 8601
1119 endDate?: string // ISO 8601
1120 originallyPublishedStartDate?: string
1121 originallyPublishedEndDate?: string
1124 categoryOneOf?: number[]
1125 licenceOneOf?: number[]
1126 languageOneOf?: string[]
1127 tagsOneOf?: string[]
1128 tagsAllOf?: string[]
1129 durationMin?: number // seconds
1130 durationMax?: number // seconds
1131 user?: MUserAccountId
1132 filter?: VideoFilter
1134 const serverActor = await getServerActor()
1136 const queryOptions = {
1137 followerActorId: serverActor.id,
1138 serverAccountId: serverActor.Account.id,
1140 includeLocalVideos: options.includeLocalVideos,
1142 isLive: options.isLive,
1144 categoryOneOf: options.categoryOneOf,
1145 licenceOneOf: options.licenceOneOf,
1146 languageOneOf: options.languageOneOf,
1148 tagsOneOf: options.tagsOneOf,
1149 tagsAllOf: options.tagsAllOf,
1152 filter: options.filter,
1154 start: options.start,
1155 count: options.count,
1158 startDate: options.startDate,
1159 endDate: options.endDate,
1161 originallyPublishedStartDate: options.originallyPublishedStartDate,
1162 originallyPublishedEndDate: options.originallyPublishedEndDate,
1164 durationMin: options.durationMin,
1165 durationMax: options.durationMax,
1167 search: options.search
1170 return VideoModel.getAvailableForApi(queryOptions)
1173 static countLocalLives () {
1179 [Op.ne]: VideoState.LIVE_ENDED
1184 return VideoModel.count(options)
1187 static countVideosUploadedByUserSince (userId: number, since: Date) {
1191 model: VideoChannelModel.unscoped(),
1195 model: AccountModel.unscoped(),
1199 model: UserModel.unscoped(),
1217 return VideoModel.unscoped().count(options)
1220 static countLivesOfAccount (accountId: number) {
1226 [Op.ne]: VideoState.LIVE_ENDED
1232 model: VideoChannelModel.unscoped(),
1240 return VideoModel.count(options)
1243 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1244 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1246 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1249 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1250 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1252 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1255 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1258 where: buildWhereIdOrUUID(id),
1262 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1265 return ModelCache.Instance.doCache({
1266 cacheType: 'load-video-immutable-id',
1273 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1275 const query: FindOptions = {
1282 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1285 return ModelCache.Instance.doCache({
1286 cacheType: 'load-video-immutable-url',
1293 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1294 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1296 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1299 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1300 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1302 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1305 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1306 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1308 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1311 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1312 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1314 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1317 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1318 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1320 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1323 static loadForGetAPI (parameters: {
1325 transaction?: Transaction
1327 }): Promise<MVideoDetails> {
1328 const { id, transaction, userId } = parameters
1329 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1331 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1334 static async getStats () {
1335 const totalLocalVideos = await VideoModel.count({
1341 let totalLocalVideoViews = await VideoModel.sum('views', {
1347 // Sequelize could return null...
1348 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1350 const { total: totalVideos } = await VideoModel.listForApi({
1353 sort: '-publishedAt',
1354 nsfw: buildNSFWFilter(),
1355 includeLocalVideos: true,
1361 totalLocalVideoViews,
1366 static incrementViews (id: number, views: number) {
1367 return VideoModel.increment('views', {
1375 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1376 const field = type === 'like'
1380 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1382 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1384 'WHERE "video"."id" = :videoId'
1386 return AccountVideoRateModel.sequelize.query(rawQuery, {
1388 replacements: { videoId, rateType: type },
1389 type: QueryTypes.UPDATE
1393 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1394 // Instances only share videos
1395 const query = 'SELECT 1 FROM "videoShare" ' +
1396 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1397 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1401 type: QueryTypes.SELECT as QueryTypes.SELECT,
1402 bind: { followerActorId, videoId },
1406 return VideoModel.sequelize.query(query, options)
1407 .then(results => results.length === 1)
1410 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1413 channelId: ofChannel.id
1418 return VideoModel.update({ support: ofChannel.support }, options)
1421 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1423 attributes: [ 'id' ],
1425 channelId: videoChannel.id
1429 return VideoModel.findAll(query)
1430 .then(videos => videos.map(v => v.id))
1433 // threshold corresponds to how many video the field should have to be returned
1434 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1435 const serverActor = await getServerActor()
1436 const followerActorId = serverActor.id
1438 const queryOptions: BuildVideosListQueryOptions = {
1439 attributes: [ `"${field}"` ],
1440 group: `GROUP BY "${field}"`,
1441 having: `HAVING COUNT("${field}") >= ${threshold}`,
1445 serverAccountId: serverActor.Account.id,
1447 includeLocalVideos: true
1450 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1452 return queryBuilder.queryVideoIds(queryOptions)
1453 .then(rows => rows.map(r => r[field]))
1456 static buildTrendingQuery (trendingDays: number) {
1460 model: VideoViewModel,
1464 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1470 private static async getAvailableForApi (
1471 options: BuildVideosListQueryOptions,
1473 ): Promise<ResultList<VideoModel>> {
1474 function getCount () {
1475 if (countVideos !== true) return Promise.resolve(undefined)
1477 const countOptions = Object.assign({}, options, { isCount: true })
1478 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1480 return queryBuilder.countVideoIds(countOptions)
1483 function getModels () {
1484 if (options.count === 0) return Promise.resolve([])
1486 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1488 return queryBuilder.queryVideos(options)
1491 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1500 return !!this.VideoBlacklist
1504 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1507 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1508 // We first transcode to WebTorrent format, so try this array first
1509 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1510 const file = fun(this.VideoFiles, file => file.resolution)
1512 return Object.assign(file, { Video: this })
1515 // No webtorrent files, try with streaming playlist files
1516 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1517 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1519 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1520 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1526 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1527 return this.getQualityFileBy(maxBy)
1530 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1531 return this.getQualityFileBy(minBy)
1534 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1535 if (Array.isArray(this.VideoFiles) === false) return undefined
1537 const file = this.VideoFiles.find(f => f.resolution === resolution)
1538 if (!file) return undefined
1540 return Object.assign(file, { Video: this })
1543 hasWebTorrentFiles () {
1544 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1547 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1548 thumbnail.videoId = this.id
1550 const savedThumbnail = await thumbnail.save({ transaction })
1552 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1554 // Already have this thumbnail, skip
1555 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1557 this.Thumbnails.push(savedThumbnail)
1561 if (Array.isArray(this.Thumbnails) === false) return undefined
1563 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1567 return !!this.getPreview()
1571 if (Array.isArray(this.Thumbnails) === false) return undefined
1573 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1577 return this.remote === false
1580 getWatchStaticPath () {
1581 return '/w/' + this.uuid
1584 getEmbedStaticPath () {
1585 return '/videos/embed/' + this.uuid
1588 getMiniatureStaticPath () {
1589 const thumbnail = this.getMiniature()
1590 if (!thumbnail) return null
1592 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1595 getPreviewStaticPath () {
1596 const preview = this.getPreview()
1597 if (!preview) return null
1599 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1600 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1603 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1604 return videoModelToFormattedJSON(this, options)
1607 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1608 return videoModelToFormattedDetailsJSON(this)
1611 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1612 let files: VideoFile[] = []
1614 if (Array.isArray(this.VideoFiles)) {
1615 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1616 files = files.concat(result)
1619 for (const p of (this.VideoStreamingPlaylists || [])) {
1620 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1621 files = files.concat(result)
1627 toActivityPubObject (this: MVideoAP): VideoObject {
1628 return videoModelToActivityPubObject(this)
1631 getTruncatedDescription () {
1632 if (!this.description) return null
1634 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1635 return peertubeTruncate(this.description, { length: maxLength })
1638 getMaxQualityResolution () {
1639 const file = this.getMaxQualityFile()
1640 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1641 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1643 return getVideoFileResolution(originalFilePath)
1646 getDescriptionAPIPath () {
1647 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1650 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1651 if (!this.VideoStreamingPlaylists) return undefined
1653 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1654 playlist.Video = this
1659 setHLSPlaylist (playlist: MStreamingPlaylist) {
1660 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1662 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1663 this.VideoStreamingPlaylists = toAdd
1667 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1668 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1672 removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1673 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1675 const promises: Promise<any>[] = [ remove(filePath) ]
1676 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1678 return Promise.all(promises)
1681 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1682 const directoryPath = getHLSDirectory(this, isRedundancy)
1684 await remove(directoryPath)
1686 if (isRedundancy !== true) {
1687 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1688 streamingPlaylistWithFiles.Video = this
1690 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1691 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1694 // Remove physical files and torrents
1696 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1702 if (this.isOwned()) return false
1704 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1707 hasPrivacyForFederation () {
1708 return isPrivacyForFederation(this.privacy)
1711 hasStateForFederation () {
1712 return isStateForFederation(this.state)
1715 isNewVideo (newPrivacy: VideoPrivacy) {
1716 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1720 return setAsUpdated('video', this.id)
1724 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1727 setPrivacy (newPrivacy: VideoPrivacy) {
1728 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1729 this.publishedAt = new Date()
1732 this.privacy = newPrivacy
1736 return this.privacy === VideoPrivacy.PRIVATE ||
1737 this.privacy === VideoPrivacy.UNLISTED ||
1738 this.privacy === VideoPrivacy.INTERNAL
1741 async publishIfNeededAndSave (t: Transaction) {
1742 if (this.state !== VideoState.PUBLISHED) {
1743 this.state = VideoState.PUBLISHED
1744 this.publishedAt = new Date()
1745 await this.save({ transaction: t })
1753 getBandwidthBits (videoFile: MVideoFile) {
1754 return Math.ceil((videoFile.size * 8) / this.duration)
1758 if (this.isOwned()) {
1760 WEBSERVER.URL + '/tracker/announce',
1761 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1765 return this.Trackers.map(t => t.url)