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-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'
47 isVideoDescriptionValid,
55 } from '../../helpers/custom-validators/videos'
56 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
57 import { logger } from '../../helpers/logger'
58 import { CONFIG } from '../../initializers/config'
59 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
60 import { sendDeleteVideo } from '../../lib/activitypub/send'
63 MChannelAccountDefault,
66 MStreamingPlaylistFilesVideo,
71 MVideoAccountLightBlacklistAllFiles,
76 MVideoFormattableDetails,
82 MVideoThumbnailBlacklist,
85 } from '../../types/models'
86 import { MThumbnail } from '../../types/models/video/thumbnail'
87 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
88 import { VideoAbuseModel } from '../abuse/video-abuse'
89 import { AccountModel } from '../account/account'
90 import { AccountVideoRateModel } from '../account/account-video-rate'
91 import { ActorModel } from '../actor/actor'
92 import { ActorImageModel } from '../actor/actor-image'
93 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
94 import { ServerModel } from '../server/server'
95 import { TrackerModel } from '../server/tracker'
96 import { VideoTrackerModel } from '../server/video-tracker'
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 { VideosModelGetQueryBuilder } from './sql/video-model-get-query-builder'
109 import { BuildVideosListQueryOptions, 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 { VideoLiveModel } from './video-live'
120 import { VideoPlaylistElementModel } from './video-playlist-element'
121 import { VideoShareModel } from './video-share'
122 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
123 import { VideoTagModel } from './video-tag'
124 import { VideoViewModel } from './video-view'
126 export enum ScopeNames {
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
134 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
135 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
136 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
139 export type ForAPIOptions = {
142 videoPlaylistId?: number
144 withAccountBlockerIds?: number[]
147 export type AvailableForListIDsOptions = {
148 serverAccountId: number
149 followerActorId: number
150 includeLocalVideos: boolean
152 attributesType?: 'none' | 'id' | 'all'
155 categoryOneOf?: number[]
157 licenceOneOf?: number[]
158 languageOneOf?: string[]
165 videoChannelId?: number
167 videoPlaylistId?: number
169 trendingDays?: number
170 user?: MUserAccountId
171 historyOfUser?: MUserId
173 baseWhere?: WhereOptions[]
177 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
178 attributes: [ 'id', 'url', 'uuid', 'remote' ]
180 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
181 const include: Includeable[] = [
183 model: VideoChannelModel.scope({
185 VideoChannelScopeNames.SUMMARY, {
187 withAccountBlockerIds: options.withAccountBlockerIds
194 attributes: [ 'type', 'filename' ],
195 model: ThumbnailModel,
200 const query: FindOptions = {}
210 if (options.videoPlaylistId) {
212 model: VideoPlaylistElementModel.unscoped(),
215 videoPlaylistId: options.videoPlaylistId
220 query.include = include
224 [ScopeNames.WITH_THUMBNAILS]: {
227 model: ThumbnailModel,
232 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
235 model: VideoChannelModel.unscoped(),
240 exclude: [ 'privateKey', 'publicKey' ]
242 model: ActorModel.unscoped(),
246 attributes: [ 'host' ],
247 model: ServerModel.unscoped(),
251 model: ActorImageModel.unscoped(),
258 model: AccountModel.unscoped(),
262 model: ActorModel.unscoped(),
264 exclude: [ 'privateKey', 'publicKey' ]
269 attributes: [ 'host' ],
270 model: ServerModel.unscoped(),
274 model: ActorImageModel.unscoped(),
286 [ScopeNames.WITH_TAGS]: {
287 include: [ TagModel ]
289 [ScopeNames.WITH_BLACKLISTED]: {
292 attributes: [ 'id', 'reason', 'unfederated' ],
293 model: VideoBlacklistModel,
298 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
299 let subInclude: any[] = []
301 if (withRedundancies === true) {
304 attributes: [ 'fileUrl' ],
305 model: VideoRedundancyModel.unscoped(),
314 model: VideoFileModel,
322 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
323 const subInclude: IncludeOptions[] = [
325 model: VideoFileModel,
330 if (withRedundancies === true) {
332 attributes: [ 'fileUrl' ],
333 model: VideoRedundancyModel.unscoped(),
341 model: VideoStreamingPlaylistModel.unscoped(),
349 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
352 model: ScheduleVideoUpdateModel.unscoped(),
357 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
361 attributes: [ 'currentTime' ],
362 model: UserVideoHistoryModel.unscoped(),
375 buildTrigramSearchIndex('video_name_trigram', 'name'),
377 { fields: [ 'createdAt' ] },
380 { name: 'publishedAt', order: 'DESC' },
381 { name: 'id', order: 'ASC' }
384 { fields: [ 'duration' ] },
387 { name: 'views', order: 'DESC' },
388 { name: 'id', order: 'ASC' }
391 { fields: [ 'channelId' ] },
393 fields: [ 'originallyPublishedAt' ],
395 originallyPublishedAt: {
401 fields: [ 'category' ], // We don't care videos with an unknown category
409 fields: [ 'licence' ], // We don't care videos with an unknown licence
417 fields: [ 'language' ], // We don't care videos with an unknown language
425 fields: [ 'nsfw' ], // Most of the videos are not NSFW
431 fields: [ 'remote' ], // Only index local videos
446 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
449 @Default(DataType.UUIDV4)
451 @Column(DataType.UUID)
455 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
461 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
467 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
473 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
474 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
478 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
480 privacy: VideoPrivacy
483 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
489 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
490 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
495 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
496 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
500 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
535 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
536 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
541 commentsEnabled: boolean
545 downloadEnabled: boolean
549 waitTranscoding: boolean
553 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
564 @Default(DataType.NOW)
571 originallyPublishedAt: Date
573 @ForeignKey(() => VideoChannelModel)
577 @BelongsTo(() => VideoChannelModel, {
583 VideoChannel: VideoChannelModel
585 @BelongsToMany(() => TagModel, {
586 foreignKey: 'videoId',
587 through: () => VideoTagModel,
592 @BelongsToMany(() => TrackerModel, {
593 foreignKey: 'videoId',
594 through: () => VideoTrackerModel,
597 Trackers: TrackerModel[]
599 @HasMany(() => ThumbnailModel, {
607 Thumbnails: ThumbnailModel[]
609 @HasMany(() => VideoPlaylistElementModel, {
616 VideoPlaylistElements: VideoPlaylistElementModel[]
618 @HasMany(() => VideoAbuseModel, {
625 VideoAbuses: VideoAbuseModel[]
627 @HasMany(() => VideoFileModel, {
635 VideoFiles: VideoFileModel[]
637 @HasMany(() => VideoStreamingPlaylistModel, {
645 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
647 @HasMany(() => VideoShareModel, {
654 VideoShares: VideoShareModel[]
656 @HasMany(() => AccountVideoRateModel, {
663 AccountVideoRates: AccountVideoRateModel[]
665 @HasMany(() => VideoCommentModel, {
673 VideoComments: VideoCommentModel[]
675 @HasMany(() => VideoViewModel, {
682 VideoViews: VideoViewModel[]
684 @HasMany(() => UserVideoHistoryModel, {
691 UserVideoHistories: UserVideoHistoryModel[]
693 @HasOne(() => ScheduleVideoUpdateModel, {
700 ScheduleVideoUpdate: ScheduleVideoUpdateModel
702 @HasOne(() => VideoBlacklistModel, {
709 VideoBlacklist: VideoBlacklistModel
711 @HasOne(() => VideoLiveModel, {
718 VideoLive: VideoLiveModel
720 @HasOne(() => VideoImportModel, {
727 VideoImport: VideoImportModel
729 @HasMany(() => VideoCaptionModel, {
736 ['separate' as any]: true
738 VideoCaptions: VideoCaptionModel[]
741 static async sendDelete (instance: MVideoAccountLight, options) {
742 if (!instance.isOwned()) return undefined
744 // Lazy load channels
745 if (!instance.VideoChannel) {
746 instance.VideoChannel = await instance.$get('VideoChannel', {
751 transaction: options.transaction
752 }) as MChannelAccountDefault
755 return sendDeleteVideo(instance, options.transaction)
759 static async removeFiles (instance: VideoModel) {
760 const tasks: Promise<any>[] = []
762 logger.info('Removing files of video %s.', instance.url)
764 if (instance.isOwned()) {
765 if (!Array.isArray(instance.VideoFiles)) {
766 instance.VideoFiles = await instance.$get('VideoFiles')
769 // Remove physical files and torrents
770 instance.VideoFiles.forEach(file => {
771 tasks.push(instance.removeFile(file))
772 tasks.push(file.removeTorrent())
775 // Remove playlists file
776 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
777 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
780 for (const p of instance.VideoStreamingPlaylists) {
781 tasks.push(instance.removeStreamingPlaylistFiles(p))
785 // Do not wait video deletion because we could be in a transaction
788 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
795 static stopLiveIfNeeded (instance: VideoModel) {
796 if (!instance.isLive) return
798 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
800 return LiveManager.Instance.stopSessionOf(instance.id)
804 static invalidateCache (instance: VideoModel) {
805 ModelCache.Instance.invalidateCache('video', instance.id)
809 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
810 const tasks: Promise<any>[] = []
812 if (!Array.isArray(instance.VideoAbuses)) {
813 instance.VideoAbuses = await instance.$get('VideoAbuses')
815 if (instance.VideoAbuses.length === 0) return undefined
818 logger.info('Saving video abuses details of video %s.', instance.url)
820 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
821 const details = instance.toFormattedDetailsJSON()
823 for (const abuse of instance.VideoAbuses) {
824 abuse.deletedVideo = details
825 tasks.push(abuse.save({ transaction: options.transaction }))
830 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
836 static listLocal (): Promise<MVideo[]> {
843 return VideoModel.findAll(query)
846 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
847 function getRawQuery (select: string) {
848 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
849 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
850 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
851 'WHERE "Account"."actorId" = ' + actorId
852 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
853 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
854 'WHERE "VideoShare"."actorId" = ' + actorId
856 return `(${queryVideo}) UNION (${queryVideoShare})`
859 const rawQuery = getRawQuery('"Video"."id"')
860 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
866 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
869 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
871 [Op.or]: getPrivaciesForFederation()
875 attributes: [ 'filename', 'language', 'fileUrl' ],
876 model: VideoCaptionModel.unscoped(),
880 attributes: [ 'id', 'url' ],
881 model: VideoShareModel.unscoped(),
883 // We only want videos shared by this actor
898 attributes: [ 'id', 'url' ],
899 model: ActorModel.unscoped()
904 model: VideoChannelModel.unscoped(),
908 attributes: [ 'name' ],
909 model: AccountModel.unscoped(),
913 attributes: [ 'id', 'url', 'followersUrl' ],
914 model: ActorModel.unscoped(),
920 attributes: [ 'id', 'url', 'followersUrl' ],
921 model: ActorModel.unscoped(),
927 model: VideoStreamingPlaylistModel.unscoped(),
931 model: VideoFileModel,
936 VideoLiveModel.unscoped(),
942 return Bluebird.all([
943 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
944 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
945 ]).then(([ rows, totals ]) => {
946 // totals: totalVideos + totalVideoShares
948 let totalVideoShares = 0
949 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
950 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
952 const total = totalVideos + totalVideoShares
960 static async listPublishedLiveUUIDs () {
962 attributes: [ 'uuid' ],
966 state: VideoState.PUBLISHED
970 const result = await VideoModel.findAll(options)
972 return result.map(v => v.uuid)
975 static listUserVideosForApi (options: {
983 const { accountId, start, count, sort, search, isLive } = options
985 function buildBaseQuery (): FindOptions {
986 const where: WhereOptions = {}
990 [Op.iLike]: '%' + search + '%'
995 where.isLive = isLive
1002 order: getVideoSort(sort),
1005 model: VideoChannelModel,
1009 model: AccountModel,
1023 const countQuery = buildBaseQuery()
1024 const findQuery = buildBaseQuery()
1026 const findScopes: (string | ScopeOptions)[] = [
1027 ScopeNames.WITH_SCHEDULED_UPDATE,
1028 ScopeNames.WITH_BLACKLISTED,
1029 ScopeNames.WITH_THUMBNAILS
1032 return Promise.all([
1033 VideoModel.count(countQuery),
1034 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1035 ]).then(([ count, rows ]) => {
1043 static async listForApi (options: {
1049 filter?: VideoFilter
1052 includeLocalVideos: boolean
1055 categoryOneOf?: number[]
1056 licenceOneOf?: number[]
1057 languageOneOf?: string[]
1058 tagsOneOf?: string[]
1059 tagsAllOf?: string[]
1062 videoChannelId?: number
1064 followerActorId?: number
1066 videoPlaylistId?: number
1068 trendingDays?: number
1070 user?: MUserAccountId
1071 historyOfUser?: MUserId
1073 countVideos?: boolean
1077 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1078 throw new Error('Try to filter all-local but no user has not the see all videos right')
1081 const trendingDays = options.sort.endsWith('trending')
1082 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1084 let trendingAlgorithm
1085 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1086 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1088 const serverActor = await getServerActor()
1090 // followerActorId === null has a meaning, so just check undefined
1091 const followerActorId = options.followerActorId !== undefined
1092 ? options.followerActorId
1095 const queryOptions = {
1096 start: options.start,
1097 count: options.count,
1100 serverAccountId: serverActor.Account.id,
1102 isLive: options.isLive,
1103 categoryOneOf: options.categoryOneOf,
1104 licenceOneOf: options.licenceOneOf,
1105 languageOneOf: options.languageOneOf,
1106 tagsOneOf: options.tagsOneOf,
1107 tagsAllOf: options.tagsAllOf,
1108 filter: options.filter,
1109 withFiles: options.withFiles,
1110 accountId: options.accountId,
1111 videoChannelId: options.videoChannelId,
1112 videoPlaylistId: options.videoPlaylistId,
1113 includeLocalVideos: options.includeLocalVideos,
1115 historyOfUser: options.historyOfUser,
1118 search: options.search
1121 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1124 static async searchAndPopulateAccountAndServer (options: {
1125 includeLocalVideos: boolean
1130 startDate?: string // ISO 8601
1131 endDate?: string // ISO 8601
1132 originallyPublishedStartDate?: string
1133 originallyPublishedEndDate?: string
1136 categoryOneOf?: number[]
1137 licenceOneOf?: number[]
1138 languageOneOf?: string[]
1139 tagsOneOf?: string[]
1140 tagsAllOf?: string[]
1141 durationMin?: number // seconds
1142 durationMax?: number // seconds
1143 user?: MUserAccountId
1144 filter?: VideoFilter
1146 const serverActor = await getServerActor()
1148 const queryOptions = {
1149 followerActorId: serverActor.id,
1150 serverAccountId: serverActor.Account.id,
1152 includeLocalVideos: options.includeLocalVideos,
1154 isLive: options.isLive,
1156 categoryOneOf: options.categoryOneOf,
1157 licenceOneOf: options.licenceOneOf,
1158 languageOneOf: options.languageOneOf,
1160 tagsOneOf: options.tagsOneOf,
1161 tagsAllOf: options.tagsAllOf,
1164 filter: options.filter,
1166 start: options.start,
1167 count: options.count,
1170 startDate: options.startDate,
1171 endDate: options.endDate,
1173 originallyPublishedStartDate: options.originallyPublishedStartDate,
1174 originallyPublishedEndDate: options.originallyPublishedEndDate,
1176 durationMin: options.durationMin,
1177 durationMax: options.durationMax,
1179 search: options.search
1182 return VideoModel.getAvailableForApi(queryOptions)
1185 static countLocalLives () {
1191 [Op.ne]: VideoState.LIVE_ENDED
1196 return VideoModel.count(options)
1199 static countVideosUploadedByUserSince (userId: number, since: Date) {
1203 model: VideoChannelModel.unscoped(),
1207 model: AccountModel.unscoped(),
1211 model: UserModel.unscoped(),
1229 return VideoModel.unscoped().count(options)
1232 static countLivesOfAccount (accountId: number) {
1238 [Op.ne]: VideoState.LIVE_ENDED
1244 model: VideoChannelModel.unscoped(),
1252 return VideoModel.count(options)
1255 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1256 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1258 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1261 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1262 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1264 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1267 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1270 where: buildWhereIdOrUUID(id),
1274 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1277 return ModelCache.Instance.doCache({
1278 cacheType: 'load-video-immutable-id',
1285 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1287 const query: FindOptions = {
1294 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1297 return ModelCache.Instance.doCache({
1298 cacheType: 'load-video-immutable-url',
1305 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1306 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1308 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1311 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1312 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1314 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1317 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1318 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1320 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1323 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1324 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1326 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1329 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1330 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1332 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1335 static loadForGetAPI (parameters: {
1337 transaction?: Transaction
1339 }): Promise<MVideoDetails> {
1340 const { id, transaction, userId } = parameters
1341 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1343 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1346 static async getStats () {
1347 const totalLocalVideos = await VideoModel.count({
1353 let totalLocalVideoViews = await VideoModel.sum('views', {
1359 // Sequelize could return null...
1360 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1362 const { total: totalVideos } = await VideoModel.listForApi({
1365 sort: '-publishedAt',
1366 nsfw: buildNSFWFilter(),
1367 includeLocalVideos: true,
1373 totalLocalVideoViews,
1378 static incrementViews (id: number, views: number) {
1379 return VideoModel.increment('views', {
1387 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1388 const field = type === 'like'
1392 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1394 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1396 'WHERE "video"."id" = :videoId'
1398 return AccountVideoRateModel.sequelize.query(rawQuery, {
1400 replacements: { videoId, rateType: type },
1401 type: QueryTypes.UPDATE
1405 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1406 // Instances only share videos
1407 const query = 'SELECT 1 FROM "videoShare" ' +
1408 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1409 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1413 type: QueryTypes.SELECT as QueryTypes.SELECT,
1414 bind: { followerActorId, videoId },
1418 return VideoModel.sequelize.query(query, options)
1419 .then(results => results.length === 1)
1422 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1425 channelId: ofChannel.id
1430 return VideoModel.update({ support: ofChannel.support }, options)
1433 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1435 attributes: [ 'id' ],
1437 channelId: videoChannel.id
1441 return VideoModel.findAll(query)
1442 .then(videos => videos.map(v => v.id))
1445 // threshold corresponds to how many video the field should have to be returned
1446 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1447 const serverActor = await getServerActor()
1448 const followerActorId = serverActor.id
1450 const queryOptions: BuildVideosListQueryOptions = {
1451 attributes: [ `"${field}"` ],
1452 group: `GROUP BY "${field}"`,
1453 having: `HAVING COUNT("${field}") >= ${threshold}`,
1457 serverAccountId: serverActor.Account.id,
1459 includeLocalVideos: true
1462 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1464 return queryBuilder.queryVideoIds(queryOptions)
1465 .then(rows => rows.map(r => r[field]))
1468 static buildTrendingQuery (trendingDays: number) {
1472 model: VideoViewModel,
1476 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1482 private static async getAvailableForApi (
1483 options: BuildVideosListQueryOptions,
1485 ): Promise<ResultList<VideoModel>> {
1486 function getCount () {
1487 if (countVideos !== true) return Promise.resolve(undefined)
1489 const countOptions = Object.assign({}, options, { isCount: true })
1490 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1492 return queryBuilder.countVideoIds(countOptions)
1495 function getModels () {
1496 if (options.count === 0) return Promise.resolve([])
1498 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1500 return queryBuilder.queryVideos(options)
1503 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1512 return !!this.VideoBlacklist
1516 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1519 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1520 // We first transcode to WebTorrent format, so try this array first
1521 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1522 const file = fun(this.VideoFiles, file => file.resolution)
1524 return Object.assign(file, { Video: this })
1527 // No webtorrent files, try with streaming playlist files
1528 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1529 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1531 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1532 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1538 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1539 return this.getQualityFileBy(maxBy)
1542 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1543 return this.getQualityFileBy(minBy)
1546 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1547 if (Array.isArray(this.VideoFiles) === false) return undefined
1549 const file = this.VideoFiles.find(f => f.resolution === resolution)
1550 if (!file) return undefined
1552 return Object.assign(file, { Video: this })
1555 hasWebTorrentFiles () {
1556 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1559 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1560 thumbnail.videoId = this.id
1562 const savedThumbnail = await thumbnail.save({ transaction })
1564 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1566 // Already have this thumbnail, skip
1567 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1569 this.Thumbnails.push(savedThumbnail)
1573 if (Array.isArray(this.Thumbnails) === false) return undefined
1575 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1579 return !!this.getPreview()
1583 if (Array.isArray(this.Thumbnails) === false) return undefined
1585 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1589 return this.remote === false
1592 getWatchStaticPath () {
1593 return '/w/' + this.uuid
1596 getEmbedStaticPath () {
1597 return '/videos/embed/' + this.uuid
1600 getMiniatureStaticPath () {
1601 const thumbnail = this.getMiniature()
1602 if (!thumbnail) return null
1604 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1607 getPreviewStaticPath () {
1608 const preview = this.getPreview()
1609 if (!preview) return null
1611 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1612 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1615 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1616 return videoModelToFormattedJSON(this, options)
1619 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1620 return videoModelToFormattedDetailsJSON(this)
1623 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1624 let files: VideoFile[] = []
1626 if (Array.isArray(this.VideoFiles)) {
1627 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1628 files = files.concat(result)
1631 for (const p of (this.VideoStreamingPlaylists || [])) {
1632 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1633 files = files.concat(result)
1639 toActivityPubObject (this: MVideoAP): VideoObject {
1640 return videoModelToActivityPubObject(this)
1643 getTruncatedDescription () {
1644 if (!this.description) return null
1646 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1647 return peertubeTruncate(this.description, { length: maxLength })
1650 getMaxQualityResolution () {
1651 const file = this.getMaxQualityFile()
1652 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1653 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1655 return getVideoFileResolution(originalFilePath)
1658 getDescriptionAPIPath () {
1659 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1662 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1663 if (!this.VideoStreamingPlaylists) return undefined
1665 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1666 playlist.Video = this
1671 setHLSPlaylist (playlist: MStreamingPlaylist) {
1672 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1674 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1675 this.VideoStreamingPlaylists = toAdd
1679 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1680 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1684 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1685 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1686 return remove(filePath)
1687 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1690 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1691 const directoryPath = getHLSDirectory(this, isRedundancy)
1693 await remove(directoryPath)
1695 if (isRedundancy !== true) {
1696 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1697 streamingPlaylistWithFiles.Video = this
1699 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1700 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1703 // Remove physical files and torrents
1705 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1711 if (this.isOwned()) return false
1713 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1716 hasPrivacyForFederation () {
1717 return isPrivacyForFederation(this.privacy)
1720 hasStateForFederation () {
1721 return isStateForFederation(this.state)
1724 isNewVideo (newPrivacy: VideoPrivacy) {
1725 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1729 return setAsUpdated('video', this.id)
1733 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1736 setPrivacy (newPrivacy: VideoPrivacy) {
1737 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1738 this.publishedAt = new Date()
1741 this.privacy = newPrivacy
1745 return this.privacy === VideoPrivacy.PRIVATE ||
1746 this.privacy === VideoPrivacy.UNLISTED ||
1747 this.privacy === VideoPrivacy.INTERNAL
1750 async publishIfNeededAndSave (t: Transaction) {
1751 if (this.state !== VideoState.PUBLISHED) {
1752 this.state = VideoState.PUBLISHED
1753 this.publishedAt = new Date()
1754 await this.save({ transaction: t })
1762 getBandwidthBits (videoFile: MVideoFile) {
1763 return Math.ceil((videoFile.size * 8) / this.duration)
1767 if (this.isOwned()) {
1769 WEBSERVER.URL + '/tracker/announce',
1770 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1774 return this.Trackers.map(t => t.url)