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,
133 MVideoFormattableDetails,
141 } from '../../typings/models'
142 import { MVideoFile, MVideoFileRedundanciesOpt } from '../../typings/models/video/video-file'
143 import { MThumbnail } from '../../typings/models/video/thumbnail'
145 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
146 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
147 buildTrigramSearchIndex('video_name_trigram', 'name'),
149 { fields: [ 'createdAt' ] },
150 { fields: [ 'publishedAt' ] },
151 { fields: [ 'duration' ] },
152 { fields: [ 'views' ] },
153 { fields: [ 'channelId' ] },
155 fields: [ 'originallyPublishedAt' ],
157 originallyPublishedAt: {
163 fields: [ 'category' ], // We don't care videos with an unknown category
171 fields: [ 'licence' ], // We don't care videos with an unknown licence
179 fields: [ 'language' ], // We don't care videos with an unknown language
187 fields: [ 'nsfw' ], // Most of the videos are not NSFW
193 fields: [ 'remote' ], // Only index local videos
208 export enum ScopeNames {
209 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
211 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
212 WITH_TAGS = 'WITH_TAGS',
213 WITH_FILES = 'WITH_FILES',
214 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
215 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
216 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
217 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
218 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
219 WITH_USER_ID = 'WITH_USER_ID',
220 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
223 export type ForAPIOptions = {
226 videoPlaylistId?: number
230 withAccountBlockerIds?: number[]
233 export type AvailableForListIDsOptions = {
234 serverAccountId: number
235 followerActorId: number
236 includeLocalVideos: boolean
238 attributesType?: 'none' | 'id' | 'all'
241 categoryOneOf?: number[]
243 licenceOneOf?: number[]
244 languageOneOf?: string[]
251 videoChannelId?: number
253 videoPlaylistId?: number
255 trendingDays?: number
256 user?: MUserAccountId
257 historyOfUser?: MUserId
259 baseWhere?: WhereOptions[]
263 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
264 const query: FindOptions = {
267 model: VideoChannelModel.scope({
269 VideoChannelScopeNames.SUMMARY, {
271 withAccountBlockerIds: options.withAccountBlockerIds
278 attributes: [ 'type', 'filename' ],
279 model: ThumbnailModel,
288 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
293 if (options.withFiles === true) {
295 model: VideoFileModel.unscoped(),
300 if (options.videoPlaylistId) {
302 model: VideoPlaylistElementModel.unscoped(),
305 videoPlaylistId: options.videoPlaylistId
312 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
313 const whereAnd = options.baseWhere ? options.baseWhere : []
315 const query: FindOptions = {
320 const attributesType = options.attributesType || 'id'
322 if (attributesType === 'id') query.attributes = [ 'id' ]
323 else if (attributesType === 'none') query.attributes = [ ]
327 [ Op.notIn ]: Sequelize.literal(
328 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
333 if (options.serverAccountId) {
336 [ Op.notIn ]: Sequelize.literal(
338 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
339 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
347 // Only list public/published videos
348 if (!options.filter || options.filter !== 'all-local') {
349 const privacyWhere = {
350 // Always list public videos
351 privacy: VideoPrivacy.PUBLIC,
352 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
355 state: VideoState.PUBLISHED
359 state: VideoState.TO_TRANSCODE,
360 waitTranscoding: false
366 whereAnd.push(privacyWhere)
369 if (options.videoPlaylistId) {
372 model: VideoPlaylistElementModel.unscoped(),
375 videoPlaylistId: options.videoPlaylistId
379 query.subQuery = false
382 if (options.filter || options.accountId || options.videoChannelId) {
383 const videoChannelInclude: IncludeOptions = {
385 model: VideoChannelModel.unscoped(),
389 if (options.videoChannelId) {
390 videoChannelInclude.where = {
391 id: options.videoChannelId
395 if (options.filter || options.accountId) {
396 const accountInclude: IncludeOptions = {
398 model: AccountModel.unscoped(),
402 if (options.filter) {
403 accountInclude.include = [
406 model: ActorModel.unscoped(),
408 where: VideoModel.buildActorWhereWithFilter(options.filter)
413 if (options.accountId) {
414 accountInclude.where = { id: options.accountId }
417 videoChannelInclude.include = [ accountInclude ]
420 query.include.push(videoChannelInclude)
423 if (options.followerActorId) {
424 let localVideosReq = ''
425 if (options.includeLocalVideos === true) {
426 localVideosReq = ' UNION ALL ' +
427 'SELECT "video"."id" AS "id" FROM "video" ' +
428 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
429 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
430 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
431 'WHERE "actor"."serverId" IS NULL'
434 // Force actorId to be a number to avoid SQL injections
435 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
438 [ Op.in ]: Sequelize.literal(
440 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
441 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
442 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
444 'SELECT "video"."id" AS "id" FROM "video" ' +
445 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
446 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
447 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
448 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
449 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
457 if (options.withFiles === true) {
460 [ Op.in ]: Sequelize.literal(
461 '(SELECT "videoId" FROM "videoFile")'
467 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
468 if (options.tagsAllOf || options.tagsOneOf) {
469 if (options.tagsOneOf) {
472 [ Op.in ]: Sequelize.literal(
474 'SELECT "videoId" FROM "videoTag" ' +
475 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
476 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
483 if (options.tagsAllOf) {
486 [ Op.in ]: Sequelize.literal(
488 'SELECT "videoId" FROM "videoTag" ' +
489 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
490 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
491 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
499 if (options.nsfw === true || options.nsfw === false) {
500 whereAnd.push({ nsfw: options.nsfw })
503 if (options.categoryOneOf) {
506 [ Op.or ]: options.categoryOneOf
511 if (options.licenceOneOf) {
514 [ Op.or ]: options.licenceOneOf
519 if (options.languageOneOf) {
520 let videoLanguages = options.languageOneOf
521 if (options.languageOneOf.find(l => l === '_unknown')) {
522 videoLanguages = videoLanguages.concat([ null ])
529 [ Op.or ]: videoLanguages
534 [ Op.in ]: Sequelize.literal(
536 'SELECT "videoId" FROM "videoCaption" ' +
537 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
546 if (options.trendingDays) {
547 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
549 query.subQuery = false
552 if (options.historyOfUser) {
554 model: UserVideoHistoryModel,
557 userId: options.historyOfUser.id
561 // Even if the relation is n:m, we know that a user only have 0..1 video history
562 // So we won't have multiple rows for the same video
563 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
564 query.subQuery = false
573 [ScopeNames.WITH_BLOCKLIST]: {
576 [ ScopeNames.WITH_THUMBNAILS ]: {
579 model: ThumbnailModel,
584 [ ScopeNames.WITH_USER_ID ]: {
587 attributes: [ 'accountId' ],
588 model: VideoChannelModel.unscoped(),
592 attributes: [ 'userId' ],
593 model: AccountModel.unscoped(),
600 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
603 model: VideoChannelModel.unscoped(),
608 exclude: [ 'privateKey', 'publicKey' ]
610 model: ActorModel.unscoped(),
614 attributes: [ 'host' ],
615 model: ServerModel.unscoped(),
619 model: AvatarModel.unscoped(),
625 model: AccountModel.unscoped(),
629 model: ActorModel.unscoped(),
631 exclude: [ 'privateKey', 'publicKey' ]
636 attributes: [ 'host' ],
637 model: ServerModel.unscoped(),
641 model: AvatarModel.unscoped(),
652 [ ScopeNames.WITH_TAGS ]: {
653 include: [ TagModel ]
655 [ ScopeNames.WITH_BLACKLISTED ]: {
658 attributes: [ 'id', 'reason', 'unfederated' ],
659 model: VideoBlacklistModel,
664 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
665 let subInclude: any[] = []
667 if (withRedundancies === true) {
670 attributes: [ 'fileUrl' ],
671 model: VideoRedundancyModel.unscoped(),
680 model: VideoFileModel.unscoped(),
681 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
688 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
689 let subInclude: any[] = []
691 if (withRedundancies === true) {
694 attributes: [ 'fileUrl' ],
695 model: VideoRedundancyModel.unscoped(),
704 model: VideoStreamingPlaylistModel.unscoped(),
705 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
712 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
715 model: ScheduleVideoUpdateModel.unscoped(),
720 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
724 attributes: [ 'currentTime' ],
725 model: UserVideoHistoryModel.unscoped(),
739 export class VideoModel extends Model<VideoModel> {
742 @Default(DataType.UUIDV4)
744 @Column(DataType.UUID)
748 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
754 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
760 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
766 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
767 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
771 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
776 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
782 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
783 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
788 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
789 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
793 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
823 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
824 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
829 commentsEnabled: boolean
833 downloadEnabled: boolean
837 waitTranscoding: boolean
841 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
852 @Default(DataType.NOW)
859 originallyPublishedAt: Date
861 @ForeignKey(() => VideoChannelModel)
865 @BelongsTo(() => VideoChannelModel, {
871 VideoChannel: VideoChannelModel
873 @BelongsToMany(() => TagModel, {
874 foreignKey: 'videoId',
875 through: () => VideoTagModel,
880 @HasMany(() => ThumbnailModel, {
888 Thumbnails: ThumbnailModel[]
890 @HasMany(() => VideoPlaylistElementModel, {
897 VideoPlaylistElements: VideoPlaylistElementModel[]
899 @HasMany(() => VideoAbuseModel, {
906 VideoAbuses: VideoAbuseModel[]
908 @HasMany(() => VideoFileModel, {
916 VideoFiles: VideoFileModel[]
918 @HasMany(() => VideoStreamingPlaylistModel, {
926 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
928 @HasMany(() => VideoShareModel, {
935 VideoShares: VideoShareModel[]
937 @HasMany(() => AccountVideoRateModel, {
944 AccountVideoRates: AccountVideoRateModel[]
946 @HasMany(() => VideoCommentModel, {
954 VideoComments: VideoCommentModel[]
956 @HasMany(() => VideoViewModel, {
963 VideoViews: VideoViewModel[]
965 @HasMany(() => UserVideoHistoryModel, {
972 UserVideoHistories: UserVideoHistoryModel[]
974 @HasOne(() => ScheduleVideoUpdateModel, {
981 ScheduleVideoUpdate: ScheduleVideoUpdateModel
983 @HasOne(() => VideoBlacklistModel, {
990 VideoBlacklist: VideoBlacklistModel
992 @HasOne(() => VideoImportModel, {
999 VideoImport: VideoImportModel
1001 @HasMany(() => VideoCaptionModel, {
1006 onDelete: 'cascade',
1008 [ 'separate' as any ]: true
1010 VideoCaptions: VideoCaptionModel[]
1013 static async sendDelete (instance: MVideoAccountLight, options) {
1014 if (instance.isOwned()) {
1015 if (!instance.VideoChannel) {
1016 instance.VideoChannel = await instance.$get('VideoChannel', {
1021 transaction: options.transaction
1022 }) as MChannelAccountDefault
1025 return sendDeleteVideo(instance, options.transaction)
1032 static async removeFiles (instance: VideoModel) {
1033 const tasks: Promise<any>[] = []
1035 logger.info('Removing files of video %s.', instance.url)
1037 if (instance.isOwned()) {
1038 if (!Array.isArray(instance.VideoFiles)) {
1039 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1042 // Remove physical files and torrents
1043 instance.VideoFiles.forEach(file => {
1044 tasks.push(instance.removeFile(file))
1045 tasks.push(instance.removeTorrent(file))
1048 // Remove playlists file
1049 tasks.push(instance.removeStreamingPlaylist())
1052 // Do not wait video deletion because we could be in a transaction
1055 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1061 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1068 return VideoModel.scope([
1069 ScopeNames.WITH_FILES,
1070 ScopeNames.WITH_STREAMING_PLAYLISTS,
1071 ScopeNames.WITH_THUMBNAILS
1075 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1076 function getRawQuery (select: string) {
1077 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1078 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1079 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1080 'WHERE "Account"."actorId" = ' + actorId
1081 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1082 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1083 'WHERE "VideoShare"."actorId" = ' + actorId
1085 return `(${queryVideo}) UNION (${queryVideoShare})`
1088 const rawQuery = getRawQuery('"Video"."id"')
1089 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1095 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1098 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1101 { privacy: VideoPrivacy.PUBLIC },
1102 { privacy: VideoPrivacy.UNLISTED }
1107 attributes: [ 'language' ],
1108 model: VideoCaptionModel.unscoped(),
1112 attributes: [ 'id', 'url' ],
1113 model: VideoShareModel.unscoped(),
1115 // We only want videos shared by this actor
1130 attributes: [ 'id', 'url' ],
1131 model: ActorModel.unscoped()
1136 model: VideoChannelModel.unscoped(),
1140 attributes: [ 'name' ],
1141 model: AccountModel.unscoped(),
1145 attributes: [ 'id', 'url', 'followersUrl' ],
1146 model: ActorModel.unscoped(),
1152 attributes: [ 'id', 'url', 'followersUrl' ],
1153 model: ActorModel.unscoped(),
1163 return Bluebird.all([
1164 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1165 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1166 ]).then(([ rows, totals ]) => {
1167 // totals: totalVideos + totalVideoShares
1169 let totalVideoShares = 0
1170 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1171 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1173 const total = totalVideos + totalVideoShares
1181 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1182 function buildBaseQuery (): FindOptions {
1186 order: getVideoSort(sort),
1189 model: VideoChannelModel,
1193 model: AccountModel,
1205 const countQuery = buildBaseQuery()
1206 const findQuery = buildBaseQuery()
1208 const findScopes = [
1209 ScopeNames.WITH_SCHEDULED_UPDATE,
1210 ScopeNames.WITH_BLACKLISTED,
1211 ScopeNames.WITH_THUMBNAILS
1214 return Promise.all([
1215 VideoModel.count(countQuery),
1216 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1217 ]).then(([ count, rows ]) => {
1225 static async listForApi (options: {
1230 includeLocalVideos: boolean,
1232 categoryOneOf?: number[],
1233 licenceOneOf?: number[],
1234 languageOneOf?: string[],
1235 tagsOneOf?: string[],
1236 tagsAllOf?: string[],
1237 filter?: VideoFilter,
1239 videoChannelId?: number,
1240 followerActorId?: number
1241 videoPlaylistId?: number,
1242 trendingDays?: number,
1243 user?: MUserAccountId,
1244 historyOfUser?: MUserId
1245 }, countVideos = true) {
1246 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1247 throw new Error('Try to filter all-local but no user has not the see all videos right')
1250 const query: FindOptions & { where?: null } = {
1251 offset: options.start,
1252 limit: options.count,
1253 order: getVideoSort(options.sort)
1256 let trendingDays: number
1257 if (options.sort.endsWith('trending')) {
1258 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1260 query.group = 'VideoModel.id'
1263 const serverActor = await getServerActor()
1265 // followerActorId === null has a meaning, so just check undefined
1266 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1268 const queryOptions = {
1270 serverAccountId: serverActor.Account.id,
1272 categoryOneOf: options.categoryOneOf,
1273 licenceOneOf: options.licenceOneOf,
1274 languageOneOf: options.languageOneOf,
1275 tagsOneOf: options.tagsOneOf,
1276 tagsAllOf: options.tagsAllOf,
1277 filter: options.filter,
1278 withFiles: options.withFiles,
1279 accountId: options.accountId,
1280 videoChannelId: options.videoChannelId,
1281 videoPlaylistId: options.videoPlaylistId,
1282 includeLocalVideos: options.includeLocalVideos,
1284 historyOfUser: options.historyOfUser,
1288 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1291 static async searchAndPopulateAccountAndServer (options: {
1292 includeLocalVideos: boolean
1297 startDate?: string // ISO 8601
1298 endDate?: string // ISO 8601
1299 originallyPublishedStartDate?: string
1300 originallyPublishedEndDate?: string
1302 categoryOneOf?: number[]
1303 licenceOneOf?: number[]
1304 languageOneOf?: string[]
1305 tagsOneOf?: string[]
1306 tagsAllOf?: string[]
1307 durationMin?: number // seconds
1308 durationMax?: number // seconds
1309 user?: MUserAccountId,
1310 filter?: VideoFilter
1314 if (options.startDate || options.endDate) {
1315 const publishedAtRange = {}
1317 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1318 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1320 whereAnd.push({ publishedAt: publishedAtRange })
1323 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1324 const originallyPublishedAtRange = {}
1326 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1327 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1329 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1332 if (options.durationMin || options.durationMax) {
1333 const durationRange = {}
1335 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1336 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1338 whereAnd.push({ duration: durationRange })
1341 const attributesInclude = []
1342 const escapedSearch = VideoModel.sequelize.escape(options.search)
1343 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1344 if (options.search) {
1348 [ Op.in ]: Sequelize.literal(
1350 'SELECT "video"."id" FROM "video" ' +
1352 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1353 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1355 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1356 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1357 'WHERE "tag"."name" = ' + escapedSearch +
1364 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1367 // Cannot search on similarity if we don't have a search
1368 if (!options.search) {
1369 attributesInclude.push(
1370 Sequelize.literal('0 as similarity')
1376 include: attributesInclude
1378 offset: options.start,
1379 limit: options.count,
1380 order: getVideoSort(options.sort)
1383 const serverActor = await getServerActor()
1384 const queryOptions = {
1385 followerActorId: serverActor.id,
1386 serverAccountId: serverActor.Account.id,
1387 includeLocalVideos: options.includeLocalVideos,
1389 categoryOneOf: options.categoryOneOf,
1390 licenceOneOf: options.licenceOneOf,
1391 languageOneOf: options.languageOneOf,
1392 tagsOneOf: options.tagsOneOf,
1393 tagsAllOf: options.tagsAllOf,
1395 filter: options.filter,
1399 return VideoModel.getAvailableForApi(query, queryOptions)
1402 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1403 const where = buildWhereIdOrUUID(id)
1409 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1412 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1413 const where = buildWhereIdOrUUID(id)
1419 return VideoModel.scope([
1420 ScopeNames.WITH_BLACKLISTED,
1421 ScopeNames.WITH_USER_ID,
1422 ScopeNames.WITH_THUMBNAILS
1426 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1427 const where = buildWhereIdOrUUID(id)
1430 attributes: [ 'id' ],
1435 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1438 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1439 const where = buildWhereIdOrUUID(id)
1447 return VideoModel.scope([
1448 ScopeNames.WITH_FILES,
1449 ScopeNames.WITH_STREAMING_PLAYLISTS,
1450 ScopeNames.WITH_THUMBNAILS
1454 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1461 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1464 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1465 const query: FindOptions = {
1472 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1475 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1476 const query: FindOptions = {
1483 return VideoModel.scope([
1484 ScopeNames.WITH_ACCOUNT_DETAILS,
1485 ScopeNames.WITH_FILES,
1486 ScopeNames.WITH_STREAMING_PLAYLISTS,
1487 ScopeNames.WITH_THUMBNAILS,
1488 ScopeNames.WITH_BLACKLISTED
1492 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1493 const where = buildWhereIdOrUUID(id)
1496 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1501 const scopes: (string | ScopeOptions)[] = [
1502 ScopeNames.WITH_TAGS,
1503 ScopeNames.WITH_BLACKLISTED,
1504 ScopeNames.WITH_ACCOUNT_DETAILS,
1505 ScopeNames.WITH_SCHEDULED_UPDATE,
1506 ScopeNames.WITH_FILES,
1507 ScopeNames.WITH_STREAMING_PLAYLISTS,
1508 ScopeNames.WITH_THUMBNAILS
1512 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1520 static loadForGetAPI (parameters: {
1521 id: number | string,
1524 }): Bluebird<MVideoDetails> {
1525 const { id, t, userId } = parameters
1526 const where = buildWhereIdOrUUID(id)
1529 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1534 const scopes: (string | ScopeOptions)[] = [
1535 ScopeNames.WITH_TAGS,
1536 ScopeNames.WITH_BLACKLISTED,
1537 ScopeNames.WITH_ACCOUNT_DETAILS,
1538 ScopeNames.WITH_SCHEDULED_UPDATE,
1539 ScopeNames.WITH_THUMBNAILS,
1540 { method: [ ScopeNames.WITH_FILES, true ] },
1541 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1545 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1553 static async getStats () {
1554 const totalLocalVideos = await VideoModel.count({
1559 const totalVideos = await VideoModel.count()
1561 let totalLocalVideoViews = await VideoModel.sum('views', {
1566 // Sequelize could return null...
1567 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1571 totalLocalVideoViews,
1576 static incrementViews (id: number, views: number) {
1577 return VideoModel.increment('views', {
1585 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1586 // Instances only share videos
1587 const query = 'SELECT 1 FROM "videoShare" ' +
1588 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1589 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1593 type: QueryTypes.SELECT,
1594 bind: { followerActorId, videoId },
1598 return VideoModel.sequelize.query(query, options)
1599 .then(results => results.length === 1)
1602 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1605 channelId: videoChannel.id
1610 return VideoModel.update({ support: videoChannel.support }, options)
1613 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1615 attributes: [ 'id' ],
1617 channelId: videoChannel.id
1621 return VideoModel.findAll(query)
1622 .then(videos => videos.map(v => v.id))
1625 // threshold corresponds to how many video the field should have to be returned
1626 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1627 const serverActor = await getServerActor()
1628 const followerActorId = serverActor.id
1630 const scopeOptions: AvailableForListIDsOptions = {
1631 serverAccountId: serverActor.Account.id,
1633 includeLocalVideos: true,
1634 attributesType: 'none' // Don't break aggregation
1637 const query: FindOptions = {
1638 attributes: [ field ],
1641 having: Sequelize.where(
1642 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1644 order: [ (this.sequelize as any).random() ]
1647 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1649 .then(rows => rows.map(r => r[ field ]))
1652 static buildTrendingQuery (trendingDays: number) {
1656 model: VideoViewModel,
1660 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1666 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1667 if (filter && (filter === 'local' || filter === 'all-local')) {
1676 private static async getAvailableForApi (
1677 query: FindOptions & { where?: null }, // Forbid where field in query
1678 options: AvailableForListIDsOptions,
1681 const idsScope: ScopeOptions = {
1683 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1687 // Remove trending sort on count, because it uses a group by
1688 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1689 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1690 const countScope: ScopeOptions = {
1692 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1696 const [ count, ids ] = await Promise.all([
1698 ? VideoModel.scope(countScope).count(countQuery)
1699 : Promise.resolve<number>(undefined),
1701 VideoModel.scope(idsScope)
1703 .then(rows => rows.map(r => r.id))
1706 if (ids.length === 0) return { data: [], total: count }
1708 const secondQuery: FindOptions = {
1711 attributes: query.attributes,
1712 order: [ // Keep original order
1714 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1719 const apiScope: (string | ScopeOptions)[] = []
1722 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1727 ScopeNames.FOR_API, {
1729 withFiles: options.withFiles,
1730 videoPlaylistId: options.videoPlaylistId
1735 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1743 static getCategoryLabel (id: number) {
1744 return VIDEO_CATEGORIES[ id ] || 'Misc'
1747 static getLicenceLabel (id: number) {
1748 return VIDEO_LICENCES[ id ] || 'Unknown'
1751 static getLanguageLabel (id: string) {
1752 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1755 static getPrivacyLabel (id: number) {
1756 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1759 static getStateLabel (id: number) {
1760 return VIDEO_STATES[ id ] || 'Unknown'
1764 return !!this.VideoBlacklist
1768 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1769 this.VideoChannel.Account.isBlocked()
1772 getOriginalFile <T extends MVideoWithFile> (this: T) {
1773 if (Array.isArray(this.VideoFiles) === false) return undefined
1775 // The original file is the file that have the higher resolution
1776 return maxBy(this.VideoFiles, file => file.resolution)
1779 getFile <T extends MVideoWithFile> (this: T, resolution: number) {
1780 if (Array.isArray(this.VideoFiles) === false) return undefined
1782 return this.VideoFiles.find(f => f.resolution === resolution)
1785 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1786 thumbnail.videoId = this.id
1788 const savedThumbnail = await thumbnail.save({ transaction })
1790 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1792 // Already have this thumbnail, skip
1793 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1795 this.Thumbnails.push(savedThumbnail)
1798 getVideoFilename (videoFile: MVideoFile) {
1799 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1802 generateThumbnailName () {
1803 return this.uuid + '.jpg'
1807 if (Array.isArray(this.Thumbnails) === false) return undefined
1809 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1812 generatePreviewName () {
1813 return this.uuid + '.jpg'
1817 if (Array.isArray(this.Thumbnails) === false) return undefined
1819 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1822 getTorrentFileName (videoFile: MVideoFile) {
1823 const extension = '.torrent'
1824 return this.uuid + '-' + videoFile.resolution + extension
1828 return this.remote === false
1831 getTorrentFilePath (videoFile: MVideoFile) {
1832 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1835 getVideoFilePath (videoFile: MVideoFile) {
1836 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1839 async createTorrentAndSetInfoHash (videoFile: MVideoFile) {
1841 // Keep the extname, it's used by the client to stream the file inside a web browser
1842 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1843 createdBy: 'PeerTube',
1845 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1846 [ WEBSERVER.URL + '/tracker/announce' ]
1848 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1851 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1853 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1854 logger.info('Creating torrent %s.', filePath)
1856 await writeFile(filePath, torrent)
1858 const parsedTorrent = parseTorrent(torrent)
1859 videoFile.infoHash = parsedTorrent.infoHash
1862 getWatchStaticPath () {
1863 return '/videos/watch/' + this.uuid
1866 getEmbedStaticPath () {
1867 return '/videos/embed/' + this.uuid
1870 getMiniatureStaticPath () {
1871 const thumbnail = this.getMiniature()
1872 if (!thumbnail) return null
1874 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1877 getPreviewStaticPath () {
1878 const preview = this.getPreview()
1879 if (!preview) return null
1881 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1882 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1885 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1886 return videoModelToFormattedJSON(this, options)
1889 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1890 return videoModelToFormattedDetailsJSON(this)
1893 getFormattedVideoFilesJSON (): VideoFile[] {
1894 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1897 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1898 return videoModelToActivityPubObject(this)
1901 getTruncatedDescription () {
1902 if (!this.description) return null
1904 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1905 return peertubeTruncate(this.description, maxLength)
1908 getOriginalFileResolution () {
1909 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1911 return getVideoFileResolution(originalFilePath)
1914 getDescriptionAPIPath () {
1915 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1919 if (!this.VideoStreamingPlaylists) return undefined
1921 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1924 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1925 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1927 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1928 return remove(filePath)
1929 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1932 removeTorrent (videoFile: MVideoFile) {
1933 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1934 return remove(torrentPath)
1935 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1938 removeStreamingPlaylist (isRedundancy = false) {
1939 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1941 const filePath = join(baseDir, this.uuid)
1942 return remove(filePath)
1943 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1947 if (this.isOwned()) return false
1949 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1953 this.changed('updatedAt', true)
1962 if (this.isOwned()) {
1963 baseUrlHttp = WEBSERVER.URL
1964 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1966 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1967 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1970 return { baseUrlHttp, baseUrlWs }
1973 generateMagnetUri (videoFile: MVideoFileRedundanciesOpt, baseUrlHttp: string, baseUrlWs: string) {
1974 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1975 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1976 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1978 const redundancies = videoFile.RedundancyVideos
1979 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1981 const magnetHash = {
1985 infoHash: videoFile.infoHash,
1989 return magnetUtil.encode(magnetHash)
1992 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1993 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1996 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1997 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2000 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2001 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2004 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2005 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
2008 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2009 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
2012 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2013 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2016 getBandwidthBits (videoFile: MVideoFile) {
2017 return Math.ceil((videoFile.size * 8) / this.duration)