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'
38 } from 'sequelize-typescript'
39 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
56 } from '../../helpers/custom-validators/videos'
57 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
58 import { logger } from '../../helpers/logger'
59 import { getServerActor } from '../../helpers/utils'
64 HLS_REDUNDANCY_DIRECTORY,
65 HLS_STREAMING_PLAYLIST_DIRECTORY,
67 STATIC_DOWNLOAD_PATHS,
75 } from '../../initializers/constants'
76 import { sendDeleteVideo } from '../../lib/activitypub/send'
77 import { AccountModel } from '../account/account'
78 import { AccountVideoRateModel } from '../account/account-video-rate'
79 import { ActorModel } from '../activitypub/actor'
80 import { AvatarModel } from '../avatar/avatar'
81 import { ServerModel } from '../server/server'
83 buildBlockedAccountSQL,
84 buildTrigramSearchIndex,
86 createSimilarityAttribute,
91 import { TagModel } from './tag'
92 import { VideoAbuseModel } from './video-abuse'
93 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
94 import { VideoCommentModel } from './video-comment'
95 import { VideoFileModel } from './video-file'
96 import { VideoShareModel } from './video-share'
97 import { VideoTagModel } from './video-tag'
98 import { ScheduleVideoUpdateModel } from './schedule-video-update'
99 import { VideoCaptionModel } from './video-caption'
100 import { VideoBlacklistModel } from './video-blacklist'
101 import { remove, writeFile } from 'fs-extra'
102 import { VideoViewModel } from './video-views'
103 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
105 videoFilesModelToFormattedJSON,
106 VideoFormattingJSONOptions,
107 videoModelToActivityPubObject,
108 videoModelToFormattedDetailsJSON,
109 videoModelToFormattedJSON
110 } from './video-format-utils'
111 import { UserVideoHistoryModel } from '../account/user-video-history'
112 import { UserModel } from '../account/user'
113 import { VideoImportModel } from './video-import'
114 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
115 import { VideoPlaylistElementModel } from './video-playlist-element'
116 import { CONFIG } from '../../initializers/config'
117 import { ThumbnailModel } from './thumbnail'
118 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
121 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
122 buildTrigramSearchIndex('video_name_trigram', 'name'),
124 { fields: [ 'createdAt' ] },
125 { fields: [ 'publishedAt' ] },
126 { fields: [ 'duration' ] },
127 { fields: [ 'views' ] },
128 { fields: [ 'channelId' ] },
130 fields: [ 'originallyPublishedAt' ],
132 originallyPublishedAt: {
138 fields: [ 'category' ], // We don't care videos with an unknown category
146 fields: [ 'licence' ], // We don't care videos with an unknown licence
154 fields: [ 'language' ], // We don't care videos with an unknown language
162 fields: [ 'nsfw' ], // Most of the videos are not NSFW
168 fields: [ 'remote' ], // Only index local videos
183 export enum ScopeNames {
184 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
186 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
187 WITH_TAGS = 'WITH_TAGS',
188 WITH_FILES = 'WITH_FILES',
189 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
190 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
191 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
192 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
193 WITH_USER_ID = 'WITH_USER_ID',
194 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
197 type ForAPIOptions = {
200 videoPlaylistId?: number
205 type AvailableForListIDsOptions = {
206 serverAccountId: number
207 followerActorId: number
208 includeLocalVideos: boolean
211 categoryOneOf?: number[]
213 licenceOneOf?: number[]
214 languageOneOf?: string[]
221 videoChannelId?: number
223 videoPlaylistId?: number
225 trendingDays?: number
227 historyOfUser?: UserModel
231 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
232 const query: FindOptions = {
235 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
240 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
246 if (options.withFiles === true) {
248 model: VideoFileModel.unscoped(),
253 if (options.videoPlaylistId) {
255 model: VideoPlaylistElementModel.unscoped(),
258 videoPlaylistId: options.videoPlaylistId
265 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
266 const query: FindOptions = {
268 attributes: [ 'id' ],
273 [ Op.notIn ]: Sequelize.literal(
274 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
280 [ Op.notIn ]: Sequelize.literal(
282 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
283 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
292 // Only list public/published videos
293 if (!options.filter || options.filter !== 'all-local') {
294 const privacyWhere = {
295 // Always list public videos
296 privacy: VideoPrivacy.PUBLIC,
297 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
300 state: VideoState.PUBLISHED
304 state: VideoState.TO_TRANSCODE,
305 waitTranscoding: false
311 Object.assign(query.where, privacyWhere)
314 if (options.videoPlaylistId) {
317 model: VideoPlaylistElementModel.unscoped(),
320 videoPlaylistId: options.videoPlaylistId
324 query.subQuery = false
327 if (options.filter || options.accountId || options.videoChannelId) {
328 const videoChannelInclude: IncludeOptions = {
330 model: VideoChannelModel.unscoped(),
334 if (options.videoChannelId) {
335 videoChannelInclude.where = {
336 id: options.videoChannelId
340 if (options.filter || options.accountId) {
341 const accountInclude: IncludeOptions = {
343 model: AccountModel.unscoped(),
347 if (options.filter) {
348 accountInclude.include = [
351 model: ActorModel.unscoped(),
353 where: VideoModel.buildActorWhereWithFilter(options.filter)
358 if (options.accountId) {
359 accountInclude.where = { id: options.accountId }
362 videoChannelInclude.include = [ accountInclude ]
365 query.include.push(videoChannelInclude)
368 if (options.followerActorId) {
369 let localVideosReq = ''
370 if (options.includeLocalVideos === true) {
371 localVideosReq = ' UNION ALL ' +
372 'SELECT "video"."id" AS "id" FROM "video" ' +
373 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
374 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
375 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
376 'WHERE "actor"."serverId" IS NULL'
379 // Force actorId to be a number to avoid SQL injections
380 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
381 query.where[ 'id' ][ Op.and ].push({
382 [ Op.in ]: Sequelize.literal(
384 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
385 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
386 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
388 'SELECT "video"."id" AS "id" FROM "video" ' +
389 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
390 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
391 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
392 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
393 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
400 if (options.withFiles === true) {
401 query.where[ 'id' ][ Op.and ].push({
402 [ Op.in ]: Sequelize.literal(
403 '(SELECT "videoId" FROM "videoFile")'
408 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
409 if (options.tagsAllOf || options.tagsOneOf) {
410 const createTagsIn = (tags: string[]) => {
411 return tags.map(t => VideoModel.sequelize.escape(t))
415 if (options.tagsOneOf) {
416 query.where[ 'id' ][ Op.and ].push({
417 [ Op.in ]: Sequelize.literal(
419 'SELECT "videoId" FROM "videoTag" ' +
420 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
421 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
427 if (options.tagsAllOf) {
428 query.where[ 'id' ][ Op.and ].push({
429 [ Op.in ]: Sequelize.literal(
431 'SELECT "videoId" FROM "videoTag" ' +
432 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
433 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
434 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
441 if (options.nsfw === true || options.nsfw === false) {
442 query.where[ 'nsfw' ] = options.nsfw
445 if (options.categoryOneOf) {
446 query.where[ 'category' ] = {
447 [ Op.or ]: options.categoryOneOf
451 if (options.licenceOneOf) {
452 query.where[ 'licence' ] = {
453 [ Op.or ]: options.licenceOneOf
457 if (options.languageOneOf) {
458 query.where[ 'language' ] = {
459 [ Op.or ]: options.languageOneOf
463 if (options.trendingDays) {
464 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
466 query.subQuery = false
469 if (options.historyOfUser) {
471 model: UserVideoHistoryModel,
474 userId: options.historyOfUser.id
478 // Even if the relation is n:m, we know that a user only have 0..1 video history
479 // So we won't have multiple rows for the same video
480 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
481 query.subQuery = false
486 [ ScopeNames.WITH_THUMBNAILS ]: {
489 model: ThumbnailModel,
494 [ ScopeNames.WITH_USER_ID ]: {
497 attributes: [ 'accountId' ],
498 model: VideoChannelModel.unscoped(),
502 attributes: [ 'userId' ],
503 model: AccountModel.unscoped(),
510 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
513 model: VideoChannelModel.unscoped(),
518 exclude: [ 'privateKey', 'publicKey' ]
520 model: ActorModel.unscoped(),
524 attributes: [ 'host' ],
525 model: ServerModel.unscoped(),
529 model: AvatarModel.unscoped(),
535 model: AccountModel.unscoped(),
539 model: ActorModel.unscoped(),
541 exclude: [ 'privateKey', 'publicKey' ]
546 attributes: [ 'host' ],
547 model: ServerModel.unscoped(),
551 model: AvatarModel.unscoped(),
562 [ ScopeNames.WITH_TAGS ]: {
563 include: [ TagModel ]
565 [ ScopeNames.WITH_BLACKLISTED ]: {
568 attributes: [ 'id', 'reason' ],
569 model: VideoBlacklistModel,
574 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
575 let subInclude: any[] = []
577 if (withRedundancies === true) {
580 attributes: [ 'fileUrl' ],
581 model: VideoRedundancyModel.unscoped(),
590 model: VideoFileModel.unscoped(),
591 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
598 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
599 let subInclude: any[] = []
601 if (withRedundancies === true) {
604 attributes: [ 'fileUrl' ],
605 model: VideoRedundancyModel.unscoped(),
614 model: VideoStreamingPlaylistModel.unscoped(),
615 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
622 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
625 model: ScheduleVideoUpdateModel.unscoped(),
630 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
634 attributes: [ 'currentTime' ],
635 model: UserVideoHistoryModel.unscoped(),
649 export class VideoModel extends Model<VideoModel> {
652 @Default(DataType.UUIDV4)
654 @Column(DataType.UUID)
658 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
664 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
670 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
676 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
677 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
681 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
686 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
692 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
693 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
698 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
699 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
703 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
733 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
734 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
739 commentsEnabled: boolean
743 downloadEnabled: boolean
747 waitTranscoding: boolean
751 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
762 @Default(DataType.NOW)
769 originallyPublishedAt: Date
771 @ForeignKey(() => VideoChannelModel)
775 @BelongsTo(() => VideoChannelModel, {
781 VideoChannel: VideoChannelModel
783 @BelongsToMany(() => TagModel, {
784 foreignKey: 'videoId',
785 through: () => VideoTagModel,
790 @HasMany(() => ThumbnailModel, {
798 Thumbnails: ThumbnailModel[]
800 @HasMany(() => VideoPlaylistElementModel, {
807 VideoPlaylistElements: VideoPlaylistElementModel[]
809 @HasMany(() => VideoAbuseModel, {
816 VideoAbuses: VideoAbuseModel[]
818 @HasMany(() => VideoFileModel, {
826 VideoFiles: VideoFileModel[]
828 @HasMany(() => VideoStreamingPlaylistModel, {
836 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
838 @HasMany(() => VideoShareModel, {
845 VideoShares: VideoShareModel[]
847 @HasMany(() => AccountVideoRateModel, {
854 AccountVideoRates: AccountVideoRateModel[]
856 @HasMany(() => VideoCommentModel, {
864 VideoComments: VideoCommentModel[]
866 @HasMany(() => VideoViewModel, {
873 VideoViews: VideoViewModel[]
875 @HasMany(() => UserVideoHistoryModel, {
882 UserVideoHistories: UserVideoHistoryModel[]
884 @HasOne(() => ScheduleVideoUpdateModel, {
891 ScheduleVideoUpdate: ScheduleVideoUpdateModel
893 @HasOne(() => VideoBlacklistModel, {
900 VideoBlacklist: VideoBlacklistModel
902 @HasOne(() => VideoImportModel, {
909 VideoImport: VideoImportModel
911 @HasMany(() => VideoCaptionModel, {
918 [ 'separate' as any ]: true
920 VideoCaptions: VideoCaptionModel[]
923 static async sendDelete (instance: VideoModel, options) {
924 if (instance.isOwned()) {
925 if (!instance.VideoChannel) {
926 instance.VideoChannel = await instance.$get('VideoChannel', {
930 include: [ ActorModel ]
933 transaction: options.transaction
934 }) as VideoChannelModel
937 return sendDeleteVideo(instance, options.transaction)
944 static async removeFiles (instance: VideoModel) {
945 const tasks: Promise<any>[] = []
947 logger.info('Removing files of video %s.', instance.url)
949 if (instance.isOwned()) {
950 if (!Array.isArray(instance.VideoFiles)) {
951 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
954 // Remove physical files and torrents
955 instance.VideoFiles.forEach(file => {
956 tasks.push(instance.removeFile(file))
957 tasks.push(instance.removeTorrent(file))
960 // Remove playlists file
961 tasks.push(instance.removeStreamingPlaylist())
964 // Do not wait video deletion because we could be in a transaction
967 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
973 static listLocal () {
980 return VideoModel.scope([
981 ScopeNames.WITH_FILES,
982 ScopeNames.WITH_STREAMING_PLAYLISTS,
983 ScopeNames.WITH_THUMBNAILS
987 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
988 function getRawQuery (select: string) {
989 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
990 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
991 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
992 'WHERE "Account"."actorId" = ' + actorId
993 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
994 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
995 'WHERE "VideoShare"."actorId" = ' + actorId
997 return `(${queryVideo}) UNION (${queryVideoShare})`
1000 const rawQuery = getRawQuery('"Video"."id"')
1001 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1007 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1010 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1013 { privacy: VideoPrivacy.PUBLIC },
1014 { privacy: VideoPrivacy.UNLISTED }
1019 attributes: [ 'language' ],
1020 model: VideoCaptionModel.unscoped(),
1024 attributes: [ 'id', 'url' ],
1025 model: VideoShareModel.unscoped(),
1027 // We only want videos shared by this actor
1042 attributes: [ 'id', 'url' ],
1043 model: ActorModel.unscoped()
1048 model: VideoChannelModel.unscoped(),
1052 attributes: [ 'name' ],
1053 model: AccountModel.unscoped(),
1057 attributes: [ 'id', 'url', 'followersUrl' ],
1058 model: ActorModel.unscoped(),
1064 attributes: [ 'id', 'url', 'followersUrl' ],
1065 model: ActorModel.unscoped(),
1075 return Bluebird.all([
1076 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1077 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1078 ]).then(([ rows, totals ]) => {
1079 // totals: totalVideos + totalVideoShares
1081 let totalVideoShares = 0
1082 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1083 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1085 const total = totalVideos + totalVideoShares
1093 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1094 function buildBaseQuery (): FindOptions {
1098 order: getVideoSort(sort),
1101 model: VideoChannelModel,
1105 model: AccountModel,
1117 const countQuery = buildBaseQuery()
1118 const findQuery = buildBaseQuery()
1120 findQuery.include.push({
1121 model: ScheduleVideoUpdateModel,
1125 findQuery.include.push({
1126 model: VideoBlacklistModel,
1130 if (withFiles === true) {
1131 findQuery.include.push({
1132 model: VideoFileModel.unscoped(),
1137 return Promise.all([
1138 VideoModel.count(countQuery),
1139 VideoModel.findAll(findQuery)
1140 ]).then(([ count, rows ]) => {
1148 static async listForApi (options: {
1153 includeLocalVideos: boolean,
1155 categoryOneOf?: number[],
1156 licenceOneOf?: number[],
1157 languageOneOf?: string[],
1158 tagsOneOf?: string[],
1159 tagsAllOf?: string[],
1160 filter?: VideoFilter,
1162 videoChannelId?: number,
1163 followerActorId?: number
1164 videoPlaylistId?: number,
1165 trendingDays?: number,
1167 historyOfUser?: UserModel
1168 }, countVideos = true) {
1169 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1170 throw new Error('Try to filter all-local but no user has not the see all videos right')
1173 const query: FindOptions = {
1174 offset: options.start,
1175 limit: options.count,
1176 order: getVideoSort(options.sort)
1179 let trendingDays: number
1180 if (options.sort.endsWith('trending')) {
1181 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1183 query.group = 'VideoModel.id'
1186 const serverActor = await getServerActor()
1188 // followerActorId === null has a meaning, so just check undefined
1189 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1191 const queryOptions = {
1193 serverAccountId: serverActor.Account.id,
1195 categoryOneOf: options.categoryOneOf,
1196 licenceOneOf: options.licenceOneOf,
1197 languageOneOf: options.languageOneOf,
1198 tagsOneOf: options.tagsOneOf,
1199 tagsAllOf: options.tagsAllOf,
1200 filter: options.filter,
1201 withFiles: options.withFiles,
1202 accountId: options.accountId,
1203 videoChannelId: options.videoChannelId,
1204 videoPlaylistId: options.videoPlaylistId,
1205 includeLocalVideos: options.includeLocalVideos,
1207 historyOfUser: options.historyOfUser,
1211 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1214 static async searchAndPopulateAccountAndServer (options: {
1215 includeLocalVideos: boolean
1220 startDate?: string // ISO 8601
1221 endDate?: string // ISO 8601
1222 originallyPublishedStartDate?: string
1223 originallyPublishedEndDate?: string
1225 categoryOneOf?: number[]
1226 licenceOneOf?: number[]
1227 languageOneOf?: string[]
1228 tagsOneOf?: string[]
1229 tagsAllOf?: string[]
1230 durationMin?: number // seconds
1231 durationMax?: number // seconds
1233 filter?: VideoFilter
1237 if (options.startDate || options.endDate) {
1238 const publishedAtRange = {}
1240 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1241 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1243 whereAnd.push({ publishedAt: publishedAtRange })
1246 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1247 const originallyPublishedAtRange = {}
1249 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1250 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1252 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1255 if (options.durationMin || options.durationMax) {
1256 const durationRange = {}
1258 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1259 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1261 whereAnd.push({ duration: durationRange })
1264 const attributesInclude = []
1265 const escapedSearch = VideoModel.sequelize.escape(options.search)
1266 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1267 if (options.search) {
1271 [ Op.in ]: Sequelize.literal(
1273 'SELECT "video"."id" FROM "video" ' +
1275 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1276 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1278 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1279 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1280 'WHERE "tag"."name" = ' + escapedSearch +
1287 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1290 // Cannot search on similarity if we don't have a search
1291 if (!options.search) {
1292 attributesInclude.push(
1293 Sequelize.literal('0 as similarity')
1297 const query: FindOptions = {
1299 include: attributesInclude
1301 offset: options.start,
1302 limit: options.count,
1303 order: getVideoSort(options.sort),
1305 [ Op.and ]: whereAnd
1309 const serverActor = await getServerActor()
1310 const queryOptions = {
1311 followerActorId: serverActor.id,
1312 serverAccountId: serverActor.Account.id,
1313 includeLocalVideos: options.includeLocalVideos,
1315 categoryOneOf: options.categoryOneOf,
1316 licenceOneOf: options.licenceOneOf,
1317 languageOneOf: options.languageOneOf,
1318 tagsOneOf: options.tagsOneOf,
1319 tagsAllOf: options.tagsAllOf,
1321 filter: options.filter
1324 return VideoModel.getAvailableForApi(query, queryOptions)
1327 static load (id: number | string, t?: Transaction) {
1328 const where = buildWhereIdOrUUID(id)
1334 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1337 static loadWithRights (id: number | string, t?: Transaction) {
1338 const where = buildWhereIdOrUUID(id)
1344 return VideoModel.scope([
1345 ScopeNames.WITH_BLACKLISTED,
1346 ScopeNames.WITH_USER_ID,
1347 ScopeNames.WITH_THUMBNAILS
1351 static loadOnlyId (id: number | string, t?: Transaction) {
1352 const where = buildWhereIdOrUUID(id)
1355 attributes: [ 'id' ],
1360 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1363 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1364 return VideoModel.scope([
1365 ScopeNames.WITH_FILES,
1366 ScopeNames.WITH_STREAMING_PLAYLISTS,
1367 ScopeNames.WITH_THUMBNAILS
1368 ]).findByPk(id, { transaction: t, logging })
1371 static loadByUUIDWithFile (uuid: string) {
1378 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1381 static loadByUrl (url: string, transaction?: Transaction) {
1382 const query: FindOptions = {
1389 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1392 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1393 const query: FindOptions = {
1400 return VideoModel.scope([
1401 ScopeNames.WITH_ACCOUNT_DETAILS,
1402 ScopeNames.WITH_FILES,
1403 ScopeNames.WITH_STREAMING_PLAYLISTS,
1404 ScopeNames.WITH_THUMBNAILS
1408 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1409 const where = buildWhereIdOrUUID(id)
1412 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1417 const scopes: (string | ScopeOptions)[] = [
1418 ScopeNames.WITH_TAGS,
1419 ScopeNames.WITH_BLACKLISTED,
1420 ScopeNames.WITH_ACCOUNT_DETAILS,
1421 ScopeNames.WITH_SCHEDULED_UPDATE,
1422 ScopeNames.WITH_FILES,
1423 ScopeNames.WITH_STREAMING_PLAYLISTS,
1424 ScopeNames.WITH_THUMBNAILS
1428 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1436 static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) {
1437 const where = buildWhereIdOrUUID(id)
1440 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1445 const scopes: (string | ScopeOptions)[] = [
1446 ScopeNames.WITH_TAGS,
1447 ScopeNames.WITH_BLACKLISTED,
1448 ScopeNames.WITH_ACCOUNT_DETAILS,
1449 ScopeNames.WITH_SCHEDULED_UPDATE,
1450 ScopeNames.WITH_THUMBNAILS,
1451 { method: [ ScopeNames.WITH_FILES, true ] },
1452 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1456 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1464 static async getStats () {
1465 const totalLocalVideos = await VideoModel.count({
1470 const totalVideos = await VideoModel.count()
1472 let totalLocalVideoViews = await VideoModel.sum('views', {
1477 // Sequelize could return null...
1478 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1482 totalLocalVideoViews,
1487 static incrementViews (id: number, views: number) {
1488 return VideoModel.increment('views', {
1496 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1497 // Instances only share videos
1498 const query = 'SELECT 1 FROM "videoShare" ' +
1499 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1500 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1504 type: QueryTypes.SELECT,
1505 bind: { followerActorId, videoId },
1509 return VideoModel.sequelize.query(query, options)
1510 .then(results => results.length === 1)
1513 // threshold corresponds to how many video the field should have to be returned
1514 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1515 const serverActor = await getServerActor()
1516 const followerActorId = serverActor.id
1518 const scopeOptions: AvailableForListIDsOptions = {
1519 serverAccountId: serverActor.Account.id,
1521 includeLocalVideos: true
1524 const query: FindOptions = {
1525 attributes: [ field ],
1528 having: Sequelize.where(
1529 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1531 order: [ (this.sequelize as any).random() ]
1534 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1536 .then(rows => rows.map(r => r[ field ]))
1539 static buildTrendingQuery (trendingDays: number) {
1543 model: VideoViewModel,
1547 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1553 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1554 if (filter && (filter === 'local' || filter === 'all-local')) {
1563 private static async getAvailableForApi (
1565 options: AvailableForListIDsOptions,
1568 const idsScope: ScopeOptions = {
1570 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1574 // Remove trending sort on count, because it uses a group by
1575 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1576 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1577 const countScope: ScopeOptions = {
1579 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1583 const [ count, rowsId ] = await Promise.all([
1584 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1585 VideoModel.scope(idsScope).findAll(query)
1587 const ids = rowsId.map(r => r.id)
1589 if (ids.length === 0) return { data: [], total: count }
1591 const secondQuery: FindOptions = {
1594 attributes: query.attributes,
1595 order: [ // Keep original order
1597 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1602 const apiScope: (string | ScopeOptions)[] = [ ScopeNames.WITH_THUMBNAILS ]
1605 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1610 ScopeNames.FOR_API, {
1612 withFiles: options.withFiles,
1613 videoPlaylistId: options.videoPlaylistId
1618 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1626 static getCategoryLabel (id: number) {
1627 return VIDEO_CATEGORIES[ id ] || 'Misc'
1630 static getLicenceLabel (id: number) {
1631 return VIDEO_LICENCES[ id ] || 'Unknown'
1634 static getLanguageLabel (id: string) {
1635 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1638 static getPrivacyLabel (id: number) {
1639 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1642 static getStateLabel (id: number) {
1643 return VIDEO_STATES[ id ] || 'Unknown'
1646 getOriginalFile () {
1647 if (Array.isArray(this.VideoFiles) === false) return undefined
1649 // The original file is the file that have the higher resolution
1650 return maxBy(this.VideoFiles, file => file.resolution)
1653 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1654 thumbnail.videoId = this.id
1656 const savedThumbnail = await thumbnail.save({ transaction })
1658 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1660 // Already have this thumbnail, skip
1661 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1663 this.Thumbnails.push(savedThumbnail)
1666 getVideoFilename (videoFile: VideoFileModel) {
1667 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1670 generateThumbnailName () {
1671 return this.uuid + '.jpg'
1675 if (Array.isArray(this.Thumbnails) === false) return undefined
1677 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1680 generatePreviewName () {
1681 return this.uuid + '.jpg'
1685 if (Array.isArray(this.Thumbnails) === false) return undefined
1687 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1690 getTorrentFileName (videoFile: VideoFileModel) {
1691 const extension = '.torrent'
1692 return this.uuid + '-' + videoFile.resolution + extension
1696 return this.remote === false
1699 getTorrentFilePath (videoFile: VideoFileModel) {
1700 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1703 getVideoFilePath (videoFile: VideoFileModel) {
1704 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1707 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1709 // Keep the extname, it's used by the client to stream the file inside a web browser
1710 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1711 createdBy: 'PeerTube',
1713 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1714 [ WEBSERVER.URL + '/tracker/announce' ]
1716 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1719 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1721 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1722 logger.info('Creating torrent %s.', filePath)
1724 await writeFile(filePath, torrent)
1726 const parsedTorrent = parseTorrent(torrent)
1727 videoFile.infoHash = parsedTorrent.infoHash
1730 getWatchStaticPath () {
1731 return '/videos/watch/' + this.uuid
1734 getEmbedStaticPath () {
1735 return '/videos/embed/' + this.uuid
1738 getMiniatureStaticPath () {
1739 const thumbnail = this.getMiniature()
1740 if (!thumbnail) return null
1742 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1745 getPreviewStaticPath () {
1746 const preview = this.getPreview()
1747 if (!preview) return null
1749 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1750 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1753 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1754 return videoModelToFormattedJSON(this, options)
1757 toFormattedDetailsJSON (): VideoDetails {
1758 return videoModelToFormattedDetailsJSON(this)
1761 getFormattedVideoFilesJSON (): VideoFile[] {
1762 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1765 toActivityPubObject (): VideoTorrentObject {
1766 return videoModelToActivityPubObject(this)
1769 getTruncatedDescription () {
1770 if (!this.description) return null
1772 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1773 return peertubeTruncate(this.description, maxLength)
1776 getOriginalFileResolution () {
1777 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1779 return getVideoFileResolution(originalFilePath)
1782 getDescriptionAPIPath () {
1783 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1786 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1787 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1789 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1790 return remove(filePath)
1791 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1794 removeTorrent (videoFile: VideoFileModel) {
1795 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1796 return remove(torrentPath)
1797 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1800 removeStreamingPlaylist (isRedundancy = false) {
1801 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1803 const filePath = join(baseDir, this.uuid)
1804 return remove(filePath)
1805 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1809 if (this.isOwned()) return false
1811 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1815 this.changed('updatedAt', true)
1824 if (this.isOwned()) {
1825 baseUrlHttp = WEBSERVER.URL
1826 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1828 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1829 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1832 return { baseUrlHttp, baseUrlWs }
1835 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1836 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1837 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1838 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1840 const redundancies = videoFile.RedundancyVideos
1841 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1843 const magnetHash = {
1847 infoHash: videoFile.infoHash,
1851 return magnetUtil.encode(magnetHash)
1854 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1855 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1858 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1859 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1862 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1863 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1866 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1867 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1870 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1871 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1874 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1875 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1878 getBandwidthBits (videoFile: VideoFileModel) {
1879 return Math.ceil((videoFile.size * 8) / this.duration)