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 downloadEnabled: boolean
724 waitTranscoding: boolean
728 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
739 @Default(Sequelize.NOW)
743 @ForeignKey(() => VideoChannelModel)
747 @BelongsTo(() => VideoChannelModel, {
753 VideoChannel: VideoChannelModel
755 @BelongsToMany(() => TagModel, {
756 foreignKey: 'videoId',
757 through: () => VideoTagModel,
762 @HasMany(() => VideoAbuseModel, {
769 VideoAbuses: VideoAbuseModel[]
771 @HasMany(() => VideoFileModel, {
779 VideoFiles: VideoFileModel[]
781 @HasMany(() => VideoStreamingPlaylistModel, {
789 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
791 @HasMany(() => VideoShareModel, {
798 VideoShares: VideoShareModel[]
800 @HasMany(() => AccountVideoRateModel, {
807 AccountVideoRates: AccountVideoRateModel[]
809 @HasMany(() => VideoCommentModel, {
817 VideoComments: VideoCommentModel[]
819 @HasMany(() => VideoViewModel, {
826 VideoViews: VideoViewModel[]
828 @HasMany(() => UserVideoHistoryModel, {
835 UserVideoHistories: UserVideoHistoryModel[]
837 @HasOne(() => ScheduleVideoUpdateModel, {
844 ScheduleVideoUpdate: ScheduleVideoUpdateModel
846 @HasOne(() => VideoBlacklistModel, {
853 VideoBlacklist: VideoBlacklistModel
855 @HasOne(() => VideoImportModel, {
862 VideoImport: VideoImportModel
864 @HasMany(() => VideoCaptionModel, {
871 [ 'separate' as any ]: true
873 VideoCaptions: VideoCaptionModel[]
876 static async sendDelete (instance: VideoModel, options) {
877 if (instance.isOwned()) {
878 if (!instance.VideoChannel) {
879 instance.VideoChannel = await instance.$get('VideoChannel', {
883 include: [ ActorModel ]
886 transaction: options.transaction
887 }) as VideoChannelModel
890 return sendDeleteVideo(instance, options.transaction)
897 static async removeFiles (instance: VideoModel) {
898 const tasks: Promise<any>[] = []
900 logger.info('Removing files of video %s.', instance.url)
902 tasks.push(instance.removeThumbnail())
904 if (instance.isOwned()) {
905 if (!Array.isArray(instance.VideoFiles)) {
906 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
909 tasks.push(instance.removePreview())
911 // Remove physical files and torrents
912 instance.VideoFiles.forEach(file => {
913 tasks.push(instance.removeFile(file))
914 tasks.push(instance.removeTorrent(file))
917 // Remove playlists file
918 tasks.push(instance.removeStreamingPlaylist())
921 // Do not wait video deletion because we could be in a transaction
924 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
930 static listLocal () {
937 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
940 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
941 function getRawQuery (select: string) {
942 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
943 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
944 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
945 'WHERE "Account"."actorId" = ' + actorId
946 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
947 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
948 'WHERE "VideoShare"."actorId" = ' + actorId
950 return `(${queryVideo}) UNION (${queryVideoShare})`
953 const rawQuery = getRawQuery('"Video"."id"')
954 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
960 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
963 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
965 [ Sequelize.Op.or ]: [
966 { privacy: VideoPrivacy.PUBLIC },
967 { privacy: VideoPrivacy.UNLISTED }
972 attributes: [ 'language' ],
973 model: VideoCaptionModel.unscoped(),
977 attributes: [ 'id', 'url' ],
978 model: VideoShareModel.unscoped(),
980 // We only want videos shared by this actor
982 [ Sequelize.Op.and ]: [
985 [ Sequelize.Op.not ]: null
995 attributes: [ 'id', 'url' ],
996 model: ActorModel.unscoped()
1001 model: VideoChannelModel.unscoped(),
1005 attributes: [ 'name' ],
1006 model: AccountModel.unscoped(),
1010 attributes: [ 'id', 'url', 'followersUrl' ],
1011 model: ActorModel.unscoped(),
1017 attributes: [ 'id', 'url', 'followersUrl' ],
1018 model: ActorModel.unscoped(),
1028 return Bluebird.all([
1029 // FIXME: typing issue
1030 VideoModel.findAll(query as any),
1031 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1032 ]).then(([ rows, totals ]) => {
1033 // totals: totalVideos + totalVideoShares
1035 let totalVideoShares = 0
1036 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1037 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1039 const total = totalVideos + totalVideoShares
1047 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1048 const query: IFindOptions<VideoModel> = {
1051 order: getVideoSort(sort),
1054 model: VideoChannelModel,
1058 model: AccountModel,
1067 model: ScheduleVideoUpdateModel,
1071 model: VideoBlacklistModel,
1077 if (withFiles === true) {
1078 query.include.push({
1079 model: VideoFileModel.unscoped(),
1084 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1092 static async listForApi (options: {
1097 includeLocalVideos: boolean,
1099 categoryOneOf?: number[],
1100 licenceOneOf?: number[],
1101 languageOneOf?: string[],
1102 tagsOneOf?: string[],
1103 tagsAllOf?: string[],
1104 filter?: VideoFilter,
1106 videoChannelId?: number,
1107 followerActorId?: number
1108 trendingDays?: number,
1110 historyOfUser?: UserModel
1111 }, countVideos = true) {
1112 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1113 throw new Error('Try to filter all-local but no user has not the see all videos right')
1116 const query: IFindOptions<VideoModel> = {
1117 offset: options.start,
1118 limit: options.count,
1119 order: getVideoSort(options.sort)
1122 let trendingDays: number
1123 if (options.sort.endsWith('trending')) {
1124 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1126 query.group = 'VideoModel.id'
1129 const serverActor = await getServerActor()
1131 // followerActorId === null has a meaning, so just check undefined
1132 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1134 const queryOptions = {
1136 serverAccountId: serverActor.Account.id,
1138 categoryOneOf: options.categoryOneOf,
1139 licenceOneOf: options.licenceOneOf,
1140 languageOneOf: options.languageOneOf,
1141 tagsOneOf: options.tagsOneOf,
1142 tagsAllOf: options.tagsAllOf,
1143 filter: options.filter,
1144 withFiles: options.withFiles,
1145 accountId: options.accountId,
1146 videoChannelId: options.videoChannelId,
1147 includeLocalVideos: options.includeLocalVideos,
1149 historyOfUser: options.historyOfUser,
1153 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1156 static async searchAndPopulateAccountAndServer (options: {
1157 includeLocalVideos: boolean
1162 startDate?: string // ISO 8601
1163 endDate?: string // ISO 8601
1165 categoryOneOf?: number[]
1166 licenceOneOf?: number[]
1167 languageOneOf?: string[]
1168 tagsOneOf?: string[]
1169 tagsAllOf?: string[]
1170 durationMin?: number // seconds
1171 durationMax?: number // seconds
1173 filter?: VideoFilter
1177 if (options.startDate || options.endDate) {
1178 const publishedAtRange = {}
1180 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1181 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1183 whereAnd.push({ publishedAt: publishedAtRange })
1186 if (options.durationMin || options.durationMax) {
1187 const durationRange = {}
1189 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1190 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1192 whereAnd.push({ duration: durationRange })
1195 const attributesInclude = []
1196 const escapedSearch = VideoModel.sequelize.escape(options.search)
1197 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1198 if (options.search) {
1202 [ Sequelize.Op.in ]: Sequelize.literal(
1204 'SELECT "video"."id" FROM "video" ' +
1206 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1207 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1209 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1210 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1211 'WHERE "tag"."name" = ' + escapedSearch +
1218 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1221 // Cannot search on similarity if we don't have a search
1222 if (!options.search) {
1223 attributesInclude.push(
1224 Sequelize.literal('0 as similarity')
1228 const query: IFindOptions<VideoModel> = {
1230 include: attributesInclude
1232 offset: options.start,
1233 limit: options.count,
1234 order: getVideoSort(options.sort),
1236 [ Sequelize.Op.and ]: whereAnd
1240 const serverActor = await getServerActor()
1241 const queryOptions = {
1242 followerActorId: serverActor.id,
1243 serverAccountId: serverActor.Account.id,
1244 includeLocalVideos: options.includeLocalVideos,
1246 categoryOneOf: options.categoryOneOf,
1247 licenceOneOf: options.licenceOneOf,
1248 languageOneOf: options.languageOneOf,
1249 tagsOneOf: options.tagsOneOf,
1250 tagsAllOf: options.tagsAllOf,
1252 filter: options.filter
1255 return VideoModel.getAvailableForApi(query, queryOptions)
1258 static load (id: number | string, t?: Sequelize.Transaction) {
1259 const where = VideoModel.buildWhereIdOrUUID(id)
1265 return VideoModel.findOne(options)
1268 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1269 const where = VideoModel.buildWhereIdOrUUID(id)
1275 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1278 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1279 const where = VideoModel.buildWhereIdOrUUID(id)
1282 attributes: [ 'id' ],
1287 return VideoModel.findOne(options)
1290 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1291 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1292 .findById(id, { transaction: t, logging })
1295 static loadByUUIDWithFile (uuid: string) {
1302 return VideoModel.findOne(options)
1305 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1306 const query: IFindOptions<VideoModel> = {
1313 return VideoModel.findOne(query)
1316 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1317 const query: IFindOptions<VideoModel> = {
1324 return VideoModel.scope([
1325 ScopeNames.WITH_ACCOUNT_DETAILS,
1326 ScopeNames.WITH_FILES,
1327 ScopeNames.WITH_STREAMING_PLAYLISTS
1331 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1332 const where = VideoModel.buildWhereIdOrUUID(id)
1335 order: [ [ 'Tags', 'name', 'ASC' ] ],
1341 ScopeNames.WITH_TAGS,
1342 ScopeNames.WITH_BLACKLISTED,
1343 ScopeNames.WITH_ACCOUNT_DETAILS,
1344 ScopeNames.WITH_SCHEDULED_UPDATE,
1345 ScopeNames.WITH_FILES,
1346 ScopeNames.WITH_STREAMING_PLAYLISTS
1350 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1358 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1359 const where = VideoModel.buildWhereIdOrUUID(id)
1362 order: [ [ 'Tags', 'name', 'ASC' ] ],
1368 ScopeNames.WITH_TAGS,
1369 ScopeNames.WITH_BLACKLISTED,
1370 ScopeNames.WITH_ACCOUNT_DETAILS,
1371 ScopeNames.WITH_SCHEDULED_UPDATE,
1372 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1373 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1377 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1385 static async getStats () {
1386 const totalLocalVideos = await VideoModel.count({
1391 const totalVideos = await VideoModel.count()
1393 let totalLocalVideoViews = await VideoModel.sum('views', {
1398 // Sequelize could return null...
1399 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1403 totalLocalVideoViews,
1408 static incrementViews (id: number, views: number) {
1409 return VideoModel.increment('views', {
1417 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1418 // Instances only share videos
1419 const query = 'SELECT 1 FROM "videoShare" ' +
1420 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1421 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1425 type: Sequelize.QueryTypes.SELECT,
1426 bind: { followerActorId, videoId },
1430 return VideoModel.sequelize.query(query, options)
1431 .then(results => results.length === 1)
1434 // threshold corresponds to how many video the field should have to be returned
1435 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1436 const serverActor = await getServerActor()
1437 const followerActorId = serverActor.id
1439 const scopeOptions: AvailableForListIDsOptions = {
1440 serverAccountId: serverActor.Account.id,
1442 includeLocalVideos: true
1445 const query: IFindOptions<VideoModel> = {
1446 attributes: [ field ],
1449 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1450 [ Sequelize.Op.gte ]: threshold
1451 }) as any, // FIXME: typings
1452 order: [ this.sequelize.random() ]
1455 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1457 .then(rows => rows.map(r => r[ field ]))
1460 static buildTrendingQuery (trendingDays: number) {
1464 model: VideoViewModel,
1468 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1474 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1475 if (filter && (filter === 'local' || filter === 'all-local')) {
1484 private static async getAvailableForApi (
1485 query: IFindOptions<VideoModel>,
1486 options: AvailableForListIDsOptions,
1491 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1495 // Remove trending sort on count, because it uses a group by
1496 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1497 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1498 const countScope = {
1500 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1504 const [ count, rowsId ] = await Promise.all([
1505 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1506 VideoModel.scope(idsScope).findAll(query)
1508 const ids = rowsId.map(r => r.id)
1510 if (ids.length === 0) return { data: [], total: count }
1513 const apiScope: any[] = [
1515 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1520 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1523 const secondQuery = {
1526 attributes: query.attributes,
1527 order: [ // Keep original order
1529 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1533 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1541 static getCategoryLabel (id: number) {
1542 return VIDEO_CATEGORIES[ id ] || 'Misc'
1545 static getLicenceLabel (id: number) {
1546 return VIDEO_LICENCES[ id ] || 'Unknown'
1549 static getLanguageLabel (id: string) {
1550 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1553 static getPrivacyLabel (id: number) {
1554 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1557 static getStateLabel (id: number) {
1558 return VIDEO_STATES[ id ] || 'Unknown'
1561 static buildWhereIdOrUUID (id: number | string) {
1562 return validator.isInt('' + id) ? { id } : { uuid: id }
1565 getOriginalFile () {
1566 if (Array.isArray(this.VideoFiles) === false) return undefined
1568 // The original file is the file that have the higher resolution
1569 return maxBy(this.VideoFiles, file => file.resolution)
1572 getVideoFilename (videoFile: VideoFileModel) {
1573 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1576 getThumbnailName () {
1577 // We always have a copy of the thumbnail
1578 const extension = '.jpg'
1579 return this.uuid + extension
1583 const extension = '.jpg'
1584 return this.uuid + extension
1587 getTorrentFileName (videoFile: VideoFileModel) {
1588 const extension = '.torrent'
1589 return this.uuid + '-' + videoFile.resolution + extension
1593 return this.remote === false
1596 createPreview (videoFile: VideoFileModel) {
1597 return generateImageFromVideoFile(
1598 this.getVideoFilePath(videoFile),
1599 CONFIG.STORAGE.PREVIEWS_DIR,
1600 this.getPreviewName(),
1605 createThumbnail (videoFile: VideoFileModel) {
1606 return generateImageFromVideoFile(
1607 this.getVideoFilePath(videoFile),
1608 CONFIG.STORAGE.THUMBNAILS_DIR,
1609 this.getThumbnailName(),
1614 getTorrentFilePath (videoFile: VideoFileModel) {
1615 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1618 getVideoFilePath (videoFile: VideoFileModel) {
1619 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1622 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1624 // Keep the extname, it's used by the client to stream the file inside a web browser
1625 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1626 createdBy: 'PeerTube',
1628 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1629 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1631 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1634 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1636 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1637 logger.info('Creating torrent %s.', filePath)
1639 await writeFile(filePath, torrent)
1641 const parsedTorrent = parseTorrent(torrent)
1642 videoFile.infoHash = parsedTorrent.infoHash
1645 getWatchStaticPath () {
1646 return '/videos/watch/' + this.uuid
1649 getEmbedStaticPath () {
1650 return '/videos/embed/' + this.uuid
1653 getThumbnailStaticPath () {
1654 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1657 getPreviewStaticPath () {
1658 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1661 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1662 return videoModelToFormattedJSON(this, options)
1665 toFormattedDetailsJSON (): VideoDetails {
1666 return videoModelToFormattedDetailsJSON(this)
1669 getFormattedVideoFilesJSON (): VideoFile[] {
1670 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1673 toActivityPubObject (): VideoTorrentObject {
1674 return videoModelToActivityPubObject(this)
1677 getTruncatedDescription () {
1678 if (!this.description) return null
1680 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1681 return peertubeTruncate(this.description, maxLength)
1684 getOriginalFileResolution () {
1685 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1687 return getVideoFileResolution(originalFilePath)
1690 getDescriptionAPIPath () {
1691 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1694 removeThumbnail () {
1695 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1696 return remove(thumbnailPath)
1697 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1701 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1702 return remove(previewPath)
1703 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1706 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1707 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1709 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1710 return remove(filePath)
1711 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1714 removeTorrent (videoFile: VideoFileModel) {
1715 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1716 return remove(torrentPath)
1717 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1720 removeStreamingPlaylist (isRedundancy = false) {
1721 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_PLAYLIST_DIRECTORY
1723 const filePath = join(baseDir, this.uuid)
1724 return remove(filePath)
1725 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1729 if (this.isOwned()) return false
1731 const now = Date.now()
1732 const createdAtTime = this.createdAt.getTime()
1733 const updatedAtTime = this.updatedAt.getTime()
1735 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1736 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1740 this.changed('updatedAt', true)
1749 if (this.isOwned()) {
1750 baseUrlHttp = CONFIG.WEBSERVER.URL
1751 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1753 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1754 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1757 return { baseUrlHttp, baseUrlWs }
1760 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1761 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1762 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1763 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1765 const redundancies = videoFile.RedundancyVideos
1766 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1768 const magnetHash = {
1772 infoHash: videoFile.infoHash,
1776 return magnetUtil.encode(magnetHash)
1779 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1780 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1783 getThumbnailUrl (baseUrlHttp: string) {
1784 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1787 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1788 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1791 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1792 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1795 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1796 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1799 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1800 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1803 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1804 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1807 getBandwidthBits (videoFile: VideoFileModel) {
1808 return Math.ceil((videoFile.size * 8) / this.duration)