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 { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
29 import { LiveManager } from '@server/lib/live/live-manager'
30 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
31 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
32 import { VideoPathManager } from '@server/lib/video-path-manager'
33 import { getServerActor } from '@server/models/application/application'
34 import { ModelCache } from '@server/models/model-cache'
35 import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
36 import { ffprobePromise, getAudioStream, uuidToShort } from '@shared/extra-utils'
50 VideoStreamingPlaylistType
51 } from '@shared/models'
52 import { AttributesOnly } from '@shared/typescript-utils'
53 import { peertubeTruncate } from '../../helpers/core-utils'
54 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
55 import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
57 isVideoDescriptionValid,
63 } from '../../helpers/custom-validators/videos'
64 import { getVideoStreamDimensionsInfo } from '../../helpers/ffmpeg'
65 import { logger } from '../../helpers/logger'
66 import { CONFIG } from '../../initializers/config'
67 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
68 import { sendDeleteVideo } from '../../lib/activitypub/send'
71 MChannelAccountDefault,
74 MStreamingPlaylistFilesVideo,
79 MVideoAccountLightBlacklistAllFiles,
84 MVideoFormattableDetails,
90 MVideoThumbnailBlacklist,
93 } from '../../types/models'
94 import { MThumbnail } from '../../types/models/video/thumbnail'
95 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
96 import { VideoAbuseModel } from '../abuse/video-abuse'
97 import { AccountModel } from '../account/account'
98 import { AccountVideoRateModel } from '../account/account-video-rate'
99 import { ActorModel } from '../actor/actor'
100 import { ActorImageModel } from '../actor/actor-image'
101 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
102 import { ServerModel } from '../server/server'
103 import { TrackerModel } from '../server/tracker'
104 import { VideoTrackerModel } from '../server/video-tracker'
105 import { setAsUpdated } from '../shared'
106 import { UserModel } from '../user/user'
107 import { UserVideoHistoryModel } from '../user/user-video-history'
108 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
109 import { VideoViewModel } from '../view/video-view'
111 videoFilesModelToFormattedJSON,
112 VideoFormattingJSONOptions,
113 videoModelToActivityPubObject,
114 videoModelToFormattedDetailsJSON,
115 videoModelToFormattedJSON
116 } from './formatter/video-format-utils'
117 import { ScheduleVideoUpdateModel } from './schedule-video-update'
119 BuildVideosListQueryOptions,
120 DisplayOnlyForFollowerOptions,
121 VideoModelGetQueryBuilder,
122 VideosIdListQueryBuilder,
123 VideosModelListQueryBuilder
125 import { TagModel } from './tag'
126 import { ThumbnailModel } from './thumbnail'
127 import { VideoBlacklistModel } from './video-blacklist'
128 import { VideoCaptionModel } from './video-caption'
129 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
130 import { VideoCommentModel } from './video-comment'
131 import { VideoFileModel } from './video-file'
132 import { VideoImportModel } from './video-import'
133 import { VideoJobInfoModel } from './video-job-info'
134 import { VideoLiveModel } from './video-live'
135 import { VideoPlaylistElementModel } from './video-playlist-element'
136 import { VideoShareModel } from './video-share'
137 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
138 import { VideoTagModel } from './video-tag'
140 export enum ScopeNames {
142 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
143 WITH_TAGS = 'WITH_TAGS',
144 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
145 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
146 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
147 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
148 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
149 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
150 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
153 export type ForAPIOptions = {
156 videoPlaylistId?: number
158 withAccountBlockerIds?: number[]
162 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
163 attributes: [ 'id', 'url', 'uuid', 'remote' ]
165 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
166 const include: Includeable[] = [
168 model: VideoChannelModel.scope({
170 VideoChannelScopeNames.SUMMARY, {
172 withAccountBlockerIds: options.withAccountBlockerIds
179 attributes: [ 'type', 'filename' ],
180 model: ThumbnailModel,
185 const query: FindOptions = {}
195 if (options.videoPlaylistId) {
197 model: VideoPlaylistElementModel.unscoped(),
200 videoPlaylistId: options.videoPlaylistId
205 query.include = include
209 [ScopeNames.WITH_THUMBNAILS]: {
212 model: ThumbnailModel,
217 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
220 model: VideoChannelModel.unscoped(),
225 exclude: [ 'privateKey', 'publicKey' ]
227 model: ActorModel.unscoped(),
231 attributes: [ 'host' ],
232 model: ServerModel.unscoped(),
236 model: ActorImageModel,
243 model: AccountModel.unscoped(),
247 model: ActorModel.unscoped(),
249 exclude: [ 'privateKey', 'publicKey' ]
254 attributes: [ 'host' ],
255 model: ServerModel.unscoped(),
259 model: ActorImageModel,
271 [ScopeNames.WITH_TAGS]: {
272 include: [ TagModel ]
274 [ScopeNames.WITH_BLACKLISTED]: {
277 attributes: [ 'id', 'reason', 'unfederated' ],
278 model: VideoBlacklistModel,
283 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
284 let subInclude: any[] = []
286 if (withRedundancies === true) {
289 attributes: [ 'fileUrl' ],
290 model: VideoRedundancyModel.unscoped(),
299 model: VideoFileModel,
307 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
308 const subInclude: IncludeOptions[] = [
310 model: VideoFileModel,
315 if (withRedundancies === true) {
317 attributes: [ 'fileUrl' ],
318 model: VideoRedundancyModel.unscoped(),
326 model: VideoStreamingPlaylistModel.unscoped(),
334 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
337 model: ScheduleVideoUpdateModel.unscoped(),
342 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
346 attributes: [ 'currentTime' ],
347 model: UserVideoHistoryModel.unscoped(),
360 buildTrigramSearchIndex('video_name_trigram', 'name'),
362 { fields: [ 'createdAt' ] },
365 { name: 'publishedAt', order: 'DESC' },
366 { name: 'id', order: 'ASC' }
369 { fields: [ 'duration' ] },
372 { name: 'views', order: 'DESC' },
373 { name: 'id', order: 'ASC' }
376 { fields: [ 'channelId' ] },
378 fields: [ 'originallyPublishedAt' ],
380 originallyPublishedAt: {
386 fields: [ 'category' ], // We don't care videos with an unknown category
394 fields: [ 'licence' ], // We don't care videos with an unknown licence
402 fields: [ 'language' ], // We don't care videos with an unknown language
410 fields: [ 'nsfw' ], // Most of the videos are not NSFW
416 fields: [ 'remote' ], // Only index local videos
431 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
434 @Default(DataType.UUIDV4)
436 @Column(DataType.UUID)
440 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
456 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
460 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
462 privacy: VideoPrivacy
465 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
471 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
472 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
477 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
478 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
482 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
517 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
523 commentsEnabled: boolean
527 downloadEnabled: boolean
531 waitTranscoding: boolean
535 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
546 @Default(DataType.NOW)
553 originallyPublishedAt: Date
555 @ForeignKey(() => VideoChannelModel)
559 @BelongsTo(() => VideoChannelModel, {
565 VideoChannel: VideoChannelModel
567 @BelongsToMany(() => TagModel, {
568 foreignKey: 'videoId',
569 through: () => VideoTagModel,
574 @BelongsToMany(() => TrackerModel, {
575 foreignKey: 'videoId',
576 through: () => VideoTrackerModel,
579 Trackers: TrackerModel[]
581 @HasMany(() => ThumbnailModel, {
589 Thumbnails: ThumbnailModel[]
591 @HasMany(() => VideoPlaylistElementModel, {
598 VideoPlaylistElements: VideoPlaylistElementModel[]
600 @HasMany(() => VideoAbuseModel, {
607 VideoAbuses: VideoAbuseModel[]
609 @HasMany(() => VideoFileModel, {
617 VideoFiles: VideoFileModel[]
619 @HasMany(() => VideoStreamingPlaylistModel, {
627 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
629 @HasMany(() => VideoShareModel, {
636 VideoShares: VideoShareModel[]
638 @HasMany(() => AccountVideoRateModel, {
645 AccountVideoRates: AccountVideoRateModel[]
647 @HasMany(() => VideoCommentModel, {
655 VideoComments: VideoCommentModel[]
657 @HasMany(() => VideoViewModel, {
664 VideoViews: VideoViewModel[]
666 @HasMany(() => UserVideoHistoryModel, {
673 UserVideoHistories: UserVideoHistoryModel[]
675 @HasOne(() => ScheduleVideoUpdateModel, {
682 ScheduleVideoUpdate: ScheduleVideoUpdateModel
684 @HasOne(() => VideoBlacklistModel, {
691 VideoBlacklist: VideoBlacklistModel
693 @HasOne(() => VideoLiveModel, {
700 VideoLive: VideoLiveModel
702 @HasOne(() => VideoImportModel, {
709 VideoImport: VideoImportModel
711 @HasMany(() => VideoCaptionModel, {
718 ['separate' as any]: true
720 VideoCaptions: VideoCaptionModel[]
722 @HasOne(() => VideoJobInfoModel, {
729 VideoJobInfo: VideoJobInfoModel
732 static async sendDelete (instance: MVideoAccountLight, options) {
733 if (!instance.isOwned()) return undefined
735 // Lazy load channels
736 if (!instance.VideoChannel) {
737 instance.VideoChannel = await instance.$get('VideoChannel', {
742 transaction: options.transaction
743 }) as MChannelAccountDefault
746 return sendDeleteVideo(instance, options.transaction)
750 static async removeFiles (instance: VideoModel, options) {
751 const tasks: Promise<any>[] = []
753 logger.info('Removing files of video %s.', instance.url)
755 if (instance.isOwned()) {
756 if (!Array.isArray(instance.VideoFiles)) {
757 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
760 // Remove physical files and torrents
761 instance.VideoFiles.forEach(file => {
762 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
765 // Remove playlists file
766 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
767 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
770 for (const p of instance.VideoStreamingPlaylists) {
771 tasks.push(instance.removeStreamingPlaylistFiles(p))
775 // Do not wait video deletion because we could be in a transaction
778 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
785 static stopLiveIfNeeded (instance: VideoModel) {
786 if (!instance.isLive) return
788 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
790 LiveManager.Instance.stopSessionOf(instance.id)
794 static invalidateCache (instance: VideoModel) {
795 ModelCache.Instance.invalidateCache('video', instance.id)
799 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
800 const tasks: Promise<any>[] = []
802 if (!Array.isArray(instance.VideoAbuses)) {
803 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
805 if (instance.VideoAbuses.length === 0) return undefined
808 logger.info('Saving video abuses details of video %s.', instance.url)
810 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
811 const details = instance.toFormattedDetailsJSON()
813 for (const abuse of instance.VideoAbuses) {
814 abuse.deletedVideo = details
815 tasks.push(abuse.save({ transaction: options.transaction }))
818 await Promise.all(tasks)
821 static listLocalIds (): Promise<number[]> {
823 attributes: [ 'id' ],
830 return VideoModel.findAll(query)
831 .then(rows => rows.map(r => r.id))
834 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
835 function getRawQuery (select: string) {
836 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
837 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
838 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
839 'WHERE "Account"."actorId" = ' + actorId
840 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
841 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
842 'WHERE "VideoShare"."actorId" = ' + actorId
844 return `(${queryVideo}) UNION (${queryVideoShare})`
847 const rawQuery = getRawQuery('"Video"."id"')
848 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
854 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
857 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
859 [Op.or]: getPrivaciesForFederation()
863 attributes: [ 'filename', 'language', 'fileUrl' ],
864 model: VideoCaptionModel.unscoped(),
868 attributes: [ 'id', 'url' ],
869 model: VideoShareModel.unscoped(),
871 // We only want videos shared by this actor
886 attributes: [ 'id', 'url' ],
887 model: ActorModel.unscoped()
892 model: VideoChannelModel.unscoped(),
896 attributes: [ 'name' ],
897 model: AccountModel.unscoped(),
901 attributes: [ 'id', 'url', 'followersUrl' ],
902 model: ActorModel.unscoped(),
908 attributes: [ 'id', 'url', 'followersUrl' ],
909 model: ActorModel.unscoped(),
915 model: VideoStreamingPlaylistModel.unscoped(),
919 model: VideoFileModel,
924 VideoLiveModel.unscoped(),
930 return Bluebird.all([
931 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
932 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
933 ]).then(([ rows, totals ]) => {
934 // totals: totalVideos + totalVideoShares
936 let totalVideoShares = 0
937 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
938 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
940 const total = totalVideos + totalVideoShares
948 static async listPublishedLiveUUIDs () {
950 attributes: [ 'uuid' ],
954 state: VideoState.PUBLISHED
958 const result = await VideoModel.findAll(options)
960 return result.map(v => v.uuid)
963 static listUserVideosForApi (options: {
973 const { accountId, channelId, start, count, sort, search, isLive } = options
975 function buildBaseQuery (): FindOptions {
976 const where: WhereOptions = {}
980 [Op.iLike]: '%' + search + '%'
984 if (exists(isLive)) {
985 where.isLive = isLive
988 const channelWhere = channelId
996 order: getVideoSort(sort),
999 model: VideoChannelModel,
1001 where: channelWhere,
1004 model: AccountModel,
1018 const countQuery = buildBaseQuery()
1019 const findQuery = buildBaseQuery()
1021 const findScopes: (string | ScopeOptions)[] = [
1022 ScopeNames.WITH_SCHEDULED_UPDATE,
1023 ScopeNames.WITH_BLACKLISTED,
1024 ScopeNames.WITH_THUMBNAILS
1027 return Promise.all([
1028 VideoModel.count(countQuery),
1029 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1030 ]).then(([ count, rows ]) => {
1038 static async listForApi (options: {
1046 include?: VideoInclude
1048 hasFiles?: boolean // default false
1049 hasWebtorrentFiles?: boolean
1050 hasHLSFiles?: boolean
1052 categoryOneOf?: number[]
1053 licenceOneOf?: number[]
1054 languageOneOf?: string[]
1055 tagsOneOf?: string[]
1056 tagsAllOf?: string[]
1057 privacyOneOf?: VideoPrivacy[]
1060 videoChannelId?: number
1062 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1064 videoPlaylistId?: number
1066 trendingDays?: number
1068 user?: MUserAccountId
1069 historyOfUser?: MUserId
1071 countVideos?: boolean
1075 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1076 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1078 const trendingDays = options.sort.endsWith('trending')
1079 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1082 let trendingAlgorithm: string
1083 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1084 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1086 const serverActor = await getServerActor()
1088 const queryOptions = {
1103 'displayOnlyForFollower',
1111 'hasWebtorrentFiles',
1115 serverAccountIdForBlock: serverActor.Account.id,
1120 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1123 static async searchAndPopulateAccountAndServer (options: {
1131 include?: VideoInclude
1133 categoryOneOf?: number[]
1134 licenceOneOf?: number[]
1135 languageOneOf?: string[]
1136 tagsOneOf?: string[]
1137 tagsAllOf?: string[]
1138 privacyOneOf?: VideoPrivacy[]
1140 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1142 user?: MUserAccountId
1144 hasWebtorrentFiles?: boolean
1145 hasHLSFiles?: boolean
1150 startDate?: string // ISO 8601
1151 endDate?: string // ISO 8601
1152 originallyPublishedStartDate?: string
1153 originallyPublishedEndDate?: string
1155 durationMin?: number // seconds
1156 durationMax?: number // seconds
1159 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1160 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1162 const serverActor = await getServerActor()
1164 const queryOptions = {
1183 'originallyPublishedStartDate',
1184 'originallyPublishedEndDate',
1188 'hasWebtorrentFiles',
1191 'displayOnlyForFollower'
1193 serverAccountIdForBlock: serverActor.Account.id
1196 return VideoModel.getAvailableForApi(queryOptions)
1199 static countLocalLives () {
1205 [Op.ne]: VideoState.LIVE_ENDED
1210 return VideoModel.count(options)
1213 static countVideosUploadedByUserSince (userId: number, since: Date) {
1217 model: VideoChannelModel.unscoped(),
1221 model: AccountModel.unscoped(),
1225 model: UserModel.unscoped(),
1243 return VideoModel.unscoped().count(options)
1246 static countLivesOfAccount (accountId: number) {
1252 [Op.ne]: VideoState.LIVE_ENDED
1258 model: VideoChannelModel.unscoped(),
1266 return VideoModel.count(options)
1269 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1270 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1272 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1275 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1276 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1278 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1281 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1284 where: buildWhereIdOrUUID(id),
1288 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1291 return ModelCache.Instance.doCache({
1292 cacheType: 'load-video-immutable-id',
1299 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1301 const query: FindOptions = {
1308 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1311 return ModelCache.Instance.doCache({
1312 cacheType: 'load-video-immutable-url',
1319 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1320 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1322 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1325 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1326 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1328 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1331 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1332 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1334 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1337 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1338 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1340 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1343 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1344 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1346 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1349 static loadForGetAPI (parameters: {
1351 transaction?: Transaction
1353 }): Promise<MVideoDetails> {
1354 const { id, transaction, userId } = parameters
1355 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1357 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1360 static async getStats () {
1361 const totalLocalVideos = await VideoModel.count({
1367 let totalLocalVideoViews = await VideoModel.sum('views', {
1373 // Sequelize could return null...
1374 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1376 const serverActor = await getServerActor()
1378 const { total: totalVideos } = await VideoModel.listForApi({
1381 sort: '-publishedAt',
1382 nsfw: buildNSFWFilter(),
1383 displayOnlyForFollower: {
1384 actorId: serverActor.id,
1391 totalLocalVideoViews,
1396 static incrementViews (id: number, views: number) {
1397 return VideoModel.increment('views', {
1405 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1406 const field = type === 'like'
1410 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1412 return AccountVideoRateModel.sequelize.query(rawQuery, {
1414 replacements: { videoId, rateType: type, count },
1415 type: QueryTypes.UPDATE
1419 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
1420 const field = type === 'like'
1424 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1426 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1428 'WHERE "video"."id" = :videoId'
1430 return AccountVideoRateModel.sequelize.query(rawQuery, {
1432 replacements: { videoId, rateType: type },
1433 type: QueryTypes.UPDATE
1437 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1438 // Instances only share videos
1439 const query = 'SELECT 1 FROM "videoShare" ' +
1440 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1441 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1445 type: QueryTypes.SELECT as QueryTypes.SELECT,
1446 bind: { followerActorId, videoId },
1450 return VideoModel.sequelize.query(query, options)
1451 .then(results => results.length === 1)
1454 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1457 channelId: ofChannel.id
1462 return VideoModel.update({ support: ofChannel.support }, options)
1465 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1467 attributes: [ 'id' ],
1469 channelId: videoChannel.id
1473 return VideoModel.findAll(query)
1474 .then(videos => videos.map(v => v.id))
1477 // threshold corresponds to how many video the field should have to be returned
1478 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1479 const serverActor = await getServerActor()
1481 const queryOptions: BuildVideosListQueryOptions = {
1482 attributes: [ `"${field}"` ],
1483 group: `GROUP BY "${field}"`,
1484 having: `HAVING COUNT("${field}") >= ${threshold}`,
1488 serverAccountIdForBlock: serverActor.Account.id,
1489 displayOnlyForFollower: {
1490 actorId: serverActor.id,
1495 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1497 return queryBuilder.queryVideoIds(queryOptions)
1498 .then(rows => rows.map(r => r[field]))
1501 static buildTrendingQuery (trendingDays: number) {
1505 model: VideoViewModel,
1510 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1516 private static async getAvailableForApi (
1517 options: BuildVideosListQueryOptions,
1519 ): Promise<ResultList<VideoModel>> {
1520 function getCount () {
1521 if (countVideos !== true) return Promise.resolve(undefined)
1523 const countOptions = Object.assign({}, options, { isCount: true })
1524 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1526 return queryBuilder.countVideoIds(countOptions)
1529 function getModels () {
1530 if (options.count === 0) return Promise.resolve([])
1532 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1534 return queryBuilder.queryVideos(options)
1537 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1545 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1546 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1547 throw new Error('Try to filter all-local but user cannot see all videos')
1551 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1552 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1553 throw new Error('Try to choose video privacies but user cannot see all videos')
1557 private static isPrivateInclude (include: VideoInclude) {
1558 return include & VideoInclude.BLACKLISTED ||
1559 include & VideoInclude.BLOCKED_OWNER ||
1560 include & VideoInclude.NOT_PUBLISHED_STATE
1564 return !!this.VideoBlacklist
1568 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1571 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1572 // We first transcode to WebTorrent format, so try this array first
1573 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1574 const file = fun(this.VideoFiles, file => file.resolution)
1576 return Object.assign(file, { Video: this })
1579 // No webtorrent files, try with streaming playlist files
1580 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1581 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1583 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1584 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1590 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1591 return this.getQualityFileBy(maxBy)
1594 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1595 return this.getQualityFileBy(minBy)
1598 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1599 if (Array.isArray(this.VideoFiles) === false) return undefined
1601 const file = this.VideoFiles.find(f => f.resolution === resolution)
1602 if (!file) return undefined
1604 return Object.assign(file, { Video: this })
1607 hasWebTorrentFiles () {
1608 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1611 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1612 thumbnail.videoId = this.id
1614 const savedThumbnail = await thumbnail.save({ transaction })
1616 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1618 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1619 this.Thumbnails.push(savedThumbnail)
1623 if (Array.isArray(this.Thumbnails) === false) return undefined
1625 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1629 return !!this.getPreview()
1633 if (Array.isArray(this.Thumbnails) === false) return undefined
1635 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1639 return this.remote === false
1642 getWatchStaticPath () {
1643 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1646 getEmbedStaticPath () {
1647 return buildVideoEmbedPath(this)
1650 getMiniatureStaticPath () {
1651 const thumbnail = this.getMiniature()
1652 if (!thumbnail) return null
1654 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1657 getPreviewStaticPath () {
1658 const preview = this.getPreview()
1659 if (!preview) return null
1661 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1662 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1665 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1666 return videoModelToFormattedJSON(this, options)
1669 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1670 return videoModelToFormattedDetailsJSON(this)
1673 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1674 let files: VideoFile[] = []
1676 if (Array.isArray(this.VideoFiles)) {
1677 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1678 files = files.concat(result)
1681 for (const p of (this.VideoStreamingPlaylists || [])) {
1682 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1683 files = files.concat(result)
1689 toActivityPubObject (this: MVideoAP): VideoObject {
1690 return videoModelToActivityPubObject(this)
1693 getTruncatedDescription () {
1694 if (!this.description) return null
1696 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1697 return peertubeTruncate(this.description, { length: maxLength })
1701 let files: MVideoFile[] = []
1703 if (Array.isArray(this.VideoFiles)) {
1704 files = files.concat(this.VideoFiles)
1707 if (Array.isArray(this.VideoStreamingPlaylists)) {
1708 for (const p of this.VideoStreamingPlaylists) {
1709 if (Array.isArray(p.VideoFiles)) {
1710 files = files.concat(p.VideoFiles)
1718 probeMaxQualityFile () {
1719 const file = this.getMaxQualityFile()
1720 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1722 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1723 const probe = await ffprobePromise(originalFilePath)
1725 const { audioStream } = await getAudioStream(originalFilePath, probe)
1730 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
1735 getDescriptionAPIPath () {
1736 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1739 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1740 if (!this.VideoStreamingPlaylists) return undefined
1742 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1743 if (!playlist) return undefined
1745 playlist.Video = this
1750 setHLSPlaylist (playlist: MStreamingPlaylist) {
1751 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1753 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1754 this.VideoStreamingPlaylists = toAdd
1758 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1759 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1763 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1764 const filePath = isRedundancy
1765 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1766 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1768 const promises: Promise<any>[] = [ remove(filePath) ]
1769 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1771 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1772 promises.push(removeWebTorrentObjectStorage(videoFile))
1775 return Promise.all(promises)
1778 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1779 const directoryPath = isRedundancy
1780 ? getHLSRedundancyDirectory(this)
1781 : getHLSDirectory(this)
1783 await remove(directoryPath)
1785 if (isRedundancy !== true) {
1786 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1787 streamingPlaylistWithFiles.Video = this
1789 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1790 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1793 // Remove physical files and torrents
1795 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1798 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1799 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1805 if (this.isOwned()) return false
1807 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1810 hasPrivacyForFederation () {
1811 return isPrivacyForFederation(this.privacy)
1814 hasStateForFederation () {
1815 return isStateForFederation(this.state)
1818 isNewVideo (newPrivacy: VideoPrivacy) {
1819 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1822 setAsRefreshed (transaction?: Transaction) {
1823 return setAsUpdated('video', this.id, transaction)
1827 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1830 setPrivacy (newPrivacy: VideoPrivacy) {
1831 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1832 this.publishedAt = new Date()
1835 this.privacy = newPrivacy
1839 return this.privacy === VideoPrivacy.PRIVATE ||
1840 this.privacy === VideoPrivacy.UNLISTED ||
1841 this.privacy === VideoPrivacy.INTERNAL
1844 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1845 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1847 this.state = newState
1849 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1850 this.publishedAt = new Date()
1853 await this.save({ transaction })
1856 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1857 return Math.ceil((videoFile.size * 8) / this.duration)
1861 if (this.isOwned()) {
1863 WEBSERVER.URL + '/tracker/announce',
1864 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1868 return this.Trackers.map(t => t.url)