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.removeFile(file))
766 tasks.push(file.removeTorrent())
769 // Remove playlists file
770 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
771 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
774 for (const p of instance.VideoStreamingPlaylists) {
775 tasks.push(instance.removeStreamingPlaylistFiles(p))
779 // Do not wait video deletion because we could be in a transaction
782 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
789 static stopLiveIfNeeded (instance: VideoModel) {
790 if (!instance.isLive) return
792 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
794 LiveManager.Instance.stopSessionOf(instance.id)
798 static invalidateCache (instance: VideoModel) {
799 ModelCache.Instance.invalidateCache('video', instance.id)
803 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
804 const tasks: Promise<any>[] = []
806 if (!Array.isArray(instance.VideoAbuses)) {
807 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
809 if (instance.VideoAbuses.length === 0) return undefined
812 logger.info('Saving video abuses details of video %s.', instance.url)
814 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
815 const details = instance.toFormattedDetailsJSON()
817 for (const abuse of instance.VideoAbuses) {
818 abuse.deletedVideo = details
819 tasks.push(abuse.save({ transaction: options.transaction }))
822 await Promise.all(tasks)
825 static listLocal (): Promise<MVideo[]> {
832 return VideoModel.findAll(query)
835 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
836 function getRawQuery (select: string) {
837 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
838 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
839 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
840 'WHERE "Account"."actorId" = ' + actorId
841 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
842 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
843 'WHERE "VideoShare"."actorId" = ' + actorId
845 return `(${queryVideo}) UNION (${queryVideoShare})`
848 const rawQuery = getRawQuery('"Video"."id"')
849 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
855 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
858 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
860 [Op.or]: getPrivaciesForFederation()
864 attributes: [ 'filename', 'language', 'fileUrl' ],
865 model: VideoCaptionModel.unscoped(),
869 attributes: [ 'id', 'url' ],
870 model: VideoShareModel.unscoped(),
872 // We only want videos shared by this actor
887 attributes: [ 'id', 'url' ],
888 model: ActorModel.unscoped()
893 model: VideoChannelModel.unscoped(),
897 attributes: [ 'name' ],
898 model: AccountModel.unscoped(),
902 attributes: [ 'id', 'url', 'followersUrl' ],
903 model: ActorModel.unscoped(),
909 attributes: [ 'id', 'url', 'followersUrl' ],
910 model: ActorModel.unscoped(),
916 model: VideoStreamingPlaylistModel.unscoped(),
920 model: VideoFileModel,
925 VideoLiveModel.unscoped(),
931 return Bluebird.all([
932 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
933 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
934 ]).then(([ rows, totals ]) => {
935 // totals: totalVideos + totalVideoShares
937 let totalVideoShares = 0
938 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
939 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
941 const total = totalVideos + totalVideoShares
949 static async listPublishedLiveUUIDs () {
951 attributes: [ 'uuid' ],
955 state: VideoState.PUBLISHED
959 const result = await VideoModel.findAll(options)
961 return result.map(v => v.uuid)
964 static listUserVideosForApi (options: {
972 const { accountId, start, count, sort, search, isLive } = options
974 function buildBaseQuery (): FindOptions {
975 const where: WhereOptions = {}
979 [Op.iLike]: '%' + search + '%'
984 where.isLive = isLive
991 order: getVideoSort(sort),
994 model: VideoChannelModel,
1012 const countQuery = buildBaseQuery()
1013 const findQuery = buildBaseQuery()
1015 const findScopes: (string | ScopeOptions)[] = [
1016 ScopeNames.WITH_SCHEDULED_UPDATE,
1017 ScopeNames.WITH_BLACKLISTED,
1018 ScopeNames.WITH_THUMBNAILS
1021 return Promise.all([
1022 VideoModel.count(countQuery),
1023 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1024 ]).then(([ count, rows ]) => {
1032 static async listForApi (options: {
1038 filter?: VideoFilter
1041 includeLocalVideos: boolean
1044 categoryOneOf?: number[]
1045 licenceOneOf?: number[]
1046 languageOneOf?: string[]
1047 tagsOneOf?: string[]
1048 tagsAllOf?: string[]
1051 videoChannelId?: number
1053 followerActorId?: number
1055 videoPlaylistId?: number
1057 trendingDays?: number
1059 user?: MUserAccountId
1060 historyOfUser?: MUserId
1062 countVideos?: boolean
1066 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1067 throw new Error('Try to filter all-local but no user has not the see all videos right')
1070 const trendingDays = options.sort.endsWith('trending')
1071 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1073 let trendingAlgorithm
1074 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1075 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1077 const serverActor = await getServerActor()
1079 // followerActorId === null has a meaning, so just check undefined
1080 const followerActorId = options.followerActorId !== undefined
1081 ? options.followerActorId
1084 const queryOptions = {
1085 start: options.start,
1086 count: options.count,
1089 serverAccountId: serverActor.Account.id,
1091 isLive: options.isLive,
1092 categoryOneOf: options.categoryOneOf,
1093 licenceOneOf: options.licenceOneOf,
1094 languageOneOf: options.languageOneOf,
1095 tagsOneOf: options.tagsOneOf,
1096 tagsAllOf: options.tagsAllOf,
1097 filter: options.filter,
1098 withFiles: options.withFiles,
1099 accountId: options.accountId,
1100 videoChannelId: options.videoChannelId,
1101 videoPlaylistId: options.videoPlaylistId,
1102 includeLocalVideos: options.includeLocalVideos,
1104 historyOfUser: options.historyOfUser,
1107 search: options.search
1110 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1113 static async searchAndPopulateAccountAndServer (options: {
1114 includeLocalVideos: boolean
1119 startDate?: string // ISO 8601
1120 endDate?: string // ISO 8601
1121 originallyPublishedStartDate?: string
1122 originallyPublishedEndDate?: string
1125 categoryOneOf?: number[]
1126 licenceOneOf?: number[]
1127 languageOneOf?: string[]
1128 tagsOneOf?: string[]
1129 tagsAllOf?: string[]
1130 durationMin?: number // seconds
1131 durationMax?: number // seconds
1132 user?: MUserAccountId
1133 filter?: VideoFilter
1135 const serverActor = await getServerActor()
1137 const queryOptions = {
1138 followerActorId: serverActor.id,
1139 serverAccountId: serverActor.Account.id,
1141 includeLocalVideos: options.includeLocalVideos,
1143 isLive: options.isLive,
1145 categoryOneOf: options.categoryOneOf,
1146 licenceOneOf: options.licenceOneOf,
1147 languageOneOf: options.languageOneOf,
1149 tagsOneOf: options.tagsOneOf,
1150 tagsAllOf: options.tagsAllOf,
1153 filter: options.filter,
1155 start: options.start,
1156 count: options.count,
1159 startDate: options.startDate,
1160 endDate: options.endDate,
1162 originallyPublishedStartDate: options.originallyPublishedStartDate,
1163 originallyPublishedEndDate: options.originallyPublishedEndDate,
1165 durationMin: options.durationMin,
1166 durationMax: options.durationMax,
1168 search: options.search
1171 return VideoModel.getAvailableForApi(queryOptions)
1174 static countLocalLives () {
1180 [Op.ne]: VideoState.LIVE_ENDED
1185 return VideoModel.count(options)
1188 static countVideosUploadedByUserSince (userId: number, since: Date) {
1192 model: VideoChannelModel.unscoped(),
1196 model: AccountModel.unscoped(),
1200 model: UserModel.unscoped(),
1218 return VideoModel.unscoped().count(options)
1221 static countLivesOfAccount (accountId: number) {
1227 [Op.ne]: VideoState.LIVE_ENDED
1233 model: VideoChannelModel.unscoped(),
1241 return VideoModel.count(options)
1244 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1245 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1247 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1250 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1251 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1253 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1256 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1259 where: buildWhereIdOrUUID(id),
1263 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1266 return ModelCache.Instance.doCache({
1267 cacheType: 'load-video-immutable-id',
1274 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1276 const query: FindOptions = {
1283 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1286 return ModelCache.Instance.doCache({
1287 cacheType: 'load-video-immutable-url',
1294 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1295 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1297 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1300 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1301 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1303 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1306 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1307 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1309 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1312 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1313 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1315 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1318 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1319 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1321 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1324 static loadForGetAPI (parameters: {
1326 transaction?: Transaction
1328 }): Promise<MVideoDetails> {
1329 const { id, transaction, userId } = parameters
1330 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1332 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1335 static async getStats () {
1336 const totalLocalVideos = await VideoModel.count({
1342 let totalLocalVideoViews = await VideoModel.sum('views', {
1348 // Sequelize could return null...
1349 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1351 const { total: totalVideos } = await VideoModel.listForApi({
1354 sort: '-publishedAt',
1355 nsfw: buildNSFWFilter(),
1356 includeLocalVideos: true,
1362 totalLocalVideoViews,
1367 static incrementViews (id: number, views: number) {
1368 return VideoModel.increment('views', {
1376 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1377 const field = type === 'like'
1381 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1383 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1385 'WHERE "video"."id" = :videoId'
1387 return AccountVideoRateModel.sequelize.query(rawQuery, {
1389 replacements: { videoId, rateType: type },
1390 type: QueryTypes.UPDATE
1394 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1395 // Instances only share videos
1396 const query = 'SELECT 1 FROM "videoShare" ' +
1397 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1398 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1402 type: QueryTypes.SELECT as QueryTypes.SELECT,
1403 bind: { followerActorId, videoId },
1407 return VideoModel.sequelize.query(query, options)
1408 .then(results => results.length === 1)
1411 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1414 channelId: ofChannel.id
1419 return VideoModel.update({ support: ofChannel.support }, options)
1422 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1424 attributes: [ 'id' ],
1426 channelId: videoChannel.id
1430 return VideoModel.findAll(query)
1431 .then(videos => videos.map(v => v.id))
1434 // threshold corresponds to how many video the field should have to be returned
1435 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1436 const serverActor = await getServerActor()
1437 const followerActorId = serverActor.id
1439 const queryOptions: BuildVideosListQueryOptions = {
1440 attributes: [ `"${field}"` ],
1441 group: `GROUP BY "${field}"`,
1442 having: `HAVING COUNT("${field}") >= ${threshold}`,
1446 serverAccountId: serverActor.Account.id,
1448 includeLocalVideos: true
1451 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1453 return queryBuilder.queryVideoIds(queryOptions)
1454 .then(rows => rows.map(r => r[field]))
1457 static buildTrendingQuery (trendingDays: number) {
1461 model: VideoViewModel,
1465 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1471 private static async getAvailableForApi (
1472 options: BuildVideosListQueryOptions,
1474 ): Promise<ResultList<VideoModel>> {
1475 function getCount () {
1476 if (countVideos !== true) return Promise.resolve(undefined)
1478 const countOptions = Object.assign({}, options, { isCount: true })
1479 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1481 return queryBuilder.countVideoIds(countOptions)
1484 function getModels () {
1485 if (options.count === 0) return Promise.resolve([])
1487 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1489 return queryBuilder.queryVideos(options)
1492 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1501 return !!this.VideoBlacklist
1505 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1508 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1509 // We first transcode to WebTorrent format, so try this array first
1510 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1511 const file = fun(this.VideoFiles, file => file.resolution)
1513 return Object.assign(file, { Video: this })
1516 // No webtorrent files, try with streaming playlist files
1517 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1518 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1520 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1521 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1527 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1528 return this.getQualityFileBy(maxBy)
1531 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1532 return this.getQualityFileBy(minBy)
1535 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1536 if (Array.isArray(this.VideoFiles) === false) return undefined
1538 const file = this.VideoFiles.find(f => f.resolution === resolution)
1539 if (!file) return undefined
1541 return Object.assign(file, { Video: this })
1544 hasWebTorrentFiles () {
1545 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1548 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1549 thumbnail.videoId = this.id
1551 const savedThumbnail = await thumbnail.save({ transaction })
1553 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1555 // Already have this thumbnail, skip
1556 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1558 this.Thumbnails.push(savedThumbnail)
1562 if (Array.isArray(this.Thumbnails) === false) return undefined
1564 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1568 return !!this.getPreview()
1572 if (Array.isArray(this.Thumbnails) === false) return undefined
1574 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1578 return this.remote === false
1581 getWatchStaticPath () {
1582 return '/w/' + this.uuid
1585 getEmbedStaticPath () {
1586 return '/videos/embed/' + this.uuid
1589 getMiniatureStaticPath () {
1590 const thumbnail = this.getMiniature()
1591 if (!thumbnail) return null
1593 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1596 getPreviewStaticPath () {
1597 const preview = this.getPreview()
1598 if (!preview) return null
1600 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1601 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1604 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1605 return videoModelToFormattedJSON(this, options)
1608 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1609 return videoModelToFormattedDetailsJSON(this)
1612 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1613 let files: VideoFile[] = []
1615 if (Array.isArray(this.VideoFiles)) {
1616 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1617 files = files.concat(result)
1620 for (const p of (this.VideoStreamingPlaylists || [])) {
1621 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1622 files = files.concat(result)
1628 toActivityPubObject (this: MVideoAP): VideoObject {
1629 return videoModelToActivityPubObject(this)
1632 getTruncatedDescription () {
1633 if (!this.description) return null
1635 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1636 return peertubeTruncate(this.description, { length: maxLength })
1639 getMaxQualityResolution () {
1640 const file = this.getMaxQualityFile()
1641 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1642 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1644 return getVideoFileResolution(originalFilePath)
1647 getDescriptionAPIPath () {
1648 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1651 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1652 if (!this.VideoStreamingPlaylists) return undefined
1654 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1655 playlist.Video = this
1660 setHLSPlaylist (playlist: MStreamingPlaylist) {
1661 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1663 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1664 this.VideoStreamingPlaylists = toAdd
1668 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1669 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1673 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1674 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1675 return remove(filePath)
1676 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1679 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1680 const directoryPath = getHLSDirectory(this, isRedundancy)
1682 await remove(directoryPath)
1684 if (isRedundancy !== true) {
1685 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1686 streamingPlaylistWithFiles.Video = this
1688 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1689 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1692 // Remove physical files and torrents
1694 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1700 if (this.isOwned()) return false
1702 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1705 hasPrivacyForFederation () {
1706 return isPrivacyForFederation(this.privacy)
1709 hasStateForFederation () {
1710 return isStateForFederation(this.state)
1713 isNewVideo (newPrivacy: VideoPrivacy) {
1714 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1718 return setAsUpdated('video', this.id)
1722 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1725 setPrivacy (newPrivacy: VideoPrivacy) {
1726 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1727 this.publishedAt = new Date()
1730 this.privacy = newPrivacy
1734 return this.privacy === VideoPrivacy.PRIVATE ||
1735 this.privacy === VideoPrivacy.UNLISTED ||
1736 this.privacy === VideoPrivacy.INTERNAL
1739 async publishIfNeededAndSave (t: Transaction) {
1740 if (this.state !== VideoState.PUBLISHED) {
1741 this.state = VideoState.PUBLISHED
1742 this.publishedAt = new Date()
1743 await this.save({ transaction: t })
1751 getBandwidthBits (videoFile: MVideoFile) {
1752 return Math.ceil((videoFile.size * 8) / this.duration)
1756 if (this.isOwned()) {
1758 WEBSERVER.URL + '/tracker/announce',
1759 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1763 return this.Trackers.map(t => t.url)