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,
43 isVideoNameValid, isVideoOriginallyPublishedAtValid,
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: [ 'originallyPublishedAt' ],
112 originallyPublishedAt: {
113 [Sequelize.Op.ne]: null
118 fields: [ 'category' ], // We don't care videos with an unknown category
121 [Sequelize.Op.ne]: null
126 fields: [ 'licence' ], // We don't care videos with an unknown licence
129 [Sequelize.Op.ne]: null
134 fields: [ 'language' ], // We don't care videos with an unknown language
137 [Sequelize.Op.ne]: null
142 fields: [ 'nsfw' ], // Most of the videos are not NSFW
148 fields: [ 'remote' ], // Only index local videos
163 export enum ScopeNames {
164 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
166 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
167 WITH_TAGS = 'WITH_TAGS',
168 WITH_FILES = 'WITH_FILES',
169 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
170 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
171 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
172 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
173 WITH_USER_ID = 'WITH_USER_ID'
176 type ForAPIOptions = {
181 type AvailableForListIDsOptions = {
182 serverAccountId: number
183 followerActorId: number
184 includeLocalVideos: boolean
186 categoryOneOf?: number[]
188 licenceOneOf?: number[]
189 languageOneOf?: string[]
194 videoChannelId?: number
195 trendingDays?: number
197 historyOfUser?: UserModel
201 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
202 const accountInclude = {
203 attributes: [ 'id', 'name' ],
204 model: AccountModel.unscoped(),
208 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
209 model: ActorModel.unscoped(),
213 attributes: [ 'host' ],
214 model: ServerModel.unscoped(),
218 model: AvatarModel.unscoped(),
226 const videoChannelInclude = {
227 attributes: [ 'name', 'description', 'id' ],
228 model: VideoChannelModel.unscoped(),
232 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
233 model: ActorModel.unscoped(),
237 attributes: [ 'host' ],
238 model: ServerModel.unscoped(),
242 model: AvatarModel.unscoped(),
251 const query: IFindOptions<VideoModel> = {
254 [ Sequelize.Op.any ]: options.ids
257 include: [ videoChannelInclude ]
260 if (options.withFiles === true) {
262 model: VideoFileModel.unscoped(),
269 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
270 const query: IFindOptions<VideoModel> = {
272 attributes: [ 'id' ],
275 [ Sequelize.Op.and ]: [
277 [ Sequelize.Op.notIn ]: Sequelize.literal(
278 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
284 [ Sequelize.Op.notIn ]: Sequelize.literal(
286 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
287 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
296 // Only list public/published videos
297 if (!options.filter || options.filter !== 'all-local') {
298 const privacyWhere = {
299 // Always list public videos
300 privacy: VideoPrivacy.PUBLIC,
301 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
302 [ Sequelize.Op.or ]: [
304 state: VideoState.PUBLISHED
307 [ Sequelize.Op.and ]: {
308 state: VideoState.TO_TRANSCODE,
309 waitTranscoding: false
315 Object.assign(query.where, privacyWhere)
318 if (options.filter || options.accountId || options.videoChannelId) {
319 const videoChannelInclude: IIncludeOptions = {
321 model: VideoChannelModel.unscoped(),
325 if (options.videoChannelId) {
326 videoChannelInclude.where = {
327 id: options.videoChannelId
331 if (options.filter || options.accountId) {
332 const accountInclude: IIncludeOptions = {
334 model: AccountModel.unscoped(),
338 if (options.filter) {
339 accountInclude.include = [
342 model: ActorModel.unscoped(),
344 where: VideoModel.buildActorWhereWithFilter(options.filter)
349 if (options.accountId) {
350 accountInclude.where = { id: options.accountId }
353 videoChannelInclude.include = [ accountInclude ]
356 query.include.push(videoChannelInclude)
359 if (options.followerActorId) {
360 let localVideosReq = ''
361 if (options.includeLocalVideos === true) {
362 localVideosReq = ' UNION ALL ' +
363 'SELECT "video"."id" AS "id" FROM "video" ' +
364 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
365 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
366 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
367 'WHERE "actor"."serverId" IS NULL'
370 // Force actorId to be a number to avoid SQL injections
371 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
372 query.where[ 'id' ][ Sequelize.Op.and ].push({
373 [ Sequelize.Op.in ]: Sequelize.literal(
375 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
376 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
377 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
379 'SELECT "video"."id" AS "id" FROM "video" ' +
380 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
381 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
382 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
383 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
384 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
391 if (options.withFiles === true) {
392 query.where[ 'id' ][ Sequelize.Op.and ].push({
393 [ Sequelize.Op.in ]: Sequelize.literal(
394 '(SELECT "videoId" FROM "videoFile")'
399 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
400 if (options.tagsAllOf || options.tagsOneOf) {
401 const createTagsIn = (tags: string[]) => {
402 return tags.map(t => VideoModel.sequelize.escape(t))
406 if (options.tagsOneOf) {
407 query.where[ 'id' ][ Sequelize.Op.and ].push({
408 [ Sequelize.Op.in ]: Sequelize.literal(
410 'SELECT "videoId" FROM "videoTag" ' +
411 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
412 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
418 if (options.tagsAllOf) {
419 query.where[ 'id' ][ Sequelize.Op.and ].push({
420 [ Sequelize.Op.in ]: Sequelize.literal(
422 'SELECT "videoId" FROM "videoTag" ' +
423 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
424 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
425 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
432 if (options.nsfw === true || options.nsfw === false) {
433 query.where[ 'nsfw' ] = options.nsfw
436 if (options.categoryOneOf) {
437 query.where[ 'category' ] = {
438 [ Sequelize.Op.or ]: options.categoryOneOf
442 if (options.licenceOneOf) {
443 query.where[ 'licence' ] = {
444 [ Sequelize.Op.or ]: options.licenceOneOf
448 if (options.languageOneOf) {
449 query.where[ 'language' ] = {
450 [ Sequelize.Op.or ]: options.languageOneOf
454 if (options.trendingDays) {
455 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
457 query.subQuery = false
460 if (options.historyOfUser) {
462 model: UserVideoHistoryModel,
465 userId: options.historyOfUser.id
469 // Even if the relation is n:m, we know that a user only have 0..1 video history
470 // So we won't have multiple rows for the same video
471 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
472 query.subQuery = false
477 [ ScopeNames.WITH_USER_ID ]: {
480 attributes: [ 'accountId' ],
481 model: () => VideoChannelModel.unscoped(),
485 attributes: [ 'userId' ],
486 model: () => AccountModel.unscoped(),
493 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
496 model: () => VideoChannelModel.unscoped(),
501 exclude: [ 'privateKey', 'publicKey' ]
503 model: () => ActorModel.unscoped(),
507 attributes: [ 'host' ],
508 model: () => ServerModel.unscoped(),
512 model: () => AvatarModel.unscoped(),
518 model: () => AccountModel.unscoped(),
522 model: () => ActorModel.unscoped(),
524 exclude: [ 'privateKey', 'publicKey' ]
529 attributes: [ 'host' ],
530 model: () => ServerModel.unscoped(),
534 model: () => AvatarModel.unscoped(),
545 [ ScopeNames.WITH_TAGS ]: {
546 include: [ () => TagModel ]
548 [ ScopeNames.WITH_BLACKLISTED ]: {
551 attributes: [ 'id', 'reason' ],
552 model: () => VideoBlacklistModel,
557 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
558 let subInclude: any[] = []
560 if (withRedundancies === true) {
563 attributes: [ 'fileUrl' ],
564 model: VideoRedundancyModel.unscoped(),
573 model: VideoFileModel.unscoped(),
575 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
582 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
583 let subInclude: any[] = []
585 if (withRedundancies === true) {
588 attributes: [ 'fileUrl' ],
589 model: VideoRedundancyModel.unscoped(),
598 model: VideoStreamingPlaylistModel.unscoped(),
600 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
607 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
610 model: () => ScheduleVideoUpdateModel.unscoped(),
615 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
619 attributes: [ 'currentTime' ],
620 model: UserVideoHistoryModel.unscoped(),
634 export class VideoModel extends Model<VideoModel> {
637 @Default(DataType.UUIDV4)
639 @Column(DataType.UUID)
643 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
649 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
655 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
661 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
662 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
666 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
671 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
677 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
678 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
683 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
684 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
688 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
718 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
719 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
724 commentsEnabled: boolean
728 downloadEnabled: boolean
732 waitTranscoding: boolean
736 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
747 @Default(Sequelize.NOW)
754 originallyPublishedAt: Date
756 @ForeignKey(() => VideoChannelModel)
760 @BelongsTo(() => VideoChannelModel, {
766 VideoChannel: VideoChannelModel
768 @BelongsToMany(() => TagModel, {
769 foreignKey: 'videoId',
770 through: () => VideoTagModel,
775 @HasMany(() => VideoAbuseModel, {
782 VideoAbuses: VideoAbuseModel[]
784 @HasMany(() => VideoFileModel, {
792 VideoFiles: VideoFileModel[]
794 @HasMany(() => VideoStreamingPlaylistModel, {
802 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
804 @HasMany(() => VideoShareModel, {
811 VideoShares: VideoShareModel[]
813 @HasMany(() => AccountVideoRateModel, {
820 AccountVideoRates: AccountVideoRateModel[]
822 @HasMany(() => VideoCommentModel, {
830 VideoComments: VideoCommentModel[]
832 @HasMany(() => VideoViewModel, {
839 VideoViews: VideoViewModel[]
841 @HasMany(() => UserVideoHistoryModel, {
848 UserVideoHistories: UserVideoHistoryModel[]
850 @HasOne(() => ScheduleVideoUpdateModel, {
857 ScheduleVideoUpdate: ScheduleVideoUpdateModel
859 @HasOne(() => VideoBlacklistModel, {
866 VideoBlacklist: VideoBlacklistModel
868 @HasOne(() => VideoImportModel, {
875 VideoImport: VideoImportModel
877 @HasMany(() => VideoCaptionModel, {
884 [ 'separate' as any ]: true
886 VideoCaptions: VideoCaptionModel[]
889 static async sendDelete (instance: VideoModel, options) {
890 if (instance.isOwned()) {
891 if (!instance.VideoChannel) {
892 instance.VideoChannel = await instance.$get('VideoChannel', {
896 include: [ ActorModel ]
899 transaction: options.transaction
900 }) as VideoChannelModel
903 return sendDeleteVideo(instance, options.transaction)
910 static async removeFiles (instance: VideoModel) {
911 const tasks: Promise<any>[] = []
913 logger.info('Removing files of video %s.', instance.url)
915 tasks.push(instance.removeThumbnail())
917 if (instance.isOwned()) {
918 if (!Array.isArray(instance.VideoFiles)) {
919 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
922 tasks.push(instance.removePreview())
924 // Remove physical files and torrents
925 instance.VideoFiles.forEach(file => {
926 tasks.push(instance.removeFile(file))
927 tasks.push(instance.removeTorrent(file))
930 // Remove playlists file
931 tasks.push(instance.removeStreamingPlaylist())
934 // Do not wait video deletion because we could be in a transaction
937 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
943 static listLocal () {
950 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
953 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
954 function getRawQuery (select: string) {
955 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
956 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
957 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
958 'WHERE "Account"."actorId" = ' + actorId
959 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
960 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
961 'WHERE "VideoShare"."actorId" = ' + actorId
963 return `(${queryVideo}) UNION (${queryVideoShare})`
966 const rawQuery = getRawQuery('"Video"."id"')
967 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
973 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
976 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
978 [ Sequelize.Op.or ]: [
979 { privacy: VideoPrivacy.PUBLIC },
980 { privacy: VideoPrivacy.UNLISTED }
985 attributes: [ 'language' ],
986 model: VideoCaptionModel.unscoped(),
990 attributes: [ 'id', 'url' ],
991 model: VideoShareModel.unscoped(),
993 // We only want videos shared by this actor
995 [ Sequelize.Op.and ]: [
998 [ Sequelize.Op.not ]: null
1008 attributes: [ 'id', 'url' ],
1009 model: ActorModel.unscoped()
1014 model: VideoChannelModel.unscoped(),
1018 attributes: [ 'name' ],
1019 model: AccountModel.unscoped(),
1023 attributes: [ 'id', 'url', 'followersUrl' ],
1024 model: ActorModel.unscoped(),
1030 attributes: [ 'id', 'url', 'followersUrl' ],
1031 model: ActorModel.unscoped(),
1041 return Bluebird.all([
1042 // FIXME: typing issue
1043 VideoModel.findAll(query as any),
1044 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1045 ]).then(([ rows, totals ]) => {
1046 // totals: totalVideos + totalVideoShares
1048 let totalVideoShares = 0
1049 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1050 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1052 const total = totalVideos + totalVideoShares
1060 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1061 const query: IFindOptions<VideoModel> = {
1064 order: getVideoSort(sort),
1067 model: VideoChannelModel,
1071 model: AccountModel,
1080 model: ScheduleVideoUpdateModel,
1084 model: VideoBlacklistModel,
1090 if (withFiles === true) {
1091 query.include.push({
1092 model: VideoFileModel.unscoped(),
1097 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1105 static async listForApi (options: {
1110 includeLocalVideos: boolean,
1112 categoryOneOf?: number[],
1113 licenceOneOf?: number[],
1114 languageOneOf?: string[],
1115 tagsOneOf?: string[],
1116 tagsAllOf?: string[],
1117 filter?: VideoFilter,
1119 videoChannelId?: number,
1120 followerActorId?: number
1121 trendingDays?: number,
1123 historyOfUser?: UserModel
1124 }, countVideos = true) {
1125 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1126 throw new Error('Try to filter all-local but no user has not the see all videos right')
1129 const query: IFindOptions<VideoModel> = {
1130 offset: options.start,
1131 limit: options.count,
1132 order: getVideoSort(options.sort)
1135 let trendingDays: number
1136 if (options.sort.endsWith('trending')) {
1137 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1139 query.group = 'VideoModel.id'
1142 const serverActor = await getServerActor()
1144 // followerActorId === null has a meaning, so just check undefined
1145 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1147 const queryOptions = {
1149 serverAccountId: serverActor.Account.id,
1151 categoryOneOf: options.categoryOneOf,
1152 licenceOneOf: options.licenceOneOf,
1153 languageOneOf: options.languageOneOf,
1154 tagsOneOf: options.tagsOneOf,
1155 tagsAllOf: options.tagsAllOf,
1156 filter: options.filter,
1157 withFiles: options.withFiles,
1158 accountId: options.accountId,
1159 videoChannelId: options.videoChannelId,
1160 includeLocalVideos: options.includeLocalVideos,
1162 historyOfUser: options.historyOfUser,
1166 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1169 static async searchAndPopulateAccountAndServer (options: {
1170 includeLocalVideos: boolean
1175 startDate?: string // ISO 8601
1176 endDate?: string // ISO 8601
1177 originallyPublishedStartDate?: string
1178 originallyPublishedEndDate?: string
1180 categoryOneOf?: number[]
1181 licenceOneOf?: number[]
1182 languageOneOf?: string[]
1183 tagsOneOf?: string[]
1184 tagsAllOf?: string[]
1185 durationMin?: number // seconds
1186 durationMax?: number // seconds
1188 filter?: VideoFilter
1192 if (options.startDate || options.endDate) {
1193 const publishedAtRange = {}
1195 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1196 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1198 whereAnd.push({ publishedAt: publishedAtRange })
1201 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1202 const originallyPublishedAtRange = {}
1204 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1205 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1207 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1210 if (options.durationMin || options.durationMax) {
1211 const durationRange = {}
1213 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1214 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1216 whereAnd.push({ duration: durationRange })
1219 const attributesInclude = []
1220 const escapedSearch = VideoModel.sequelize.escape(options.search)
1221 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1222 if (options.search) {
1226 [ Sequelize.Op.in ]: Sequelize.literal(
1228 'SELECT "video"."id" FROM "video" ' +
1230 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1231 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1233 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1234 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1235 'WHERE "tag"."name" = ' + escapedSearch +
1242 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1245 // Cannot search on similarity if we don't have a search
1246 if (!options.search) {
1247 attributesInclude.push(
1248 Sequelize.literal('0 as similarity')
1252 const query: IFindOptions<VideoModel> = {
1254 include: attributesInclude
1256 offset: options.start,
1257 limit: options.count,
1258 order: getVideoSort(options.sort),
1260 [ Sequelize.Op.and ]: whereAnd
1264 const serverActor = await getServerActor()
1265 const queryOptions = {
1266 followerActorId: serverActor.id,
1267 serverAccountId: serverActor.Account.id,
1268 includeLocalVideos: options.includeLocalVideos,
1270 categoryOneOf: options.categoryOneOf,
1271 licenceOneOf: options.licenceOneOf,
1272 languageOneOf: options.languageOneOf,
1273 tagsOneOf: options.tagsOneOf,
1274 tagsAllOf: options.tagsAllOf,
1276 filter: options.filter
1279 return VideoModel.getAvailableForApi(query, queryOptions)
1282 static load (id: number | string, t?: Sequelize.Transaction) {
1283 const where = VideoModel.buildWhereIdOrUUID(id)
1289 return VideoModel.findOne(options)
1292 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1293 const where = VideoModel.buildWhereIdOrUUID(id)
1299 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1302 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1303 const where = VideoModel.buildWhereIdOrUUID(id)
1306 attributes: [ 'id' ],
1311 return VideoModel.findOne(options)
1314 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1315 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1316 .findById(id, { transaction: t, logging })
1319 static loadByUUIDWithFile (uuid: string) {
1326 return VideoModel.findOne(options)
1329 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1330 const query: IFindOptions<VideoModel> = {
1337 return VideoModel.findOne(query)
1340 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1341 const query: IFindOptions<VideoModel> = {
1348 return VideoModel.scope([
1349 ScopeNames.WITH_ACCOUNT_DETAILS,
1350 ScopeNames.WITH_FILES,
1351 ScopeNames.WITH_STREAMING_PLAYLISTS
1355 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1356 const where = VideoModel.buildWhereIdOrUUID(id)
1359 order: [ [ 'Tags', 'name', 'ASC' ] ],
1365 ScopeNames.WITH_TAGS,
1366 ScopeNames.WITH_BLACKLISTED,
1367 ScopeNames.WITH_ACCOUNT_DETAILS,
1368 ScopeNames.WITH_SCHEDULED_UPDATE,
1369 ScopeNames.WITH_FILES,
1370 ScopeNames.WITH_STREAMING_PLAYLISTS
1374 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1382 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1383 const where = VideoModel.buildWhereIdOrUUID(id)
1386 order: [ [ 'Tags', 'name', 'ASC' ] ],
1392 ScopeNames.WITH_TAGS,
1393 ScopeNames.WITH_BLACKLISTED,
1394 ScopeNames.WITH_ACCOUNT_DETAILS,
1395 ScopeNames.WITH_SCHEDULED_UPDATE,
1396 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1397 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1401 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1409 static async getStats () {
1410 const totalLocalVideos = await VideoModel.count({
1415 const totalVideos = await VideoModel.count()
1417 let totalLocalVideoViews = await VideoModel.sum('views', {
1422 // Sequelize could return null...
1423 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1427 totalLocalVideoViews,
1432 static incrementViews (id: number, views: number) {
1433 return VideoModel.increment('views', {
1441 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1442 // Instances only share videos
1443 const query = 'SELECT 1 FROM "videoShare" ' +
1444 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1445 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1449 type: Sequelize.QueryTypes.SELECT,
1450 bind: { followerActorId, videoId },
1454 return VideoModel.sequelize.query(query, options)
1455 .then(results => results.length === 1)
1458 // threshold corresponds to how many video the field should have to be returned
1459 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1460 const serverActor = await getServerActor()
1461 const followerActorId = serverActor.id
1463 const scopeOptions: AvailableForListIDsOptions = {
1464 serverAccountId: serverActor.Account.id,
1466 includeLocalVideos: true
1469 const query: IFindOptions<VideoModel> = {
1470 attributes: [ field ],
1473 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1474 [ Sequelize.Op.gte ]: threshold
1475 }) as any, // FIXME: typings
1476 order: [ this.sequelize.random() ]
1479 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1481 .then(rows => rows.map(r => r[ field ]))
1484 static buildTrendingQuery (trendingDays: number) {
1488 model: VideoViewModel,
1492 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1498 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1499 if (filter && (filter === 'local' || filter === 'all-local')) {
1508 private static async getAvailableForApi (
1509 query: IFindOptions<VideoModel>,
1510 options: AvailableForListIDsOptions,
1515 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1519 // Remove trending sort on count, because it uses a group by
1520 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1521 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1522 const countScope = {
1524 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1528 const [ count, rowsId ] = await Promise.all([
1529 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1530 VideoModel.scope(idsScope).findAll(query)
1532 const ids = rowsId.map(r => r.id)
1534 if (ids.length === 0) return { data: [], total: count }
1537 const apiScope: any[] = [
1539 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1544 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1547 const secondQuery = {
1550 attributes: query.attributes,
1551 order: [ // Keep original order
1553 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1557 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1565 static getCategoryLabel (id: number) {
1566 return VIDEO_CATEGORIES[ id ] || 'Misc'
1569 static getLicenceLabel (id: number) {
1570 return VIDEO_LICENCES[ id ] || 'Unknown'
1573 static getLanguageLabel (id: string) {
1574 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1577 static getPrivacyLabel (id: number) {
1578 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1581 static getStateLabel (id: number) {
1582 return VIDEO_STATES[ id ] || 'Unknown'
1585 static buildWhereIdOrUUID (id: number | string) {
1586 return validator.isInt('' + id) ? { id } : { uuid: id }
1589 getOriginalFile () {
1590 if (Array.isArray(this.VideoFiles) === false) return undefined
1592 // The original file is the file that have the higher resolution
1593 return maxBy(this.VideoFiles, file => file.resolution)
1596 getVideoFilename (videoFile: VideoFileModel) {
1597 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1600 getThumbnailName () {
1601 // We always have a copy of the thumbnail
1602 const extension = '.jpg'
1603 return this.uuid + extension
1607 const extension = '.jpg'
1608 return this.uuid + extension
1611 getTorrentFileName (videoFile: VideoFileModel) {
1612 const extension = '.torrent'
1613 return this.uuid + '-' + videoFile.resolution + extension
1617 return this.remote === false
1620 createPreview (videoFile: VideoFileModel) {
1621 return generateImageFromVideoFile(
1622 this.getVideoFilePath(videoFile),
1623 CONFIG.STORAGE.PREVIEWS_DIR,
1624 this.getPreviewName(),
1629 createThumbnail (videoFile: VideoFileModel) {
1630 return generateImageFromVideoFile(
1631 this.getVideoFilePath(videoFile),
1632 CONFIG.STORAGE.THUMBNAILS_DIR,
1633 this.getThumbnailName(),
1638 getTorrentFilePath (videoFile: VideoFileModel) {
1639 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1642 getVideoFilePath (videoFile: VideoFileModel) {
1643 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1646 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1648 // Keep the extname, it's used by the client to stream the file inside a web browser
1649 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1650 createdBy: 'PeerTube',
1652 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1653 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1655 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1658 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1660 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1661 logger.info('Creating torrent %s.', filePath)
1663 await writeFile(filePath, torrent)
1665 const parsedTorrent = parseTorrent(torrent)
1666 videoFile.infoHash = parsedTorrent.infoHash
1669 getWatchStaticPath () {
1670 return '/videos/watch/' + this.uuid
1673 getEmbedStaticPath () {
1674 return '/videos/embed/' + this.uuid
1677 getThumbnailStaticPath () {
1678 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1681 getPreviewStaticPath () {
1682 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1685 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1686 return videoModelToFormattedJSON(this, options)
1689 toFormattedDetailsJSON (): VideoDetails {
1690 return videoModelToFormattedDetailsJSON(this)
1693 getFormattedVideoFilesJSON (): VideoFile[] {
1694 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1697 toActivityPubObject (): VideoTorrentObject {
1698 return videoModelToActivityPubObject(this)
1701 getTruncatedDescription () {
1702 if (!this.description) return null
1704 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1705 return peertubeTruncate(this.description, maxLength)
1708 getOriginalFileResolution () {
1709 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1711 return getVideoFileResolution(originalFilePath)
1714 getDescriptionAPIPath () {
1715 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1718 removeThumbnail () {
1719 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1720 return remove(thumbnailPath)
1721 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1725 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1726 return remove(previewPath)
1727 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1730 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1731 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1733 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1734 return remove(filePath)
1735 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1738 removeTorrent (videoFile: VideoFileModel) {
1739 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1740 return remove(torrentPath)
1741 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1744 removeStreamingPlaylist (isRedundancy = false) {
1745 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_PLAYLIST_DIRECTORY
1747 const filePath = join(baseDir, this.uuid)
1748 return remove(filePath)
1749 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1753 if (this.isOwned()) return false
1755 const now = Date.now()
1756 const createdAtTime = this.createdAt.getTime()
1757 const updatedAtTime = this.updatedAt.getTime()
1759 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1760 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1764 this.changed('updatedAt', true)
1773 if (this.isOwned()) {
1774 baseUrlHttp = CONFIG.WEBSERVER.URL
1775 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1777 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1778 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1781 return { baseUrlHttp, baseUrlWs }
1784 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1785 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1786 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1787 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1789 const redundancies = videoFile.RedundancyVideos
1790 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1792 const magnetHash = {
1796 infoHash: videoFile.infoHash,
1800 return magnetUtil.encode(magnetHash)
1803 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1804 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1807 getThumbnailUrl (baseUrlHttp: string) {
1808 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1811 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1812 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1815 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1816 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1819 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1820 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1823 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1824 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1827 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1828 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1831 getBandwidthBits (videoFile: VideoFileModel) {
1832 return Math.ceil((videoFile.size * 8) / this.duration)