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 { 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,
68 STATIC_DOWNLOAD_PATHS,
76 } from '../../initializers/constants'
77 import { sendDeleteVideo } from '../../lib/activitypub/send'
78 import { AccountModel } from '../account/account'
79 import { AccountVideoRateModel } from '../account/account-video-rate'
80 import { ActorModel } from '../activitypub/actor'
81 import { AvatarModel } from '../avatar/avatar'
82 import { ServerModel } from '../server/server'
84 buildBlockedAccountSQL,
85 buildTrigramSearchIndex,
88 createSimilarityAttribute,
93 import { TagModel } from './tag'
94 import { VideoAbuseModel } from './video-abuse'
95 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
96 import { VideoCommentModel } from './video-comment'
97 import { VideoFileModel } from './video-file'
98 import { VideoShareModel } from './video-share'
99 import { VideoTagModel } from './video-tag'
100 import { ScheduleVideoUpdateModel } from './schedule-video-update'
101 import { VideoCaptionModel } from './video-caption'
102 import { VideoBlacklistModel } from './video-blacklist'
103 import { remove, writeFile } from 'fs-extra'
104 import { VideoViewModel } from './video-views'
105 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 videoFilesModelToFormattedJSON,
108 VideoFormattingJSONOptions,
109 videoModelToActivityPubObject,
110 videoModelToFormattedDetailsJSON,
111 videoModelToFormattedJSON
112 } from './video-format-utils'
113 import { UserVideoHistoryModel } from '../account/user-video-history'
114 import { VideoImportModel } from './video-import'
115 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
116 import { VideoPlaylistElementModel } from './video-playlist-element'
117 import { CONFIG } from '../../initializers/config'
118 import { ThumbnailModel } from './thumbnail'
119 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 import { createTorrentPromise } from '../../helpers/webtorrent'
121 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
124 MChannelAccountDefault,
129 MVideoAccountLightBlacklistAllFiles,
137 } from '../../typings/models'
138 import { MVideoFile, MVideoFileRedundanciesOpt } from '../../typings/models/video/video-file'
139 import { MThumbnail } from '../../typings/models/video/thumbnail'
141 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
142 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
143 buildTrigramSearchIndex('video_name_trigram', 'name'),
145 { fields: [ 'createdAt' ] },
146 { fields: [ 'publishedAt' ] },
147 { fields: [ 'duration' ] },
148 { fields: [ 'views' ] },
149 { fields: [ 'channelId' ] },
151 fields: [ 'originallyPublishedAt' ],
153 originallyPublishedAt: {
159 fields: [ 'category' ], // We don't care videos with an unknown category
167 fields: [ 'licence' ], // We don't care videos with an unknown licence
175 fields: [ 'language' ], // We don't care videos with an unknown language
183 fields: [ 'nsfw' ], // Most of the videos are not NSFW
189 fields: [ 'remote' ], // Only index local videos
204 export enum ScopeNames {
205 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
207 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
208 WITH_TAGS = 'WITH_TAGS',
209 WITH_FILES = 'WITH_FILES',
210 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
211 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
212 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
213 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
214 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
215 WITH_USER_ID = 'WITH_USER_ID',
216 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
219 export type ForAPIOptions = {
222 videoPlaylistId?: number
226 withAccountBlockerIds?: number[]
229 export type AvailableForListIDsOptions = {
230 serverAccountId: number
231 followerActorId: number
232 includeLocalVideos: boolean
234 attributesType?: 'none' | 'id' | 'all'
237 categoryOneOf?: number[]
239 licenceOneOf?: number[]
240 languageOneOf?: string[]
247 videoChannelId?: number
249 videoPlaylistId?: number
251 trendingDays?: number
252 user?: MUserAccountId
253 historyOfUser?: MUserId
255 baseWhere?: WhereOptions[]
259 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
260 const query: FindOptions = {
263 model: VideoChannelModel.scope({
265 VideoChannelScopeNames.SUMMARY, {
267 withAccountBlockerIds: options.withAccountBlockerIds
274 attributes: [ 'type', 'filename' ],
275 model: ThumbnailModel,
284 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
289 if (options.withFiles === true) {
291 model: VideoFileModel.unscoped(),
296 if (options.videoPlaylistId) {
298 model: VideoPlaylistElementModel.unscoped(),
301 videoPlaylistId: options.videoPlaylistId
308 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
309 const whereAnd = options.baseWhere ? options.baseWhere : []
311 const query: FindOptions = {
316 const attributesType = options.attributesType || 'id'
318 if (attributesType === 'id') query.attributes = [ 'id' ]
319 else if (attributesType === 'none') query.attributes = [ ]
323 [ Op.notIn ]: Sequelize.literal(
324 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
329 if (options.serverAccountId) {
332 [ Op.notIn ]: Sequelize.literal(
334 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
335 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
343 // Only list public/published videos
344 if (!options.filter || options.filter !== 'all-local') {
345 const privacyWhere = {
346 // Always list public videos
347 privacy: VideoPrivacy.PUBLIC,
348 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
351 state: VideoState.PUBLISHED
355 state: VideoState.TO_TRANSCODE,
356 waitTranscoding: false
362 whereAnd.push(privacyWhere)
365 if (options.videoPlaylistId) {
368 model: VideoPlaylistElementModel.unscoped(),
371 videoPlaylistId: options.videoPlaylistId
375 query.subQuery = false
378 if (options.filter || options.accountId || options.videoChannelId) {
379 const videoChannelInclude: IncludeOptions = {
381 model: VideoChannelModel.unscoped(),
385 if (options.videoChannelId) {
386 videoChannelInclude.where = {
387 id: options.videoChannelId
391 if (options.filter || options.accountId) {
392 const accountInclude: IncludeOptions = {
394 model: AccountModel.unscoped(),
398 if (options.filter) {
399 accountInclude.include = [
402 model: ActorModel.unscoped(),
404 where: VideoModel.buildActorWhereWithFilter(options.filter)
409 if (options.accountId) {
410 accountInclude.where = { id: options.accountId }
413 videoChannelInclude.include = [ accountInclude ]
416 query.include.push(videoChannelInclude)
419 if (options.followerActorId) {
420 let localVideosReq = ''
421 if (options.includeLocalVideos === true) {
422 localVideosReq = ' UNION ALL ' +
423 'SELECT "video"."id" AS "id" FROM "video" ' +
424 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
425 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
426 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
427 'WHERE "actor"."serverId" IS NULL'
430 // Force actorId to be a number to avoid SQL injections
431 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
434 [ Op.in ]: Sequelize.literal(
436 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
437 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
438 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
440 'SELECT "video"."id" AS "id" FROM "video" ' +
441 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
442 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
443 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
444 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
445 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
453 if (options.withFiles === true) {
456 [ Op.in ]: Sequelize.literal(
457 '(SELECT "videoId" FROM "videoFile")'
463 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
464 if (options.tagsAllOf || options.tagsOneOf) {
465 if (options.tagsOneOf) {
468 [ Op.in ]: Sequelize.literal(
470 'SELECT "videoId" FROM "videoTag" ' +
471 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
472 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
479 if (options.tagsAllOf) {
482 [ Op.in ]: Sequelize.literal(
484 'SELECT "videoId" FROM "videoTag" ' +
485 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
486 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
487 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
495 if (options.nsfw === true || options.nsfw === false) {
496 whereAnd.push({ nsfw: options.nsfw })
499 if (options.categoryOneOf) {
502 [ Op.or ]: options.categoryOneOf
507 if (options.licenceOneOf) {
510 [ Op.or ]: options.licenceOneOf
515 if (options.languageOneOf) {
516 let videoLanguages = options.languageOneOf
517 if (options.languageOneOf.find(l => l === '_unknown')) {
518 videoLanguages = videoLanguages.concat([ null ])
525 [ Op.or ]: videoLanguages
530 [ Op.in ]: Sequelize.literal(
532 'SELECT "videoId" FROM "videoCaption" ' +
533 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
542 if (options.trendingDays) {
543 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
545 query.subQuery = false
548 if (options.historyOfUser) {
550 model: UserVideoHistoryModel,
553 userId: options.historyOfUser.id
557 // Even if the relation is n:m, we know that a user only have 0..1 video history
558 // So we won't have multiple rows for the same video
559 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
560 query.subQuery = false
569 [ScopeNames.WITH_BLOCKLIST]: {
572 [ ScopeNames.WITH_THUMBNAILS ]: {
575 model: ThumbnailModel,
580 [ ScopeNames.WITH_USER_ID ]: {
583 attributes: [ 'accountId' ],
584 model: VideoChannelModel.unscoped(),
588 attributes: [ 'userId' ],
589 model: AccountModel.unscoped(),
596 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
599 model: VideoChannelModel.unscoped(),
604 exclude: [ 'privateKey', 'publicKey' ]
606 model: ActorModel.unscoped(),
610 attributes: [ 'host' ],
611 model: ServerModel.unscoped(),
615 model: AvatarModel.unscoped(),
621 model: AccountModel.unscoped(),
625 model: ActorModel.unscoped(),
627 exclude: [ 'privateKey', 'publicKey' ]
632 attributes: [ 'host' ],
633 model: ServerModel.unscoped(),
637 model: AvatarModel.unscoped(),
648 [ ScopeNames.WITH_TAGS ]: {
649 include: [ TagModel ]
651 [ ScopeNames.WITH_BLACKLISTED ]: {
654 attributes: [ 'id', 'reason', 'unfederated' ],
655 model: VideoBlacklistModel,
660 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
661 let subInclude: any[] = []
663 if (withRedundancies === true) {
666 attributes: [ 'fileUrl' ],
667 model: VideoRedundancyModel.unscoped(),
676 model: VideoFileModel.unscoped(),
677 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
684 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
685 let subInclude: any[] = []
687 if (withRedundancies === true) {
690 attributes: [ 'fileUrl' ],
691 model: VideoRedundancyModel.unscoped(),
700 model: VideoStreamingPlaylistModel.unscoped(),
701 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
708 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
711 model: ScheduleVideoUpdateModel.unscoped(),
716 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
720 attributes: [ 'currentTime' ],
721 model: UserVideoHistoryModel.unscoped(),
735 export class VideoModel extends Model<VideoModel> {
738 @Default(DataType.UUIDV4)
740 @Column(DataType.UUID)
744 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
750 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
756 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
762 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
763 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
767 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
772 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
778 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
779 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
784 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
785 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
789 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
819 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
820 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
825 commentsEnabled: boolean
829 downloadEnabled: boolean
833 waitTranscoding: boolean
837 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
848 @Default(DataType.NOW)
855 originallyPublishedAt: Date
857 @ForeignKey(() => VideoChannelModel)
861 @BelongsTo(() => VideoChannelModel, {
867 VideoChannel: VideoChannelModel
869 @BelongsToMany(() => TagModel, {
870 foreignKey: 'videoId',
871 through: () => VideoTagModel,
876 @HasMany(() => ThumbnailModel, {
884 Thumbnails: ThumbnailModel[]
886 @HasMany(() => VideoPlaylistElementModel, {
893 VideoPlaylistElements: VideoPlaylistElementModel[]
895 @HasMany(() => VideoAbuseModel, {
902 VideoAbuses: VideoAbuseModel[]
904 @HasMany(() => VideoFileModel, {
912 VideoFiles: VideoFileModel[]
914 @HasMany(() => VideoStreamingPlaylistModel, {
922 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
924 @HasMany(() => VideoShareModel, {
931 VideoShares: VideoShareModel[]
933 @HasMany(() => AccountVideoRateModel, {
940 AccountVideoRates: AccountVideoRateModel[]
942 @HasMany(() => VideoCommentModel, {
950 VideoComments: VideoCommentModel[]
952 @HasMany(() => VideoViewModel, {
959 VideoViews: VideoViewModel[]
961 @HasMany(() => UserVideoHistoryModel, {
968 UserVideoHistories: UserVideoHistoryModel[]
970 @HasOne(() => ScheduleVideoUpdateModel, {
977 ScheduleVideoUpdate: ScheduleVideoUpdateModel
979 @HasOne(() => VideoBlacklistModel, {
986 VideoBlacklist: VideoBlacklistModel
988 @HasOne(() => VideoImportModel, {
995 VideoImport: VideoImportModel
997 @HasMany(() => VideoCaptionModel, {
1002 onDelete: 'cascade',
1004 [ 'separate' as any ]: true
1006 VideoCaptions: VideoCaptionModel[]
1009 static async sendDelete (instance: MVideoAccountLight, options) {
1010 if (instance.isOwned()) {
1011 if (!instance.VideoChannel) {
1012 instance.VideoChannel = await instance.$get('VideoChannel', {
1017 transaction: options.transaction
1018 }) as MChannelAccountDefault
1021 return sendDeleteVideo(instance, options.transaction)
1028 static async removeFiles (instance: VideoModel) {
1029 const tasks: Promise<any>[] = []
1031 logger.info('Removing files of video %s.', instance.url)
1033 if (instance.isOwned()) {
1034 if (!Array.isArray(instance.VideoFiles)) {
1035 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1038 // Remove physical files and torrents
1039 instance.VideoFiles.forEach(file => {
1040 tasks.push(instance.removeFile(file))
1041 tasks.push(instance.removeTorrent(file))
1044 // Remove playlists file
1045 tasks.push(instance.removeStreamingPlaylist())
1048 // Do not wait video deletion because we could be in a transaction
1051 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1057 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1064 return VideoModel.scope([
1065 ScopeNames.WITH_FILES,
1066 ScopeNames.WITH_STREAMING_PLAYLISTS,
1067 ScopeNames.WITH_THUMBNAILS
1071 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1072 function getRawQuery (select: string) {
1073 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1074 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1075 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1076 'WHERE "Account"."actorId" = ' + actorId
1077 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1078 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1079 'WHERE "VideoShare"."actorId" = ' + actorId
1081 return `(${queryVideo}) UNION (${queryVideoShare})`
1084 const rawQuery = getRawQuery('"Video"."id"')
1085 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1091 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1094 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1097 { privacy: VideoPrivacy.PUBLIC },
1098 { privacy: VideoPrivacy.UNLISTED }
1103 attributes: [ 'language' ],
1104 model: VideoCaptionModel.unscoped(),
1108 attributes: [ 'id', 'url' ],
1109 model: VideoShareModel.unscoped(),
1111 // We only want videos shared by this actor
1126 attributes: [ 'id', 'url' ],
1127 model: ActorModel.unscoped()
1132 model: VideoChannelModel.unscoped(),
1136 attributes: [ 'name' ],
1137 model: AccountModel.unscoped(),
1141 attributes: [ 'id', 'url', 'followersUrl' ],
1142 model: ActorModel.unscoped(),
1148 attributes: [ 'id', 'url', 'followersUrl' ],
1149 model: ActorModel.unscoped(),
1159 return Bluebird.all([
1160 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1161 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1162 ]).then(([ rows, totals ]) => {
1163 // totals: totalVideos + totalVideoShares
1165 let totalVideoShares = 0
1166 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1167 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1169 const total = totalVideos + totalVideoShares
1177 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1178 function buildBaseQuery (): FindOptions {
1182 order: getVideoSort(sort),
1185 model: VideoChannelModel,
1189 model: AccountModel,
1201 const countQuery = buildBaseQuery()
1202 const findQuery = buildBaseQuery()
1204 const findScopes = [
1205 ScopeNames.WITH_SCHEDULED_UPDATE,
1206 ScopeNames.WITH_BLACKLISTED,
1207 ScopeNames.WITH_THUMBNAILS
1210 return Promise.all([
1211 VideoModel.count(countQuery),
1212 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1213 ]).then(([ count, rows ]) => {
1221 static async listForApi (options: {
1226 includeLocalVideos: boolean,
1228 categoryOneOf?: number[],
1229 licenceOneOf?: number[],
1230 languageOneOf?: string[],
1231 tagsOneOf?: string[],
1232 tagsAllOf?: string[],
1233 filter?: VideoFilter,
1235 videoChannelId?: number,
1236 followerActorId?: number
1237 videoPlaylistId?: number,
1238 trendingDays?: number,
1239 user?: MUserAccountId,
1240 historyOfUser?: MUserId
1241 }, countVideos = true) {
1242 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1243 throw new Error('Try to filter all-local but no user has not the see all videos right')
1246 const query: FindOptions & { where?: null } = {
1247 offset: options.start,
1248 limit: options.count,
1249 order: getVideoSort(options.sort)
1252 let trendingDays: number
1253 if (options.sort.endsWith('trending')) {
1254 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1256 query.group = 'VideoModel.id'
1259 const serverActor = await getServerActor()
1261 // followerActorId === null has a meaning, so just check undefined
1262 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1264 const queryOptions = {
1266 serverAccountId: serverActor.Account.id,
1268 categoryOneOf: options.categoryOneOf,
1269 licenceOneOf: options.licenceOneOf,
1270 languageOneOf: options.languageOneOf,
1271 tagsOneOf: options.tagsOneOf,
1272 tagsAllOf: options.tagsAllOf,
1273 filter: options.filter,
1274 withFiles: options.withFiles,
1275 accountId: options.accountId,
1276 videoChannelId: options.videoChannelId,
1277 videoPlaylistId: options.videoPlaylistId,
1278 includeLocalVideos: options.includeLocalVideos,
1280 historyOfUser: options.historyOfUser,
1284 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1287 static async searchAndPopulateAccountAndServer (options: {
1288 includeLocalVideos: boolean
1293 startDate?: string // ISO 8601
1294 endDate?: string // ISO 8601
1295 originallyPublishedStartDate?: string
1296 originallyPublishedEndDate?: string
1298 categoryOneOf?: number[]
1299 licenceOneOf?: number[]
1300 languageOneOf?: string[]
1301 tagsOneOf?: string[]
1302 tagsAllOf?: string[]
1303 durationMin?: number // seconds
1304 durationMax?: number // seconds
1305 user?: MUserAccountId,
1306 filter?: VideoFilter
1310 if (options.startDate || options.endDate) {
1311 const publishedAtRange = {}
1313 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1314 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1316 whereAnd.push({ publishedAt: publishedAtRange })
1319 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1320 const originallyPublishedAtRange = {}
1322 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1323 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1325 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1328 if (options.durationMin || options.durationMax) {
1329 const durationRange = {}
1331 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1332 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1334 whereAnd.push({ duration: durationRange })
1337 const attributesInclude = []
1338 const escapedSearch = VideoModel.sequelize.escape(options.search)
1339 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1340 if (options.search) {
1344 [ Op.in ]: Sequelize.literal(
1346 'SELECT "video"."id" FROM "video" ' +
1348 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1349 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1351 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1352 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1353 'WHERE "tag"."name" = ' + escapedSearch +
1360 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1363 // Cannot search on similarity if we don't have a search
1364 if (!options.search) {
1365 attributesInclude.push(
1366 Sequelize.literal('0 as similarity')
1372 include: attributesInclude
1374 offset: options.start,
1375 limit: options.count,
1376 order: getVideoSort(options.sort)
1379 const serverActor = await getServerActor()
1380 const queryOptions = {
1381 followerActorId: serverActor.id,
1382 serverAccountId: serverActor.Account.id,
1383 includeLocalVideos: options.includeLocalVideos,
1385 categoryOneOf: options.categoryOneOf,
1386 licenceOneOf: options.licenceOneOf,
1387 languageOneOf: options.languageOneOf,
1388 tagsOneOf: options.tagsOneOf,
1389 tagsAllOf: options.tagsAllOf,
1391 filter: options.filter,
1395 return VideoModel.getAvailableForApi(query, queryOptions)
1398 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1399 const where = buildWhereIdOrUUID(id)
1405 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1408 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1409 const where = buildWhereIdOrUUID(id)
1415 return VideoModel.scope([
1416 ScopeNames.WITH_BLACKLISTED,
1417 ScopeNames.WITH_USER_ID,
1418 ScopeNames.WITH_THUMBNAILS
1422 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1423 const where = buildWhereIdOrUUID(id)
1426 attributes: [ 'id' ],
1431 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1434 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1435 const where = buildWhereIdOrUUID(id)
1443 return VideoModel.scope([
1444 ScopeNames.WITH_FILES,
1445 ScopeNames.WITH_STREAMING_PLAYLISTS,
1446 ScopeNames.WITH_THUMBNAILS
1450 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1457 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1460 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1461 const query: FindOptions = {
1468 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1471 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1472 const query: FindOptions = {
1479 return VideoModel.scope([
1480 ScopeNames.WITH_ACCOUNT_DETAILS,
1481 ScopeNames.WITH_FILES,
1482 ScopeNames.WITH_STREAMING_PLAYLISTS,
1483 ScopeNames.WITH_THUMBNAILS,
1484 ScopeNames.WITH_BLACKLISTED
1488 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1489 const where = buildWhereIdOrUUID(id)
1492 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1497 const scopes: (string | ScopeOptions)[] = [
1498 ScopeNames.WITH_TAGS,
1499 ScopeNames.WITH_BLACKLISTED,
1500 ScopeNames.WITH_ACCOUNT_DETAILS,
1501 ScopeNames.WITH_SCHEDULED_UPDATE,
1502 ScopeNames.WITH_FILES,
1503 ScopeNames.WITH_STREAMING_PLAYLISTS,
1504 ScopeNames.WITH_THUMBNAILS
1508 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1516 static loadForGetAPI (parameters: {
1517 id: number | string,
1520 }): Bluebird<MVideoDetails> {
1521 const { id, t, userId } = parameters
1522 const where = buildWhereIdOrUUID(id)
1525 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1530 const scopes: (string | ScopeOptions)[] = [
1531 ScopeNames.WITH_TAGS,
1532 ScopeNames.WITH_BLACKLISTED,
1533 ScopeNames.WITH_ACCOUNT_DETAILS,
1534 ScopeNames.WITH_SCHEDULED_UPDATE,
1535 ScopeNames.WITH_THUMBNAILS,
1536 { method: [ ScopeNames.WITH_FILES, true ] },
1537 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1541 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1549 static async getStats () {
1550 const totalLocalVideos = await VideoModel.count({
1555 const totalVideos = await VideoModel.count()
1557 let totalLocalVideoViews = await VideoModel.sum('views', {
1562 // Sequelize could return null...
1563 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1567 totalLocalVideoViews,
1572 static incrementViews (id: number, views: number) {
1573 return VideoModel.increment('views', {
1581 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1582 // Instances only share videos
1583 const query = 'SELECT 1 FROM "videoShare" ' +
1584 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1585 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1589 type: QueryTypes.SELECT,
1590 bind: { followerActorId, videoId },
1594 return VideoModel.sequelize.query(query, options)
1595 .then(results => results.length === 1)
1598 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1601 channelId: videoChannel.id
1606 return VideoModel.update({ support: videoChannel.support }, options)
1609 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1611 attributes: [ 'id' ],
1613 channelId: videoChannel.id
1617 return VideoModel.findAll(query)
1618 .then(videos => videos.map(v => v.id))
1621 // threshold corresponds to how many video the field should have to be returned
1622 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1623 const serverActor = await getServerActor()
1624 const followerActorId = serverActor.id
1626 const scopeOptions: AvailableForListIDsOptions = {
1627 serverAccountId: serverActor.Account.id,
1629 includeLocalVideos: true,
1630 attributesType: 'none' // Don't break aggregation
1633 const query: FindOptions = {
1634 attributes: [ field ],
1637 having: Sequelize.where(
1638 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1640 order: [ (this.sequelize as any).random() ]
1643 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1645 .then(rows => rows.map(r => r[ field ]))
1648 static buildTrendingQuery (trendingDays: number) {
1652 model: VideoViewModel,
1656 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1662 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1663 if (filter && (filter === 'local' || filter === 'all-local')) {
1672 private static async getAvailableForApi (
1673 query: FindOptions & { where?: null }, // Forbid where field in query
1674 options: AvailableForListIDsOptions,
1677 const idsScope: ScopeOptions = {
1679 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1683 // Remove trending sort on count, because it uses a group by
1684 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1685 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1686 const countScope: ScopeOptions = {
1688 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1692 const [ count, ids ] = await Promise.all([
1694 ? VideoModel.scope(countScope).count(countQuery)
1695 : Promise.resolve<number>(undefined),
1697 VideoModel.scope(idsScope)
1699 .then(rows => rows.map(r => r.id))
1702 if (ids.length === 0) return { data: [], total: count }
1704 const secondQuery: FindOptions = {
1707 attributes: query.attributes,
1708 order: [ // Keep original order
1710 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1715 const apiScope: (string | ScopeOptions)[] = []
1718 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1723 ScopeNames.FOR_API, {
1725 withFiles: options.withFiles,
1726 videoPlaylistId: options.videoPlaylistId
1731 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1739 static getCategoryLabel (id: number) {
1740 return VIDEO_CATEGORIES[ id ] || 'Misc'
1743 static getLicenceLabel (id: number) {
1744 return VIDEO_LICENCES[ id ] || 'Unknown'
1747 static getLanguageLabel (id: string) {
1748 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1751 static getPrivacyLabel (id: number) {
1752 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1755 static getStateLabel (id: number) {
1756 return VIDEO_STATES[ id ] || 'Unknown'
1760 return !!this.VideoBlacklist
1764 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1765 this.VideoChannel.Account.isBlocked()
1768 getOriginalFile () {
1769 if (Array.isArray(this.VideoFiles) === false) return undefined
1771 // The original file is the file that have the higher resolution
1772 return maxBy(this.VideoFiles, file => file.resolution)
1775 getFile (resolution: number) {
1776 if (Array.isArray(this.VideoFiles) === false) return undefined
1778 return this.VideoFiles.find(f => f.resolution === resolution)
1781 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1782 thumbnail.videoId = this.id
1784 const savedThumbnail = await thumbnail.save({ transaction })
1786 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1788 // Already have this thumbnail, skip
1789 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1791 this.Thumbnails.push(savedThumbnail)
1794 getVideoFilename (videoFile: MVideoFile) {
1795 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1798 generateThumbnailName () {
1799 return this.uuid + '.jpg'
1803 if (Array.isArray(this.Thumbnails) === false) return undefined
1805 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1808 generatePreviewName () {
1809 return this.uuid + '.jpg'
1813 if (Array.isArray(this.Thumbnails) === false) return undefined
1815 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1818 getTorrentFileName (videoFile: MVideoFile) {
1819 const extension = '.torrent'
1820 return this.uuid + '-' + videoFile.resolution + extension
1824 return this.remote === false
1827 getTorrentFilePath (videoFile: MVideoFile) {
1828 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1831 getVideoFilePath (videoFile: MVideoFile) {
1832 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1835 async createTorrentAndSetInfoHash (videoFile: MVideoFile) {
1837 // Keep the extname, it's used by the client to stream the file inside a web browser
1838 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1839 createdBy: 'PeerTube',
1841 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1842 [ WEBSERVER.URL + '/tracker/announce' ]
1844 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1847 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1849 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1850 logger.info('Creating torrent %s.', filePath)
1852 await writeFile(filePath, torrent)
1854 const parsedTorrent = parseTorrent(torrent)
1855 videoFile.infoHash = parsedTorrent.infoHash
1858 getWatchStaticPath () {
1859 return '/videos/watch/' + this.uuid
1862 getEmbedStaticPath () {
1863 return '/videos/embed/' + this.uuid
1866 getMiniatureStaticPath () {
1867 const thumbnail = this.getMiniature()
1868 if (!thumbnail) return null
1870 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1873 getPreviewStaticPath () {
1874 const preview = this.getPreview()
1875 if (!preview) return null
1877 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1878 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1881 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1882 return videoModelToFormattedJSON(this, options)
1885 toFormattedDetailsJSON (): VideoDetails {
1886 return videoModelToFormattedDetailsJSON(this)
1889 getFormattedVideoFilesJSON (): VideoFile[] {
1890 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1893 toActivityPubObject (): VideoTorrentObject {
1894 return videoModelToActivityPubObject(this)
1897 getTruncatedDescription () {
1898 if (!this.description) return null
1900 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1901 return peertubeTruncate(this.description, maxLength)
1904 getOriginalFileResolution () {
1905 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1907 return getVideoFileResolution(originalFilePath)
1910 getDescriptionAPIPath () {
1911 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1915 if (!this.VideoStreamingPlaylists) return undefined
1917 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1920 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1921 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1923 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1924 return remove(filePath)
1925 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1928 removeTorrent (videoFile: MVideoFile) {
1929 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1930 return remove(torrentPath)
1931 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1934 removeStreamingPlaylist (isRedundancy = false) {
1935 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1937 const filePath = join(baseDir, this.uuid)
1938 return remove(filePath)
1939 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1943 if (this.isOwned()) return false
1945 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1949 this.changed('updatedAt', true)
1958 if (this.isOwned()) {
1959 baseUrlHttp = WEBSERVER.URL
1960 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1962 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1963 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1966 return { baseUrlHttp, baseUrlWs }
1969 generateMagnetUri (videoFile: MVideoFileRedundanciesOpt, baseUrlHttp: string, baseUrlWs: string) {
1970 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1971 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1972 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1974 const redundancies = videoFile.RedundancyVideos
1975 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1977 const magnetHash = {
1981 infoHash: videoFile.infoHash,
1985 return magnetUtil.encode(magnetHash)
1988 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1989 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1992 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1993 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1996 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1997 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2000 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2001 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
2004 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2005 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
2008 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2009 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2012 getBandwidthBits (videoFile: MVideoFile) {
2013 return Math.ceil((videoFile.size * 8) / this.duration)