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'
70 } from '../../initializers/constants'
71 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 MChannelAccountDefault,
77 MStreamingPlaylistFilesVideo,
82 MVideoAccountLightBlacklistAllFiles,
87 MVideoFormattableDetails,
93 MVideoThumbnailBlacklist,
97 } from '../../types/models'
98 import { MThumbnail } from '../../types/models/video/thumbnail'
99 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../types/models/video/video-file'
100 import { VideoAbuseModel } from '../abuse/video-abuse'
101 import { AccountModel } from '../account/account'
102 import { AccountVideoRateModel } from '../account/account-video-rate'
103 import { UserModel } from '../account/user'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { ActorModel } from '../activitypub/actor'
106 import { AvatarModel } from '../avatar/avatar'
107 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
108 import { ServerModel } from '../server/server'
109 import { TrackerModel } from '../server/tracker'
110 import { VideoTrackerModel } from '../server/video-tracker'
111 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
112 import { ScheduleVideoUpdateModel } from './schedule-video-update'
113 import { TagModel } from './tag'
114 import { ThumbnailModel } from './thumbnail'
115 import { VideoBlacklistModel } from './video-blacklist'
116 import { VideoCaptionModel } from './video-caption'
117 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
118 import { VideoCommentModel } from './video-comment'
119 import { VideoFileModel } from './video-file'
121 videoFilesModelToFormattedJSON,
122 VideoFormattingJSONOptions,
123 videoModelToActivityPubObject,
124 videoModelToFormattedDetailsJSON,
125 videoModelToFormattedJSON
126 } from './video-format-utils'
127 import { VideoImportModel } from './video-import'
128 import { VideoLiveModel } from './video-live'
129 import { VideoPlaylistElementModel } from './video-playlist-element'
130 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
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 {
137 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
139 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
140 WITH_TAGS = 'WITH_TAGS',
141 WITH_TRACKERS = 'WITH_TRACKERS',
142 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
143 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
144 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
145 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
146 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
147 WITH_USER_ID = 'WITH_USER_ID',
148 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
149 WITH_THUMBNAILS = 'WITH_THUMBNAILS',
150 WITH_LIVE = 'WITH_LIVE'
153 export type ForAPIOptions = {
156 videoPlaylistId?: number
158 withAccountBlockerIds?: number[]
161 export type AvailableForListIDsOptions = {
162 serverAccountId: number
163 followerActorId: number
164 includeLocalVideos: boolean
166 attributesType?: 'none' | 'id' | 'all'
169 categoryOneOf?: number[]
171 licenceOneOf?: number[]
172 languageOneOf?: string[]
179 videoChannelId?: number
181 videoPlaylistId?: number
183 trendingDays?: number
184 user?: MUserAccountId
185 historyOfUser?: MUserId
187 baseWhere?: WhereOptions[]
191 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
192 attributes: [ 'id', 'url', 'uuid', 'remote' ]
194 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
195 const include: Includeable[] = [
197 model: VideoChannelModel.scope({
199 VideoChannelScopeNames.SUMMARY, {
201 withAccountBlockerIds: options.withAccountBlockerIds
208 attributes: [ 'type', 'filename' ],
209 model: ThumbnailModel,
214 const query: FindOptions = {}
224 if (options.videoPlaylistId) {
226 model: VideoPlaylistElementModel.unscoped(),
229 videoPlaylistId: options.videoPlaylistId
234 query.include = include
238 [ScopeNames.WITH_THUMBNAILS]: {
241 model: ThumbnailModel,
246 [ScopeNames.WITH_LIVE]: {
249 model: VideoLiveModel.unscoped(),
254 [ScopeNames.WITH_USER_ID]: {
257 attributes: [ 'accountId' ],
258 model: VideoChannelModel.unscoped(),
262 attributes: [ 'userId' ],
263 model: AccountModel.unscoped(),
270 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
273 model: VideoChannelModel.unscoped(),
278 exclude: [ 'privateKey', 'publicKey' ]
280 model: ActorModel.unscoped(),
284 attributes: [ 'host' ],
285 model: ServerModel.unscoped(),
289 model: AvatarModel.unscoped(),
295 model: AccountModel.unscoped(),
299 model: ActorModel.unscoped(),
301 exclude: [ 'privateKey', 'publicKey' ]
306 attributes: [ 'host' ],
307 model: ServerModel.unscoped(),
311 model: AvatarModel.unscoped(),
322 [ScopeNames.WITH_TAGS]: {
323 include: [ TagModel ]
325 [ScopeNames.WITH_TRACKERS]: {
328 attributes: [ 'id', 'url' ],
333 [ScopeNames.WITH_BLACKLISTED]: {
336 attributes: [ 'id', 'reason', 'unfederated' ],
337 model: VideoBlacklistModel,
342 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
343 let subInclude: any[] = []
345 if (withRedundancies === true) {
348 attributes: [ 'fileUrl' ],
349 model: VideoRedundancyModel.unscoped(),
358 model: VideoFileModel,
366 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
367 const subInclude: IncludeOptions[] = [
369 model: VideoFileModel,
374 if (withRedundancies === true) {
376 attributes: [ 'fileUrl' ],
377 model: VideoRedundancyModel.unscoped(),
385 model: VideoStreamingPlaylistModel.unscoped(),
393 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
396 model: ScheduleVideoUpdateModel.unscoped(),
401 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
405 attributes: [ 'currentTime' ],
406 model: UserVideoHistoryModel.unscoped(),
419 buildTrigramSearchIndex('video_name_trigram', 'name'),
421 { fields: [ 'createdAt' ] },
424 { name: 'publishedAt', order: 'DESC' },
425 { name: 'id', order: 'ASC' }
428 { fields: [ 'duration' ] },
429 { fields: [ 'views' ] },
430 { fields: [ 'channelId' ] },
432 fields: [ 'originallyPublishedAt' ],
434 originallyPublishedAt: {
440 fields: [ 'category' ], // We don't care videos with an unknown category
448 fields: [ 'licence' ], // We don't care videos with an unknown licence
456 fields: [ 'language' ], // We don't care videos with an unknown language
464 fields: [ 'nsfw' ], // Most of the videos are not NSFW
470 fields: [ 'remote' ], // Only index local videos
485 export class VideoModel extends Model {
488 @Default(DataType.UUIDV4)
490 @Column(DataType.UUID)
494 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
500 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
506 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
512 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
513 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
517 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
519 privacy: VideoPrivacy
522 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
528 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
529 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
534 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
535 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
539 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
574 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
575 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
580 commentsEnabled: boolean
584 downloadEnabled: boolean
588 waitTranscoding: boolean
592 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
603 @Default(DataType.NOW)
610 originallyPublishedAt: Date
612 @ForeignKey(() => VideoChannelModel)
616 @BelongsTo(() => VideoChannelModel, {
622 VideoChannel: VideoChannelModel
624 @BelongsToMany(() => TagModel, {
625 foreignKey: 'videoId',
626 through: () => VideoTagModel,
631 @BelongsToMany(() => TrackerModel, {
632 foreignKey: 'videoId',
633 through: () => VideoTrackerModel,
636 Trackers: TrackerModel[]
638 @HasMany(() => ThumbnailModel, {
646 Thumbnails: ThumbnailModel[]
648 @HasMany(() => VideoPlaylistElementModel, {
655 VideoPlaylistElements: VideoPlaylistElementModel[]
657 @HasMany(() => VideoAbuseModel, {
664 VideoAbuses: VideoAbuseModel[]
666 @HasMany(() => VideoFileModel, {
674 VideoFiles: VideoFileModel[]
676 @HasMany(() => VideoStreamingPlaylistModel, {
684 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
686 @HasMany(() => VideoShareModel, {
693 VideoShares: VideoShareModel[]
695 @HasMany(() => AccountVideoRateModel, {
702 AccountVideoRates: AccountVideoRateModel[]
704 @HasMany(() => VideoCommentModel, {
712 VideoComments: VideoCommentModel[]
714 @HasMany(() => VideoViewModel, {
721 VideoViews: VideoViewModel[]
723 @HasMany(() => UserVideoHistoryModel, {
730 UserVideoHistories: UserVideoHistoryModel[]
732 @HasOne(() => ScheduleVideoUpdateModel, {
739 ScheduleVideoUpdate: ScheduleVideoUpdateModel
741 @HasOne(() => VideoBlacklistModel, {
748 VideoBlacklist: VideoBlacklistModel
750 @HasOne(() => VideoLiveModel, {
757 VideoLive: VideoLiveModel
759 @HasOne(() => VideoImportModel, {
766 VideoImport: VideoImportModel
768 @HasMany(() => VideoCaptionModel, {
775 ['separate' as any]: true
777 VideoCaptions: VideoCaptionModel[]
780 static async sendDelete (instance: MVideoAccountLight, options) {
781 if (instance.isOwned()) {
782 if (!instance.VideoChannel) {
783 instance.VideoChannel = await instance.$get('VideoChannel', {
788 transaction: options.transaction
789 }) as MChannelAccountDefault
792 return sendDeleteVideo(instance, options.transaction)
799 static async removeFiles (instance: VideoModel) {
800 const tasks: Promise<any>[] = []
802 logger.info('Removing files of video %s.', instance.url)
804 if (instance.isOwned()) {
805 if (!Array.isArray(instance.VideoFiles)) {
806 instance.VideoFiles = await instance.$get('VideoFiles')
809 // Remove physical files and torrents
810 instance.VideoFiles.forEach(file => {
811 tasks.push(instance.removeFile(file))
812 tasks.push(file.removeTorrent())
815 // Remove playlists file
816 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
817 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
820 for (const p of instance.VideoStreamingPlaylists) {
821 tasks.push(instance.removeStreamingPlaylistFiles(p))
825 // Do not wait video deletion because we could be in a transaction
828 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
835 static stopLiveIfNeeded (instance: VideoModel) {
836 if (!instance.isLive) return
838 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
840 return LiveManager.Instance.stopSessionOf(instance.id)
844 static invalidateCache (instance: VideoModel) {
845 ModelCache.Instance.invalidateCache('video', instance.id)
849 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
850 const tasks: Promise<any>[] = []
852 if (!Array.isArray(instance.VideoAbuses)) {
853 instance.VideoAbuses = await instance.$get('VideoAbuses')
855 if (instance.VideoAbuses.length === 0) return undefined
858 logger.info('Saving video abuses details of video %s.', instance.url)
860 const details = instance.toFormattedDetailsJSON()
862 for (const abuse of instance.VideoAbuses) {
863 abuse.deletedVideo = details
864 tasks.push(abuse.save({ transaction: options.transaction }))
869 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
875 static listLocal (): Promise<MVideo[]> {
882 return VideoModel.findAll(query)
885 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
886 function getRawQuery (select: string) {
887 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
888 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
889 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
890 'WHERE "Account"."actorId" = ' + actorId
891 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
892 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
893 'WHERE "VideoShare"."actorId" = ' + actorId
895 return `(${queryVideo}) UNION (${queryVideoShare})`
898 const rawQuery = getRawQuery('"Video"."id"')
899 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
905 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
908 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
910 [Op.or]: getPrivaciesForFederation()
914 attributes: [ 'language', 'fileUrl' ],
915 model: VideoCaptionModel.unscoped(),
919 attributes: [ 'id', 'url' ],
920 model: VideoShareModel.unscoped(),
922 // We only want videos shared by this actor
937 attributes: [ 'id', 'url' ],
938 model: ActorModel.unscoped()
943 model: VideoChannelModel.unscoped(),
947 attributes: [ 'name' ],
948 model: AccountModel.unscoped(),
952 attributes: [ 'id', 'url', 'followersUrl' ],
953 model: ActorModel.unscoped(),
959 attributes: [ 'id', 'url', 'followersUrl' ],
960 model: ActorModel.unscoped(),
966 model: VideoStreamingPlaylistModel.unscoped(),
970 model: VideoFileModel,
975 VideoLiveModel.unscoped(),
981 return Bluebird.all([
982 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
983 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
984 ]).then(([ rows, totals ]) => {
985 // totals: totalVideos + totalVideoShares
987 let totalVideoShares = 0
988 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
989 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
991 const total = totalVideos + totalVideoShares
999 static async listPublishedLiveIds () {
1001 attributes: [ 'id' ],
1004 state: VideoState.PUBLISHED
1008 const result = await VideoModel.findAll(options)
1010 return result.map(v => v.id)
1013 static listUserVideosForApi (options: {
1020 const { accountId, start, count, sort, search } = options
1022 function buildBaseQuery (): FindOptions {
1026 order: getVideoSort(sort),
1029 model: VideoChannelModel,
1033 model: AccountModel,
1045 baseQuery = Object.assign(baseQuery, {
1048 [Op.iLike]: '%' + search + '%'
1057 const countQuery = buildBaseQuery()
1058 const findQuery = buildBaseQuery()
1060 const findScopes: (string | ScopeOptions)[] = [
1061 ScopeNames.WITH_SCHEDULED_UPDATE,
1062 ScopeNames.WITH_BLACKLISTED,
1063 ScopeNames.WITH_THUMBNAILS
1066 return Promise.all([
1067 VideoModel.count(countQuery),
1068 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1069 ]).then(([ count, rows ]) => {
1077 static async listForApi (options: {
1082 includeLocalVideos: boolean
1084 categoryOneOf?: number[]
1085 licenceOneOf?: number[]
1086 languageOneOf?: string[]
1087 tagsOneOf?: string[]
1088 tagsAllOf?: string[]
1089 filter?: VideoFilter
1091 videoChannelId?: number
1092 followerActorId?: number
1093 videoPlaylistId?: number
1094 trendingDays?: number
1095 user?: MUserAccountId
1096 historyOfUser?: MUserId
1097 countVideos?: boolean
1100 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1101 throw new Error('Try to filter all-local but no user has not the see all videos right')
1104 const trendingDays = options.sort.endsWith('trending')
1105 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1107 let trendingAlgorithm
1108 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1109 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1111 const serverActor = await getServerActor()
1113 // followerActorId === null has a meaning, so just check undefined
1114 const followerActorId = options.followerActorId !== undefined
1115 ? options.followerActorId
1118 const queryOptions = {
1119 start: options.start,
1120 count: options.count,
1123 serverAccountId: serverActor.Account.id,
1125 categoryOneOf: options.categoryOneOf,
1126 licenceOneOf: options.licenceOneOf,
1127 languageOneOf: options.languageOneOf,
1128 tagsOneOf: options.tagsOneOf,
1129 tagsAllOf: options.tagsAllOf,
1130 filter: options.filter,
1131 withFiles: options.withFiles,
1132 accountId: options.accountId,
1133 videoChannelId: options.videoChannelId,
1134 videoPlaylistId: options.videoPlaylistId,
1135 includeLocalVideos: options.includeLocalVideos,
1137 historyOfUser: options.historyOfUser,
1140 search: options.search
1143 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1146 static async searchAndPopulateAccountAndServer (options: {
1147 includeLocalVideos: boolean
1152 startDate?: string // ISO 8601
1153 endDate?: string // ISO 8601
1154 originallyPublishedStartDate?: string
1155 originallyPublishedEndDate?: string
1157 categoryOneOf?: number[]
1158 licenceOneOf?: number[]
1159 languageOneOf?: string[]
1160 tagsOneOf?: string[]
1161 tagsAllOf?: string[]
1162 durationMin?: number // seconds
1163 durationMax?: number // seconds
1164 user?: MUserAccountId
1165 filter?: VideoFilter
1167 const serverActor = await getServerActor()
1168 const queryOptions = {
1169 followerActorId: serverActor.id,
1170 serverAccountId: serverActor.Account.id,
1171 includeLocalVideos: options.includeLocalVideos,
1173 categoryOneOf: options.categoryOneOf,
1174 licenceOneOf: options.licenceOneOf,
1175 languageOneOf: options.languageOneOf,
1176 tagsOneOf: options.tagsOneOf,
1177 tagsAllOf: options.tagsAllOf,
1179 filter: options.filter,
1180 start: options.start,
1181 count: options.count,
1183 startDate: options.startDate,
1184 endDate: options.endDate,
1185 originallyPublishedStartDate: options.originallyPublishedStartDate,
1186 originallyPublishedEndDate: options.originallyPublishedEndDate,
1188 durationMin: options.durationMin,
1189 durationMax: options.durationMax,
1191 search: options.search
1194 return VideoModel.getAvailableForApi(queryOptions)
1197 static countLocalLives () {
1203 [Op.ne]: VideoState.LIVE_ENDED
1208 return VideoModel.count(options)
1211 static countVideosUploadedByUserSince (userId: number, since: Date) {
1215 model: VideoChannelModel.unscoped(),
1219 model: AccountModel.unscoped(),
1223 model: UserModel.unscoped(),
1241 return VideoModel.unscoped().count(options)
1244 static countLivesOfAccount (accountId: number) {
1250 [Op.ne]: VideoState.LIVE_ENDED
1256 model: VideoChannelModel.unscoped(),
1264 return VideoModel.count(options)
1267 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1268 const where = buildWhereIdOrUUID(id)
1274 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1277 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1278 const where = buildWhereIdOrUUID(id)
1284 return VideoModel.scope([
1285 ScopeNames.WITH_THUMBNAILS,
1286 ScopeNames.WITH_BLACKLISTED
1290 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1293 where: buildWhereIdOrUUID(id),
1297 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1300 return ModelCache.Instance.doCache({
1301 cacheType: 'load-video-immutable-id',
1308 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1309 const where = buildWhereIdOrUUID(id)
1315 return VideoModel.scope([
1316 ScopeNames.WITH_BLACKLISTED,
1317 ScopeNames.WITH_USER_ID
1321 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1322 const where = buildWhereIdOrUUID(id)
1325 attributes: [ 'id' ],
1330 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1333 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1334 const where = buildWhereIdOrUUID(id)
1342 return VideoModel.scope([
1343 ScopeNames.WITH_WEBTORRENT_FILES,
1344 ScopeNames.WITH_STREAMING_PLAYLISTS,
1345 ScopeNames.WITH_THUMBNAILS
1349 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1356 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1359 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1360 const query: FindOptions = {
1367 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1370 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1372 const query: FindOptions = {
1379 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1382 return ModelCache.Instance.doCache({
1383 cacheType: 'load-video-immutable-url',
1390 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1391 const query: FindOptions = {
1398 return VideoModel.scope([
1399 ScopeNames.WITH_ACCOUNT_DETAILS,
1400 ScopeNames.WITH_WEBTORRENT_FILES,
1401 ScopeNames.WITH_STREAMING_PLAYLISTS,
1402 ScopeNames.WITH_THUMBNAILS,
1403 ScopeNames.WITH_BLACKLISTED
1407 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1408 const where = buildWhereIdOrUUID(id)
1411 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1416 const scopes: (string | ScopeOptions)[] = [
1417 ScopeNames.WITH_TAGS,
1418 ScopeNames.WITH_BLACKLISTED,
1419 ScopeNames.WITH_ACCOUNT_DETAILS,
1420 ScopeNames.WITH_SCHEDULED_UPDATE,
1421 ScopeNames.WITH_WEBTORRENT_FILES,
1422 ScopeNames.WITH_STREAMING_PLAYLISTS,
1423 ScopeNames.WITH_THUMBNAILS,
1424 ScopeNames.WITH_LIVE
1428 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1436 static loadForGetAPI (parameters: {
1440 }): Promise<MVideoDetails> {
1441 const { id, t, userId } = parameters
1442 const where = buildWhereIdOrUUID(id)
1445 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1450 const scopes: (string | ScopeOptions)[] = [
1451 ScopeNames.WITH_TAGS,
1452 ScopeNames.WITH_BLACKLISTED,
1453 ScopeNames.WITH_ACCOUNT_DETAILS,
1454 ScopeNames.WITH_SCHEDULED_UPDATE,
1455 ScopeNames.WITH_THUMBNAILS,
1456 ScopeNames.WITH_LIVE,
1457 ScopeNames.WITH_TRACKERS,
1458 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1459 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1463 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1471 static async getStats () {
1472 const totalLocalVideos = await VideoModel.count({
1478 let totalLocalVideoViews = await VideoModel.sum('views', {
1484 // Sequelize could return null...
1485 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1487 const { total: totalVideos } = await VideoModel.listForApi({
1490 sort: '-publishedAt',
1491 nsfw: buildNSFWFilter(),
1492 includeLocalVideos: true,
1498 totalLocalVideoViews,
1503 static incrementViews (id: number, views: number) {
1504 return VideoModel.increment('views', {
1512 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1513 // Instances only share videos
1514 const query = 'SELECT 1 FROM "videoShare" ' +
1515 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1516 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1520 type: QueryTypes.SELECT as QueryTypes.SELECT,
1521 bind: { followerActorId, videoId },
1525 return VideoModel.sequelize.query(query, options)
1526 .then(results => results.length === 1)
1529 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1532 channelId: videoChannel.id
1537 return VideoModel.update({ support: videoChannel.support }, options)
1540 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1542 attributes: [ 'id' ],
1544 channelId: videoChannel.id
1548 return VideoModel.findAll(query)
1549 .then(videos => videos.map(v => v.id))
1552 // threshold corresponds to how many video the field should have to be returned
1553 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1554 const serverActor = await getServerActor()
1555 const followerActorId = serverActor.id
1557 const queryOptions: BuildVideosQueryOptions = {
1558 attributes: [ `"${field}"` ],
1559 group: `GROUP BY "${field}"`,
1560 having: `HAVING COUNT("${field}") >= ${threshold}`,
1564 serverAccountId: serverActor.Account.id,
1566 includeLocalVideos: true
1569 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1571 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1572 .then(rows => rows.map(r => r[field]))
1575 static buildTrendingQuery (trendingDays: number) {
1579 model: VideoViewModel,
1583 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1589 private static async getAvailableForApi (
1590 options: BuildVideosQueryOptions,
1592 ): Promise<ResultList<VideoModel>> {
1593 function getCount () {
1594 if (countVideos !== true) return Promise.resolve(undefined)
1596 const countOptions = Object.assign({}, options, { isCount: true })
1597 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1599 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1600 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1603 function getModels () {
1604 if (options.count === 0) return Promise.resolve([])
1606 const { query, replacements, order } = buildListQuery(VideoModel, options)
1607 const queryModels = wrapForAPIResults(query, replacements, options, order)
1609 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1610 .then(rows => VideoModel.buildAPIResult(rows))
1613 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1621 private static buildAPIResult (rows: any[]) {
1622 const videosMemo: { [ id: number ]: VideoModel } = {}
1623 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1625 const thumbnailsDone = new Set<number>()
1626 const historyDone = new Set<number>()
1627 const videoFilesDone = new Set<number>()
1629 const videos: VideoModel[] = []
1631 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1632 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1633 const serverKeys = [ 'id', 'host' ]
1634 const videoFileKeys = [
1648 'videoStreamingPlaylistId'
1650 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1674 'originallyPublishedAt',
1679 const buildOpts = { raw: true }
1681 function buildActor (rowActor: any) {
1682 const avatarModel = rowActor.Avatar.id !== null
1683 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1686 const serverModel = rowActor.Server.id !== null
1687 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1690 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1691 actorModel.Avatar = avatarModel
1692 actorModel.Server = serverModel
1697 for (const row of rows) {
1698 if (!videosMemo[row.id]) {
1700 const channel = row.VideoChannel
1701 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1702 channelModel.Actor = buildActor(channel.Actor)
1704 const account = row.VideoChannel.Account
1705 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1706 accountModel.Actor = buildActor(account.Actor)
1708 channelModel.Account = accountModel
1710 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1711 videoModel.VideoChannel = channelModel
1713 videoModel.UserVideoHistories = []
1714 videoModel.Thumbnails = []
1715 videoModel.VideoFiles = []
1716 videoModel.VideoStreamingPlaylists = []
1718 videosMemo[row.id] = videoModel
1719 // Don't take object value to have a sorted array
1720 videos.push(videoModel)
1723 const videoModel = videosMemo[row.id]
1725 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1726 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1727 videoModel.UserVideoHistories.push(historyModel)
1729 historyDone.add(row.userVideoHistory.id)
1732 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1733 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1734 videoModel.Thumbnails.push(thumbnailModel)
1736 thumbnailsDone.add(row.Thumbnails.id)
1739 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1740 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1741 videoModel.VideoFiles.push(videoFileModel)
1743 videoFilesDone.add(row.VideoFiles.id)
1746 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1747 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1748 streamingPlaylist.VideoFiles = []
1750 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1752 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1755 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1756 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1758 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1759 streamingPlaylist.VideoFiles.push(videoFileModel)
1761 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1768 static getCategoryLabel (id: number) {
1769 return VIDEO_CATEGORIES[id] || 'Misc'
1772 static getLicenceLabel (id: number) {
1773 return VIDEO_LICENCES[id] || 'Unknown'
1776 static getLanguageLabel (id: string) {
1777 return VIDEO_LANGUAGES[id] || 'Unknown'
1780 static getPrivacyLabel (id: number) {
1781 return VIDEO_PRIVACIES[id] || 'Unknown'
1784 static getStateLabel (id: number) {
1785 return VIDEO_STATES[id] || 'Unknown'
1789 return !!this.VideoBlacklist
1793 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1796 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1797 // We first transcode to WebTorrent format, so try this array first
1798 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1799 const file = fun(this.VideoFiles, file => file.resolution)
1801 return Object.assign(file, { Video: this })
1804 // No webtorrent files, try with streaming playlist files
1805 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1806 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1808 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1809 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1815 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1816 return this.getQualityFileBy(maxBy)
1819 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1820 return this.getQualityFileBy(minBy)
1823 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1824 if (Array.isArray(this.VideoFiles) === false) return undefined
1826 const file = this.VideoFiles.find(f => f.resolution === resolution)
1827 if (!file) return undefined
1829 return Object.assign(file, { Video: this })
1832 hasWebTorrentFiles () {
1833 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1836 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1837 thumbnail.videoId = this.id
1839 const savedThumbnail = await thumbnail.save({ transaction })
1841 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1843 // Already have this thumbnail, skip
1844 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1846 this.Thumbnails.push(savedThumbnail)
1849 generateThumbnailName () {
1850 return uuidv4() + '.jpg'
1854 if (Array.isArray(this.Thumbnails) === false) return undefined
1856 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1859 generatePreviewName () {
1860 return uuidv4() + '.jpg'
1864 return !!this.getPreview()
1868 if (Array.isArray(this.Thumbnails) === false) return undefined
1870 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1874 return this.remote === false
1877 getWatchStaticPath () {
1878 return '/videos/watch/' + this.uuid
1881 getEmbedStaticPath () {
1882 return '/videos/embed/' + this.uuid
1885 getMiniatureStaticPath () {
1886 const thumbnail = this.getMiniature()
1887 if (!thumbnail) return null
1889 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1892 getPreviewStaticPath () {
1893 const preview = this.getPreview()
1894 if (!preview) return null
1896 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1897 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1900 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1901 return videoModelToFormattedJSON(this, options)
1904 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1905 return videoModelToFormattedDetailsJSON(this)
1908 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1909 let files: VideoFile[] = []
1911 if (Array.isArray(this.VideoFiles)) {
1912 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1913 files = files.concat(result)
1916 for (const p of (this.VideoStreamingPlaylists || [])) {
1917 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1918 files = files.concat(result)
1924 toActivityPubObject (this: MVideoAP): VideoObject {
1925 return videoModelToActivityPubObject(this)
1928 getTruncatedDescription () {
1929 if (!this.description) return null
1931 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1932 return peertubeTruncate(this.description, { length: maxLength })
1935 getMaxQualityResolution () {
1936 const file = this.getMaxQualityFile()
1937 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1938 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1940 return getVideoFileResolution(originalFilePath)
1943 getDescriptionAPIPath () {
1944 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1947 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1948 if (!this.VideoStreamingPlaylists) return undefined
1950 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1951 playlist.Video = this
1956 setHLSPlaylist (playlist: MStreamingPlaylist) {
1957 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1959 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1960 this.VideoStreamingPlaylists = toAdd
1964 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1965 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1969 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1970 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1971 return remove(filePath)
1972 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1975 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1976 const directoryPath = getHLSDirectory(this, isRedundancy)
1978 await remove(directoryPath)
1980 if (isRedundancy !== true) {
1981 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1982 streamingPlaylistWithFiles.Video = this
1984 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1985 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1988 // Remove physical files and torrents
1990 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
1996 if (this.isOwned()) return false
1998 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2001 hasPrivacyForFederation () {
2002 return isPrivacyForFederation(this.privacy)
2005 hasStateForFederation () {
2006 return isStateForFederation(this.state)
2009 isNewVideo (newPrivacy: VideoPrivacy) {
2010 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2014 this.changed('updatedAt', true)
2020 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2023 setPrivacy (newPrivacy: VideoPrivacy) {
2024 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2025 this.publishedAt = new Date()
2028 this.privacy = newPrivacy
2032 return this.privacy === VideoPrivacy.PRIVATE ||
2033 this.privacy === VideoPrivacy.UNLISTED ||
2034 this.privacy === VideoPrivacy.INTERNAL
2037 async publishIfNeededAndSave (t: Transaction) {
2038 if (this.state !== VideoState.PUBLISHED) {
2039 this.state = VideoState.PUBLISHED
2040 this.publishedAt = new Date()
2041 await this.save({ transaction: t })
2049 getBandwidthBits (videoFile: MVideoFile) {
2050 return Math.ceil((videoFile.size * 8) / this.duration)
2054 if (this.isOwned()) {
2056 WEBSERVER.URL + '/tracker/announce',
2057 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2061 return this.Trackers.map(t => t.url)