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 HLS_REDUNDANCY_DIRECTORY,
56 HLS_STREAMING_PLAYLIST_DIRECTORY,
59 STATIC_DOWNLOAD_PATHS,
68 } from '../../initializers/constants'
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,
84 import { TagModel } from './tag'
85 import { VideoAbuseModel } from './video-abuse'
86 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
87 import { VideoCommentModel } from './video-comment'
88 import { VideoFileModel } from './video-file'
89 import { VideoShareModel } from './video-share'
90 import { VideoTagModel } from './video-tag'
91 import { ScheduleVideoUpdateModel } from './schedule-video-update'
92 import { VideoCaptionModel } from './video-caption'
93 import { VideoBlacklistModel } from './video-blacklist'
94 import { remove, writeFile } from 'fs-extra'
95 import { VideoViewModel } from './video-views'
96 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
98 videoFilesModelToFormattedJSON,
99 VideoFormattingJSONOptions,
100 videoModelToActivityPubObject,
101 videoModelToFormattedDetailsJSON,
102 videoModelToFormattedJSON
103 } from './video-format-utils'
104 import { UserVideoHistoryModel } from '../account/user-video-history'
105 import { UserModel } from '../account/user'
106 import { VideoImportModel } from './video-import'
107 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
108 import { VideoPlaylistElementModel } from './video-playlist-element'
109 import { CONFIG } from '../../initializers/config'
110 import { ThumbnailModel } from './thumbnail'
111 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
113 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
114 const indexes: Sequelize.DefineIndexesOptions[] = [
115 buildTrigramSearchIndex('video_name_trigram', 'name'),
117 { fields: [ 'createdAt' ] },
118 { fields: [ 'publishedAt' ] },
119 { fields: [ 'duration' ] },
120 { fields: [ 'views' ] },
121 { fields: [ 'channelId' ] },
123 fields: [ 'originallyPublishedAt' ],
125 originallyPublishedAt: {
126 [Sequelize.Op.ne]: null
131 fields: [ 'category' ], // We don't care videos with an unknown category
134 [Sequelize.Op.ne]: null
139 fields: [ 'licence' ], // We don't care videos with an unknown licence
142 [Sequelize.Op.ne]: null
147 fields: [ 'language' ], // We don't care videos with an unknown language
150 [Sequelize.Op.ne]: null
155 fields: [ 'nsfw' ], // Most of the videos are not NSFW
161 fields: [ 'remote' ], // Only index local videos
176 export enum ScopeNames {
177 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
179 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
180 WITH_TAGS = 'WITH_TAGS',
181 WITH_FILES = 'WITH_FILES',
182 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
183 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
184 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
185 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
186 WITH_USER_ID = 'WITH_USER_ID',
187 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
190 type ForAPIOptions = {
193 videoPlaylistId?: number
198 type AvailableForListIDsOptions = {
199 serverAccountId: number
200 followerActorId: number
201 includeLocalVideos: boolean
204 categoryOneOf?: number[]
206 licenceOneOf?: number[]
207 languageOneOf?: string[]
214 videoChannelId?: number
216 videoPlaylistId?: number
218 trendingDays?: number
220 historyOfUser?: UserModel
224 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
225 const query: IFindOptions<VideoModel> = {
228 [ Sequelize.Op.any ]: options.ids
233 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
239 if (options.withFiles === true) {
241 model: VideoFileModel.unscoped(),
246 if (options.videoPlaylistId) {
248 model: VideoPlaylistElementModel.unscoped(),
251 videoPlaylistId: options.videoPlaylistId
258 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
259 const query: IFindOptions<VideoModel> = {
261 attributes: [ 'id' ],
264 [ Sequelize.Op.and ]: [
266 [ Sequelize.Op.notIn ]: Sequelize.literal(
267 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
273 [ Sequelize.Op.notIn ]: Sequelize.literal(
275 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
276 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
285 // Only list public/published videos
286 if (!options.filter || options.filter !== 'all-local') {
287 const privacyWhere = {
288 // Always list public videos
289 privacy: VideoPrivacy.PUBLIC,
290 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
291 [ Sequelize.Op.or ]: [
293 state: VideoState.PUBLISHED
296 [ Sequelize.Op.and ]: {
297 state: VideoState.TO_TRANSCODE,
298 waitTranscoding: false
304 Object.assign(query.where, privacyWhere)
307 if (options.videoPlaylistId) {
310 model: VideoPlaylistElementModel.unscoped(),
313 videoPlaylistId: options.videoPlaylistId
317 query.subQuery = false
320 if (options.filter || options.accountId || options.videoChannelId) {
321 const videoChannelInclude: IIncludeOptions = {
323 model: VideoChannelModel.unscoped(),
327 if (options.videoChannelId) {
328 videoChannelInclude.where = {
329 id: options.videoChannelId
333 if (options.filter || options.accountId) {
334 const accountInclude: IIncludeOptions = {
336 model: AccountModel.unscoped(),
340 if (options.filter) {
341 accountInclude.include = [
344 model: ActorModel.unscoped(),
346 where: VideoModel.buildActorWhereWithFilter(options.filter)
351 if (options.accountId) {
352 accountInclude.where = { id: options.accountId }
355 videoChannelInclude.include = [ accountInclude ]
358 query.include.push(videoChannelInclude)
361 if (options.followerActorId) {
362 let localVideosReq = ''
363 if (options.includeLocalVideos === true) {
364 localVideosReq = ' UNION ALL ' +
365 'SELECT "video"."id" AS "id" FROM "video" ' +
366 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
367 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
368 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
369 'WHERE "actor"."serverId" IS NULL'
372 // Force actorId to be a number to avoid SQL injections
373 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
374 query.where[ 'id' ][ Sequelize.Op.and ].push({
375 [ Sequelize.Op.in ]: Sequelize.literal(
377 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
378 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
379 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
381 'SELECT "video"."id" AS "id" FROM "video" ' +
382 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
383 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
384 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
385 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
386 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
393 if (options.withFiles === true) {
394 query.where[ 'id' ][ Sequelize.Op.and ].push({
395 [ Sequelize.Op.in ]: Sequelize.literal(
396 '(SELECT "videoId" FROM "videoFile")'
401 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
402 if (options.tagsAllOf || options.tagsOneOf) {
403 const createTagsIn = (tags: string[]) => {
404 return tags.map(t => VideoModel.sequelize.escape(t))
408 if (options.tagsOneOf) {
409 query.where[ 'id' ][ Sequelize.Op.and ].push({
410 [ Sequelize.Op.in ]: Sequelize.literal(
412 'SELECT "videoId" FROM "videoTag" ' +
413 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
414 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
420 if (options.tagsAllOf) {
421 query.where[ 'id' ][ Sequelize.Op.and ].push({
422 [ Sequelize.Op.in ]: Sequelize.literal(
424 'SELECT "videoId" FROM "videoTag" ' +
425 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
426 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
427 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
434 if (options.nsfw === true || options.nsfw === false) {
435 query.where[ 'nsfw' ] = options.nsfw
438 if (options.categoryOneOf) {
439 query.where[ 'category' ] = {
440 [ Sequelize.Op.or ]: options.categoryOneOf
444 if (options.licenceOneOf) {
445 query.where[ 'licence' ] = {
446 [ Sequelize.Op.or ]: options.licenceOneOf
450 if (options.languageOneOf) {
451 query.where[ 'language' ] = {
452 [ Sequelize.Op.or ]: options.languageOneOf
456 if (options.trendingDays) {
457 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
459 query.subQuery = false
462 if (options.historyOfUser) {
464 model: UserVideoHistoryModel,
467 userId: options.historyOfUser.id
471 // Even if the relation is n:m, we know that a user only have 0..1 video history
472 // So we won't have multiple rows for the same video
473 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
474 query.subQuery = false
479 [ ScopeNames.WITH_THUMBNAILS ]: {
482 model: () => ThumbnailModel,
487 [ ScopeNames.WITH_USER_ID ]: {
490 attributes: [ 'accountId' ],
491 model: () => VideoChannelModel.unscoped(),
495 attributes: [ 'userId' ],
496 model: () => AccountModel.unscoped(),
503 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
506 model: () => VideoChannelModel.unscoped(),
511 exclude: [ 'privateKey', 'publicKey' ]
513 model: () => ActorModel.unscoped(),
517 attributes: [ 'host' ],
518 model: () => ServerModel.unscoped(),
522 model: () => AvatarModel.unscoped(),
528 model: () => AccountModel.unscoped(),
532 model: () => ActorModel.unscoped(),
534 exclude: [ 'privateKey', 'publicKey' ]
539 attributes: [ 'host' ],
540 model: () => ServerModel.unscoped(),
544 model: () => AvatarModel.unscoped(),
555 [ ScopeNames.WITH_TAGS ]: {
556 include: [ () => TagModel ]
558 [ ScopeNames.WITH_BLACKLISTED ]: {
561 attributes: [ 'id', 'reason' ],
562 model: () => VideoBlacklistModel,
567 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
568 let subInclude: any[] = []
570 if (withRedundancies === true) {
573 attributes: [ 'fileUrl' ],
574 model: VideoRedundancyModel.unscoped(),
583 model: VideoFileModel.unscoped(),
585 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
592 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
593 let subInclude: any[] = []
595 if (withRedundancies === true) {
598 attributes: [ 'fileUrl' ],
599 model: VideoRedundancyModel.unscoped(),
608 model: VideoStreamingPlaylistModel.unscoped(),
610 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
617 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
620 model: () => ScheduleVideoUpdateModel.unscoped(),
625 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
629 attributes: [ 'currentTime' ],
630 model: UserVideoHistoryModel.unscoped(),
644 export class VideoModel extends Model<VideoModel> {
647 @Default(DataType.UUIDV4)
649 @Column(DataType.UUID)
653 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
659 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
665 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
671 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
672 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
676 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
681 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
687 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
688 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
693 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
694 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
698 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
728 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
729 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
734 commentsEnabled: boolean
738 downloadEnabled: boolean
742 waitTranscoding: boolean
746 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
757 @Default(Sequelize.NOW)
764 originallyPublishedAt: Date
766 @ForeignKey(() => VideoChannelModel)
770 @BelongsTo(() => VideoChannelModel, {
776 VideoChannel: VideoChannelModel
778 @BelongsToMany(() => TagModel, {
779 foreignKey: 'videoId',
780 through: () => VideoTagModel,
785 @HasMany(() => ThumbnailModel, {
793 Thumbnails: ThumbnailModel[]
795 @HasMany(() => VideoPlaylistElementModel, {
802 VideoPlaylistElements: VideoPlaylistElementModel[]
804 @HasMany(() => VideoAbuseModel, {
811 VideoAbuses: VideoAbuseModel[]
813 @HasMany(() => VideoFileModel, {
821 VideoFiles: VideoFileModel[]
823 @HasMany(() => VideoStreamingPlaylistModel, {
831 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
833 @HasMany(() => VideoShareModel, {
840 VideoShares: VideoShareModel[]
842 @HasMany(() => AccountVideoRateModel, {
849 AccountVideoRates: AccountVideoRateModel[]
851 @HasMany(() => VideoCommentModel, {
859 VideoComments: VideoCommentModel[]
861 @HasMany(() => VideoViewModel, {
868 VideoViews: VideoViewModel[]
870 @HasMany(() => UserVideoHistoryModel, {
877 UserVideoHistories: UserVideoHistoryModel[]
879 @HasOne(() => ScheduleVideoUpdateModel, {
886 ScheduleVideoUpdate: ScheduleVideoUpdateModel
888 @HasOne(() => VideoBlacklistModel, {
895 VideoBlacklist: VideoBlacklistModel
897 @HasOne(() => VideoImportModel, {
904 VideoImport: VideoImportModel
906 @HasMany(() => VideoCaptionModel, {
913 [ 'separate' as any ]: true
915 VideoCaptions: VideoCaptionModel[]
918 static async sendDelete (instance: VideoModel, options) {
919 if (instance.isOwned()) {
920 if (!instance.VideoChannel) {
921 instance.VideoChannel = await instance.$get('VideoChannel', {
925 include: [ ActorModel ]
928 transaction: options.transaction
929 }) as VideoChannelModel
932 return sendDeleteVideo(instance, options.transaction)
939 static async removeFiles (instance: VideoModel) {
940 const tasks: Promise<any>[] = []
942 logger.info('Removing files of video %s.', instance.url)
944 if (instance.isOwned()) {
945 if (!Array.isArray(instance.VideoFiles)) {
946 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
949 // Remove physical files and torrents
950 instance.VideoFiles.forEach(file => {
951 tasks.push(instance.removeFile(file))
952 tasks.push(instance.removeTorrent(file))
955 // Remove playlists file
956 tasks.push(instance.removeStreamingPlaylist())
959 // Do not wait video deletion because we could be in a transaction
962 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
968 static listLocal () {
975 return VideoModel.scope([
976 ScopeNames.WITH_FILES,
977 ScopeNames.WITH_STREAMING_PLAYLISTS,
978 ScopeNames.WITH_THUMBNAILS
982 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
983 function getRawQuery (select: string) {
984 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
985 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
986 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
987 'WHERE "Account"."actorId" = ' + actorId
988 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
989 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
990 'WHERE "VideoShare"."actorId" = ' + actorId
992 return `(${queryVideo}) UNION (${queryVideoShare})`
995 const rawQuery = getRawQuery('"Video"."id"')
996 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1002 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
1005 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1007 [ Sequelize.Op.or ]: [
1008 { privacy: VideoPrivacy.PUBLIC },
1009 { privacy: VideoPrivacy.UNLISTED }
1014 attributes: [ 'language' ],
1015 model: VideoCaptionModel.unscoped(),
1019 attributes: [ 'id', 'url' ],
1020 model: VideoShareModel.unscoped(),
1022 // We only want videos shared by this actor
1024 [ Sequelize.Op.and ]: [
1027 [ Sequelize.Op.not ]: null
1037 attributes: [ 'id', 'url' ],
1038 model: ActorModel.unscoped()
1043 model: VideoChannelModel.unscoped(),
1047 attributes: [ 'name' ],
1048 model: AccountModel.unscoped(),
1052 attributes: [ 'id', 'url', 'followersUrl' ],
1053 model: ActorModel.unscoped(),
1059 attributes: [ 'id', 'url', 'followersUrl' ],
1060 model: ActorModel.unscoped(),
1070 return Bluebird.all([
1071 // FIXME: typing issue
1072 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query as any),
1073 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1074 ]).then(([ rows, totals ]) => {
1075 // totals: totalVideos + totalVideoShares
1077 let totalVideoShares = 0
1078 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1079 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1081 const total = totalVideos + totalVideoShares
1089 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1090 const query: IFindOptions<VideoModel> = {
1093 order: getVideoSort(sort),
1096 model: VideoChannelModel,
1100 model: AccountModel,
1109 model: ScheduleVideoUpdateModel,
1113 model: VideoBlacklistModel,
1119 if (withFiles === true) {
1120 query.include.push({
1121 model: VideoFileModel.unscoped(),
1126 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS)
1127 .findAndCountAll(query)
1128 .then(({ rows, count }) => {
1136 static async listForApi (options: {
1141 includeLocalVideos: boolean,
1143 categoryOneOf?: number[],
1144 licenceOneOf?: number[],
1145 languageOneOf?: string[],
1146 tagsOneOf?: string[],
1147 tagsAllOf?: string[],
1148 filter?: VideoFilter,
1150 videoChannelId?: number,
1151 followerActorId?: number
1152 videoPlaylistId?: number,
1153 trendingDays?: number,
1155 historyOfUser?: UserModel
1156 }, countVideos = true) {
1157 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1158 throw new Error('Try to filter all-local but no user has not the see all videos right')
1161 const query: IFindOptions<VideoModel> = {
1162 offset: options.start,
1163 limit: options.count,
1164 order: getVideoSort(options.sort)
1167 let trendingDays: number
1168 if (options.sort.endsWith('trending')) {
1169 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1171 query.group = 'VideoModel.id'
1174 const serverActor = await getServerActor()
1176 // followerActorId === null has a meaning, so just check undefined
1177 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1179 const queryOptions = {
1181 serverAccountId: serverActor.Account.id,
1183 categoryOneOf: options.categoryOneOf,
1184 licenceOneOf: options.licenceOneOf,
1185 languageOneOf: options.languageOneOf,
1186 tagsOneOf: options.tagsOneOf,
1187 tagsAllOf: options.tagsAllOf,
1188 filter: options.filter,
1189 withFiles: options.withFiles,
1190 accountId: options.accountId,
1191 videoChannelId: options.videoChannelId,
1192 videoPlaylistId: options.videoPlaylistId,
1193 includeLocalVideos: options.includeLocalVideos,
1195 historyOfUser: options.historyOfUser,
1199 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1202 static async searchAndPopulateAccountAndServer (options: {
1203 includeLocalVideos: boolean
1208 startDate?: string // ISO 8601
1209 endDate?: string // ISO 8601
1210 originallyPublishedStartDate?: string
1211 originallyPublishedEndDate?: string
1213 categoryOneOf?: number[]
1214 licenceOneOf?: number[]
1215 languageOneOf?: string[]
1216 tagsOneOf?: string[]
1217 tagsAllOf?: string[]
1218 durationMin?: number // seconds
1219 durationMax?: number // seconds
1221 filter?: VideoFilter
1225 if (options.startDate || options.endDate) {
1226 const publishedAtRange = {}
1228 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1229 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1231 whereAnd.push({ publishedAt: publishedAtRange })
1234 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1235 const originallyPublishedAtRange = {}
1237 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1238 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1240 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1243 if (options.durationMin || options.durationMax) {
1244 const durationRange = {}
1246 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1247 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1249 whereAnd.push({ duration: durationRange })
1252 const attributesInclude = []
1253 const escapedSearch = VideoModel.sequelize.escape(options.search)
1254 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1255 if (options.search) {
1259 [ Sequelize.Op.in ]: Sequelize.literal(
1261 'SELECT "video"."id" FROM "video" ' +
1263 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1264 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1266 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1267 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1268 'WHERE "tag"."name" = ' + escapedSearch +
1275 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1278 // Cannot search on similarity if we don't have a search
1279 if (!options.search) {
1280 attributesInclude.push(
1281 Sequelize.literal('0 as similarity')
1285 const query: IFindOptions<VideoModel> = {
1287 include: attributesInclude
1289 offset: options.start,
1290 limit: options.count,
1291 order: getVideoSort(options.sort),
1293 [ Sequelize.Op.and ]: whereAnd
1297 const serverActor = await getServerActor()
1298 const queryOptions = {
1299 followerActorId: serverActor.id,
1300 serverAccountId: serverActor.Account.id,
1301 includeLocalVideos: options.includeLocalVideos,
1303 categoryOneOf: options.categoryOneOf,
1304 licenceOneOf: options.licenceOneOf,
1305 languageOneOf: options.languageOneOf,
1306 tagsOneOf: options.tagsOneOf,
1307 tagsAllOf: options.tagsAllOf,
1309 filter: options.filter
1312 return VideoModel.getAvailableForApi(query, queryOptions)
1315 static load (id: number | string, t?: Sequelize.Transaction) {
1316 const where = buildWhereIdOrUUID(id)
1322 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1325 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1326 const where = buildWhereIdOrUUID(id)
1332 return VideoModel.scope([
1333 ScopeNames.WITH_BLACKLISTED,
1334 ScopeNames.WITH_USER_ID,
1335 ScopeNames.WITH_THUMBNAILS
1339 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1340 const where = buildWhereIdOrUUID(id)
1343 attributes: [ 'id' ],
1348 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1351 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1352 return VideoModel.scope([
1353 ScopeNames.WITH_FILES,
1354 ScopeNames.WITH_STREAMING_PLAYLISTS,
1355 ScopeNames.WITH_THUMBNAILS
1356 ]).findByPk(id, { transaction: t, logging })
1359 static loadByUUIDWithFile (uuid: string) {
1366 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1369 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1370 const query: IFindOptions<VideoModel> = {
1377 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1380 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1381 const query: IFindOptions<VideoModel> = {
1388 return VideoModel.scope([
1389 ScopeNames.WITH_ACCOUNT_DETAILS,
1390 ScopeNames.WITH_FILES,
1391 ScopeNames.WITH_STREAMING_PLAYLISTS,
1392 ScopeNames.WITH_THUMBNAILS
1396 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1397 const where = buildWhereIdOrUUID(id)
1400 order: [ [ 'Tags', 'name', 'ASC' ] ],
1406 ScopeNames.WITH_TAGS,
1407 ScopeNames.WITH_BLACKLISTED,
1408 ScopeNames.WITH_ACCOUNT_DETAILS,
1409 ScopeNames.WITH_SCHEDULED_UPDATE,
1410 ScopeNames.WITH_FILES,
1411 ScopeNames.WITH_STREAMING_PLAYLISTS,
1412 ScopeNames.WITH_THUMBNAILS
1416 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1424 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1425 const where = buildWhereIdOrUUID(id)
1428 order: [ [ 'Tags', 'name', 'ASC' ] ],
1434 ScopeNames.WITH_TAGS,
1435 ScopeNames.WITH_BLACKLISTED,
1436 ScopeNames.WITH_ACCOUNT_DETAILS,
1437 ScopeNames.WITH_SCHEDULED_UPDATE,
1438 ScopeNames.WITH_THUMBNAILS,
1439 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1440 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1444 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1452 static async getStats () {
1453 const totalLocalVideos = await VideoModel.count({
1458 const totalVideos = await VideoModel.count()
1460 let totalLocalVideoViews = await VideoModel.sum('views', {
1465 // Sequelize could return null...
1466 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1470 totalLocalVideoViews,
1475 static incrementViews (id: number, views: number) {
1476 return VideoModel.increment('views', {
1484 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1485 // Instances only share videos
1486 const query = 'SELECT 1 FROM "videoShare" ' +
1487 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1488 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1492 type: Sequelize.QueryTypes.SELECT,
1493 bind: { followerActorId, videoId },
1497 return VideoModel.sequelize.query(query, options)
1498 .then(results => results.length === 1)
1501 // threshold corresponds to how many video the field should have to be returned
1502 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1503 const serverActor = await getServerActor()
1504 const followerActorId = serverActor.id
1506 const scopeOptions: AvailableForListIDsOptions = {
1507 serverAccountId: serverActor.Account.id,
1509 includeLocalVideos: true
1512 const query: IFindOptions<VideoModel> = {
1513 attributes: [ field ],
1516 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1517 [ Sequelize.Op.gte ]: threshold
1518 }) as any, // FIXME: typings
1519 order: [ this.sequelize.random() ]
1522 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1524 .then(rows => rows.map(r => r[ field ]))
1527 static buildTrendingQuery (trendingDays: number) {
1531 model: VideoViewModel,
1535 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1541 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1542 if (filter && (filter === 'local' || filter === 'all-local')) {
1551 private static async getAvailableForApi (
1552 query: IFindOptions<VideoModel>,
1553 options: AvailableForListIDsOptions,
1558 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1562 // Remove trending sort on count, because it uses a group by
1563 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1564 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1565 const countScope = {
1567 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1571 const [ count, rowsId ] = await Promise.all([
1572 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1573 VideoModel.scope(idsScope).findAll(query)
1575 const ids = rowsId.map(r => r.id)
1577 if (ids.length === 0) return { data: [], total: count }
1579 const secondQuery: IFindOptions<VideoModel> = {
1582 attributes: query.attributes,
1583 order: [ // Keep original order
1585 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1591 const apiScope: any[] = [ ScopeNames.WITH_THUMBNAILS ]
1594 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1596 // Even if the relation is n:m, we know that a user only have 0..1 video history
1597 // So we won't have multiple rows for the same video
1598 // A subquery adds some bugs in our query so disable it
1599 secondQuery.subQuery = false
1604 ScopeNames.FOR_API, {
1606 withFiles: options.withFiles,
1607 videoPlaylistId: options.videoPlaylistId
1612 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1620 static getCategoryLabel (id: number) {
1621 return VIDEO_CATEGORIES[ id ] || 'Misc'
1624 static getLicenceLabel (id: number) {
1625 return VIDEO_LICENCES[ id ] || 'Unknown'
1628 static getLanguageLabel (id: string) {
1629 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1632 static getPrivacyLabel (id: number) {
1633 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1636 static getStateLabel (id: number) {
1637 return VIDEO_STATES[ id ] || 'Unknown'
1640 getOriginalFile () {
1641 if (Array.isArray(this.VideoFiles) === false) return undefined
1643 // The original file is the file that have the higher resolution
1644 return maxBy(this.VideoFiles, file => file.resolution)
1647 addThumbnail (thumbnail: ThumbnailModel) {
1648 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1650 // Already have this thumbnail, skip
1651 if (this.Thumbnails.find(t => t.id === thumbnail.id)) return
1653 this.Thumbnails.push(thumbnail)
1656 getVideoFilename (videoFile: VideoFileModel) {
1657 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1660 generateThumbnailName () {
1661 return this.uuid + '.jpg'
1665 if (Array.isArray(this.Thumbnails) === false) return undefined
1667 return this.Thumbnails.find(t => t.type === ThumbnailType.THUMBNAIL)
1670 generatePreviewName () {
1671 return this.uuid + '.jpg'
1675 if (Array.isArray(this.Thumbnails) === false) return undefined
1677 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1680 getTorrentFileName (videoFile: VideoFileModel) {
1681 const extension = '.torrent'
1682 return this.uuid + '-' + videoFile.resolution + extension
1686 return this.remote === false
1689 getTorrentFilePath (videoFile: VideoFileModel) {
1690 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1693 getVideoFilePath (videoFile: VideoFileModel) {
1694 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1697 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1699 // Keep the extname, it's used by the client to stream the file inside a web browser
1700 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1701 createdBy: 'PeerTube',
1703 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1704 [ WEBSERVER.URL + '/tracker/announce' ]
1706 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1709 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1711 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1712 logger.info('Creating torrent %s.', filePath)
1714 await writeFile(filePath, torrent)
1716 const parsedTorrent = parseTorrent(torrent)
1717 videoFile.infoHash = parsedTorrent.infoHash
1720 getWatchStaticPath () {
1721 return '/videos/watch/' + this.uuid
1724 getEmbedStaticPath () {
1725 return '/videos/embed/' + this.uuid
1728 getThumbnailStaticPath () {
1729 const thumbnail = this.getThumbnail()
1730 if (!thumbnail) return null
1732 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1735 getPreviewStaticPath () {
1736 const preview = this.getPreview()
1737 if (!preview) return null
1739 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1740 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1743 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1744 return videoModelToFormattedJSON(this, options)
1747 toFormattedDetailsJSON (): VideoDetails {
1748 return videoModelToFormattedDetailsJSON(this)
1751 getFormattedVideoFilesJSON (): VideoFile[] {
1752 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1755 toActivityPubObject (): VideoTorrentObject {
1756 return videoModelToActivityPubObject(this)
1759 getTruncatedDescription () {
1760 if (!this.description) return null
1762 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1763 return peertubeTruncate(this.description, maxLength)
1766 getOriginalFileResolution () {
1767 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1769 return getVideoFileResolution(originalFilePath)
1772 getDescriptionAPIPath () {
1773 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1776 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1777 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1779 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1780 return remove(filePath)
1781 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1784 removeTorrent (videoFile: VideoFileModel) {
1785 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1786 return remove(torrentPath)
1787 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1790 removeStreamingPlaylist (isRedundancy = false) {
1791 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1793 const filePath = join(baseDir, this.uuid)
1794 return remove(filePath)
1795 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1799 if (this.isOwned()) return false
1801 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1805 this.changed('updatedAt', true)
1814 if (this.isOwned()) {
1815 baseUrlHttp = WEBSERVER.URL
1816 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1818 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1819 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1822 return { baseUrlHttp, baseUrlWs }
1825 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1826 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1827 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1828 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1830 const redundancies = videoFile.RedundancyVideos
1831 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1833 const magnetHash = {
1837 infoHash: videoFile.infoHash,
1841 return magnetUtil.encode(magnetHash)
1844 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1845 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1848 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1849 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1852 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1853 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1856 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1857 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1860 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1861 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1864 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1865 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1868 getBandwidthBits (videoFile: VideoFileModel) {
1869 return Math.ceil((videoFile.size * 8) / this.duration)