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 { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
28 import { LiveManager } from '@server/lib/live/live-manager'
29 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
30 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
31 import { VideoPathManager } from '@server/lib/video-path-manager'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
35 import { ffprobePromise, getAudioStream, uuidToShort } from '@shared/extra-utils'
49 VideoStreamingPlaylistType
50 } from '@shared/models'
51 import { AttributesOnly } from '@shared/typescript-utils'
52 import { peertubeTruncate } from '../../helpers/core-utils'
53 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
54 import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
56 isVideoDescriptionValid,
62 } from '../../helpers/custom-validators/videos'
63 import { getVideoStreamDimensionsInfo } from '../../helpers/ffmpeg'
64 import { logger } from '../../helpers/logger'
65 import { CONFIG } from '../../initializers/config'
66 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 MChannelAccountDefault,
73 MStreamingPlaylistFilesVideo,
78 MVideoAccountLightBlacklistAllFiles,
83 MVideoFormattableDetails,
89 MVideoThumbnailBlacklist,
92 } from '../../types/models'
93 import { MThumbnail } from '../../types/models/video/thumbnail'
94 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
95 import { VideoAbuseModel } from '../abuse/video-abuse'
96 import { AccountModel } from '../account/account'
97 import { AccountVideoRateModel } from '../account/account-video-rate'
98 import { ActorModel } from '../actor/actor'
99 import { ActorImageModel } from '../actor/actor-image'
100 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
101 import { ServerModel } from '../server/server'
102 import { TrackerModel } from '../server/tracker'
103 import { VideoTrackerModel } from '../server/video-tracker'
104 import { setAsUpdated } from '../shared'
105 import { UserModel } from '../user/user'
106 import { UserVideoHistoryModel } from '../user/user-video-history'
107 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
108 import { VideoViewModel } from '../view/video-view'
110 videoFilesModelToFormattedJSON,
111 VideoFormattingJSONOptions,
112 videoModelToActivityPubObject,
113 videoModelToFormattedDetailsJSON,
114 videoModelToFormattedJSON
115 } from './formatter/video-format-utils'
116 import { ScheduleVideoUpdateModel } from './schedule-video-update'
118 BuildVideosListQueryOptions,
119 DisplayOnlyForFollowerOptions,
120 VideoModelGetQueryBuilder,
121 VideosIdListQueryBuilder,
122 VideosModelListQueryBuilder
124 import { TagModel } from './tag'
125 import { ThumbnailModel } from './thumbnail'
126 import { VideoBlacklistModel } from './video-blacklist'
127 import { VideoCaptionModel } from './video-caption'
128 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
129 import { VideoCommentModel } from './video-comment'
130 import { VideoFileModel } from './video-file'
131 import { VideoImportModel } from './video-import'
132 import { VideoJobInfoModel } from './video-job-info'
133 import { VideoLiveModel } from './video-live'
134 import { VideoPlaylistElementModel } from './video-playlist-element'
135 import { VideoShareModel } from './video-share'
136 import { VideoSourceModel } from './video-source'
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 @HasOne(() => VideoSourceModel, {
607 VideoSource: VideoSourceModel
609 @HasMany(() => VideoAbuseModel, {
616 VideoAbuses: VideoAbuseModel[]
618 @HasMany(() => VideoFileModel, {
626 VideoFiles: VideoFileModel[]
628 @HasMany(() => VideoStreamingPlaylistModel, {
636 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
638 @HasMany(() => VideoShareModel, {
645 VideoShares: VideoShareModel[]
647 @HasMany(() => AccountVideoRateModel, {
654 AccountVideoRates: AccountVideoRateModel[]
656 @HasMany(() => VideoCommentModel, {
664 VideoComments: VideoCommentModel[]
666 @HasMany(() => VideoViewModel, {
673 VideoViews: VideoViewModel[]
675 @HasMany(() => UserVideoHistoryModel, {
682 UserVideoHistories: UserVideoHistoryModel[]
684 @HasOne(() => ScheduleVideoUpdateModel, {
691 ScheduleVideoUpdate: ScheduleVideoUpdateModel
693 @HasOne(() => VideoBlacklistModel, {
700 VideoBlacklist: VideoBlacklistModel
702 @HasOne(() => VideoLiveModel, {
709 VideoLive: VideoLiveModel
711 @HasOne(() => VideoImportModel, {
718 VideoImport: VideoImportModel
720 @HasMany(() => VideoCaptionModel, {
727 ['separate' as any]: true
729 VideoCaptions: VideoCaptionModel[]
731 @HasOne(() => VideoJobInfoModel, {
738 VideoJobInfo: VideoJobInfoModel
741 static async sendDelete (instance: MVideoAccountLight, options) {
742 if (!instance.isOwned()) return undefined
744 // Lazy load channels
745 if (!instance.VideoChannel) {
746 instance.VideoChannel = await instance.$get('VideoChannel', {
751 transaction: options.transaction
752 }) as MChannelAccountDefault
755 return sendDeleteVideo(instance, options.transaction)
759 static async removeFiles (instance: VideoModel, options) {
760 const tasks: Promise<any>[] = []
762 logger.info('Removing files of video %s.', instance.url)
764 if (instance.isOwned()) {
765 if (!Array.isArray(instance.VideoFiles)) {
766 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
769 // Remove physical files and torrents
770 instance.VideoFiles.forEach(file => {
771 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
774 // Remove playlists file
775 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
776 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
779 for (const p of instance.VideoStreamingPlaylists) {
780 tasks.push(instance.removeStreamingPlaylistFiles(p))
784 // Do not wait video deletion because we could be in a transaction
787 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
794 static stopLiveIfNeeded (instance: VideoModel) {
795 if (!instance.isLive) return
797 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
799 LiveManager.Instance.stopSessionOf(instance.id, null)
803 static invalidateCache (instance: VideoModel) {
804 ModelCache.Instance.invalidateCache('video', instance.id)
808 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
809 const tasks: Promise<any>[] = []
811 if (!Array.isArray(instance.VideoAbuses)) {
812 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
814 if (instance.VideoAbuses.length === 0) return undefined
817 logger.info('Saving video abuses details of video %s.', instance.url)
819 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
820 const details = instance.toFormattedDetailsJSON()
822 for (const abuse of instance.VideoAbuses) {
823 abuse.deletedVideo = details
824 tasks.push(abuse.save({ transaction: options.transaction }))
827 await Promise.all(tasks)
830 static listLocalIds (): Promise<number[]> {
832 attributes: [ 'id' ],
839 return VideoModel.findAll(query)
840 .then(rows => rows.map(r => r.id))
843 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
844 function getRawQuery (select: string) {
845 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
846 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
847 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
848 'WHERE "Account"."actorId" = ' + actorId
849 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
850 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
851 'WHERE "VideoShare"."actorId" = ' + actorId
853 return `(${queryVideo}) UNION (${queryVideoShare})`
856 const rawQuery = getRawQuery('"Video"."id"')
857 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
863 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
866 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
868 [Op.or]: getPrivaciesForFederation()
872 attributes: [ 'filename', 'language', 'fileUrl' ],
873 model: VideoCaptionModel.unscoped(),
877 attributes: [ 'id', 'url' ],
878 model: VideoShareModel.unscoped(),
880 // We only want videos shared by this actor
895 attributes: [ 'id', 'url' ],
896 model: ActorModel.unscoped()
901 model: VideoChannelModel.unscoped(),
905 attributes: [ 'name' ],
906 model: AccountModel.unscoped(),
910 attributes: [ 'id', 'url', 'followersUrl' ],
911 model: ActorModel.unscoped(),
917 attributes: [ 'id', 'url', 'followersUrl' ],
918 model: ActorModel.unscoped(),
924 model: VideoStreamingPlaylistModel.unscoped(),
928 model: VideoFileModel,
933 VideoLiveModel.unscoped(),
939 return Bluebird.all([
940 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
941 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
942 ]).then(([ rows, totals ]) => {
943 // totals: totalVideos + totalVideoShares
945 let totalVideoShares = 0
946 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
947 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
949 const total = totalVideos + totalVideoShares
957 static async listPublishedLiveUUIDs () {
959 attributes: [ 'uuid' ],
963 state: VideoState.PUBLISHED
967 const result = await VideoModel.findAll(options)
969 return result.map(v => v.uuid)
972 static listUserVideosForApi (options: {
982 const { accountId, channelId, start, count, sort, search, isLive } = options
984 function buildBaseQuery (forCount: boolean): FindOptions {
985 const where: WhereOptions = {}
989 [Op.iLike]: '%' + search + '%'
993 if (exists(isLive)) {
994 where.isLive = isLive
997 const channelWhere = channelId
1005 order: getVideoSort(sort),
1008 model: VideoChannelModel,
1010 where: channelWhere,
1014 ? AccountModel.unscoped()
1029 const countQuery = buildBaseQuery(true)
1030 const findQuery = buildBaseQuery(false)
1032 const findScopes: (string | ScopeOptions)[] = [
1033 ScopeNames.WITH_SCHEDULED_UPDATE,
1034 ScopeNames.WITH_BLACKLISTED,
1035 ScopeNames.WITH_THUMBNAILS
1038 return Promise.all([
1039 VideoModel.count(countQuery),
1040 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1041 ]).then(([ count, rows ]) => {
1049 static async listForApi (options: {
1057 include?: VideoInclude
1059 hasFiles?: boolean // default false
1060 hasWebtorrentFiles?: boolean
1061 hasHLSFiles?: boolean
1063 categoryOneOf?: number[]
1064 licenceOneOf?: number[]
1065 languageOneOf?: string[]
1066 tagsOneOf?: string[]
1067 tagsAllOf?: string[]
1068 privacyOneOf?: VideoPrivacy[]
1071 videoChannelId?: number
1073 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1075 videoPlaylistId?: number
1077 trendingDays?: number
1079 user?: MUserAccountId
1080 historyOfUser?: MUserId
1082 countVideos?: boolean
1086 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1087 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1089 const trendingDays = options.sort.endsWith('trending')
1090 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1093 let trendingAlgorithm: string
1094 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1095 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1097 const serverActor = await getServerActor()
1099 const queryOptions = {
1114 'displayOnlyForFollower',
1122 'hasWebtorrentFiles',
1126 serverAccountIdForBlock: serverActor.Account.id,
1131 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1134 static async searchAndPopulateAccountAndServer (options: {
1142 include?: VideoInclude
1144 categoryOneOf?: number[]
1145 licenceOneOf?: number[]
1146 languageOneOf?: string[]
1147 tagsOneOf?: string[]
1148 tagsAllOf?: string[]
1149 privacyOneOf?: VideoPrivacy[]
1151 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1153 user?: MUserAccountId
1155 hasWebtorrentFiles?: boolean
1156 hasHLSFiles?: boolean
1161 startDate?: string // ISO 8601
1162 endDate?: string // ISO 8601
1163 originallyPublishedStartDate?: string
1164 originallyPublishedEndDate?: string
1166 durationMin?: number // seconds
1167 durationMax?: number // seconds
1170 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1171 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1173 const serverActor = await getServerActor()
1175 const queryOptions = {
1194 'originallyPublishedStartDate',
1195 'originallyPublishedEndDate',
1199 'hasWebtorrentFiles',
1202 'displayOnlyForFollower'
1204 serverAccountIdForBlock: serverActor.Account.id
1207 return VideoModel.getAvailableForApi(queryOptions)
1210 static countLocalLives () {
1216 [Op.ne]: VideoState.LIVE_ENDED
1221 return VideoModel.count(options)
1224 static countVideosUploadedByUserSince (userId: number, since: Date) {
1228 model: VideoChannelModel.unscoped(),
1232 model: AccountModel.unscoped(),
1236 model: UserModel.unscoped(),
1254 return VideoModel.unscoped().count(options)
1257 static countLivesOfAccount (accountId: number) {
1263 [Op.ne]: VideoState.LIVE_ENDED
1269 model: VideoChannelModel.unscoped(),
1277 return VideoModel.count(options)
1280 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1281 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1283 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1286 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1287 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1289 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1292 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1295 where: buildWhereIdOrUUID(id),
1299 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1302 return ModelCache.Instance.doCache({
1303 cacheType: 'load-video-immutable-id',
1310 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1312 const query: FindOptions = {
1319 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1322 return ModelCache.Instance.doCache({
1323 cacheType: 'load-video-immutable-url',
1330 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1331 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1333 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1336 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1337 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1339 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1342 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1343 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1345 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1348 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1349 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1351 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1354 static loadFull (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1355 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1357 return queryBuilder.queryVideo({ id, transaction: t, type: 'full', userId })
1360 static loadForGetAPI (parameters: {
1362 transaction?: Transaction
1364 }): Promise<MVideoDetails> {
1365 const { id, transaction, userId } = parameters
1366 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1368 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1371 static async getStats () {
1372 const serverActor = await getServerActor()
1374 let totalLocalVideoViews = await VideoModel.sum('views', {
1380 // Sequelize could return null...
1381 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1383 const baseOptions = {
1386 sort: '-publishedAt',
1388 displayOnlyForFollower: {
1389 actorId: serverActor.id,
1394 const { total: totalLocalVideos } = await VideoModel.listForApi({
1400 const { total: totalVideos } = await VideoModel.listForApi(baseOptions)
1404 totalLocalVideoViews,
1409 static incrementViews (id: number, views: number) {
1410 return VideoModel.increment('views', {
1418 static updateRatesOf (videoId: number, type: VideoRateType, count: number, t: Transaction) {
1419 const field = type === 'like'
1423 const rawQuery = `UPDATE "video" SET "${field}" = :count WHERE "video"."id" = :videoId`
1425 return AccountVideoRateModel.sequelize.query(rawQuery, {
1427 replacements: { videoId, rateType: type, count },
1428 type: QueryTypes.UPDATE
1432 static syncLocalRates (videoId: number, type: VideoRateType, t: Transaction) {
1433 const field = type === 'like'
1437 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1439 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1441 'WHERE "video"."id" = :videoId'
1443 return AccountVideoRateModel.sequelize.query(rawQuery, {
1445 replacements: { videoId, rateType: type },
1446 type: QueryTypes.UPDATE
1450 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1451 // Instances only share videos
1452 const query = 'SELECT 1 FROM "videoShare" ' +
1453 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1454 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1458 type: QueryTypes.SELECT as QueryTypes.SELECT,
1459 bind: { followerActorId, videoId },
1463 return VideoModel.sequelize.query(query, options)
1464 .then(results => results.length === 1)
1467 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1470 channelId: ofChannel.id
1475 return VideoModel.update({ support: ofChannel.support }, options)
1478 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1480 attributes: [ 'id' ],
1482 channelId: videoChannel.id
1486 return VideoModel.findAll(query)
1487 .then(videos => videos.map(v => v.id))
1490 // threshold corresponds to how many video the field should have to be returned
1491 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1492 const serverActor = await getServerActor()
1494 const queryOptions: BuildVideosListQueryOptions = {
1495 attributes: [ `"${field}"` ],
1496 group: `GROUP BY "${field}"`,
1497 having: `HAVING COUNT("${field}") >= ${threshold}`,
1501 serverAccountIdForBlock: serverActor.Account.id,
1502 displayOnlyForFollower: {
1503 actorId: serverActor.id,
1508 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1510 return queryBuilder.queryVideoIds(queryOptions)
1511 .then(rows => rows.map(r => r[field]))
1514 static buildTrendingQuery (trendingDays: number) {
1518 model: VideoViewModel,
1523 [Op.gte as any]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1529 private static async getAvailableForApi (
1530 options: BuildVideosListQueryOptions,
1532 ): Promise<ResultList<VideoModel>> {
1533 function getCount () {
1534 if (countVideos !== true) return Promise.resolve(undefined)
1536 const countOptions = Object.assign({}, options, { isCount: true })
1537 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1539 return queryBuilder.countVideoIds(countOptions)
1542 function getModels () {
1543 if (options.count === 0) return Promise.resolve([])
1545 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1547 return queryBuilder.queryVideos(options)
1550 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1558 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1559 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1560 throw new Error('Try to filter all-local but user cannot see all videos')
1564 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1565 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1566 throw new Error('Try to choose video privacies but user cannot see all videos')
1570 private static isPrivateInclude (include: VideoInclude) {
1571 return include & VideoInclude.BLACKLISTED ||
1572 include & VideoInclude.BLOCKED_OWNER ||
1573 include & VideoInclude.NOT_PUBLISHED_STATE
1577 return !!this.VideoBlacklist
1581 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1584 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1585 // We first transcode to WebTorrent format, so try this array first
1586 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1587 const file = fun(this.VideoFiles, file => file.resolution)
1589 return Object.assign(file, { Video: this })
1592 // No webtorrent files, try with streaming playlist files
1593 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1594 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1596 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1597 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1603 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1604 return this.getQualityFileBy(maxBy)
1607 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1608 return this.getQualityFileBy(minBy)
1611 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1612 if (Array.isArray(this.VideoFiles) === false) return undefined
1614 const file = this.VideoFiles.find(f => f.resolution === resolution)
1615 if (!file) return undefined
1617 return Object.assign(file, { Video: this })
1620 hasWebTorrentFiles () {
1621 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1624 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1625 thumbnail.videoId = this.id
1627 const savedThumbnail = await thumbnail.save({ transaction })
1629 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1631 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1632 this.Thumbnails.push(savedThumbnail)
1636 if (Array.isArray(this.Thumbnails) === false) return undefined
1638 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1642 return !!this.getPreview()
1646 if (Array.isArray(this.Thumbnails) === false) return undefined
1648 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1652 return this.remote === false
1655 getWatchStaticPath () {
1656 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1659 getEmbedStaticPath () {
1660 return buildVideoEmbedPath(this)
1663 getMiniatureStaticPath () {
1664 const thumbnail = this.getMiniature()
1665 if (!thumbnail) return null
1667 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1670 getPreviewStaticPath () {
1671 const preview = this.getPreview()
1672 if (!preview) return null
1674 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1675 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1678 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1679 return videoModelToFormattedJSON(this, options)
1682 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1683 return videoModelToFormattedDetailsJSON(this)
1686 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1687 let files: VideoFile[] = []
1689 if (Array.isArray(this.VideoFiles)) {
1690 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1691 files = files.concat(result)
1694 for (const p of (this.VideoStreamingPlaylists || [])) {
1695 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1696 files = files.concat(result)
1702 toActivityPubObject (this: MVideoAP): VideoObject {
1703 return videoModelToActivityPubObject(this)
1706 getTruncatedDescription () {
1707 if (!this.description) return null
1709 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1710 return peertubeTruncate(this.description, { length: maxLength })
1714 let files: MVideoFile[] = []
1716 if (Array.isArray(this.VideoFiles)) {
1717 files = files.concat(this.VideoFiles)
1720 if (Array.isArray(this.VideoStreamingPlaylists)) {
1721 for (const p of this.VideoStreamingPlaylists) {
1722 if (Array.isArray(p.VideoFiles)) {
1723 files = files.concat(p.VideoFiles)
1731 probeMaxQualityFile () {
1732 const file = this.getMaxQualityFile()
1733 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1735 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), async originalFilePath => {
1736 const probe = await ffprobePromise(originalFilePath)
1738 const { audioStream } = await getAudioStream(originalFilePath, probe)
1743 ...await getVideoStreamDimensionsInfo(originalFilePath, probe)
1748 getDescriptionAPIPath () {
1749 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1752 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1753 if (!this.VideoStreamingPlaylists) return undefined
1755 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1756 if (!playlist) return undefined
1758 playlist.Video = this
1763 setHLSPlaylist (playlist: MStreamingPlaylist) {
1764 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1766 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1767 this.VideoStreamingPlaylists = toAdd
1771 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1772 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1776 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1777 const filePath = isRedundancy
1778 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1779 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1781 const promises: Promise<any>[] = [ remove(filePath) ]
1782 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1784 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1785 promises.push(removeWebTorrentObjectStorage(videoFile))
1788 return Promise.all(promises)
1791 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1792 const directoryPath = isRedundancy
1793 ? getHLSRedundancyDirectory(this)
1794 : getHLSDirectory(this)
1796 await remove(directoryPath)
1798 if (isRedundancy !== true) {
1799 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1800 streamingPlaylistWithFiles.Video = this
1802 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1803 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1806 // Remove physical files and torrents
1808 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1811 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1812 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1818 if (this.isOwned()) return false
1820 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1823 hasPrivacyForFederation () {
1824 return isPrivacyForFederation(this.privacy)
1827 hasStateForFederation () {
1828 return isStateForFederation(this.state)
1831 isNewVideo (newPrivacy: VideoPrivacy) {
1832 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1835 setAsRefreshed (transaction?: Transaction) {
1836 return setAsUpdated('video', this.id, transaction)
1840 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1843 setPrivacy (newPrivacy: VideoPrivacy) {
1844 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1845 this.publishedAt = new Date()
1848 this.privacy = newPrivacy
1852 return this.privacy === VideoPrivacy.PRIVATE ||
1853 this.privacy === VideoPrivacy.UNLISTED ||
1854 this.privacy === VideoPrivacy.INTERNAL
1857 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1858 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1860 this.state = newState
1862 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1863 this.publishedAt = new Date()
1866 await this.save({ transaction })
1869 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1870 return Math.ceil((videoFile.size * 8) / this.duration)
1874 if (this.isOwned()) {
1876 WEBSERVER.URL + '/tracker/announce',
1877 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1881 return this.Trackers.map(t => t.url)