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 { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
29 import { LiveManager } from '@server/lib/live-manager'
30 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
31 import { getServerActor } from '@server/models/application/application'
32 import { ModelCache } from '@server/models/model-cache'
33 import { VideoFile } from '@shared/models/videos/video-file.model'
34 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
35 import { VideoObject } from '../../../shared/models/activitypub/objects'
36 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
37 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
38 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
39 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
40 import { peertubeTruncate } from '../../helpers/core-utils'
41 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
42 import { isBooleanValid } from '../../helpers/custom-validators/misc'
45 isVideoDescriptionValid,
53 } from '../../helpers/custom-validators/videos'
54 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
55 import { logger } from '../../helpers/logger'
56 import { CONFIG } from '../../initializers/config'
69 } from '../../initializers/constants'
70 import { sendDeleteVideo } from '../../lib/activitypub/send'
73 MChannelAccountDefault,
76 MStreamingPlaylistFilesVideo,
81 MVideoAccountLightBlacklistAllFiles,
86 MVideoFormattableDetails,
92 MVideoThumbnailBlacklist,
96 } from '../../types/models'
97 import { MThumbnail } from '../../types/models/video/thumbnail'
98 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
99 import { VideoAbuseModel } from '../abuse/video-abuse'
100 import { AccountModel } from '../account/account'
101 import { AccountVideoRateModel } from '../account/account-video-rate'
102 import { ActorImageModel } from '../account/actor-image'
103 import { UserModel } from '../account/user'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { ActorModel } from '../activitypub/actor'
106 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 import { ServerModel } from '../server/server'
108 import { TrackerModel } from '../server/tracker'
109 import { VideoTrackerModel } from '../server/video-tracker'
110 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
111 import { ScheduleVideoUpdateModel } from './schedule-video-update'
112 import { TagModel } from './tag'
113 import { ThumbnailModel } from './thumbnail'
114 import { VideoBlacklistModel } from './video-blacklist'
115 import { VideoCaptionModel } from './video-caption'
116 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
117 import { VideoCommentModel } from './video-comment'
118 import { VideoFileModel } from './video-file'
120 videoFilesModelToFormattedJSON,
121 VideoFormattingJSONOptions,
122 videoModelToActivityPubObject,
123 videoModelToFormattedDetailsJSON,
124 videoModelToFormattedJSON
125 } from './video-format-utils'
126 import { VideoImportModel } from './video-import'
127 import { VideoLiveModel } from './video-live'
128 import { VideoPlaylistElementModel } from './video-playlist-element'
129 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
130 import { VideoShareModel } from './video-share'
131 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
132 import { VideoTagModel } from './video-tag'
133 import { VideoViewModel } from './video-view'
135 export enum ScopeNames {
136 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
138 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
139 WITH_TAGS = 'WITH_TAGS',
140 WITH_TRACKERS = 'WITH_TRACKERS',
141 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
142 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
143 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
144 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
145 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
146 WITH_USER_ID = 'WITH_USER_ID',
147 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
148 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
149 WITH_LIVE = 'WITH_LIVE'
152 export type ForAPIOptions = {
155 videoPlaylistId?: number
157 withAccountBlockerIds?: number[]
160 export type AvailableForListIDsOptions = {
161 serverAccountId: number
162 followerActorId: number
163 includeLocalVideos: boolean
165 attributesType?: 'none' | 'id' | 'all'
168 categoryOneOf?: number[]
170 licenceOneOf?: number[]
171 languageOneOf?: string[]
178 videoChannelId?: number
180 videoPlaylistId?: number
182 trendingDays?: number
183 user?: MUserAccountId
184 historyOfUser?: MUserId
186 baseWhere?: WhereOptions[]
190 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
191 attributes: [ 'id', 'url', 'uuid', 'remote' ]
193 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
194 const include: Includeable[] = [
196 model: VideoChannelModel.scope({
198 VideoChannelScopeNames.SUMMARY, {
200 withAccountBlockerIds: options.withAccountBlockerIds
207 attributes: [ 'type', 'filename' ],
208 model: ThumbnailModel,
213 const query: FindOptions = {}
223 if (options.videoPlaylistId) {
225 model: VideoPlaylistElementModel.unscoped(),
228 videoPlaylistId: options.videoPlaylistId
233 query.include = include
237 [ScopeNames.WITH_THUMBNAILS]: {
240 model: ThumbnailModel,
245 [ScopeNames.WITH_LIVE]: {
248 model: VideoLiveModel.unscoped(),
253 [ScopeNames.WITH_USER_ID]: {
256 attributes: [ 'accountId' ],
257 model: VideoChannelModel.unscoped(),
261 attributes: [ 'userId' ],
262 model: AccountModel.unscoped(),
269 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
272 model: VideoChannelModel.unscoped(),
277 exclude: [ 'privateKey', 'publicKey' ]
279 model: ActorModel.unscoped(),
283 attributes: [ 'host' ],
284 model: ServerModel.unscoped(),
288 model: ActorImageModel.unscoped(),
295 model: AccountModel.unscoped(),
299 model: ActorModel.unscoped(),
301 exclude: [ 'privateKey', 'publicKey' ]
306 attributes: [ 'host' ],
307 model: ServerModel.unscoped(),
311 model: ActorImageModel.unscoped(),
323 [ScopeNames.WITH_TAGS]: {
324 include: [ TagModel ]
326 [ScopeNames.WITH_TRACKERS]: {
329 attributes: [ 'id', 'url' ],
334 [ScopeNames.WITH_BLACKLISTED]: {
337 attributes: [ 'id', 'reason', 'unfederated' ],
338 model: VideoBlacklistModel,
343 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
344 let subInclude: any[] = []
346 if (withRedundancies === true) {
349 attributes: [ 'fileUrl' ],
350 model: VideoRedundancyModel.unscoped(),
359 model: VideoFileModel,
367 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
368 const subInclude: IncludeOptions[] = [
370 model: VideoFileModel,
375 if (withRedundancies === true) {
377 attributes: [ 'fileUrl' ],
378 model: VideoRedundancyModel.unscoped(),
386 model: VideoStreamingPlaylistModel.unscoped(),
394 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
397 model: ScheduleVideoUpdateModel.unscoped(),
402 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
406 attributes: [ 'currentTime' ],
407 model: UserVideoHistoryModel.unscoped(),
420 buildTrigramSearchIndex('video_name_trigram', 'name'),
422 { fields: [ 'createdAt' ] },
425 { name: 'publishedAt', order: 'DESC' },
426 { name: 'id', order: 'ASC' }
429 { fields: [ 'duration' ] },
432 { name: 'views', order: 'DESC' },
433 { name: 'id', order: 'ASC' }
436 { fields: [ 'channelId' ] },
438 fields: [ 'originallyPublishedAt' ],
440 originallyPublishedAt: {
446 fields: [ 'category' ], // We don't care videos with an unknown category
454 fields: [ 'licence' ], // We don't care videos with an unknown licence
462 fields: [ 'language' ], // We don't care videos with an unknown language
470 fields: [ 'nsfw' ], // Most of the videos are not NSFW
476 fields: [ 'remote' ], // Only index local videos
491 export class VideoModel extends Model {
494 @Default(DataType.UUIDV4)
496 @Column(DataType.UUID)
500 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
506 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
512 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
518 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
519 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
523 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
525 privacy: VideoPrivacy
528 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
534 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
535 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
540 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
541 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
545 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
580 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
581 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
586 commentsEnabled: boolean
590 downloadEnabled: boolean
594 waitTranscoding: boolean
598 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
609 @Default(DataType.NOW)
616 originallyPublishedAt: Date
618 @ForeignKey(() => VideoChannelModel)
622 @BelongsTo(() => VideoChannelModel, {
628 VideoChannel: VideoChannelModel
630 @BelongsToMany(() => TagModel, {
631 foreignKey: 'videoId',
632 through: () => VideoTagModel,
637 @BelongsToMany(() => TrackerModel, {
638 foreignKey: 'videoId',
639 through: () => VideoTrackerModel,
642 Trackers: TrackerModel[]
644 @HasMany(() => ThumbnailModel, {
652 Thumbnails: ThumbnailModel[]
654 @HasMany(() => VideoPlaylistElementModel, {
661 VideoPlaylistElements: VideoPlaylistElementModel[]
663 @HasMany(() => VideoAbuseModel, {
670 VideoAbuses: VideoAbuseModel[]
672 @HasMany(() => VideoFileModel, {
680 VideoFiles: VideoFileModel[]
682 @HasMany(() => VideoStreamingPlaylistModel, {
690 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
692 @HasMany(() => VideoShareModel, {
699 VideoShares: VideoShareModel[]
701 @HasMany(() => AccountVideoRateModel, {
708 AccountVideoRates: AccountVideoRateModel[]
710 @HasMany(() => VideoCommentModel, {
718 VideoComments: VideoCommentModel[]
720 @HasMany(() => VideoViewModel, {
727 VideoViews: VideoViewModel[]
729 @HasMany(() => UserVideoHistoryModel, {
736 UserVideoHistories: UserVideoHistoryModel[]
738 @HasOne(() => ScheduleVideoUpdateModel, {
745 ScheduleVideoUpdate: ScheduleVideoUpdateModel
747 @HasOne(() => VideoBlacklistModel, {
754 VideoBlacklist: VideoBlacklistModel
756 @HasOne(() => VideoLiveModel, {
763 VideoLive: VideoLiveModel
765 @HasOne(() => VideoImportModel, {
772 VideoImport: VideoImportModel
774 @HasMany(() => VideoCaptionModel, {
781 ['separate' as any]: true
783 VideoCaptions: VideoCaptionModel[]
786 static async sendDelete (instance: MVideoAccountLight, options) {
787 if (!instance.isOwned()) return undefined
789 // Lazy load channels
790 if (!instance.VideoChannel) {
791 instance.VideoChannel = await instance.$get('VideoChannel', {
796 transaction: options.transaction
797 }) as MChannelAccountDefault
800 return sendDeleteVideo(instance, options.transaction)
804 static async removeFiles (instance: VideoModel) {
805 const tasks: Promise<any>[] = []
807 logger.info('Removing files of video %s.', instance.url)
809 if (instance.isOwned()) {
810 if (!Array.isArray(instance.VideoFiles)) {
811 instance.VideoFiles = await instance.$get('VideoFiles')
814 // Remove physical files and torrents
815 instance.VideoFiles.forEach(file => {
816 tasks.push(instance.removeFile(file))
817 tasks.push(file.removeTorrent())
820 // Remove playlists file
821 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
822 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
825 for (const p of instance.VideoStreamingPlaylists) {
826 tasks.push(instance.removeStreamingPlaylistFiles(p))
830 // Do not wait video deletion because we could be in a transaction
833 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
840 static stopLiveIfNeeded (instance: VideoModel) {
841 if (!instance.isLive) return
843 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
845 return LiveManager.Instance.stopSessionOf(instance.id)
849 static invalidateCache (instance: VideoModel) {
850 ModelCache.Instance.invalidateCache('video', instance.id)
854 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
855 const tasks: Promise<any>[] = []
857 if (!Array.isArray(instance.VideoAbuses)) {
858 instance.VideoAbuses = await instance.$get('VideoAbuses')
860 if (instance.VideoAbuses.length === 0) return undefined
863 logger.info('Saving video abuses details of video %s.', instance.url)
865 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
866 const details = instance.toFormattedDetailsJSON()
868 for (const abuse of instance.VideoAbuses) {
869 abuse.deletedVideo = details
870 tasks.push(abuse.save({ transaction: options.transaction }))
875 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
881 static listLocal (): Promise<MVideo[]> {
888 return VideoModel.findAll(query)
891 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
892 function getRawQuery (select: string) {
893 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
894 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
895 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
896 'WHERE "Account"."actorId" = ' + actorId
897 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
898 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
899 'WHERE "VideoShare"."actorId" = ' + actorId
901 return `(${queryVideo}) UNION (${queryVideoShare})`
904 const rawQuery = getRawQuery('"Video"."id"')
905 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
911 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
914 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
916 [Op.or]: getPrivaciesForFederation()
920 attributes: [ 'filename', 'language', 'fileUrl' ],
921 model: VideoCaptionModel.unscoped(),
925 attributes: [ 'id', 'url' ],
926 model: VideoShareModel.unscoped(),
928 // We only want videos shared by this actor
943 attributes: [ 'id', 'url' ],
944 model: ActorModel.unscoped()
949 model: VideoChannelModel.unscoped(),
953 attributes: [ 'name' ],
954 model: AccountModel.unscoped(),
958 attributes: [ 'id', 'url', 'followersUrl' ],
959 model: ActorModel.unscoped(),
965 attributes: [ 'id', 'url', 'followersUrl' ],
966 model: ActorModel.unscoped(),
972 model: VideoStreamingPlaylistModel.unscoped(),
976 model: VideoFileModel,
981 VideoLiveModel.unscoped(),
987 return Bluebird.all([
988 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
989 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
990 ]).then(([ rows, totals ]) => {
991 // totals: totalVideos + totalVideoShares
993 let totalVideoShares = 0
994 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
995 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
997 const total = totalVideos + totalVideoShares
1005 static async listPublishedLiveIds () {
1007 attributes: [ 'id' ],
1010 state: VideoState.PUBLISHED
1014 const result = await VideoModel.findAll(options)
1016 return result.map(v => v.id)
1019 static listUserVideosForApi (options: {
1026 const { accountId, start, count, sort, search } = options
1028 function buildBaseQuery (): FindOptions {
1032 order: getVideoSort(sort),
1035 model: VideoChannelModel,
1039 model: AccountModel,
1051 baseQuery = Object.assign(baseQuery, {
1054 [Op.iLike]: '%' + search + '%'
1063 const countQuery = buildBaseQuery()
1064 const findQuery = buildBaseQuery()
1066 const findScopes: (string | ScopeOptions)[] = [
1067 ScopeNames.WITH_SCHEDULED_UPDATE,
1068 ScopeNames.WITH_BLACKLISTED,
1069 ScopeNames.WITH_THUMBNAILS
1072 return Promise.all([
1073 VideoModel.count(countQuery),
1074 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1075 ]).then(([ count, rows ]) => {
1083 static async listForApi (options: {
1088 includeLocalVideos: boolean
1090 categoryOneOf?: number[]
1091 licenceOneOf?: number[]
1092 languageOneOf?: string[]
1093 tagsOneOf?: string[]
1094 tagsAllOf?: string[]
1095 filter?: VideoFilter
1097 videoChannelId?: number
1098 followerActorId?: number
1099 videoPlaylistId?: number
1100 trendingDays?: number
1101 user?: MUserAccountId
1102 historyOfUser?: MUserId
1103 countVideos?: boolean
1106 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1107 throw new Error('Try to filter all-local but no user has not the see all videos right')
1110 const trendingDays = options.sort.endsWith('trending')
1111 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1113 let trendingAlgorithm
1114 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1115 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1117 const serverActor = await getServerActor()
1119 // followerActorId === null has a meaning, so just check undefined
1120 const followerActorId = options.followerActorId !== undefined
1121 ? options.followerActorId
1124 const queryOptions = {
1125 start: options.start,
1126 count: options.count,
1129 serverAccountId: serverActor.Account.id,
1131 categoryOneOf: options.categoryOneOf,
1132 licenceOneOf: options.licenceOneOf,
1133 languageOneOf: options.languageOneOf,
1134 tagsOneOf: options.tagsOneOf,
1135 tagsAllOf: options.tagsAllOf,
1136 filter: options.filter,
1137 withFiles: options.withFiles,
1138 accountId: options.accountId,
1139 videoChannelId: options.videoChannelId,
1140 videoPlaylistId: options.videoPlaylistId,
1141 includeLocalVideos: options.includeLocalVideos,
1143 historyOfUser: options.historyOfUser,
1146 search: options.search
1149 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1152 static async searchAndPopulateAccountAndServer (options: {
1153 includeLocalVideos: boolean
1158 startDate?: string // ISO 8601
1159 endDate?: string // ISO 8601
1160 originallyPublishedStartDate?: string
1161 originallyPublishedEndDate?: string
1163 categoryOneOf?: number[]
1164 licenceOneOf?: number[]
1165 languageOneOf?: string[]
1166 tagsOneOf?: string[]
1167 tagsAllOf?: string[]
1168 durationMin?: number // seconds
1169 durationMax?: number // seconds
1170 user?: MUserAccountId
1171 filter?: VideoFilter
1173 const serverActor = await getServerActor()
1174 const queryOptions = {
1175 followerActorId: serverActor.id,
1176 serverAccountId: serverActor.Account.id,
1177 includeLocalVideos: options.includeLocalVideos,
1179 categoryOneOf: options.categoryOneOf,
1180 licenceOneOf: options.licenceOneOf,
1181 languageOneOf: options.languageOneOf,
1182 tagsOneOf: options.tagsOneOf,
1183 tagsAllOf: options.tagsAllOf,
1185 filter: options.filter,
1186 start: options.start,
1187 count: options.count,
1189 startDate: options.startDate,
1190 endDate: options.endDate,
1191 originallyPublishedStartDate: options.originallyPublishedStartDate,
1192 originallyPublishedEndDate: options.originallyPublishedEndDate,
1194 durationMin: options.durationMin,
1195 durationMax: options.durationMax,
1197 search: options.search
1200 return VideoModel.getAvailableForApi(queryOptions)
1203 static countLocalLives () {
1209 [Op.ne]: VideoState.LIVE_ENDED
1214 return VideoModel.count(options)
1217 static countVideosUploadedByUserSince (userId: number, since: Date) {
1221 model: VideoChannelModel.unscoped(),
1225 model: AccountModel.unscoped(),
1229 model: UserModel.unscoped(),
1247 return VideoModel.unscoped().count(options)
1250 static countLivesOfAccount (accountId: number) {
1256 [Op.ne]: VideoState.LIVE_ENDED
1262 model: VideoChannelModel.unscoped(),
1270 return VideoModel.count(options)
1273 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1274 const where = buildWhereIdOrUUID(id)
1280 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1283 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1284 const where = buildWhereIdOrUUID(id)
1290 return VideoModel.scope([
1291 ScopeNames.WITH_THUMBNAILS,
1292 ScopeNames.WITH_BLACKLISTED
1296 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1299 where: buildWhereIdOrUUID(id),
1303 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1306 return ModelCache.Instance.doCache({
1307 cacheType: 'load-video-immutable-id',
1314 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1315 const where = buildWhereIdOrUUID(id)
1321 return VideoModel.scope([
1322 ScopeNames.WITH_BLACKLISTED,
1323 ScopeNames.WITH_USER_ID
1327 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1328 const where = buildWhereIdOrUUID(id)
1331 attributes: [ 'id' ],
1336 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1339 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1340 const where = buildWhereIdOrUUID(id)
1348 return VideoModel.scope([
1349 ScopeNames.WITH_WEBTORRENT_FILES,
1350 ScopeNames.WITH_STREAMING_PLAYLISTS,
1351 ScopeNames.WITH_THUMBNAILS
1355 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1362 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1365 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1366 const query: FindOptions = {
1373 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1376 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1378 const query: FindOptions = {
1385 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1388 return ModelCache.Instance.doCache({
1389 cacheType: 'load-video-immutable-url',
1396 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1397 const query: FindOptions = {
1404 return VideoModel.scope([
1405 ScopeNames.WITH_ACCOUNT_DETAILS,
1406 ScopeNames.WITH_WEBTORRENT_FILES,
1407 ScopeNames.WITH_STREAMING_PLAYLISTS,
1408 ScopeNames.WITH_THUMBNAILS,
1409 ScopeNames.WITH_BLACKLISTED
1413 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1414 const where = buildWhereIdOrUUID(id)
1417 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1422 const scopes: (string | ScopeOptions)[] = [
1423 ScopeNames.WITH_TAGS,
1424 ScopeNames.WITH_BLACKLISTED,
1425 ScopeNames.WITH_ACCOUNT_DETAILS,
1426 ScopeNames.WITH_SCHEDULED_UPDATE,
1427 ScopeNames.WITH_WEBTORRENT_FILES,
1428 ScopeNames.WITH_STREAMING_PLAYLISTS,
1429 ScopeNames.WITH_THUMBNAILS,
1430 ScopeNames.WITH_LIVE
1434 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1442 static loadForGetAPI (parameters: {
1446 }): Promise<MVideoDetails> {
1447 const { id, t, userId } = parameters
1448 const where = buildWhereIdOrUUID(id)
1451 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1456 const scopes: (string | ScopeOptions)[] = [
1457 ScopeNames.WITH_TAGS,
1458 ScopeNames.WITH_BLACKLISTED,
1459 ScopeNames.WITH_ACCOUNT_DETAILS,
1460 ScopeNames.WITH_SCHEDULED_UPDATE,
1461 ScopeNames.WITH_THUMBNAILS,
1462 ScopeNames.WITH_LIVE,
1463 ScopeNames.WITH_TRACKERS,
1464 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1465 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1469 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1477 static async getStats () {
1478 const totalLocalVideos = await VideoModel.count({
1484 let totalLocalVideoViews = await VideoModel.sum('views', {
1490 // Sequelize could return null...
1491 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1493 const { total: totalVideos } = await VideoModel.listForApi({
1496 sort: '-publishedAt',
1497 nsfw: buildNSFWFilter(),
1498 includeLocalVideos: true,
1504 totalLocalVideoViews,
1509 static incrementViews (id: number, views: number) {
1510 return VideoModel.increment('views', {
1518 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1519 const field = type === 'like'
1523 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1525 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1527 'WHERE "video"."id" = :videoId'
1529 return AccountVideoRateModel.sequelize.query(rawQuery, {
1531 replacements: { videoId, rateType: type },
1532 type: QueryTypes.UPDATE
1536 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1537 // Instances only share videos
1538 const query = 'SELECT 1 FROM "videoShare" ' +
1539 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1540 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1544 type: QueryTypes.SELECT as QueryTypes.SELECT,
1545 bind: { followerActorId, videoId },
1549 return VideoModel.sequelize.query(query, options)
1550 .then(results => results.length === 1)
1553 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1556 channelId: videoChannel.id
1561 return VideoModel.update({ support: videoChannel.support }, options)
1564 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1566 attributes: [ 'id' ],
1568 channelId: videoChannel.id
1572 return VideoModel.findAll(query)
1573 .then(videos => videos.map(v => v.id))
1576 // threshold corresponds to how many video the field should have to be returned
1577 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1578 const serverActor = await getServerActor()
1579 const followerActorId = serverActor.id
1581 const queryOptions: BuildVideosQueryOptions = {
1582 attributes: [ `"${field}"` ],
1583 group: `GROUP BY "${field}"`,
1584 having: `HAVING COUNT("${field}") >= ${threshold}`,
1588 serverAccountId: serverActor.Account.id,
1590 includeLocalVideos: true
1593 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1595 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1596 .then(rows => rows.map(r => r[field]))
1599 static buildTrendingQuery (trendingDays: number) {
1603 model: VideoViewModel,
1607 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1613 private static async getAvailableForApi (
1614 options: BuildVideosQueryOptions,
1616 ): Promise<ResultList<VideoModel>> {
1617 function getCount () {
1618 if (countVideos !== true) return Promise.resolve(undefined)
1620 const countOptions = Object.assign({}, options, { isCount: true })
1621 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1623 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1624 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1627 function getModels () {
1628 if (options.count === 0) return Promise.resolve([])
1630 const { query, replacements, order } = buildListQuery(VideoModel, options)
1631 const queryModels = wrapForAPIResults(query, replacements, options, order)
1633 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1634 .then(rows => VideoModel.buildAPIResult(rows))
1637 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1645 private static buildAPIResult (rows: any[]) {
1646 const videosMemo: { [ id: number ]: VideoModel } = {}
1647 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1649 const thumbnailsDone = new Set<number>()
1650 const historyDone = new Set<number>()
1651 const videoFilesDone = new Set<number>()
1653 const videos: VideoModel[] = []
1655 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1656 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1657 const serverKeys = [ 'id', 'host' ]
1658 const videoFileKeys = [
1672 'videoStreamingPlaylistId'
1674 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1698 'originallyPublishedAt',
1703 const buildOpts = { raw: true }
1705 function buildActor (rowActor: any) {
1706 const avatarModel = rowActor.Avatar.id !== null
1707 ? new ActorImageModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1710 const serverModel = rowActor.Server.id !== null
1711 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1714 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1715 actorModel.Avatar = avatarModel
1716 actorModel.Server = serverModel
1721 for (const row of rows) {
1722 if (!videosMemo[row.id]) {
1724 const channel = row.VideoChannel
1725 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1726 channelModel.Actor = buildActor(channel.Actor)
1728 const account = row.VideoChannel.Account
1729 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1730 accountModel.Actor = buildActor(account.Actor)
1732 channelModel.Account = accountModel
1734 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1735 videoModel.VideoChannel = channelModel
1737 videoModel.UserVideoHistories = []
1738 videoModel.Thumbnails = []
1739 videoModel.VideoFiles = []
1740 videoModel.VideoStreamingPlaylists = []
1742 videosMemo[row.id] = videoModel
1743 // Don't take object value to have a sorted array
1744 videos.push(videoModel)
1747 const videoModel = videosMemo[row.id]
1749 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1750 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1751 videoModel.UserVideoHistories.push(historyModel)
1753 historyDone.add(row.userVideoHistory.id)
1756 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1757 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1758 videoModel.Thumbnails.push(thumbnailModel)
1760 thumbnailsDone.add(row.Thumbnails.id)
1763 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1764 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1765 videoModel.VideoFiles.push(videoFileModel)
1767 videoFilesDone.add(row.VideoFiles.id)
1770 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1771 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1772 streamingPlaylist.VideoFiles = []
1774 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1776 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1779 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1780 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1782 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1783 streamingPlaylist.VideoFiles.push(videoFileModel)
1785 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1792 static getCategoryLabel (id: number) {
1793 return VIDEO_CATEGORIES[id] || 'Misc'
1796 static getLicenceLabel (id: number) {
1797 return VIDEO_LICENCES[id] || 'Unknown'
1800 static getLanguageLabel (id: string) {
1801 return VIDEO_LANGUAGES[id] || 'Unknown'
1804 static getPrivacyLabel (id: number) {
1805 return VIDEO_PRIVACIES[id] || 'Unknown'
1808 static getStateLabel (id: number) {
1809 return VIDEO_STATES[id] || 'Unknown'
1813 return !!this.VideoBlacklist
1817 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1820 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1821 // We first transcode to WebTorrent format, so try this array first
1822 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1823 const file = fun(this.VideoFiles, file => file.resolution)
1825 return Object.assign(file, { Video: this })
1828 // No webtorrent files, try with streaming playlist files
1829 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1830 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1832 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1833 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1839 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1840 return this.getQualityFileBy(maxBy)
1843 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1844 return this.getQualityFileBy(minBy)
1847 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1848 if (Array.isArray(this.VideoFiles) === false) return undefined
1850 const file = this.VideoFiles.find(f => f.resolution === resolution)
1851 if (!file) return undefined
1853 return Object.assign(file, { Video: this })
1856 hasWebTorrentFiles () {
1857 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1860 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1861 thumbnail.videoId = this.id
1863 const savedThumbnail = await thumbnail.save({ transaction })
1865 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1867 // Already have this thumbnail, skip
1868 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1870 this.Thumbnails.push(savedThumbnail)
1874 if (Array.isArray(this.Thumbnails) === false) return undefined
1876 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1880 return !!this.getPreview()
1884 if (Array.isArray(this.Thumbnails) === false) return undefined
1886 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1890 return this.remote === false
1893 getWatchStaticPath () {
1894 return '/videos/watch/' + this.uuid
1897 getEmbedStaticPath () {
1898 return '/videos/embed/' + this.uuid
1901 getMiniatureStaticPath () {
1902 const thumbnail = this.getMiniature()
1903 if (!thumbnail) return null
1905 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1908 getPreviewStaticPath () {
1909 const preview = this.getPreview()
1910 if (!preview) return null
1912 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1913 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1916 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1917 return videoModelToFormattedJSON(this, options)
1920 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1921 return videoModelToFormattedDetailsJSON(this)
1924 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1925 let files: VideoFile[] = []
1927 if (Array.isArray(this.VideoFiles)) {
1928 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1929 files = files.concat(result)
1932 for (const p of (this.VideoStreamingPlaylists || [])) {
1933 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1934 files = files.concat(result)
1940 toActivityPubObject (this: MVideoAP): VideoObject {
1941 return videoModelToActivityPubObject(this)
1944 getTruncatedDescription () {
1945 if (!this.description) return null
1947 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1948 return peertubeTruncate(this.description, { length: maxLength })
1951 getMaxQualityResolution () {
1952 const file = this.getMaxQualityFile()
1953 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1954 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1956 return getVideoFileResolution(originalFilePath)
1959 getDescriptionAPIPath () {
1960 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1963 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1964 if (!this.VideoStreamingPlaylists) return undefined
1966 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1967 playlist.Video = this
1972 setHLSPlaylist (playlist: MStreamingPlaylist) {
1973 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1975 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1976 this.VideoStreamingPlaylists = toAdd
1980 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1981 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1985 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1986 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1987 return remove(filePath)
1988 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1991 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1992 const directoryPath = getHLSDirectory(this, isRedundancy)
1994 await remove(directoryPath)
1996 if (isRedundancy !== true) {
1997 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1998 streamingPlaylistWithFiles.Video = this
2000 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2001 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2004 // Remove physical files and torrents
2006 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2012 if (this.isOwned()) return false
2014 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2017 hasPrivacyForFederation () {
2018 return isPrivacyForFederation(this.privacy)
2021 hasStateForFederation () {
2022 return isStateForFederation(this.state)
2025 isNewVideo (newPrivacy: VideoPrivacy) {
2026 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2031 where: { id: this.id }
2034 return VideoModel.update({ updatedAt: new Date() }, options)
2038 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2041 setPrivacy (newPrivacy: VideoPrivacy) {
2042 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2043 this.publishedAt = new Date()
2046 this.privacy = newPrivacy
2050 return this.privacy === VideoPrivacy.PRIVATE ||
2051 this.privacy === VideoPrivacy.UNLISTED ||
2052 this.privacy === VideoPrivacy.INTERNAL
2055 async publishIfNeededAndSave (t: Transaction) {
2056 if (this.state !== VideoState.PUBLISHED) {
2057 this.state = VideoState.PUBLISHED
2058 this.publishedAt = new Date()
2059 await this.save({ transaction: t })
2067 getBandwidthBits (videoFile: MVideoFile) {
2068 return Math.ceil((videoFile.size * 8) / this.duration)
2072 if (this.isOwned()) {
2074 WEBSERVER.URL + '/tracker/announce',
2075 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2079 return this.Trackers.map(t => t.url)