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 listLocalIds (): Promise<number[]> {
810 attributes: [ 'id' ],
817 return VideoModel.findAll(query)
818 .then(rows => rows.map(r => r.id))
821 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
822 function getRawQuery (select: string) {
823 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
824 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
825 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
826 'WHERE "Account"."actorId" = ' + actorId
827 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
828 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
829 'WHERE "VideoShare"."actorId" = ' + actorId
831 return `(${queryVideo}) UNION (${queryVideoShare})`
834 const rawQuery = getRawQuery('"Video"."id"')
835 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
841 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
844 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
846 [Op.or]: getPrivaciesForFederation()
850 attributes: [ 'filename', 'language', 'fileUrl' ],
851 model: VideoCaptionModel.unscoped(),
855 attributes: [ 'id', 'url' ],
856 model: VideoShareModel.unscoped(),
858 // We only want videos shared by this actor
873 attributes: [ 'id', 'url' ],
874 model: ActorModel.unscoped()
879 model: VideoChannelModel.unscoped(),
883 attributes: [ 'name' ],
884 model: AccountModel.unscoped(),
888 attributes: [ 'id', 'url', 'followersUrl' ],
889 model: ActorModel.unscoped(),
895 attributes: [ 'id', 'url', 'followersUrl' ],
896 model: ActorModel.unscoped(),
902 model: VideoStreamingPlaylistModel.unscoped(),
906 model: VideoFileModel,
911 VideoLiveModel.unscoped(),
917 return Bluebird.all([
918 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
919 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
920 ]).then(([ rows, totals ]) => {
921 // totals: totalVideos + totalVideoShares
923 let totalVideoShares = 0
924 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
925 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
927 const total = totalVideos + totalVideoShares
935 static async listPublishedLiveUUIDs () {
937 attributes: [ 'uuid' ],
941 state: VideoState.PUBLISHED
945 const result = await VideoModel.findAll(options)
947 return result.map(v => v.uuid)
950 static listUserVideosForApi (options: {
960 const { accountId, channelId, start, count, sort, search, isLive } = options
962 function buildBaseQuery (): FindOptions {
963 const where: WhereOptions = {}
967 [Op.iLike]: '%' + search + '%'
971 if (exists(isLive)) {
972 where.isLive = isLive
975 const channelWhere = channelId
983 order: getVideoSort(sort),
986 model: VideoChannelModel,
1005 const countQuery = buildBaseQuery()
1006 const findQuery = buildBaseQuery()
1008 const findScopes: (string | ScopeOptions)[] = [
1009 ScopeNames.WITH_SCHEDULED_UPDATE,
1010 ScopeNames.WITH_BLACKLISTED,
1011 ScopeNames.WITH_THUMBNAILS
1014 return Promise.all([
1015 VideoModel.count(countQuery),
1016 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1017 ]).then(([ count, rows ]) => {
1025 static async listForApi (options: {
1033 include?: VideoInclude
1035 hasFiles?: boolean // default false
1036 hasWebtorrentFiles?: boolean
1037 hasHLSFiles?: boolean
1039 categoryOneOf?: number[]
1040 licenceOneOf?: number[]
1041 languageOneOf?: string[]
1042 tagsOneOf?: string[]
1043 tagsAllOf?: string[]
1046 videoChannelId?: number
1048 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1050 videoPlaylistId?: number
1052 trendingDays?: number
1054 user?: MUserAccountId
1055 historyOfUser?: MUserId
1057 countVideos?: boolean
1061 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1063 const trendingDays = options.sort.endsWith('trending')
1064 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1067 let trendingAlgorithm: string
1068 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1069 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1071 const serverActor = await getServerActor()
1073 const queryOptions = {
1087 'displayOnlyForFollower',
1095 'hasWebtorrentFiles',
1099 serverAccountIdForBlock: serverActor.Account.id,
1104 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1107 static async searchAndPopulateAccountAndServer (options: {
1115 include?: VideoInclude
1117 categoryOneOf?: number[]
1118 licenceOneOf?: number[]
1119 languageOneOf?: string[]
1120 tagsOneOf?: string[]
1121 tagsAllOf?: string[]
1123 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1125 user?: MUserAccountId
1127 hasWebtorrentFiles?: boolean
1128 hasHLSFiles?: boolean
1133 startDate?: string // ISO 8601
1134 endDate?: string // ISO 8601
1135 originallyPublishedStartDate?: string
1136 originallyPublishedEndDate?: string
1138 durationMin?: number // seconds
1139 durationMax?: number // seconds
1142 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1144 const serverActor = await getServerActor()
1146 const queryOptions = {
1164 'originallyPublishedStartDate',
1165 'originallyPublishedEndDate',
1169 'hasWebtorrentFiles',
1172 'displayOnlyForFollower'
1174 serverAccountIdForBlock: serverActor.Account.id
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 VideoModelGetQueryBuilder(VideoModel.sequelize)
1253 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1256 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1257 const queryBuilder = new VideoModelGetQueryBuilder(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 VideoModelGetQueryBuilder(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 VideoModelGetQueryBuilder(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 VideoModelGetQueryBuilder(VideoModel.sequelize)
1315 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1318 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1319 const queryBuilder = new VideoModelGetQueryBuilder(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 VideoModelGetQueryBuilder(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 VideoModelGetQueryBuilder(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 serverActor = await getServerActor()
1359 const { total: totalVideos } = await VideoModel.listForApi({
1362 sort: '-publishedAt',
1363 nsfw: buildNSFWFilter(),
1364 displayOnlyForFollower: {
1365 actorId: serverActor.id,
1372 totalLocalVideoViews,
1377 static incrementViews (id: number, views: number) {
1378 return VideoModel.increment('views', {
1386 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1387 const field = type === 'like'
1391 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1393 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1395 'WHERE "video"."id" = :videoId'
1397 return AccountVideoRateModel.sequelize.query(rawQuery, {
1399 replacements: { videoId, rateType: type },
1400 type: QueryTypes.UPDATE
1404 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1405 // Instances only share videos
1406 const query = 'SELECT 1 FROM "videoShare" ' +
1407 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1408 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1412 type: QueryTypes.SELECT as QueryTypes.SELECT,
1413 bind: { followerActorId, videoId },
1417 return VideoModel.sequelize.query(query, options)
1418 .then(results => results.length === 1)
1421 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1424 channelId: ofChannel.id
1429 return VideoModel.update({ support: ofChannel.support }, options)
1432 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1434 attributes: [ 'id' ],
1436 channelId: videoChannel.id
1440 return VideoModel.findAll(query)
1441 .then(videos => videos.map(v => v.id))
1444 // threshold corresponds to how many video the field should have to be returned
1445 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1446 const serverActor = await getServerActor()
1448 const queryOptions: BuildVideosListQueryOptions = {
1449 attributes: [ `"${field}"` ],
1450 group: `GROUP BY "${field}"`,
1451 having: `HAVING COUNT("${field}") >= ${threshold}`,
1455 serverAccountIdForBlock: serverActor.Account.id,
1456 displayOnlyForFollower: {
1457 actorId: serverActor.id,
1462 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1464 return queryBuilder.queryVideoIds(queryOptions)
1465 .then(rows => rows.map(r => r[field]))
1468 static buildTrendingQuery (trendingDays: number) {
1472 model: VideoViewModel,
1476 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1482 private static async getAvailableForApi (
1483 options: BuildVideosListQueryOptions,
1485 ): Promise<ResultList<VideoModel>> {
1486 function getCount () {
1487 if (countVideos !== true) return Promise.resolve(undefined)
1489 const countOptions = Object.assign({}, options, { isCount: true })
1490 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1492 return queryBuilder.countVideoIds(countOptions)
1495 function getModels () {
1496 if (options.count === 0) return Promise.resolve([])
1498 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1500 return queryBuilder.queryVideos(options)
1503 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1511 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1512 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1513 throw new Error('Try to filter all-local but no user has not the see all videos right')
1517 private static isPrivateInclude (include: VideoInclude) {
1518 return include & VideoInclude.BLACKLISTED ||
1519 include & VideoInclude.BLOCKED_OWNER ||
1520 include & VideoInclude.HIDDEN_PRIVACY ||
1521 include & VideoInclude.NOT_PUBLISHED_STATE
1525 return !!this.VideoBlacklist
1529 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1532 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1533 // We first transcode to WebTorrent format, so try this array first
1534 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1535 const file = fun(this.VideoFiles, file => file.resolution)
1537 return Object.assign(file, { Video: this })
1540 // No webtorrent files, try with streaming playlist files
1541 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1542 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1544 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1545 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1551 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1552 return this.getQualityFileBy(maxBy)
1555 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1556 return this.getQualityFileBy(minBy)
1559 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1560 if (Array.isArray(this.VideoFiles) === false) return undefined
1562 const file = this.VideoFiles.find(f => f.resolution === resolution)
1563 if (!file) return undefined
1565 return Object.assign(file, { Video: this })
1568 hasWebTorrentFiles () {
1569 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1572 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1573 thumbnail.videoId = this.id
1575 const savedThumbnail = await thumbnail.save({ transaction })
1577 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1579 // Already have this thumbnail, skip
1580 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1582 this.Thumbnails.push(savedThumbnail)
1586 if (Array.isArray(this.Thumbnails) === false) return undefined
1588 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1592 return !!this.getPreview()
1596 if (Array.isArray(this.Thumbnails) === false) return undefined
1598 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1602 return this.remote === false
1605 getWatchStaticPath () {
1606 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1609 getEmbedStaticPath () {
1610 return buildVideoEmbedPath(this)
1613 getMiniatureStaticPath () {
1614 const thumbnail = this.getMiniature()
1615 if (!thumbnail) return null
1617 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1620 getPreviewStaticPath () {
1621 const preview = this.getPreview()
1622 if (!preview) return null
1624 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1625 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1628 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1629 return videoModelToFormattedJSON(this, options)
1632 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1633 return videoModelToFormattedDetailsJSON(this)
1636 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1637 let files: VideoFile[] = []
1639 if (Array.isArray(this.VideoFiles)) {
1640 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1641 files = files.concat(result)
1644 for (const p of (this.VideoStreamingPlaylists || [])) {
1645 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1646 files = files.concat(result)
1652 toActivityPubObject (this: MVideoAP): VideoObject {
1653 return videoModelToActivityPubObject(this)
1656 getTruncatedDescription () {
1657 if (!this.description) return null
1659 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1660 return peertubeTruncate(this.description, { length: maxLength })
1663 getMaxQualityResolution () {
1664 const file = this.getMaxQualityFile()
1665 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1667 return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => {
1668 return getVideoFileResolution(originalFilePath)
1672 getDescriptionAPIPath () {
1673 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1676 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1677 if (!this.VideoStreamingPlaylists) return undefined
1679 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1680 if (!playlist) return undefined
1682 playlist.Video = this
1687 setHLSPlaylist (playlist: MStreamingPlaylist) {
1688 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1690 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1691 this.VideoStreamingPlaylists = toAdd
1695 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1696 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1700 removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1701 const filePath = isRedundancy
1702 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1703 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1705 const promises: Promise<any>[] = [ remove(filePath) ]
1706 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1708 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1709 promises.push(removeWebTorrentObjectStorage(videoFile))
1712 return Promise.all(promises)
1715 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1716 const directoryPath = isRedundancy
1717 ? getHLSRedundancyDirectory(this)
1718 : getHLSDirectory(this)
1720 await remove(directoryPath)
1722 if (isRedundancy !== true) {
1723 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1724 streamingPlaylistWithFiles.Video = this
1726 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1727 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1730 // Remove physical files and torrents
1732 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1735 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1736 await removeHLSObjectStorage(streamingPlaylist, this)
1742 if (this.isOwned()) return false
1744 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1747 hasPrivacyForFederation () {
1748 return isPrivacyForFederation(this.privacy)
1751 hasStateForFederation () {
1752 return isStateForFederation(this.state)
1755 isNewVideo (newPrivacy: VideoPrivacy) {
1756 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1760 return setAsUpdated('video', this.id)
1764 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1767 setPrivacy (newPrivacy: VideoPrivacy) {
1768 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1769 this.publishedAt = new Date()
1772 this.privacy = newPrivacy
1776 return this.privacy === VideoPrivacy.PRIVATE ||
1777 this.privacy === VideoPrivacy.UNLISTED ||
1778 this.privacy === VideoPrivacy.INTERNAL
1781 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1782 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1784 this.state = newState
1786 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1787 this.publishedAt = new Date()
1790 await this.save({ transaction })
1793 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1794 return Math.ceil((videoFile.size * 8) / this.duration)
1798 if (this.isOwned()) {
1800 WEBSERVER.URL + '/tracker/announce',
1801 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1805 return this.Trackers.map(t => t.url)