1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy, pick } 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 { v4 as uuidv4 } from 'uuid'
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 { VideoFile } from '@shared/models/videos/video-file.model'
35 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
36 import { VideoObject } from '../../../shared/models/activitypub/objects'
37 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
38 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
39 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
40 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
41 import { peertubeTruncate } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
56 import { logger } from '../../helpers/logger'
57 import { CONFIG } from '../../initializers/config'
70 } from '../../initializers/constants'
71 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 MChannelAccountDefault,
77 MStreamingPlaylistFilesVideo,
82 MVideoAccountLightBlacklistAllFiles,
87 MVideoFormattableDetails,
93 MVideoThumbnailBlacklist,
97 } from '../../types/models'
98 import { MThumbnail } from '../../types/models/video/thumbnail'
99 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
100 import { VideoAbuseModel } from '../abuse/video-abuse'
101 import { AccountModel } from '../account/account'
102 import { AccountVideoRateModel } from '../account/account-video-rate'
103 import { ActorImageModel } from '../account/actor-image'
104 import { UserModel } from '../account/user'
105 import { UserVideoHistoryModel } from '../account/user-video-history'
106 import { ActorModel } from '../activitypub/actor'
107 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
108 import { ServerModel } from '../server/server'
109 import { TrackerModel } from '../server/tracker'
110 import { VideoTrackerModel } from '../server/video-tracker'
111 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
112 import { ScheduleVideoUpdateModel } from './schedule-video-update'
113 import { TagModel } from './tag'
114 import { ThumbnailModel } from './thumbnail'
115 import { VideoBlacklistModel } from './video-blacklist'
116 import { VideoCaptionModel } from './video-caption'
117 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
118 import { VideoCommentModel } from './video-comment'
119 import { VideoFileModel } from './video-file'
121 videoFilesModelToFormattedJSON,
122 VideoFormattingJSONOptions,
123 videoModelToActivityPubObject,
124 videoModelToFormattedDetailsJSON,
125 videoModelToFormattedJSON
126 } from './video-format-utils'
127 import { VideoImportModel } from './video-import'
128 import { VideoLiveModel } from './video-live'
129 import { VideoPlaylistElementModel } from './video-playlist-element'
130 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
131 import { VideoShareModel } from './video-share'
132 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
133 import { VideoTagModel } from './video-tag'
134 import { VideoViewModel } from './video-view'
136 export enum ScopeNames {
137 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
139 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
140 WITH_TAGS = 'WITH_TAGS',
141 WITH_TRACKERS = 'WITH_TRACKERS',
142 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
143 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
144 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
145 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
146 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
147 WITH_USER_ID = 'WITH_USER_ID',
148 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
149 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
150 WITH_LIVE = 'WITH_LIVE'
153 export type ForAPIOptions = {
156 videoPlaylistId?: number
158 withAccountBlockerIds?: number[]
161 export type AvailableForListIDsOptions = {
162 serverAccountId: number
163 followerActorId: number
164 includeLocalVideos: boolean
166 attributesType?: 'none' | 'id' | 'all'
169 categoryOneOf?: number[]
171 licenceOneOf?: number[]
172 languageOneOf?: string[]
179 videoChannelId?: number
181 videoPlaylistId?: number
183 trendingDays?: number
184 user?: MUserAccountId
185 historyOfUser?: MUserId
187 baseWhere?: WhereOptions[]
191 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
192 attributes: [ 'id', 'url', 'uuid', 'remote' ]
194 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
195 const include: Includeable[] = [
197 model: VideoChannelModel.scope({
199 VideoChannelScopeNames.SUMMARY, {
201 withAccountBlockerIds: options.withAccountBlockerIds
208 attributes: [ 'type', 'filename' ],
209 model: ThumbnailModel,
214 const query: FindOptions = {}
224 if (options.videoPlaylistId) {
226 model: VideoPlaylistElementModel.unscoped(),
229 videoPlaylistId: options.videoPlaylistId
234 query.include = include
238 [ScopeNames.WITH_THUMBNAILS]: {
241 model: ThumbnailModel,
246 [ScopeNames.WITH_LIVE]: {
249 model: VideoLiveModel.unscoped(),
254 [ScopeNames.WITH_USER_ID]: {
257 attributes: [ 'accountId' ],
258 model: VideoChannelModel.unscoped(),
262 attributes: [ 'userId' ],
263 model: AccountModel.unscoped(),
270 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
273 model: VideoChannelModel.unscoped(),
278 exclude: [ 'privateKey', 'publicKey' ]
280 model: ActorModel.unscoped(),
284 attributes: [ 'host' ],
285 model: ServerModel.unscoped(),
289 model: ActorImageModel.unscoped(),
296 model: AccountModel.unscoped(),
300 model: ActorModel.unscoped(),
302 exclude: [ 'privateKey', 'publicKey' ]
307 attributes: [ 'host' ],
308 model: ServerModel.unscoped(),
312 model: ActorImageModel.unscoped(),
324 [ScopeNames.WITH_TAGS]: {
325 include: [ TagModel ]
327 [ScopeNames.WITH_TRACKERS]: {
330 attributes: [ 'id', 'url' ],
335 [ScopeNames.WITH_BLACKLISTED]: {
338 attributes: [ 'id', 'reason', 'unfederated' ],
339 model: VideoBlacklistModel,
344 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
345 let subInclude: any[] = []
347 if (withRedundancies === true) {
350 attributes: [ 'fileUrl' ],
351 model: VideoRedundancyModel.unscoped(),
360 model: VideoFileModel,
368 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
369 const subInclude: IncludeOptions[] = [
371 model: VideoFileModel,
376 if (withRedundancies === true) {
378 attributes: [ 'fileUrl' ],
379 model: VideoRedundancyModel.unscoped(),
387 model: VideoStreamingPlaylistModel.unscoped(),
395 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
398 model: ScheduleVideoUpdateModel.unscoped(),
403 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
407 attributes: [ 'currentTime' ],
408 model: UserVideoHistoryModel.unscoped(),
421 buildTrigramSearchIndex('video_name_trigram', 'name'),
423 { fields: [ 'createdAt' ] },
426 { name: 'publishedAt', order: 'DESC' },
427 { name: 'id', order: 'ASC' }
430 { fields: [ 'duration' ] },
433 { name: 'views', order: 'DESC' },
434 { name: 'id', order: 'ASC' }
437 { fields: [ 'channelId' ] },
439 fields: [ 'originallyPublishedAt' ],
441 originallyPublishedAt: {
447 fields: [ 'category' ], // We don't care videos with an unknown category
455 fields: [ 'licence' ], // We don't care videos with an unknown licence
463 fields: [ 'language' ], // We don't care videos with an unknown language
471 fields: [ 'nsfw' ], // Most of the videos are not NSFW
477 fields: [ 'remote' ], // Only index local videos
492 export class VideoModel extends Model {
495 @Default(DataType.UUIDV4)
497 @Column(DataType.UUID)
501 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
507 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
513 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
519 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
520 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
524 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
526 privacy: VideoPrivacy
529 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
535 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
536 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
541 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
542 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
546 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
581 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
582 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
587 commentsEnabled: boolean
591 downloadEnabled: boolean
595 waitTranscoding: boolean
599 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
610 @Default(DataType.NOW)
617 originallyPublishedAt: Date
619 @ForeignKey(() => VideoChannelModel)
623 @BelongsTo(() => VideoChannelModel, {
629 VideoChannel: VideoChannelModel
631 @BelongsToMany(() => TagModel, {
632 foreignKey: 'videoId',
633 through: () => VideoTagModel,
638 @BelongsToMany(() => TrackerModel, {
639 foreignKey: 'videoId',
640 through: () => VideoTrackerModel,
643 Trackers: TrackerModel[]
645 @HasMany(() => ThumbnailModel, {
653 Thumbnails: ThumbnailModel[]
655 @HasMany(() => VideoPlaylistElementModel, {
662 VideoPlaylistElements: VideoPlaylistElementModel[]
664 @HasMany(() => VideoAbuseModel, {
671 VideoAbuses: VideoAbuseModel[]
673 @HasMany(() => VideoFileModel, {
681 VideoFiles: VideoFileModel[]
683 @HasMany(() => VideoStreamingPlaylistModel, {
691 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
693 @HasMany(() => VideoShareModel, {
700 VideoShares: VideoShareModel[]
702 @HasMany(() => AccountVideoRateModel, {
709 AccountVideoRates: AccountVideoRateModel[]
711 @HasMany(() => VideoCommentModel, {
719 VideoComments: VideoCommentModel[]
721 @HasMany(() => VideoViewModel, {
728 VideoViews: VideoViewModel[]
730 @HasMany(() => UserVideoHistoryModel, {
737 UserVideoHistories: UserVideoHistoryModel[]
739 @HasOne(() => ScheduleVideoUpdateModel, {
746 ScheduleVideoUpdate: ScheduleVideoUpdateModel
748 @HasOne(() => VideoBlacklistModel, {
755 VideoBlacklist: VideoBlacklistModel
757 @HasOne(() => VideoLiveModel, {
764 VideoLive: VideoLiveModel
766 @HasOne(() => VideoImportModel, {
773 VideoImport: VideoImportModel
775 @HasMany(() => VideoCaptionModel, {
782 ['separate' as any]: true
784 VideoCaptions: VideoCaptionModel[]
787 static async sendDelete (instance: MVideoAccountLight, options) {
788 if (!instance.isOwned()) return undefined
790 // Lazy load channels
791 if (!instance.VideoChannel) {
792 instance.VideoChannel = await instance.$get('VideoChannel', {
797 transaction: options.transaction
798 }) as MChannelAccountDefault
801 return sendDeleteVideo(instance, options.transaction)
805 static async removeFiles (instance: VideoModel) {
806 const tasks: Promise<any>[] = []
808 logger.info('Removing files of video %s.', instance.url)
810 if (instance.isOwned()) {
811 if (!Array.isArray(instance.VideoFiles)) {
812 instance.VideoFiles = await instance.$get('VideoFiles')
815 // Remove physical files and torrents
816 instance.VideoFiles.forEach(file => {
817 tasks.push(instance.removeFile(file))
818 tasks.push(file.removeTorrent())
821 // Remove playlists file
822 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
823 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
826 for (const p of instance.VideoStreamingPlaylists) {
827 tasks.push(instance.removeStreamingPlaylistFiles(p))
831 // Do not wait video deletion because we could be in a transaction
834 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
841 static stopLiveIfNeeded (instance: VideoModel) {
842 if (!instance.isLive) return
844 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
846 return LiveManager.Instance.stopSessionOf(instance.id)
850 static invalidateCache (instance: VideoModel) {
851 ModelCache.Instance.invalidateCache('video', instance.id)
855 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
856 const tasks: Promise<any>[] = []
858 if (!Array.isArray(instance.VideoAbuses)) {
859 instance.VideoAbuses = await instance.$get('VideoAbuses')
861 if (instance.VideoAbuses.length === 0) return undefined
864 logger.info('Saving video abuses details of video %s.', instance.url)
866 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
867 const details = instance.toFormattedDetailsJSON()
869 for (const abuse of instance.VideoAbuses) {
870 abuse.deletedVideo = details
871 tasks.push(abuse.save({ transaction: options.transaction }))
876 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
882 static listLocal (): Promise<MVideo[]> {
889 return VideoModel.findAll(query)
892 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
893 function getRawQuery (select: string) {
894 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
895 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
896 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
897 'WHERE "Account"."actorId" = ' + actorId
898 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
899 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
900 'WHERE "VideoShare"."actorId" = ' + actorId
902 return `(${queryVideo}) UNION (${queryVideoShare})`
905 const rawQuery = getRawQuery('"Video"."id"')
906 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
912 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
915 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
917 [Op.or]: getPrivaciesForFederation()
921 attributes: [ 'language', 'fileUrl' ],
922 model: VideoCaptionModel.unscoped(),
926 attributes: [ 'id', 'url' ],
927 model: VideoShareModel.unscoped(),
929 // We only want videos shared by this actor
944 attributes: [ 'id', 'url' ],
945 model: ActorModel.unscoped()
950 model: VideoChannelModel.unscoped(),
954 attributes: [ 'name' ],
955 model: AccountModel.unscoped(),
959 attributes: [ 'id', 'url', 'followersUrl' ],
960 model: ActorModel.unscoped(),
966 attributes: [ 'id', 'url', 'followersUrl' ],
967 model: ActorModel.unscoped(),
973 model: VideoStreamingPlaylistModel.unscoped(),
977 model: VideoFileModel,
982 VideoLiveModel.unscoped(),
988 return Bluebird.all([
989 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
990 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
991 ]).then(([ rows, totals ]) => {
992 // totals: totalVideos + totalVideoShares
994 let totalVideoShares = 0
995 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
996 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
998 const total = totalVideos + totalVideoShares
1006 static async listPublishedLiveIds () {
1008 attributes: [ 'id' ],
1011 state: VideoState.PUBLISHED
1015 const result = await VideoModel.findAll(options)
1017 return result.map(v => v.id)
1020 static listUserVideosForApi (options: {
1027 const { accountId, start, count, sort, search } = options
1029 function buildBaseQuery (): FindOptions {
1033 order: getVideoSort(sort),
1036 model: VideoChannelModel,
1040 model: AccountModel,
1052 baseQuery = Object.assign(baseQuery, {
1055 [Op.iLike]: '%' + search + '%'
1064 const countQuery = buildBaseQuery()
1065 const findQuery = buildBaseQuery()
1067 const findScopes: (string | ScopeOptions)[] = [
1068 ScopeNames.WITH_SCHEDULED_UPDATE,
1069 ScopeNames.WITH_BLACKLISTED,
1070 ScopeNames.WITH_THUMBNAILS
1073 return Promise.all([
1074 VideoModel.count(countQuery),
1075 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1076 ]).then(([ count, rows ]) => {
1084 static async listForApi (options: {
1089 includeLocalVideos: boolean
1091 categoryOneOf?: number[]
1092 licenceOneOf?: number[]
1093 languageOneOf?: string[]
1094 tagsOneOf?: string[]
1095 tagsAllOf?: string[]
1096 filter?: VideoFilter
1098 videoChannelId?: number
1099 followerActorId?: number
1100 videoPlaylistId?: number
1101 trendingDays?: number
1102 user?: MUserAccountId
1103 historyOfUser?: MUserId
1104 countVideos?: boolean
1107 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1108 throw new Error('Try to filter all-local but no user has not the see all videos right')
1111 const trendingDays = options.sort.endsWith('trending')
1112 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1114 let trendingAlgorithm
1115 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1116 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1118 const serverActor = await getServerActor()
1120 // followerActorId === null has a meaning, so just check undefined
1121 const followerActorId = options.followerActorId !== undefined
1122 ? options.followerActorId
1125 const queryOptions = {
1126 start: options.start,
1127 count: options.count,
1130 serverAccountId: serverActor.Account.id,
1132 categoryOneOf: options.categoryOneOf,
1133 licenceOneOf: options.licenceOneOf,
1134 languageOneOf: options.languageOneOf,
1135 tagsOneOf: options.tagsOneOf,
1136 tagsAllOf: options.tagsAllOf,
1137 filter: options.filter,
1138 withFiles: options.withFiles,
1139 accountId: options.accountId,
1140 videoChannelId: options.videoChannelId,
1141 videoPlaylistId: options.videoPlaylistId,
1142 includeLocalVideos: options.includeLocalVideos,
1144 historyOfUser: options.historyOfUser,
1147 search: options.search
1150 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1153 static async searchAndPopulateAccountAndServer (options: {
1154 includeLocalVideos: boolean
1159 startDate?: string // ISO 8601
1160 endDate?: string // ISO 8601
1161 originallyPublishedStartDate?: string
1162 originallyPublishedEndDate?: string
1164 categoryOneOf?: number[]
1165 licenceOneOf?: number[]
1166 languageOneOf?: string[]
1167 tagsOneOf?: string[]
1168 tagsAllOf?: string[]
1169 durationMin?: number // seconds
1170 durationMax?: number // seconds
1171 user?: MUserAccountId
1172 filter?: VideoFilter
1174 const serverActor = await getServerActor()
1175 const queryOptions = {
1176 followerActorId: serverActor.id,
1177 serverAccountId: serverActor.Account.id,
1178 includeLocalVideos: options.includeLocalVideos,
1180 categoryOneOf: options.categoryOneOf,
1181 licenceOneOf: options.licenceOneOf,
1182 languageOneOf: options.languageOneOf,
1183 tagsOneOf: options.tagsOneOf,
1184 tagsAllOf: options.tagsAllOf,
1186 filter: options.filter,
1187 start: options.start,
1188 count: options.count,
1190 startDate: options.startDate,
1191 endDate: options.endDate,
1192 originallyPublishedStartDate: options.originallyPublishedStartDate,
1193 originallyPublishedEndDate: options.originallyPublishedEndDate,
1195 durationMin: options.durationMin,
1196 durationMax: options.durationMax,
1198 search: options.search
1201 return VideoModel.getAvailableForApi(queryOptions)
1204 static countLocalLives () {
1210 [Op.ne]: VideoState.LIVE_ENDED
1215 return VideoModel.count(options)
1218 static countVideosUploadedByUserSince (userId: number, since: Date) {
1222 model: VideoChannelModel.unscoped(),
1226 model: AccountModel.unscoped(),
1230 model: UserModel.unscoped(),
1248 return VideoModel.unscoped().count(options)
1251 static countLivesOfAccount (accountId: number) {
1257 [Op.ne]: VideoState.LIVE_ENDED
1263 model: VideoChannelModel.unscoped(),
1271 return VideoModel.count(options)
1274 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1275 const where = buildWhereIdOrUUID(id)
1281 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1284 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1285 const where = buildWhereIdOrUUID(id)
1291 return VideoModel.scope([
1292 ScopeNames.WITH_THUMBNAILS,
1293 ScopeNames.WITH_BLACKLISTED
1297 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1300 where: buildWhereIdOrUUID(id),
1304 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1307 return ModelCache.Instance.doCache({
1308 cacheType: 'load-video-immutable-id',
1315 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1316 const where = buildWhereIdOrUUID(id)
1322 return VideoModel.scope([
1323 ScopeNames.WITH_BLACKLISTED,
1324 ScopeNames.WITH_USER_ID
1328 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1329 const where = buildWhereIdOrUUID(id)
1332 attributes: [ 'id' ],
1337 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1340 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1341 const where = buildWhereIdOrUUID(id)
1349 return VideoModel.scope([
1350 ScopeNames.WITH_WEBTORRENT_FILES,
1351 ScopeNames.WITH_STREAMING_PLAYLISTS,
1352 ScopeNames.WITH_THUMBNAILS
1356 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1363 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1366 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1367 const query: FindOptions = {
1374 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1377 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1379 const query: FindOptions = {
1386 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1389 return ModelCache.Instance.doCache({
1390 cacheType: 'load-video-immutable-url',
1397 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1398 const query: FindOptions = {
1405 return VideoModel.scope([
1406 ScopeNames.WITH_ACCOUNT_DETAILS,
1407 ScopeNames.WITH_WEBTORRENT_FILES,
1408 ScopeNames.WITH_STREAMING_PLAYLISTS,
1409 ScopeNames.WITH_THUMBNAILS,
1410 ScopeNames.WITH_BLACKLISTED
1414 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1415 const where = buildWhereIdOrUUID(id)
1418 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1423 const scopes: (string | ScopeOptions)[] = [
1424 ScopeNames.WITH_TAGS,
1425 ScopeNames.WITH_BLACKLISTED,
1426 ScopeNames.WITH_ACCOUNT_DETAILS,
1427 ScopeNames.WITH_SCHEDULED_UPDATE,
1428 ScopeNames.WITH_WEBTORRENT_FILES,
1429 ScopeNames.WITH_STREAMING_PLAYLISTS,
1430 ScopeNames.WITH_THUMBNAILS,
1431 ScopeNames.WITH_LIVE
1435 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1443 static loadForGetAPI (parameters: {
1447 }): Promise<MVideoDetails> {
1448 const { id, t, userId } = parameters
1449 const where = buildWhereIdOrUUID(id)
1452 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1457 const scopes: (string | ScopeOptions)[] = [
1458 ScopeNames.WITH_TAGS,
1459 ScopeNames.WITH_BLACKLISTED,
1460 ScopeNames.WITH_ACCOUNT_DETAILS,
1461 ScopeNames.WITH_SCHEDULED_UPDATE,
1462 ScopeNames.WITH_THUMBNAILS,
1463 ScopeNames.WITH_LIVE,
1464 ScopeNames.WITH_TRACKERS,
1465 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1466 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1470 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1478 static async getStats () {
1479 const totalLocalVideos = await VideoModel.count({
1485 let totalLocalVideoViews = await VideoModel.sum('views', {
1491 // Sequelize could return null...
1492 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1494 const { total: totalVideos } = await VideoModel.listForApi({
1497 sort: '-publishedAt',
1498 nsfw: buildNSFWFilter(),
1499 includeLocalVideos: true,
1505 totalLocalVideoViews,
1510 static incrementViews (id: number, views: number) {
1511 return VideoModel.increment('views', {
1519 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1520 const field = type === 'like'
1524 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1526 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1528 'WHERE "video"."id" = :videoId'
1530 return AccountVideoRateModel.sequelize.query(rawQuery, {
1532 replacements: { videoId, rateType: type },
1533 type: QueryTypes.UPDATE
1537 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1538 // Instances only share videos
1539 const query = 'SELECT 1 FROM "videoShare" ' +
1540 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1541 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1545 type: QueryTypes.SELECT as QueryTypes.SELECT,
1546 bind: { followerActorId, videoId },
1550 return VideoModel.sequelize.query(query, options)
1551 .then(results => results.length === 1)
1554 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1557 channelId: videoChannel.id
1562 return VideoModel.update({ support: videoChannel.support }, options)
1565 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1567 attributes: [ 'id' ],
1569 channelId: videoChannel.id
1573 return VideoModel.findAll(query)
1574 .then(videos => videos.map(v => v.id))
1577 // threshold corresponds to how many video the field should have to be returned
1578 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1579 const serverActor = await getServerActor()
1580 const followerActorId = serverActor.id
1582 const queryOptions: BuildVideosQueryOptions = {
1583 attributes: [ `"${field}"` ],
1584 group: `GROUP BY "${field}"`,
1585 having: `HAVING COUNT("${field}") >= ${threshold}`,
1589 serverAccountId: serverActor.Account.id,
1591 includeLocalVideos: true
1594 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1596 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1597 .then(rows => rows.map(r => r[field]))
1600 static buildTrendingQuery (trendingDays: number) {
1604 model: VideoViewModel,
1608 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1614 private static async getAvailableForApi (
1615 options: BuildVideosQueryOptions,
1617 ): Promise<ResultList<VideoModel>> {
1618 function getCount () {
1619 if (countVideos !== true) return Promise.resolve(undefined)
1621 const countOptions = Object.assign({}, options, { isCount: true })
1622 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1624 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1625 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1628 function getModels () {
1629 if (options.count === 0) return Promise.resolve([])
1631 const { query, replacements, order } = buildListQuery(VideoModel, options)
1632 const queryModels = wrapForAPIResults(query, replacements, options, order)
1634 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1635 .then(rows => VideoModel.buildAPIResult(rows))
1638 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1646 private static buildAPIResult (rows: any[]) {
1647 const videosMemo: { [ id: number ]: VideoModel } = {}
1648 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1650 const thumbnailsDone = new Set<number>()
1651 const historyDone = new Set<number>()
1652 const videoFilesDone = new Set<number>()
1654 const videos: VideoModel[] = []
1656 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1657 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1658 const serverKeys = [ 'id', 'host' ]
1659 const videoFileKeys = [
1673 'videoStreamingPlaylistId'
1675 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1699 'originallyPublishedAt',
1704 const buildOpts = { raw: true }
1706 function buildActor (rowActor: any) {
1707 const avatarModel = rowActor.Avatar.id !== null
1708 ? new ActorImageModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1711 const serverModel = rowActor.Server.id !== null
1712 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1715 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1716 actorModel.Avatar = avatarModel
1717 actorModel.Server = serverModel
1722 for (const row of rows) {
1723 if (!videosMemo[row.id]) {
1725 const channel = row.VideoChannel
1726 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1727 channelModel.Actor = buildActor(channel.Actor)
1729 const account = row.VideoChannel.Account
1730 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1731 accountModel.Actor = buildActor(account.Actor)
1733 channelModel.Account = accountModel
1735 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1736 videoModel.VideoChannel = channelModel
1738 videoModel.UserVideoHistories = []
1739 videoModel.Thumbnails = []
1740 videoModel.VideoFiles = []
1741 videoModel.VideoStreamingPlaylists = []
1743 videosMemo[row.id] = videoModel
1744 // Don't take object value to have a sorted array
1745 videos.push(videoModel)
1748 const videoModel = videosMemo[row.id]
1750 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1751 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1752 videoModel.UserVideoHistories.push(historyModel)
1754 historyDone.add(row.userVideoHistory.id)
1757 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1758 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1759 videoModel.Thumbnails.push(thumbnailModel)
1761 thumbnailsDone.add(row.Thumbnails.id)
1764 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1765 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1766 videoModel.VideoFiles.push(videoFileModel)
1768 videoFilesDone.add(row.VideoFiles.id)
1771 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1772 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1773 streamingPlaylist.VideoFiles = []
1775 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1777 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1780 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1781 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1783 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1784 streamingPlaylist.VideoFiles.push(videoFileModel)
1786 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1793 static getCategoryLabel (id: number) {
1794 return VIDEO_CATEGORIES[id] || 'Misc'
1797 static getLicenceLabel (id: number) {
1798 return VIDEO_LICENCES[id] || 'Unknown'
1801 static getLanguageLabel (id: string) {
1802 return VIDEO_LANGUAGES[id] || 'Unknown'
1805 static getPrivacyLabel (id: number) {
1806 return VIDEO_PRIVACIES[id] || 'Unknown'
1809 static getStateLabel (id: number) {
1810 return VIDEO_STATES[id] || 'Unknown'
1814 return !!this.VideoBlacklist
1818 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1821 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1822 // We first transcode to WebTorrent format, so try this array first
1823 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1824 const file = fun(this.VideoFiles, file => file.resolution)
1826 return Object.assign(file, { Video: this })
1829 // No webtorrent files, try with streaming playlist files
1830 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1831 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1833 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1834 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1840 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1841 return this.getQualityFileBy(maxBy)
1844 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1845 return this.getQualityFileBy(minBy)
1848 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1849 if (Array.isArray(this.VideoFiles) === false) return undefined
1851 const file = this.VideoFiles.find(f => f.resolution === resolution)
1852 if (!file) return undefined
1854 return Object.assign(file, { Video: this })
1857 hasWebTorrentFiles () {
1858 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1861 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1862 thumbnail.videoId = this.id
1864 const savedThumbnail = await thumbnail.save({ transaction })
1866 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1868 // Already have this thumbnail, skip
1869 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1871 this.Thumbnails.push(savedThumbnail)
1874 generateThumbnailName () {
1875 return uuidv4() + '.jpg'
1879 if (Array.isArray(this.Thumbnails) === false) return undefined
1881 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1884 generatePreviewName () {
1885 return uuidv4() + '.jpg'
1889 return !!this.getPreview()
1893 if (Array.isArray(this.Thumbnails) === false) return undefined
1895 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1899 return this.remote === false
1902 getWatchStaticPath () {
1903 return '/videos/watch/' + this.uuid
1906 getEmbedStaticPath () {
1907 return '/videos/embed/' + this.uuid
1910 getMiniatureStaticPath () {
1911 const thumbnail = this.getMiniature()
1912 if (!thumbnail) return null
1914 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1917 getPreviewStaticPath () {
1918 const preview = this.getPreview()
1919 if (!preview) return null
1921 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1922 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1925 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1926 return videoModelToFormattedJSON(this, options)
1929 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1930 return videoModelToFormattedDetailsJSON(this)
1933 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1934 let files: VideoFile[] = []
1936 if (Array.isArray(this.VideoFiles)) {
1937 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1938 files = files.concat(result)
1941 for (const p of (this.VideoStreamingPlaylists || [])) {
1942 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1943 files = files.concat(result)
1949 toActivityPubObject (this: MVideoAP): VideoObject {
1950 return videoModelToActivityPubObject(this)
1953 getTruncatedDescription () {
1954 if (!this.description) return null
1956 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1957 return peertubeTruncate(this.description, { length: maxLength })
1960 getMaxQualityResolution () {
1961 const file = this.getMaxQualityFile()
1962 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1963 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1965 return getVideoFileResolution(originalFilePath)
1968 getDescriptionAPIPath () {
1969 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1972 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1973 if (!this.VideoStreamingPlaylists) return undefined
1975 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1976 playlist.Video = this
1981 setHLSPlaylist (playlist: MStreamingPlaylist) {
1982 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1984 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1985 this.VideoStreamingPlaylists = toAdd
1989 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1990 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1994 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1995 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1996 return remove(filePath)
1997 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2000 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2001 const directoryPath = getHLSDirectory(this, isRedundancy)
2003 await remove(directoryPath)
2005 if (isRedundancy !== true) {
2006 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2007 streamingPlaylistWithFiles.Video = this
2009 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2010 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2013 // Remove physical files and torrents
2015 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2021 if (this.isOwned()) return false
2023 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2026 hasPrivacyForFederation () {
2027 return isPrivacyForFederation(this.privacy)
2030 hasStateForFederation () {
2031 return isStateForFederation(this.state)
2034 isNewVideo (newPrivacy: VideoPrivacy) {
2035 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2039 this.changed('updatedAt', true)
2045 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2048 setPrivacy (newPrivacy: VideoPrivacy) {
2049 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2050 this.publishedAt = new Date()
2053 this.privacy = newPrivacy
2057 return this.privacy === VideoPrivacy.PRIVATE ||
2058 this.privacy === VideoPrivacy.UNLISTED ||
2059 this.privacy === VideoPrivacy.INTERNAL
2062 async publishIfNeededAndSave (t: Transaction) {
2063 if (this.state !== VideoState.PUBLISHED) {
2064 this.state = VideoState.PUBLISHED
2065 this.publishedAt = new Date()
2066 await this.save({ transaction: t })
2074 getBandwidthBits (videoFile: MVideoFile) {
2075 return Math.ceil((videoFile.size * 8) / this.duration)
2079 if (this.isOwned()) {
2081 WEBSERVER.URL + '/tracker/announce',
2082 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2086 return this.Trackers.map(t => t.url)