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 { createTorrentPromise, 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'
121 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
122 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
123 buildTrigramSearchIndex('video_name_trigram', 'name'),
125 { fields: [ 'createdAt' ] },
126 { fields: [ 'publishedAt' ] },
127 { fields: [ 'duration' ] },
128 { fields: [ 'views' ] },
129 { fields: [ 'channelId' ] },
131 fields: [ 'originallyPublishedAt' ],
133 originallyPublishedAt: {
139 fields: [ 'category' ], // We don't care videos with an unknown category
147 fields: [ 'licence' ], // We don't care videos with an unknown licence
155 fields: [ 'language' ], // We don't care videos with an unknown language
163 fields: [ 'nsfw' ], // Most of the videos are not NSFW
169 fields: [ 'remote' ], // Only index local videos
184 export enum ScopeNames {
185 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
187 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
188 WITH_TAGS = 'WITH_TAGS',
189 WITH_FILES = 'WITH_FILES',
190 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
191 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
192 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
193 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
194 WITH_USER_ID = 'WITH_USER_ID',
195 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
198 type ForAPIOptions = {
201 videoPlaylistId?: number
206 type AvailableForListIDsOptions = {
207 serverAccountId: number
208 followerActorId: number
209 includeLocalVideos: boolean
214 categoryOneOf?: number[]
216 licenceOneOf?: number[]
217 languageOneOf?: string[]
224 videoChannelId?: number
226 videoPlaylistId?: number
228 trendingDays?: number
230 historyOfUser?: UserModel
232 baseWhere?: WhereOptions[]
236 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
237 const query: FindOptions = {
240 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
245 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
249 attributes: [ 'type', 'filename' ],
250 model: ThumbnailModel,
256 if (options.withFiles === true) {
258 model: VideoFileModel.unscoped(),
263 if (options.videoPlaylistId) {
265 model: VideoPlaylistElementModel.unscoped(),
268 videoPlaylistId: options.videoPlaylistId
275 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
276 const whereAnd = options.baseWhere ? options.baseWhere : []
278 const query: FindOptions = {
280 attributes: options.withoutId === true ? [] : [ 'id' ],
286 [ Op.notIn ]: Sequelize.literal(
287 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
294 [ Op.notIn ]: Sequelize.literal(
296 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
297 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
304 // Only list public/published videos
305 if (!options.filter || options.filter !== 'all-local') {
306 const privacyWhere = {
307 // Always list public videos
308 privacy: VideoPrivacy.PUBLIC,
309 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
312 state: VideoState.PUBLISHED
316 state: VideoState.TO_TRANSCODE,
317 waitTranscoding: false
323 whereAnd.push(privacyWhere)
326 if (options.videoPlaylistId) {
329 model: VideoPlaylistElementModel.unscoped(),
332 videoPlaylistId: options.videoPlaylistId
336 query.subQuery = false
339 if (options.filter || options.accountId || options.videoChannelId) {
340 const videoChannelInclude: IncludeOptions = {
342 model: VideoChannelModel.unscoped(),
346 if (options.videoChannelId) {
347 videoChannelInclude.where = {
348 id: options.videoChannelId
352 if (options.filter || options.accountId) {
353 const accountInclude: IncludeOptions = {
355 model: AccountModel.unscoped(),
359 if (options.filter) {
360 accountInclude.include = [
363 model: ActorModel.unscoped(),
365 where: VideoModel.buildActorWhereWithFilter(options.filter)
370 if (options.accountId) {
371 accountInclude.where = { id: options.accountId }
374 videoChannelInclude.include = [ accountInclude ]
377 query.include.push(videoChannelInclude)
380 if (options.followerActorId) {
381 let localVideosReq = ''
382 if (options.includeLocalVideos === true) {
383 localVideosReq = ' UNION ALL ' +
384 'SELECT "video"."id" AS "id" FROM "video" ' +
385 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
386 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
387 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
388 'WHERE "actor"."serverId" IS NULL'
391 // Force actorId to be a number to avoid SQL injections
392 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
395 [ Op.in ]: Sequelize.literal(
397 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
398 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
399 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
401 'SELECT "video"."id" AS "id" FROM "video" ' +
402 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
403 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
404 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
405 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
406 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
414 if (options.withFiles === true) {
417 [ Op.in ]: Sequelize.literal(
418 '(SELECT "videoId" FROM "videoFile")'
424 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
425 if (options.tagsAllOf || options.tagsOneOf) {
426 if (options.tagsOneOf) {
429 [ Op.in ]: Sequelize.literal(
431 'SELECT "videoId" FROM "videoTag" ' +
432 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
433 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
440 if (options.tagsAllOf) {
443 [ Op.in ]: Sequelize.literal(
445 'SELECT "videoId" FROM "videoTag" ' +
446 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
447 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
448 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
456 if (options.nsfw === true || options.nsfw === false) {
457 whereAnd.push({ nsfw: options.nsfw })
460 if (options.categoryOneOf) {
463 [ Op.or ]: options.categoryOneOf
468 if (options.licenceOneOf) {
471 [ Op.or ]: options.licenceOneOf
476 if (options.languageOneOf) {
477 let videoLanguages = options.languageOneOf
478 if (options.languageOneOf.find(l => l === '_unknown')) {
479 videoLanguages = videoLanguages.concat([ null ])
486 [ Op.or ]: videoLanguages
491 [ Op.in ]: Sequelize.literal(
493 'SELECT "videoId" FROM "videoCaption" ' +
494 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
503 if (options.trendingDays) {
504 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
506 query.subQuery = false
509 if (options.historyOfUser) {
511 model: UserVideoHistoryModel,
514 userId: options.historyOfUser.id
518 // Even if the relation is n:m, we know that a user only have 0..1 video history
519 // So we won't have multiple rows for the same video
520 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
521 query.subQuery = false
530 [ ScopeNames.WITH_THUMBNAILS ]: {
533 model: ThumbnailModel,
538 [ ScopeNames.WITH_USER_ID ]: {
541 attributes: [ 'accountId' ],
542 model: VideoChannelModel.unscoped(),
546 attributes: [ 'userId' ],
547 model: AccountModel.unscoped(),
554 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
557 model: VideoChannelModel.unscoped(),
562 exclude: [ 'privateKey', 'publicKey' ]
564 model: ActorModel.unscoped(),
568 attributes: [ 'host' ],
569 model: ServerModel.unscoped(),
573 model: AvatarModel.unscoped(),
579 model: AccountModel.unscoped(),
583 model: ActorModel.unscoped(),
585 exclude: [ 'privateKey', 'publicKey' ]
590 attributes: [ 'host' ],
591 model: ServerModel.unscoped(),
595 model: AvatarModel.unscoped(),
606 [ ScopeNames.WITH_TAGS ]: {
607 include: [ TagModel ]
609 [ ScopeNames.WITH_BLACKLISTED ]: {
612 attributes: [ 'id', 'reason' ],
613 model: VideoBlacklistModel,
618 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
619 let subInclude: any[] = []
621 if (withRedundancies === true) {
624 attributes: [ 'fileUrl' ],
625 model: VideoRedundancyModel.unscoped(),
634 model: VideoFileModel.unscoped(),
635 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
642 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
643 let subInclude: any[] = []
645 if (withRedundancies === true) {
648 attributes: [ 'fileUrl' ],
649 model: VideoRedundancyModel.unscoped(),
658 model: VideoStreamingPlaylistModel.unscoped(),
659 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
666 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
669 model: ScheduleVideoUpdateModel.unscoped(),
674 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
678 attributes: [ 'currentTime' ],
679 model: UserVideoHistoryModel.unscoped(),
693 export class VideoModel extends Model<VideoModel> {
696 @Default(DataType.UUIDV4)
698 @Column(DataType.UUID)
702 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
708 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
714 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
720 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
721 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
725 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
730 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
736 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
737 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
742 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
743 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
747 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
777 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
778 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
783 commentsEnabled: boolean
787 downloadEnabled: boolean
791 waitTranscoding: boolean
795 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
806 @Default(DataType.NOW)
813 originallyPublishedAt: Date
815 @ForeignKey(() => VideoChannelModel)
819 @BelongsTo(() => VideoChannelModel, {
825 VideoChannel: VideoChannelModel
827 @BelongsToMany(() => TagModel, {
828 foreignKey: 'videoId',
829 through: () => VideoTagModel,
834 @HasMany(() => ThumbnailModel, {
842 Thumbnails: ThumbnailModel[]
844 @HasMany(() => VideoPlaylistElementModel, {
851 VideoPlaylistElements: VideoPlaylistElementModel[]
853 @HasMany(() => VideoAbuseModel, {
860 VideoAbuses: VideoAbuseModel[]
862 @HasMany(() => VideoFileModel, {
870 VideoFiles: VideoFileModel[]
872 @HasMany(() => VideoStreamingPlaylistModel, {
880 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
882 @HasMany(() => VideoShareModel, {
889 VideoShares: VideoShareModel[]
891 @HasMany(() => AccountVideoRateModel, {
898 AccountVideoRates: AccountVideoRateModel[]
900 @HasMany(() => VideoCommentModel, {
908 VideoComments: VideoCommentModel[]
910 @HasMany(() => VideoViewModel, {
917 VideoViews: VideoViewModel[]
919 @HasMany(() => UserVideoHistoryModel, {
926 UserVideoHistories: UserVideoHistoryModel[]
928 @HasOne(() => ScheduleVideoUpdateModel, {
935 ScheduleVideoUpdate: ScheduleVideoUpdateModel
937 @HasOne(() => VideoBlacklistModel, {
944 VideoBlacklist: VideoBlacklistModel
946 @HasOne(() => VideoImportModel, {
953 VideoImport: VideoImportModel
955 @HasMany(() => VideoCaptionModel, {
962 [ 'separate' as any ]: true
964 VideoCaptions: VideoCaptionModel[]
967 static async sendDelete (instance: VideoModel, options) {
968 if (instance.isOwned()) {
969 if (!instance.VideoChannel) {
970 instance.VideoChannel = await instance.$get('VideoChannel', {
974 include: [ ActorModel ]
977 transaction: options.transaction
978 }) as VideoChannelModel
981 return sendDeleteVideo(instance, options.transaction)
988 static async removeFiles (instance: VideoModel) {
989 const tasks: Promise<any>[] = []
991 logger.info('Removing files of video %s.', instance.url)
993 if (instance.isOwned()) {
994 if (!Array.isArray(instance.VideoFiles)) {
995 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
998 // Remove physical files and torrents
999 instance.VideoFiles.forEach(file => {
1000 tasks.push(instance.removeFile(file))
1001 tasks.push(instance.removeTorrent(file))
1004 // Remove playlists file
1005 tasks.push(instance.removeStreamingPlaylist())
1008 // Do not wait video deletion because we could be in a transaction
1011 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1017 static listLocal () {
1024 return VideoModel.scope([
1025 ScopeNames.WITH_FILES,
1026 ScopeNames.WITH_STREAMING_PLAYLISTS,
1027 ScopeNames.WITH_THUMBNAILS
1031 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1032 function getRawQuery (select: string) {
1033 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1034 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1035 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1036 'WHERE "Account"."actorId" = ' + actorId
1037 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1038 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1039 'WHERE "VideoShare"."actorId" = ' + actorId
1041 return `(${queryVideo}) UNION (${queryVideoShare})`
1044 const rawQuery = getRawQuery('"Video"."id"')
1045 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1051 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1054 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1057 { privacy: VideoPrivacy.PUBLIC },
1058 { privacy: VideoPrivacy.UNLISTED }
1063 attributes: [ 'language' ],
1064 model: VideoCaptionModel.unscoped(),
1068 attributes: [ 'id', 'url' ],
1069 model: VideoShareModel.unscoped(),
1071 // We only want videos shared by this actor
1086 attributes: [ 'id', 'url' ],
1087 model: ActorModel.unscoped()
1092 model: VideoChannelModel.unscoped(),
1096 attributes: [ 'name' ],
1097 model: AccountModel.unscoped(),
1101 attributes: [ 'id', 'url', 'followersUrl' ],
1102 model: ActorModel.unscoped(),
1108 attributes: [ 'id', 'url', 'followersUrl' ],
1109 model: ActorModel.unscoped(),
1119 return Bluebird.all([
1120 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1121 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1122 ]).then(([ rows, totals ]) => {
1123 // totals: totalVideos + totalVideoShares
1125 let totalVideoShares = 0
1126 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1127 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1129 const total = totalVideos + totalVideoShares
1137 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1138 function buildBaseQuery (): FindOptions {
1142 order: getVideoSort(sort),
1145 model: VideoChannelModel,
1149 model: AccountModel,
1161 const countQuery = buildBaseQuery()
1162 const findQuery = buildBaseQuery()
1164 const findScopes = [
1165 ScopeNames.WITH_SCHEDULED_UPDATE,
1166 ScopeNames.WITH_BLACKLISTED,
1167 ScopeNames.WITH_THUMBNAILS
1170 if (withFiles === true) {
1171 findQuery.include.push({
1172 model: VideoFileModel.unscoped(),
1177 return Promise.all([
1178 VideoModel.count(countQuery),
1179 VideoModel.scope(findScopes).findAll(findQuery)
1180 ]).then(([ count, rows ]) => {
1188 static async listForApi (options: {
1193 includeLocalVideos: boolean,
1195 categoryOneOf?: number[],
1196 licenceOneOf?: number[],
1197 languageOneOf?: string[],
1198 tagsOneOf?: string[],
1199 tagsAllOf?: string[],
1200 filter?: VideoFilter,
1202 videoChannelId?: number,
1203 followerActorId?: number
1204 videoPlaylistId?: number,
1205 trendingDays?: number,
1207 historyOfUser?: UserModel
1208 }, countVideos = true) {
1209 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1210 throw new Error('Try to filter all-local but no user has not the see all videos right')
1213 const query: FindOptions & { where?: null } = {
1214 offset: options.start,
1215 limit: options.count,
1216 order: getVideoSort(options.sort)
1219 let trendingDays: number
1220 if (options.sort.endsWith('trending')) {
1221 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1223 query.group = 'VideoModel.id'
1226 const serverActor = await getServerActor()
1228 // followerActorId === null has a meaning, so just check undefined
1229 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1231 const queryOptions = {
1233 serverAccountId: serverActor.Account.id,
1235 categoryOneOf: options.categoryOneOf,
1236 licenceOneOf: options.licenceOneOf,
1237 languageOneOf: options.languageOneOf,
1238 tagsOneOf: options.tagsOneOf,
1239 tagsAllOf: options.tagsAllOf,
1240 filter: options.filter,
1241 withFiles: options.withFiles,
1242 accountId: options.accountId,
1243 videoChannelId: options.videoChannelId,
1244 videoPlaylistId: options.videoPlaylistId,
1245 includeLocalVideos: options.includeLocalVideos,
1247 historyOfUser: options.historyOfUser,
1251 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1254 static async searchAndPopulateAccountAndServer (options: {
1255 includeLocalVideos: boolean
1260 startDate?: string // ISO 8601
1261 endDate?: string // ISO 8601
1262 originallyPublishedStartDate?: string
1263 originallyPublishedEndDate?: string
1265 categoryOneOf?: number[]
1266 licenceOneOf?: number[]
1267 languageOneOf?: string[]
1268 tagsOneOf?: string[]
1269 tagsAllOf?: string[]
1270 durationMin?: number // seconds
1271 durationMax?: number // seconds
1273 filter?: VideoFilter
1277 if (options.startDate || options.endDate) {
1278 const publishedAtRange = {}
1280 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1281 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1283 whereAnd.push({ publishedAt: publishedAtRange })
1286 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1287 const originallyPublishedAtRange = {}
1289 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1290 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1292 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1295 if (options.durationMin || options.durationMax) {
1296 const durationRange = {}
1298 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1299 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1301 whereAnd.push({ duration: durationRange })
1304 const attributesInclude = []
1305 const escapedSearch = VideoModel.sequelize.escape(options.search)
1306 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1307 if (options.search) {
1311 [ Op.in ]: Sequelize.literal(
1313 'SELECT "video"."id" FROM "video" ' +
1315 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1316 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1318 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1319 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1320 'WHERE "tag"."name" = ' + escapedSearch +
1327 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1330 // Cannot search on similarity if we don't have a search
1331 if (!options.search) {
1332 attributesInclude.push(
1333 Sequelize.literal('0 as similarity')
1339 include: attributesInclude
1341 offset: options.start,
1342 limit: options.count,
1343 order: getVideoSort(options.sort)
1346 const serverActor = await getServerActor()
1347 const queryOptions = {
1348 followerActorId: serverActor.id,
1349 serverAccountId: serverActor.Account.id,
1350 includeLocalVideos: options.includeLocalVideos,
1352 categoryOneOf: options.categoryOneOf,
1353 licenceOneOf: options.licenceOneOf,
1354 languageOneOf: options.languageOneOf,
1355 tagsOneOf: options.tagsOneOf,
1356 tagsAllOf: options.tagsAllOf,
1358 filter: options.filter,
1362 return VideoModel.getAvailableForApi(query, queryOptions)
1365 static load (id: number | string, t?: Transaction) {
1366 const where = buildWhereIdOrUUID(id)
1372 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1375 static loadWithRights (id: number | string, t?: Transaction) {
1376 const where = buildWhereIdOrUUID(id)
1382 return VideoModel.scope([
1383 ScopeNames.WITH_BLACKLISTED,
1384 ScopeNames.WITH_USER_ID,
1385 ScopeNames.WITH_THUMBNAILS
1389 static loadOnlyId (id: number | string, t?: Transaction) {
1390 const where = buildWhereIdOrUUID(id)
1393 attributes: [ 'id' ],
1398 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1401 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1402 return VideoModel.scope([
1403 ScopeNames.WITH_FILES,
1404 ScopeNames.WITH_STREAMING_PLAYLISTS,
1405 ScopeNames.WITH_THUMBNAILS
1406 ]).findByPk(id, { transaction: t, logging })
1409 static loadByUUIDWithFile (uuid: string) {
1416 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1419 static loadByUrl (url: string, transaction?: Transaction) {
1420 const query: FindOptions = {
1427 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1430 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1431 const query: FindOptions = {
1438 return VideoModel.scope([
1439 ScopeNames.WITH_ACCOUNT_DETAILS,
1440 ScopeNames.WITH_FILES,
1441 ScopeNames.WITH_STREAMING_PLAYLISTS,
1442 ScopeNames.WITH_THUMBNAILS
1446 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1447 const where = buildWhereIdOrUUID(id)
1450 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
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_FILES,
1461 ScopeNames.WITH_STREAMING_PLAYLISTS,
1462 ScopeNames.WITH_THUMBNAILS
1466 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1474 static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) {
1475 const where = buildWhereIdOrUUID(id)
1478 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1483 const scopes: (string | ScopeOptions)[] = [
1484 ScopeNames.WITH_TAGS,
1485 ScopeNames.WITH_BLACKLISTED,
1486 ScopeNames.WITH_ACCOUNT_DETAILS,
1487 ScopeNames.WITH_SCHEDULED_UPDATE,
1488 ScopeNames.WITH_THUMBNAILS,
1489 { method: [ ScopeNames.WITH_FILES, true ] },
1490 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1494 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1502 static async getStats () {
1503 const totalLocalVideos = await VideoModel.count({
1508 const totalVideos = await VideoModel.count()
1510 let totalLocalVideoViews = await VideoModel.sum('views', {
1515 // Sequelize could return null...
1516 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1520 totalLocalVideoViews,
1525 static incrementViews (id: number, views: number) {
1526 return VideoModel.increment('views', {
1534 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1535 // Instances only share videos
1536 const query = 'SELECT 1 FROM "videoShare" ' +
1537 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1538 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1542 type: QueryTypes.SELECT,
1543 bind: { followerActorId, videoId },
1547 return VideoModel.sequelize.query(query, options)
1548 .then(results => results.length === 1)
1551 static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) {
1554 channelId: videoChannel.id
1559 return VideoModel.update({ support: videoChannel.support }, options)
1562 static getAllIdsFromChannel (videoChannel: VideoChannelModel) {
1564 attributes: [ 'id' ],
1566 channelId: videoChannel.id
1570 return VideoModel.findAll(query)
1571 .then(videos => videos.map(v => v.id))
1574 // threshold corresponds to how many video the field should have to be returned
1575 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1576 const serverActor = await getServerActor()
1577 const followerActorId = serverActor.id
1579 const scopeOptions: AvailableForListIDsOptions = {
1580 serverAccountId: serverActor.Account.id,
1582 includeLocalVideos: true,
1583 withoutId: true // Don't break aggregation
1586 const query: FindOptions = {
1587 attributes: [ field ],
1590 having: Sequelize.where(
1591 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1593 order: [ (this.sequelize as any).random() ]
1596 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1598 .then(rows => rows.map(r => r[ field ]))
1601 static buildTrendingQuery (trendingDays: number) {
1605 model: VideoViewModel,
1609 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1615 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1616 if (filter && (filter === 'local' || filter === 'all-local')) {
1625 private static async getAvailableForApi (
1626 query: FindOptions & { where?: null }, // Forbid where field in query
1627 options: AvailableForListIDsOptions,
1630 const idsScope: ScopeOptions = {
1632 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1636 // Remove trending sort on count, because it uses a group by
1637 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1638 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1639 const countScope: ScopeOptions = {
1641 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1645 const [ count, ids ] = await Promise.all([
1647 ? VideoModel.scope(countScope).count(countQuery)
1648 : Promise.resolve<number>(undefined),
1650 VideoModel.scope(idsScope)
1652 .then(rows => rows.map(r => r.id))
1655 if (ids.length === 0) return { data: [], total: count }
1657 const secondQuery: FindOptions = {
1660 attributes: query.attributes,
1661 order: [ // Keep original order
1663 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1668 const apiScope: (string | ScopeOptions)[] = []
1671 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1676 ScopeNames.FOR_API, {
1678 withFiles: options.withFiles,
1679 videoPlaylistId: options.videoPlaylistId
1684 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1692 static getCategoryLabel (id: number) {
1693 return VIDEO_CATEGORIES[ id ] || 'Misc'
1696 static getLicenceLabel (id: number) {
1697 return VIDEO_LICENCES[ id ] || 'Unknown'
1700 static getLanguageLabel (id: string) {
1701 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1704 static getPrivacyLabel (id: number) {
1705 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1708 static getStateLabel (id: number) {
1709 return VIDEO_STATES[ id ] || 'Unknown'
1712 getOriginalFile () {
1713 if (Array.isArray(this.VideoFiles) === false) return undefined
1715 // The original file is the file that have the higher resolution
1716 return maxBy(this.VideoFiles, file => file.resolution)
1719 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1720 thumbnail.videoId = this.id
1722 const savedThumbnail = await thumbnail.save({ transaction })
1724 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1726 // Already have this thumbnail, skip
1727 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1729 this.Thumbnails.push(savedThumbnail)
1732 getVideoFilename (videoFile: VideoFileModel) {
1733 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1736 generateThumbnailName () {
1737 return this.uuid + '.jpg'
1741 if (Array.isArray(this.Thumbnails) === false) return undefined
1743 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1746 generatePreviewName () {
1747 return this.uuid + '.jpg'
1751 if (Array.isArray(this.Thumbnails) === false) return undefined
1753 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1756 getTorrentFileName (videoFile: VideoFileModel) {
1757 const extension = '.torrent'
1758 return this.uuid + '-' + videoFile.resolution + extension
1762 return this.remote === false
1765 getTorrentFilePath (videoFile: VideoFileModel) {
1766 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1769 getVideoFilePath (videoFile: VideoFileModel) {
1770 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1773 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1775 // Keep the extname, it's used by the client to stream the file inside a web browser
1776 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1777 createdBy: 'PeerTube',
1779 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1780 [ WEBSERVER.URL + '/tracker/announce' ]
1782 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1785 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1787 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1788 logger.info('Creating torrent %s.', filePath)
1790 await writeFile(filePath, torrent)
1792 const parsedTorrent = parseTorrent(torrent)
1793 videoFile.infoHash = parsedTorrent.infoHash
1796 getWatchStaticPath () {
1797 return '/videos/watch/' + this.uuid
1800 getEmbedStaticPath () {
1801 return '/videos/embed/' + this.uuid
1804 getMiniatureStaticPath () {
1805 const thumbnail = this.getMiniature()
1806 if (!thumbnail) return null
1808 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1811 getPreviewStaticPath () {
1812 const preview = this.getPreview()
1813 if (!preview) return null
1815 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1816 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1819 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1820 return videoModelToFormattedJSON(this, options)
1823 toFormattedDetailsJSON (): VideoDetails {
1824 return videoModelToFormattedDetailsJSON(this)
1827 getFormattedVideoFilesJSON (): VideoFile[] {
1828 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1831 toActivityPubObject (): VideoTorrentObject {
1832 return videoModelToActivityPubObject(this)
1835 getTruncatedDescription () {
1836 if (!this.description) return null
1838 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1839 return peertubeTruncate(this.description, maxLength)
1842 getOriginalFileResolution () {
1843 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1845 return getVideoFileResolution(originalFilePath)
1848 getDescriptionAPIPath () {
1849 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1852 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1853 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1855 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1856 return remove(filePath)
1857 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1860 removeTorrent (videoFile: VideoFileModel) {
1861 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1862 return remove(torrentPath)
1863 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1866 removeStreamingPlaylist (isRedundancy = false) {
1867 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1869 const filePath = join(baseDir, this.uuid)
1870 return remove(filePath)
1871 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1875 if (this.isOwned()) return false
1877 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1881 this.changed('updatedAt', true)
1890 if (this.isOwned()) {
1891 baseUrlHttp = WEBSERVER.URL
1892 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1894 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1895 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1898 return { baseUrlHttp, baseUrlWs }
1901 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1902 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1903 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1904 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1906 const redundancies = videoFile.RedundancyVideos
1907 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1909 const magnetHash = {
1913 infoHash: videoFile.infoHash,
1917 return magnetUtil.encode(magnetHash)
1920 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1921 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1924 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1925 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1928 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1929 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1932 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1933 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1936 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1937 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1940 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1941 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1944 getBandwidthBits (videoFile: VideoFileModel) {
1945 return Math.ceil((videoFile.size * 8) / this.duration)