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 { VideoInclude } from '@shared/models'
38 import { VideoFile } from '@shared/models/videos/video-file.model'
39 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoRateType, VideoStorage } from '../../../shared/models/videos'
42 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.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 { exists, 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 { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
109 import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, 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[]
149 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
150 attributes: [ 'id', 'url', 'uuid', 'remote' ]
152 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
153 const include: Includeable[] = [
155 model: VideoChannelModel.scope({
157 VideoChannelScopeNames.SUMMARY, {
159 withAccountBlockerIds: options.withAccountBlockerIds
166 attributes: [ 'type', 'filename' ],
167 model: ThumbnailModel,
172 const query: FindOptions = {}
182 if (options.videoPlaylistId) {
184 model: VideoPlaylistElementModel.unscoped(),
187 videoPlaylistId: options.videoPlaylistId
192 query.include = include
196 [ScopeNames.WITH_THUMBNAILS]: {
199 model: ThumbnailModel,
204 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
207 model: VideoChannelModel.unscoped(),
212 exclude: [ 'privateKey', 'publicKey' ]
214 model: ActorModel.unscoped(),
218 attributes: [ 'host' ],
219 model: ServerModel.unscoped(),
223 model: ActorImageModel.unscoped(),
230 model: AccountModel.unscoped(),
234 model: ActorModel.unscoped(),
236 exclude: [ 'privateKey', 'publicKey' ]
241 attributes: [ 'host' ],
242 model: ServerModel.unscoped(),
246 model: ActorImageModel.unscoped(),
258 [ScopeNames.WITH_TAGS]: {
259 include: [ TagModel ]
261 [ScopeNames.WITH_BLACKLISTED]: {
264 attributes: [ 'id', 'reason', 'unfederated' ],
265 model: VideoBlacklistModel,
270 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
271 let subInclude: any[] = []
273 if (withRedundancies === true) {
276 attributes: [ 'fileUrl' ],
277 model: VideoRedundancyModel.unscoped(),
286 model: VideoFileModel,
294 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
295 const subInclude: IncludeOptions[] = [
297 model: VideoFileModel,
302 if (withRedundancies === true) {
304 attributes: [ 'fileUrl' ],
305 model: VideoRedundancyModel.unscoped(),
313 model: VideoStreamingPlaylistModel.unscoped(),
321 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
324 model: ScheduleVideoUpdateModel.unscoped(),
329 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
333 attributes: [ 'currentTime' ],
334 model: UserVideoHistoryModel.unscoped(),
347 buildTrigramSearchIndex('video_name_trigram', 'name'),
349 { fields: [ 'createdAt' ] },
352 { name: 'publishedAt', order: 'DESC' },
353 { name: 'id', order: 'ASC' }
356 { fields: [ 'duration' ] },
359 { name: 'views', order: 'DESC' },
360 { name: 'id', order: 'ASC' }
363 { fields: [ 'channelId' ] },
365 fields: [ 'originallyPublishedAt' ],
367 originallyPublishedAt: {
373 fields: [ 'category' ], // We don't care videos with an unknown category
381 fields: [ 'licence' ], // We don't care videos with an unknown licence
389 fields: [ 'language' ], // We don't care videos with an unknown language
397 fields: [ 'nsfw' ], // Most of the videos are not NSFW
403 fields: [ 'remote' ], // Only index local videos
418 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
421 @Default(DataType.UUIDV4)
423 @Column(DataType.UUID)
427 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
443 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
447 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
449 privacy: VideoPrivacy
452 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
458 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
459 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
464 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
465 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
469 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
504 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
505 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
510 commentsEnabled: boolean
514 downloadEnabled: boolean
518 waitTranscoding: boolean
522 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
533 @Default(DataType.NOW)
540 originallyPublishedAt: Date
542 @ForeignKey(() => VideoChannelModel)
546 @BelongsTo(() => VideoChannelModel, {
552 VideoChannel: VideoChannelModel
554 @BelongsToMany(() => TagModel, {
555 foreignKey: 'videoId',
556 through: () => VideoTagModel,
561 @BelongsToMany(() => TrackerModel, {
562 foreignKey: 'videoId',
563 through: () => VideoTrackerModel,
566 Trackers: TrackerModel[]
568 @HasMany(() => ThumbnailModel, {
576 Thumbnails: ThumbnailModel[]
578 @HasMany(() => VideoPlaylistElementModel, {
585 VideoPlaylistElements: VideoPlaylistElementModel[]
587 @HasMany(() => VideoAbuseModel, {
594 VideoAbuses: VideoAbuseModel[]
596 @HasMany(() => VideoFileModel, {
604 VideoFiles: VideoFileModel[]
606 @HasMany(() => VideoStreamingPlaylistModel, {
614 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
616 @HasMany(() => VideoShareModel, {
623 VideoShares: VideoShareModel[]
625 @HasMany(() => AccountVideoRateModel, {
632 AccountVideoRates: AccountVideoRateModel[]
634 @HasMany(() => VideoCommentModel, {
642 VideoComments: VideoCommentModel[]
644 @HasMany(() => VideoViewModel, {
651 VideoViews: VideoViewModel[]
653 @HasMany(() => UserVideoHistoryModel, {
660 UserVideoHistories: UserVideoHistoryModel[]
662 @HasOne(() => ScheduleVideoUpdateModel, {
669 ScheduleVideoUpdate: ScheduleVideoUpdateModel
671 @HasOne(() => VideoBlacklistModel, {
678 VideoBlacklist: VideoBlacklistModel
680 @HasOne(() => VideoLiveModel, {
687 VideoLive: VideoLiveModel
689 @HasOne(() => VideoImportModel, {
696 VideoImport: VideoImportModel
698 @HasMany(() => VideoCaptionModel, {
705 ['separate' as any]: true
707 VideoCaptions: VideoCaptionModel[]
709 @HasOne(() => VideoJobInfoModel, {
716 VideoJobInfo: VideoJobInfoModel
719 static async sendDelete (instance: MVideoAccountLight, options) {
720 if (!instance.isOwned()) return undefined
722 // Lazy load channels
723 if (!instance.VideoChannel) {
724 instance.VideoChannel = await instance.$get('VideoChannel', {
729 transaction: options.transaction
730 }) as MChannelAccountDefault
733 return sendDeleteVideo(instance, options.transaction)
737 static async removeFiles (instance: VideoModel, options) {
738 const tasks: Promise<any>[] = []
740 logger.info('Removing files of video %s.', instance.url)
742 if (instance.isOwned()) {
743 if (!Array.isArray(instance.VideoFiles)) {
744 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
747 // Remove physical files and torrents
748 instance.VideoFiles.forEach(file => {
749 tasks.push(instance.removeFileAndTorrent(file))
752 // Remove playlists file
753 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
754 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
757 for (const p of instance.VideoStreamingPlaylists) {
758 tasks.push(instance.removeStreamingPlaylistFiles(p))
762 // Do not wait video deletion because we could be in a transaction
765 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
772 static stopLiveIfNeeded (instance: VideoModel) {
773 if (!instance.isLive) return
775 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
777 LiveManager.Instance.stopSessionOf(instance.id)
781 static invalidateCache (instance: VideoModel) {
782 ModelCache.Instance.invalidateCache('video', instance.id)
786 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
787 const tasks: Promise<any>[] = []
789 if (!Array.isArray(instance.VideoAbuses)) {
790 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
792 if (instance.VideoAbuses.length === 0) return undefined
795 logger.info('Saving video abuses details of video %s.', instance.url)
797 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
798 const details = instance.toFormattedDetailsJSON()
800 for (const abuse of instance.VideoAbuses) {
801 abuse.deletedVideo = details
802 tasks.push(abuse.save({ transaction: options.transaction }))
805 await Promise.all(tasks)
808 static listLocal (): Promise<MVideo[]> {
815 return VideoModel.findAll(query)
818 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
819 function getRawQuery (select: string) {
820 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
821 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
822 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
823 'WHERE "Account"."actorId" = ' + actorId
824 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
825 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
826 'WHERE "VideoShare"."actorId" = ' + actorId
828 return `(${queryVideo}) UNION (${queryVideoShare})`
831 const rawQuery = getRawQuery('"Video"."id"')
832 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
838 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
841 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
843 [Op.or]: getPrivaciesForFederation()
847 attributes: [ 'filename', 'language', 'fileUrl' ],
848 model: VideoCaptionModel.unscoped(),
852 attributes: [ 'id', 'url' ],
853 model: VideoShareModel.unscoped(),
855 // We only want videos shared by this actor
870 attributes: [ 'id', 'url' ],
871 model: ActorModel.unscoped()
876 model: VideoChannelModel.unscoped(),
880 attributes: [ 'name' ],
881 model: AccountModel.unscoped(),
885 attributes: [ 'id', 'url', 'followersUrl' ],
886 model: ActorModel.unscoped(),
892 attributes: [ 'id', 'url', 'followersUrl' ],
893 model: ActorModel.unscoped(),
899 model: VideoStreamingPlaylistModel.unscoped(),
903 model: VideoFileModel,
908 VideoLiveModel.unscoped(),
914 return Bluebird.all([
915 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
916 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
917 ]).then(([ rows, totals ]) => {
918 // totals: totalVideos + totalVideoShares
920 let totalVideoShares = 0
921 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
922 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
924 const total = totalVideos + totalVideoShares
932 static async listPublishedLiveUUIDs () {
934 attributes: [ 'uuid' ],
938 state: VideoState.PUBLISHED
942 const result = await VideoModel.findAll(options)
944 return result.map(v => v.uuid)
947 static listUserVideosForApi (options: {
957 const { accountId, channelId, start, count, sort, search, isLive } = options
959 function buildBaseQuery (): FindOptions {
960 const where: WhereOptions = {}
964 [Op.iLike]: '%' + search + '%'
968 if (exists(isLive)) {
969 where.isLive = isLive
972 const channelWhere = channelId
980 order: getVideoSort(sort),
983 model: VideoChannelModel,
1002 const countQuery = buildBaseQuery()
1003 const findQuery = buildBaseQuery()
1005 const findScopes: (string | ScopeOptions)[] = [
1006 ScopeNames.WITH_SCHEDULED_UPDATE,
1007 ScopeNames.WITH_BLACKLISTED,
1008 ScopeNames.WITH_THUMBNAILS
1011 return Promise.all([
1012 VideoModel.count(countQuery),
1013 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1014 ]).then(([ count, rows ]) => {
1022 static async listForApi (options: {
1030 include?: VideoInclude
1032 hasFiles?: boolean // default false
1034 categoryOneOf?: number[]
1035 licenceOneOf?: number[]
1036 languageOneOf?: string[]
1037 tagsOneOf?: string[]
1038 tagsAllOf?: string[]
1041 videoChannelId?: number
1043 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1045 videoPlaylistId?: number
1047 trendingDays?: number
1049 user?: MUserAccountId
1050 historyOfUser?: MUserId
1052 countVideos?: boolean
1056 if (VideoModel.isPrivateInclude(options.include) && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1057 throw new Error('Try to filter all-local but no user has not the see all videos right')
1060 const trendingDays = options.sort.endsWith('trending')
1061 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1064 let trendingAlgorithm: string
1065 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1066 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1068 const serverActor = await getServerActor()
1070 const queryOptions = {
1084 'displayOnlyForFollower',
1094 serverAccountIdForBlock: serverActor.Account.id,
1099 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1102 static async searchAndPopulateAccountAndServer (options: {
1108 startDate?: string // ISO 8601
1109 endDate?: string // ISO 8601
1110 originallyPublishedStartDate?: string
1111 originallyPublishedEndDate?: string
1115 include?: VideoInclude
1116 categoryOneOf?: number[]
1117 licenceOneOf?: number[]
1118 languageOneOf?: string[]
1119 tagsOneOf?: string[]
1120 tagsAllOf?: string[]
1121 durationMin?: number // seconds
1122 durationMax?: number // seconds
1123 user?: MUserAccountId
1125 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1127 const serverActor = await getServerActor()
1129 const queryOptions = {
1147 'originallyPublishedStartDate',
1148 'originallyPublishedEndDate',
1153 'displayOnlyForFollower'
1155 serverAccountIdForBlock: serverActor.Account.id
1158 return VideoModel.getAvailableForApi(queryOptions)
1161 static countLocalLives () {
1167 [Op.ne]: VideoState.LIVE_ENDED
1172 return VideoModel.count(options)
1175 static countVideosUploadedByUserSince (userId: number, since: Date) {
1179 model: VideoChannelModel.unscoped(),
1183 model: AccountModel.unscoped(),
1187 model: UserModel.unscoped(),
1205 return VideoModel.unscoped().count(options)
1208 static countLivesOfAccount (accountId: number) {
1214 [Op.ne]: VideoState.LIVE_ENDED
1220 model: VideoChannelModel.unscoped(),
1228 return VideoModel.count(options)
1231 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1232 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1234 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1237 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1238 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1240 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1243 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1246 where: buildWhereIdOrUUID(id),
1250 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1253 return ModelCache.Instance.doCache({
1254 cacheType: 'load-video-immutable-id',
1261 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1263 const query: FindOptions = {
1270 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1273 return ModelCache.Instance.doCache({
1274 cacheType: 'load-video-immutable-url',
1281 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1282 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1284 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1287 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1288 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1290 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1293 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1294 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1296 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1299 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1300 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1302 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1305 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1306 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1308 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1311 static loadForGetAPI (parameters: {
1313 transaction?: Transaction
1315 }): Promise<MVideoDetails> {
1316 const { id, transaction, userId } = parameters
1317 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1319 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1322 static async getStats () {
1323 const totalLocalVideos = await VideoModel.count({
1329 let totalLocalVideoViews = await VideoModel.sum('views', {
1335 // Sequelize could return null...
1336 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1338 const serverActor = await getServerActor()
1340 const { total: totalVideos } = await VideoModel.listForApi({
1343 sort: '-publishedAt',
1344 nsfw: buildNSFWFilter(),
1345 displayOnlyForFollower: {
1346 actorId: serverActor.id,
1353 totalLocalVideoViews,
1358 static incrementViews (id: number, views: number) {
1359 return VideoModel.increment('views', {
1367 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1368 const field = type === 'like'
1372 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1374 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1376 'WHERE "video"."id" = :videoId'
1378 return AccountVideoRateModel.sequelize.query(rawQuery, {
1380 replacements: { videoId, rateType: type },
1381 type: QueryTypes.UPDATE
1385 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1386 // Instances only share videos
1387 const query = 'SELECT 1 FROM "videoShare" ' +
1388 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1389 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1393 type: QueryTypes.SELECT as QueryTypes.SELECT,
1394 bind: { followerActorId, videoId },
1398 return VideoModel.sequelize.query(query, options)
1399 .then(results => results.length === 1)
1402 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1405 channelId: ofChannel.id
1410 return VideoModel.update({ support: ofChannel.support }, options)
1413 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1415 attributes: [ 'id' ],
1417 channelId: videoChannel.id
1421 return VideoModel.findAll(query)
1422 .then(videos => videos.map(v => v.id))
1425 // threshold corresponds to how many video the field should have to be returned
1426 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1427 const serverActor = await getServerActor()
1429 const queryOptions: BuildVideosListQueryOptions = {
1430 attributes: [ `"${field}"` ],
1431 group: `GROUP BY "${field}"`,
1432 having: `HAVING COUNT("${field}") >= ${threshold}`,
1436 serverAccountIdForBlock: serverActor.Account.id,
1437 displayOnlyForFollower: {
1438 actorId: serverActor.id,
1443 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1445 return queryBuilder.queryVideoIds(queryOptions)
1446 .then(rows => rows.map(r => r[field]))
1449 static buildTrendingQuery (trendingDays: number) {
1453 model: VideoViewModel,
1457 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1463 private static async getAvailableForApi (
1464 options: BuildVideosListQueryOptions,
1466 ): Promise<ResultList<VideoModel>> {
1467 function getCount () {
1468 if (countVideos !== true) return Promise.resolve(undefined)
1470 const countOptions = Object.assign({}, options, { isCount: true })
1471 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1473 return queryBuilder.countVideoIds(countOptions)
1476 function getModels () {
1477 if (options.count === 0) return Promise.resolve([])
1479 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1481 return queryBuilder.queryVideos(options)
1484 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1492 private static isPrivateInclude (include: VideoInclude) {
1493 return include & VideoInclude.BLACKLISTED ||
1494 include & VideoInclude.BLOCKED_OWNER ||
1495 include & VideoInclude.HIDDEN_PRIVACY ||
1496 include & VideoInclude.NOT_PUBLISHED_STATE
1500 return !!this.VideoBlacklist
1504 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1507 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1508 // We first transcode to WebTorrent format, so try this array first
1509 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1510 const file = fun(this.VideoFiles, file => file.resolution)
1512 return Object.assign(file, { Video: this })
1515 // No webtorrent files, try with streaming playlist files
1516 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1517 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1519 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1520 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1526 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1527 return this.getQualityFileBy(maxBy)
1530 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1531 return this.getQualityFileBy(minBy)
1534 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1535 if (Array.isArray(this.VideoFiles) === false) return undefined
1537 const file = this.VideoFiles.find(f => f.resolution === resolution)
1538 if (!file) return undefined
1540 return Object.assign(file, { Video: this })
1543 hasWebTorrentFiles () {
1544 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1547 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1548 thumbnail.videoId = this.id
1550 const savedThumbnail = await thumbnail.save({ transaction })
1552 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1554 // Already have this thumbnail, skip
1555 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1557 this.Thumbnails.push(savedThumbnail)
1561 if (Array.isArray(this.Thumbnails) === false) return undefined
1563 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1567 return !!this.getPreview()
1571 if (Array.isArray(this.Thumbnails) === false) return undefined
1573 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1577 return this.remote === false
1580 getWatchStaticPath () {
1581 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1584 getEmbedStaticPath () {
1585 return buildVideoEmbedPath(this)
1588 getMiniatureStaticPath () {
1589 const thumbnail = this.getMiniature()
1590 if (!thumbnail) return null
1592 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1595 getPreviewStaticPath () {
1596 const preview = this.getPreview()
1597 if (!preview) return null
1599 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1600 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1603 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1604 return videoModelToFormattedJSON(this, options)
1607 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1608 return videoModelToFormattedDetailsJSON(this)
1611 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1612 let files: VideoFile[] = []
1614 if (Array.isArray(this.VideoFiles)) {
1615 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1616 files = files.concat(result)
1619 for (const p of (this.VideoStreamingPlaylists || [])) {
1620 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1621 files = files.concat(result)
1627 toActivityPubObject (this: MVideoAP): VideoObject {
1628 return videoModelToActivityPubObject(this)
1631 getTruncatedDescription () {
1632 if (!this.description) return null
1634 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1635 return peertubeTruncate(this.description, { length: maxLength })
1638 getMaxQualityResolution () {
1639 const file = this.getMaxQualityFile()
1640 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1642 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => {
1643 return getVideoFileResolution(originalFilePath)
1647 getDescriptionAPIPath () {
1648 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1651 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1652 if (!this.VideoStreamingPlaylists) return undefined
1654 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1655 playlist.Video = this
1660 setHLSPlaylist (playlist: MStreamingPlaylist) {
1661 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1663 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1664 this.VideoStreamingPlaylists = toAdd
1668 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1669 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1673 removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1674 const filePath = isRedundancy
1675 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1676 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1678 const promises: Promise<any>[] = [ remove(filePath) ]
1679 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1681 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1682 promises.push(removeWebTorrentObjectStorage(videoFile))
1685 return Promise.all(promises)
1688 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1689 const directoryPath = isRedundancy
1690 ? getHLSRedundancyDirectory(this)
1691 : getHLSDirectory(this)
1693 await remove(directoryPath)
1695 if (isRedundancy !== true) {
1696 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1697 streamingPlaylistWithFiles.Video = this
1699 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1700 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1703 // Remove physical files and torrents
1705 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1708 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1709 await removeHLSObjectStorage(streamingPlaylist, this)
1715 if (this.isOwned()) return false
1717 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1720 hasPrivacyForFederation () {
1721 return isPrivacyForFederation(this.privacy)
1724 hasStateForFederation () {
1725 return isStateForFederation(this.state)
1728 isNewVideo (newPrivacy: VideoPrivacy) {
1729 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1733 return setAsUpdated('video', this.id)
1737 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1740 setPrivacy (newPrivacy: VideoPrivacy) {
1741 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1742 this.publishedAt = new Date()
1745 this.privacy = newPrivacy
1749 return this.privacy === VideoPrivacy.PRIVATE ||
1750 this.privacy === VideoPrivacy.UNLISTED ||
1751 this.privacy === VideoPrivacy.INTERNAL
1754 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1755 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1757 this.state = newState
1759 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1760 this.publishedAt = new Date()
1763 await this.save({ transaction })
1766 getBandwidthBits (videoFile: MVideoFile) {
1767 return Math.ceil((videoFile.size * 8) / this.duration)
1771 if (this.isOwned()) {
1773 WEBSERVER.URL + '/tracker/announce',
1774 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1778 return this.Trackers.map(t => t.url)