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'
56 HLS_PLAYLIST_DIRECTORY,
57 HLS_REDUNDANCY_DIRECTORY,
60 STATIC_DOWNLOAD_PATHS,
68 } from '../../initializers'
69 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 import { AccountModel } from '../account/account'
71 import { AccountVideoRateModel } from '../account/account-video-rate'
72 import { ActorModel } from '../activitypub/actor'
73 import { AvatarModel } from '../avatar/avatar'
74 import { ServerModel } from '../server/server'
76 buildBlockedAccountSQL,
77 buildTrigramSearchIndex,
79 createSimilarityAttribute,
83 import { TagModel } from './tag'
84 import { VideoAbuseModel } from './video-abuse'
85 import { VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel'
86 import { VideoCommentModel } from './video-comment'
87 import { VideoFileModel } from './video-file'
88 import { VideoShareModel } from './video-share'
89 import { VideoTagModel } from './video-tag'
90 import { ScheduleVideoUpdateModel } from './schedule-video-update'
91 import { VideoCaptionModel } from './video-caption'
92 import { VideoBlacklistModel } from './video-blacklist'
93 import { remove, writeFile } from 'fs-extra'
94 import { VideoViewModel } from './video-views'
95 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
97 videoFilesModelToFormattedJSON,
98 VideoFormattingJSONOptions,
99 videoModelToActivityPubObject,
100 videoModelToFormattedDetailsJSON,
101 videoModelToFormattedJSON
102 } from './video-format-utils'
103 import { UserVideoHistoryModel } from '../account/user-video-history'
104 import { UserModel } from '../account/user'
105 import { VideoImportModel } from './video-import'
106 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
107 import { VideoPlaylistElementModel } from './video-playlist-element'
109 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
110 const indexes: Sequelize.DefineIndexesOptions[] = [
111 buildTrigramSearchIndex('video_name_trigram', 'name'),
113 { fields: [ 'createdAt' ] },
114 { fields: [ 'publishedAt' ] },
115 { fields: [ 'duration' ] },
116 { fields: [ 'views' ] },
117 { fields: [ 'channelId' ] },
119 fields: [ 'originallyPublishedAt' ],
121 originallyPublishedAt: {
122 [Sequelize.Op.ne]: null
127 fields: [ 'category' ], // We don't care videos with an unknown category
130 [Sequelize.Op.ne]: null
135 fields: [ 'licence' ], // We don't care videos with an unknown licence
138 [Sequelize.Op.ne]: null
143 fields: [ 'language' ], // We don't care videos with an unknown language
146 [Sequelize.Op.ne]: null
151 fields: [ 'nsfw' ], // Most of the videos are not NSFW
157 fields: [ 'remote' ], // Only index local videos
172 export enum ScopeNames {
173 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
175 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
176 WITH_TAGS = 'WITH_TAGS',
177 WITH_FILES = 'WITH_FILES',
178 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
179 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
180 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
181 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
182 WITH_USER_ID = 'WITH_USER_ID'
185 type ForAPIOptions = {
188 videoPlaylistId?: number
193 type AvailableForListIDsOptions = {
194 serverAccountId: number
195 followerActorId: number
196 includeLocalVideos: boolean
199 categoryOneOf?: number[]
201 licenceOneOf?: number[]
202 languageOneOf?: string[]
209 videoChannelId?: number
211 videoPlaylistId?: number
213 trendingDays?: number
215 historyOfUser?: UserModel
219 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
220 const query: IFindOptions<VideoModel> = {
223 [ Sequelize.Op.any ]: options.ids
228 model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY)
233 if (options.withFiles === true) {
235 model: VideoFileModel.unscoped(),
240 if (options.videoPlaylistId) {
242 model: VideoPlaylistElementModel.unscoped(),
249 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
250 const query: IFindOptions<VideoModel> = {
252 attributes: [ 'id' ],
255 [ Sequelize.Op.and ]: [
257 [ Sequelize.Op.notIn ]: Sequelize.literal(
258 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
264 [ Sequelize.Op.notIn ]: Sequelize.literal(
266 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
267 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
276 // Only list public/published videos
277 if (!options.filter || options.filter !== 'all-local') {
278 const privacyWhere = {
279 // Always list public videos
280 privacy: VideoPrivacy.PUBLIC,
281 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
282 [ Sequelize.Op.or ]: [
284 state: VideoState.PUBLISHED
287 [ Sequelize.Op.and ]: {
288 state: VideoState.TO_TRANSCODE,
289 waitTranscoding: false
295 Object.assign(query.where, privacyWhere)
298 if (options.videoPlaylistId) {
301 model: VideoPlaylistElementModel.unscoped(),
304 videoPlaylistId: options.videoPlaylistId
309 if (options.filter || options.accountId || options.videoChannelId) {
310 const videoChannelInclude: IIncludeOptions = {
312 model: VideoChannelModel.unscoped(),
316 if (options.videoChannelId) {
317 videoChannelInclude.where = {
318 id: options.videoChannelId
322 if (options.filter || options.accountId) {
323 const accountInclude: IIncludeOptions = {
325 model: AccountModel.unscoped(),
329 if (options.filter) {
330 accountInclude.include = [
333 model: ActorModel.unscoped(),
335 where: VideoModel.buildActorWhereWithFilter(options.filter)
340 if (options.accountId) {
341 accountInclude.where = { id: options.accountId }
344 videoChannelInclude.include = [ accountInclude ]
347 query.include.push(videoChannelInclude)
350 if (options.followerActorId) {
351 let localVideosReq = ''
352 if (options.includeLocalVideos === true) {
353 localVideosReq = ' UNION ALL ' +
354 'SELECT "video"."id" AS "id" FROM "video" ' +
355 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
356 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
357 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
358 'WHERE "actor"."serverId" IS NULL'
361 // Force actorId to be a number to avoid SQL injections
362 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
363 query.where[ 'id' ][ Sequelize.Op.and ].push({
364 [ Sequelize.Op.in ]: Sequelize.literal(
366 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
367 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
368 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
370 'SELECT "video"."id" AS "id" FROM "video" ' +
371 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
372 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
373 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
374 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
375 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
382 if (options.withFiles === true) {
383 query.where[ 'id' ][ Sequelize.Op.and ].push({
384 [ Sequelize.Op.in ]: Sequelize.literal(
385 '(SELECT "videoId" FROM "videoFile")'
390 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
391 if (options.tagsAllOf || options.tagsOneOf) {
392 const createTagsIn = (tags: string[]) => {
393 return tags.map(t => VideoModel.sequelize.escape(t))
397 if (options.tagsOneOf) {
398 query.where[ 'id' ][ Sequelize.Op.and ].push({
399 [ Sequelize.Op.in ]: Sequelize.literal(
401 'SELECT "videoId" FROM "videoTag" ' +
402 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
403 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
409 if (options.tagsAllOf) {
410 query.where[ 'id' ][ Sequelize.Op.and ].push({
411 [ Sequelize.Op.in ]: Sequelize.literal(
413 'SELECT "videoId" FROM "videoTag" ' +
414 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
415 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
416 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
423 if (options.nsfw === true || options.nsfw === false) {
424 query.where[ 'nsfw' ] = options.nsfw
427 if (options.categoryOneOf) {
428 query.where[ 'category' ] = {
429 [ Sequelize.Op.or ]: options.categoryOneOf
433 if (options.licenceOneOf) {
434 query.where[ 'licence' ] = {
435 [ Sequelize.Op.or ]: options.licenceOneOf
439 if (options.languageOneOf) {
440 query.where[ 'language' ] = {
441 [ Sequelize.Op.or ]: options.languageOneOf
445 if (options.trendingDays) {
446 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
448 query.subQuery = false
451 if (options.historyOfUser) {
453 model: UserVideoHistoryModel,
456 userId: options.historyOfUser.id
460 // Even if the relation is n:m, we know that a user only have 0..1 video history
461 // So we won't have multiple rows for the same video
462 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
463 query.subQuery = false
468 [ ScopeNames.WITH_USER_ID ]: {
471 attributes: [ 'accountId' ],
472 model: () => VideoChannelModel.unscoped(),
476 attributes: [ 'userId' ],
477 model: () => AccountModel.unscoped(),
484 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
487 model: () => VideoChannelModel.unscoped(),
492 exclude: [ 'privateKey', 'publicKey' ]
494 model: () => ActorModel.unscoped(),
498 attributes: [ 'host' ],
499 model: () => ServerModel.unscoped(),
503 model: () => AvatarModel.unscoped(),
509 model: () => AccountModel.unscoped(),
513 model: () => ActorModel.unscoped(),
515 exclude: [ 'privateKey', 'publicKey' ]
520 attributes: [ 'host' ],
521 model: () => ServerModel.unscoped(),
525 model: () => AvatarModel.unscoped(),
536 [ ScopeNames.WITH_TAGS ]: {
537 include: [ () => TagModel ]
539 [ ScopeNames.WITH_BLACKLISTED ]: {
542 attributes: [ 'id', 'reason' ],
543 model: () => VideoBlacklistModel,
548 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
549 let subInclude: any[] = []
551 if (withRedundancies === true) {
554 attributes: [ 'fileUrl' ],
555 model: VideoRedundancyModel.unscoped(),
564 model: VideoFileModel.unscoped(),
566 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
573 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
574 let subInclude: any[] = []
576 if (withRedundancies === true) {
579 attributes: [ 'fileUrl' ],
580 model: VideoRedundancyModel.unscoped(),
589 model: VideoStreamingPlaylistModel.unscoped(),
591 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
598 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
601 model: () => ScheduleVideoUpdateModel.unscoped(),
606 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
610 attributes: [ 'currentTime' ],
611 model: UserVideoHistoryModel.unscoped(),
625 export class VideoModel extends Model<VideoModel> {
628 @Default(DataType.UUIDV4)
630 @Column(DataType.UUID)
634 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
640 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
646 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
652 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
653 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
657 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
662 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
668 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
669 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
674 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
675 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
679 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
709 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
710 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
715 commentsEnabled: boolean
719 downloadEnabled: boolean
723 waitTranscoding: boolean
727 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
738 @Default(Sequelize.NOW)
745 originallyPublishedAt: Date
747 @ForeignKey(() => VideoChannelModel)
751 @BelongsTo(() => VideoChannelModel, {
757 VideoChannel: VideoChannelModel
759 @BelongsToMany(() => TagModel, {
760 foreignKey: 'videoId',
761 through: () => VideoTagModel,
766 @HasMany(() => VideoPlaylistElementModel, {
773 VideoPlaylistElements: VideoPlaylistElementModel[]
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 videoPlaylistId?: number,
1122 trendingDays?: number,
1124 historyOfUser?: UserModel
1125 }, countVideos = true) {
1126 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1127 throw new Error('Try to filter all-local but no user has not the see all videos right')
1130 const query: IFindOptions<VideoModel> = {
1131 offset: options.start,
1132 limit: options.count,
1133 order: getVideoSort(options.sort)
1136 let trendingDays: number
1137 if (options.sort.endsWith('trending')) {
1138 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1140 query.group = 'VideoModel.id'
1143 const serverActor = await getServerActor()
1145 // followerActorId === null has a meaning, so just check undefined
1146 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1148 const queryOptions = {
1150 serverAccountId: serverActor.Account.id,
1152 categoryOneOf: options.categoryOneOf,
1153 licenceOneOf: options.licenceOneOf,
1154 languageOneOf: options.languageOneOf,
1155 tagsOneOf: options.tagsOneOf,
1156 tagsAllOf: options.tagsAllOf,
1157 filter: options.filter,
1158 withFiles: options.withFiles,
1159 accountId: options.accountId,
1160 videoChannelId: options.videoChannelId,
1161 videoPlaylistId: options.videoPlaylistId,
1162 includeLocalVideos: options.includeLocalVideos,
1164 historyOfUser: options.historyOfUser,
1168 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1171 static async searchAndPopulateAccountAndServer (options: {
1172 includeLocalVideos: boolean
1177 startDate?: string // ISO 8601
1178 endDate?: string // ISO 8601
1179 originallyPublishedStartDate?: string
1180 originallyPublishedEndDate?: string
1182 categoryOneOf?: number[]
1183 licenceOneOf?: number[]
1184 languageOneOf?: string[]
1185 tagsOneOf?: string[]
1186 tagsAllOf?: string[]
1187 durationMin?: number // seconds
1188 durationMax?: number // seconds
1190 filter?: VideoFilter
1194 if (options.startDate || options.endDate) {
1195 const publishedAtRange = {}
1197 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1198 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1200 whereAnd.push({ publishedAt: publishedAtRange })
1203 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1204 const originallyPublishedAtRange = {}
1206 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1207 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1209 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1212 if (options.durationMin || options.durationMax) {
1213 const durationRange = {}
1215 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1216 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1218 whereAnd.push({ duration: durationRange })
1221 const attributesInclude = []
1222 const escapedSearch = VideoModel.sequelize.escape(options.search)
1223 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1224 if (options.search) {
1228 [ Sequelize.Op.in ]: Sequelize.literal(
1230 'SELECT "video"."id" FROM "video" ' +
1232 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1233 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1235 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1236 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1237 'WHERE "tag"."name" = ' + escapedSearch +
1244 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1247 // Cannot search on similarity if we don't have a search
1248 if (!options.search) {
1249 attributesInclude.push(
1250 Sequelize.literal('0 as similarity')
1254 const query: IFindOptions<VideoModel> = {
1256 include: attributesInclude
1258 offset: options.start,
1259 limit: options.count,
1260 order: getVideoSort(options.sort),
1262 [ Sequelize.Op.and ]: whereAnd
1266 const serverActor = await getServerActor()
1267 const queryOptions = {
1268 followerActorId: serverActor.id,
1269 serverAccountId: serverActor.Account.id,
1270 includeLocalVideos: options.includeLocalVideos,
1272 categoryOneOf: options.categoryOneOf,
1273 licenceOneOf: options.licenceOneOf,
1274 languageOneOf: options.languageOneOf,
1275 tagsOneOf: options.tagsOneOf,
1276 tagsAllOf: options.tagsAllOf,
1278 filter: options.filter
1281 return VideoModel.getAvailableForApi(query, queryOptions)
1284 static load (id: number | string, t?: Sequelize.Transaction) {
1285 const where = buildWhereIdOrUUID(id)
1291 return VideoModel.findOne(options)
1294 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1295 const where = buildWhereIdOrUUID(id)
1301 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1304 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1305 const where = buildWhereIdOrUUID(id)
1308 attributes: [ 'id' ],
1313 return VideoModel.findOne(options)
1316 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1317 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1318 .findByPk(id, { transaction: t, logging })
1321 static loadByUUIDWithFile (uuid: string) {
1328 return VideoModel.findOne(options)
1331 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1332 const query: IFindOptions<VideoModel> = {
1339 return VideoModel.findOne(query)
1342 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1343 const query: IFindOptions<VideoModel> = {
1350 return VideoModel.scope([
1351 ScopeNames.WITH_ACCOUNT_DETAILS,
1352 ScopeNames.WITH_FILES,
1353 ScopeNames.WITH_STREAMING_PLAYLISTS
1357 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1358 const where = buildWhereIdOrUUID(id)
1361 order: [ [ 'Tags', 'name', 'ASC' ] ],
1367 ScopeNames.WITH_TAGS,
1368 ScopeNames.WITH_BLACKLISTED,
1369 ScopeNames.WITH_ACCOUNT_DETAILS,
1370 ScopeNames.WITH_SCHEDULED_UPDATE,
1371 ScopeNames.WITH_FILES,
1372 ScopeNames.WITH_STREAMING_PLAYLISTS
1376 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1384 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1385 const where = buildWhereIdOrUUID(id)
1388 order: [ [ 'Tags', 'name', 'ASC' ] ],
1394 ScopeNames.WITH_TAGS,
1395 ScopeNames.WITH_BLACKLISTED,
1396 ScopeNames.WITH_ACCOUNT_DETAILS,
1397 ScopeNames.WITH_SCHEDULED_UPDATE,
1398 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1399 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1403 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1411 static async getStats () {
1412 const totalLocalVideos = await VideoModel.count({
1417 const totalVideos = await VideoModel.count()
1419 let totalLocalVideoViews = await VideoModel.sum('views', {
1424 // Sequelize could return null...
1425 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1429 totalLocalVideoViews,
1434 static incrementViews (id: number, views: number) {
1435 return VideoModel.increment('views', {
1443 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1444 // Instances only share videos
1445 const query = 'SELECT 1 FROM "videoShare" ' +
1446 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1447 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1451 type: Sequelize.QueryTypes.SELECT,
1452 bind: { followerActorId, videoId },
1456 return VideoModel.sequelize.query(query, options)
1457 .then(results => results.length === 1)
1460 // threshold corresponds to how many video the field should have to be returned
1461 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1462 const serverActor = await getServerActor()
1463 const followerActorId = serverActor.id
1465 const scopeOptions: AvailableForListIDsOptions = {
1466 serverAccountId: serverActor.Account.id,
1468 includeLocalVideos: true
1471 const query: IFindOptions<VideoModel> = {
1472 attributes: [ field ],
1475 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1476 [ Sequelize.Op.gte ]: threshold
1477 }) as any, // FIXME: typings
1478 order: [ this.sequelize.random() ]
1481 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1483 .then(rows => rows.map(r => r[ field ]))
1486 static buildTrendingQuery (trendingDays: number) {
1490 model: VideoViewModel,
1494 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1500 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1501 if (filter && (filter === 'local' || filter === 'all-local')) {
1510 private static async getAvailableForApi (
1511 query: IFindOptions<VideoModel>,
1512 options: AvailableForListIDsOptions,
1517 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1521 // Remove trending sort on count, because it uses a group by
1522 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1523 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1524 const countScope = {
1526 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1530 const [ count, rowsId ] = await Promise.all([
1531 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1532 VideoModel.scope(idsScope).findAll(query)
1534 const ids = rowsId.map(r => r.id)
1536 if (ids.length === 0) return { data: [], total: count }
1539 const apiScope: any[] = [
1541 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1546 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1549 const secondQuery = {
1552 attributes: query.attributes,
1553 order: [ // Keep original order
1555 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1559 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1567 static getCategoryLabel (id: number) {
1568 return VIDEO_CATEGORIES[ id ] || 'Misc'
1571 static getLicenceLabel (id: number) {
1572 return VIDEO_LICENCES[ id ] || 'Unknown'
1575 static getLanguageLabel (id: string) {
1576 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1579 static getPrivacyLabel (id: number) {
1580 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1583 static getStateLabel (id: number) {
1584 return VIDEO_STATES[ id ] || 'Unknown'
1587 getOriginalFile () {
1588 if (Array.isArray(this.VideoFiles) === false) return undefined
1590 // The original file is the file that have the higher resolution
1591 return maxBy(this.VideoFiles, file => file.resolution)
1594 getVideoFilename (videoFile: VideoFileModel) {
1595 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1598 getThumbnailName () {
1599 const extension = '.jpg'
1600 return this.uuid + extension
1604 const extension = '.jpg'
1605 return this.uuid + extension
1608 getTorrentFileName (videoFile: VideoFileModel) {
1609 const extension = '.torrent'
1610 return this.uuid + '-' + videoFile.resolution + extension
1614 return this.remote === false
1617 createPreview (videoFile: VideoFileModel) {
1618 return generateImageFromVideoFile(
1619 this.getVideoFilePath(videoFile),
1620 CONFIG.STORAGE.PREVIEWS_DIR,
1621 this.getPreviewName(),
1626 createThumbnail (videoFile: VideoFileModel) {
1627 return generateImageFromVideoFile(
1628 this.getVideoFilePath(videoFile),
1629 CONFIG.STORAGE.THUMBNAILS_DIR,
1630 this.getThumbnailName(),
1635 getTorrentFilePath (videoFile: VideoFileModel) {
1636 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1639 getVideoFilePath (videoFile: VideoFileModel) {
1640 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1643 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1645 // Keep the extname, it's used by the client to stream the file inside a web browser
1646 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1647 createdBy: 'PeerTube',
1649 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1650 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1652 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1655 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1657 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1658 logger.info('Creating torrent %s.', filePath)
1660 await writeFile(filePath, torrent)
1662 const parsedTorrent = parseTorrent(torrent)
1663 videoFile.infoHash = parsedTorrent.infoHash
1666 getWatchStaticPath () {
1667 return '/videos/watch/' + this.uuid
1670 getEmbedStaticPath () {
1671 return '/videos/embed/' + this.uuid
1674 getThumbnailStaticPath () {
1675 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1678 getPreviewStaticPath () {
1679 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1682 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1683 return videoModelToFormattedJSON(this, options)
1686 toFormattedDetailsJSON (): VideoDetails {
1687 return videoModelToFormattedDetailsJSON(this)
1690 getFormattedVideoFilesJSON (): VideoFile[] {
1691 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1694 toActivityPubObject (): VideoTorrentObject {
1695 return videoModelToActivityPubObject(this)
1698 getTruncatedDescription () {
1699 if (!this.description) return null
1701 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1702 return peertubeTruncate(this.description, maxLength)
1705 getOriginalFileResolution () {
1706 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1708 return getVideoFileResolution(originalFilePath)
1711 getDescriptionAPIPath () {
1712 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1715 removeThumbnail () {
1716 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1717 return remove(thumbnailPath)
1718 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1722 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1723 return remove(previewPath)
1724 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1727 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1728 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1730 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1731 return remove(filePath)
1732 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1735 removeTorrent (videoFile: VideoFileModel) {
1736 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1737 return remove(torrentPath)
1738 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1741 removeStreamingPlaylist (isRedundancy = false) {
1742 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_PLAYLIST_DIRECTORY
1744 const filePath = join(baseDir, this.uuid)
1745 return remove(filePath)
1746 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1750 if (this.isOwned()) return false
1752 const now = Date.now()
1753 const createdAtTime = this.createdAt.getTime()
1754 const updatedAtTime = this.updatedAt.getTime()
1756 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1757 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1761 this.changed('updatedAt', true)
1770 if (this.isOwned()) {
1771 baseUrlHttp = CONFIG.WEBSERVER.URL
1772 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1774 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1775 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1778 return { baseUrlHttp, baseUrlWs }
1781 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1782 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1783 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1784 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1786 const redundancies = videoFile.RedundancyVideos
1787 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1789 const magnetHash = {
1793 infoHash: videoFile.infoHash,
1797 return magnetUtil.encode(magnetHash)
1800 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1801 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1804 getThumbnailUrl (baseUrlHttp: string) {
1805 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1808 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1809 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1812 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1813 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1816 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1817 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1820 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1821 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1824 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1825 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1828 getBandwidthBits (videoFile: VideoFileModel) {
1829 return Math.ceil((videoFile.size * 8) / this.duration)