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,
135 MVideoWithAllFiles, MVideoWithFile,
138 } from '../../typings/models'
139 import { MVideoFile, MVideoFileRedundanciesOpt } from '../../typings/models/video/video-file'
140 import { MThumbnail } from '../../typings/models/video/thumbnail'
142 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
143 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
144 buildTrigramSearchIndex('video_name_trigram', 'name'),
146 { fields: [ 'createdAt' ] },
147 { fields: [ 'publishedAt' ] },
148 { fields: [ 'duration' ] },
149 { fields: [ 'views' ] },
150 { fields: [ 'channelId' ] },
152 fields: [ 'originallyPublishedAt' ],
154 originallyPublishedAt: {
160 fields: [ 'category' ], // We don't care videos with an unknown category
168 fields: [ 'licence' ], // We don't care videos with an unknown licence
176 fields: [ 'language' ], // We don't care videos with an unknown language
184 fields: [ 'nsfw' ], // Most of the videos are not NSFW
190 fields: [ 'remote' ], // Only index local videos
205 export enum ScopeNames {
206 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
208 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
209 WITH_TAGS = 'WITH_TAGS',
210 WITH_FILES = 'WITH_FILES',
211 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
212 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
213 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
214 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
215 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
216 WITH_USER_ID = 'WITH_USER_ID',
217 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
220 export type ForAPIOptions = {
223 videoPlaylistId?: number
227 withAccountBlockerIds?: number[]
230 export type AvailableForListIDsOptions = {
231 serverAccountId: number
232 followerActorId: number
233 includeLocalVideos: boolean
235 attributesType?: 'none' | 'id' | 'all'
238 categoryOneOf?: number[]
240 licenceOneOf?: number[]
241 languageOneOf?: string[]
248 videoChannelId?: number
250 videoPlaylistId?: number
252 trendingDays?: number
253 user?: MUserAccountId
254 historyOfUser?: MUserId
256 baseWhere?: WhereOptions[]
260 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
261 const query: FindOptions = {
264 model: VideoChannelModel.scope({
266 VideoChannelScopeNames.SUMMARY, {
268 withAccountBlockerIds: options.withAccountBlockerIds
275 attributes: [ 'type', 'filename' ],
276 model: ThumbnailModel,
285 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
290 if (options.withFiles === true) {
292 model: VideoFileModel.unscoped(),
297 if (options.videoPlaylistId) {
299 model: VideoPlaylistElementModel.unscoped(),
302 videoPlaylistId: options.videoPlaylistId
309 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
310 const whereAnd = options.baseWhere ? options.baseWhere : []
312 const query: FindOptions = {
317 const attributesType = options.attributesType || 'id'
319 if (attributesType === 'id') query.attributes = [ 'id' ]
320 else if (attributesType === 'none') query.attributes = [ ]
324 [ Op.notIn ]: Sequelize.literal(
325 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
330 if (options.serverAccountId) {
333 [ Op.notIn ]: Sequelize.literal(
335 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
336 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
344 // Only list public/published videos
345 if (!options.filter || options.filter !== 'all-local') {
346 const privacyWhere = {
347 // Always list public videos
348 privacy: VideoPrivacy.PUBLIC,
349 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
352 state: VideoState.PUBLISHED
356 state: VideoState.TO_TRANSCODE,
357 waitTranscoding: false
363 whereAnd.push(privacyWhere)
366 if (options.videoPlaylistId) {
369 model: VideoPlaylistElementModel.unscoped(),
372 videoPlaylistId: options.videoPlaylistId
376 query.subQuery = false
379 if (options.filter || options.accountId || options.videoChannelId) {
380 const videoChannelInclude: IncludeOptions = {
382 model: VideoChannelModel.unscoped(),
386 if (options.videoChannelId) {
387 videoChannelInclude.where = {
388 id: options.videoChannelId
392 if (options.filter || options.accountId) {
393 const accountInclude: IncludeOptions = {
395 model: AccountModel.unscoped(),
399 if (options.filter) {
400 accountInclude.include = [
403 model: ActorModel.unscoped(),
405 where: VideoModel.buildActorWhereWithFilter(options.filter)
410 if (options.accountId) {
411 accountInclude.where = { id: options.accountId }
414 videoChannelInclude.include = [ accountInclude ]
417 query.include.push(videoChannelInclude)
420 if (options.followerActorId) {
421 let localVideosReq = ''
422 if (options.includeLocalVideos === true) {
423 localVideosReq = ' UNION ALL ' +
424 'SELECT "video"."id" AS "id" FROM "video" ' +
425 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
426 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
427 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
428 'WHERE "actor"."serverId" IS NULL'
431 // Force actorId to be a number to avoid SQL injections
432 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
435 [ Op.in ]: Sequelize.literal(
437 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
438 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
439 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
441 'SELECT "video"."id" AS "id" FROM "video" ' +
442 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
443 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
444 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
445 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
446 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
454 if (options.withFiles === true) {
457 [ Op.in ]: Sequelize.literal(
458 '(SELECT "videoId" FROM "videoFile")'
464 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
465 if (options.tagsAllOf || options.tagsOneOf) {
466 if (options.tagsOneOf) {
469 [ Op.in ]: Sequelize.literal(
471 'SELECT "videoId" FROM "videoTag" ' +
472 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
473 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
480 if (options.tagsAllOf) {
483 [ Op.in ]: Sequelize.literal(
485 'SELECT "videoId" FROM "videoTag" ' +
486 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
487 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
488 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
496 if (options.nsfw === true || options.nsfw === false) {
497 whereAnd.push({ nsfw: options.nsfw })
500 if (options.categoryOneOf) {
503 [ Op.or ]: options.categoryOneOf
508 if (options.licenceOneOf) {
511 [ Op.or ]: options.licenceOneOf
516 if (options.languageOneOf) {
517 let videoLanguages = options.languageOneOf
518 if (options.languageOneOf.find(l => l === '_unknown')) {
519 videoLanguages = videoLanguages.concat([ null ])
526 [ Op.or ]: videoLanguages
531 [ Op.in ]: Sequelize.literal(
533 'SELECT "videoId" FROM "videoCaption" ' +
534 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
543 if (options.trendingDays) {
544 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
546 query.subQuery = false
549 if (options.historyOfUser) {
551 model: UserVideoHistoryModel,
554 userId: options.historyOfUser.id
558 // Even if the relation is n:m, we know that a user only have 0..1 video history
559 // So we won't have multiple rows for the same video
560 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
561 query.subQuery = false
570 [ScopeNames.WITH_BLOCKLIST]: {
573 [ ScopeNames.WITH_THUMBNAILS ]: {
576 model: ThumbnailModel,
581 [ ScopeNames.WITH_USER_ID ]: {
584 attributes: [ 'accountId' ],
585 model: VideoChannelModel.unscoped(),
589 attributes: [ 'userId' ],
590 model: AccountModel.unscoped(),
597 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
600 model: VideoChannelModel.unscoped(),
605 exclude: [ 'privateKey', 'publicKey' ]
607 model: ActorModel.unscoped(),
611 attributes: [ 'host' ],
612 model: ServerModel.unscoped(),
616 model: AvatarModel.unscoped(),
622 model: AccountModel.unscoped(),
626 model: ActorModel.unscoped(),
628 exclude: [ 'privateKey', 'publicKey' ]
633 attributes: [ 'host' ],
634 model: ServerModel.unscoped(),
638 model: AvatarModel.unscoped(),
649 [ ScopeNames.WITH_TAGS ]: {
650 include: [ TagModel ]
652 [ ScopeNames.WITH_BLACKLISTED ]: {
655 attributes: [ 'id', 'reason', 'unfederated' ],
656 model: VideoBlacklistModel,
661 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
662 let subInclude: any[] = []
664 if (withRedundancies === true) {
667 attributes: [ 'fileUrl' ],
668 model: VideoRedundancyModel.unscoped(),
677 model: VideoFileModel.unscoped(),
678 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
685 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
686 let subInclude: any[] = []
688 if (withRedundancies === true) {
691 attributes: [ 'fileUrl' ],
692 model: VideoRedundancyModel.unscoped(),
701 model: VideoStreamingPlaylistModel.unscoped(),
702 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
709 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
712 model: ScheduleVideoUpdateModel.unscoped(),
717 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
721 attributes: [ 'currentTime' ],
722 model: UserVideoHistoryModel.unscoped(),
736 export class VideoModel extends Model<VideoModel> {
739 @Default(DataType.UUIDV4)
741 @Column(DataType.UUID)
745 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
751 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
757 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
763 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
764 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
768 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
773 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
779 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
780 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
785 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
786 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
790 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
820 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
821 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
826 commentsEnabled: boolean
830 downloadEnabled: boolean
834 waitTranscoding: boolean
838 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
849 @Default(DataType.NOW)
856 originallyPublishedAt: Date
858 @ForeignKey(() => VideoChannelModel)
862 @BelongsTo(() => VideoChannelModel, {
868 VideoChannel: VideoChannelModel
870 @BelongsToMany(() => TagModel, {
871 foreignKey: 'videoId',
872 through: () => VideoTagModel,
877 @HasMany(() => ThumbnailModel, {
885 Thumbnails: ThumbnailModel[]
887 @HasMany(() => VideoPlaylistElementModel, {
894 VideoPlaylistElements: VideoPlaylistElementModel[]
896 @HasMany(() => VideoAbuseModel, {
903 VideoAbuses: VideoAbuseModel[]
905 @HasMany(() => VideoFileModel, {
913 VideoFiles: VideoFileModel[]
915 @HasMany(() => VideoStreamingPlaylistModel, {
923 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
925 @HasMany(() => VideoShareModel, {
932 VideoShares: VideoShareModel[]
934 @HasMany(() => AccountVideoRateModel, {
941 AccountVideoRates: AccountVideoRateModel[]
943 @HasMany(() => VideoCommentModel, {
951 VideoComments: VideoCommentModel[]
953 @HasMany(() => VideoViewModel, {
960 VideoViews: VideoViewModel[]
962 @HasMany(() => UserVideoHistoryModel, {
969 UserVideoHistories: UserVideoHistoryModel[]
971 @HasOne(() => ScheduleVideoUpdateModel, {
978 ScheduleVideoUpdate: ScheduleVideoUpdateModel
980 @HasOne(() => VideoBlacklistModel, {
987 VideoBlacklist: VideoBlacklistModel
989 @HasOne(() => VideoImportModel, {
996 VideoImport: VideoImportModel
998 @HasMany(() => VideoCaptionModel, {
1003 onDelete: 'cascade',
1005 [ 'separate' as any ]: true
1007 VideoCaptions: VideoCaptionModel[]
1010 static async sendDelete (instance: MVideoAccountLight, options) {
1011 if (instance.isOwned()) {
1012 if (!instance.VideoChannel) {
1013 instance.VideoChannel = await instance.$get('VideoChannel', {
1018 transaction: options.transaction
1019 }) as MChannelAccountDefault
1022 return sendDeleteVideo(instance, options.transaction)
1029 static async removeFiles (instance: VideoModel) {
1030 const tasks: Promise<any>[] = []
1032 logger.info('Removing files of video %s.', instance.url)
1034 if (instance.isOwned()) {
1035 if (!Array.isArray(instance.VideoFiles)) {
1036 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1039 // Remove physical files and torrents
1040 instance.VideoFiles.forEach(file => {
1041 tasks.push(instance.removeFile(file))
1042 tasks.push(instance.removeTorrent(file))
1045 // Remove playlists file
1046 tasks.push(instance.removeStreamingPlaylist())
1049 // Do not wait video deletion because we could be in a transaction
1052 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1058 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1065 return VideoModel.scope([
1066 ScopeNames.WITH_FILES,
1067 ScopeNames.WITH_STREAMING_PLAYLISTS,
1068 ScopeNames.WITH_THUMBNAILS
1072 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1073 function getRawQuery (select: string) {
1074 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1075 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1076 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1077 'WHERE "Account"."actorId" = ' + actorId
1078 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1079 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1080 'WHERE "VideoShare"."actorId" = ' + actorId
1082 return `(${queryVideo}) UNION (${queryVideoShare})`
1085 const rawQuery = getRawQuery('"Video"."id"')
1086 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1092 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1095 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1098 { privacy: VideoPrivacy.PUBLIC },
1099 { privacy: VideoPrivacy.UNLISTED }
1104 attributes: [ 'language' ],
1105 model: VideoCaptionModel.unscoped(),
1109 attributes: [ 'id', 'url' ],
1110 model: VideoShareModel.unscoped(),
1112 // We only want videos shared by this actor
1127 attributes: [ 'id', 'url' ],
1128 model: ActorModel.unscoped()
1133 model: VideoChannelModel.unscoped(),
1137 attributes: [ 'name' ],
1138 model: AccountModel.unscoped(),
1142 attributes: [ 'id', 'url', 'followersUrl' ],
1143 model: ActorModel.unscoped(),
1149 attributes: [ 'id', 'url', 'followersUrl' ],
1150 model: ActorModel.unscoped(),
1160 return Bluebird.all([
1161 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1162 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1163 ]).then(([ rows, totals ]) => {
1164 // totals: totalVideos + totalVideoShares
1166 let totalVideoShares = 0
1167 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1168 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1170 const total = totalVideos + totalVideoShares
1178 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1179 function buildBaseQuery (): FindOptions {
1183 order: getVideoSort(sort),
1186 model: VideoChannelModel,
1190 model: AccountModel,
1202 const countQuery = buildBaseQuery()
1203 const findQuery = buildBaseQuery()
1205 const findScopes = [
1206 ScopeNames.WITH_SCHEDULED_UPDATE,
1207 ScopeNames.WITH_BLACKLISTED,
1208 ScopeNames.WITH_THUMBNAILS
1211 return Promise.all([
1212 VideoModel.count(countQuery),
1213 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1214 ]).then(([ count, rows ]) => {
1222 static async listForApi (options: {
1227 includeLocalVideos: boolean,
1229 categoryOneOf?: number[],
1230 licenceOneOf?: number[],
1231 languageOneOf?: string[],
1232 tagsOneOf?: string[],
1233 tagsAllOf?: string[],
1234 filter?: VideoFilter,
1236 videoChannelId?: number,
1237 followerActorId?: number
1238 videoPlaylistId?: number,
1239 trendingDays?: number,
1240 user?: MUserAccountId,
1241 historyOfUser?: MUserId
1242 }, countVideos = true) {
1243 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1244 throw new Error('Try to filter all-local but no user has not the see all videos right')
1247 const query: FindOptions & { where?: null } = {
1248 offset: options.start,
1249 limit: options.count,
1250 order: getVideoSort(options.sort)
1253 let trendingDays: number
1254 if (options.sort.endsWith('trending')) {
1255 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1257 query.group = 'VideoModel.id'
1260 const serverActor = await getServerActor()
1262 // followerActorId === null has a meaning, so just check undefined
1263 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1265 const queryOptions = {
1267 serverAccountId: serverActor.Account.id,
1269 categoryOneOf: options.categoryOneOf,
1270 licenceOneOf: options.licenceOneOf,
1271 languageOneOf: options.languageOneOf,
1272 tagsOneOf: options.tagsOneOf,
1273 tagsAllOf: options.tagsAllOf,
1274 filter: options.filter,
1275 withFiles: options.withFiles,
1276 accountId: options.accountId,
1277 videoChannelId: options.videoChannelId,
1278 videoPlaylistId: options.videoPlaylistId,
1279 includeLocalVideos: options.includeLocalVideos,
1281 historyOfUser: options.historyOfUser,
1285 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1288 static async searchAndPopulateAccountAndServer (options: {
1289 includeLocalVideos: boolean
1294 startDate?: string // ISO 8601
1295 endDate?: string // ISO 8601
1296 originallyPublishedStartDate?: string
1297 originallyPublishedEndDate?: string
1299 categoryOneOf?: number[]
1300 licenceOneOf?: number[]
1301 languageOneOf?: string[]
1302 tagsOneOf?: string[]
1303 tagsAllOf?: string[]
1304 durationMin?: number // seconds
1305 durationMax?: number // seconds
1306 user?: MUserAccountId,
1307 filter?: VideoFilter
1311 if (options.startDate || options.endDate) {
1312 const publishedAtRange = {}
1314 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1315 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1317 whereAnd.push({ publishedAt: publishedAtRange })
1320 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1321 const originallyPublishedAtRange = {}
1323 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1324 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1326 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1329 if (options.durationMin || options.durationMax) {
1330 const durationRange = {}
1332 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1333 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1335 whereAnd.push({ duration: durationRange })
1338 const attributesInclude = []
1339 const escapedSearch = VideoModel.sequelize.escape(options.search)
1340 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1341 if (options.search) {
1345 [ Op.in ]: Sequelize.literal(
1347 'SELECT "video"."id" FROM "video" ' +
1349 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1350 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1352 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1353 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1354 'WHERE "tag"."name" = ' + escapedSearch +
1361 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1364 // Cannot search on similarity if we don't have a search
1365 if (!options.search) {
1366 attributesInclude.push(
1367 Sequelize.literal('0 as similarity')
1373 include: attributesInclude
1375 offset: options.start,
1376 limit: options.count,
1377 order: getVideoSort(options.sort)
1380 const serverActor = await getServerActor()
1381 const queryOptions = {
1382 followerActorId: serverActor.id,
1383 serverAccountId: serverActor.Account.id,
1384 includeLocalVideos: options.includeLocalVideos,
1386 categoryOneOf: options.categoryOneOf,
1387 licenceOneOf: options.licenceOneOf,
1388 languageOneOf: options.languageOneOf,
1389 tagsOneOf: options.tagsOneOf,
1390 tagsAllOf: options.tagsAllOf,
1392 filter: options.filter,
1396 return VideoModel.getAvailableForApi(query, queryOptions)
1399 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1400 const where = buildWhereIdOrUUID(id)
1406 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1409 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1410 const where = buildWhereIdOrUUID(id)
1416 return VideoModel.scope([
1417 ScopeNames.WITH_BLACKLISTED,
1418 ScopeNames.WITH_USER_ID,
1419 ScopeNames.WITH_THUMBNAILS
1423 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1424 const where = buildWhereIdOrUUID(id)
1427 attributes: [ 'id' ],
1432 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1435 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1436 const where = buildWhereIdOrUUID(id)
1444 return VideoModel.scope([
1445 ScopeNames.WITH_FILES,
1446 ScopeNames.WITH_STREAMING_PLAYLISTS,
1447 ScopeNames.WITH_THUMBNAILS
1451 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1458 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1461 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1462 const query: FindOptions = {
1469 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1472 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1473 const query: FindOptions = {
1480 return VideoModel.scope([
1481 ScopeNames.WITH_ACCOUNT_DETAILS,
1482 ScopeNames.WITH_FILES,
1483 ScopeNames.WITH_STREAMING_PLAYLISTS,
1484 ScopeNames.WITH_THUMBNAILS,
1485 ScopeNames.WITH_BLACKLISTED
1489 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1490 const where = buildWhereIdOrUUID(id)
1493 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1498 const scopes: (string | ScopeOptions)[] = [
1499 ScopeNames.WITH_TAGS,
1500 ScopeNames.WITH_BLACKLISTED,
1501 ScopeNames.WITH_ACCOUNT_DETAILS,
1502 ScopeNames.WITH_SCHEDULED_UPDATE,
1503 ScopeNames.WITH_FILES,
1504 ScopeNames.WITH_STREAMING_PLAYLISTS,
1505 ScopeNames.WITH_THUMBNAILS
1509 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1517 static loadForGetAPI (parameters: {
1518 id: number | string,
1521 }): Bluebird<MVideoDetails> {
1522 const { id, t, userId } = parameters
1523 const where = buildWhereIdOrUUID(id)
1526 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1531 const scopes: (string | ScopeOptions)[] = [
1532 ScopeNames.WITH_TAGS,
1533 ScopeNames.WITH_BLACKLISTED,
1534 ScopeNames.WITH_ACCOUNT_DETAILS,
1535 ScopeNames.WITH_SCHEDULED_UPDATE,
1536 ScopeNames.WITH_THUMBNAILS,
1537 { method: [ ScopeNames.WITH_FILES, true ] },
1538 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1542 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1550 static async getStats () {
1551 const totalLocalVideos = await VideoModel.count({
1556 const totalVideos = await VideoModel.count()
1558 let totalLocalVideoViews = await VideoModel.sum('views', {
1563 // Sequelize could return null...
1564 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1568 totalLocalVideoViews,
1573 static incrementViews (id: number, views: number) {
1574 return VideoModel.increment('views', {
1582 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1583 // Instances only share videos
1584 const query = 'SELECT 1 FROM "videoShare" ' +
1585 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1586 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1590 type: QueryTypes.SELECT,
1591 bind: { followerActorId, videoId },
1595 return VideoModel.sequelize.query(query, options)
1596 .then(results => results.length === 1)
1599 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1602 channelId: videoChannel.id
1607 return VideoModel.update({ support: videoChannel.support }, options)
1610 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1612 attributes: [ 'id' ],
1614 channelId: videoChannel.id
1618 return VideoModel.findAll(query)
1619 .then(videos => videos.map(v => v.id))
1622 // threshold corresponds to how many video the field should have to be returned
1623 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1624 const serverActor = await getServerActor()
1625 const followerActorId = serverActor.id
1627 const scopeOptions: AvailableForListIDsOptions = {
1628 serverAccountId: serverActor.Account.id,
1630 includeLocalVideos: true,
1631 attributesType: 'none' // Don't break aggregation
1634 const query: FindOptions = {
1635 attributes: [ field ],
1638 having: Sequelize.where(
1639 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1641 order: [ (this.sequelize as any).random() ]
1644 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1646 .then(rows => rows.map(r => r[ field ]))
1649 static buildTrendingQuery (trendingDays: number) {
1653 model: VideoViewModel,
1657 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1663 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1664 if (filter && (filter === 'local' || filter === 'all-local')) {
1673 private static async getAvailableForApi (
1674 query: FindOptions & { where?: null }, // Forbid where field in query
1675 options: AvailableForListIDsOptions,
1678 const idsScope: ScopeOptions = {
1680 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1684 // Remove trending sort on count, because it uses a group by
1685 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1686 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1687 const countScope: ScopeOptions = {
1689 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1693 const [ count, ids ] = await Promise.all([
1695 ? VideoModel.scope(countScope).count(countQuery)
1696 : Promise.resolve<number>(undefined),
1698 VideoModel.scope(idsScope)
1700 .then(rows => rows.map(r => r.id))
1703 if (ids.length === 0) return { data: [], total: count }
1705 const secondQuery: FindOptions = {
1708 attributes: query.attributes,
1709 order: [ // Keep original order
1711 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1716 const apiScope: (string | ScopeOptions)[] = []
1719 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1724 ScopeNames.FOR_API, {
1726 withFiles: options.withFiles,
1727 videoPlaylistId: options.videoPlaylistId
1732 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1740 static getCategoryLabel (id: number) {
1741 return VIDEO_CATEGORIES[ id ] || 'Misc'
1744 static getLicenceLabel (id: number) {
1745 return VIDEO_LICENCES[ id ] || 'Unknown'
1748 static getLanguageLabel (id: string) {
1749 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1752 static getPrivacyLabel (id: number) {
1753 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1756 static getStateLabel (id: number) {
1757 return VIDEO_STATES[ id ] || 'Unknown'
1761 return !!this.VideoBlacklist
1765 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1766 this.VideoChannel.Account.isBlocked()
1769 getOriginalFile <T extends MVideoWithFile> (this: T) {
1770 if (Array.isArray(this.VideoFiles) === false) return undefined
1772 // The original file is the file that have the higher resolution
1773 return maxBy(this.VideoFiles, file => file.resolution)
1776 getFile <T extends MVideoWithFile> (this: T, resolution: number) {
1777 if (Array.isArray(this.VideoFiles) === false) return undefined
1779 return this.VideoFiles.find(f => f.resolution === resolution)
1782 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1783 thumbnail.videoId = this.id
1785 const savedThumbnail = await thumbnail.save({ transaction })
1787 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1789 // Already have this thumbnail, skip
1790 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1792 this.Thumbnails.push(savedThumbnail)
1795 getVideoFilename (videoFile: MVideoFile) {
1796 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1799 generateThumbnailName () {
1800 return this.uuid + '.jpg'
1804 if (Array.isArray(this.Thumbnails) === false) return undefined
1806 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1809 generatePreviewName () {
1810 return this.uuid + '.jpg'
1814 if (Array.isArray(this.Thumbnails) === false) return undefined
1816 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1819 getTorrentFileName (videoFile: MVideoFile) {
1820 const extension = '.torrent'
1821 return this.uuid + '-' + videoFile.resolution + extension
1825 return this.remote === false
1828 getTorrentFilePath (videoFile: MVideoFile) {
1829 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1832 getVideoFilePath (videoFile: MVideoFile) {
1833 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1836 async createTorrentAndSetInfoHash (videoFile: MVideoFile) {
1838 // Keep the extname, it's used by the client to stream the file inside a web browser
1839 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1840 createdBy: 'PeerTube',
1842 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1843 [ WEBSERVER.URL + '/tracker/announce' ]
1845 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1848 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1850 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1851 logger.info('Creating torrent %s.', filePath)
1853 await writeFile(filePath, torrent)
1855 const parsedTorrent = parseTorrent(torrent)
1856 videoFile.infoHash = parsedTorrent.infoHash
1859 getWatchStaticPath () {
1860 return '/videos/watch/' + this.uuid
1863 getEmbedStaticPath () {
1864 return '/videos/embed/' + this.uuid
1867 getMiniatureStaticPath () {
1868 const thumbnail = this.getMiniature()
1869 if (!thumbnail) return null
1871 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1874 getPreviewStaticPath () {
1875 const preview = this.getPreview()
1876 if (!preview) return null
1878 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1879 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1882 toFormattedJSON <T extends MVideoFormattable> (this: T, options?: VideoFormattingJSONOptions): Video {
1883 return videoModelToFormattedJSON(this, options)
1886 toFormattedDetailsJSON (): VideoDetails {
1887 return videoModelToFormattedDetailsJSON(this)
1890 getFormattedVideoFilesJSON (): VideoFile[] {
1891 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1894 toActivityPubObject (): VideoTorrentObject {
1895 return videoModelToActivityPubObject(this)
1898 getTruncatedDescription () {
1899 if (!this.description) return null
1901 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1902 return peertubeTruncate(this.description, maxLength)
1905 getOriginalFileResolution () {
1906 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1908 return getVideoFileResolution(originalFilePath)
1911 getDescriptionAPIPath () {
1912 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1916 if (!this.VideoStreamingPlaylists) return undefined
1918 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1921 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1922 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1924 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1925 return remove(filePath)
1926 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1929 removeTorrent (videoFile: MVideoFile) {
1930 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1931 return remove(torrentPath)
1932 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1935 removeStreamingPlaylist (isRedundancy = false) {
1936 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1938 const filePath = join(baseDir, this.uuid)
1939 return remove(filePath)
1940 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1944 if (this.isOwned()) return false
1946 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1950 this.changed('updatedAt', true)
1959 if (this.isOwned()) {
1960 baseUrlHttp = WEBSERVER.URL
1961 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1963 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1964 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1967 return { baseUrlHttp, baseUrlWs }
1970 generateMagnetUri (videoFile: MVideoFileRedundanciesOpt, baseUrlHttp: string, baseUrlWs: string) {
1971 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1972 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1973 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1975 const redundancies = videoFile.RedundancyVideos
1976 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1978 const magnetHash = {
1982 infoHash: videoFile.infoHash,
1986 return magnetUtil.encode(magnetHash)
1989 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1990 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1993 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1994 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1997 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
1998 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2001 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2002 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
2005 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2006 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
2009 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2010 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2013 getBandwidthBits (videoFile: MVideoFile) {
2014 return Math.ceil((videoFile.size * 8) / this.duration)