1 import Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy } from 'lodash'
4 import { join } from 'path'
5 import { FindOptions, Includeable, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
26 } from 'sequelize-typescript'
27 import { buildNSFWFilter } from '@server/helpers/express-utils'
28 import { uuidToShort } from '@shared/core-utils/uuid'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live/live-manager'
31 import { removeHLSObjectStorage, removeWebTorrentObjectStorage } from '@server/lib/object-storage'
32 import { getHLSDirectory, getHLSRedundancyDirectory } from '@server/lib/paths'
33 import { VideoPathManager } from '@server/lib/video-path-manager'
34 import { getServerActor } from '@server/models/application/application'
35 import { ModelCache } from '@server/models/model-cache'
36 import { AttributesOnly, buildVideoEmbedPath, buildVideoWatchPath, pick } from '@shared/core-utils'
37 import { VideoFile, VideoInclude } from '@shared/models'
38 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
39 import { VideoObject } from '../../../shared/models/activitypub/objects'
40 import { Video, VideoDetails, VideoRateType, VideoStorage } from '../../../shared/models/videos'
41 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
42 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
43 import { peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { exists, isBooleanValid } from '../../helpers/custom-validators/misc'
47 isVideoDescriptionValid,
53 } from '../../helpers/custom-validators/videos'
54 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
55 import { logger } from '../../helpers/logger'
56 import { CONFIG } from '../../initializers/config'
57 import { ACTIVITY_PUB, API_VERSION, CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, STATIC_PATHS, WEBSERVER } from '../../initializers/constants'
58 import { sendDeleteVideo } from '../../lib/activitypub/send'
61 MChannelAccountDefault,
64 MStreamingPlaylistFilesVideo,
69 MVideoAccountLightBlacklistAllFiles,
74 MVideoFormattableDetails,
80 MVideoThumbnailBlacklist,
83 } from '../../types/models'
84 import { MThumbnail } from '../../types/models/video/thumbnail'
85 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
86 import { VideoAbuseModel } from '../abuse/video-abuse'
87 import { AccountModel } from '../account/account'
88 import { AccountVideoRateModel } from '../account/account-video-rate'
89 import { ActorModel } from '../actor/actor'
90 import { ActorImageModel } from '../actor/actor-image'
91 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
92 import { ServerModel } from '../server/server'
93 import { TrackerModel } from '../server/tracker'
94 import { VideoTrackerModel } from '../server/video-tracker'
95 import { setAsUpdated } from '../shared'
96 import { UserModel } from '../user/user'
97 import { UserVideoHistoryModel } from '../user/user-video-history'
98 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
100 videoFilesModelToFormattedJSON,
101 VideoFormattingJSONOptions,
102 videoModelToActivityPubObject,
103 videoModelToFormattedDetailsJSON,
104 videoModelToFormattedJSON
105 } from './formatter/video-format-utils'
106 import { ScheduleVideoUpdateModel } from './schedule-video-update'
107 import { VideoModelGetQueryBuilder } from './sql/video-model-get-query-builder'
108 import { BuildVideosListQueryOptions, DisplayOnlyForFollowerOptions, VideosIdListQueryBuilder } from './sql/videos-id-list-query-builder'
109 import { VideosModelListQueryBuilder } from './sql/videos-model-list-query-builder'
110 import { TagModel } from './tag'
111 import { ThumbnailModel } from './thumbnail'
112 import { VideoBlacklistModel } from './video-blacklist'
113 import { VideoCaptionModel } from './video-caption'
114 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
115 import { VideoCommentModel } from './video-comment'
116 import { VideoFileModel } from './video-file'
117 import { VideoImportModel } from './video-import'
118 import { VideoJobInfoModel } from './video-job-info'
119 import { VideoLiveModel } from './video-live'
120 import { VideoPlaylistElementModel } from './video-playlist-element'
121 import { VideoShareModel } from './video-share'
122 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
123 import { VideoTagModel } from './video-tag'
124 import { VideoViewModel } from './video-view'
126 export enum ScopeNames {
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
134 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
135 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
136 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
139 export type ForAPIOptions = {
142 videoPlaylistId?: number
144 withAccountBlockerIds?: number[]
148 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
149 attributes: [ 'id', 'url', 'uuid', 'remote' ]
151 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
152 const include: Includeable[] = [
154 model: VideoChannelModel.scope({
156 VideoChannelScopeNames.SUMMARY, {
158 withAccountBlockerIds: options.withAccountBlockerIds
165 attributes: [ 'type', 'filename' ],
166 model: ThumbnailModel,
171 const query: FindOptions = {}
181 if (options.videoPlaylistId) {
183 model: VideoPlaylistElementModel.unscoped(),
186 videoPlaylistId: options.videoPlaylistId
191 query.include = include
195 [ScopeNames.WITH_THUMBNAILS]: {
198 model: ThumbnailModel,
203 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
206 model: VideoChannelModel.unscoped(),
211 exclude: [ 'privateKey', 'publicKey' ]
213 model: ActorModel.unscoped(),
217 attributes: [ 'host' ],
218 model: ServerModel.unscoped(),
222 model: ActorImageModel.unscoped(),
229 model: AccountModel.unscoped(),
233 model: ActorModel.unscoped(),
235 exclude: [ 'privateKey', 'publicKey' ]
240 attributes: [ 'host' ],
241 model: ServerModel.unscoped(),
245 model: ActorImageModel.unscoped(),
257 [ScopeNames.WITH_TAGS]: {
258 include: [ TagModel ]
260 [ScopeNames.WITH_BLACKLISTED]: {
263 attributes: [ 'id', 'reason', 'unfederated' ],
264 model: VideoBlacklistModel,
269 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
270 let subInclude: any[] = []
272 if (withRedundancies === true) {
275 attributes: [ 'fileUrl' ],
276 model: VideoRedundancyModel.unscoped(),
285 model: VideoFileModel,
293 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
294 const subInclude: IncludeOptions[] = [
296 model: VideoFileModel,
301 if (withRedundancies === true) {
303 attributes: [ 'fileUrl' ],
304 model: VideoRedundancyModel.unscoped(),
312 model: VideoStreamingPlaylistModel.unscoped(),
320 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
323 model: ScheduleVideoUpdateModel.unscoped(),
328 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
332 attributes: [ 'currentTime' ],
333 model: UserVideoHistoryModel.unscoped(),
346 buildTrigramSearchIndex('video_name_trigram', 'name'),
348 { fields: [ 'createdAt' ] },
351 { name: 'publishedAt', order: 'DESC' },
352 { name: 'id', order: 'ASC' }
355 { fields: [ 'duration' ] },
358 { name: 'views', order: 'DESC' },
359 { name: 'id', order: 'ASC' }
362 { fields: [ 'channelId' ] },
364 fields: [ 'originallyPublishedAt' ],
366 originallyPublishedAt: {
372 fields: [ 'category' ], // We don't care videos with an unknown category
380 fields: [ 'licence' ], // We don't care videos with an unknown licence
388 fields: [ 'language' ], // We don't care videos with an unknown language
396 fields: [ 'nsfw' ], // Most of the videos are not NSFW
402 fields: [ 'remote' ], // Only index local videos
417 export class VideoModel extends Model<Partial<AttributesOnly<VideoModel>>> {
420 @Default(DataType.UUIDV4)
422 @Column(DataType.UUID)
426 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
442 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
446 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
448 privacy: VideoPrivacy
451 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
457 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
458 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
463 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
464 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
468 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
503 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
504 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
509 commentsEnabled: boolean
513 downloadEnabled: boolean
517 waitTranscoding: boolean
521 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
532 @Default(DataType.NOW)
539 originallyPublishedAt: Date
541 @ForeignKey(() => VideoChannelModel)
545 @BelongsTo(() => VideoChannelModel, {
551 VideoChannel: VideoChannelModel
553 @BelongsToMany(() => TagModel, {
554 foreignKey: 'videoId',
555 through: () => VideoTagModel,
560 @BelongsToMany(() => TrackerModel, {
561 foreignKey: 'videoId',
562 through: () => VideoTrackerModel,
565 Trackers: TrackerModel[]
567 @HasMany(() => ThumbnailModel, {
575 Thumbnails: ThumbnailModel[]
577 @HasMany(() => VideoPlaylistElementModel, {
584 VideoPlaylistElements: VideoPlaylistElementModel[]
586 @HasMany(() => VideoAbuseModel, {
593 VideoAbuses: VideoAbuseModel[]
595 @HasMany(() => VideoFileModel, {
603 VideoFiles: VideoFileModel[]
605 @HasMany(() => VideoStreamingPlaylistModel, {
613 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
615 @HasMany(() => VideoShareModel, {
622 VideoShares: VideoShareModel[]
624 @HasMany(() => AccountVideoRateModel, {
631 AccountVideoRates: AccountVideoRateModel[]
633 @HasMany(() => VideoCommentModel, {
641 VideoComments: VideoCommentModel[]
643 @HasMany(() => VideoViewModel, {
650 VideoViews: VideoViewModel[]
652 @HasMany(() => UserVideoHistoryModel, {
659 UserVideoHistories: UserVideoHistoryModel[]
661 @HasOne(() => ScheduleVideoUpdateModel, {
668 ScheduleVideoUpdate: ScheduleVideoUpdateModel
670 @HasOne(() => VideoBlacklistModel, {
677 VideoBlacklist: VideoBlacklistModel
679 @HasOne(() => VideoLiveModel, {
686 VideoLive: VideoLiveModel
688 @HasOne(() => VideoImportModel, {
695 VideoImport: VideoImportModel
697 @HasMany(() => VideoCaptionModel, {
704 ['separate' as any]: true
706 VideoCaptions: VideoCaptionModel[]
708 @HasOne(() => VideoJobInfoModel, {
715 VideoJobInfo: VideoJobInfoModel
718 static async sendDelete (instance: MVideoAccountLight, options) {
719 if (!instance.isOwned()) return undefined
721 // Lazy load channels
722 if (!instance.VideoChannel) {
723 instance.VideoChannel = await instance.$get('VideoChannel', {
728 transaction: options.transaction
729 }) as MChannelAccountDefault
732 return sendDeleteVideo(instance, options.transaction)
736 static async removeFiles (instance: VideoModel, options) {
737 const tasks: Promise<any>[] = []
739 logger.info('Removing files of video %s.', instance.url)
741 if (instance.isOwned()) {
742 if (!Array.isArray(instance.VideoFiles)) {
743 instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })
746 // Remove physical files and torrents
747 instance.VideoFiles.forEach(file => {
748 tasks.push(instance.removeWebTorrentFileAndTorrent(file))
751 // Remove playlists file
752 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
753 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists', { transaction: options.transaction })
756 for (const p of instance.VideoStreamingPlaylists) {
757 tasks.push(instance.removeStreamingPlaylistFiles(p))
761 // Do not wait video deletion because we could be in a transaction
764 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
771 static stopLiveIfNeeded (instance: VideoModel) {
772 if (!instance.isLive) return
774 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
776 LiveManager.Instance.stopSessionOf(instance.id)
780 static invalidateCache (instance: VideoModel) {
781 ModelCache.Instance.invalidateCache('video', instance.id)
785 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
786 const tasks: Promise<any>[] = []
788 if (!Array.isArray(instance.VideoAbuses)) {
789 instance.VideoAbuses = await instance.$get('VideoAbuses', { transaction: options.transaction })
791 if (instance.VideoAbuses.length === 0) return undefined
794 logger.info('Saving video abuses details of video %s.', instance.url)
796 if (!instance.Trackers) instance.Trackers = await instance.$get('Trackers', { transaction: options.transaction })
797 const details = instance.toFormattedDetailsJSON()
799 for (const abuse of instance.VideoAbuses) {
800 abuse.deletedVideo = details
801 tasks.push(abuse.save({ transaction: options.transaction }))
804 await Promise.all(tasks)
807 static listLocalIds (): Promise<number[]> {
809 attributes: [ 'id' ],
816 return VideoModel.findAll(query)
817 .then(rows => rows.map(r => r.id))
820 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
821 function getRawQuery (select: string) {
822 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
823 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
824 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
825 'WHERE "Account"."actorId" = ' + actorId
826 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
827 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
828 'WHERE "VideoShare"."actorId" = ' + actorId
830 return `(${queryVideo}) UNION (${queryVideoShare})`
833 const rawQuery = getRawQuery('"Video"."id"')
834 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
840 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ]),
843 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
845 [Op.or]: getPrivaciesForFederation()
849 attributes: [ 'filename', 'language', 'fileUrl' ],
850 model: VideoCaptionModel.unscoped(),
854 attributes: [ 'id', 'url' ],
855 model: VideoShareModel.unscoped(),
857 // We only want videos shared by this actor
872 attributes: [ 'id', 'url' ],
873 model: ActorModel.unscoped()
878 model: VideoChannelModel.unscoped(),
882 attributes: [ 'name' ],
883 model: AccountModel.unscoped(),
887 attributes: [ 'id', 'url', 'followersUrl' ],
888 model: ActorModel.unscoped(),
894 attributes: [ 'id', 'url', 'followersUrl' ],
895 model: ActorModel.unscoped(),
901 model: VideoStreamingPlaylistModel.unscoped(),
905 model: VideoFileModel,
910 VideoLiveModel.unscoped(),
916 return Bluebird.all([
917 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
918 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
919 ]).then(([ rows, totals ]) => {
920 // totals: totalVideos + totalVideoShares
922 let totalVideoShares = 0
923 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
924 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
926 const total = totalVideos + totalVideoShares
934 static async listPublishedLiveUUIDs () {
936 attributes: [ 'uuid' ],
940 state: VideoState.PUBLISHED
944 const result = await VideoModel.findAll(options)
946 return result.map(v => v.uuid)
949 static listUserVideosForApi (options: {
959 const { accountId, channelId, start, count, sort, search, isLive } = options
961 function buildBaseQuery (): FindOptions {
962 const where: WhereOptions = {}
966 [Op.iLike]: '%' + search + '%'
970 if (exists(isLive)) {
971 where.isLive = isLive
974 const channelWhere = channelId
982 order: getVideoSort(sort),
985 model: VideoChannelModel,
1004 const countQuery = buildBaseQuery()
1005 const findQuery = buildBaseQuery()
1007 const findScopes: (string | ScopeOptions)[] = [
1008 ScopeNames.WITH_SCHEDULED_UPDATE,
1009 ScopeNames.WITH_BLACKLISTED,
1010 ScopeNames.WITH_THUMBNAILS
1013 return Promise.all([
1014 VideoModel.count(countQuery),
1015 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1016 ]).then(([ count, rows ]) => {
1024 static async listForApi (options: {
1032 include?: VideoInclude
1034 hasFiles?: boolean // default false
1035 hasWebtorrentFiles?: boolean
1036 hasHLSFiles?: boolean
1038 categoryOneOf?: number[]
1039 licenceOneOf?: number[]
1040 languageOneOf?: string[]
1041 tagsOneOf?: string[]
1042 tagsAllOf?: string[]
1043 privacyOneOf?: VideoPrivacy[]
1046 videoChannelId?: number
1048 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1050 videoPlaylistId?: number
1052 trendingDays?: number
1054 user?: MUserAccountId
1055 historyOfUser?: MUserId
1057 countVideos?: boolean
1061 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1062 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1064 const trendingDays = options.sort.endsWith('trending')
1065 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1068 let trendingAlgorithm: string
1069 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1070 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1072 const serverActor = await getServerActor()
1074 const queryOptions = {
1089 'displayOnlyForFollower',
1097 'hasWebtorrentFiles',
1101 serverAccountIdForBlock: serverActor.Account.id,
1106 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1109 static async searchAndPopulateAccountAndServer (options: {
1117 include?: VideoInclude
1119 categoryOneOf?: number[]
1120 licenceOneOf?: number[]
1121 languageOneOf?: string[]
1122 tagsOneOf?: string[]
1123 tagsAllOf?: string[]
1124 privacyOneOf?: VideoPrivacy[]
1126 displayOnlyForFollower: DisplayOnlyForFollowerOptions | null
1128 user?: MUserAccountId
1130 hasWebtorrentFiles?: boolean
1131 hasHLSFiles?: boolean
1136 startDate?: string // ISO 8601
1137 endDate?: string // ISO 8601
1138 originallyPublishedStartDate?: string
1139 originallyPublishedEndDate?: string
1141 durationMin?: number // seconds
1142 durationMax?: number // seconds
1145 VideoModel.throwIfPrivateIncludeWithoutUser(options.include, options.user)
1146 VideoModel.throwIfPrivacyOneOfWithoutUser(options.privacyOneOf, options.user)
1148 const serverActor = await getServerActor()
1150 const queryOptions = {
1169 'originallyPublishedStartDate',
1170 'originallyPublishedEndDate',
1174 'hasWebtorrentFiles',
1177 'displayOnlyForFollower'
1179 serverAccountIdForBlock: serverActor.Account.id
1182 return VideoModel.getAvailableForApi(queryOptions)
1185 static countLocalLives () {
1191 [Op.ne]: VideoState.LIVE_ENDED
1196 return VideoModel.count(options)
1199 static countVideosUploadedByUserSince (userId: number, since: Date) {
1203 model: VideoChannelModel.unscoped(),
1207 model: AccountModel.unscoped(),
1211 model: UserModel.unscoped(),
1229 return VideoModel.unscoped().count(options)
1232 static countLivesOfAccount (accountId: number) {
1238 [Op.ne]: VideoState.LIVE_ENDED
1244 model: VideoChannelModel.unscoped(),
1252 return VideoModel.count(options)
1255 static load (id: number | string, transaction?: Transaction): Promise<MVideoThumbnail> {
1256 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1258 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails' })
1261 static loadWithBlacklist (id: number | string, transaction?: Transaction): Promise<MVideoThumbnailBlacklist> {
1262 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1264 return queryBuilder.queryVideo({ id, transaction, type: 'thumbnails-blacklist' })
1267 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1270 where: buildWhereIdOrUUID(id),
1274 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1277 return ModelCache.Instance.doCache({
1278 cacheType: 'load-video-immutable-id',
1285 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1287 const query: FindOptions = {
1294 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1297 return ModelCache.Instance.doCache({
1298 cacheType: 'load-video-immutable-url',
1305 static loadOnlyId (id: number | string, transaction?: Transaction): Promise<MVideoId> {
1306 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1308 return queryBuilder.queryVideo({ id, transaction, type: 'id' })
1311 static loadWithFiles (id: number | string, transaction?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1312 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1314 return queryBuilder.queryVideo({ id, transaction, type: 'all-files', logging })
1317 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1318 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1320 return queryBuilder.queryVideo({ url, transaction, type: 'thumbnails' })
1323 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1324 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1326 return queryBuilder.queryVideo({ url, transaction, type: 'account-blacklist-files' })
1329 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1330 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1332 return queryBuilder.queryVideo({ id, transaction: t, type: 'full-light', userId })
1335 static loadForGetAPI (parameters: {
1337 transaction?: Transaction
1339 }): Promise<MVideoDetails> {
1340 const { id, transaction, userId } = parameters
1341 const queryBuilder = new VideoModelGetQueryBuilder(VideoModel.sequelize)
1343 return queryBuilder.queryVideo({ id, transaction, type: 'api', userId })
1346 static async getStats () {
1347 const totalLocalVideos = await VideoModel.count({
1353 let totalLocalVideoViews = await VideoModel.sum('views', {
1359 // Sequelize could return null...
1360 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1362 const serverActor = await getServerActor()
1364 const { total: totalVideos } = await VideoModel.listForApi({
1367 sort: '-publishedAt',
1368 nsfw: buildNSFWFilter(),
1369 displayOnlyForFollower: {
1370 actorId: serverActor.id,
1377 totalLocalVideoViews,
1382 static incrementViews (id: number, views: number) {
1383 return VideoModel.increment('views', {
1391 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1392 const field = type === 'like'
1396 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1398 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1400 'WHERE "video"."id" = :videoId'
1402 return AccountVideoRateModel.sequelize.query(rawQuery, {
1404 replacements: { videoId, rateType: type },
1405 type: QueryTypes.UPDATE
1409 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1410 // Instances only share videos
1411 const query = 'SELECT 1 FROM "videoShare" ' +
1412 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1413 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1417 type: QueryTypes.SELECT as QueryTypes.SELECT,
1418 bind: { followerActorId, videoId },
1422 return VideoModel.sequelize.query(query, options)
1423 .then(results => results.length === 1)
1426 static bulkUpdateSupportField (ofChannel: MChannel, t: Transaction) {
1429 channelId: ofChannel.id
1434 return VideoModel.update({ support: ofChannel.support }, options)
1437 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1439 attributes: [ 'id' ],
1441 channelId: videoChannel.id
1445 return VideoModel.findAll(query)
1446 .then(videos => videos.map(v => v.id))
1449 // threshold corresponds to how many video the field should have to be returned
1450 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1451 const serverActor = await getServerActor()
1453 const queryOptions: BuildVideosListQueryOptions = {
1454 attributes: [ `"${field}"` ],
1455 group: `GROUP BY "${field}"`,
1456 having: `HAVING COUNT("${field}") >= ${threshold}`,
1460 serverAccountIdForBlock: serverActor.Account.id,
1461 displayOnlyForFollower: {
1462 actorId: serverActor.id,
1467 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1469 return queryBuilder.queryVideoIds(queryOptions)
1470 .then(rows => rows.map(r => r[field]))
1473 static buildTrendingQuery (trendingDays: number) {
1477 model: VideoViewModel,
1481 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1487 private static async getAvailableForApi (
1488 options: BuildVideosListQueryOptions,
1490 ): Promise<ResultList<VideoModel>> {
1491 function getCount () {
1492 if (countVideos !== true) return Promise.resolve(undefined)
1494 const countOptions = Object.assign({}, options, { isCount: true })
1495 const queryBuilder = new VideosIdListQueryBuilder(VideoModel.sequelize)
1497 return queryBuilder.countVideoIds(countOptions)
1500 function getModels () {
1501 if (options.count === 0) return Promise.resolve([])
1503 const queryBuilder = new VideosModelListQueryBuilder(VideoModel.sequelize)
1505 return queryBuilder.queryVideos(options)
1508 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1516 private static throwIfPrivateIncludeWithoutUser (include: VideoInclude, user: MUserAccountId) {
1517 if (VideoModel.isPrivateInclude(include) && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1518 throw new Error('Try to filter all-local but user cannot see all videos')
1522 private static throwIfPrivacyOneOfWithoutUser (privacyOneOf: VideoPrivacy[], user: MUserAccountId) {
1523 if (privacyOneOf && !user?.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1524 throw new Error('Try to choose video privacies but user cannot see all videos')
1528 private static isPrivateInclude (include: VideoInclude) {
1529 return include & VideoInclude.BLACKLISTED ||
1530 include & VideoInclude.BLOCKED_OWNER ||
1531 include & VideoInclude.NOT_PUBLISHED_STATE
1535 return !!this.VideoBlacklist
1539 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1542 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1543 // We first transcode to WebTorrent format, so try this array first
1544 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1545 const file = fun(this.VideoFiles, file => file.resolution)
1547 return Object.assign(file, { Video: this })
1550 // No webtorrent files, try with streaming playlist files
1551 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1552 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1554 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1555 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1561 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1562 return this.getQualityFileBy(maxBy)
1565 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1566 return this.getQualityFileBy(minBy)
1569 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1570 if (Array.isArray(this.VideoFiles) === false) return undefined
1572 const file = this.VideoFiles.find(f => f.resolution === resolution)
1573 if (!file) return undefined
1575 return Object.assign(file, { Video: this })
1578 hasWebTorrentFiles () {
1579 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1582 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction?: Transaction) {
1583 thumbnail.videoId = this.id
1585 const savedThumbnail = await thumbnail.save({ transaction })
1587 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1589 this.Thumbnails = this.Thumbnails.filter(t => t.id !== savedThumbnail.id)
1590 this.Thumbnails.push(savedThumbnail)
1594 if (Array.isArray(this.Thumbnails) === false) return undefined
1596 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1600 return !!this.getPreview()
1604 if (Array.isArray(this.Thumbnails) === false) return undefined
1606 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1610 return this.remote === false
1613 getWatchStaticPath () {
1614 return buildVideoWatchPath({ shortUUID: uuidToShort(this.uuid) })
1617 getEmbedStaticPath () {
1618 return buildVideoEmbedPath(this)
1621 getMiniatureStaticPath () {
1622 const thumbnail = this.getMiniature()
1623 if (!thumbnail) return null
1625 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1628 getPreviewStaticPath () {
1629 const preview = this.getPreview()
1630 if (!preview) return null
1632 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1633 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1636 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1637 return videoModelToFormattedJSON(this, options)
1640 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1641 return videoModelToFormattedDetailsJSON(this)
1644 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1645 let files: VideoFile[] = []
1647 if (Array.isArray(this.VideoFiles)) {
1648 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1649 files = files.concat(result)
1652 for (const p of (this.VideoStreamingPlaylists || [])) {
1653 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1654 files = files.concat(result)
1660 toActivityPubObject (this: MVideoAP): VideoObject {
1661 return videoModelToActivityPubObject(this)
1664 getTruncatedDescription () {
1665 if (!this.description) return null
1667 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1668 return peertubeTruncate(this.description, { length: maxLength })
1671 getMaxQualityResolution () {
1672 const file = this.getMaxQualityFile()
1673 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1675 return VideoPathManager.Instance.makeAvailableVideoFile(file.withVideoOrPlaylist(videoOrPlaylist), originalFilePath => {
1676 return getVideoFileResolution(originalFilePath)
1680 getDescriptionAPIPath () {
1681 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1684 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1685 if (!this.VideoStreamingPlaylists) return undefined
1687 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1688 if (!playlist) return undefined
1690 playlist.Video = this
1695 setHLSPlaylist (playlist: MStreamingPlaylist) {
1696 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1698 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1699 this.VideoStreamingPlaylists = toAdd
1703 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1704 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1708 removeWebTorrentFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) {
1709 const filePath = isRedundancy
1710 ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile)
1711 : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile)
1713 const promises: Promise<any>[] = [ remove(filePath) ]
1714 if (!isRedundancy) promises.push(videoFile.removeTorrent())
1716 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
1717 promises.push(removeWebTorrentObjectStorage(videoFile))
1720 return Promise.all(promises)
1723 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1724 const directoryPath = isRedundancy
1725 ? getHLSRedundancyDirectory(this)
1726 : getHLSDirectory(this)
1728 await remove(directoryPath)
1730 if (isRedundancy !== true) {
1731 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1732 streamingPlaylistWithFiles.Video = this
1734 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1735 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1738 // Remove physical files and torrents
1740 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1743 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
1744 await removeHLSObjectStorage(streamingPlaylist.withVideo(this))
1750 if (this.isOwned()) return false
1752 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1755 hasPrivacyForFederation () {
1756 return isPrivacyForFederation(this.privacy)
1759 hasStateForFederation () {
1760 return isStateForFederation(this.state)
1763 isNewVideo (newPrivacy: VideoPrivacy) {
1764 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1767 setAsRefreshed (transaction?: Transaction) {
1768 return setAsUpdated('video', this.id, transaction)
1772 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1775 setPrivacy (newPrivacy: VideoPrivacy) {
1776 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1777 this.publishedAt = new Date()
1780 this.privacy = newPrivacy
1784 return this.privacy === VideoPrivacy.PRIVATE ||
1785 this.privacy === VideoPrivacy.UNLISTED ||
1786 this.privacy === VideoPrivacy.INTERNAL
1789 async setNewState (newState: VideoState, isNewVideo: boolean, transaction: Transaction) {
1790 if (this.state === newState) throw new Error('Cannot use same state ' + newState)
1792 this.state = newState
1794 if (this.state === VideoState.PUBLISHED && isNewVideo) {
1795 this.publishedAt = new Date()
1798 await this.save({ transaction })
1801 getBandwidthBits (this: MVideo, videoFile: MVideoFile) {
1802 return Math.ceil((videoFile.size * 8) / this.duration)
1806 if (this.isOwned()) {
1808 WEBSERVER.URL + '/tracker/announce',
1809 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
1813 return this.Trackers.map(t => t.url)