1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy, pick } from 'lodash'
3 import { join } from 'path'
4 import { FindOptions, IncludeOptions, Op, QueryTypes, ScopeOptions, Sequelize, Transaction, WhereOptions } from 'sequelize'
25 } from 'sequelize-typescript'
26 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
27 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
28 import { Video, VideoDetails } from '../../../shared/models/videos'
29 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
30 import { peertubeTruncate } from '../../helpers/core-utils'
31 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
32 import { isBooleanValid } from '../../helpers/custom-validators/misc'
35 isVideoDescriptionValid,
43 } from '../../helpers/custom-validators/videos'
44 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
45 import { logger } from '../../helpers/logger'
52 STATIC_DOWNLOAD_PATHS,
60 } from '../../initializers/constants'
61 import { sendDeleteVideo } from '../../lib/activitypub/send'
62 import { AccountModel } from '../account/account'
63 import { AccountVideoRateModel } from '../account/account-video-rate'
64 import { ActorModel } from '../activitypub/actor'
65 import { AvatarModel } from '../avatar/avatar'
66 import { ServerModel } from '../server/server'
67 import { buildTrigramSearchIndex, buildWhereIdOrUUID, getVideoSort, isOutdated, throwIfNotValid } from '../utils'
68 import { TagModel } from './tag'
69 import { VideoAbuseModel } from './video-abuse'
70 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
71 import { VideoCommentModel } from './video-comment'
72 import { VideoFileModel } from './video-file'
73 import { VideoShareModel } from './video-share'
74 import { VideoTagModel } from './video-tag'
75 import { ScheduleVideoUpdateModel } from './schedule-video-update'
76 import { VideoCaptionModel } from './video-caption'
77 import { VideoBlacklistModel } from './video-blacklist'
78 import { remove } from 'fs-extra'
79 import { VideoViewModel } from './video-views'
80 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
82 videoFilesModelToFormattedJSON,
83 VideoFormattingJSONOptions,
84 videoModelToActivityPubObject,
85 videoModelToFormattedDetailsJSON,
86 videoModelToFormattedJSON
87 } from './video-format-utils'
88 import { UserVideoHistoryModel } from '../account/user-video-history'
89 import { VideoImportModel } from './video-import'
90 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
91 import { VideoPlaylistElementModel } from './video-playlist-element'
92 import { CONFIG } from '../../initializers/config'
93 import { ThumbnailModel } from './thumbnail'
94 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
95 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
98 MChannelAccountDefault,
101 MStreamingPlaylistFilesVideo,
105 MVideoAccountLightBlacklistAllFiles,
110 MVideoFormattableDetails,
116 MVideoThumbnailBlacklist,
120 } from '../../typings/models'
121 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
122 import { MThumbnail } from '../../typings/models/video/thumbnail'
123 import { VideoFile } from '@shared/models/videos/video-file.model'
124 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
125 import { ModelCache } from '@server/models/model-cache'
126 import { buildListQuery, BuildVideosQueryOptions, wrapForAPIResults } from './video-query-builder'
127 import { buildNSFWFilter } from '@server/helpers/express-utils'
128 import { getServerActor } from '@server/models/application/application'
130 export enum ScopeNames {
131 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
133 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
134 WITH_TAGS = 'WITH_TAGS',
135 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
136 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
137 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
138 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
139 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
140 WITH_USER_ID = 'WITH_USER_ID',
141 WITH_IMMUTABLE_ATTRIBUTES = 'WITH_IMMUTABLE_ATTRIBUTES',
142 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
145 export type ForAPIOptions = {
148 videoPlaylistId?: number
152 withAccountBlockerIds?: number[]
155 export type AvailableForListIDsOptions = {
156 serverAccountId: number
157 followerActorId: number
158 includeLocalVideos: boolean
160 attributesType?: 'none' | 'id' | 'all'
163 categoryOneOf?: number[]
165 licenceOneOf?: number[]
166 languageOneOf?: string[]
173 videoChannelId?: number
175 videoPlaylistId?: number
177 trendingDays?: number
178 user?: MUserAccountId
179 historyOfUser?: MUserId
181 baseWhere?: WhereOptions[]
185 [ScopeNames.WITH_IMMUTABLE_ATTRIBUTES]: {
186 attributes: [ 'id', 'url', 'uuid', 'remote' ]
188 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
189 const query: FindOptions = {
192 model: VideoChannelModel.scope({
194 VideoChannelScopeNames.SUMMARY, {
196 withAccountBlockerIds: options.withAccountBlockerIds
203 attributes: [ 'type', 'filename' ],
204 model: ThumbnailModel,
218 if (options.withFiles === true) {
220 model: VideoFileModel,
225 if (options.videoPlaylistId) {
227 model: VideoPlaylistElementModel.unscoped(),
230 videoPlaylistId: options.videoPlaylistId
237 [ScopeNames.WITH_THUMBNAILS]: {
240 model: ThumbnailModel,
245 [ScopeNames.WITH_USER_ID]: {
248 attributes: [ 'accountId' ],
249 model: VideoChannelModel.unscoped(),
253 attributes: [ 'userId' ],
254 model: AccountModel.unscoped(),
261 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
264 model: VideoChannelModel.unscoped(),
269 exclude: [ 'privateKey', 'publicKey' ]
271 model: ActorModel.unscoped(),
275 attributes: [ 'host' ],
276 model: ServerModel.unscoped(),
280 model: AvatarModel.unscoped(),
286 model: AccountModel.unscoped(),
290 model: ActorModel.unscoped(),
292 exclude: [ 'privateKey', 'publicKey' ]
297 attributes: [ 'host' ],
298 model: ServerModel.unscoped(),
302 model: AvatarModel.unscoped(),
313 [ScopeNames.WITH_TAGS]: {
314 include: [ TagModel ]
316 [ScopeNames.WITH_BLACKLISTED]: {
319 attributes: [ 'id', 'reason', 'unfederated' ],
320 model: VideoBlacklistModel,
325 [ScopeNames.WITH_WEBTORRENT_FILES]: (withRedundancies = false) => {
326 let subInclude: any[] = []
328 if (withRedundancies === true) {
331 attributes: [ 'fileUrl' ],
332 model: VideoRedundancyModel.unscoped(),
341 model: VideoFileModel,
342 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
349 [ScopeNames.WITH_STREAMING_PLAYLISTS]: (withRedundancies = false) => {
350 const subInclude: IncludeOptions[] = [
352 model: VideoFileModel,
357 if (withRedundancies === true) {
359 attributes: [ 'fileUrl' ],
360 model: VideoRedundancyModel.unscoped(),
368 model: VideoStreamingPlaylistModel.unscoped(),
369 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
376 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
379 model: ScheduleVideoUpdateModel.unscoped(),
384 [ScopeNames.WITH_USER_HISTORY]: (userId: number) => {
388 attributes: [ 'currentTime' ],
389 model: UserVideoHistoryModel.unscoped(),
402 buildTrigramSearchIndex('video_name_trigram', 'name'),
404 { fields: [ 'createdAt' ] },
407 { name: 'publishedAt', order: 'DESC' },
408 { name: 'id', order: 'ASC' }
411 { fields: [ 'duration' ] },
412 { fields: [ 'views' ] },
413 { fields: [ 'channelId' ] },
415 fields: [ 'originallyPublishedAt' ],
417 originallyPublishedAt: {
423 fields: [ 'category' ], // We don't care videos with an unknown category
431 fields: [ 'licence' ], // We don't care videos with an unknown licence
439 fields: [ 'language' ], // We don't care videos with an unknown language
447 fields: [ 'nsfw' ], // Most of the videos are not NSFW
453 fields: [ 'remote' ], // Only index local videos
468 export class VideoModel extends Model<VideoModel> {
471 @Default(DataType.UUIDV4)
473 @Column(DataType.UUID)
477 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
483 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
489 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
495 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
496 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
500 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
505 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
511 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
512 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
517 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
522 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
552 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
553 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
558 commentsEnabled: boolean
562 downloadEnabled: boolean
566 waitTranscoding: boolean
570 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
581 @Default(DataType.NOW)
588 originallyPublishedAt: Date
590 @ForeignKey(() => VideoChannelModel)
594 @BelongsTo(() => VideoChannelModel, {
600 VideoChannel: VideoChannelModel
602 @BelongsToMany(() => TagModel, {
603 foreignKey: 'videoId',
604 through: () => VideoTagModel,
609 @HasMany(() => ThumbnailModel, {
617 Thumbnails: ThumbnailModel[]
619 @HasMany(() => VideoPlaylistElementModel, {
626 VideoPlaylistElements: VideoPlaylistElementModel[]
628 @HasMany(() => VideoAbuseModel, {
635 VideoAbuses: VideoAbuseModel[]
637 @HasMany(() => VideoFileModel, {
645 VideoFiles: VideoFileModel[]
647 @HasMany(() => VideoStreamingPlaylistModel, {
655 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
657 @HasMany(() => VideoShareModel, {
664 VideoShares: VideoShareModel[]
666 @HasMany(() => AccountVideoRateModel, {
673 AccountVideoRates: AccountVideoRateModel[]
675 @HasMany(() => VideoCommentModel, {
683 VideoComments: VideoCommentModel[]
685 @HasMany(() => VideoViewModel, {
692 VideoViews: VideoViewModel[]
694 @HasMany(() => UserVideoHistoryModel, {
701 UserVideoHistories: UserVideoHistoryModel[]
703 @HasOne(() => ScheduleVideoUpdateModel, {
710 ScheduleVideoUpdate: ScheduleVideoUpdateModel
712 @HasOne(() => VideoBlacklistModel, {
719 VideoBlacklist: VideoBlacklistModel
721 @HasOne(() => VideoImportModel, {
728 VideoImport: VideoImportModel
730 @HasMany(() => VideoCaptionModel, {
737 ['separate' as any]: true
739 VideoCaptions: VideoCaptionModel[]
742 static async sendDelete (instance: MVideoAccountLight, options) {
743 if (instance.isOwned()) {
744 if (!instance.VideoChannel) {
745 instance.VideoChannel = await instance.$get('VideoChannel', {
750 transaction: options.transaction
751 }) as MChannelAccountDefault
754 return sendDeleteVideo(instance, options.transaction)
761 static async removeFiles (instance: VideoModel) {
762 const tasks: Promise<any>[] = []
764 logger.info('Removing files of video %s.', instance.url)
766 if (instance.isOwned()) {
767 if (!Array.isArray(instance.VideoFiles)) {
768 instance.VideoFiles = await instance.$get('VideoFiles')
771 // Remove physical files and torrents
772 instance.VideoFiles.forEach(file => {
773 tasks.push(instance.removeFile(file))
774 tasks.push(instance.removeTorrent(file))
777 // Remove playlists file
778 if (!Array.isArray(instance.VideoStreamingPlaylists)) {
779 instance.VideoStreamingPlaylists = await instance.$get('VideoStreamingPlaylists')
782 for (const p of instance.VideoStreamingPlaylists) {
783 tasks.push(instance.removeStreamingPlaylistFiles(p))
787 // Do not wait video deletion because we could be in a transaction
790 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
797 static invalidateCache (instance: VideoModel) {
798 ModelCache.Instance.invalidateCache('video', instance.id)
802 static async saveEssentialDataToAbuses (instance: VideoModel, options) {
803 const tasks: Promise<any>[] = []
805 logger.info('Saving video abuses details of video %s.', instance.url)
807 if (!Array.isArray(instance.VideoAbuses)) {
808 instance.VideoAbuses = await instance.$get('VideoAbuses')
810 if (instance.VideoAbuses.length === 0) return undefined
813 const details = instance.toFormattedDetailsJSON()
815 for (const abuse of instance.VideoAbuses) {
816 abuse.deletedVideo = details
817 tasks.push(abuse.save({ transaction: options.transaction }))
822 logger.error('Some errors when saving details of video %s in its abuses before destroy hook.', instance.uuid, { err })
828 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
835 return VideoModel.scope([
836 ScopeNames.WITH_WEBTORRENT_FILES,
837 ScopeNames.WITH_STREAMING_PLAYLISTS,
838 ScopeNames.WITH_THUMBNAILS
842 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
843 function getRawQuery (select: string) {
844 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
845 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
846 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
847 'WHERE "Account"."actorId" = ' + actorId
848 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
849 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
850 'WHERE "VideoShare"."actorId" = ' + actorId
852 return `(${queryVideo}) UNION (${queryVideoShare})`
855 const rawQuery = getRawQuery('"Video"."id"')
856 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
862 order: getVideoSort('-createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
865 [Op.in]: Sequelize.literal('(' + rawQuery + ')')
868 { privacy: VideoPrivacy.PUBLIC },
869 { privacy: VideoPrivacy.UNLISTED }
874 attributes: [ 'language', 'fileUrl' ],
875 model: VideoCaptionModel.unscoped(),
879 attributes: [ 'id', 'url' ],
880 model: VideoShareModel.unscoped(),
882 // We only want videos shared by this actor
897 attributes: [ 'id', 'url' ],
898 model: ActorModel.unscoped()
903 model: VideoChannelModel.unscoped(),
907 attributes: [ 'name' ],
908 model: AccountModel.unscoped(),
912 attributes: [ 'id', 'url', 'followersUrl' ],
913 model: ActorModel.unscoped(),
919 attributes: [ 'id', 'url', 'followersUrl' ],
920 model: ActorModel.unscoped(),
930 return Bluebird.all([
931 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
932 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
933 ]).then(([ rows, totals ]) => {
934 // totals: totalVideos + totalVideoShares
936 let totalVideoShares = 0
937 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
938 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
940 const total = totalVideos + totalVideoShares
948 static listUserVideosForApi (
955 function buildBaseQuery (): FindOptions {
959 order: getVideoSort(sort),
962 model: VideoChannelModel,
978 baseQuery = Object.assign(baseQuery, {
981 [Op.iLike]: '%' + search + '%'
990 const countQuery = buildBaseQuery()
991 const findQuery = buildBaseQuery()
993 const findScopes: (string | ScopeOptions)[] = [
994 ScopeNames.WITH_SCHEDULED_UPDATE,
995 ScopeNames.WITH_BLACKLISTED,
996 ScopeNames.WITH_THUMBNAILS
1000 VideoModel.count(countQuery),
1001 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1002 ]).then(([ count, rows ]) => {
1010 static async listForApi (options: {
1015 includeLocalVideos: boolean
1017 categoryOneOf?: number[]
1018 licenceOneOf?: number[]
1019 languageOneOf?: string[]
1020 tagsOneOf?: string[]
1021 tagsAllOf?: string[]
1022 filter?: VideoFilter
1024 videoChannelId?: number
1025 followerActorId?: number
1026 videoPlaylistId?: number
1027 trendingDays?: number
1028 user?: MUserAccountId
1029 historyOfUser?: MUserId
1030 countVideos?: boolean
1032 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1033 throw new Error('Try to filter all-local but no user has not the see all videos right')
1036 const trendingDays = options.sort.endsWith('trending')
1037 ? CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1040 const serverActor = await getServerActor()
1042 // followerActorId === null has a meaning, so just check undefined
1043 const followerActorId = options.followerActorId !== undefined
1044 ? options.followerActorId
1047 const queryOptions = {
1048 start: options.start,
1049 count: options.count,
1052 serverAccountId: serverActor.Account.id,
1054 categoryOneOf: options.categoryOneOf,
1055 licenceOneOf: options.licenceOneOf,
1056 languageOneOf: options.languageOneOf,
1057 tagsOneOf: options.tagsOneOf,
1058 tagsAllOf: options.tagsAllOf,
1059 filter: options.filter,
1060 withFiles: options.withFiles,
1061 accountId: options.accountId,
1062 videoChannelId: options.videoChannelId,
1063 videoPlaylistId: options.videoPlaylistId,
1064 includeLocalVideos: options.includeLocalVideos,
1066 historyOfUser: options.historyOfUser,
1070 return VideoModel.getAvailableForApi(queryOptions, options.countVideos)
1073 static async searchAndPopulateAccountAndServer (options: {
1074 includeLocalVideos: boolean
1079 startDate?: string // ISO 8601
1080 endDate?: string // ISO 8601
1081 originallyPublishedStartDate?: string
1082 originallyPublishedEndDate?: string
1084 categoryOneOf?: number[]
1085 licenceOneOf?: number[]
1086 languageOneOf?: string[]
1087 tagsOneOf?: string[]
1088 tagsAllOf?: string[]
1089 durationMin?: number // seconds
1090 durationMax?: number // seconds
1091 user?: MUserAccountId
1092 filter?: VideoFilter
1094 const serverActor = await getServerActor()
1095 const queryOptions = {
1096 followerActorId: serverActor.id,
1097 serverAccountId: serverActor.Account.id,
1098 includeLocalVideos: options.includeLocalVideos,
1100 categoryOneOf: options.categoryOneOf,
1101 licenceOneOf: options.licenceOneOf,
1102 languageOneOf: options.languageOneOf,
1103 tagsOneOf: options.tagsOneOf,
1104 tagsAllOf: options.tagsAllOf,
1106 filter: options.filter,
1107 start: options.start,
1108 count: options.count,
1110 startDate: options.startDate,
1111 endDate: options.endDate,
1112 originallyPublishedStartDate: options.originallyPublishedStartDate,
1113 originallyPublishedEndDate: options.originallyPublishedEndDate,
1115 durationMin: options.durationMin,
1116 durationMax: options.durationMax,
1118 search: options.search
1121 return VideoModel.getAvailableForApi(queryOptions)
1124 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1125 const where = buildWhereIdOrUUID(id)
1131 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1134 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1135 const where = buildWhereIdOrUUID(id)
1141 return VideoModel.scope([
1142 ScopeNames.WITH_THUMBNAILS,
1143 ScopeNames.WITH_BLACKLISTED
1147 static loadImmutableAttributes (id: number | string, t?: Transaction): Bluebird<MVideoImmutable> {
1150 where: buildWhereIdOrUUID(id),
1154 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1157 return ModelCache.Instance.doCache({
1158 cacheType: 'load-video-immutable-id',
1165 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1166 const where = buildWhereIdOrUUID(id)
1172 return VideoModel.scope([
1173 ScopeNames.WITH_BLACKLISTED,
1174 ScopeNames.WITH_USER_ID,
1175 ScopeNames.WITH_THUMBNAILS
1179 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1180 const where = buildWhereIdOrUUID(id)
1183 attributes: [ 'id' ],
1188 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1191 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1192 const where = buildWhereIdOrUUID(id)
1200 return VideoModel.scope([
1201 ScopeNames.WITH_WEBTORRENT_FILES,
1202 ScopeNames.WITH_STREAMING_PLAYLISTS,
1203 ScopeNames.WITH_THUMBNAILS
1207 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1214 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1217 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1218 const query: FindOptions = {
1225 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1228 static loadByUrlImmutableAttributes (url: string, transaction?: Transaction): Bluebird<MVideoImmutable> {
1230 const query: FindOptions = {
1237 return VideoModel.scope(ScopeNames.WITH_IMMUTABLE_ATTRIBUTES).findOne(query)
1240 return ModelCache.Instance.doCache({
1241 cacheType: 'load-video-immutable-url',
1248 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1249 const query: FindOptions = {
1256 return VideoModel.scope([
1257 ScopeNames.WITH_ACCOUNT_DETAILS,
1258 ScopeNames.WITH_WEBTORRENT_FILES,
1259 ScopeNames.WITH_STREAMING_PLAYLISTS,
1260 ScopeNames.WITH_THUMBNAILS,
1261 ScopeNames.WITH_BLACKLISTED
1265 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1266 const where = buildWhereIdOrUUID(id)
1269 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1274 const scopes: (string | ScopeOptions)[] = [
1275 ScopeNames.WITH_TAGS,
1276 ScopeNames.WITH_BLACKLISTED,
1277 ScopeNames.WITH_ACCOUNT_DETAILS,
1278 ScopeNames.WITH_SCHEDULED_UPDATE,
1279 ScopeNames.WITH_WEBTORRENT_FILES,
1280 ScopeNames.WITH_STREAMING_PLAYLISTS,
1281 ScopeNames.WITH_THUMBNAILS
1285 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1293 static loadForGetAPI (parameters: {
1297 }): Bluebird<MVideoDetails> {
1298 const { id, t, userId } = parameters
1299 const where = buildWhereIdOrUUID(id)
1302 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1307 const scopes: (string | ScopeOptions)[] = [
1308 ScopeNames.WITH_TAGS,
1309 ScopeNames.WITH_BLACKLISTED,
1310 ScopeNames.WITH_ACCOUNT_DETAILS,
1311 ScopeNames.WITH_SCHEDULED_UPDATE,
1312 ScopeNames.WITH_THUMBNAILS,
1313 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1314 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1318 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1326 static async getStats () {
1327 const totalLocalVideos = await VideoModel.count({
1333 let totalLocalVideoViews = await VideoModel.sum('views', {
1339 // Sequelize could return null...
1340 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1342 const { total: totalVideos } = await VideoModel.listForApi({
1345 sort: '-publishedAt',
1346 nsfw: buildNSFWFilter(),
1347 includeLocalVideos: true,
1353 totalLocalVideoViews,
1358 static incrementViews (id: number, views: number) {
1359 return VideoModel.increment('views', {
1367 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1368 // Instances only share videos
1369 const query = 'SELECT 1 FROM "videoShare" ' +
1370 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1371 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1375 type: QueryTypes.SELECT as QueryTypes.SELECT,
1376 bind: { followerActorId, videoId },
1380 return VideoModel.sequelize.query(query, options)
1381 .then(results => results.length === 1)
1384 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1387 channelId: videoChannel.id
1392 return VideoModel.update({ support: videoChannel.support }, options)
1395 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1397 attributes: [ 'id' ],
1399 channelId: videoChannel.id
1403 return VideoModel.findAll(query)
1404 .then(videos => videos.map(v => v.id))
1407 // threshold corresponds to how many video the field should have to be returned
1408 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1409 const serverActor = await getServerActor()
1410 const followerActorId = serverActor.id
1412 const queryOptions: BuildVideosQueryOptions = {
1413 attributes: [ `"${field}"` ],
1414 group: `GROUP BY "${field}"`,
1415 having: `HAVING COUNT("${field}") >= ${threshold}`,
1419 serverAccountId: serverActor.Account.id,
1421 includeLocalVideos: true
1424 const { query, replacements } = buildListQuery(VideoModel, queryOptions)
1426 return this.sequelize.query<any>(query, { replacements, type: QueryTypes.SELECT })
1427 .then(rows => rows.map(r => r[field]))
1430 static buildTrendingQuery (trendingDays: number) {
1434 model: VideoViewModel,
1438 [Op.gte]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1444 private static async getAvailableForApi (
1445 options: BuildVideosQueryOptions,
1448 function getCount () {
1449 if (countVideos !== true) return Promise.resolve(undefined)
1451 const countOptions = Object.assign({}, options, { isCount: true })
1452 const { query: queryCount, replacements: replacementsCount } = buildListQuery(VideoModel, countOptions)
1454 return VideoModel.sequelize.query<any>(queryCount, { replacements: replacementsCount, type: QueryTypes.SELECT })
1455 .then(rows => rows.length !== 0 ? rows[0].total : 0)
1458 function getModels () {
1459 if (options.count === 0) return Promise.resolve([])
1461 const { query, replacements, order } = buildListQuery(VideoModel, options)
1462 const queryModels = wrapForAPIResults(query, replacements, options, order)
1464 return VideoModel.sequelize.query<any>(queryModels, { replacements, type: QueryTypes.SELECT, nest: true })
1465 .then(rows => VideoModel.buildAPIResult(rows))
1468 const [ count, rows ] = await Promise.all([ getCount(), getModels() ])
1476 private static buildAPIResult (rows: any[]) {
1477 const memo: { [ id: number ]: VideoModel } = {}
1479 const thumbnailsDone = new Set<number>()
1480 const historyDone = new Set<number>()
1481 const videoFilesDone = new Set<number>()
1483 const videos: VideoModel[] = []
1485 const avatarKeys = [ 'id', 'filename', 'fileUrl', 'onDisk', 'createdAt', 'updatedAt' ]
1486 const actorKeys = [ 'id', 'preferredUsername', 'url', 'serverId', 'avatarId' ]
1487 const serverKeys = [ 'id', 'host' ]
1488 const videoFileKeys = [ 'id', 'createdAt', 'updatedAt', 'resolution', 'size', 'extname', 'infoHash', 'fps', 'videoId' ]
1511 'originallyPublishedAt',
1517 function buildActor (rowActor: any) {
1518 const avatarModel = rowActor.Avatar.id !== null
1519 ? new AvatarModel(pick(rowActor.Avatar, avatarKeys))
1522 const serverModel = rowActor.Server.id !== null
1523 ? new ServerModel(pick(rowActor.Server, serverKeys))
1526 const actorModel = new ActorModel(pick(rowActor, actorKeys))
1527 actorModel.Avatar = avatarModel
1528 actorModel.Server = serverModel
1533 for (const row of rows) {
1534 if (!memo[row.id]) {
1536 const channel = row.VideoChannel
1537 const channelModel = new VideoChannelModel(pick(channel, [ 'id', 'name', 'description', 'actorId' ]))
1538 channelModel.Actor = buildActor(channel.Actor)
1540 const account = row.VideoChannel.Account
1541 const accountModel = new AccountModel(pick(account, [ 'id', 'name' ]))
1542 accountModel.Actor = buildActor(account.Actor)
1544 channelModel.Account = accountModel
1546 const videoModel = new VideoModel(pick(row, videoKeys))
1547 videoModel.VideoChannel = channelModel
1549 videoModel.UserVideoHistories = []
1550 videoModel.Thumbnails = []
1551 videoModel.VideoFiles = []
1553 memo[row.id] = videoModel
1554 // Don't take object value to have a sorted array
1555 videos.push(videoModel)
1558 const videoModel = memo[row.id]
1560 if (row.userVideoHistory?.id && !historyDone.has(row.userVideoHistory.id)) {
1561 const historyModel = new UserVideoHistoryModel(pick(row.userVideoHistory, [ 'id', 'currentTime' ]))
1562 videoModel.UserVideoHistories.push(historyModel)
1564 historyDone.add(row.userVideoHistory.id)
1567 if (row.Thumbnails?.id && !thumbnailsDone.has(row.Thumbnails.id)) {
1568 const thumbnailModel = new ThumbnailModel(pick(row.Thumbnails, [ 'id', 'type', 'filename' ]))
1569 videoModel.Thumbnails.push(thumbnailModel)
1571 thumbnailsDone.add(row.Thumbnails.id)
1574 if (row.VideoFiles?.id && !videoFilesDone.has(row.VideoFiles.id)) {
1575 const videoFileModel = new VideoFileModel(pick(row.VideoFiles, videoFileKeys))
1576 videoModel.VideoFiles.push(videoFileModel)
1578 videoFilesDone.add(row.VideoFiles.id)
1585 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1586 const castedPrivacy = parseInt(privacy + '', 10)
1588 return castedPrivacy === VideoPrivacy.PUBLIC || castedPrivacy === VideoPrivacy.UNLISTED
1591 static getCategoryLabel (id: number) {
1592 return VIDEO_CATEGORIES[id] || 'Misc'
1595 static getLicenceLabel (id: number) {
1596 return VIDEO_LICENCES[id] || 'Unknown'
1599 static getLanguageLabel (id: string) {
1600 return VIDEO_LANGUAGES[id] || 'Unknown'
1603 static getPrivacyLabel (id: number) {
1604 return VIDEO_PRIVACIES[id] || 'Unknown'
1607 static getStateLabel (id: number) {
1608 return VIDEO_STATES[id] || 'Unknown'
1612 return !!this.VideoBlacklist
1616 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1617 this.VideoChannel.Account.isBlocked()
1620 getQualityFileBy<T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1621 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1622 const file = fun(this.VideoFiles, file => file.resolution)
1624 return Object.assign(file, { Video: this })
1627 // No webtorrent files, try with streaming playlist files
1628 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1629 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1631 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1632 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1638 getMaxQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1639 return this.getQualityFileBy(maxBy)
1642 getMinQualityFile<T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1643 return this.getQualityFileBy(minBy)
1646 getWebTorrentFile<T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1647 if (Array.isArray(this.VideoFiles) === false) return undefined
1649 const file = this.VideoFiles.find(f => f.resolution === resolution)
1650 if (!file) return undefined
1652 return Object.assign(file, { Video: this })
1655 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1656 thumbnail.videoId = this.id
1658 const savedThumbnail = await thumbnail.save({ transaction })
1660 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1662 // Already have this thumbnail, skip
1663 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1665 this.Thumbnails.push(savedThumbnail)
1668 generateThumbnailName () {
1669 return this.uuid + '.jpg'
1673 if (Array.isArray(this.Thumbnails) === false) return undefined
1675 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1678 generatePreviewName () {
1679 return this.uuid + '.jpg'
1683 return !!this.getPreview()
1687 if (Array.isArray(this.Thumbnails) === false) return undefined
1689 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1693 return this.remote === false
1696 getWatchStaticPath () {
1697 return '/videos/watch/' + this.uuid
1700 getEmbedStaticPath () {
1701 return '/videos/embed/' + this.uuid
1704 getMiniatureStaticPath () {
1705 const thumbnail = this.getMiniature()
1706 if (!thumbnail) return null
1708 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1711 getPreviewStaticPath () {
1712 const preview = this.getPreview()
1713 if (!preview) return null
1715 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1716 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1719 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1720 return videoModelToFormattedJSON(this, options)
1723 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1724 return videoModelToFormattedDetailsJSON(this)
1727 getFormattedVideoFilesJSON (): VideoFile[] {
1728 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1729 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1732 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1733 return videoModelToActivityPubObject(this)
1736 getTruncatedDescription () {
1737 if (!this.description) return null
1739 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1740 return peertubeTruncate(this.description, { length: maxLength })
1743 getMaxQualityResolution () {
1744 const file = this.getMaxQualityFile()
1745 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1746 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1748 return getVideoFileResolution(originalFilePath)
1751 getDescriptionAPIPath () {
1752 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1755 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1756 if (!this.VideoStreamingPlaylists) return undefined
1758 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1759 playlist.Video = this
1764 setHLSPlaylist (playlist: MStreamingPlaylist) {
1765 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1767 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1768 this.VideoStreamingPlaylists = toAdd
1772 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1773 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1777 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1778 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1779 return remove(filePath)
1780 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1783 removeTorrent (videoFile: MVideoFile) {
1784 const torrentPath = getTorrentFilePath(this, videoFile)
1785 return remove(torrentPath)
1786 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1789 async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) {
1790 const directoryPath = getHLSDirectory(this, isRedundancy)
1792 await remove(directoryPath)
1794 if (isRedundancy !== true) {
1795 const streamingPlaylistWithFiles = streamingPlaylist as MStreamingPlaylistFilesVideo
1796 streamingPlaylistWithFiles.Video = this
1798 if (!Array.isArray(streamingPlaylistWithFiles.VideoFiles)) {
1799 streamingPlaylistWithFiles.VideoFiles = await streamingPlaylistWithFiles.$get('VideoFiles')
1802 // Remove physical files and torrents
1804 streamingPlaylistWithFiles.VideoFiles.map(file => streamingPlaylistWithFiles.removeTorrent(file))
1810 if (this.isOwned()) return false
1812 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1815 hasPrivacyForFederation () {
1816 return VideoModel.isPrivacyForFederation(this.privacy)
1819 isNewVideo (newPrivacy: VideoPrivacy) {
1820 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
1824 this.changed('updatedAt', true)
1830 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
1833 setPrivacy (newPrivacy: VideoPrivacy) {
1834 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
1835 this.publishedAt = new Date()
1838 this.privacy = newPrivacy
1842 return this.privacy === VideoPrivacy.PRIVATE ||
1843 this.privacy === VideoPrivacy.UNLISTED ||
1844 this.privacy === VideoPrivacy.INTERNAL
1847 async publishIfNeededAndSave (t: Transaction) {
1848 if (this.state !== VideoState.PUBLISHED) {
1849 this.state = VideoState.PUBLISHED
1850 this.publishedAt = new Date()
1851 await this.save({ transaction: t })
1860 if (this.isOwned()) {
1862 baseUrlHttp: WEBSERVER.URL,
1863 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1868 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1869 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1873 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1874 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1877 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1878 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1881 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1882 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
1885 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1886 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
1889 getVideoFileMetadataUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1890 const path = '/api/v1/videos/'
1892 return this.isOwned()
1893 ? baseUrlHttp + path + this.uuid + '/metadata/' + videoFile.id
1894 : videoFile.metadataUrl
1897 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1898 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
1901 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1902 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
1905 getBandwidthBits (videoFile: MVideoFile) {
1906 return Math.ceil((videoFile.size * 8) / this.duration)