1 import * as Bluebird from 'bluebird'
2 import { remove } from 'fs-extra'
3 import { maxBy, minBy, pick } 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 { v4 as uuidv4 } from 'uuid'
28 import { buildNSFWFilter } from '@server/helpers/express-utils'
29 import { getPrivaciesForFederation, isPrivacyForFederation, isStateForFederation } from '@server/helpers/video'
30 import { LiveManager } from '@server/lib/live-manager'
31 import { getHLSDirectory, getVideoFilePath } from '@server/lib/video-paths'
32 import { getServerActor } from '@server/models/application/application'
33 import { ModelCache } from '@server/models/model-cache'
34 import { VideoFile } from '@shared/models/videos/video-file.model'
35 import { ResultList, UserRight, VideoPrivacy, VideoState } from '../../../shared'
36 import { VideoObject } from '../../../shared/models/activitypub/objects'
37 import { Video, VideoDetails } from '../../../shared/models/videos'
38 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
39 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
40 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
41 import { peertubeTruncate } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffprobe-utils'
56 import { logger } from '../../helpers/logger'
57 import { CONFIG } from '../../initializers/config'
71 } from '../../initializers/constants'
72 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 MChannelAccountDefault,
78 MStreamingPlaylistFilesVideo,
83 MVideoAccountLightBlacklistAllFiles,
88 MVideoFormattableDetails,
94 MVideoThumbnailBlacklist,
98 } from '../../types/models'
99 import { MThumbnail } from '../../types/models/video/thumbnail'
100 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
101 import { VideoAbuseModel } from '../abuse/video-abuse'
102 import { AccountModel } from '../account/account'
103 import { AccountVideoRateModel } from '../account/account-video-rate'
104 import { UserModel } from '../account/user'
105 import { UserVideoHistoryModel } from '../account/user-video-history'
106 import { ActorModel } from '../activitypub/actor'
107 import { AvatarModel } from '../avatar/avatar'
108 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
109 import { ServerModel } from '../server/server'
110 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
111 import { ScheduleVideoUpdateModel } from './schedule-video-update'
112 import { TagModel } from './tag'
113 import { ThumbnailModel } from './thumbnail'
114 import { VideoBlacklistModel } from './video-blacklist'
115 import { VideoCaptionModel } from './video-caption'
116 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
117 import { VideoCommentModel } from './video-comment'
118 import { VideoFileModel } from './video-file'
120 videoFilesModelToFormattedJSON,
121 VideoFormattingJSONOptions,
122 videoModelToActivityPubObject,
123 videoModelToFormattedDetailsJSON,
124 videoModelToFormattedJSON
125 } from './video-format-utils'
126 import { VideoImportModel } from './video-import'
127 import { VideoLiveModel } from './video-live'
128 import { VideoPlaylistElementModel } from './video-playlist-element'
129 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
130 import { VideoShareModel } from './video-share'
131 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
132 import { VideoTagModel } from './video-tag'
133 import { VideoViewModel } from './video-view'
135 export enum ScopeNames {
136 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
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_USER_HISTORY = 'WITH_USER_HISTORY',
144 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
145 WITH_USER_ID = 'WITH_USER_ID',
146 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
147 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
148 WITH_LIVE = 'WITH_LIVE'
151 export type ForAPIOptions = {
154 videoPlaylistId?: number
156 withAccountBlockerIds?: number[]
159 export type AvailableForListIDsOptions = {
160 serverAccountId: number
161 followerActorId: number
162 includeLocalVideos: boolean
164 attributesType?: 'none' | 'id' | 'all'
167 categoryOneOf?: number[]
169 licenceOneOf?: number[]
170 languageOneOf?: string[]
177 videoChannelId?: number
179 videoPlaylistId?: number
181 trendingDays?: number
182 user?: MUserAccountId
183 historyOfUser?: MUserId
185 baseWhere?: WhereOptions[]
189 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
190 attributes: [ 'id', 'url', 'uuid', 'remote' ]
192 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
193 const include: Includeable[] = [
195 model: VideoChannelModel.scope({
197 VideoChannelScopeNames.SUMMARY, {
199 withAccountBlockerIds: options.withAccountBlockerIds
206 attributes: [ 'type', 'filename' ],
207 model: ThumbnailModel,
212 const query: FindOptions = {}
222 if (options.videoPlaylistId) {
224 model: VideoPlaylistElementModel.unscoped(),
227 videoPlaylistId: options.videoPlaylistId
232 query.include = include
236 [ScopeNames.WITH_THUMBNAILS]: {
239 model: ThumbnailModel,
244 [ScopeNames.WITH_LIVE]: {
247 model: VideoLiveModel.unscoped(),
252 [ScopeNames.WITH_USER_ID]: {
255 attributes: [ 'accountId' ],
256 model: VideoChannelModel.unscoped(),
260 attributes: [ 'userId' ],
261 model: AccountModel.unscoped(),
268 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
271 model: VideoChannelModel.unscoped(),
276 exclude: [ 'privateKey', 'publicKey' ]
278 model: ActorModel.unscoped(),
282 attributes: [ 'host' ],
283 model: ServerModel.unscoped(),
287 model: AvatarModel.unscoped(),
293 model: AccountModel.unscoped(),
297 model: ActorModel.unscoped(),
299 exclude: [ 'privateKey', 'publicKey' ]
304 attributes: [ 'host' ],
305 model: ServerModel.unscoped(),
309 model: AvatarModel.unscoped(),
320 [ScopeNames.WITH_TAGS]: {
321 include: [ TagModel ]
323 [ScopeNames.WITH_BLACKLISTED]: {
326 attributes: [ 'id', 'reason', 'unfederated' ],
327 model: VideoBlacklistModel,
332 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
333 let subInclude: any[] = []
335 if (withRedundancies === true) {
338 attributes: [ 'fileUrl' ],
339 model: VideoRedundancyModel.unscoped(),
348 model: VideoFileModel,
355 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
356 const subInclude: IncludeOptions[] = [
358 model: VideoFileModel,
363 if (withRedundancies === true) {
365 attributes: [ 'fileUrl' ],
366 model: VideoRedundancyModel.unscoped(),
374 model: VideoStreamingPlaylistModel.unscoped(),
381 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
384 model: ScheduleVideoUpdateModel.unscoped(),
389 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
393 attributes: [ 'currentTime' ],
394 model: UserVideoHistoryModel.unscoped(),
407 buildTrigramSearchIndex('video_name_trigram', 'name'),
409 { fields: [ 'createdAt' ] },
412 { name: 'publishedAt', order: 'DESC' },
413 { name: 'id', order: 'ASC' }
416 { fields: [ 'duration' ] },
417 { fields: [ 'views' ] },
418 { fields: [ 'channelId' ] },
420 fields: [ 'originallyPublishedAt' ],
422 originallyPublishedAt: {
428 fields: [ 'category' ], // We don't care videos with an unknown category
436 fields: [ 'licence' ], // We don't care videos with an unknown licence
444 fields: [ 'language' ], // We don't care videos with an unknown language
452 fields: [ 'nsfw' ], // Most of the videos are not NSFW
458 fields: [ 'remote' ], // Only index local videos
473 export class VideoModel extends Model {
476 @Default(DataType.UUIDV4)
478 @Column(DataType.UUID)
482 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
488 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
494 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
500 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
501 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
505 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
507 privacy: VideoPrivacy
510 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
516 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
517 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
522 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
523 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
527 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
562 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
563 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
568 commentsEnabled: boolean
572 downloadEnabled: boolean
576 waitTranscoding: boolean
580 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
591 @Default(DataType.NOW)
598 originallyPublishedAt: Date
600 @ForeignKey(() => VideoChannelModel)
604 @BelongsTo(() => VideoChannelModel, {
610 VideoChannel: VideoChannelModel
612 @BelongsToMany(() => TagModel, {
613 foreignKey: 'videoId',
614 through: () => VideoTagModel,
619 @HasMany(() => ThumbnailModel, {
627 Thumbnails: ThumbnailModel[]
629 @HasMany(() => VideoPlaylistElementModel, {
636 VideoPlaylistElements: VideoPlaylistElementModel[]
638 @HasMany(() => VideoAbuseModel, {
645 VideoAbuses: VideoAbuseModel[]
647 @HasMany(() => VideoFileModel, {
655 VideoFiles: VideoFileModel[]
657 @HasMany(() => VideoStreamingPlaylistModel, {
665 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
667 @HasMany(() => VideoShareModel, {
674 VideoShares: VideoShareModel[]
676 @HasMany(() => AccountVideoRateModel, {
683 AccountVideoRates: AccountVideoRateModel[]
685 @HasMany(() => VideoCommentModel, {
693 VideoComments: VideoCommentModel[]
695 @HasMany(() => VideoViewModel, {
702 VideoViews: VideoViewModel[]
704 @HasMany(() => UserVideoHistoryModel, {
711 UserVideoHistories: UserVideoHistoryModel[]
713 @HasOne(() => ScheduleVideoUpdateModel, {
720 ScheduleVideoUpdate: ScheduleVideoUpdateModel
722 @HasOne(() => VideoBlacklistModel, {
729 VideoBlacklist: VideoBlacklistModel
731 @HasOne(() => VideoLiveModel, {
738 VideoLive: VideoLiveModel
740 @HasOne(() => VideoImportModel, {
747 VideoImport: VideoImportModel
749 @HasMany(() => VideoCaptionModel, {
756 ['separate' as any]: true
758 VideoCaptions: VideoCaptionModel[]
761 static async sendDelete (instance: MVideoAccountLight, options) {
762 if (instance.isOwned()) {
763 if (!instance.VideoChannel) {
764 instance.VideoChannel = await instance.$get('VideoChannel', {
769 transaction: options.transaction
770 }) as MChannelAccountDefault
773 return sendDeleteVideo(instance, options.transaction)
780 static async removeFiles (instance: VideoModel) {
781 const tasks: Promise<any>[] = []
783 logger.info('Removing files of video %s.', instance.url)
785 if (instance.isOwned()) {
786 if (!Array.isArray(instance.VideoFiles)) {
787 instance.VideoFiles = await instance.$get('VideoFiles')
790 // Remove physical files and torrents
791 instance.VideoFiles.forEach(file => {
792 tasks.push(instance.removeFile(file))
793 tasks.push(file.removeTorrent())
796 // Remove playlists file
797 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
798 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
801 for (const p of instance.VideoStreamingPlaylists) {
802 tasks.push(instance.removeStreamingPlaylistFiles(p))
806 // Do not wait video deletion because we could be in a transaction
809 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
816 static stopLiveIfNeeded (instance: VideoModel) {
817 if (!instance.isLive) return
819 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
821 return LiveManager.Instance.stopSessionOf(instance.id)
825 static invalidateCache (instance: VideoModel) {
826 ModelCache.Instance.invalidateCache('video', instance.id)
830 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
831 const tasks: Promise<any>[] = []
833 if (!Array.isArray(instance.VideoAbuses)) {
834 instance.VideoAbuses = await instance.$get('VideoAbuses')
836 if (instance.VideoAbuses.length === 0) return undefined
839 logger.info('Saving video abuses details of video %s.', instance.url)
841 const details = instance.toFormattedDetailsJSON()
843 for (const abuse of instance.VideoAbuses) {
844 abuse.deletedVideo = details
845 tasks.push(abuse.save({ transaction: options.transaction }))
850 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
856 static listLocal (): Promise<MVideo[]> {
863 return VideoModel.findAll(query)
866 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
867 function getRawQuery (select: string) {
868 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
869 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
870 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
871 'WHERE "Account"."actorId" = ' + actorId
872 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
873 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
874 'WHERE "VideoShare"."actorId" = ' + actorId
876 return `(${queryVideo}) UNION (${queryVideoShare})`
879 const rawQuery = getRawQuery('"Video"."id"')
880 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
886 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
889 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
891 [Op.or]: getPrivaciesForFederation()
895 attributes: [ 'language', 'fileUrl' ],
896 model: VideoCaptionModel.unscoped(),
900 attributes: [ 'id', 'url' ],
901 model: VideoShareModel.unscoped(),
903 // We only want videos shared by this actor
918 attributes: [ 'id', 'url' ],
919 model: ActorModel.unscoped()
924 model: VideoChannelModel.unscoped(),
928 attributes: [ 'name' ],
929 model: AccountModel.unscoped(),
933 attributes: [ 'id', 'url', 'followersUrl' ],
934 model: ActorModel.unscoped(),
940 attributes: [ 'id', 'url', 'followersUrl' ],
941 model: ActorModel.unscoped(),
947 model: VideoStreamingPlaylistModel.unscoped(),
951 model: VideoFileModel,
956 VideoLiveModel.unscoped(),
962 return Bluebird.all([
963 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
964 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
965 ]).then(([ rows, totals ]) => {
966 // totals: totalVideos + totalVideoShares
968 let totalVideoShares = 0
969 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
970 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
972 const total = totalVideos + totalVideoShares
980 static async listPublishedLiveIds () {
982 attributes: [ 'id' ],
985 state: VideoState.PUBLISHED
989 const result = await VideoModel.findAll(options)
991 return result.map(v => v.id)
994 static listUserVideosForApi (options: {
1001 const { accountId, start, count, sort, search } = options
1003 function buildBaseQuery (): FindOptions {
1007 order: getVideoSort(sort),
1010 model: VideoChannelModel,
1014 model: AccountModel,
1026 baseQuery = Object.assign(baseQuery, {
1029 [Op.iLike]: '%' + search + '%'
1038 const countQuery = buildBaseQuery()
1039 const findQuery = buildBaseQuery()
1041 const findScopes: (string | ScopeOptions)[] = [
1042 ScopeNames.WITH_SCHEDULED_UPDATE,
1043 ScopeNames.WITH_BLACKLISTED,
1044 ScopeNames.WITH_THUMBNAILS
1047 return Promise.all([
1048 VideoModel.count(countQuery),
1049 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1050 ]).then(([ count, rows ]) => {
1058 static async listForApi (options: {
1063 includeLocalVideos: boolean
1065 categoryOneOf?: number[]
1066 licenceOneOf?: number[]
1067 languageOneOf?: string[]
1068 tagsOneOf?: string[]
1069 tagsAllOf?: string[]
1070 filter?: VideoFilter
1072 videoChannelId?: number
1073 followerActorId?: number
1074 videoPlaylistId?: number
1075 trendingDays?: number
1076 user?: MUserAccountId
1077 historyOfUser?: MUserId
1078 countVideos?: boolean
1081 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1082 throw new Error('Try to filter all-local but no user has not the see all videos right')
1085 const trendingDays = options.sort.endsWith('trending')
1086 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1088 let trendingAlgorithm
1089 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1090 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1092 const serverActor = await getServerActor()
1094 // followerActorId === null has a meaning, so just check undefined
1095 const followerActorId = options.followerActorId !== undefined
1096 ? options.followerActorId
1099 const queryOptions = {
1100 start: options.start,
1101 count: options.count,
1104 serverAccountId: serverActor.Account.id,
1106 categoryOneOf: options.categoryOneOf,
1107 licenceOneOf: options.licenceOneOf,
1108 languageOneOf: options.languageOneOf,
1109 tagsOneOf: options.tagsOneOf,
1110 tagsAllOf: options.tagsAllOf,
1111 filter: options.filter,
1112 withFiles: options.withFiles,
1113 accountId: options.accountId,
1114 videoChannelId: options.videoChannelId,
1115 videoPlaylistId: options.videoPlaylistId,
1116 includeLocalVideos: options.includeLocalVideos,
1118 historyOfUser: options.historyOfUser,
1121 search: options.search
1124 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1127 static async searchAndPopulateAccountAndServer (options: {
1128 includeLocalVideos: boolean
1133 startDate?: string // ISO 8601
1134 endDate?: string // ISO 8601
1135 originallyPublishedStartDate?: string
1136 originallyPublishedEndDate?: string
1138 categoryOneOf?: number[]
1139 licenceOneOf?: number[]
1140 languageOneOf?: string[]
1141 tagsOneOf?: string[]
1142 tagsAllOf?: string[]
1143 durationMin?: number // seconds
1144 durationMax?: number // seconds
1145 user?: MUserAccountId
1146 filter?: VideoFilter
1148 const serverActor = await getServerActor()
1149 const queryOptions = {
1150 followerActorId: serverActor.id,
1151 serverAccountId: serverActor.Account.id,
1152 includeLocalVideos: options.includeLocalVideos,
1154 categoryOneOf: options.categoryOneOf,
1155 licenceOneOf: options.licenceOneOf,
1156 languageOneOf: options.languageOneOf,
1157 tagsOneOf: options.tagsOneOf,
1158 tagsAllOf: options.tagsAllOf,
1160 filter: options.filter,
1161 start: options.start,
1162 count: options.count,
1164 startDate: options.startDate,
1165 endDate: options.endDate,
1166 originallyPublishedStartDate: options.originallyPublishedStartDate,
1167 originallyPublishedEndDate: options.originallyPublishedEndDate,
1169 durationMin: options.durationMin,
1170 durationMax: options.durationMax,
1172 search: options.search
1175 return VideoModel.getAvailableForApi(queryOptions)
1178 static countLocalLives () {
1184 [Op.ne]: VideoState.LIVE_ENDED
1189 return VideoModel.count(options)
1192 static countVideosUploadedByUserSince (userId: number, since: Date) {
1196 model: VideoChannelModel.unscoped(),
1200 model: AccountModel.unscoped(),
1204 model: UserModel.unscoped(),
1222 return VideoModel.unscoped().count(options)
1225 static countLivesOfAccount (accountId: number) {
1231 [Op.ne]: VideoState.LIVE_ENDED
1237 model: VideoChannelModel.unscoped(),
1245 return VideoModel.count(options)
1248 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1249 const where = buildWhereIdOrUUID(id)
1255 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1258 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1259 const where = buildWhereIdOrUUID(id)
1265 return VideoModel.scope([
1266 ScopeNames.WITH_THUMBNAILS,
1267 ScopeNames.WITH_BLACKLISTED
1271 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1274 where: buildWhereIdOrUUID(id),
1278 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1281 return ModelCache.Instance.doCache({
1282 cacheType: 'load-video-immutable-id',
1289 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1290 const where = buildWhereIdOrUUID(id)
1296 return VideoModel.scope([
1297 ScopeNames.WITH_BLACKLISTED,
1298 ScopeNames.WITH_USER_ID,
1299 ScopeNames.WITH_THUMBNAILS
1303 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1304 const where = buildWhereIdOrUUID(id)
1307 attributes: [ 'id' ],
1312 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1315 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1316 const where = buildWhereIdOrUUID(id)
1324 return VideoModel.scope([
1325 ScopeNames.WITH_WEBTORRENT_FILES,
1326 ScopeNames.WITH_STREAMING_PLAYLISTS,
1327 ScopeNames.WITH_THUMBNAILS
1331 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1338 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1341 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1342 const query: FindOptions = {
1349 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1352 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1354 const query: FindOptions = {
1361 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1364 return ModelCache.Instance.doCache({
1365 cacheType: 'load-video-immutable-url',
1372 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1373 const query: FindOptions = {
1380 return VideoModel.scope([
1381 ScopeNames.WITH_ACCOUNT_DETAILS,
1382 ScopeNames.WITH_WEBTORRENT_FILES,
1383 ScopeNames.WITH_STREAMING_PLAYLISTS,
1384 ScopeNames.WITH_THUMBNAILS,
1385 ScopeNames.WITH_BLACKLISTED
1389 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1390 const where = buildWhereIdOrUUID(id)
1393 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1398 const scopes: (string | ScopeOptions)[] = [
1399 ScopeNames.WITH_TAGS,
1400 ScopeNames.WITH_BLACKLISTED,
1401 ScopeNames.WITH_ACCOUNT_DETAILS,
1402 ScopeNames.WITH_SCHEDULED_UPDATE,
1403 ScopeNames.WITH_WEBTORRENT_FILES,
1404 ScopeNames.WITH_STREAMING_PLAYLISTS,
1405 ScopeNames.WITH_THUMBNAILS,
1406 ScopeNames.WITH_LIVE
1410 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1418 static loadForGetAPI (parameters: {
1422 }): Promise<MVideoDetails> {
1423 const { id, t, userId } = parameters
1424 const where = buildWhereIdOrUUID(id)
1427 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1432 const scopes: (string | ScopeOptions)[] = [
1433 ScopeNames.WITH_TAGS,
1434 ScopeNames.WITH_BLACKLISTED,
1435 ScopeNames.WITH_ACCOUNT_DETAILS,
1436 ScopeNames.WITH_SCHEDULED_UPDATE,
1437 ScopeNames.WITH_THUMBNAILS,
1438 ScopeNames.WITH_LIVE,
1439 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1440 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1444 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1452 static async getStats () {
1453 const totalLocalVideos = await VideoModel.count({
1459 let totalLocalVideoViews = await VideoModel.sum('views', {
1465 // Sequelize could return null...
1466 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1468 const { total: totalVideos } = await VideoModel.listForApi({
1471 sort: '-publishedAt',
1472 nsfw: buildNSFWFilter(),
1473 includeLocalVideos: true,
1479 totalLocalVideoViews,
1484 static incrementViews (id: number, views: number) {
1485 return VideoModel.increment('views', {
1493 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1494 // Instances only share videos
1495 const query = 'SELECT 1 FROM "videoShare" ' +
1496 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1497 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1501 type: QueryTypes.SELECT as QueryTypes.SELECT,
1502 bind: { followerActorId, videoId },
1506 return VideoModel.sequelize.query(query, options)
1507 .then(results => results.length === 1)
1510 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1513 channelId: videoChannel.id
1518 return VideoModel.update({ support: videoChannel.support }, options)
1521 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1523 attributes: [ 'id' ],
1525 channelId: videoChannel.id
1529 return VideoModel.findAll(query)
1530 .then(videos => videos.map(v => v.id))
1533 // threshold corresponds to how many video the field should have to be returned
1534 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1535 const serverActor = await getServerActor()
1536 const followerActorId = serverActor.id
1538 const queryOptions: BuildVideosQueryOptions = {
1539 attributes: [ `"${field}"` ],
1540 group: `GROUP BY "${field}"`,
1541 having: `HAVING COUNT("${field}") >= ${threshold}`,
1545 serverAccountId: serverActor.Account.id,
1547 includeLocalVideos: true
1550 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1552 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1553 .then(rows => rows.map(r => r[field]))
1556 static buildTrendingQuery (trendingDays: number) {
1560 model: VideoViewModel,
1564 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1570 private static async getAvailableForApi (
1571 options: BuildVideosQueryOptions,
1573 ): Promise<ResultList<VideoModel>> {
1574 function getCount () {
1575 if (countVideos !== true) return Promise.resolve(undefined)
1577 const countOptions = Object.assign({}, options, { isCount: true })
1578 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1580 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1581 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1584 function getModels () {
1585 if (options.count === 0) return Promise.resolve([])
1587 const { query, replacements, order } = buildListQuery(VideoModel, options)
1588 const queryModels = wrapForAPIResults(query, replacements, options, order)
1590 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1591 .then(rows => VideoModel.buildAPIResult(rows))
1594 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1602 private static buildAPIResult (rows: any[]) {
1603 const videosMemo: { [ id: number ]: VideoModel } = {}
1604 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1606 const thumbnailsDone = new Set<number>()
1607 const historyDone = new Set<number>()
1608 const videoFilesDone = new Set<number>()
1610 const videos: VideoModel[] = []
1612 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1613 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1614 const serverKeys = [ 'id', 'host' ]
1615 const videoFileKeys = [
1629 'videoStreamingPlaylistId'
1631 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1655 'originallyPublishedAt',
1660 const buildOpts = { raw: true }
1662 function buildActor (rowActor: any) {
1663 const avatarModel = rowActor.Avatar.id !== null
1664 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1667 const serverModel = rowActor.Server.id !== null
1668 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1671 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1672 actorModel.Avatar = avatarModel
1673 actorModel.Server = serverModel
1678 for (const row of rows) {
1679 if (!videosMemo[row.id]) {
1681 const channel = row.VideoChannel
1682 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1683 channelModel.Actor = buildActor(channel.Actor)
1685 const account = row.VideoChannel.Account
1686 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1687 accountModel.Actor = buildActor(account.Actor)
1689 channelModel.Account = accountModel
1691 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1692 videoModel.VideoChannel = channelModel
1694 videoModel.UserVideoHistories = []
1695 videoModel.Thumbnails = []
1696 videoModel.VideoFiles = []
1697 videoModel.VideoStreamingPlaylists = []
1699 videosMemo[row.id] = videoModel
1700 // Don't take object value to have a sorted array
1701 videos.push(videoModel)
1704 const videoModel = videosMemo[row.id]
1706 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1707 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1708 videoModel.UserVideoHistories.push(historyModel)
1710 historyDone.add(row.userVideoHistory.id)
1713 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1714 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1715 videoModel.Thumbnails.push(thumbnailModel)
1717 thumbnailsDone.add(row.Thumbnails.id)
1720 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1721 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1722 videoModel.VideoFiles.push(videoFileModel)
1724 videoFilesDone.add(row.VideoFiles.id)
1727 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1728 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1729 streamingPlaylist.VideoFiles = []
1731 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1733 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1736 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1737 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1739 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1740 streamingPlaylist.VideoFiles.push(videoFileModel)
1742 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1749 static getCategoryLabel (id: number) {
1750 return VIDEO_CATEGORIES[id] || 'Misc'
1753 static getLicenceLabel (id: number) {
1754 return VIDEO_LICENCES[id] || 'Unknown'
1757 static getLanguageLabel (id: string) {
1758 return VIDEO_LANGUAGES[id] || 'Unknown'
1761 static getPrivacyLabel (id: number) {
1762 return VIDEO_PRIVACIES[id] || 'Unknown'
1765 static getStateLabel (id: number) {
1766 return VIDEO_STATES[id] || 'Unknown'
1770 return !!this.VideoBlacklist
1774 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1777 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1778 // We first transcode to WebTorrent format, so try this array first
1779 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1780 const file = fun(this.VideoFiles, file => file.resolution)
1782 return Object.assign(file, { Video: this })
1785 // No webtorrent files, try with streaming playlist files
1786 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1787 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1789 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1790 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1796 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1797 return this.getQualityFileBy(maxBy)
1800 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1801 return this.getQualityFileBy(minBy)
1804 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1805 if (Array.isArray(this.VideoFiles) === false) return undefined
1807 const file = this.VideoFiles.find(f => f.resolution === resolution)
1808 if (!file) return undefined
1810 return Object.assign(file, { Video: this })
1813 hasWebTorrentFiles () {
1814 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1817 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1818 thumbnail.videoId = this.id
1820 const savedThumbnail = await thumbnail.save({ transaction })
1822 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1824 // Already have this thumbnail, skip
1825 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1827 this.Thumbnails.push(savedThumbnail)
1830 generateThumbnailName () {
1831 return uuidv4() + '.jpg'
1835 if (Array.isArray(this.Thumbnails) === false) return undefined
1837 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1840 generatePreviewName () {
1841 return uuidv4() + '.jpg'
1845 return !!this.getPreview()
1849 if (Array.isArray(this.Thumbnails) === false) return undefined
1851 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1855 return this.remote === false
1858 getWatchStaticPath () {
1859 return '/videos/watch/' + this.uuid
1862 getEmbedStaticPath () {
1863 return '/videos/embed/' + this.uuid
1866 getMiniatureStaticPath () {
1867 const thumbnail = this.getMiniature()
1868 if (!thumbnail) return null
1870 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1873 getPreviewStaticPath () {
1874 const preview = this.getPreview()
1875 if (!preview) return null
1877 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1878 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1881 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1882 return videoModelToFormattedJSON(this, options)
1885 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1886 return videoModelToFormattedDetailsJSON(this)
1889 getFormattedVideoFilesJSON (): VideoFile[] {
1890 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1891 let files: VideoFile[] = []
1893 if (Array.isArray(this.VideoFiles)) {
1894 const result = videoFilesModelToFormattedJSON(this, this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1895 files = files.concat(result)
1898 for (const p of (this.VideoStreamingPlaylists || [])) {
1901 const result = videoFilesModelToFormattedJSON(p, this, baseUrlHttp, baseUrlWs, p.VideoFiles)
1902 files = files.concat(result)
1908 toActivityPubObject (this: MVideoAP): VideoObject {
1909 return videoModelToActivityPubObject(this)
1912 getTruncatedDescription () {
1913 if (!this.description) return null
1915 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1916 return peertubeTruncate(this.description, { length: maxLength })
1919 getMaxQualityResolution () {
1920 const file = this.getMaxQualityFile()
1921 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1922 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1924 return getVideoFileResolution(originalFilePath)
1927 getDescriptionAPIPath () {
1928 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1931 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1932 if (!this.VideoStreamingPlaylists) return undefined
1934 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1935 playlist.Video = this
1940 setHLSPlaylist (playlist: MStreamingPlaylist) {
1941 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1943 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1944 this.VideoStreamingPlaylists = toAdd
1948 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1949 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1953 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1954 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1955 return remove(filePath)
1956 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1959 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1960 const directoryPath = getHLSDirectory(this, isRedundancy)
1962 await remove(directoryPath)
1964 if (isRedundancy !== true) {
1965 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1966 streamingPlaylistWithFiles.Video = this
1968 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1969 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1972 // Remove physical files and torrents
1974 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1980 if (this.isOwned()) return false
1982 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1985 hasPrivacyForFederation () {
1986 return isPrivacyForFederation(this.privacy)
1989 hasStateForFederation () {
1990 return isStateForFederation(this.state)
1993 isNewVideo (newPrivacy: VideoPrivacy) {
1994 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
1998 this.changed('updatedAt', true)
2004 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2007 setPrivacy (newPrivacy: VideoPrivacy) {
2008 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2009 this.publishedAt = new Date()
2012 this.privacy = newPrivacy
2016 return this.privacy === VideoPrivacy.PRIVATE ||
2017 this.privacy === VideoPrivacy.UNLISTED ||
2018 this.privacy === VideoPrivacy.INTERNAL
2021 async publishIfNeededAndSave (t: Transaction) {
2022 if (this.state !== VideoState.PUBLISHED) {
2023 this.state = VideoState.PUBLISHED
2024 this.publishedAt = new Date()
2025 await this.save({ transaction: t })
2034 if (this.isOwned()) {
2036 baseUrlHttp: WEBSERVER.URL,
2037 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2042 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2043 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2047 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2048 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2051 getBandwidthBits (videoFile: MVideoFile) {
2052 return Math.ceil((videoFile.size * 8) / this.duration)