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/live-manager'
31 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { AttributesOnly } from '@shared/core-utils'
35 import { VideoFile } from '@shared/models/videos/video-file.model'
36 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
37 import { VideoObject } from '../../../shared/models/activitypub/objects'
38 import { Video, VideoDetails, VideoRateType } from '../../../shared/models/videos'
39 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
42 import { peertubeTruncate } from '../../helpers/core-utils'
43 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
44 import { isBooleanValid } from '../../helpers/custom-validators/misc'
47 isVideoDescriptionValid,
55 } from '../../helpers/custom-validators/videos'
56 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
57 import { logger } from '../../helpers/logger'
58 import { CONFIG } from '../../initializers/config'
59 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
60 import { sendDeleteVideo } from '../../lib/activitypub/send'
63 MChannelAccountDefault,
66 MStreamingPlaylistFilesVideo,
71 MVideoAccountLightBlacklistAllFiles,
76 MVideoFormattableDetails,
82 MVideoThumbnailBlacklist,
85 } from '../../types/models'
86 import { MThumbnail } from '../../types/models/video/thumbnail'
87 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
88 import { VideoAbuseModel } from '../abuse/video-abuse'
89 import { AccountModel } from '../account/account'
90 import { AccountVideoRateModel } from '../account/account-video-rate'
91 import { ActorModel } from '../actor/actor'
92 import { ActorImageModel } from '../actor/actor-image'
93 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
94 import { ServerModel } from '../server/server'
95 import { TrackerModel } from '../server/tracker'
96 import { VideoTrackerModel } from '../server/video-tracker'
97 import { UserModel } from '../user/user'
98 import { UserVideoHistoryModel } from '../user/user-video-history'
99 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
101 videoFilesModelToFormattedJSON,
102 VideoFormattingJSONOptions,
103 videoModelToActivityPubObject,
104 videoModelToFormattedDetailsJSON,
105 videoModelToFormattedJSON
106 } from './formatter/video-format-utils'
107 import { ScheduleVideoUpdateModel } from './schedule-video-update'
108 import { VideosModelGetQueryBuilder } from './sql/video-model-get-query-builder'
109 import { BuildVideosListQueryOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
110 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
111 import { TagModel } from './tag'
112 import { ThumbnailModel } from './thumbnail'
113 import { VideoBlacklistModel } from './video-blacklist'
114 import { VideoCaptionModel } from './video-caption'
115 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
116 import { VideoCommentModel } from './video-comment'
117 import { VideoFileModel } from './video-file'
118 import { VideoImportModel } from './video-import'
119 import { VideoLiveModel } from './video-live'
120 import { VideoPlaylistElementModel } from './video-playlist-element'
121 import { VideoShareModel } from './video-share'
122 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
123 import { VideoTagModel } from './video-tag'
124 import { VideoViewModel } from './video-view'
126 export enum ScopeNames {
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
134 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
135 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
136 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
139 export type ForAPIOptions = {
142 videoPlaylistId?: number
144 withAccountBlockerIds?: number[]
147 export type AvailableForListIDsOptions = {
148 serverAccountId: number
149 followerActorId: number
150 includeLocalVideos: boolean
152 attributesType?: 'none' | 'id' | 'all'
155 categoryOneOf?: number[]
157 licenceOneOf?: number[]
158 languageOneOf?: string[]
165 videoChannelId?: number
167 videoPlaylistId?: number
169 trendingDays?: number
170 user?: MUserAccountId
171 historyOfUser?: MUserId
173 baseWhere?: WhereOptions[]
177 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
178 attributes: [ 'id', 'url', 'uuid', 'remote' ]
180 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
181 const include: Includeable[] = [
183 model: VideoChannelModel.scope({
185 VideoChannelScopeNames.SUMMARY, {
187 withAccountBlockerIds: options.withAccountBlockerIds
194 attributes: [ 'type', 'filename' ],
195 model: ThumbnailModel,
200 const query: FindOptions = {}
210 if (options.videoPlaylistId) {
212 model: VideoPlaylistElementModel.unscoped(),
215 videoPlaylistId: options.videoPlaylistId
220 query.include = include
224 [ScopeNames.WITH_THUMBNAILS]: {
227 model: ThumbnailModel,
232 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
235 model: VideoChannelModel.unscoped(),
240 exclude: [ 'privateKey', 'publicKey' ]
242 model: ActorModel.unscoped(),
246 attributes: [ 'host' ],
247 model: ServerModel.unscoped(),
251 model: ActorImageModel.unscoped(),
258 model: AccountModel.unscoped(),
262 model: ActorModel.unscoped(),
264 exclude: [ 'privateKey', 'publicKey' ]
269 attributes: [ 'host' ],
270 model: ServerModel.unscoped(),
274 model: ActorImageModel.unscoped(),
286 [ScopeNames.WITH_TAGS]: {
287 include: [ TagModel ]
289 [ScopeNames.WITH_BLACKLISTED]: {
292 attributes: [ 'id', 'reason', 'unfederated' ],
293 model: VideoBlacklistModel,
298 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
299 let subInclude: any[] = []
301 if (withRedundancies === true) {
304 attributes: [ 'fileUrl' ],
305 model: VideoRedundancyModel.unscoped(),
314 model: VideoFileModel,
322 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
323 const subInclude: IncludeOptions[] = [
325 model: VideoFileModel,
330 if (withRedundancies === true) {
332 attributes: [ 'fileUrl' ],
333 model: VideoRedundancyModel.unscoped(),
341 model: VideoStreamingPlaylistModel.unscoped(),
349 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
352 model: ScheduleVideoUpdateModel.unscoped(),
357 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
361 attributes: [ 'currentTime' ],
362 model: UserVideoHistoryModel.unscoped(),
375 buildTrigramSearchIndex('video_name_trigram', 'name'),
377 { fields: [ 'createdAt' ] },
380 { name: 'publishedAt', order: 'DESC' },
381 { name: 'id', order: 'ASC' }
384 { fields: [ 'duration' ] },
387 { name: 'views', order: 'DESC' },
388 { name: 'id', order: 'ASC' }
391 { fields: [ 'channelId' ] },
393 fields: [ 'originallyPublishedAt' ],
395 originallyPublishedAt: {
401 fields: [ 'category' ], // We don't care videos with an unknown category
409 fields: [ 'licence' ], // We don't care videos with an unknown licence
417 fields: [ 'language' ], // We don't care videos with an unknown language
425 fields: [ 'nsfw' ], // Most of the videos are not NSFW
431 fields: [ 'remote' ], // Only index local videos
446 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
449 @Default(DataType.UUIDV4)
451 @Column(DataType.UUID)
455 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
461 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
467 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
473 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
474 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
478 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
480 privacy: VideoPrivacy
483 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
489 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
490 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
495 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
496 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
500 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
535 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
536 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
541 commentsEnabled: boolean
545 downloadEnabled: boolean
549 waitTranscoding: boolean
553 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
564 @Default(DataType.NOW)
571 originallyPublishedAt: Date
573 @ForeignKey(() => VideoChannelModel)
577 @BelongsTo(() => VideoChannelModel, {
583 VideoChannel: VideoChannelModel
585 @BelongsToMany(() => TagModel, {
586 foreignKey: 'videoId',
587 through: () => VideoTagModel,
592 @BelongsToMany(() => TrackerModel, {
593 foreignKey: 'videoId',
594 through: () => VideoTrackerModel,
597 Trackers: TrackerModel[]
599 @HasMany(() => ThumbnailModel, {
607 Thumbnails: ThumbnailModel[]
609 @HasMany(() => VideoPlaylistElementModel, {
616 VideoPlaylistElements: VideoPlaylistElementModel[]
618 @HasMany(() => VideoAbuseModel, {
625 VideoAbuses: VideoAbuseModel[]
627 @HasMany(() => VideoFileModel, {
635 VideoFiles: VideoFileModel[]
637 @HasMany(() => VideoStreamingPlaylistModel, {
645 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
647 @HasMany(() => VideoShareModel, {
654 VideoShares: VideoShareModel[]
656 @HasMany(() => AccountVideoRateModel, {
663 AccountVideoRates: AccountVideoRateModel[]
665 @HasMany(() => VideoCommentModel, {
673 VideoComments: VideoCommentModel[]
675 @HasMany(() => VideoViewModel, {
682 VideoViews: VideoViewModel[]
684 @HasMany(() => UserVideoHistoryModel, {
691 UserVideoHistories: UserVideoHistoryModel[]
693 @HasOne(() => ScheduleVideoUpdateModel, {
700 ScheduleVideoUpdate: ScheduleVideoUpdateModel
702 @HasOne(() => VideoBlacklistModel, {
709 VideoBlacklist: VideoBlacklistModel
711 @HasOne(() => VideoLiveModel, {
718 VideoLive: VideoLiveModel
720 @HasOne(() => VideoImportModel, {
727 VideoImport: VideoImportModel
729 @HasMany(() => VideoCaptionModel, {
736 ['separate' as any]: true
738 VideoCaptions: VideoCaptionModel[]
741 static async sendDelete (instance: MVideoAccountLight, options) {
742 if (!instance.isOwned()) return undefined
744 // Lazy load channels
745 if (!instance.VideoChannel) {
746 instance.VideoChannel = await instance.$get('VideoChannel', {
751 transaction: options.transaction
752 }) as MChannelAccountDefault
755 return sendDeleteVideo(instance, options.transaction)
759 static async removeFiles (instance: VideoModel, options) {
760 const tasks: Promise<any>[] = []
762 logger.info('Removing files of video %s.', instance.url)
764 if (instance.isOwned()) {
765 if (!Array.isArray(instance.VideoFiles)) {
766 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
769 // Remove physical files and torrents
770 instance.VideoFiles.forEach(file => {
771 tasks.push(instance.removeFile(file))
772 tasks.push(file.removeTorrent())
775 // Remove playlists file
776 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
777 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
780 for (const p of instance.VideoStreamingPlaylists) {
781 tasks.push(instance.removeStreamingPlaylistFiles(p))
785 // Do not wait video deletion because we could be in a transaction
788 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
795 static stopLiveIfNeeded (instance: VideoModel) {
796 if (!instance.isLive) return
798 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
800 LiveManager.Instance.stopSessionOf(instance.id)
804 static invalidateCache (instance: VideoModel) {
805 ModelCache.Instance.invalidateCache('video', instance.id)
809 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
810 const tasks: Promise<any>[] = []
812 if (!Array.isArray(instance.VideoAbuses)) {
813 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
815 if (instance.VideoAbuses.length === 0) return undefined
818 logger.info('Saving video abuses details of video %s.', instance.url)
820 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
821 const details = instance.toFormattedDetailsJSON()
823 for (const abuse of instance.VideoAbuses) {
824 abuse.deletedVideo = details
825 tasks.push(abuse.save({ transaction: options.transaction }))
828 await Promise.all(tasks)
831 static listLocal (): Promise<MVideo[]> {
838 return VideoModel.findAll(query)
841 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
842 function getRawQuery (select: string) {
843 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
844 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
845 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
846 'WHERE "Account"."actorId" = ' + actorId
847 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
848 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
849 'WHERE "VideoShare"."actorId" = ' + actorId
851 return `(${queryVideo}) UNION (${queryVideoShare})`
854 const rawQuery = getRawQuery('"Video"."id"')
855 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
861 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
864 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
866 [Op.or]: getPrivaciesForFederation()
870 attributes: [ 'filename', 'language', 'fileUrl' ],
871 model: VideoCaptionModel.unscoped(),
875 attributes: [ 'id', 'url' ],
876 model: VideoShareModel.unscoped(),
878 // We only want videos shared by this actor
893 attributes: [ 'id', 'url' ],
894 model: ActorModel.unscoped()
899 model: VideoChannelModel.unscoped(),
903 attributes: [ 'name' ],
904 model: AccountModel.unscoped(),
908 attributes: [ 'id', 'url', 'followersUrl' ],
909 model: ActorModel.unscoped(),
915 attributes: [ 'id', 'url', 'followersUrl' ],
916 model: ActorModel.unscoped(),
922 model: VideoStreamingPlaylistModel.unscoped(),
926 model: VideoFileModel,
931 VideoLiveModel.unscoped(),
937 return Bluebird.all([
938 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
939 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
940 ]).then(([ rows, totals ]) => {
941 // totals: totalVideos + totalVideoShares
943 let totalVideoShares = 0
944 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
945 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
947 const total = totalVideos + totalVideoShares
955 static async listPublishedLiveUUIDs () {
957 attributes: [ 'uuid' ],
961 state: VideoState.PUBLISHED
965 const result = await VideoModel.findAll(options)
967 return result.map(v => v.uuid)
970 static listUserVideosForApi (options: {
978 const { accountId, start, count, sort, search, isLive } = options
980 function buildBaseQuery (): FindOptions {
981 const where: WhereOptions = {}
985 [Op.iLike]: '%' + search + '%'
990 where.isLive = isLive
997 order: getVideoSort(sort),
1000 model: VideoChannelModel,
1004 model: AccountModel,
1018 const countQuery = buildBaseQuery()
1019 const findQuery = buildBaseQuery()
1021 const findScopes: (string | ScopeOptions)[] = [
1022 ScopeNames.WITH_SCHEDULED_UPDATE,
1023 ScopeNames.WITH_BLACKLISTED,
1024 ScopeNames.WITH_THUMBNAILS
1027 return Promise.all([
1028 VideoModel.count(countQuery),
1029 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1030 ]).then(([ count, rows ]) => {
1038 static async listForApi (options: {
1044 filter?: VideoFilter
1047 includeLocalVideos: boolean
1050 categoryOneOf?: number[]
1051 licenceOneOf?: number[]
1052 languageOneOf?: string[]
1053 tagsOneOf?: string[]
1054 tagsAllOf?: string[]
1057 videoChannelId?: number
1059 followerActorId?: number
1061 videoPlaylistId?: number
1063 trendingDays?: number
1065 user?: MUserAccountId
1066 historyOfUser?: MUserId
1068 countVideos?: boolean
1072 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1073 throw new Error('Try to filter all-local but no user has not the see all videos right')
1076 const trendingDays = options.sort.endsWith('trending')
1077 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1079 let trendingAlgorithm
1080 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1081 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1083 const serverActor = await getServerActor()
1085 // followerActorId === null has a meaning, so just check undefined
1086 const followerActorId = options.followerActorId !== undefined
1087 ? options.followerActorId
1090 const queryOptions = {
1091 start: options.start,
1092 count: options.count,
1095 serverAccountId: serverActor.Account.id,
1097 isLive: options.isLive,
1098 categoryOneOf: options.categoryOneOf,
1099 licenceOneOf: options.licenceOneOf,
1100 languageOneOf: options.languageOneOf,
1101 tagsOneOf: options.tagsOneOf,
1102 tagsAllOf: options.tagsAllOf,
1103 filter: options.filter,
1104 withFiles: options.withFiles,
1105 accountId: options.accountId,
1106 videoChannelId: options.videoChannelId,
1107 videoPlaylistId: options.videoPlaylistId,
1108 includeLocalVideos: options.includeLocalVideos,
1110 historyOfUser: options.historyOfUser,
1113 search: options.search
1116 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1119 static async searchAndPopulateAccountAndServer (options: {
1120 includeLocalVideos: boolean
1125 startDate?: string // ISO 8601
1126 endDate?: string // ISO 8601
1127 originallyPublishedStartDate?: string
1128 originallyPublishedEndDate?: string
1131 categoryOneOf?: number[]
1132 licenceOneOf?: number[]
1133 languageOneOf?: string[]
1134 tagsOneOf?: string[]
1135 tagsAllOf?: string[]
1136 durationMin?: number // seconds
1137 durationMax?: number // seconds
1138 user?: MUserAccountId
1139 filter?: VideoFilter
1141 const serverActor = await getServerActor()
1143 const queryOptions = {
1144 followerActorId: serverActor.id,
1145 serverAccountId: serverActor.Account.id,
1147 includeLocalVideos: options.includeLocalVideos,
1149 isLive: options.isLive,
1151 categoryOneOf: options.categoryOneOf,
1152 licenceOneOf: options.licenceOneOf,
1153 languageOneOf: options.languageOneOf,
1155 tagsOneOf: options.tagsOneOf,
1156 tagsAllOf: options.tagsAllOf,
1159 filter: options.filter,
1161 start: options.start,
1162 count: options.count,
1165 startDate: options.startDate,
1166 endDate: options.endDate,
1168 originallyPublishedStartDate: options.originallyPublishedStartDate,
1169 originallyPublishedEndDate: options.originallyPublishedEndDate,
1171 durationMin: options.durationMin,
1172 durationMax: options.durationMax,
1174 search: options.search
1177 return VideoModel.getAvailableForApi(queryOptions)
1180 static countLocalLives () {
1186 [Op.ne]: VideoState.LIVE_ENDED
1191 return VideoModel.count(options)
1194 static countVideosUploadedByUserSince (userId: number, since: Date) {
1198 model: VideoChannelModel.unscoped(),
1202 model: AccountModel.unscoped(),
1206 model: UserModel.unscoped(),
1224 return VideoModel.unscoped().count(options)
1227 static countLivesOfAccount (accountId: number) {
1233 [Op.ne]: VideoState.LIVE_ENDED
1239 model: VideoChannelModel.unscoped(),
1247 return VideoModel.count(options)
1250 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1251 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1253 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1256 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1257 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1259 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1262 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1265 where: buildWhereIdOrUUID(id),
1269 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1272 return ModelCache.Instance.doCache({
1273 cacheType: 'load-video-immutable-id',
1280 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1282 const query: FindOptions = {
1289 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1292 return ModelCache.Instance.doCache({
1293 cacheType: 'load-video-immutable-url',
1300 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1301 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1303 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1306 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1307 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1309 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1312 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1313 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1315 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1318 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1319 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1321 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1324 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1325 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1327 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1330 static loadForGetAPI (parameters: {
1332 transaction?: Transaction
1334 }): Promise<MVideoDetails> {
1335 const { id, transaction, userId } = parameters
1336 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1338 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1341 static async getStats () {
1342 const totalLocalVideos = await VideoModel.count({
1348 let totalLocalVideoViews = await VideoModel.sum('views', {
1354 // Sequelize could return null...
1355 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1357 const { total: totalVideos } = await VideoModel.listForApi({
1360 sort: '-publishedAt',
1361 nsfw: buildNSFWFilter(),
1362 includeLocalVideos: true,
1368 totalLocalVideoViews,
1373 static incrementViews (id: number, views: number) {
1374 return VideoModel.increment('views', {
1382 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1383 const field = type === 'like'
1387 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1389 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1391 'WHERE "video"."id" = :videoId'
1393 return AccountVideoRateModel.sequelize.query(rawQuery, {
1395 replacements: { videoId, rateType: type },
1396 type: QueryTypes.UPDATE
1400 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1401 // Instances only share videos
1402 const query = 'SELECT 1 FROM "videoShare" ' +
1403 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1404 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1408 type: QueryTypes.SELECT as QueryTypes.SELECT,
1409 bind: { followerActorId, videoId },
1413 return VideoModel.sequelize.query(query, options)
1414 .then(results => results.length === 1)
1417 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1420 channelId: ofChannel.id
1425 return VideoModel.update({ support: ofChannel.support }, options)
1428 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1430 attributes: [ 'id' ],
1432 channelId: videoChannel.id
1436 return VideoModel.findAll(query)
1437 .then(videos => videos.map(v => v.id))
1440 // threshold corresponds to how many video the field should have to be returned
1441 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1442 const serverActor = await getServerActor()
1443 const followerActorId = serverActor.id
1445 const queryOptions: BuildVideosListQueryOptions = {
1446 attributes: [ `"${field}"` ],
1447 group: `GROUP BY "${field}"`,
1448 having: `HAVING COUNT("${field}") >= ${threshold}`,
1452 serverAccountId: serverActor.Account.id,
1454 includeLocalVideos: true
1457 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1459 return queryBuilder.queryVideoIds(queryOptions)
1460 .then(rows => rows.map(r => r[field]))
1463 static buildTrendingQuery (trendingDays: number) {
1467 model: VideoViewModel,
1471 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1477 private static async getAvailableForApi (
1478 options: BuildVideosListQueryOptions,
1480 ): Promise<ResultList<VideoModel>> {
1481 function getCount () {
1482 if (countVideos !== true) return Promise.resolve(undefined)
1484 const countOptions = Object.assign({}, options, { isCount: true })
1485 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1487 return queryBuilder.countVideoIds(countOptions)
1490 function getModels () {
1491 if (options.count === 0) return Promise.resolve([])
1493 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1495 return queryBuilder.queryVideos(options)
1498 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1507 return !!this.VideoBlacklist
1511 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1514 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1515 // We first transcode to WebTorrent format, so try this array first
1516 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1517 const file = fun(this.VideoFiles, file => file.resolution)
1519 return Object.assign(file, { Video: this })
1522 // No webtorrent files, try with streaming playlist files
1523 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1524 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1526 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1527 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1533 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1534 return this.getQualityFileBy(maxBy)
1537 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1538 return this.getQualityFileBy(minBy)
1541 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1542 if (Array.isArray(this.VideoFiles) === false) return undefined
1544 const file = this.VideoFiles.find(f => f.resolution === resolution)
1545 if (!file) return undefined
1547 return Object.assign(file, { Video: this })
1550 hasWebTorrentFiles () {
1551 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1554 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1555 thumbnail.videoId = this.id
1557 const savedThumbnail = await thumbnail.save({ transaction })
1559 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1561 // Already have this thumbnail, skip
1562 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1564 this.Thumbnails.push(savedThumbnail)
1568 if (Array.isArray(this.Thumbnails) === false) return undefined
1570 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1574 return !!this.getPreview()
1578 if (Array.isArray(this.Thumbnails) === false) return undefined
1580 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1584 return this.remote === false
1587 getWatchStaticPath () {
1588 return '/w/' + this.uuid
1591 getEmbedStaticPath () {
1592 return '/videos/embed/' + this.uuid
1595 getMiniatureStaticPath () {
1596 const thumbnail = this.getMiniature()
1597 if (!thumbnail) return null
1599 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1602 getPreviewStaticPath () {
1603 const preview = this.getPreview()
1604 if (!preview) return null
1606 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1607 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1610 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1611 return videoModelToFormattedJSON(this, options)
1614 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1615 return videoModelToFormattedDetailsJSON(this)
1618 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1619 let files: VideoFile[] = []
1621 if (Array.isArray(this.VideoFiles)) {
1622 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1623 files = files.concat(result)
1626 for (const p of (this.VideoStreamingPlaylists || [])) {
1627 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1628 files = files.concat(result)
1634 toActivityPubObject (this: MVideoAP): VideoObject {
1635 return videoModelToActivityPubObject(this)
1638 getTruncatedDescription () {
1639 if (!this.description) return null
1641 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1642 return peertubeTruncate(this.description, { length: maxLength })
1645 getMaxQualityResolution () {
1646 const file = this.getMaxQualityFile()
1647 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1648 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1650 return getVideoFileResolution(originalFilePath)
1653 getDescriptionAPIPath () {
1654 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1657 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1658 if (!this.VideoStreamingPlaylists) return undefined
1660 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1661 playlist.Video = this
1666 setHLSPlaylist (playlist: MStreamingPlaylist) {
1667 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1669 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1670 this.VideoStreamingPlaylists = toAdd
1674 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1675 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1679 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1680 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1681 return remove(filePath)
1682 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1685 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1686 const directoryPath = getHLSDirectory(this, isRedundancy)
1688 await remove(directoryPath)
1690 if (isRedundancy !== true) {
1691 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1692 streamingPlaylistWithFiles.Video = this
1694 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1695 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1698 // Remove physical files and torrents
1700 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1706 if (this.isOwned()) return false
1708 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1711 hasPrivacyForFederation () {
1712 return isPrivacyForFederation(this.privacy)
1715 hasStateForFederation () {
1716 return isStateForFederation(this.state)
1719 isNewVideo (newPrivacy: VideoPrivacy) {
1720 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1724 return setAsUpdated('video', this.id)
1728 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1731 setPrivacy (newPrivacy: VideoPrivacy) {
1732 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1733 this.publishedAt = new Date()
1736 this.privacy = newPrivacy
1740 return this.privacy === VideoPrivacy.PRIVATE ||
1741 this.privacy === VideoPrivacy.UNLISTED ||
1742 this.privacy === VideoPrivacy.INTERNAL
1745 async publishIfNeededAndSave (t: Transaction) {
1746 if (this.state !== VideoState.PUBLISHED) {
1747 this.state = VideoState.PUBLISHED
1748 this.publishedAt = new Date()
1749 await this.save({ transaction: t })
1757 getBandwidthBits (videoFile: MVideoFile) {
1758 return Math.ceil((videoFile.size * 8) / this.duration)
1762 if (this.isOwned()) {
1764 WEBSERVER.URL + '/tracker/announce',
1765 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1769 return this.Trackers.map(t => t.url)