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'
6 import * as Sequelize from 'sequelize'
29 } from 'sequelize-typescript'
30 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
55 CONSTRAINTS_FIELDS, HLS_PLAYLIST_DIRECTORY, HLS_REDUNDANCY_DIRECTORY,
58 STATIC_DOWNLOAD_PATHS,
66 } from '../../initializers'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { buildBlockedAccountSQL, buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
81 import { ScheduleVideoUpdateModel } from './schedule-video-update'
82 import { VideoCaptionModel } from './video-caption'
83 import { VideoBlacklistModel } from './video-blacklist'
84 import { remove, writeFile } from 'fs-extra'
85 import { VideoViewModel } from './video-views'
86 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
88 videoFilesModelToFormattedJSON,
89 VideoFormattingJSONOptions,
90 videoModelToActivityPubObject,
91 videoModelToFormattedDetailsJSON,
92 videoModelToFormattedJSON
93 } from './video-format-utils'
94 import * as validator from 'validator'
95 import { UserVideoHistoryModel } from '../account/user-video-history'
96 import { UserModel } from '../account/user'
97 import { VideoImportModel } from './video-import'
98 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
100 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
101 const indexes: Sequelize.DefineIndexesOptions[] = [
102 buildTrigramSearchIndex('video_name_trigram', 'name'),
104 { fields: [ 'createdAt' ] },
105 { fields: [ 'publishedAt' ] },
106 { fields: [ 'duration' ] },
107 { fields: [ 'views' ] },
108 { fields: [ 'channelId' ] },
110 fields: [ 'category' ], // We don't care videos with an unknown category
113 [Sequelize.Op.ne]: null
118 fields: [ 'licence' ], // We don't care videos with an unknown licence
121 [Sequelize.Op.ne]: null
126 fields: [ 'language' ], // We don't care videos with an unknown language
129 [Sequelize.Op.ne]: null
134 fields: [ 'nsfw' ], // Most of the videos are not NSFW
140 fields: [ 'remote' ], // Only index local videos
155 export enum ScopeNames {
156 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
158 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
159 WITH_TAGS = 'WITH_TAGS',
160 WITH_FILES = 'WITH_FILES',
161 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
162 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
163 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
164 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
165 WITH_USER_ID = 'WITH_USER_ID'
168 type ForAPIOptions = {
173 type AvailableForListIDsOptions = {
174 serverAccountId: number
175 followerActorId: number
176 includeLocalVideos: boolean
178 categoryOneOf?: number[]
180 licenceOneOf?: number[]
181 languageOneOf?: string[]
186 videoChannelId?: number
187 trendingDays?: number
189 historyOfUser?: UserModel
193 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
194 const accountInclude = {
195 attributes: [ 'id', 'name' ],
196 model: AccountModel.unscoped(),
200 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
201 model: ActorModel.unscoped(),
205 attributes: [ 'host' ],
206 model: ServerModel.unscoped(),
210 model: AvatarModel.unscoped(),
218 const videoChannelInclude = {
219 attributes: [ 'name', 'description', 'id' ],
220 model: VideoChannelModel.unscoped(),
224 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
225 model: ActorModel.unscoped(),
229 attributes: [ 'host' ],
230 model: ServerModel.unscoped(),
234 model: AvatarModel.unscoped(),
243 const query: IFindOptions<VideoModel> = {
246 [ Sequelize.Op.any ]: options.ids
249 include: [ videoChannelInclude ]
252 if (options.withFiles === true) {
254 model: VideoFileModel.unscoped(),
261 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
262 const query: IFindOptions<VideoModel> = {
264 attributes: [ 'id' ],
267 [ Sequelize.Op.and ]: [
269 [ Sequelize.Op.notIn ]: Sequelize.literal(
270 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
276 [ Sequelize.Op.notIn ]: Sequelize.literal(
278 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
279 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
288 // Only list public/published videos
289 if (!options.filter || options.filter !== 'all-local') {
290 const privacyWhere = {
291 // Always list public videos
292 privacy: VideoPrivacy.PUBLIC,
293 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
294 [ Sequelize.Op.or ]: [
296 state: VideoState.PUBLISHED
299 [ Sequelize.Op.and ]: {
300 state: VideoState.TO_TRANSCODE,
301 waitTranscoding: false
307 Object.assign(query.where, privacyWhere)
310 if (options.filter || options.accountId || options.videoChannelId) {
311 const videoChannelInclude: IIncludeOptions = {
313 model: VideoChannelModel.unscoped(),
317 if (options.videoChannelId) {
318 videoChannelInclude.where = {
319 id: options.videoChannelId
323 if (options.filter || options.accountId) {
324 const accountInclude: IIncludeOptions = {
326 model: AccountModel.unscoped(),
330 if (options.filter) {
331 accountInclude.include = [
334 model: ActorModel.unscoped(),
336 where: VideoModel.buildActorWhereWithFilter(options.filter)
341 if (options.accountId) {
342 accountInclude.where = { id: options.accountId }
345 videoChannelInclude.include = [ accountInclude ]
348 query.include.push(videoChannelInclude)
351 if (options.followerActorId) {
352 let localVideosReq = ''
353 if (options.includeLocalVideos === true) {
354 localVideosReq = ' UNION ALL ' +
355 'SELECT "video"."id" AS "id" FROM "video" ' +
356 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
357 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
358 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
359 'WHERE "actor"."serverId" IS NULL'
362 // Force actorId to be a number to avoid SQL injections
363 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
364 query.where[ 'id' ][ Sequelize.Op.and ].push({
365 [ Sequelize.Op.in ]: Sequelize.literal(
367 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
368 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
369 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
371 'SELECT "video"."id" AS "id" FROM "video" ' +
372 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
373 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
374 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
375 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
376 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
383 if (options.withFiles === true) {
384 query.where[ 'id' ][ Sequelize.Op.and ].push({
385 [ Sequelize.Op.in ]: Sequelize.literal(
386 '(SELECT "videoId" FROM "videoFile")'
391 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
392 if (options.tagsAllOf || options.tagsOneOf) {
393 const createTagsIn = (tags: string[]) => {
394 return tags.map(t => VideoModel.sequelize.escape(t))
398 if (options.tagsOneOf) {
399 query.where[ 'id' ][ Sequelize.Op.and ].push({
400 [ Sequelize.Op.in ]: Sequelize.literal(
402 'SELECT "videoId" FROM "videoTag" ' +
403 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
404 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
410 if (options.tagsAllOf) {
411 query.where[ 'id' ][ Sequelize.Op.and ].push({
412 [ Sequelize.Op.in ]: Sequelize.literal(
414 'SELECT "videoId" FROM "videoTag" ' +
415 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
416 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
417 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
424 if (options.nsfw === true || options.nsfw === false) {
425 query.where[ 'nsfw' ] = options.nsfw
428 if (options.categoryOneOf) {
429 query.where[ 'category' ] = {
430 [ Sequelize.Op.or ]: options.categoryOneOf
434 if (options.licenceOneOf) {
435 query.where[ 'licence' ] = {
436 [ Sequelize.Op.or ]: options.licenceOneOf
440 if (options.languageOneOf) {
441 query.where[ 'language' ] = {
442 [ Sequelize.Op.or ]: options.languageOneOf
446 if (options.trendingDays) {
447 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
449 query.subQuery = false
452 if (options.historyOfUser) {
454 model: UserVideoHistoryModel,
457 userId: options.historyOfUser.id
461 // Even if the relation is n:m, we know that a user only have 0..1 video history
462 // So we won't have multiple rows for the same video
463 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
464 query.subQuery = false
469 [ ScopeNames.WITH_USER_ID ]: {
472 attributes: [ 'accountId' ],
473 model: () => VideoChannelModel.unscoped(),
477 attributes: [ 'userId' ],
478 model: () => AccountModel.unscoped(),
485 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
488 model: () => VideoChannelModel.unscoped(),
493 exclude: [ 'privateKey', 'publicKey' ]
495 model: () => ActorModel.unscoped(),
499 attributes: [ 'host' ],
500 model: () => ServerModel.unscoped(),
504 model: () => AvatarModel.unscoped(),
510 model: () => AccountModel.unscoped(),
514 model: () => ActorModel.unscoped(),
516 exclude: [ 'privateKey', 'publicKey' ]
521 attributes: [ 'host' ],
522 model: () => ServerModel.unscoped(),
526 model: () => AvatarModel.unscoped(),
537 [ ScopeNames.WITH_TAGS ]: {
538 include: [ () => TagModel ]
540 [ ScopeNames.WITH_BLACKLISTED ]: {
543 attributes: [ 'id', 'reason' ],
544 model: () => VideoBlacklistModel,
549 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
550 let subInclude: any[] = []
552 if (withRedundancies === true) {
555 attributes: [ 'fileUrl' ],
556 model: VideoRedundancyModel.unscoped(),
565 model: VideoFileModel.unscoped(),
567 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
574 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
575 let subInclude: any[] = []
577 if (withRedundancies === true) {
580 attributes: [ 'fileUrl' ],
581 model: VideoRedundancyModel.unscoped(),
590 model: VideoStreamingPlaylistModel.unscoped(),
592 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
599 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
602 model: () => ScheduleVideoUpdateModel.unscoped(),
607 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
611 attributes: [ 'currentTime' ],
612 model: UserVideoHistoryModel.unscoped(),
626 export class VideoModel extends Model<VideoModel> {
629 @Default(DataType.UUIDV4)
631 @Column(DataType.UUID)
635 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
641 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
647 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
653 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
654 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
658 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
663 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
669 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
670 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
675 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
676 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
680 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
710 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
711 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
716 commentsEnabled: boolean
720 waitTranscoding: boolean
724 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
735 @Default(Sequelize.NOW)
739 @ForeignKey(() => VideoChannelModel)
743 @BelongsTo(() => VideoChannelModel, {
749 VideoChannel: VideoChannelModel
751 @BelongsToMany(() => TagModel, {
752 foreignKey: 'videoId',
753 through: () => VideoTagModel,
758 @HasMany(() => VideoAbuseModel, {
765 VideoAbuses: VideoAbuseModel[]
767 @HasMany(() => VideoFileModel, {
775 VideoFiles: VideoFileModel[]
777 @HasMany(() => VideoStreamingPlaylistModel, {
785 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
787 @HasMany(() => VideoShareModel, {
794 VideoShares: VideoShareModel[]
796 @HasMany(() => AccountVideoRateModel, {
803 AccountVideoRates: AccountVideoRateModel[]
805 @HasMany(() => VideoCommentModel, {
813 VideoComments: VideoCommentModel[]
815 @HasMany(() => VideoViewModel, {
822 VideoViews: VideoViewModel[]
824 @HasMany(() => UserVideoHistoryModel, {
831 UserVideoHistories: UserVideoHistoryModel[]
833 @HasOne(() => ScheduleVideoUpdateModel, {
840 ScheduleVideoUpdate: ScheduleVideoUpdateModel
842 @HasOne(() => VideoBlacklistModel, {
849 VideoBlacklist: VideoBlacklistModel
851 @HasOne(() => VideoImportModel, {
858 VideoImport: VideoImportModel
860 @HasMany(() => VideoCaptionModel, {
867 [ 'separate' as any ]: true
869 VideoCaptions: VideoCaptionModel[]
872 static async sendDelete (instance: VideoModel, options) {
873 if (instance.isOwned()) {
874 if (!instance.VideoChannel) {
875 instance.VideoChannel = await instance.$get('VideoChannel', {
879 include: [ ActorModel ]
882 transaction: options.transaction
883 }) as VideoChannelModel
886 return sendDeleteVideo(instance, options.transaction)
893 static async removeFiles (instance: VideoModel) {
894 const tasks: Promise<any>[] = []
896 logger.info('Removing files of video %s.', instance.url)
898 tasks.push(instance.removeThumbnail())
900 if (instance.isOwned()) {
901 if (!Array.isArray(instance.VideoFiles)) {
902 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
905 tasks.push(instance.removePreview())
907 // Remove physical files and torrents
908 instance.VideoFiles.forEach(file => {
909 tasks.push(instance.removeFile(file))
910 tasks.push(instance.removeTorrent(file))
913 // Remove playlists file
914 tasks.push(instance.removeStreamingPlaylist())
917 // Do not wait video deletion because we could be in a transaction
920 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
926 static listLocal () {
933 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
936 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
937 function getRawQuery (select: string) {
938 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
939 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
940 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
941 'WHERE "Account"."actorId" = ' + actorId
942 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
943 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
944 'WHERE "VideoShare"."actorId" = ' + actorId
946 return `(${queryVideo}) UNION (${queryVideoShare})`
949 const rawQuery = getRawQuery('"Video"."id"')
950 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
956 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
959 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
961 [ Sequelize.Op.or ]: [
962 { privacy: VideoPrivacy.PUBLIC },
963 { privacy: VideoPrivacy.UNLISTED }
968 attributes: [ 'language' ],
969 model: VideoCaptionModel.unscoped(),
973 attributes: [ 'id', 'url' ],
974 model: VideoShareModel.unscoped(),
976 // We only want videos shared by this actor
978 [ Sequelize.Op.and ]: [
981 [ Sequelize.Op.not ]: null
991 attributes: [ 'id', 'url' ],
992 model: ActorModel.unscoped()
997 model: VideoChannelModel.unscoped(),
1001 attributes: [ 'name' ],
1002 model: AccountModel.unscoped(),
1006 attributes: [ 'id', 'url', 'followersUrl' ],
1007 model: ActorModel.unscoped(),
1013 attributes: [ 'id', 'url', 'followersUrl' ],
1014 model: ActorModel.unscoped(),
1024 return Bluebird.all([
1025 // FIXME: typing issue
1026 VideoModel.findAll(query as any),
1027 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1028 ]).then(([ rows, totals ]) => {
1029 // totals: totalVideos + totalVideoShares
1031 let totalVideoShares = 0
1032 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1033 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1035 const total = totalVideos + totalVideoShares
1043 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1044 const query: IFindOptions<VideoModel> = {
1047 order: getVideoSort(sort),
1050 model: VideoChannelModel,
1054 model: AccountModel,
1063 model: ScheduleVideoUpdateModel,
1067 model: VideoBlacklistModel,
1073 if (withFiles === true) {
1074 query.include.push({
1075 model: VideoFileModel.unscoped(),
1080 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1088 static async listForApi (options: {
1093 includeLocalVideos: boolean,
1095 categoryOneOf?: number[],
1096 licenceOneOf?: number[],
1097 languageOneOf?: string[],
1098 tagsOneOf?: string[],
1099 tagsAllOf?: string[],
1100 filter?: VideoFilter,
1102 videoChannelId?: number,
1103 followerActorId?: number
1104 trendingDays?: number,
1106 historyOfUser?: UserModel
1107 }, countVideos = true) {
1108 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1109 throw new Error('Try to filter all-local but no user has not the see all videos right')
1112 const query: IFindOptions<VideoModel> = {
1113 offset: options.start,
1114 limit: options.count,
1115 order: getVideoSort(options.sort)
1118 let trendingDays: number
1119 if (options.sort.endsWith('trending')) {
1120 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1122 query.group = 'VideoModel.id'
1125 const serverActor = await getServerActor()
1127 // followerActorId === null has a meaning, so just check undefined
1128 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1130 const queryOptions = {
1132 serverAccountId: serverActor.Account.id,
1134 categoryOneOf: options.categoryOneOf,
1135 licenceOneOf: options.licenceOneOf,
1136 languageOneOf: options.languageOneOf,
1137 tagsOneOf: options.tagsOneOf,
1138 tagsAllOf: options.tagsAllOf,
1139 filter: options.filter,
1140 withFiles: options.withFiles,
1141 accountId: options.accountId,
1142 videoChannelId: options.videoChannelId,
1143 includeLocalVideos: options.includeLocalVideos,
1145 historyOfUser: options.historyOfUser,
1149 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1152 static async searchAndPopulateAccountAndServer (options: {
1153 includeLocalVideos: boolean
1158 startDate?: string // ISO 8601
1159 endDate?: string // ISO 8601
1161 categoryOneOf?: number[]
1162 licenceOneOf?: number[]
1163 languageOneOf?: string[]
1164 tagsOneOf?: string[]
1165 tagsAllOf?: string[]
1166 durationMin?: number // seconds
1167 durationMax?: number // seconds
1169 filter?: VideoFilter
1173 if (options.startDate || options.endDate) {
1174 const publishedAtRange = {}
1176 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1177 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1179 whereAnd.push({ publishedAt: publishedAtRange })
1182 if (options.durationMin || options.durationMax) {
1183 const durationRange = {}
1185 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1186 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1188 whereAnd.push({ duration: durationRange })
1191 const attributesInclude = []
1192 const escapedSearch = VideoModel.sequelize.escape(options.search)
1193 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1194 if (options.search) {
1198 [ Sequelize.Op.in ]: Sequelize.literal(
1200 'SELECT "video"."id" FROM "video" ' +
1202 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1203 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1205 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1206 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1207 'WHERE "tag"."name" = ' + escapedSearch +
1214 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1217 // Cannot search on similarity if we don't have a search
1218 if (!options.search) {
1219 attributesInclude.push(
1220 Sequelize.literal('0 as similarity')
1224 const query: IFindOptions<VideoModel> = {
1226 include: attributesInclude
1228 offset: options.start,
1229 limit: options.count,
1230 order: getVideoSort(options.sort),
1232 [ Sequelize.Op.and ]: whereAnd
1236 const serverActor = await getServerActor()
1237 const queryOptions = {
1238 followerActorId: serverActor.id,
1239 serverAccountId: serverActor.Account.id,
1240 includeLocalVideos: options.includeLocalVideos,
1242 categoryOneOf: options.categoryOneOf,
1243 licenceOneOf: options.licenceOneOf,
1244 languageOneOf: options.languageOneOf,
1245 tagsOneOf: options.tagsOneOf,
1246 tagsAllOf: options.tagsAllOf,
1248 filter: options.filter
1251 return VideoModel.getAvailableForApi(query, queryOptions)
1254 static load (id: number | string, t?: Sequelize.Transaction) {
1255 const where = VideoModel.buildWhereIdOrUUID(id)
1261 return VideoModel.findOne(options)
1264 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1265 const where = VideoModel.buildWhereIdOrUUID(id)
1271 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1274 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1275 const where = VideoModel.buildWhereIdOrUUID(id)
1278 attributes: [ 'id' ],
1283 return VideoModel.findOne(options)
1286 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1287 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1288 .findById(id, { transaction: t, logging })
1291 static loadByUUIDWithFile (uuid: string) {
1298 return VideoModel.findOne(options)
1301 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1302 const query: IFindOptions<VideoModel> = {
1309 return VideoModel.findOne(query)
1312 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1313 const query: IFindOptions<VideoModel> = {
1320 return VideoModel.scope([
1321 ScopeNames.WITH_ACCOUNT_DETAILS,
1322 ScopeNames.WITH_FILES,
1323 ScopeNames.WITH_STREAMING_PLAYLISTS
1327 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1328 const where = VideoModel.buildWhereIdOrUUID(id)
1331 order: [ [ 'Tags', 'name', 'ASC' ] ],
1337 ScopeNames.WITH_TAGS,
1338 ScopeNames.WITH_BLACKLISTED,
1339 ScopeNames.WITH_ACCOUNT_DETAILS,
1340 ScopeNames.WITH_SCHEDULED_UPDATE,
1341 ScopeNames.WITH_FILES,
1342 ScopeNames.WITH_STREAMING_PLAYLISTS
1346 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1354 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1355 const where = VideoModel.buildWhereIdOrUUID(id)
1358 order: [ [ 'Tags', 'name', 'ASC' ] ],
1364 ScopeNames.WITH_TAGS,
1365 ScopeNames.WITH_BLACKLISTED,
1366 ScopeNames.WITH_ACCOUNT_DETAILS,
1367 ScopeNames.WITH_SCHEDULED_UPDATE,
1368 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1369 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1373 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1381 static async getStats () {
1382 const totalLocalVideos = await VideoModel.count({
1387 const totalVideos = await VideoModel.count()
1389 let totalLocalVideoViews = await VideoModel.sum('views', {
1394 // Sequelize could return null...
1395 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1399 totalLocalVideoViews,
1404 static incrementViews (id: number, views: number) {
1405 return VideoModel.increment('views', {
1413 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1414 // Instances only share videos
1415 const query = 'SELECT 1 FROM "videoShare" ' +
1416 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1417 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1421 type: Sequelize.QueryTypes.SELECT,
1422 bind: { followerActorId, videoId },
1426 return VideoModel.sequelize.query(query, options)
1427 .then(results => results.length === 1)
1430 // threshold corresponds to how many video the field should have to be returned
1431 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1432 const serverActor = await getServerActor()
1433 const followerActorId = serverActor.id
1435 const scopeOptions: AvailableForListIDsOptions = {
1436 serverAccountId: serverActor.Account.id,
1438 includeLocalVideos: true
1441 const query: IFindOptions<VideoModel> = {
1442 attributes: [ field ],
1445 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1446 [ Sequelize.Op.gte ]: threshold
1447 }) as any, // FIXME: typings
1448 order: [ this.sequelize.random() ]
1451 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1453 .then(rows => rows.map(r => r[ field ]))
1456 static buildTrendingQuery (trendingDays: number) {
1460 model: VideoViewModel,
1464 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1470 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1471 if (filter && (filter === 'local' || filter === 'all-local')) {
1480 private static async getAvailableForApi (
1481 query: IFindOptions<VideoModel>,
1482 options: AvailableForListIDsOptions,
1487 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1491 // Remove trending sort on count, because it uses a group by
1492 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1493 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1494 const countScope = {
1496 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1500 const [ count, rowsId ] = await Promise.all([
1501 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1502 VideoModel.scope(idsScope).findAll(query)
1504 const ids = rowsId.map(r => r.id)
1506 if (ids.length === 0) return { data: [], total: count }
1509 const apiScope: any[] = [
1511 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1516 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1519 const secondQuery = {
1522 attributes: query.attributes,
1523 order: [ // Keep original order
1525 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1529 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1537 static getCategoryLabel (id: number) {
1538 return VIDEO_CATEGORIES[ id ] || 'Misc'
1541 static getLicenceLabel (id: number) {
1542 return VIDEO_LICENCES[ id ] || 'Unknown'
1545 static getLanguageLabel (id: string) {
1546 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1549 static getPrivacyLabel (id: number) {
1550 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1553 static getStateLabel (id: number) {
1554 return VIDEO_STATES[ id ] || 'Unknown'
1557 static buildWhereIdOrUUID (id: number | string) {
1558 return validator.isInt('' + id) ? { id } : { uuid: id }
1561 getOriginalFile () {
1562 if (Array.isArray(this.VideoFiles) === false) return undefined
1564 // The original file is the file that have the higher resolution
1565 return maxBy(this.VideoFiles, file => file.resolution)
1568 getVideoFilename (videoFile: VideoFileModel) {
1569 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1572 getThumbnailName () {
1573 // We always have a copy of the thumbnail
1574 const extension = '.jpg'
1575 return this.uuid + extension
1579 const extension = '.jpg'
1580 return this.uuid + extension
1583 getTorrentFileName (videoFile: VideoFileModel) {
1584 const extension = '.torrent'
1585 return this.uuid + '-' + videoFile.resolution + extension
1589 return this.remote === false
1592 createPreview (videoFile: VideoFileModel) {
1593 return generateImageFromVideoFile(
1594 this.getVideoFilePath(videoFile),
1595 CONFIG.STORAGE.PREVIEWS_DIR,
1596 this.getPreviewName(),
1601 createThumbnail (videoFile: VideoFileModel) {
1602 return generateImageFromVideoFile(
1603 this.getVideoFilePath(videoFile),
1604 CONFIG.STORAGE.THUMBNAILS_DIR,
1605 this.getThumbnailName(),
1610 getTorrentFilePath (videoFile: VideoFileModel) {
1611 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1614 getVideoFilePath (videoFile: VideoFileModel) {
1615 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1618 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1620 // Keep the extname, it's used by the client to stream the file inside a web browser
1621 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1622 createdBy: 'PeerTube',
1624 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1625 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1627 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1630 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1632 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1633 logger.info('Creating torrent %s.', filePath)
1635 await writeFile(filePath, torrent)
1637 const parsedTorrent = parseTorrent(torrent)
1638 videoFile.infoHash = parsedTorrent.infoHash
1641 getWatchStaticPath () {
1642 return '/videos/watch/' + this.uuid
1645 getEmbedStaticPath () {
1646 return '/videos/embed/' + this.uuid
1649 getThumbnailStaticPath () {
1650 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1653 getPreviewStaticPath () {
1654 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1657 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1658 return videoModelToFormattedJSON(this, options)
1661 toFormattedDetailsJSON (): VideoDetails {
1662 return videoModelToFormattedDetailsJSON(this)
1665 getFormattedVideoFilesJSON (): VideoFile[] {
1666 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1669 toActivityPubObject (): VideoTorrentObject {
1670 return videoModelToActivityPubObject(this)
1673 getTruncatedDescription () {
1674 if (!this.description) return null
1676 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1677 return peertubeTruncate(this.description, maxLength)
1680 getOriginalFileResolution () {
1681 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1683 return getVideoFileResolution(originalFilePath)
1686 getDescriptionAPIPath () {
1687 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1690 removeThumbnail () {
1691 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1692 return remove(thumbnailPath)
1693 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1697 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1698 return remove(previewPath)
1699 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1702 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1703 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1705 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1706 return remove(filePath)
1707 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1710 removeTorrent (videoFile: VideoFileModel) {
1711 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1712 return remove(torrentPath)
1713 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1716 removeStreamingPlaylist (isRedundancy = false) {
1717 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_PLAYLIST_DIRECTORY
1719 const filePath = join(baseDir, this.uuid)
1720 return remove(filePath)
1721 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1725 if (this.isOwned()) return false
1727 const now = Date.now()
1728 const createdAtTime = this.createdAt.getTime()
1729 const updatedAtTime = this.updatedAt.getTime()
1731 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1732 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1736 this.changed('updatedAt', true)
1745 if (this.isOwned()) {
1746 baseUrlHttp = CONFIG.WEBSERVER.URL
1747 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1749 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1750 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1753 return { baseUrlHttp, baseUrlWs }
1756 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1757 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1758 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1759 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1761 const redundancies = videoFile.RedundancyVideos
1762 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1764 const magnetHash = {
1768 infoHash: videoFile.infoHash,
1772 return magnetUtil.encode(magnetHash)
1775 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1776 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1779 getThumbnailUrl (baseUrlHttp: string) {
1780 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1783 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1784 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1787 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1788 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1791 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1792 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1795 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1796 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1799 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1800 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1803 getBandwidthBits (videoFile: VideoFileModel) {
1804 return Math.ceil((videoFile.size * 8) / this.duration)