1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy } from 'lodash'
4 import { join } from 'path'
5 import { FindOptions, Includeable, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
26 } from 'sequelize-typescript'
27 import { setAsUpdated } from '@server/helpers/database-utils'
28 import { buildNSFWFilter } from '@server/helpers/express-utils'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live-manager'
31 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { AttributesOnly } from '@shared/core-utils'
35 import { VideoFile } from '@shared/models/videos/video-file.model'
36 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
37 import { VideoObject } from '../../../shared/models/activitypub/objects'
38 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
39 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
42 import { peertubeTruncate } from '../../helpers/core-utils'
43 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
44 import { isBooleanValid } from '../../helpers/custom-validators/misc'
47 isVideoDescriptionValid,
55 } from '../../helpers/custom-validators/videos'
56 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
57 import { logger } from '../../helpers/logger'
58 import { CONFIG } from '../../initializers/config'
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'
114 videoFilesModelToFormattedJSON,
115 VideoFormattingJSONOptions,
116 videoModelToActivityPubObject,
117 videoModelToFormattedDetailsJSON,
118 videoModelToFormattedJSON
119 } from './formatter/video-format-utils'
120 import { ScheduleVideoUpdateModel } from './schedule-video-update'
121 import { BuildVideosListQueryOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
122 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
123 import { TagModel } from './tag'
124 import { ThumbnailModel } from './thumbnail'
125 import { VideoBlacklistModel } from './video-blacklist'
126 import { VideoCaptionModel } from './video-caption'
127 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
128 import { VideoCommentModel } from './video-comment'
129 import { VideoFileModel } from './video-file'
130 import { VideoImportModel } from './video-import'
131 import { VideoLiveModel } from './video-live'
132 import { VideoPlaylistElementModel } from './video-playlist-element'
133 import { VideoShareModel } from './video-share'
134 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
135 import { VideoTagModel } from './video-tag'
136 import { VideoViewModel } from './video-view'
138 export enum ScopeNames {
139 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
141 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
142 WITH_TAGS = 'WITH_TAGS',
143 WITH_TRACKERS = 'WITH_TRACKERS',
144 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
145 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
146 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
147 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
148 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
149 WITH_USER_ID = 'WITH_USER_ID',
150 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
151 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
152 WITH_LIVE = 'WITH_LIVE'
155 export type ForAPIOptions = {
158 videoPlaylistId?: number
160 withAccountBlockerIds?: number[]
163 export type AvailableForListIDsOptions = {
164 serverAccountId: number
165 followerActorId: number
166 includeLocalVideos: boolean
168 attributesType?: 'none' | 'id' | 'all'
171 categoryOneOf?: number[]
173 licenceOneOf?: number[]
174 languageOneOf?: string[]
181 videoChannelId?: number
183 videoPlaylistId?: number
185 trendingDays?: number
186 user?: MUserAccountId
187 historyOfUser?: MUserId
189 baseWhere?: WhereOptions[]
193 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
194 attributes: [ 'id', 'url', 'uuid', 'remote' ]
196 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
197 const include: Includeable[] = [
199 model: VideoChannelModel.scope({
201 VideoChannelScopeNames.SUMMARY, {
203 withAccountBlockerIds: options.withAccountBlockerIds
210 attributes: [ 'type', 'filename' ],
211 model: ThumbnailModel,
216 const query: FindOptions = {}
226 if (options.videoPlaylistId) {
228 model: VideoPlaylistElementModel.unscoped(),
231 videoPlaylistId: options.videoPlaylistId
236 query.include = include
240 [ScopeNames.WITH_THUMBNAILS]: {
243 model: ThumbnailModel,
248 [ScopeNames.WITH_LIVE]: {
251 model: VideoLiveModel.unscoped(),
256 [ScopeNames.WITH_USER_ID]: {
259 attributes: [ 'accountId' ],
260 model: VideoChannelModel.unscoped(),
264 attributes: [ 'userId' ],
265 model: AccountModel.unscoped(),
272 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
275 model: VideoChannelModel.unscoped(),
280 exclude: [ 'privateKey', 'publicKey' ]
282 model: ActorModel.unscoped(),
286 attributes: [ 'host' ],
287 model: ServerModel.unscoped(),
291 model: ActorImageModel.unscoped(),
298 model: AccountModel.unscoped(),
302 model: ActorModel.unscoped(),
304 exclude: [ 'privateKey', 'publicKey' ]
309 attributes: [ 'host' ],
310 model: ServerModel.unscoped(),
314 model: ActorImageModel.unscoped(),
326 [ScopeNames.WITH_TAGS]: {
327 include: [ TagModel ]
329 [ScopeNames.WITH_TRACKERS]: {
332 attributes: [ 'id', 'url' ],
337 [ScopeNames.WITH_BLACKLISTED]: {
340 attributes: [ 'id', 'reason', 'unfederated' ],
341 model: VideoBlacklistModel,
346 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
347 let subInclude: any[] = []
349 if (withRedundancies === true) {
352 attributes: [ 'fileUrl' ],
353 model: VideoRedundancyModel.unscoped(),
362 model: VideoFileModel,
370 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
371 const subInclude: IncludeOptions[] = [
373 model: VideoFileModel,
378 if (withRedundancies === true) {
380 attributes: [ 'fileUrl' ],
381 model: VideoRedundancyModel.unscoped(),
389 model: VideoStreamingPlaylistModel.unscoped(),
397 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
400 model: ScheduleVideoUpdateModel.unscoped(),
405 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
409 attributes: [ 'currentTime' ],
410 model: UserVideoHistoryModel.unscoped(),
423 buildTrigramSearchIndex('video_name_trigram', 'name'),
425 { fields: [ 'createdAt' ] },
428 { name: 'publishedAt', order: 'DESC' },
429 { name: 'id', order: 'ASC' }
432 { fields: [ 'duration' ] },
435 { name: 'views', order: 'DESC' },
436 { name: 'id', order: 'ASC' }
439 { fields: [ 'channelId' ] },
441 fields: [ 'originallyPublishedAt' ],
443 originallyPublishedAt: {
449 fields: [ 'category' ], // We don't care videos with an unknown category
457 fields: [ 'licence' ], // We don't care videos with an unknown licence
465 fields: [ 'language' ], // We don't care videos with an unknown language
473 fields: [ 'nsfw' ], // Most of the videos are not NSFW
479 fields: [ 'remote' ], // Only index local videos
494 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
497 @Default(DataType.UUIDV4)
499 @Column(DataType.UUID)
503 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
509 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
515 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
521 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
522 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
526 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
528 privacy: VideoPrivacy
531 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
537 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
538 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
543 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
544 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
548 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
583 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
584 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
589 commentsEnabled: boolean
593 downloadEnabled: boolean
597 waitTranscoding: boolean
601 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
612 @Default(DataType.NOW)
619 originallyPublishedAt: Date
621 @ForeignKey(() => VideoChannelModel)
625 @BelongsTo(() => VideoChannelModel, {
631 VideoChannel: VideoChannelModel
633 @BelongsToMany(() => TagModel, {
634 foreignKey: 'videoId',
635 through: () => VideoTagModel,
640 @BelongsToMany(() => TrackerModel, {
641 foreignKey: 'videoId',
642 through: () => VideoTrackerModel,
645 Trackers: TrackerModel[]
647 @HasMany(() => ThumbnailModel, {
655 Thumbnails: ThumbnailModel[]
657 @HasMany(() => VideoPlaylistElementModel, {
664 VideoPlaylistElements: VideoPlaylistElementModel[]
666 @HasMany(() => VideoAbuseModel, {
673 VideoAbuses: VideoAbuseModel[]
675 @HasMany(() => VideoFileModel, {
683 VideoFiles: VideoFileModel[]
685 @HasMany(() => VideoStreamingPlaylistModel, {
693 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
695 @HasMany(() => VideoShareModel, {
702 VideoShares: VideoShareModel[]
704 @HasMany(() => AccountVideoRateModel, {
711 AccountVideoRates: AccountVideoRateModel[]
713 @HasMany(() => VideoCommentModel, {
721 VideoComments: VideoCommentModel[]
723 @HasMany(() => VideoViewModel, {
730 VideoViews: VideoViewModel[]
732 @HasMany(() => UserVideoHistoryModel, {
739 UserVideoHistories: UserVideoHistoryModel[]
741 @HasOne(() => ScheduleVideoUpdateModel, {
748 ScheduleVideoUpdate: ScheduleVideoUpdateModel
750 @HasOne(() => VideoBlacklistModel, {
757 VideoBlacklist: VideoBlacklistModel
759 @HasOne(() => VideoLiveModel, {
766 VideoLive: VideoLiveModel
768 @HasOne(() => VideoImportModel, {
775 VideoImport: VideoImportModel
777 @HasMany(() => VideoCaptionModel, {
784 ['separate' as any]: true
786 VideoCaptions: VideoCaptionModel[]
789 static async sendDelete (instance: MVideoAccountLight, options) {
790 if (!instance.isOwned()) return undefined
792 // Lazy load channels
793 if (!instance.VideoChannel) {
794 instance.VideoChannel = await instance.$get('VideoChannel', {
799 transaction: options.transaction
800 }) as MChannelAccountDefault
803 return sendDeleteVideo(instance, options.transaction)
807 static async removeFiles (instance: VideoModel) {
808 const tasks: Promise<any>[] = []
810 logger.info('Removing files of video %s.', instance.url)
812 if (instance.isOwned()) {
813 if (!Array.isArray(instance.VideoFiles)) {
814 instance.VideoFiles = await instance.$get('VideoFiles')
817 // Remove physical files and torrents
818 instance.VideoFiles.forEach(file => {
819 tasks.push(instance.removeFile(file))
820 tasks.push(file.removeTorrent())
823 // Remove playlists file
824 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
825 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
828 for (const p of instance.VideoStreamingPlaylists) {
829 tasks.push(instance.removeStreamingPlaylistFiles(p))
833 // Do not wait video deletion because we could be in a transaction
836 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
843 static stopLiveIfNeeded (instance: VideoModel) {
844 if (!instance.isLive) return
846 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
848 return LiveManager.Instance.stopSessionOf(instance.id)
852 static invalidateCache (instance: VideoModel) {
853 ModelCache.Instance.invalidateCache('video', instance.id)
857 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
858 const tasks: Promise<any>[] = []
860 if (!Array.isArray(instance.VideoAbuses)) {
861 instance.VideoAbuses = await instance.$get('VideoAbuses')
863 if (instance.VideoAbuses.length === 0) return undefined
866 logger.info('Saving video abuses details of video %s.', instance.url)
868 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
869 const details = instance.toFormattedDetailsJSON()
871 for (const abuse of instance.VideoAbuses) {
872 abuse.deletedVideo = details
873 tasks.push(abuse.save({ transaction: options.transaction }))
878 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
884 static listLocal (): Promise<MVideo[]> {
891 return VideoModel.findAll(query)
894 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
895 function getRawQuery (select: string) {
896 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
897 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
898 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
899 'WHERE "Account"."actorId" = ' + actorId
900 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
901 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
902 'WHERE "VideoShare"."actorId" = ' + actorId
904 return `(${queryVideo}) UNION (${queryVideoShare})`
907 const rawQuery = getRawQuery('"Video"."id"')
908 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
914 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
917 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
919 [Op.or]: getPrivaciesForFederation()
923 attributes: [ 'filename', 'language', 'fileUrl' ],
924 model: VideoCaptionModel.unscoped(),
928 attributes: [ 'id', 'url' ],
929 model: VideoShareModel.unscoped(),
931 // We only want videos shared by this actor
946 attributes: [ 'id', 'url' ],
947 model: ActorModel.unscoped()
952 model: VideoChannelModel.unscoped(),
956 attributes: [ 'name' ],
957 model: AccountModel.unscoped(),
961 attributes: [ 'id', 'url', 'followersUrl' ],
962 model: ActorModel.unscoped(),
968 attributes: [ 'id', 'url', 'followersUrl' ],
969 model: ActorModel.unscoped(),
975 model: VideoStreamingPlaylistModel.unscoped(),
979 model: VideoFileModel,
984 VideoLiveModel.unscoped(),
990 return Bluebird.all([
991 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
992 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
993 ]).then(([ rows, totals ]) => {
994 // totals: totalVideos + totalVideoShares
996 let totalVideoShares = 0
997 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
998 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
1000 const total = totalVideos + totalVideoShares
1008 static async listPublishedLiveUUIDs () {
1010 attributes: [ 'uuid' ],
1014 state: VideoState.PUBLISHED
1018 const result = await VideoModel.findAll(options)
1020 return result.map(v => v.uuid)
1023 static listUserVideosForApi (options: {
1031 const { accountId, start, count, sort, search, isLive } = options
1033 function buildBaseQuery (): FindOptions {
1034 const where: WhereOptions = {}
1038 [Op.iLike]: '%' + search + '%'
1043 where.isLive = isLive
1050 order: getVideoSort(sort),
1053 model: VideoChannelModel,
1057 model: AccountModel,
1071 const countQuery = buildBaseQuery()
1072 const findQuery = buildBaseQuery()
1074 const findScopes: (string | ScopeOptions)[] = [
1075 ScopeNames.WITH_SCHEDULED_UPDATE,
1076 ScopeNames.WITH_BLACKLISTED,
1077 ScopeNames.WITH_THUMBNAILS
1080 return Promise.all([
1081 VideoModel.count(countQuery),
1082 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1083 ]).then(([ count, rows ]) => {
1091 static async listForApi (options: {
1097 filter?: VideoFilter
1100 includeLocalVideos: boolean
1103 categoryOneOf?: number[]
1104 licenceOneOf?: number[]
1105 languageOneOf?: string[]
1106 tagsOneOf?: string[]
1107 tagsAllOf?: string[]
1110 videoChannelId?: number
1112 followerActorId?: number
1114 videoPlaylistId?: number
1116 trendingDays?: number
1118 user?: MUserAccountId
1119 historyOfUser?: MUserId
1121 countVideos?: boolean
1125 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1126 throw new Error('Try to filter all-local but no user has not the see all videos right')
1129 const trendingDays = options.sort.endsWith('trending')
1130 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1132 let trendingAlgorithm
1133 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1134 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1136 const serverActor = await getServerActor()
1138 // followerActorId === null has a meaning, so just check undefined
1139 const followerActorId = options.followerActorId !== undefined
1140 ? options.followerActorId
1143 const queryOptions = {
1144 start: options.start,
1145 count: options.count,
1148 serverAccountId: serverActor.Account.id,
1150 isLive: options.isLive,
1151 categoryOneOf: options.categoryOneOf,
1152 licenceOneOf: options.licenceOneOf,
1153 languageOneOf: options.languageOneOf,
1154 tagsOneOf: options.tagsOneOf,
1155 tagsAllOf: options.tagsAllOf,
1156 filter: options.filter,
1157 withFiles: options.withFiles,
1158 accountId: options.accountId,
1159 videoChannelId: options.videoChannelId,
1160 videoPlaylistId: options.videoPlaylistId,
1161 includeLocalVideos: options.includeLocalVideos,
1163 historyOfUser: options.historyOfUser,
1166 search: options.search
1169 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1172 static async searchAndPopulateAccountAndServer (options: {
1173 includeLocalVideos: boolean
1178 startDate?: string // ISO 8601
1179 endDate?: string // ISO 8601
1180 originallyPublishedStartDate?: string
1181 originallyPublishedEndDate?: string
1184 categoryOneOf?: number[]
1185 licenceOneOf?: number[]
1186 languageOneOf?: string[]
1187 tagsOneOf?: string[]
1188 tagsAllOf?: string[]
1189 durationMin?: number // seconds
1190 durationMax?: number // seconds
1191 user?: MUserAccountId
1192 filter?: VideoFilter
1194 const serverActor = await getServerActor()
1196 const queryOptions = {
1197 followerActorId: serverActor.id,
1198 serverAccountId: serverActor.Account.id,
1200 includeLocalVideos: options.includeLocalVideos,
1202 isLive: options.isLive,
1204 categoryOneOf: options.categoryOneOf,
1205 licenceOneOf: options.licenceOneOf,
1206 languageOneOf: options.languageOneOf,
1208 tagsOneOf: options.tagsOneOf,
1209 tagsAllOf: options.tagsAllOf,
1212 filter: options.filter,
1214 start: options.start,
1215 count: options.count,
1218 startDate: options.startDate,
1219 endDate: options.endDate,
1221 originallyPublishedStartDate: options.originallyPublishedStartDate,
1222 originallyPublishedEndDate: options.originallyPublishedEndDate,
1224 durationMin: options.durationMin,
1225 durationMax: options.durationMax,
1227 search: options.search
1230 return VideoModel.getAvailableForApi(queryOptions)
1233 static countLocalLives () {
1239 [Op.ne]: VideoState.LIVE_ENDED
1244 return VideoModel.count(options)
1247 static countVideosUploadedByUserSince (userId: number, since: Date) {
1251 model: VideoChannelModel.unscoped(),
1255 model: AccountModel.unscoped(),
1259 model: UserModel.unscoped(),
1277 return VideoModel.unscoped().count(options)
1280 static countLivesOfAccount (accountId: number) {
1286 [Op.ne]: VideoState.LIVE_ENDED
1292 model: VideoChannelModel.unscoped(),
1300 return VideoModel.count(options)
1303 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1304 const where = buildWhereIdOrUUID(id)
1310 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1313 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1314 const where = buildWhereIdOrUUID(id)
1320 return VideoModel.scope([
1321 ScopeNames.WITH_THUMBNAILS,
1322 ScopeNames.WITH_BLACKLISTED
1326 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1329 where: buildWhereIdOrUUID(id),
1333 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1336 return ModelCache.Instance.doCache({
1337 cacheType: 'load-video-immutable-id',
1344 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1345 const where = buildWhereIdOrUUID(id)
1351 return VideoModel.scope([
1352 ScopeNames.WITH_BLACKLISTED,
1353 ScopeNames.WITH_USER_ID
1357 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1358 const where = buildWhereIdOrUUID(id)
1361 attributes: [ 'id' ],
1366 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1369 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1370 const where = buildWhereIdOrUUID(id)
1378 return VideoModel.scope([
1379 ScopeNames.WITH_WEBTORRENT_FILES,
1380 ScopeNames.WITH_STREAMING_PLAYLISTS,
1381 ScopeNames.WITH_THUMBNAILS
1385 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1392 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1395 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1396 const query: FindOptions = {
1403 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1406 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1408 const query: FindOptions = {
1415 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1418 return ModelCache.Instance.doCache({
1419 cacheType: 'load-video-immutable-url',
1426 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1427 const query: FindOptions = {
1434 return VideoModel.scope([
1435 ScopeNames.WITH_ACCOUNT_DETAILS,
1436 ScopeNames.WITH_WEBTORRENT_FILES,
1437 ScopeNames.WITH_STREAMING_PLAYLISTS,
1438 ScopeNames.WITH_THUMBNAILS,
1439 ScopeNames.WITH_BLACKLISTED
1443 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1444 const where = buildWhereIdOrUUID(id)
1447 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1452 const scopes: (string | ScopeOptions)[] = [
1453 ScopeNames.WITH_TAGS,
1454 ScopeNames.WITH_BLACKLISTED,
1455 ScopeNames.WITH_ACCOUNT_DETAILS,
1456 ScopeNames.WITH_SCHEDULED_UPDATE,
1457 ScopeNames.WITH_WEBTORRENT_FILES,
1458 ScopeNames.WITH_STREAMING_PLAYLISTS,
1459 ScopeNames.WITH_THUMBNAILS,
1460 ScopeNames.WITH_LIVE
1464 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1472 static loadForGetAPI (parameters: {
1476 }): Promise<MVideoDetails> {
1477 const { id, t, userId } = parameters
1478 const where = buildWhereIdOrUUID(id)
1481 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1486 const scopes: (string | ScopeOptions)[] = [
1487 ScopeNames.WITH_TAGS,
1488 ScopeNames.WITH_BLACKLISTED,
1489 ScopeNames.WITH_ACCOUNT_DETAILS,
1490 ScopeNames.WITH_SCHEDULED_UPDATE,
1491 ScopeNames.WITH_THUMBNAILS,
1492 ScopeNames.WITH_LIVE,
1493 ScopeNames.WITH_TRACKERS,
1494 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1495 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1499 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1507 static async getStats () {
1508 const totalLocalVideos = await VideoModel.count({
1514 let totalLocalVideoViews = await VideoModel.sum('views', {
1520 // Sequelize could return null...
1521 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1523 const { total: totalVideos } = await VideoModel.listForApi({
1526 sort: '-publishedAt',
1527 nsfw: buildNSFWFilter(),
1528 includeLocalVideos: true,
1534 totalLocalVideoViews,
1539 static incrementViews (id: number, views: number) {
1540 return VideoModel.increment('views', {
1548 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1549 const field = type === 'like'
1553 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1555 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1557 'WHERE "video"."id" = :videoId'
1559 return AccountVideoRateModel.sequelize.query(rawQuery, {
1561 replacements: { videoId, rateType: type },
1562 type: QueryTypes.UPDATE
1566 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1567 // Instances only share videos
1568 const query = 'SELECT 1 FROM "videoShare" ' +
1569 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1570 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1574 type: QueryTypes.SELECT as QueryTypes.SELECT,
1575 bind: { followerActorId, videoId },
1579 return VideoModel.sequelize.query(query, options)
1580 .then(results => results.length === 1)
1583 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1586 channelId: videoChannel.id
1591 return VideoModel.update({ support: videoChannel.support }, options)
1594 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1596 attributes: [ 'id' ],
1598 channelId: videoChannel.id
1602 return VideoModel.findAll(query)
1603 .then(videos => videos.map(v => v.id))
1606 // threshold corresponds to how many video the field should have to be returned
1607 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1608 const serverActor = await getServerActor()
1609 const followerActorId = serverActor.id
1611 const queryOptions: BuildVideosListQueryOptions = {
1612 attributes: [ `"${field}"` ],
1613 group: `GROUP BY "${field}"`,
1614 having: `HAVING COUNT("${field}") >= ${threshold}`,
1618 serverAccountId: serverActor.Account.id,
1620 includeLocalVideos: true
1623 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1625 return queryBuilder.queryVideoIds(queryOptions)
1626 .then(rows => rows.map(r => r[field]))
1629 static buildTrendingQuery (trendingDays: number) {
1633 model: VideoViewModel,
1637 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1643 private static async getAvailableForApi (
1644 options: BuildVideosListQueryOptions,
1646 ): Promise<ResultList<VideoModel>> {
1647 function getCount () {
1648 if (countVideos !== true) return Promise.resolve(undefined)
1650 const countOptions = Object.assign({}, options, { isCount: true })
1651 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1653 return queryBuilder.countVideoIds(countOptions)
1656 function getModels () {
1657 if (options.count === 0) return Promise.resolve([])
1659 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1661 return queryBuilder.queryVideos(options)
1664 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1672 static getCategoryLabel (id: number) {
1673 return VIDEO_CATEGORIES[id] || 'Misc'
1676 static getLicenceLabel (id: number) {
1677 return VIDEO_LICENCES[id] || 'Unknown'
1680 static getLanguageLabel (id: string) {
1681 return VIDEO_LANGUAGES[id] || 'Unknown'
1684 static getPrivacyLabel (id: number) {
1685 return VIDEO_PRIVACIES[id] || 'Unknown'
1688 static getStateLabel (id: number) {
1689 return VIDEO_STATES[id] || 'Unknown'
1693 return !!this.VideoBlacklist
1697 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1700 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1701 // We first transcode to WebTorrent format, so try this array first
1702 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1703 const file = fun(this.VideoFiles, file => file.resolution)
1705 return Object.assign(file, { Video: this })
1708 // No webtorrent files, try with streaming playlist files
1709 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1710 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1712 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1713 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1719 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1720 return this.getQualityFileBy(maxBy)
1723 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1724 return this.getQualityFileBy(minBy)
1727 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1728 if (Array.isArray(this.VideoFiles) === false) return undefined
1730 const file = this.VideoFiles.find(f => f.resolution === resolution)
1731 if (!file) return undefined
1733 return Object.assign(file, { Video: this })
1736 hasWebTorrentFiles () {
1737 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1740 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1741 thumbnail.videoId = this.id
1743 const savedThumbnail = await thumbnail.save({ transaction })
1745 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1747 // Already have this thumbnail, skip
1748 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1750 this.Thumbnails.push(savedThumbnail)
1754 if (Array.isArray(this.Thumbnails) === false) return undefined
1756 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1760 return !!this.getPreview()
1764 if (Array.isArray(this.Thumbnails) === false) return undefined
1766 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1770 return this.remote === false
1773 getWatchStaticPath () {
1774 return '/w/' + this.uuid
1777 getEmbedStaticPath () {
1778 return '/videos/embed/' + this.uuid
1781 getMiniatureStaticPath () {
1782 const thumbnail = this.getMiniature()
1783 if (!thumbnail) return null
1785 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1788 getPreviewStaticPath () {
1789 const preview = this.getPreview()
1790 if (!preview) return null
1792 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1793 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1796 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1797 return videoModelToFormattedJSON(this, options)
1800 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1801 return videoModelToFormattedDetailsJSON(this)
1804 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1805 let files: VideoFile[] = []
1807 if (Array.isArray(this.VideoFiles)) {
1808 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1809 files = files.concat(result)
1812 for (const p of (this.VideoStreamingPlaylists || [])) {
1813 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1814 files = files.concat(result)
1820 toActivityPubObject (this: MVideoAP): VideoObject {
1821 return videoModelToActivityPubObject(this)
1824 getTruncatedDescription () {
1825 if (!this.description) return null
1827 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1828 return peertubeTruncate(this.description, { length: maxLength })
1831 getMaxQualityResolution () {
1832 const file = this.getMaxQualityFile()
1833 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1834 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1836 return getVideoFileResolution(originalFilePath)
1839 getDescriptionAPIPath () {
1840 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1843 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1844 if (!this.VideoStreamingPlaylists) return undefined
1846 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1847 playlist.Video = this
1852 setHLSPlaylist (playlist: MStreamingPlaylist) {
1853 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1855 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1856 this.VideoStreamingPlaylists = toAdd
1860 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1861 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1865 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1866 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1867 return remove(filePath)
1868 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1871 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1872 const directoryPath = getHLSDirectory(this, isRedundancy)
1874 await remove(directoryPath)
1876 if (isRedundancy !== true) {
1877 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1878 streamingPlaylistWithFiles.Video = this
1880 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1881 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1884 // Remove physical files and torrents
1886 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1892 if (this.isOwned()) return false
1894 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1897 hasPrivacyForFederation () {
1898 return isPrivacyForFederation(this.privacy)
1901 hasStateForFederation () {
1902 return isStateForFederation(this.state)
1905 isNewVideo (newPrivacy: VideoPrivacy) {
1906 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1910 return setAsUpdated('video', this.id)
1914 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1917 setPrivacy (newPrivacy: VideoPrivacy) {
1918 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1919 this.publishedAt = new Date()
1922 this.privacy = newPrivacy
1926 return this.privacy === VideoPrivacy.PRIVATE ||
1927 this.privacy === VideoPrivacy.UNLISTED ||
1928 this.privacy === VideoPrivacy.INTERNAL
1931 async publishIfNeededAndSave (t: Transaction) {
1932 if (this.state !== VideoState.PUBLISHED) {
1933 this.state = VideoState.PUBLISHED
1934 this.publishedAt = new Date()
1935 await this.save({ transaction: t })
1943 getBandwidthBits (videoFile: MVideoFile) {
1944 return Math.ceil((videoFile.size * 8) / this.duration)
1948 if (this.isOwned()) {
1950 WEBSERVER.URL + '/tracker/announce',
1951 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1955 return this.Trackers.map(t => t.url)