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 { 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'
71 } from '../../initializers/constants'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 MChannelAccountDefault,
78 MStreamingPlaylistFilesVideo,
83 MVideoAccountLightBlacklistAllFiles,
88 MVideoFormattableDetails,
94 MVideoThumbnailBlacklist,
98 } from '../../types/models'
99 import { MThumbnail } from '../../types/models/video/thumbnail'
100 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
101 import { VideoAbuseModel } from '../abuse/video-abuse'
102 import { AccountModel } from '../account/account'
103 import { AccountVideoRateModel } from '../account/account-video-rate'
104 import { ActorModel } from '../actor/actor'
105 import { ActorImageModel } from '../actor/actor-image'
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 { UserModel } from '../user/user'
111 import { UserVideoHistoryModel } from '../user/user-video-history'
112 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
113 import { ScheduleVideoUpdateModel } from './schedule-video-update'
114 import { TagModel } from './tag'
115 import { ThumbnailModel } from './thumbnail'
116 import { VideoBlacklistModel } from './video-blacklist'
117 import { VideoCaptionModel } from './video-caption'
118 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
119 import { VideoCommentModel } from './video-comment'
120 import { VideoFileModel } from './video-file'
122 videoFilesModelToFormattedJSON,
123 VideoFormattingJSONOptions,
124 videoModelToActivityPubObject,
125 videoModelToFormattedDetailsJSON,
126 videoModelToFormattedJSON
127 } from './video-format-utils'
128 import { VideoImportModel } from './video-import'
129 import { VideoLiveModel } from './video-live'
130 import { VideoPlaylistElementModel } from './video-playlist-element'
131 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
132 import { VideoShareModel } from './video-share'
133 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
134 import { VideoTagModel } from './video-tag'
135 import { VideoViewModel } from './video-view'
137 export enum ScopeNames {
138 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
140 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
141 WITH_TAGS = 'WITH_TAGS',
142 WITH_TRACKERS = 'WITH_TRACKERS',
143 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
144 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
145 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
146 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
147 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
148 WITH_USER_ID = 'WITH_USER_ID',
149 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
150 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
151 WITH_LIVE = 'WITH_LIVE'
154 export type ForAPIOptions = {
157 videoPlaylistId?: number
159 withAccountBlockerIds?: number[]
162 export type AvailableForListIDsOptions = {
163 serverAccountId: number
164 followerActorId: number
165 includeLocalVideos: boolean
167 attributesType?: 'none' | 'id' | 'all'
170 categoryOneOf?: number[]
172 licenceOneOf?: number[]
173 languageOneOf?: string[]
180 videoChannelId?: number
182 videoPlaylistId?: number
184 trendingDays?: number
185 user?: MUserAccountId
186 historyOfUser?: MUserId
188 baseWhere?: WhereOptions[]
192 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
193 attributes: [ 'id', 'url', 'uuid', 'remote' ]
195 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
196 const include: Includeable[] = [
198 model: VideoChannelModel.scope({
200 VideoChannelScopeNames.SUMMARY, {
202 withAccountBlockerIds: options.withAccountBlockerIds
209 attributes: [ 'type', 'filename' ],
210 model: ThumbnailModel,
215 const query: FindOptions = {}
225 if (options.videoPlaylistId) {
227 model: VideoPlaylistElementModel.unscoped(),
230 videoPlaylistId: options.videoPlaylistId
235 query.include = include
239 [ScopeNames.WITH_THUMBNAILS]: {
242 model: ThumbnailModel,
247 [ScopeNames.WITH_LIVE]: {
250 model: VideoLiveModel.unscoped(),
255 [ScopeNames.WITH_USER_ID]: {
258 attributes: [ 'accountId' ],
259 model: VideoChannelModel.unscoped(),
263 attributes: [ 'userId' ],
264 model: AccountModel.unscoped(),
271 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
274 model: VideoChannelModel.unscoped(),
279 exclude: [ 'privateKey', 'publicKey' ]
281 model: ActorModel.unscoped(),
285 attributes: [ 'host' ],
286 model: ServerModel.unscoped(),
290 model: ActorImageModel.unscoped(),
297 model: AccountModel.unscoped(),
301 model: ActorModel.unscoped(),
303 exclude: [ 'privateKey', 'publicKey' ]
308 attributes: [ 'host' ],
309 model: ServerModel.unscoped(),
313 model: ActorImageModel.unscoped(),
325 [ScopeNames.WITH_TAGS]: {
326 include: [ TagModel ]
328 [ScopeNames.WITH_TRACKERS]: {
331 attributes: [ 'id', 'url' ],
336 [ScopeNames.WITH_BLACKLISTED]: {
339 attributes: [ 'id', 'reason', 'unfederated' ],
340 model: VideoBlacklistModel,
345 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
346 let subInclude: any[] = []
348 if (withRedundancies === true) {
351 attributes: [ 'fileUrl' ],
352 model: VideoRedundancyModel.unscoped(),
361 model: VideoFileModel,
369 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
370 const subInclude: IncludeOptions[] = [
372 model: VideoFileModel,
377 if (withRedundancies === true) {
379 attributes: [ 'fileUrl' ],
380 model: VideoRedundancyModel.unscoped(),
388 model: VideoStreamingPlaylistModel.unscoped(),
396 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
399 model: ScheduleVideoUpdateModel.unscoped(),
404 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
408 attributes: [ 'currentTime' ],
409 model: UserVideoHistoryModel.unscoped(),
422 buildTrigramSearchIndex('video_name_trigram', 'name'),
424 { fields: [ 'createdAt' ] },
427 { name: 'publishedAt', order: 'DESC' },
428 { name: 'id', order: 'ASC' }
431 { fields: [ 'duration' ] },
434 { name: 'views', order: 'DESC' },
435 { name: 'id', order: 'ASC' }
438 { fields: [ 'channelId' ] },
440 fields: [ 'originallyPublishedAt' ],
442 originallyPublishedAt: {
448 fields: [ 'category' ], // We don't care videos with an unknown category
456 fields: [ 'licence' ], // We don't care videos with an unknown licence
464 fields: [ 'language' ], // We don't care videos with an unknown language
472 fields: [ 'nsfw' ], // Most of the videos are not NSFW
478 fields: [ 'remote' ], // Only index local videos
493 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
496 @Default(DataType.UUIDV4)
498 @Column(DataType.UUID)
502 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
508 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
514 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
520 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
521 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
525 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
527 privacy: VideoPrivacy
530 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
536 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
537 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
542 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
543 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
547 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
582 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
583 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
588 commentsEnabled: boolean
592 downloadEnabled: boolean
596 waitTranscoding: boolean
600 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
611 @Default(DataType.NOW)
618 originallyPublishedAt: Date
620 @ForeignKey(() => VideoChannelModel)
624 @BelongsTo(() => VideoChannelModel, {
630 VideoChannel: VideoChannelModel
632 @BelongsToMany(() => TagModel, {
633 foreignKey: 'videoId',
634 through: () => VideoTagModel,
639 @BelongsToMany(() => TrackerModel, {
640 foreignKey: 'videoId',
641 through: () => VideoTrackerModel,
644 Trackers: TrackerModel[]
646 @HasMany(() => ThumbnailModel, {
654 Thumbnails: ThumbnailModel[]
656 @HasMany(() => VideoPlaylistElementModel, {
663 VideoPlaylistElements: VideoPlaylistElementModel[]
665 @HasMany(() => VideoAbuseModel, {
672 VideoAbuses: VideoAbuseModel[]
674 @HasMany(() => VideoFileModel, {
682 VideoFiles: VideoFileModel[]
684 @HasMany(() => VideoStreamingPlaylistModel, {
692 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
694 @HasMany(() => VideoShareModel, {
701 VideoShares: VideoShareModel[]
703 @HasMany(() => AccountVideoRateModel, {
710 AccountVideoRates: AccountVideoRateModel[]
712 @HasMany(() => VideoCommentModel, {
720 VideoComments: VideoCommentModel[]
722 @HasMany(() => VideoViewModel, {
729 VideoViews: VideoViewModel[]
731 @HasMany(() => UserVideoHistoryModel, {
738 UserVideoHistories: UserVideoHistoryModel[]
740 @HasOne(() => ScheduleVideoUpdateModel, {
747 ScheduleVideoUpdate: ScheduleVideoUpdateModel
749 @HasOne(() => VideoBlacklistModel, {
756 VideoBlacklist: VideoBlacklistModel
758 @HasOne(() => VideoLiveModel, {
765 VideoLive: VideoLiveModel
767 @HasOne(() => VideoImportModel, {
774 VideoImport: VideoImportModel
776 @HasMany(() => VideoCaptionModel, {
783 ['separate' as any]: true
785 VideoCaptions: VideoCaptionModel[]
788 static async sendDelete (instance: MVideoAccountLight, options) {
789 if (!instance.isOwned()) return undefined
791 // Lazy load channels
792 if (!instance.VideoChannel) {
793 instance.VideoChannel = await instance.$get('VideoChannel', {
798 transaction: options.transaction
799 }) as MChannelAccountDefault
802 return sendDeleteVideo(instance, options.transaction)
806 static async removeFiles (instance: VideoModel) {
807 const tasks: Promise<any>[] = []
809 logger.info('Removing files of video %s.', instance.url)
811 if (instance.isOwned()) {
812 if (!Array.isArray(instance.VideoFiles)) {
813 instance.VideoFiles = await instance.$get('VideoFiles')
816 // Remove physical files and torrents
817 instance.VideoFiles.forEach(file => {
818 tasks.push(instance.removeFile(file))
819 tasks.push(file.removeTorrent())
822 // Remove playlists file
823 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
824 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
827 for (const p of instance.VideoStreamingPlaylists) {
828 tasks.push(instance.removeStreamingPlaylistFiles(p))
832 // Do not wait video deletion because we could be in a transaction
835 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
842 static stopLiveIfNeeded (instance: VideoModel) {
843 if (!instance.isLive) return
845 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
847 return LiveManager.Instance.stopSessionOf(instance.id)
851 static invalidateCache (instance: VideoModel) {
852 ModelCache.Instance.invalidateCache('video', instance.id)
856 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
857 const tasks: Promise<any>[] = []
859 if (!Array.isArray(instance.VideoAbuses)) {
860 instance.VideoAbuses = await instance.$get('VideoAbuses')
862 if (instance.VideoAbuses.length === 0) return undefined
865 logger.info('Saving video abuses details of video %s.', instance.url)
867 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
868 const details = instance.toFormattedDetailsJSON()
870 for (const abuse of instance.VideoAbuses) {
871 abuse.deletedVideo = details
872 tasks.push(abuse.save({ transaction: options.transaction }))
877 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
883 static listLocal (): Promise<MVideo[]> {
890 return VideoModel.findAll(query)
893 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
894 function getRawQuery (select: string) {
895 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
896 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
897 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
898 'WHERE "Account"."actorId" = ' + actorId
899 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
900 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
901 'WHERE "VideoShare"."actorId" = ' + actorId
903 return `(${queryVideo}) UNION (${queryVideoShare})`
906 const rawQuery = getRawQuery('"Video"."id"')
907 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
913 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
916 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
918 [Op.or]: getPrivaciesForFederation()
922 attributes: [ 'filename', 'language', 'fileUrl' ],
923 model: VideoCaptionModel.unscoped(),
927 attributes: [ 'id', 'url' ],
928 model: VideoShareModel.unscoped(),
930 // We only want videos shared by this actor
945 attributes: [ 'id', 'url' ],
946 model: ActorModel.unscoped()
951 model: VideoChannelModel.unscoped(),
955 attributes: [ 'name' ],
956 model: AccountModel.unscoped(),
960 attributes: [ 'id', 'url', 'followersUrl' ],
961 model: ActorModel.unscoped(),
967 attributes: [ 'id', 'url', 'followersUrl' ],
968 model: ActorModel.unscoped(),
974 model: VideoStreamingPlaylistModel.unscoped(),
978 model: VideoFileModel,
983 VideoLiveModel.unscoped(),
989 return Bluebird.all([
990 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
991 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
992 ]).then(([ rows, totals ]) => {
993 // totals: totalVideos + totalVideoShares
995 let totalVideoShares = 0
996 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
997 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
999 const total = totalVideos + totalVideoShares
1007 static async listPublishedLiveIds () {
1009 attributes: [ 'id' ],
1012 state: VideoState.PUBLISHED
1016 const result = await VideoModel.findAll(options)
1018 return result.map(v => v.id)
1021 static listUserVideosForApi (options: {
1029 const { accountId, start, count, sort, search, isLive } = options
1031 function buildBaseQuery (): FindOptions {
1032 const where: WhereOptions = {}
1036 [Op.iLike]: '%' + search + '%'
1041 where.isLive = isLive
1048 order: getVideoSort(sort),
1051 model: VideoChannelModel,
1055 model: AccountModel,
1069 const countQuery = buildBaseQuery()
1070 const findQuery = buildBaseQuery()
1072 const findScopes: (string | ScopeOptions)[] = [
1073 ScopeNames.WITH_SCHEDULED_UPDATE,
1074 ScopeNames.WITH_BLACKLISTED,
1075 ScopeNames.WITH_THUMBNAILS
1078 return Promise.all([
1079 VideoModel.count(countQuery),
1080 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1081 ]).then(([ count, rows ]) => {
1089 static async listForApi (options: {
1095 filter?: VideoFilter
1098 includeLocalVideos: boolean
1101 categoryOneOf?: number[]
1102 licenceOneOf?: number[]
1103 languageOneOf?: string[]
1104 tagsOneOf?: string[]
1105 tagsAllOf?: string[]
1108 videoChannelId?: number
1110 followerActorId?: number
1112 videoPlaylistId?: number
1114 trendingDays?: number
1116 user?: MUserAccountId
1117 historyOfUser?: MUserId
1119 countVideos?: boolean
1123 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1124 throw new Error('Try to filter all-local but no user has not the see all videos right')
1127 const trendingDays = options.sort.endsWith('trending')
1128 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1130 let trendingAlgorithm
1131 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1132 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1134 const serverActor = await getServerActor()
1136 // followerActorId === null has a meaning, so just check undefined
1137 const followerActorId = options.followerActorId !== undefined
1138 ? options.followerActorId
1141 const queryOptions = {
1142 start: options.start,
1143 count: options.count,
1146 serverAccountId: serverActor.Account.id,
1148 isLive: options.isLive,
1149 categoryOneOf: options.categoryOneOf,
1150 licenceOneOf: options.licenceOneOf,
1151 languageOneOf: options.languageOneOf,
1152 tagsOneOf: options.tagsOneOf,
1153 tagsAllOf: options.tagsAllOf,
1154 filter: options.filter,
1155 withFiles: options.withFiles,
1156 accountId: options.accountId,
1157 videoChannelId: options.videoChannelId,
1158 videoPlaylistId: options.videoPlaylistId,
1159 includeLocalVideos: options.includeLocalVideos,
1161 historyOfUser: options.historyOfUser,
1164 search: options.search
1167 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1170 static async searchAndPopulateAccountAndServer (options: {
1171 includeLocalVideos: boolean
1176 startDate?: string // ISO 8601
1177 endDate?: string // ISO 8601
1178 originallyPublishedStartDate?: string
1179 originallyPublishedEndDate?: string
1182 categoryOneOf?: number[]
1183 licenceOneOf?: number[]
1184 languageOneOf?: string[]
1185 tagsOneOf?: string[]
1186 tagsAllOf?: string[]
1187 durationMin?: number // seconds
1188 durationMax?: number // seconds
1189 user?: MUserAccountId
1190 filter?: VideoFilter
1192 const serverActor = await getServerActor()
1194 const queryOptions = {
1195 followerActorId: serverActor.id,
1196 serverAccountId: serverActor.Account.id,
1198 includeLocalVideos: options.includeLocalVideos,
1200 isLive: options.isLive,
1202 categoryOneOf: options.categoryOneOf,
1203 licenceOneOf: options.licenceOneOf,
1204 languageOneOf: options.languageOneOf,
1206 tagsOneOf: options.tagsOneOf,
1207 tagsAllOf: options.tagsAllOf,
1210 filter: options.filter,
1212 start: options.start,
1213 count: options.count,
1216 startDate: options.startDate,
1217 endDate: options.endDate,
1219 originallyPublishedStartDate: options.originallyPublishedStartDate,
1220 originallyPublishedEndDate: options.originallyPublishedEndDate,
1222 durationMin: options.durationMin,
1223 durationMax: options.durationMax,
1225 search: options.search
1228 return VideoModel.getAvailableForApi(queryOptions)
1231 static countLocalLives () {
1237 [Op.ne]: VideoState.LIVE_ENDED
1242 return VideoModel.count(options)
1245 static countVideosUploadedByUserSince (userId: number, since: Date) {
1249 model: VideoChannelModel.unscoped(),
1253 model: AccountModel.unscoped(),
1257 model: UserModel.unscoped(),
1275 return VideoModel.unscoped().count(options)
1278 static countLivesOfAccount (accountId: number) {
1284 [Op.ne]: VideoState.LIVE_ENDED
1290 model: VideoChannelModel.unscoped(),
1298 return VideoModel.count(options)
1301 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1302 const where = buildWhereIdOrUUID(id)
1308 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1311 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1312 const where = buildWhereIdOrUUID(id)
1318 return VideoModel.scope([
1319 ScopeNames.WITH_THUMBNAILS,
1320 ScopeNames.WITH_BLACKLISTED
1324 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1327 where: buildWhereIdOrUUID(id),
1331 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1334 return ModelCache.Instance.doCache({
1335 cacheType: 'load-video-immutable-id',
1342 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1343 const where = buildWhereIdOrUUID(id)
1349 return VideoModel.scope([
1350 ScopeNames.WITH_BLACKLISTED,
1351 ScopeNames.WITH_USER_ID
1355 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1356 const where = buildWhereIdOrUUID(id)
1359 attributes: [ 'id' ],
1364 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1367 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1368 const where = buildWhereIdOrUUID(id)
1376 return VideoModel.scope([
1377 ScopeNames.WITH_WEBTORRENT_FILES,
1378 ScopeNames.WITH_STREAMING_PLAYLISTS,
1379 ScopeNames.WITH_THUMBNAILS
1383 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1390 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1393 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1394 const query: FindOptions = {
1401 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1404 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1406 const query: FindOptions = {
1413 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1416 return ModelCache.Instance.doCache({
1417 cacheType: 'load-video-immutable-url',
1424 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1425 const query: FindOptions = {
1432 return VideoModel.scope([
1433 ScopeNames.WITH_ACCOUNT_DETAILS,
1434 ScopeNames.WITH_WEBTORRENT_FILES,
1435 ScopeNames.WITH_STREAMING_PLAYLISTS,
1436 ScopeNames.WITH_THUMBNAILS,
1437 ScopeNames.WITH_BLACKLISTED
1441 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1442 const where = buildWhereIdOrUUID(id)
1445 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1450 const scopes: (string | ScopeOptions)[] = [
1451 ScopeNames.WITH_TAGS,
1452 ScopeNames.WITH_BLACKLISTED,
1453 ScopeNames.WITH_ACCOUNT_DETAILS,
1454 ScopeNames.WITH_SCHEDULED_UPDATE,
1455 ScopeNames.WITH_WEBTORRENT_FILES,
1456 ScopeNames.WITH_STREAMING_PLAYLISTS,
1457 ScopeNames.WITH_THUMBNAILS,
1458 ScopeNames.WITH_LIVE
1462 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1470 static loadForGetAPI (parameters: {
1474 }): Promise<MVideoDetails> {
1475 const { id, t, userId } = parameters
1476 const where = buildWhereIdOrUUID(id)
1479 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1484 const scopes: (string | ScopeOptions)[] = [
1485 ScopeNames.WITH_TAGS,
1486 ScopeNames.WITH_BLACKLISTED,
1487 ScopeNames.WITH_ACCOUNT_DETAILS,
1488 ScopeNames.WITH_SCHEDULED_UPDATE,
1489 ScopeNames.WITH_THUMBNAILS,
1490 ScopeNames.WITH_LIVE,
1491 ScopeNames.WITH_TRACKERS,
1492 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1493 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1497 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1505 static async getStats () {
1506 const totalLocalVideos = await VideoModel.count({
1512 let totalLocalVideoViews = await VideoModel.sum('views', {
1518 // Sequelize could return null...
1519 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1521 const { total: totalVideos } = await VideoModel.listForApi({
1524 sort: '-publishedAt',
1525 nsfw: buildNSFWFilter(),
1526 includeLocalVideos: true,
1532 totalLocalVideoViews,
1537 static incrementViews (id: number, views: number) {
1538 return VideoModel.increment('views', {
1546 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1547 const field = type === 'like'
1551 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1553 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1555 'WHERE "video"."id" = :videoId'
1557 return AccountVideoRateModel.sequelize.query(rawQuery, {
1559 replacements: { videoId, rateType: type },
1560 type: QueryTypes.UPDATE
1564 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1565 // Instances only share videos
1566 const query = 'SELECT 1 FROM "videoShare" ' +
1567 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1568 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1572 type: QueryTypes.SELECT as QueryTypes.SELECT,
1573 bind: { followerActorId, videoId },
1577 return VideoModel.sequelize.query(query, options)
1578 .then(results => results.length === 1)
1581 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1584 channelId: videoChannel.id
1589 return VideoModel.update({ support: videoChannel.support }, options)
1592 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1594 attributes: [ 'id' ],
1596 channelId: videoChannel.id
1600 return VideoModel.findAll(query)
1601 .then(videos => videos.map(v => v.id))
1604 // threshold corresponds to how many video the field should have to be returned
1605 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1606 const serverActor = await getServerActor()
1607 const followerActorId = serverActor.id
1609 const queryOptions: BuildVideosQueryOptions = {
1610 attributes: [ `"${field}"` ],
1611 group: `GROUP BY "${field}"`,
1612 having: `HAVING COUNT("${field}") >= ${threshold}`,
1616 serverAccountId: serverActor.Account.id,
1618 includeLocalVideos: true
1621 const { query, replacements } = buildListQuery(VideoModel.sequelize, queryOptions)
1623 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1624 .then(rows => rows.map(r => r[field]))
1627 static buildTrendingQuery (trendingDays: number) {
1631 model: VideoViewModel,
1635 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1641 private static async getAvailableForApi (
1642 options: BuildVideosQueryOptions,
1644 ): Promise<ResultList<VideoModel>> {
1645 function getCount () {
1646 if (countVideos !== true) return Promise.resolve(undefined)
1648 const countOptions = Object.assign({}, options, { isCount: true })
1649 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel.sequelize, countOptions)
1651 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1652 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1655 function getModels () {
1656 if (options.count === 0) return Promise.resolve([])
1658 const { query, replacements, order } = buildListQuery(VideoModel.sequelize, options)
1659 const queryModels = wrapForAPIResults(query, replacements, options, order)
1661 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1662 .then(rows => VideoModel.buildAPIResult(rows))
1665 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1673 private static buildAPIResult (rows: any[]) {
1674 const videosMemo: { [ id: number ]: VideoModel } = {}
1675 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1677 const thumbnailsDone = new Set<number>()
1678 const historyDone = new Set<number>()
1679 const videoFilesDone = new Set<number>()
1681 const videos: VideoModel[] = []
1683 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1684 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1685 const serverKeys = [ 'id', 'host' ]
1686 const videoFileKeys = [
1700 'videoStreamingPlaylistId'
1702 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1726 'originallyPublishedAt',
1731 const buildOpts = { raw: true }
1733 function buildActor (rowActor: any) {
1734 const avatarModel = rowActor.Avatar.id !== null
1735 ? new ActorImageModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1738 const serverModel = rowActor.Server.id !== null
1739 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1742 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1743 actorModel.Avatar = avatarModel
1744 actorModel.Server = serverModel
1749 for (const row of rows) {
1750 if (!videosMemo[row.id]) {
1752 const channel = row.VideoChannel
1753 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1754 channelModel.Actor = buildActor(channel.Actor)
1756 const account = row.VideoChannel.Account
1757 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1758 accountModel.Actor = buildActor(account.Actor)
1760 channelModel.Account = accountModel
1762 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1763 videoModel.VideoChannel = channelModel
1765 videoModel.UserVideoHistories = []
1766 videoModel.Thumbnails = []
1767 videoModel.VideoFiles = []
1768 videoModel.VideoStreamingPlaylists = []
1770 videosMemo[row.id] = videoModel
1771 // Don't take object value to have a sorted array
1772 videos.push(videoModel)
1775 const videoModel = videosMemo[row.id]
1777 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1778 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1779 videoModel.UserVideoHistories.push(historyModel)
1781 historyDone.add(row.userVideoHistory.id)
1784 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1785 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1786 videoModel.Thumbnails.push(thumbnailModel)
1788 thumbnailsDone.add(row.Thumbnails.id)
1791 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1792 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1793 videoModel.VideoFiles.push(videoFileModel)
1795 videoFilesDone.add(row.VideoFiles.id)
1798 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1799 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1800 streamingPlaylist.VideoFiles = []
1802 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1804 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1807 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1808 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1810 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1811 streamingPlaylist.VideoFiles.push(videoFileModel)
1813 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1820 static getCategoryLabel (id: number) {
1821 return VIDEO_CATEGORIES[id] || 'Misc'
1824 static getLicenceLabel (id: number) {
1825 return VIDEO_LICENCES[id] || 'Unknown'
1828 static getLanguageLabel (id: string) {
1829 return VIDEO_LANGUAGES[id] || 'Unknown'
1832 static getPrivacyLabel (id: number) {
1833 return VIDEO_PRIVACIES[id] || 'Unknown'
1836 static getStateLabel (id: number) {
1837 return VIDEO_STATES[id] || 'Unknown'
1841 return !!this.VideoBlacklist
1845 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1848 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1849 // We first transcode to WebTorrent format, so try this array first
1850 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1851 const file = fun(this.VideoFiles, file => file.resolution)
1853 return Object.assign(file, { Video: this })
1856 // No webtorrent files, try with streaming playlist files
1857 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1858 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1860 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1861 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1867 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1868 return this.getQualityFileBy(maxBy)
1871 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1872 return this.getQualityFileBy(minBy)
1875 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1876 if (Array.isArray(this.VideoFiles) === false) return undefined
1878 const file = this.VideoFiles.find(f => f.resolution === resolution)
1879 if (!file) return undefined
1881 return Object.assign(file, { Video: this })
1884 hasWebTorrentFiles () {
1885 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1888 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1889 thumbnail.videoId = this.id
1891 const savedThumbnail = await thumbnail.save({ transaction })
1893 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1895 // Already have this thumbnail, skip
1896 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1898 this.Thumbnails.push(savedThumbnail)
1902 if (Array.isArray(this.Thumbnails) === false) return undefined
1904 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1908 return !!this.getPreview()
1912 if (Array.isArray(this.Thumbnails) === false) return undefined
1914 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1918 return this.remote === false
1921 getWatchStaticPath () {
1922 return '/videos/watch/' + this.uuid
1925 getEmbedStaticPath () {
1926 return '/videos/embed/' + this.uuid
1929 getMiniatureStaticPath () {
1930 const thumbnail = this.getMiniature()
1931 if (!thumbnail) return null
1933 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1936 getPreviewStaticPath () {
1937 const preview = this.getPreview()
1938 if (!preview) return null
1940 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1941 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1944 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1945 return videoModelToFormattedJSON(this, options)
1948 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1949 return videoModelToFormattedDetailsJSON(this)
1952 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1953 let files: VideoFile[] = []
1955 if (Array.isArray(this.VideoFiles)) {
1956 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1957 files = files.concat(result)
1960 for (const p of (this.VideoStreamingPlaylists || [])) {
1961 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1962 files = files.concat(result)
1968 toActivityPubObject (this: MVideoAP): VideoObject {
1969 return videoModelToActivityPubObject(this)
1972 getTruncatedDescription () {
1973 if (!this.description) return null
1975 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1976 return peertubeTruncate(this.description, { length: maxLength })
1979 getMaxQualityResolution () {
1980 const file = this.getMaxQualityFile()
1981 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1982 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1984 return getVideoFileResolution(originalFilePath)
1987 getDescriptionAPIPath () {
1988 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1991 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1992 if (!this.VideoStreamingPlaylists) return undefined
1994 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1995 playlist.Video = this
2000 setHLSPlaylist (playlist: MStreamingPlaylist) {
2001 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
2003 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
2004 this.VideoStreamingPlaylists = toAdd
2008 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
2009 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
2013 removeFile (videoFile: MVideoFile, isRedundancy = false) {
2014 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
2015 return remove(filePath)
2016 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
2019 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
2020 const directoryPath = getHLSDirectory(this, isRedundancy)
2022 await remove(directoryPath)
2024 if (isRedundancy !== true) {
2025 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2026 streamingPlaylistWithFiles.Video = this
2028 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2029 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2032 // Remove physical files and torrents
2034 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2040 if (this.isOwned()) return false
2042 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2045 hasPrivacyForFederation () {
2046 return isPrivacyForFederation(this.privacy)
2049 hasStateForFederation () {
2050 return isStateForFederation(this.state)
2053 isNewVideo (newPrivacy: VideoPrivacy) {
2054 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2058 return setAsUpdated('video', this.id)
2062 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2065 setPrivacy (newPrivacy: VideoPrivacy) {
2066 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2067 this.publishedAt = new Date()
2070 this.privacy = newPrivacy
2074 return this.privacy === VideoPrivacy.PRIVATE ||
2075 this.privacy === VideoPrivacy.UNLISTED ||
2076 this.privacy === VideoPrivacy.INTERNAL
2079 async publishIfNeededAndSave (t: Transaction) {
2080 if (this.state !== VideoState.PUBLISHED) {
2081 this.state = VideoState.PUBLISHED
2082 this.publishedAt = new Date()
2083 await this.save({ transaction: t })
2091 getBandwidthBits (videoFile: MVideoFile) {
2092 return Math.ceil((videoFile.size * 8) / this.duration)
2096 if (this.isOwned()) {
2098 WEBSERVER.URL + '/tracker/announce',
2099 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2103 return this.Trackers.map(t => t.url)