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, VideoRateType } 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' ] },
431 { name: 'views', order: 'DESC' },
432 { name: 'id', order: 'ASC' }
435 { fields: [ 'channelId' ] },
437 fields: [ 'originallyPublishedAt' ],
439 originallyPublishedAt: {
445 fields: [ 'category' ], // We don't care videos with an unknown category
453 fields: [ 'licence' ], // We don't care videos with an unknown licence
461 fields: [ 'language' ], // We don't care videos with an unknown language
469 fields: [ 'nsfw' ], // Most of the videos are not NSFW
475 fields: [ 'remote' ], // Only index local videos
490 export class VideoModel extends Model {
493 @Default(DataType.UUIDV4)
495 @Column(DataType.UUID)
499 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
505 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
511 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
517 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
522 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
524 privacy: VideoPrivacy
527 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
533 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
534 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
539 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
540 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
544 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
579 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
580 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
585 commentsEnabled: boolean
589 downloadEnabled: boolean
593 waitTranscoding: boolean
597 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
608 @Default(DataType.NOW)
615 originallyPublishedAt: Date
617 @ForeignKey(() => VideoChannelModel)
621 @BelongsTo(() => VideoChannelModel, {
627 VideoChannel: VideoChannelModel
629 @BelongsToMany(() => TagModel, {
630 foreignKey: 'videoId',
631 through: () => VideoTagModel,
636 @BelongsToMany(() => TrackerModel, {
637 foreignKey: 'videoId',
638 through: () => VideoTrackerModel,
641 Trackers: TrackerModel[]
643 @HasMany(() => ThumbnailModel, {
651 Thumbnails: ThumbnailModel[]
653 @HasMany(() => VideoPlaylistElementModel, {
660 VideoPlaylistElements: VideoPlaylistElementModel[]
662 @HasMany(() => VideoAbuseModel, {
669 VideoAbuses: VideoAbuseModel[]
671 @HasMany(() => VideoFileModel, {
679 VideoFiles: VideoFileModel[]
681 @HasMany(() => VideoStreamingPlaylistModel, {
689 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
691 @HasMany(() => VideoShareModel, {
698 VideoShares: VideoShareModel[]
700 @HasMany(() => AccountVideoRateModel, {
707 AccountVideoRates: AccountVideoRateModel[]
709 @HasMany(() => VideoCommentModel, {
717 VideoComments: VideoCommentModel[]
719 @HasMany(() => VideoViewModel, {
726 VideoViews: VideoViewModel[]
728 @HasMany(() => UserVideoHistoryModel, {
735 UserVideoHistories: UserVideoHistoryModel[]
737 @HasOne(() => ScheduleVideoUpdateModel, {
744 ScheduleVideoUpdate: ScheduleVideoUpdateModel
746 @HasOne(() => VideoBlacklistModel, {
753 VideoBlacklist: VideoBlacklistModel
755 @HasOne(() => VideoLiveModel, {
762 VideoLive: VideoLiveModel
764 @HasOne(() => VideoImportModel, {
771 VideoImport: VideoImportModel
773 @HasMany(() => VideoCaptionModel, {
780 ['separate' as any]: true
782 VideoCaptions: VideoCaptionModel[]
785 static async sendDelete (instance: MVideoAccountLight, options) {
786 if (instance.isOwned()) {
787 if (!instance.VideoChannel) {
788 instance.VideoChannel = await instance.$get('VideoChannel', {
793 transaction: options.transaction
794 }) as MChannelAccountDefault
797 return sendDeleteVideo(instance, options.transaction)
804 static async removeFiles (instance: VideoModel) {
805 const tasks: Promise<any>[] = []
807 logger.info('Removing files of video %s.', instance.url)
809 if (instance.isOwned()) {
810 if (!Array.isArray(instance.VideoFiles)) {
811 instance.VideoFiles = await instance.$get('VideoFiles')
814 // Remove physical files and torrents
815 instance.VideoFiles.forEach(file => {
816 tasks.push(instance.removeFile(file))
817 tasks.push(file.removeTorrent())
820 // Remove playlists file
821 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
822 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
825 for (const p of instance.VideoStreamingPlaylists) {
826 tasks.push(instance.removeStreamingPlaylistFiles(p))
830 // Do not wait video deletion because we could be in a transaction
833 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
840 static stopLiveIfNeeded (instance: VideoModel) {
841 if (!instance.isLive) return
843 logger.info('Stopping live of video %s after video deletion.', instance.uuid)
845 return LiveManager.Instance.stopSessionOf(instance.id)
849 static invalidateCache (instance: VideoModel) {
850 ModelCache.Instance.invalidateCache('video', instance.id)
854 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
855 const tasks: Promise<any>[] = []
857 if (!Array.isArray(instance.VideoAbuses)) {
858 instance.VideoAbuses = await instance.$get('VideoAbuses')
860 if (instance.VideoAbuses.length === 0) return undefined
863 logger.info('Saving video abuses details of video %s.', instance.url)
865 const details = instance.toFormattedDetailsJSON()
867 for (const abuse of instance.VideoAbuses) {
868 abuse.deletedVideo = details
869 tasks.push(abuse.save({ transaction: options.transaction }))
874 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
880 static listLocal (): Promise<MVideo[]> {
887 return VideoModel.findAll(query)
890 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
891 function getRawQuery (select: string) {
892 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
893 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
894 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
895 'WHERE "Account"."actorId" = ' + actorId
896 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
897 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
898 'WHERE "VideoShare"."actorId" = ' + actorId
900 return `(${queryVideo}) UNION (${queryVideoShare})`
903 const rawQuery = getRawQuery('"Video"."id"')
904 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
910 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
913 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
915 [Op.or]: getPrivaciesForFederation()
919 attributes: [ 'language', 'fileUrl' ],
920 model: VideoCaptionModel.unscoped(),
924 attributes: [ 'id', 'url' ],
925 model: VideoShareModel.unscoped(),
927 // We only want videos shared by this actor
942 attributes: [ 'id', 'url' ],
943 model: ActorModel.unscoped()
948 model: VideoChannelModel.unscoped(),
952 attributes: [ 'name' ],
953 model: AccountModel.unscoped(),
957 attributes: [ 'id', 'url', 'followersUrl' ],
958 model: ActorModel.unscoped(),
964 attributes: [ 'id', 'url', 'followersUrl' ],
965 model: ActorModel.unscoped(),
971 model: VideoStreamingPlaylistModel.unscoped(),
975 model: VideoFileModel,
980 VideoLiveModel.unscoped(),
986 return Bluebird.all([
987 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
988 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
989 ]).then(([ rows, totals ]) => {
990 // totals: totalVideos + totalVideoShares
992 let totalVideoShares = 0
993 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
994 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
996 const total = totalVideos + totalVideoShares
1004 static async listPublishedLiveIds () {
1006 attributes: [ 'id' ],
1009 state: VideoState.PUBLISHED
1013 const result = await VideoModel.findAll(options)
1015 return result.map(v => v.id)
1018 static listUserVideosForApi (options: {
1025 const { accountId, start, count, sort, search } = options
1027 function buildBaseQuery (): FindOptions {
1031 order: getVideoSort(sort),
1034 model: VideoChannelModel,
1038 model: AccountModel,
1050 baseQuery = Object.assign(baseQuery, {
1053 [Op.iLike]: '%' + search + '%'
1062 const countQuery = buildBaseQuery()
1063 const findQuery = buildBaseQuery()
1065 const findScopes: (string | ScopeOptions)[] = [
1066 ScopeNames.WITH_SCHEDULED_UPDATE,
1067 ScopeNames.WITH_BLACKLISTED,
1068 ScopeNames.WITH_THUMBNAILS
1071 return Promise.all([
1072 VideoModel.count(countQuery),
1073 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1074 ]).then(([ count, rows ]) => {
1082 static async listForApi (options: {
1087 includeLocalVideos: boolean
1089 categoryOneOf?: number[]
1090 licenceOneOf?: number[]
1091 languageOneOf?: string[]
1092 tagsOneOf?: string[]
1093 tagsAllOf?: string[]
1094 filter?: VideoFilter
1096 videoChannelId?: number
1097 followerActorId?: number
1098 videoPlaylistId?: number
1099 trendingDays?: number
1100 user?: MUserAccountId
1101 historyOfUser?: MUserId
1102 countVideos?: boolean
1105 if ((options.filter === 'all-local' || options.filter === 'all') && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1106 throw new Error('Try to filter all-local but no user has not the see all videos right')
1109 const trendingDays = options.sort.endsWith('trending')
1110 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1112 let trendingAlgorithm
1113 if (options.sort.endsWith('hot')) trendingAlgorithm = 'hot'
1114 if (options.sort.endsWith('best')) trendingAlgorithm = 'best'
1116 const serverActor = await getServerActor()
1118 // followerActorId === null has a meaning, so just check undefined
1119 const followerActorId = options.followerActorId !== undefined
1120 ? options.followerActorId
1123 const queryOptions = {
1124 start: options.start,
1125 count: options.count,
1128 serverAccountId: serverActor.Account.id,
1130 categoryOneOf: options.categoryOneOf,
1131 licenceOneOf: options.licenceOneOf,
1132 languageOneOf: options.languageOneOf,
1133 tagsOneOf: options.tagsOneOf,
1134 tagsAllOf: options.tagsAllOf,
1135 filter: options.filter,
1136 withFiles: options.withFiles,
1137 accountId: options.accountId,
1138 videoChannelId: options.videoChannelId,
1139 videoPlaylistId: options.videoPlaylistId,
1140 includeLocalVideos: options.includeLocalVideos,
1142 historyOfUser: options.historyOfUser,
1145 search: options.search
1148 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1151 static async searchAndPopulateAccountAndServer (options: {
1152 includeLocalVideos: boolean
1157 startDate?: string // ISO 8601
1158 endDate?: string // ISO 8601
1159 originallyPublishedStartDate?: string
1160 originallyPublishedEndDate?: string
1162 categoryOneOf?: number[]
1163 licenceOneOf?: number[]
1164 languageOneOf?: string[]
1165 tagsOneOf?: string[]
1166 tagsAllOf?: string[]
1167 durationMin?: number // seconds
1168 durationMax?: number // seconds
1169 user?: MUserAccountId
1170 filter?: VideoFilter
1172 const serverActor = await getServerActor()
1173 const queryOptions = {
1174 followerActorId: serverActor.id,
1175 serverAccountId: serverActor.Account.id,
1176 includeLocalVideos: options.includeLocalVideos,
1178 categoryOneOf: options.categoryOneOf,
1179 licenceOneOf: options.licenceOneOf,
1180 languageOneOf: options.languageOneOf,
1181 tagsOneOf: options.tagsOneOf,
1182 tagsAllOf: options.tagsAllOf,
1184 filter: options.filter,
1185 start: options.start,
1186 count: options.count,
1188 startDate: options.startDate,
1189 endDate: options.endDate,
1190 originallyPublishedStartDate: options.originallyPublishedStartDate,
1191 originallyPublishedEndDate: options.originallyPublishedEndDate,
1193 durationMin: options.durationMin,
1194 durationMax: options.durationMax,
1196 search: options.search
1199 return VideoModel.getAvailableForApi(queryOptions)
1202 static countLocalLives () {
1208 [Op.ne]: VideoState.LIVE_ENDED
1213 return VideoModel.count(options)
1216 static countVideosUploadedByUserSince (userId: number, since: Date) {
1220 model: VideoChannelModel.unscoped(),
1224 model: AccountModel.unscoped(),
1228 model: UserModel.unscoped(),
1246 return VideoModel.unscoped().count(options)
1249 static countLivesOfAccount (accountId: number) {
1255 [Op.ne]: VideoState.LIVE_ENDED
1261 model: VideoChannelModel.unscoped(),
1269 return VideoModel.count(options)
1272 static load (id: number | string, t?: Transaction): Promise<MVideoThumbnail> {
1273 const where = buildWhereIdOrUUID(id)
1279 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1282 static loadWithBlacklist (id: number | string, t?: Transaction): Promise<MVideoThumbnailBlacklist> {
1283 const where = buildWhereIdOrUUID(id)
1289 return VideoModel.scope([
1290 ScopeNames.WITH_THUMBNAILS,
1291 ScopeNames.WITH_BLACKLISTED
1295 static loadImmutableAttributes (id: number | string, t?: Transaction): Promise<MVideoImmutable> {
1298 where: buildWhereIdOrUUID(id),
1302 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1305 return ModelCache.Instance.doCache({
1306 cacheType: 'load-video-immutable-id',
1313 static loadWithRights (id: number | string, t?: Transaction): Promise<MVideoWithRights> {
1314 const where = buildWhereIdOrUUID(id)
1320 return VideoModel.scope([
1321 ScopeNames.WITH_BLACKLISTED,
1322 ScopeNames.WITH_USER_ID
1326 static loadOnlyId (id: number | string, t?: Transaction): Promise<MVideoIdThumbnail> {
1327 const where = buildWhereIdOrUUID(id)
1330 attributes: [ 'id' ],
1335 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1338 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Promise<MVideoWithAllFiles> {
1339 const where = buildWhereIdOrUUID(id)
1347 return VideoModel.scope([
1348 ScopeNames.WITH_WEBTORRENT_FILES,
1349 ScopeNames.WITH_STREAMING_PLAYLISTS,
1350 ScopeNames.WITH_THUMBNAILS
1354 static loadByUUID (uuid: string): Promise<MVideoThumbnail> {
1361 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1364 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoThumbnail> {
1365 const query: FindOptions = {
1372 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1375 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Promise<MVideoImmutable> {
1377 const query: FindOptions = {
1384 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1387 return ModelCache.Instance.doCache({
1388 cacheType: 'load-video-immutable-url',
1395 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Promise<MVideoAccountLightBlacklistAllFiles> {
1396 const query: FindOptions = {
1403 return VideoModel.scope([
1404 ScopeNames.WITH_ACCOUNT_DETAILS,
1405 ScopeNames.WITH_WEBTORRENT_FILES,
1406 ScopeNames.WITH_STREAMING_PLAYLISTS,
1407 ScopeNames.WITH_THUMBNAILS,
1408 ScopeNames.WITH_BLACKLISTED
1412 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Promise<MVideoFullLight> {
1413 const where = buildWhereIdOrUUID(id)
1416 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1421 const scopes: (string | ScopeOptions)[] = [
1422 ScopeNames.WITH_TAGS,
1423 ScopeNames.WITH_BLACKLISTED,
1424 ScopeNames.WITH_ACCOUNT_DETAILS,
1425 ScopeNames.WITH_SCHEDULED_UPDATE,
1426 ScopeNames.WITH_WEBTORRENT_FILES,
1427 ScopeNames.WITH_STREAMING_PLAYLISTS,
1428 ScopeNames.WITH_THUMBNAILS,
1429 ScopeNames.WITH_LIVE
1433 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1441 static loadForGetAPI (parameters: {
1445 }): Promise<MVideoDetails> {
1446 const { id, t, userId } = parameters
1447 const where = buildWhereIdOrUUID(id)
1450 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1455 const scopes: (string | ScopeOptions)[] = [
1456 ScopeNames.WITH_TAGS,
1457 ScopeNames.WITH_BLACKLISTED,
1458 ScopeNames.WITH_ACCOUNT_DETAILS,
1459 ScopeNames.WITH_SCHEDULED_UPDATE,
1460 ScopeNames.WITH_THUMBNAILS,
1461 ScopeNames.WITH_LIVE,
1462 ScopeNames.WITH_TRACKERS,
1463 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1464 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1468 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1476 static async getStats () {
1477 const totalLocalVideos = await VideoModel.count({
1483 let totalLocalVideoViews = await VideoModel.sum('views', {
1489 // Sequelize could return null...
1490 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1492 const { total: totalVideos } = await VideoModel.listForApi({
1495 sort: '-publishedAt',
1496 nsfw: buildNSFWFilter(),
1497 includeLocalVideos: true,
1503 totalLocalVideoViews,
1508 static incrementViews (id: number, views: number) {
1509 return VideoModel.increment('views', {
1517 static updateRatesOf (videoId: number, type: VideoRateType, t: Transaction) {
1518 const field = type === 'like'
1522 const rawQuery = `UPDATE "video" SET "${field}" = ` +
1524 'SELECT COUNT(id) FROM "accountVideoRate" WHERE "accountVideoRate"."videoId" = "video"."id" AND type = :rateType' +
1526 'WHERE "video"."id" = :videoId'
1528 return AccountVideoRateModel.sequelize.query(rawQuery, {
1530 replacements: { videoId, rateType: type },
1531 type: QueryTypes.UPDATE
1535 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1536 // Instances only share videos
1537 const query = 'SELECT 1 FROM "videoShare" ' +
1538 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1539 'WHERE "actorFollow"."actorId" = $followerActorId AND "actorFollow"."state" = \'accepted\' AND "videoShare"."videoId" = $videoId ' +
1543 type: QueryTypes.SELECT as QueryTypes.SELECT,
1544 bind: { followerActorId, videoId },
1548 return VideoModel.sequelize.query(query, options)
1549 .then(results => results.length === 1)
1552 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1555 channelId: videoChannel.id
1560 return VideoModel.update({ support: videoChannel.support }, options)
1563 static getAllIdsFromChannel (videoChannel: MChannelId): Promise<number[]> {
1565 attributes: [ 'id' ],
1567 channelId: videoChannel.id
1571 return VideoModel.findAll(query)
1572 .then(videos => videos.map(v => v.id))
1575 // threshold corresponds to how many video the field should have to be returned
1576 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1577 const serverActor = await getServerActor()
1578 const followerActorId = serverActor.id
1580 const queryOptions: BuildVideosQueryOptions = {
1581 attributes: [ `"${field}"` ],
1582 group: `GROUP BY "${field}"`,
1583 having: `HAVING COUNT("${field}") >= ${threshold}`,
1587 serverAccountId: serverActor.Account.id,
1589 includeLocalVideos: true
1592 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1594 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1595 .then(rows => rows.map(r => r[field]))
1598 static buildTrendingQuery (trendingDays: number) {
1602 model: VideoViewModel,
1606 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1612 private static async getAvailableForApi (
1613 options: BuildVideosQueryOptions,
1615 ): Promise<ResultList<VideoModel>> {
1616 function getCount () {
1617 if (countVideos !== true) return Promise.resolve(undefined)
1619 const countOptions = Object.assign({}, options, { isCount: true })
1620 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1622 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1623 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1626 function getModels () {
1627 if (options.count === 0) return Promise.resolve([])
1629 const { query, replacements, order } = buildListQuery(VideoModel, options)
1630 const queryModels = wrapForAPIResults(query, replacements, options, order)
1632 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1633 .then(rows => VideoModel.buildAPIResult(rows))
1636 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1644 private static buildAPIResult (rows: any[]) {
1645 const videosMemo: { [ id: number ]: VideoModel } = {}
1646 const videoStreamingPlaylistMemo: { [ id: number ]: VideoStreamingPlaylistModel } = {}
1648 const thumbnailsDone = new Set<number>()
1649 const historyDone = new Set<number>()
1650 const videoFilesDone = new Set<number>()
1652 const videos: VideoModel[] = []
1654 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1655 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1656 const serverKeys = [ 'id', 'host' ]
1657 const videoFileKeys = [
1671 'videoStreamingPlaylistId'
1673 const videoStreamingPlaylistKeys = [ 'id', 'type', 'playlistUrl' ]
1697 'originallyPublishedAt',
1702 const buildOpts = { raw: true }
1704 function buildActor (rowActor: any) {
1705 const avatarModel = rowActor.Avatar.id !== null
1706 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys), buildOpts)
1709 const serverModel = rowActor.Server.id !== null
1710 ? new ServerModel(pick(rowActor.Server, serverKeys), buildOpts)
1713 const actorModel = new ActorModel(pick(rowActor, actorKeys), buildOpts)
1714 actorModel.Avatar = avatarModel
1715 actorModel.Server = serverModel
1720 for (const row of rows) {
1721 if (!videosMemo[row.id]) {
1723 const channel = row.VideoChannel
1724 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]), buildOpts)
1725 channelModel.Actor = buildActor(channel.Actor)
1727 const account = row.VideoChannel.Account
1728 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]), buildOpts)
1729 accountModel.Actor = buildActor(account.Actor)
1731 channelModel.Account = accountModel
1733 const videoModel = new VideoModel(pick(row, videoKeys), buildOpts)
1734 videoModel.VideoChannel = channelModel
1736 videoModel.UserVideoHistories = []
1737 videoModel.Thumbnails = []
1738 videoModel.VideoFiles = []
1739 videoModel.VideoStreamingPlaylists = []
1741 videosMemo[row.id] = videoModel
1742 // Don't take object value to have a sorted array
1743 videos.push(videoModel)
1746 const videoModel = videosMemo[row.id]
1748 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1749 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]), buildOpts)
1750 videoModel.UserVideoHistories.push(historyModel)
1752 historyDone.add(row.userVideoHistory.id)
1755 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1756 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]), buildOpts)
1757 videoModel.Thumbnails.push(thumbnailModel)
1759 thumbnailsDone.add(row.Thumbnails.id)
1762 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1763 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys), buildOpts)
1764 videoModel.VideoFiles.push(videoFileModel)
1766 videoFilesDone.add(row.VideoFiles.id)
1769 if (row.VideoStreamingPlaylists?.id && !videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]) {
1770 const streamingPlaylist = new VideoStreamingPlaylistModel(pick(row.VideoStreamingPlaylists, videoStreamingPlaylistKeys), buildOpts)
1771 streamingPlaylist.VideoFiles = []
1773 videoModel.VideoStreamingPlaylists.push(streamingPlaylist)
1775 videoStreamingPlaylistMemo[streamingPlaylist.id] = streamingPlaylist
1778 if (row.VideoStreamingPlaylists?.VideoFiles?.id && !videoFilesDone.has(row.VideoStreamingPlaylists.VideoFiles.id)) {
1779 const streamingPlaylist = videoStreamingPlaylistMemo[row.VideoStreamingPlaylists.id]
1781 const videoFileModel = new VideoFileModel(pick(row.VideoStreamingPlaylists.VideoFiles, videoFileKeys), buildOpts)
1782 streamingPlaylist.VideoFiles.push(videoFileModel)
1784 videoFilesDone.add(row.VideoStreamingPlaylists.VideoFiles.id)
1791 static getCategoryLabel (id: number) {
1792 return VIDEO_CATEGORIES[id] || 'Misc'
1795 static getLicenceLabel (id: number) {
1796 return VIDEO_LICENCES[id] || 'Unknown'
1799 static getLanguageLabel (id: string) {
1800 return VIDEO_LANGUAGES[id] || 'Unknown'
1803 static getPrivacyLabel (id: number) {
1804 return VIDEO_PRIVACIES[id] || 'Unknown'
1807 static getStateLabel (id: number) {
1808 return VIDEO_STATES[id] || 'Unknown'
1812 return !!this.VideoBlacklist
1816 return this.VideoChannel.Account.Actor.Server?.isBlocked() || this.VideoChannel.Account.isBlocked()
1819 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1820 // We first transcode to WebTorrent format, so try this array first
1821 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1822 const file = fun(this.VideoFiles, file => file.resolution)
1824 return Object.assign(file, { Video: this })
1827 // No webtorrent files, try with streaming playlist files
1828 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1829 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1831 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1832 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1838 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1839 return this.getQualityFileBy(maxBy)
1842 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1843 return this.getQualityFileBy(minBy)
1846 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1847 if (Array.isArray(this.VideoFiles) === false) return undefined
1849 const file = this.VideoFiles.find(f => f.resolution === resolution)
1850 if (!file) return undefined
1852 return Object.assign(file, { Video: this })
1855 hasWebTorrentFiles () {
1856 return Array.isArray(this.VideoFiles) === true && this.VideoFiles.length !== 0
1859 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1860 thumbnail.videoId = this.id
1862 const savedThumbnail = await thumbnail.save({ transaction })
1864 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1866 // Already have this thumbnail, skip
1867 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1869 this.Thumbnails.push(savedThumbnail)
1872 generateThumbnailName () {
1873 return uuidv4() + '.jpg'
1877 if (Array.isArray(this.Thumbnails) === false) return undefined
1879 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1882 generatePreviewName () {
1883 return uuidv4() + '.jpg'
1887 return !!this.getPreview()
1891 if (Array.isArray(this.Thumbnails) === false) return undefined
1893 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1897 return this.remote === false
1900 getWatchStaticPath () {
1901 return '/videos/watch/' + this.uuid
1904 getEmbedStaticPath () {
1905 return '/videos/embed/' + this.uuid
1908 getMiniatureStaticPath () {
1909 const thumbnail = this.getMiniature()
1910 if (!thumbnail) return null
1912 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1915 getPreviewStaticPath () {
1916 const preview = this.getPreview()
1917 if (!preview) return null
1919 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1920 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1923 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1924 return videoModelToFormattedJSON(this, options)
1927 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1928 return videoModelToFormattedDetailsJSON(this)
1931 getFormattedVideoFilesJSON (includeMagnet = true): VideoFile[] {
1932 let files: VideoFile[] = []
1934 if (Array.isArray(this.VideoFiles)) {
1935 const result = videoFilesModelToFormattedJSON(this, this.VideoFiles, includeMagnet)
1936 files = files.concat(result)
1939 for (const p of (this.VideoStreamingPlaylists || [])) {
1940 const result = videoFilesModelToFormattedJSON(this, p.VideoFiles, includeMagnet)
1941 files = files.concat(result)
1947 toActivityPubObject (this: MVideoAP): VideoObject {
1948 return videoModelToActivityPubObject(this)
1951 getTruncatedDescription () {
1952 if (!this.description) return null
1954 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1955 return peertubeTruncate(this.description, { length: maxLength })
1958 getMaxQualityResolution () {
1959 const file = this.getMaxQualityFile()
1960 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1961 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1963 return getVideoFileResolution(originalFilePath)
1966 getDescriptionAPIPath () {
1967 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1970 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1971 if (!this.VideoStreamingPlaylists) return undefined
1973 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1974 playlist.Video = this
1979 setHLSPlaylist (playlist: MStreamingPlaylist) {
1980 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1982 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1983 this.VideoStreamingPlaylists = toAdd
1987 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1988 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1992 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1993 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1994 return remove(filePath)
1995 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1998 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1999 const directoryPath = getHLSDirectory(this, isRedundancy)
2001 await remove(directoryPath)
2003 if (isRedundancy !== true) {
2004 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
2005 streamingPlaylistWithFiles.Video = this
2007 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
2008 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
2011 // Remove physical files and torrents
2013 streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent())
2019 if (this.isOwned()) return false
2021 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2024 hasPrivacyForFederation () {
2025 return isPrivacyForFederation(this.privacy)
2028 hasStateForFederation () {
2029 return isStateForFederation(this.state)
2032 isNewVideo (newPrivacy: VideoPrivacy) {
2033 return this.hasPrivacyForFederation() === false && isPrivacyForFederation(newPrivacy) === true
2037 this.changed('updatedAt', true)
2043 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2046 setPrivacy (newPrivacy: VideoPrivacy) {
2047 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2048 this.publishedAt = new Date()
2051 this.privacy = newPrivacy
2055 return this.privacy === VideoPrivacy.PRIVATE ||
2056 this.privacy === VideoPrivacy.UNLISTED ||
2057 this.privacy === VideoPrivacy.INTERNAL
2060 async publishIfNeededAndSave (t: Transaction) {
2061 if (this.state !== VideoState.PUBLISHED) {
2062 this.state = VideoState.PUBLISHED
2063 this.publishedAt = new Date()
2064 await this.save({ transaction: t })
2072 getBandwidthBits (videoFile: MVideoFile) {
2073 return Math.ceil((videoFile.size * 8) / this.duration)
2077 if (this.isOwned()) {
2079 WEBSERVER.URL + '/tracker/announce',
2080 WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'
2084 return this.Trackers.map(t => t.url)