1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
38 } from 'sequelize-typescript'
39 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
56 } from '../../helpers/custom-validators/videos'
57 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
58 import { logger } from '../../helpers/logger'
59 import { getServerActor } from '../../helpers/utils'
64 HLS_REDUNDANCY_DIRECTORY,
65 HLS_STREAMING_PLAYLIST_DIRECTORY,
67 STATIC_DOWNLOAD_PATHS,
75 } from '../../initializers/constants'
76 import { sendDeleteVideo } from '../../lib/activitypub/send'
77 import { AccountModel } from '../account/account'
78 import { AccountVideoRateModel } from '../account/account-video-rate'
79 import { ActorModel } from '../activitypub/actor'
80 import { AvatarModel } from '../avatar/avatar'
81 import { ServerModel } from '../server/server'
83 buildBlockedAccountSQL,
84 buildTrigramSearchIndex,
87 createSimilarityAttribute,
92 import { TagModel } from './tag'
93 import { VideoAbuseModel } from './video-abuse'
94 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
95 import { VideoCommentModel } from './video-comment'
96 import { VideoFileModel } from './video-file'
97 import { VideoShareModel } from './video-share'
98 import { VideoTagModel } from './video-tag'
99 import { ScheduleVideoUpdateModel } from './schedule-video-update'
100 import { VideoCaptionModel } from './video-caption'
101 import { VideoBlacklistModel } from './video-blacklist'
102 import { remove, writeFile } from 'fs-extra'
103 import { VideoViewModel } from './video-views'
104 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
106 videoFilesModelToFormattedJSON,
107 VideoFormattingJSONOptions,
108 videoModelToActivityPubObject,
109 videoModelToFormattedDetailsJSON,
110 videoModelToFormattedJSON
111 } from './video-format-utils'
112 import { UserVideoHistoryModel } from '../account/user-video-history'
113 import { UserModel } from '../account/user'
114 import { VideoImportModel } from './video-import'
115 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
116 import { VideoPlaylistElementModel } from './video-playlist-element'
117 import { CONFIG } from '../../initializers/config'
118 import { ThumbnailModel } from './thumbnail'
119 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 import { createTorrentPromise } from '../../helpers/webtorrent'
122 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
123 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
124 buildTrigramSearchIndex('video_name_trigram', 'name'),
126 { fields: [ 'createdAt' ] },
127 { fields: [ 'publishedAt' ] },
128 { fields: [ 'duration' ] },
129 { fields: [ 'views' ] },
130 { fields: [ 'channelId' ] },
132 fields: [ 'originallyPublishedAt' ],
134 originallyPublishedAt: {
140 fields: [ 'category' ], // We don't care videos with an unknown category
148 fields: [ 'licence' ], // We don't care videos with an unknown licence
156 fields: [ 'language' ], // We don't care videos with an unknown language
164 fields: [ 'nsfw' ], // Most of the videos are not NSFW
170 fields: [ 'remote' ], // Only index local videos
185 export enum ScopeNames {
186 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
188 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
189 WITH_TAGS = 'WITH_TAGS',
190 WITH_FILES = 'WITH_FILES',
191 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
192 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
193 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
194 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
195 WITH_USER_ID = 'WITH_USER_ID',
196 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
199 type ForAPIOptions = {
202 videoPlaylistId?: number
207 type AvailableForListIDsOptions = {
208 serverAccountId: number
209 followerActorId: number
210 includeLocalVideos: boolean
215 categoryOneOf?: number[]
217 licenceOneOf?: number[]
218 languageOneOf?: string[]
225 videoChannelId?: number
227 videoPlaylistId?: number
229 trendingDays?: number
231 historyOfUser?: UserModel
233 baseWhere?: WhereOptions[]
237 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
238 const query: FindOptions = {
241 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
246 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
250 attributes: [ 'type', 'filename' ],
251 model: ThumbnailModel,
257 if (options.withFiles === true) {
259 model: VideoFileModel.unscoped(),
264 if (options.videoPlaylistId) {
266 model: VideoPlaylistElementModel.unscoped(),
269 videoPlaylistId: options.videoPlaylistId
276 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
277 const whereAnd = options.baseWhere ? options.baseWhere : []
279 const query: FindOptions = {
281 attributes: options.withoutId === true ? [] : [ 'id' ],
287 [ Op.notIn ]: Sequelize.literal(
288 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
295 [ Op.notIn ]: Sequelize.literal(
297 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
298 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
305 // Only list public/published videos
306 if (!options.filter || options.filter !== 'all-local') {
307 const privacyWhere = {
308 // Always list public videos
309 privacy: VideoPrivacy.PUBLIC,
310 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
313 state: VideoState.PUBLISHED
317 state: VideoState.TO_TRANSCODE,
318 waitTranscoding: false
324 whereAnd.push(privacyWhere)
327 if (options.videoPlaylistId) {
330 model: VideoPlaylistElementModel.unscoped(),
333 videoPlaylistId: options.videoPlaylistId
337 query.subQuery = false
340 if (options.filter || options.accountId || options.videoChannelId) {
341 const videoChannelInclude: IncludeOptions = {
343 model: VideoChannelModel.unscoped(),
347 if (options.videoChannelId) {
348 videoChannelInclude.where = {
349 id: options.videoChannelId
353 if (options.filter || options.accountId) {
354 const accountInclude: IncludeOptions = {
356 model: AccountModel.unscoped(),
360 if (options.filter) {
361 accountInclude.include = [
364 model: ActorModel.unscoped(),
366 where: VideoModel.buildActorWhereWithFilter(options.filter)
371 if (options.accountId) {
372 accountInclude.where = { id: options.accountId }
375 videoChannelInclude.include = [ accountInclude ]
378 query.include.push(videoChannelInclude)
381 if (options.followerActorId) {
382 let localVideosReq = ''
383 if (options.includeLocalVideos === true) {
384 localVideosReq = ' UNION ALL ' +
385 'SELECT "video"."id" AS "id" FROM "video" ' +
386 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
387 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
388 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
389 'WHERE "actor"."serverId" IS NULL'
392 // Force actorId to be a number to avoid SQL injections
393 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
396 [ Op.in ]: Sequelize.literal(
398 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
399 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
400 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
402 'SELECT "video"."id" AS "id" FROM "video" ' +
403 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
404 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
405 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
406 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
407 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
415 if (options.withFiles === true) {
418 [ Op.in ]: Sequelize.literal(
419 '(SELECT "videoId" FROM "videoFile")'
425 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
426 if (options.tagsAllOf || options.tagsOneOf) {
427 if (options.tagsOneOf) {
430 [ Op.in ]: Sequelize.literal(
432 'SELECT "videoId" FROM "videoTag" ' +
433 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
434 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
441 if (options.tagsAllOf) {
444 [ Op.in ]: Sequelize.literal(
446 'SELECT "videoId" FROM "videoTag" ' +
447 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
448 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
449 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
457 if (options.nsfw === true || options.nsfw === false) {
458 whereAnd.push({ nsfw: options.nsfw })
461 if (options.categoryOneOf) {
464 [ Op.or ]: options.categoryOneOf
469 if (options.licenceOneOf) {
472 [ Op.or ]: options.licenceOneOf
477 if (options.languageOneOf) {
478 let videoLanguages = options.languageOneOf
479 if (options.languageOneOf.find(l => l === '_unknown')) {
480 videoLanguages = videoLanguages.concat([ null ])
487 [ Op.or ]: videoLanguages
492 [ Op.in ]: Sequelize.literal(
494 'SELECT "videoId" FROM "videoCaption" ' +
495 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
504 if (options.trendingDays) {
505 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
507 query.subQuery = false
510 if (options.historyOfUser) {
512 model: UserVideoHistoryModel,
515 userId: options.historyOfUser.id
519 // Even if the relation is n:m, we know that a user only have 0..1 video history
520 // So we won't have multiple rows for the same video
521 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
522 query.subQuery = false
531 [ ScopeNames.WITH_THUMBNAILS ]: {
534 model: ThumbnailModel,
539 [ ScopeNames.WITH_USER_ID ]: {
542 attributes: [ 'accountId' ],
543 model: VideoChannelModel.unscoped(),
547 attributes: [ 'userId' ],
548 model: AccountModel.unscoped(),
555 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
558 model: VideoChannelModel.unscoped(),
563 exclude: [ 'privateKey', 'publicKey' ]
565 model: ActorModel.unscoped(),
569 attributes: [ 'host' ],
570 model: ServerModel.unscoped(),
574 model: AvatarModel.unscoped(),
580 model: AccountModel.unscoped(),
584 model: ActorModel.unscoped(),
586 exclude: [ 'privateKey', 'publicKey' ]
591 attributes: [ 'host' ],
592 model: ServerModel.unscoped(),
596 model: AvatarModel.unscoped(),
607 [ ScopeNames.WITH_TAGS ]: {
608 include: [ TagModel ]
610 [ ScopeNames.WITH_BLACKLISTED ]: {
613 attributes: [ 'id', 'reason' ],
614 model: VideoBlacklistModel,
619 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
620 let subInclude: any[] = []
622 if (withRedundancies === true) {
625 attributes: [ 'fileUrl' ],
626 model: VideoRedundancyModel.unscoped(),
635 model: VideoFileModel.unscoped(),
636 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
643 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
644 let subInclude: any[] = []
646 if (withRedundancies === true) {
649 attributes: [ 'fileUrl' ],
650 model: VideoRedundancyModel.unscoped(),
659 model: VideoStreamingPlaylistModel.unscoped(),
660 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
667 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
670 model: ScheduleVideoUpdateModel.unscoped(),
675 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
679 attributes: [ 'currentTime' ],
680 model: UserVideoHistoryModel.unscoped(),
694 export class VideoModel extends Model<VideoModel> {
697 @Default(DataType.UUIDV4)
699 @Column(DataType.UUID)
703 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
709 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
715 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
721 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
722 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
726 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
731 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
737 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
738 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
743 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
744 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
748 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
778 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
779 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
784 commentsEnabled: boolean
788 downloadEnabled: boolean
792 waitTranscoding: boolean
796 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
807 @Default(DataType.NOW)
814 originallyPublishedAt: Date
816 @ForeignKey(() => VideoChannelModel)
820 @BelongsTo(() => VideoChannelModel, {
826 VideoChannel: VideoChannelModel
828 @BelongsToMany(() => TagModel, {
829 foreignKey: 'videoId',
830 through: () => VideoTagModel,
835 @HasMany(() => ThumbnailModel, {
843 Thumbnails: ThumbnailModel[]
845 @HasMany(() => VideoPlaylistElementModel, {
852 VideoPlaylistElements: VideoPlaylistElementModel[]
854 @HasMany(() => VideoAbuseModel, {
861 VideoAbuses: VideoAbuseModel[]
863 @HasMany(() => VideoFileModel, {
871 VideoFiles: VideoFileModel[]
873 @HasMany(() => VideoStreamingPlaylistModel, {
881 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
883 @HasMany(() => VideoShareModel, {
890 VideoShares: VideoShareModel[]
892 @HasMany(() => AccountVideoRateModel, {
899 AccountVideoRates: AccountVideoRateModel[]
901 @HasMany(() => VideoCommentModel, {
909 VideoComments: VideoCommentModel[]
911 @HasMany(() => VideoViewModel, {
918 VideoViews: VideoViewModel[]
920 @HasMany(() => UserVideoHistoryModel, {
927 UserVideoHistories: UserVideoHistoryModel[]
929 @HasOne(() => ScheduleVideoUpdateModel, {
936 ScheduleVideoUpdate: ScheduleVideoUpdateModel
938 @HasOne(() => VideoBlacklistModel, {
945 VideoBlacklist: VideoBlacklistModel
947 @HasOne(() => VideoImportModel, {
954 VideoImport: VideoImportModel
956 @HasMany(() => VideoCaptionModel, {
963 [ 'separate' as any ]: true
965 VideoCaptions: VideoCaptionModel[]
968 static async sendDelete (instance: VideoModel, options) {
969 if (instance.isOwned()) {
970 if (!instance.VideoChannel) {
971 instance.VideoChannel = await instance.$get('VideoChannel', {
975 include: [ ActorModel ]
978 transaction: options.transaction
979 }) as VideoChannelModel
982 return sendDeleteVideo(instance, options.transaction)
989 static async removeFiles (instance: VideoModel) {
990 const tasks: Promise<any>[] = []
992 logger.info('Removing files of video %s.', instance.url)
994 if (instance.isOwned()) {
995 if (!Array.isArray(instance.VideoFiles)) {
996 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
999 // Remove physical files and torrents
1000 instance.VideoFiles.forEach(file => {
1001 tasks.push(instance.removeFile(file))
1002 tasks.push(instance.removeTorrent(file))
1005 // Remove playlists file
1006 tasks.push(instance.removeStreamingPlaylist())
1009 // Do not wait video deletion because we could be in a transaction
1012 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1018 static listLocal () {
1025 return VideoModel.scope([
1026 ScopeNames.WITH_FILES,
1027 ScopeNames.WITH_STREAMING_PLAYLISTS,
1028 ScopeNames.WITH_THUMBNAILS
1032 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1033 function getRawQuery (select: string) {
1034 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1035 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1036 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1037 'WHERE "Account"."actorId" = ' + actorId
1038 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1039 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1040 'WHERE "VideoShare"."actorId" = ' + actorId
1042 return `(${queryVideo}) UNION (${queryVideoShare})`
1045 const rawQuery = getRawQuery('"Video"."id"')
1046 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1052 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1055 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1058 { privacy: VideoPrivacy.PUBLIC },
1059 { privacy: VideoPrivacy.UNLISTED }
1064 attributes: [ 'language' ],
1065 model: VideoCaptionModel.unscoped(),
1069 attributes: [ 'id', 'url' ],
1070 model: VideoShareModel.unscoped(),
1072 // We only want videos shared by this actor
1087 attributes: [ 'id', 'url' ],
1088 model: ActorModel.unscoped()
1093 model: VideoChannelModel.unscoped(),
1097 attributes: [ 'name' ],
1098 model: AccountModel.unscoped(),
1102 attributes: [ 'id', 'url', 'followersUrl' ],
1103 model: ActorModel.unscoped(),
1109 attributes: [ 'id', 'url', 'followersUrl' ],
1110 model: ActorModel.unscoped(),
1120 return Bluebird.all([
1121 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1122 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1123 ]).then(([ rows, totals ]) => {
1124 // totals: totalVideos + totalVideoShares
1126 let totalVideoShares = 0
1127 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1128 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1130 const total = totalVideos + totalVideoShares
1138 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1139 function buildBaseQuery (): FindOptions {
1143 order: getVideoSort(sort),
1146 model: VideoChannelModel,
1150 model: AccountModel,
1162 const countQuery = buildBaseQuery()
1163 const findQuery = buildBaseQuery()
1165 const findScopes = [
1166 ScopeNames.WITH_SCHEDULED_UPDATE,
1167 ScopeNames.WITH_BLACKLISTED,
1168 ScopeNames.WITH_THUMBNAILS
1171 if (withFiles === true) {
1172 findQuery.include.push({
1173 model: VideoFileModel.unscoped(),
1178 return Promise.all([
1179 VideoModel.count(countQuery),
1180 VideoModel.scope(findScopes).findAll(findQuery)
1181 ]).then(([ count, rows ]) => {
1189 static async listForApi (options: {
1194 includeLocalVideos: boolean,
1196 categoryOneOf?: number[],
1197 licenceOneOf?: number[],
1198 languageOneOf?: string[],
1199 tagsOneOf?: string[],
1200 tagsAllOf?: string[],
1201 filter?: VideoFilter,
1203 videoChannelId?: number,
1204 followerActorId?: number
1205 videoPlaylistId?: number,
1206 trendingDays?: number,
1208 historyOfUser?: UserModel
1209 }, countVideos = true) {
1210 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1211 throw new Error('Try to filter all-local but no user has not the see all videos right')
1214 const query: FindOptions & { where?: null } = {
1215 offset: options.start,
1216 limit: options.count,
1217 order: getVideoSort(options.sort)
1220 let trendingDays: number
1221 if (options.sort.endsWith('trending')) {
1222 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1224 query.group = 'VideoModel.id'
1227 const serverActor = await getServerActor()
1229 // followerActorId === null has a meaning, so just check undefined
1230 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1232 const queryOptions = {
1234 serverAccountId: serverActor.Account.id,
1236 categoryOneOf: options.categoryOneOf,
1237 licenceOneOf: options.licenceOneOf,
1238 languageOneOf: options.languageOneOf,
1239 tagsOneOf: options.tagsOneOf,
1240 tagsAllOf: options.tagsAllOf,
1241 filter: options.filter,
1242 withFiles: options.withFiles,
1243 accountId: options.accountId,
1244 videoChannelId: options.videoChannelId,
1245 videoPlaylistId: options.videoPlaylistId,
1246 includeLocalVideos: options.includeLocalVideos,
1248 historyOfUser: options.historyOfUser,
1252 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1255 static async searchAndPopulateAccountAndServer (options: {
1256 includeLocalVideos: boolean
1261 startDate?: string // ISO 8601
1262 endDate?: string // ISO 8601
1263 originallyPublishedStartDate?: string
1264 originallyPublishedEndDate?: string
1266 categoryOneOf?: number[]
1267 licenceOneOf?: number[]
1268 languageOneOf?: string[]
1269 tagsOneOf?: string[]
1270 tagsAllOf?: string[]
1271 durationMin?: number // seconds
1272 durationMax?: number // seconds
1274 filter?: VideoFilter
1278 if (options.startDate || options.endDate) {
1279 const publishedAtRange = {}
1281 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1282 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1284 whereAnd.push({ publishedAt: publishedAtRange })
1287 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1288 const originallyPublishedAtRange = {}
1290 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1291 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1293 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1296 if (options.durationMin || options.durationMax) {
1297 const durationRange = {}
1299 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1300 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1302 whereAnd.push({ duration: durationRange })
1305 const attributesInclude = []
1306 const escapedSearch = VideoModel.sequelize.escape(options.search)
1307 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1308 if (options.search) {
1312 [ Op.in ]: Sequelize.literal(
1314 'SELECT "video"."id" FROM "video" ' +
1316 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1317 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1319 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1320 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1321 'WHERE "tag"."name" = ' + escapedSearch +
1328 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1331 // Cannot search on similarity if we don't have a search
1332 if (!options.search) {
1333 attributesInclude.push(
1334 Sequelize.literal('0 as similarity')
1340 include: attributesInclude
1342 offset: options.start,
1343 limit: options.count,
1344 order: getVideoSort(options.sort)
1347 const serverActor = await getServerActor()
1348 const queryOptions = {
1349 followerActorId: serverActor.id,
1350 serverAccountId: serverActor.Account.id,
1351 includeLocalVideos: options.includeLocalVideos,
1353 categoryOneOf: options.categoryOneOf,
1354 licenceOneOf: options.licenceOneOf,
1355 languageOneOf: options.languageOneOf,
1356 tagsOneOf: options.tagsOneOf,
1357 tagsAllOf: options.tagsAllOf,
1359 filter: options.filter,
1363 return VideoModel.getAvailableForApi(query, queryOptions)
1366 static load (id: number | string, t?: Transaction) {
1367 const where = buildWhereIdOrUUID(id)
1373 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1376 static loadWithRights (id: number | string, t?: Transaction) {
1377 const where = buildWhereIdOrUUID(id)
1383 return VideoModel.scope([
1384 ScopeNames.WITH_BLACKLISTED,
1385 ScopeNames.WITH_USER_ID,
1386 ScopeNames.WITH_THUMBNAILS
1390 static loadOnlyId (id: number | string, t?: Transaction) {
1391 const where = buildWhereIdOrUUID(id)
1394 attributes: [ 'id' ],
1399 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1402 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1403 return VideoModel.scope([
1404 ScopeNames.WITH_FILES,
1405 ScopeNames.WITH_STREAMING_PLAYLISTS,
1406 ScopeNames.WITH_THUMBNAILS
1407 ]).findByPk(id, { transaction: t, logging })
1410 static loadByUUIDWithFile (uuid: string) {
1417 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1420 static loadByUrl (url: string, transaction?: Transaction) {
1421 const query: FindOptions = {
1428 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1431 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1432 const query: FindOptions = {
1439 return VideoModel.scope([
1440 ScopeNames.WITH_ACCOUNT_DETAILS,
1441 ScopeNames.WITH_FILES,
1442 ScopeNames.WITH_STREAMING_PLAYLISTS,
1443 ScopeNames.WITH_THUMBNAILS
1447 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1448 const where = buildWhereIdOrUUID(id)
1451 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1456 const scopes: (string | ScopeOptions)[] = [
1457 ScopeNames.WITH_TAGS,
1458 ScopeNames.WITH_BLACKLISTED,
1459 ScopeNames.WITH_ACCOUNT_DETAILS,
1460 ScopeNames.WITH_SCHEDULED_UPDATE,
1461 ScopeNames.WITH_FILES,
1462 ScopeNames.WITH_STREAMING_PLAYLISTS,
1463 ScopeNames.WITH_THUMBNAILS
1467 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1475 static loadForGetAPI (parameters: {
1476 id: number | string,
1480 const { id, t, userId } = parameters
1481 const where = buildWhereIdOrUUID(id)
1484 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1489 const scopes: (string | ScopeOptions)[] = [
1490 ScopeNames.WITH_TAGS,
1491 ScopeNames.WITH_BLACKLISTED,
1492 ScopeNames.WITH_ACCOUNT_DETAILS,
1493 ScopeNames.WITH_SCHEDULED_UPDATE,
1494 ScopeNames.WITH_THUMBNAILS,
1495 { method: [ ScopeNames.WITH_FILES, true ] },
1496 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1500 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1508 static async getStats () {
1509 const totalLocalVideos = await VideoModel.count({
1514 const totalVideos = await VideoModel.count()
1516 let totalLocalVideoViews = await VideoModel.sum('views', {
1521 // Sequelize could return null...
1522 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1526 totalLocalVideoViews,
1531 static incrementViews (id: number, views: number) {
1532 return VideoModel.increment('views', {
1540 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1541 // Instances only share videos
1542 const query = 'SELECT 1 FROM "videoShare" ' +
1543 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1544 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1548 type: QueryTypes.SELECT,
1549 bind: { followerActorId, videoId },
1553 return VideoModel.sequelize.query(query, options)
1554 .then(results => results.length === 1)
1557 static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) {
1560 channelId: videoChannel.id
1565 return VideoModel.update({ support: videoChannel.support }, options)
1568 static getAllIdsFromChannel (videoChannel: VideoChannelModel) {
1570 attributes: [ 'id' ],
1572 channelId: videoChannel.id
1576 return VideoModel.findAll(query)
1577 .then(videos => videos.map(v => v.id))
1580 // threshold corresponds to how many video the field should have to be returned
1581 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1582 const serverActor = await getServerActor()
1583 const followerActorId = serverActor.id
1585 const scopeOptions: AvailableForListIDsOptions = {
1586 serverAccountId: serverActor.Account.id,
1588 includeLocalVideos: true,
1589 withoutId: true // Don't break aggregation
1592 const query: FindOptions = {
1593 attributes: [ field ],
1596 having: Sequelize.where(
1597 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1599 order: [ (this.sequelize as any).random() ]
1602 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1604 .then(rows => rows.map(r => r[ field ]))
1607 static buildTrendingQuery (trendingDays: number) {
1611 model: VideoViewModel,
1615 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1621 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1622 if (filter && (filter === 'local' || filter === 'all-local')) {
1631 private static async getAvailableForApi (
1632 query: FindOptions & { where?: null }, // Forbid where field in query
1633 options: AvailableForListIDsOptions,
1636 const idsScope: ScopeOptions = {
1638 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1642 // Remove trending sort on count, because it uses a group by
1643 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1644 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1645 const countScope: ScopeOptions = {
1647 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1651 const [ count, ids ] = await Promise.all([
1653 ? VideoModel.scope(countScope).count(countQuery)
1654 : Promise.resolve<number>(undefined),
1656 VideoModel.scope(idsScope)
1658 .then(rows => rows.map(r => r.id))
1661 if (ids.length === 0) return { data: [], total: count }
1663 const secondQuery: FindOptions = {
1666 attributes: query.attributes,
1667 order: [ // Keep original order
1669 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1674 const apiScope: (string | ScopeOptions)[] = []
1677 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1682 ScopeNames.FOR_API, {
1684 withFiles: options.withFiles,
1685 videoPlaylistId: options.videoPlaylistId
1690 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1698 static getCategoryLabel (id: number) {
1699 return VIDEO_CATEGORIES[ id ] || 'Misc'
1702 static getLicenceLabel (id: number) {
1703 return VIDEO_LICENCES[ id ] || 'Unknown'
1706 static getLanguageLabel (id: string) {
1707 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1710 static getPrivacyLabel (id: number) {
1711 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1714 static getStateLabel (id: number) {
1715 return VIDEO_STATES[ id ] || 'Unknown'
1719 return !!this.VideoBlacklist
1722 getOriginalFile () {
1723 if (Array.isArray(this.VideoFiles) === false) return undefined
1725 // The original file is the file that have the higher resolution
1726 return maxBy(this.VideoFiles, file => file.resolution)
1729 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1730 thumbnail.videoId = this.id
1732 const savedThumbnail = await thumbnail.save({ transaction })
1734 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1736 // Already have this thumbnail, skip
1737 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1739 this.Thumbnails.push(savedThumbnail)
1742 getVideoFilename (videoFile: VideoFileModel) {
1743 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1746 generateThumbnailName () {
1747 return this.uuid + '.jpg'
1751 if (Array.isArray(this.Thumbnails) === false) return undefined
1753 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1756 generatePreviewName () {
1757 return this.uuid + '.jpg'
1761 if (Array.isArray(this.Thumbnails) === false) return undefined
1763 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1766 getTorrentFileName (videoFile: VideoFileModel) {
1767 const extension = '.torrent'
1768 return this.uuid + '-' + videoFile.resolution + extension
1772 return this.remote === false
1775 getTorrentFilePath (videoFile: VideoFileModel) {
1776 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1779 getVideoFilePath (videoFile: VideoFileModel) {
1780 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1783 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1785 // Keep the extname, it's used by the client to stream the file inside a web browser
1786 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1787 createdBy: 'PeerTube',
1789 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1790 [ WEBSERVER.URL + '/tracker/announce' ]
1792 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1795 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1797 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1798 logger.info('Creating torrent %s.', filePath)
1800 await writeFile(filePath, torrent)
1802 const parsedTorrent = parseTorrent(torrent)
1803 videoFile.infoHash = parsedTorrent.infoHash
1806 getWatchStaticPath () {
1807 return '/videos/watch/' + this.uuid
1810 getEmbedStaticPath () {
1811 return '/videos/embed/' + this.uuid
1814 getMiniatureStaticPath () {
1815 const thumbnail = this.getMiniature()
1816 if (!thumbnail) return null
1818 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1821 getPreviewStaticPath () {
1822 const preview = this.getPreview()
1823 if (!preview) return null
1825 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1826 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1829 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1830 return videoModelToFormattedJSON(this, options)
1833 toFormattedDetailsJSON (): VideoDetails {
1834 return videoModelToFormattedDetailsJSON(this)
1837 getFormattedVideoFilesJSON (): VideoFile[] {
1838 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1841 toActivityPubObject (): VideoTorrentObject {
1842 return videoModelToActivityPubObject(this)
1845 getTruncatedDescription () {
1846 if (!this.description) return null
1848 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1849 return peertubeTruncate(this.description, maxLength)
1852 getOriginalFileResolution () {
1853 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1855 return getVideoFileResolution(originalFilePath)
1858 getDescriptionAPIPath () {
1859 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1862 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1863 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1865 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1866 return remove(filePath)
1867 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1870 removeTorrent (videoFile: VideoFileModel) {
1871 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1872 return remove(torrentPath)
1873 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1876 removeStreamingPlaylist (isRedundancy = false) {
1877 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1879 const filePath = join(baseDir, this.uuid)
1880 return remove(filePath)
1881 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1885 if (this.isOwned()) return false
1887 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1891 this.changed('updatedAt', true)
1900 if (this.isOwned()) {
1901 baseUrlHttp = WEBSERVER.URL
1902 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1904 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1905 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1908 return { baseUrlHttp, baseUrlWs }
1911 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1912 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1913 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1914 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1916 const redundancies = videoFile.RedundancyVideos
1917 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1919 const magnetHash = {
1923 infoHash: videoFile.infoHash,
1927 return magnetUtil.encode(magnetHash)
1930 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1931 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1934 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1935 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1938 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1939 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1942 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1943 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1946 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1947 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1950 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1951 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1954 getBandwidthBits (videoFile: VideoFileModel) {
1955 return Math.ceil((videoFile.size * 8) / this.duration)