1 import 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 { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { uuidToShort } from '@server/helpers/uuid'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live/live-manager'
31 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
32 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
33 import { VideoPathManager } from '@server/lib/video-path-manager'
34 import { getServerActor } from '@server/models/application/application'
35 import { ModelCache } from '@server/models/model-cache'
36 import { AttributesOnly, buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
37 import { VideoFile } from '@shared/models/videos/video-file.model'
38 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
39 import { VideoObject } from '../../../shared/models/activitypub/objects'
40 import { Video, VideoDetails, VideoRateType, VideoStorage } from '../../../shared/models/videos'
41 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
44 import { peertubeTruncate } from '../../helpers/core-utils'
45 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
46 import { isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
56 import { logger } from '../../helpers/logger'
57 import { CONFIG } from '../../initializers/config'
58 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
59 import { sendDeleteVideo } from '../../lib/activitypub/send'
62 MChannelAccountDefault,
65 MStreamingPlaylistFilesVideo,
70 MVideoAccountLightBlacklistAllFiles,
75 MVideoFormattableDetails,
81 MVideoThumbnailBlacklist,
84 } from '../../types/models'
85 import { MThumbnail } from '../../types/models/video/thumbnail'
86 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
87 import { VideoAbuseModel } from '../abuse/video-abuse'
88 import { AccountModel } from '../account/account'
89 import { AccountVideoRateModel } from '../account/account-video-rate'
90 import { ActorModel } from '../actor/actor'
91 import { ActorImageModel } from '../actor/actor-image'
92 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
93 import { ServerModel } from '../server/server'
94 import { TrackerModel } from '../server/tracker'
95 import { VideoTrackerModel } from '../server/video-tracker'
96 import { setAsUpdated } from '../shared'
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 { VideoJobInfoModel } from './video-job-info'
120 import { VideoLiveModel } from './video-live'
121 import { VideoPlaylistElementModel } from './video-playlist-element'
122 import { VideoShareModel } from './video-share'
123 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
124 import { VideoTagModel } from './video-tag'
125 import { VideoViewModel } from './video-view'
127 export enum ScopeNames {
129 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
130 WITH_TAGS = 'WITH_TAGS',
131 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
132 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
133 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
134 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
135 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
136 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
137 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
140 export type ForAPIOptions = {
143 videoPlaylistId?: number
145 withAccountBlockerIds?: number[]
148 export type AvailableForListIDsOptions = {
149 serverAccountId: number
150 followerActorId: number
151 includeLocalVideos: boolean
153 attributesType?: 'none' | 'id' | 'all'
156 categoryOneOf?: number[]
158 licenceOneOf?: number[]
159 languageOneOf?: string[]
166 videoChannelId?: number
168 videoPlaylistId?: number
170 trendingDays?: number
171 user?: MUserAccountId
172 historyOfUser?: MUserId
174 baseWhere?: WhereOptions[]
178 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
179 attributes: [ 'id', 'url', 'uuid', 'remote' ]
181 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
182 const include: Includeable[] = [
184 model: VideoChannelModel.scope({
186 VideoChannelScopeNames.SUMMARY, {
188 withAccountBlockerIds: options.withAccountBlockerIds
195 attributes: [ 'type', 'filename' ],
196 model: ThumbnailModel,
201 const query: FindOptions = {}
211 if (options.videoPlaylistId) {
213 model: VideoPlaylistElementModel.unscoped(),
216 videoPlaylistId: options.videoPlaylistId
221 query.include = include
225 [ScopeNames.WITH_THUMBNAILS]: {
228 model: ThumbnailModel,
233 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
236 model: VideoChannelModel.unscoped(),
241 exclude: [ 'privateKey', 'publicKey' ]
243 model: ActorModel.unscoped(),
247 attributes: [ 'host' ],
248 model: ServerModel.unscoped(),
252 model: ActorImageModel.unscoped(),
259 model: AccountModel.unscoped(),
263 model: ActorModel.unscoped(),
265 exclude: [ 'privateKey', 'publicKey' ]
270 attributes: [ 'host' ],
271 model: ServerModel.unscoped(),
275 model: ActorImageModel.unscoped(),
287 [ScopeNames.WITH_TAGS]: {
288 include: [ TagModel ]
290 [ScopeNames.WITH_BLACKLISTED]: {
293 attributes: [ 'id', 'reason', 'unfederated' ],
294 model: VideoBlacklistModel,
299 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
300 let subInclude: any[] = []
302 if (withRedundancies === true) {
305 attributes: [ 'fileUrl' ],
306 model: VideoRedundancyModel.unscoped(),
315 model: VideoFileModel,
323 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
324 const subInclude: IncludeOptions[] = [
326 model: VideoFileModel,
331 if (withRedundancies === true) {
333 attributes: [ 'fileUrl' ],
334 model: VideoRedundancyModel.unscoped(),
342 model: VideoStreamingPlaylistModel.unscoped(),
350 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
353 model: ScheduleVideoUpdateModel.unscoped(),
358 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
362 attributes: [ 'currentTime' ],
363 model: UserVideoHistoryModel.unscoped(),
376 buildTrigramSearchIndex('video_name_trigram', 'name'),
378 { fields: [ 'createdAt' ] },
381 { name: 'publishedAt', order: 'DESC' },
382 { name: 'id', order: 'ASC' }
385 { fields: [ 'duration' ] },
388 { name: 'views', order: 'DESC' },
389 { name: 'id', order: 'ASC' }
392 { fields: [ 'channelId' ] },
394 fields: [ 'originallyPublishedAt' ],
396 originallyPublishedAt: {
402 fields: [ 'category' ], // We don't care videos with an unknown category
410 fields: [ 'licence' ], // We don't care videos with an unknown licence
418 fields: [ 'language' ], // We don't care videos with an unknown language
426 fields: [ 'nsfw' ], // Most of the videos are not NSFW
432 fields: [ 'remote' ], // Only index local videos
447 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
450 @Default(DataType.UUIDV4)
452 @Column(DataType.UUID)
456 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
472 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
476 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
478 privacy: VideoPrivacy
481 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
487 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
488 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
493 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
494 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
498 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
533 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
534 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
539 commentsEnabled: boolean
543 downloadEnabled: boolean
547 waitTranscoding: boolean
551 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
562 @Default(DataType.NOW)
569 originallyPublishedAt: Date
571 @ForeignKey(() => VideoChannelModel)
575 @BelongsTo(() => VideoChannelModel, {
581 VideoChannel: VideoChannelModel
583 @BelongsToMany(() => TagModel, {
584 foreignKey: 'videoId',
585 through: () => VideoTagModel,
590 @BelongsToMany(() => TrackerModel, {
591 foreignKey: 'videoId',
592 through: () => VideoTrackerModel,
595 Trackers: TrackerModel[]
597 @HasMany(() => ThumbnailModel, {
605 Thumbnails: ThumbnailModel[]
607 @HasMany(() => VideoPlaylistElementModel, {
614 VideoPlaylistElements: VideoPlaylistElementModel[]
616 @HasMany(() => VideoAbuseModel, {
623 VideoAbuses: VideoAbuseModel[]
625 @HasMany(() => VideoFileModel, {
633 VideoFiles: VideoFileModel[]
635 @HasMany(() => VideoStreamingPlaylistModel, {
643 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
645 @HasMany(() => VideoShareModel, {
652 VideoShares: VideoShareModel[]
654 @HasMany(() => AccountVideoRateModel, {
661 AccountVideoRates: AccountVideoRateModel[]
663 @HasMany(() => VideoCommentModel, {
671 VideoComments: VideoCommentModel[]
673 @HasMany(() => VideoViewModel, {
680 VideoViews: VideoViewModel[]
682 @HasMany(() => UserVideoHistoryModel, {
689 UserVideoHistories: UserVideoHistoryModel[]
691 @HasOne(() => ScheduleVideoUpdateModel, {
698 ScheduleVideoUpdate: ScheduleVideoUpdateModel
700 @HasOne(() => VideoBlacklistModel, {
707 VideoBlacklist: VideoBlacklistModel
709 @HasOne(() => VideoLiveModel, {
716 VideoLive: VideoLiveModel
718 @HasOne(() => VideoImportModel, {
725 VideoImport: VideoImportModel
727 @HasMany(() => VideoCaptionModel, {
734 ['separate' as any]: true
736 VideoCaptions: VideoCaptionModel[]
738 @HasOne(() => VideoJobInfoModel, {
745 VideoJobInfo: VideoJobInfoModel
748 static async sendDelete (instance: MVideoAccountLight, options) {
749 if (!instance.isOwned()) return undefined
751 // Lazy load channels
752 if (!instance.VideoChannel) {
753 instance.VideoChannel = await instance.$get('VideoChannel', {
758 transaction: options.transaction
759 }) as MChannelAccountDefault
762 return sendDeleteVideo(instance, options.transaction)
766 static async removeFiles (instance: VideoModel, options) {
767 const tasks: Promise<any>[] = []
769 logger.info('Removing files of video %s.', instance.url)
771 if (instance.isOwned()) {
772 if (!Array.isArray(instance.VideoFiles)) {
773 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
776 // Remove physical files and torrents
777 instance.VideoFiles.forEach(file => {
778 tasks.push(instance.removeFileAndTorrent(file))
781 // Remove playlists file
782 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
783 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
786 for (const p of instance.VideoStreamingPlaylists) {
787 tasks.push(instance.removeStreamingPlaylistFiles(p))
791 // Do not wait video deletion because we could be in a transaction
794 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
801 static stopLiveIfNeeded (instance: VideoModel) {
802 if (!instance.isLive) return
804 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
806 LiveManager.Instance.stopSessionOf(instance.id)
810 static invalidateCache (instance: VideoModel) {
811 ModelCache.Instance.invalidateCache('video', instance.id)
815 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
816 const tasks: Promise<any>[] = []
818 if (!Array.isArray(instance.VideoAbuses)) {
819 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
821 if (instance.VideoAbuses.length === 0) return undefined
824 logger.info('Saving video abuses details of video %s.', instance.url)
826 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
827 const details = instance.toFormattedDetailsJSON()
829 for (const abuse of instance.VideoAbuses) {
830 abuse.deletedVideo = details
831 tasks.push(abuse.save({ transaction: options.transaction }))
834 await Promise.all(tasks)
837 static listLocal (): Promise<MVideo[]> {
844 return VideoModel.findAll(query)
847 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
848 function getRawQuery (select: string) {
849 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
850 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
851 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
852 'WHERE "Account"."actorId" = ' + actorId
853 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
854 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
855 'WHERE "VideoShare"."actorId" = ' + actorId
857 return `(${queryVideo}) UNION (${queryVideoShare})`
860 const rawQuery = getRawQuery('"Video"."id"')
861 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
867 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
870 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
872 [Op.or]: getPrivaciesForFederation()
876 attributes: [ 'filename', 'language', 'fileUrl' ],
877 model: VideoCaptionModel.unscoped(),
881 attributes: [ 'id', 'url' ],
882 model: VideoShareModel.unscoped(),
884 // We only want videos shared by this actor
899 attributes: [ 'id', 'url' ],
900 model: ActorModel.unscoped()
905 model: VideoChannelModel.unscoped(),
909 attributes: [ 'name' ],
910 model: AccountModel.unscoped(),
914 attributes: [ 'id', 'url', 'followersUrl' ],
915 model: ActorModel.unscoped(),
921 attributes: [ 'id', 'url', 'followersUrl' ],
922 model: ActorModel.unscoped(),
928 model: VideoStreamingPlaylistModel.unscoped(),
932 model: VideoFileModel,
937 VideoLiveModel.unscoped(),
943 return Bluebird.all([
944 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
945 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
946 ]).then(([ rows, totals ]) => {
947 // totals: totalVideos + totalVideoShares
949 let totalVideoShares = 0
950 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
951 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
953 const total = totalVideos + totalVideoShares
961 static async listPublishedLiveUUIDs () {
963 attributes: [ 'uuid' ],
967 state: VideoState.PUBLISHED
971 const result = await VideoModel.findAll(options)
973 return result.map(v => v.uuid)
976 static listUserVideosForApi (options: {
984 const { accountId, start, count, sort, search, isLive } = options
986 function buildBaseQuery (): FindOptions {
987 const where: WhereOptions = {}
991 [Op.iLike]: '%' + search + '%'
996 where.isLive = isLive
1003 order: getVideoSort(sort),
1006 model: VideoChannelModel,
1010 model: AccountModel,
1024 const countQuery = buildBaseQuery()
1025 const findQuery = buildBaseQuery()
1027 const findScopes: (string | ScopeOptions)[] = [
1028 ScopeNames.WITH_SCHEDULED_UPDATE,
1029 ScopeNames.WITH_BLACKLISTED,
1030 ScopeNames.WITH_THUMBNAILS
1033 return Promise.all([
1034 VideoModel.count(countQuery),
1035 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1036 ]).then(([ count, rows ]) => {
1044 static async listForApi (options: {
1050 filter?: VideoFilter
1053 includeLocalVideos: boolean
1056 categoryOneOf?: number[]
1057 licenceOneOf?: number[]
1058 languageOneOf?: string[]
1059 tagsOneOf?: string[]
1060 tagsAllOf?: string[]
1063 videoChannelId?: number
1065 followerActorId?: number
1067 videoPlaylistId?: number
1069 trendingDays?: number
1071 user?: MUserAccountId
1072 historyOfUser?: MUserId
1074 countVideos?: boolean
1078 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1079 throw new Error('Try to filter all-local but no user has not the see all videos right')
1082 const trendingDays = options.sort.endsWith('trending')
1083 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1086 let trendingAlgorithm: string
1087 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1088 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1090 const serverActor = await getServerActor()
1092 // followerActorId === null has a meaning, so just check undefined
1093 const followerActorId = options.followerActorId !== undefined
1094 ? options.followerActorId
1097 const queryOptions = {
1114 'includeLocalVideos',
1121 serverAccountId: serverActor.Account.id,
1126 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1129 static async searchAndPopulateAccountAndServer (options: {
1133 includeLocalVideos: boolean
1136 startDate?: string // ISO 8601
1137 endDate?: string // ISO 8601
1138 originallyPublishedStartDate?: string
1139 originallyPublishedEndDate?: string
1142 categoryOneOf?: number[]
1143 licenceOneOf?: number[]
1144 languageOneOf?: string[]
1145 tagsOneOf?: string[]
1146 tagsAllOf?: string[]
1147 durationMin?: number // seconds
1148 durationMax?: number // seconds
1149 user?: MUserAccountId
1150 filter?: VideoFilter
1153 const serverActor = await getServerActor()
1155 const queryOptions = {
1157 'includeLocalVideos',
1173 'originallyPublishedStartDate',
1174 'originallyPublishedEndDate',
1181 followerActorId: serverActor.id,
1182 serverAccountId: serverActor.Account.id
1185 return VideoModel.getAvailableForApi(queryOptions)
1188 static countLocalLives () {
1194 [Op.ne]: VideoState.LIVE_ENDED
1199 return VideoModel.count(options)
1202 static countVideosUploadedByUserSince (userId: number, since: Date) {
1206 model: VideoChannelModel.unscoped(),
1210 model: AccountModel.unscoped(),
1214 model: UserModel.unscoped(),
1232 return VideoModel.unscoped().count(options)
1235 static countLivesOfAccount (accountId: number) {
1241 [Op.ne]: VideoState.LIVE_ENDED
1247 model: VideoChannelModel.unscoped(),
1255 return VideoModel.count(options)
1258 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1259 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1261 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1264 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1265 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1267 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1270 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1273 where: buildWhereIdOrUUID(id),
1277 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1280 return ModelCache.Instance.doCache({
1281 cacheType: 'load-video-immutable-id',
1288 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1290 const query: FindOptions = {
1297 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1300 return ModelCache.Instance.doCache({
1301 cacheType: 'load-video-immutable-url',
1308 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1309 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1311 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1314 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1315 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1317 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1320 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1321 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1323 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1326 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1327 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1329 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1332 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1333 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1335 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1338 static loadForGetAPI (parameters: {
1340 transaction?: Transaction
1342 }): Promise<MVideoDetails> {
1343 const { id, transaction, userId } = parameters
1344 const queryBuilder = new VideosModelGetQueryBuilder(VideoModel.sequelize)
1346 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1349 static async getStats () {
1350 const totalLocalVideos = await VideoModel.count({
1356 let totalLocalVideoViews = await VideoModel.sum('views', {
1362 // Sequelize could return null...
1363 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1365 const { total: totalVideos } = await VideoModel.listForApi({
1368 sort: '-publishedAt',
1369 nsfw: buildNSFWFilter(),
1370 includeLocalVideos: true,
1376 totalLocalVideoViews,
1381 static incrementViews (id: number, views: number) {
1382 return VideoModel.increment('views', {
1390 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1391 const field = type === 'like'
1395 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1397 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1399 'WHERE "video"."id" = :videoId'
1401 return AccountVideoRateModel.sequelize.query(rawQuery, {
1403 replacements: { videoId, rateType: type },
1404 type: QueryTypes.UPDATE
1408 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1409 // Instances only share videos
1410 const query = 'SELECT 1 FROM "videoShare" ' +
1411 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1412 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1416 type: QueryTypes.SELECT as QueryTypes.SELECT,
1417 bind: { followerActorId, videoId },
1421 return VideoModel.sequelize.query(query, options)
1422 .then(results => results.length === 1)
1425 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1428 channelId: ofChannel.id
1433 return VideoModel.update({ support: ofChannel.support }, options)
1436 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1438 attributes: [ 'id' ],
1440 channelId: videoChannel.id
1444 return VideoModel.findAll(query)
1445 .then(videos => videos.map(v => v.id))
1448 // threshold corresponds to how many video the field should have to be returned
1449 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1450 const serverActor = await getServerActor()
1451 const followerActorId = serverActor.id
1453 const queryOptions: BuildVideosListQueryOptions = {
1454 attributes: [ `"${field}"` ],
1455 group: `GROUP BY "${field}"`,
1456 having: `HAVING COUNT("${field}") >= ${threshold}`,
1460 serverAccountId: serverActor.Account.id,
1462 includeLocalVideos: true
1465 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1467 return queryBuilder.queryVideoIds(queryOptions)
1468 .then(rows => rows.map(r => r[field]))
1471 static buildTrendingQuery (trendingDays: number) {
1475 model: VideoViewModel,
1479 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1485 private static async getAvailableForApi (
1486 options: BuildVideosListQueryOptions,
1488 ): Promise<ResultList<VideoModel>> {
1489 function getCount () {
1490 if (countVideos !== true) return Promise.resolve(undefined)
1492 const countOptions = Object.assign({}, options, { isCount: true })
1493 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1495 return queryBuilder.countVideoIds(countOptions)
1498 function getModels () {
1499 if (options.count === 0) return Promise.resolve([])
1501 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1503 return queryBuilder.queryVideos(options)
1506 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1515 return !!this.VideoBlacklist
1519 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1522 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1523 // We first transcode to WebTorrent format, so try this array first
1524 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1525 const file = fun(this.VideoFiles, file => file.resolution)
1527 return Object.assign(file, { Video: this })
1530 // No webtorrent files, try with streaming playlist files
1531 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1532 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1534 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1535 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1541 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1542 return this.getQualityFileBy(maxBy)
1545 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1546 return this.getQualityFileBy(minBy)
1549 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1550 if (Array.isArray(this.VideoFiles) === false) return undefined
1552 const file = this.VideoFiles.find(f => f.resolution === resolution)
1553 if (!file) return undefined
1555 return Object.assign(file, { Video: this })
1558 hasWebTorrentFiles () {
1559 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1562 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1563 thumbnail.videoId = this.id
1565 const savedThumbnail = await thumbnail.save({ transaction })
1567 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1569 // Already have this thumbnail, skip
1570 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1572 this.Thumbnails.push(savedThumbnail)
1576 if (Array.isArray(this.Thumbnails) === false) return undefined
1578 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1582 return !!this.getPreview()
1586 if (Array.isArray(this.Thumbnails) === false) return undefined
1588 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1592 return this.remote === false
1595 getWatchStaticPath () {
1596 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1599 getEmbedStaticPath () {
1600 return buildVideoEmbedPath(this)
1603 getMiniatureStaticPath () {
1604 const thumbnail = this.getMiniature()
1605 if (!thumbnail) return null
1607 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1610 getPreviewStaticPath () {
1611 const preview = this.getPreview()
1612 if (!preview) return null
1614 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1615 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1618 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1619 return videoModelToFormattedJSON(this, options)
1622 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1623 return videoModelToFormattedDetailsJSON(this)
1626 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1627 let files: VideoFile[] = []
1629 if (Array.isArray(this.VideoFiles)) {
1630 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1631 files = files.concat(result)
1634 for (const p of (this.VideoStreamingPlaylists || [])) {
1635 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1636 files = files.concat(result)
1642 toActivityPubObject (this: MVideoAP): VideoObject {
1643 return videoModelToActivityPubObject(this)
1646 getTruncatedDescription () {
1647 if (!this.description) return null
1649 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1650 return peertubeTruncate(this.description, { length: maxLength })
1653 getMaxQualityResolution () {
1654 const file = this.getMaxQualityFile()
1655 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1657 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => {
1658 return getVideoFileResolution(originalFilePath)
1662 getDescriptionAPIPath () {
1663 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1666 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1667 if (!this.VideoStreamingPlaylists) return undefined
1669 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1670 playlist.Video = this
1675 setHLSPlaylist (playlist: MStreamingPlaylist) {
1676 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1678 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1679 this.VideoStreamingPlaylists = toAdd
1683 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1684 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1688 removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1689 const filePath = isRedundancy
1690 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1691 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1693 const promises: Promise<any>[] = [ remove(filePath) ]
1694 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1696 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1697 promises.push(removeWebTorrentObjectStorage(videoFile))
1700 return Promise.all(promises)
1703 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1704 const directoryPath = isRedundancy
1705 ? getHLSRedundancyDirectory(this)
1706 : getHLSDirectory(this)
1708 await remove(directoryPath)
1710 if (isRedundancy !== true) {
1711 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1712 streamingPlaylistWithFiles.Video = this
1714 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1715 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1718 // Remove physical files and torrents
1720 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1723 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1724 await removeHLSObjectStorage(streamingPlaylist, this)
1730 if (this.isOwned()) return false
1732 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1735 hasPrivacyForFederation () {
1736 return isPrivacyForFederation(this.privacy)
1739 hasStateForFederation () {
1740 return isStateForFederation(this.state)
1743 isNewVideo (newPrivacy: VideoPrivacy) {
1744 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1748 return setAsUpdated('video', this.id)
1752 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1755 setPrivacy (newPrivacy: VideoPrivacy) {
1756 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1757 this.publishedAt = new Date()
1760 this.privacy = newPrivacy
1764 return this.privacy === VideoPrivacy.PRIVATE ||
1765 this.privacy === VideoPrivacy.UNLISTED ||
1766 this.privacy === VideoPrivacy.INTERNAL
1769 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1770 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1772 this.state = newState
1774 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1775 this.publishedAt = new Date()
1778 await this.save({ transaction })
1781 getBandwidthBits (videoFile: MVideoFile) {
1782 return Math.ceil((videoFile.size * 8) / this.duration)
1786 if (this.isOwned()) {
1788 WEBSERVER.URL + '/tracker/announce',
1789 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1793 return this.Trackers.map(t => t.url)