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 { 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 { getVideoFileResolution } from '../../helpers/ffprobe-utils'
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'
110 videoFilesModelToFormattedJSON,
111 VideoFormattingJSONOptions,
112 videoModelToActivityPubObject,
113 videoModelToFormattedDetailsJSON,
114 videoModelToFormattedJSON
115 } from './formatter/video-format-utils'
116 import { ScheduleVideoUpdateModel } from './schedule-video-update'
117 import { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
118 import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
119 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
120 import { TagModel } from './tag'
121 import { ThumbnailModel } from './thumbnail'
122 import { VideoBlacklistModel } from './video-blacklist'
123 import { VideoCaptionModel } from './video-caption'
124 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
125 import { VideoCommentModel } from './video-comment'
126 import { VideoFileModel } from './video-file'
127 import { VideoImportModel } from './video-import'
128 import { VideoJobInfoModel } from './video-job-info'
129 import { VideoLiveModel } from './video-live'
130 import { VideoPlaylistElementModel } from './video-playlist-element'
131 import { VideoShareModel } from './video-share'
132 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
133 import { VideoTagModel } from './video-tag'
134 import { VideoViewModel } from './video-view'
136 export enum ScopeNames {
138 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
139 WITH_TAGS = 'WITH_TAGS',
140 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
141 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
142 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
143 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
144 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
145 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
146 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
149 export type ForAPIOptions = {
152 videoPlaylistId?: number
154 withAccountBlockerIds?: number[]
158 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
159 attributes: [ 'id', 'url', 'uuid', 'remote' ]
161 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
162 const include: Includeable[] = [
164 model: VideoChannelModel.scope({
166 VideoChannelScopeNames.SUMMARY, {
168 withAccountBlockerIds: options.withAccountBlockerIds
175 attributes: [ 'type', 'filename' ],
176 model: ThumbnailModel,
181 const query: FindOptions = {}
191 if (options.videoPlaylistId) {
193 model: VideoPlaylistElementModel.unscoped(),
196 videoPlaylistId: options.videoPlaylistId
201 query.include = include
205 [ScopeNames.WITH_THUMBNAILS]: {
208 model: ThumbnailModel,
213 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
216 model: VideoChannelModel.unscoped(),
221 exclude: [ 'privateKey', 'publicKey' ]
223 model: ActorModel.unscoped(),
227 attributes: [ 'host' ],
228 model: ServerModel.unscoped(),
232 model: ActorImageModel.unscoped(),
239 model: AccountModel.unscoped(),
243 model: ActorModel.unscoped(),
245 exclude: [ 'privateKey', 'publicKey' ]
250 attributes: [ 'host' ],
251 model: ServerModel.unscoped(),
255 model: ActorImageModel.unscoped(),
267 [ScopeNames.WITH_TAGS]: {
268 include: [ TagModel ]
270 [ScopeNames.WITH_BLACKLISTED]: {
273 attributes: [ 'id', 'reason', 'unfederated' ],
274 model: VideoBlacklistModel,
279 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
280 let subInclude: any[] = []
282 if (withRedundancies === true) {
285 attributes: [ 'fileUrl' ],
286 model: VideoRedundancyModel.unscoped(),
295 model: VideoFileModel,
303 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
304 const subInclude: IncludeOptions[] = [
306 model: VideoFileModel,
311 if (withRedundancies === true) {
313 attributes: [ 'fileUrl' ],
314 model: VideoRedundancyModel.unscoped(),
322 model: VideoStreamingPlaylistModel.unscoped(),
330 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
333 model: ScheduleVideoUpdateModel.unscoped(),
338 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
342 attributes: [ 'currentTime' ],
343 model: UserVideoHistoryModel.unscoped(),
356 buildTrigramSearchIndex('video_name_trigram', 'name'),
358 { fields: [ 'createdAt' ] },
361 { name: 'publishedAt', order: 'DESC' },
362 { name: 'id', order: 'ASC' }
365 { fields: [ 'duration' ] },
368 { name: 'views', order: 'DESC' },
369 { name: 'id', order: 'ASC' }
372 { fields: [ 'channelId' ] },
374 fields: [ 'originallyPublishedAt' ],
376 originallyPublishedAt: {
382 fields: [ 'category' ], // We don't care videos with an unknown category
390 fields: [ 'licence' ], // We don't care videos with an unknown licence
398 fields: [ 'language' ], // We don't care videos with an unknown language
406 fields: [ 'nsfw' ], // Most of the videos are not NSFW
412 fields: [ 'remote' ], // Only index local videos
427 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
430 @Default(DataType.UUIDV4)
432 @Column(DataType.UUID)
436 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
452 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
456 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
458 privacy: VideoPrivacy
461 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
467 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
468 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
473 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
474 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
478 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
513 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
514 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
519 commentsEnabled: boolean
523 downloadEnabled: boolean
527 waitTranscoding: boolean
531 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
542 @Default(DataType.NOW)
549 originallyPublishedAt: Date
551 @ForeignKey(() => VideoChannelModel)
555 @BelongsTo(() => VideoChannelModel, {
561 VideoChannel: VideoChannelModel
563 @BelongsToMany(() => TagModel, {
564 foreignKey: 'videoId',
565 through: () => VideoTagModel,
570 @BelongsToMany(() => TrackerModel, {
571 foreignKey: 'videoId',
572 through: () => VideoTrackerModel,
575 Trackers: TrackerModel[]
577 @HasMany(() => ThumbnailModel, {
585 Thumbnails: ThumbnailModel[]
587 @HasMany(() => VideoPlaylistElementModel, {
594 VideoPlaylistElements: VideoPlaylistElementModel[]
596 @HasMany(() => VideoAbuseModel, {
603 VideoAbuses: VideoAbuseModel[]
605 @HasMany(() => VideoFileModel, {
613 VideoFiles: VideoFileModel[]
615 @HasMany(() => VideoStreamingPlaylistModel, {
623 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
625 @HasMany(() => VideoShareModel, {
632 VideoShares: VideoShareModel[]
634 @HasMany(() => AccountVideoRateModel, {
641 AccountVideoRates: AccountVideoRateModel[]
643 @HasMany(() => VideoCommentModel, {
651 VideoComments: VideoCommentModel[]
653 @HasMany(() => VideoViewModel, {
660 VideoViews: VideoViewModel[]
662 @HasMany(() => UserVideoHistoryModel, {
669 UserVideoHistories: UserVideoHistoryModel[]
671 @HasOne(() => ScheduleVideoUpdateModel, {
678 ScheduleVideoUpdate: ScheduleVideoUpdateModel
680 @HasOne(() => VideoBlacklistModel, {
687 VideoBlacklist: VideoBlacklistModel
689 @HasOne(() => VideoLiveModel, {
696 VideoLive: VideoLiveModel
698 @HasOne(() => VideoImportModel, {
705 VideoImport: VideoImportModel
707 @HasMany(() => VideoCaptionModel, {
714 ['separate' as any]: true
716 VideoCaptions: VideoCaptionModel[]
718 @HasOne(() => VideoJobInfoModel, {
725 VideoJobInfo: VideoJobInfoModel
728 static async sendDelete (instance: MVideoAccountLight, options) {
729 if (!instance.isOwned()) return undefined
731 // Lazy load channels
732 if (!instance.VideoChannel) {
733 instance.VideoChannel = await instance.$get('VideoChannel', {
738 transaction: options.transaction
739 }) as MChannelAccountDefault
742 return sendDeleteVideo(instance, options.transaction)
746 static async removeFiles (instance: VideoModel, options) {
747 const tasks: Promise<any>[] = []
749 logger.info('Removing files of video %s.', instance.url)
751 if (instance.isOwned()) {
752 if (!Array.isArray(instance.VideoFiles)) {
753 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
756 // Remove physical files and torrents
757 instance.VideoFiles.forEach(file => {
758 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
761 // Remove playlists file
762 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
763 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
766 for (const p of instance.VideoStreamingPlaylists) {
767 tasks.push(instance.removeStreamingPlaylistFiles(p))
771 // Do not wait video deletion because we could be in a transaction
774 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
781 static stopLiveIfNeeded (instance: VideoModel) {
782 if (!instance.isLive) return
784 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
786 LiveManager.Instance.stopSessionOf(instance.id)
790 static invalidateCache (instance: VideoModel) {
791 ModelCache.Instance.invalidateCache('video', instance.id)
795 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
796 const tasks: Promise<any>[] = []
798 if (!Array.isArray(instance.VideoAbuses)) {
799 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
801 if (instance.VideoAbuses.length === 0) return undefined
804 logger.info('Saving video abuses details of video %s.', instance.url)
806 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
807 const details = instance.toFormattedDetailsJSON()
809 for (const abuse of instance.VideoAbuses) {
810 abuse.deletedVideo = details
811 tasks.push(abuse.save({ transaction: options.transaction }))
814 await Promise.all(tasks)
817 static listLocalIds (): Promise<number[]> {
819 attributes: [ 'id' ],
826 return VideoModel.findAll(query)
827 .then(rows => rows.map(r => r.id))
830 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
831 function getRawQuery (select: string) {
832 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
833 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
834 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
835 'WHERE "Account"."actorId" = ' + actorId
836 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
837 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
838 'WHERE "VideoShare"."actorId" = ' + actorId
840 return `(${queryVideo}) UNION (${queryVideoShare})`
843 const rawQuery = getRawQuery('"Video"."id"')
844 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
850 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
853 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
855 [Op.or]: getPrivaciesForFederation()
859 attributes: [ 'filename', 'language', 'fileUrl' ],
860 model: VideoCaptionModel.unscoped(),
864 attributes: [ 'id', 'url' ],
865 model: VideoShareModel.unscoped(),
867 // We only want videos shared by this actor
882 attributes: [ 'id', 'url' ],
883 model: ActorModel.unscoped()
888 model: VideoChannelModel.unscoped(),
892 attributes: [ 'name' ],
893 model: AccountModel.unscoped(),
897 attributes: [ 'id', 'url', 'followersUrl' ],
898 model: ActorModel.unscoped(),
904 attributes: [ 'id', 'url', 'followersUrl' ],
905 model: ActorModel.unscoped(),
911 model: VideoStreamingPlaylistModel.unscoped(),
915 model: VideoFileModel,
920 VideoLiveModel.unscoped(),
926 return Bluebird.all([
927 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
928 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
929 ]).then(([ rows, totals ]) => {
930 // totals: totalVideos + totalVideoShares
932 let totalVideoShares = 0
933 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
934 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
936 const total = totalVideos + totalVideoShares
944 static async listPublishedLiveUUIDs () {
946 attributes: [ 'uuid' ],
950 state: VideoState.PUBLISHED
954 const result = await VideoModel.findAll(options)
956 return result.map(v => v.uuid)
959 static listUserVideosForApi (options: {
969 const { accountId, channelId, start, count, sort, search, isLive } = options
971 function buildBaseQuery (): FindOptions {
972 const where: WhereOptions = {}
976 [Op.iLike]: '%' + search + '%'
980 if (exists(isLive)) {
981 where.isLive = isLive
984 const channelWhere = channelId
992 order: getVideoSort(sort),
995 model: VideoChannelModel,
1000 model: AccountModel,
1014 const countQuery = buildBaseQuery()
1015 const findQuery = buildBaseQuery()
1017 const findScopes: (string | ScopeOptions)[] = [
1018 ScopeNames.WITH_SCHEDULED_UPDATE,
1019 ScopeNames.WITH_BLACKLISTED,
1020 ScopeNames.WITH_THUMBNAILS
1023 return Promise.all([
1024 VideoModel.count(countQuery),
1025 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1026 ]).then(([ count, rows ]) => {
1034 static async listForApi (options: {
1042 include?: VideoInclude
1044 hasFiles?: boolean // default false
1045 hasWebtorrentFiles?: boolean
1046 hasHLSFiles?: boolean
1048 categoryOneOf?: number[]
1049 licenceOneOf?: number[]
1050 languageOneOf?: string[]
1051 tagsOneOf?: string[]
1052 tagsAllOf?: string[]
1053 privacyOneOf?: VideoPrivacy[]
1056 videoChannelId?: number
1058 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1060 videoPlaylistId?: number
1062 trendingDays?: number
1064 user?: MUserAccountId
1065 historyOfUser?: MUserId
1067 countVideos?: boolean
1071 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1072 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1074 const trendingDays = options.sort.endsWith('trending')
1075 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1078 let trendingAlgorithm: string
1079 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1080 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1082 const serverActor = await getServerActor()
1084 const queryOptions = {
1099 'displayOnlyForFollower',
1107 'hasWebtorrentFiles',
1111 serverAccountIdForBlock: serverActor.Account.id,
1116 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1119 static async searchAndPopulateAccountAndServer (options: {
1127 include?: VideoInclude
1129 categoryOneOf?: number[]
1130 licenceOneOf?: number[]
1131 languageOneOf?: string[]
1132 tagsOneOf?: string[]
1133 tagsAllOf?: string[]
1134 privacyOneOf?: VideoPrivacy[]
1136 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1138 user?: MUserAccountId
1140 hasWebtorrentFiles?: boolean
1141 hasHLSFiles?: boolean
1146 startDate?: string // ISO 8601
1147 endDate?: string // ISO 8601
1148 originallyPublishedStartDate?: string
1149 originallyPublishedEndDate?: string
1151 durationMin?: number // seconds
1152 durationMax?: number // seconds
1155 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1156 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1158 const serverActor = await getServerActor()
1160 const queryOptions = {
1179 'originallyPublishedStartDate',
1180 'originallyPublishedEndDate',
1184 'hasWebtorrentFiles',
1187 'displayOnlyForFollower'
1189 serverAccountIdForBlock: serverActor.Account.id
1192 return VideoModel.getAvailableForApi(queryOptions)
1195 static countLocalLives () {
1201 [Op.ne]: VideoState.LIVE_ENDED
1206 return VideoModel.count(options)
1209 static countVideosUploadedByUserSince (userId: number, since: Date) {
1213 model: VideoChannelModel.unscoped(),
1217 model: AccountModel.unscoped(),
1221 model: UserModel.unscoped(),
1239 return VideoModel.unscoped().count(options)
1242 static countLivesOfAccount (accountId: number) {
1248 [Op.ne]: VideoState.LIVE_ENDED
1254 model: VideoChannelModel.unscoped(),
1262 return VideoModel.count(options)
1265 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1266 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1268 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1271 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1272 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1274 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1277 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1280 where: buildWhereIdOrUUID(id),
1284 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1287 return ModelCache.Instance.doCache({
1288 cacheType: 'load-video-immutable-id',
1295 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1297 const query: FindOptions = {
1304 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1307 return ModelCache.Instance.doCache({
1308 cacheType: 'load-video-immutable-url',
1315 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1316 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1318 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1321 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1322 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1324 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1327 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1328 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1330 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1333 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1334 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1336 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1339 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1340 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1342 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1345 static loadForGetAPI (parameters: {
1347 transaction?: Transaction
1349 }): Promise<MVideoDetails> {
1350 const { id, transaction, userId } = parameters
1351 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1353 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1356 static async getStats () {
1357 const totalLocalVideos = await VideoModel.count({
1363 let totalLocalVideoViews = await VideoModel.sum('views', {
1369 // Sequelize could return null...
1370 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1372 const serverActor = await getServerActor()
1374 const { total: totalVideos } = await VideoModel.listForApi({
1377 sort: '-publishedAt',
1378 nsfw: buildNSFWFilter(),
1379 displayOnlyForFollower: {
1380 actorId: serverActor.id,
1387 totalLocalVideoViews,
1392 static incrementViews (id: number, views: number) {
1393 return VideoModel.increment('views', {
1401 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1402 const field = type === 'like'
1406 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1408 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1410 'WHERE "video"."id" = :videoId'
1412 return AccountVideoRateModel.sequelize.query(rawQuery, {
1414 replacements: { videoId, rateType: type },
1415 type: QueryTypes.UPDATE
1419 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1420 // Instances only share videos
1421 const query = 'SELECT 1 FROM "videoShare" ' +
1422 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1423 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1427 type: QueryTypes.SELECT as QueryTypes.SELECT,
1428 bind: { followerActorId, videoId },
1432 return VideoModel.sequelize.query(query, options)
1433 .then(results => results.length === 1)
1436 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1439 channelId: ofChannel.id
1444 return VideoModel.update({ support: ofChannel.support }, options)
1447 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1449 attributes: [ 'id' ],
1451 channelId: videoChannel.id
1455 return VideoModel.findAll(query)
1456 .then(videos => videos.map(v => v.id))
1459 // threshold corresponds to how many video the field should have to be returned
1460 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1461 const serverActor = await getServerActor()
1463 const queryOptions: BuildVideosListQueryOptions = {
1464 attributes: [ `"${field}"` ],
1465 group: `GROUP BY "${field}"`,
1466 having: `HAVING COUNT("${field}") >= ${threshold}`,
1470 serverAccountIdForBlock: serverActor.Account.id,
1471 displayOnlyForFollower: {
1472 actorId: serverActor.id,
1477 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1479 return queryBuilder.queryVideoIds(queryOptions)
1480 .then(rows => rows.map(r => r[field]))
1483 static buildTrendingQuery (trendingDays: number) {
1487 model: VideoViewModel,
1491 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1497 private static async getAvailableForApi (
1498 options: BuildVideosListQueryOptions,
1500 ): Promise<ResultList<VideoModel>> {
1501 function getCount () {
1502 if (countVideos !== true) return Promise.resolve(undefined)
1504 const countOptions = Object.assign({}, options, { isCount: true })
1505 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1507 return queryBuilder.countVideoIds(countOptions)
1510 function getModels () {
1511 if (options.count === 0) return Promise.resolve([])
1513 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1515 return queryBuilder.queryVideos(options)
1518 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1526 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1527 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1528 throw new Error('Try to filter all-local but user cannot see all videos')
1532 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1533 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1534 throw new Error('Try to choose video privacies but user cannot see all videos')
1538 private static isPrivateInclude (include: VideoInclude) {
1539 return include & VideoInclude.BLACKLISTED ||
1540 include & VideoInclude.BLOCKED_OWNER ||
1541 include & VideoInclude.NOT_PUBLISHED_STATE
1545 return !!this.VideoBlacklist
1549 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1552 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1553 // We first transcode to WebTorrent format, so try this array first
1554 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1555 const file = fun(this.VideoFiles, file => file.resolution)
1557 return Object.assign(file, { Video: this })
1560 // No webtorrent files, try with streaming playlist files
1561 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1562 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1564 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1565 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1571 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1572 return this.getQualityFileBy(maxBy)
1575 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1576 return this.getQualityFileBy(minBy)
1579 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1580 if (Array.isArray(this.VideoFiles) === false) return undefined
1582 const file = this.VideoFiles.find(f => f.resolution === resolution)
1583 if (!file) return undefined
1585 return Object.assign(file, { Video: this })
1588 hasWebTorrentFiles () {
1589 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1592 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1593 thumbnail.videoId = this.id
1595 const savedThumbnail = await thumbnail.save({ transaction })
1597 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1599 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1600 this.Thumbnails.push(savedThumbnail)
1604 if (Array.isArray(this.Thumbnails) === false) return undefined
1606 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1610 return !!this.getPreview()
1614 if (Array.isArray(this.Thumbnails) === false) return undefined
1616 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1620 return this.remote === false
1623 getWatchStaticPath () {
1624 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1627 getEmbedStaticPath () {
1628 return buildVideoEmbedPath(this)
1631 getMiniatureStaticPath () {
1632 const thumbnail = this.getMiniature()
1633 if (!thumbnail) return null
1635 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1638 getPreviewStaticPath () {
1639 const preview = this.getPreview()
1640 if (!preview) return null
1642 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1643 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1646 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1647 return videoModelToFormattedJSON(this, options)
1650 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1651 return videoModelToFormattedDetailsJSON(this)
1654 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1655 let files: VideoFile[] = []
1657 if (Array.isArray(this.VideoFiles)) {
1658 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1659 files = files.concat(result)
1662 for (const p of (this.VideoStreamingPlaylists || [])) {
1663 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1664 files = files.concat(result)
1670 toActivityPubObject (this: MVideoAP): VideoObject {
1671 return videoModelToActivityPubObject(this)
1674 getTruncatedDescription () {
1675 if (!this.description) return null
1677 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1678 return peertubeTruncate(this.description, { length: maxLength })
1681 getMaxQualityResolution () {
1682 const file = this.getMaxQualityFile()
1683 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1685 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), originalFilePath => {
1686 return getVideoFileResolution(originalFilePath)
1690 getDescriptionAPIPath () {
1691 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1694 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1695 if (!this.VideoStreamingPlaylists) return undefined
1697 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1698 if (!playlist) return undefined
1700 playlist.Video = this
1705 setHLSPlaylist (playlist: MStreamingPlaylist) {
1706 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1708 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1709 this.VideoStreamingPlaylists = toAdd
1713 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1714 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1718 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1719 const filePath = isRedundancy
1720 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1721 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1723 const promises: Promise<any>[] = [ remove(filePath) ]
1724 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1726 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1727 promises.push(removeWebTorrentObjectStorage(videoFile))
1730 return Promise.all(promises)
1733 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1734 const directoryPath = isRedundancy
1735 ? getHLSRedundancyDirectory(this)
1736 : getHLSDirectory(this)
1738 await remove(directoryPath)
1740 if (isRedundancy !== true) {
1741 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1742 streamingPlaylistWithFiles.Video = this
1744 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1745 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1748 // Remove physical files and torrents
1750 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1753 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1754 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1760 if (this.isOwned()) return false
1762 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1765 hasPrivacyForFederation () {
1766 return isPrivacyForFederation(this.privacy)
1769 hasStateForFederation () {
1770 return isStateForFederation(this.state)
1773 isNewVideo (newPrivacy: VideoPrivacy) {
1774 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1777 setAsRefreshed (transaction?: Transaction) {
1778 return setAsUpdated('video', this.id, transaction)
1782 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1785 setPrivacy (newPrivacy: VideoPrivacy) {
1786 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1787 this.publishedAt = new Date()
1790 this.privacy = newPrivacy
1794 return this.privacy === VideoPrivacy.PRIVATE ||
1795 this.privacy === VideoPrivacy.UNLISTED ||
1796 this.privacy === VideoPrivacy.INTERNAL
1799 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1800 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1802 this.state = newState
1804 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1805 this.publishedAt = new Date()
1808 await this.save({ transaction })
1811 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1812 return Math.ceil((videoFile.size * 8) / this.duration)
1816 if (this.isOwned()) {
1818 WEBSERVER.URL + '/tracker/announce',
1819 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1823 return this.Trackers.map(t => t.url)