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, VideoResolution, 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 { UserModel } from '../account/user'
115 import { VideoImportModel } from './video-import'
116 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
117 import { VideoPlaylistElementModel } from './video-playlist-element'
118 import { CONFIG } from '../../initializers/config'
119 import { ThumbnailModel } from './thumbnail'
120 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
121 import { createTorrentPromise } from '../../helpers/webtorrent'
122 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
124 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
125 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
126 buildTrigramSearchIndex('video_name_trigram', 'name'),
128 { fields: [ 'createdAt' ] },
129 { fields: [ 'publishedAt' ] },
130 { fields: [ 'duration' ] },
131 { fields: [ 'views' ] },
132 { fields: [ 'channelId' ] },
134 fields: [ 'originallyPublishedAt' ],
136 originallyPublishedAt: {
142 fields: [ 'category' ], // We don't care videos with an unknown category
150 fields: [ 'licence' ], // We don't care videos with an unknown licence
158 fields: [ 'language' ], // We don't care videos with an unknown language
166 fields: [ 'nsfw' ], // Most of the videos are not NSFW
172 fields: [ 'remote' ], // Only index local videos
187 export enum ScopeNames {
188 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
190 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
191 WITH_TAGS = 'WITH_TAGS',
192 WITH_FILES = 'WITH_FILES',
193 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
194 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
195 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
196 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
197 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
198 WITH_USER_ID = 'WITH_USER_ID',
199 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
202 export type ForAPIOptions = {
205 videoPlaylistId?: number
209 withAccountBlockerIds?: number[]
212 export type AvailableForListIDsOptions = {
213 serverAccountId: number
214 followerActorId: number
215 includeLocalVideos: boolean
217 attributesType?: 'none' | 'id' | 'all'
220 categoryOneOf?: number[]
222 licenceOneOf?: number[]
223 languageOneOf?: string[]
230 videoChannelId?: number
232 videoPlaylistId?: number
234 trendingDays?: number
236 historyOfUser?: UserModel
238 baseWhere?: WhereOptions[]
242 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
243 const query: FindOptions = {
246 model: VideoChannelModel.scope({
248 VideoChannelScopeNames.SUMMARY, {
250 withAccountBlockerIds: options.withAccountBlockerIds
257 attributes: [ 'type', 'filename' ],
258 model: ThumbnailModel,
267 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
272 if (options.withFiles === true) {
274 model: VideoFileModel.unscoped(),
279 if (options.videoPlaylistId) {
281 model: VideoPlaylistElementModel.unscoped(),
284 videoPlaylistId: options.videoPlaylistId
291 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
292 const whereAnd = options.baseWhere ? options.baseWhere : []
294 const query: FindOptions = {
299 const attributesType = options.attributesType || 'id'
301 if (attributesType === 'id') query.attributes = [ 'id' ]
302 else if (attributesType === 'none') query.attributes = [ ]
306 [ Op.notIn ]: Sequelize.literal(
307 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
312 if (options.serverAccountId) {
315 [ Op.notIn ]: Sequelize.literal(
317 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
318 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
326 // Only list public/published videos
327 if (!options.filter || options.filter !== 'all-local') {
328 const privacyWhere = {
329 // Always list public videos
330 privacy: VideoPrivacy.PUBLIC,
331 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
334 state: VideoState.PUBLISHED
338 state: VideoState.TO_TRANSCODE,
339 waitTranscoding: false
345 whereAnd.push(privacyWhere)
348 if (options.videoPlaylistId) {
351 model: VideoPlaylistElementModel.unscoped(),
354 videoPlaylistId: options.videoPlaylistId
358 query.subQuery = false
361 if (options.filter || options.accountId || options.videoChannelId) {
362 const videoChannelInclude: IncludeOptions = {
364 model: VideoChannelModel.unscoped(),
368 if (options.videoChannelId) {
369 videoChannelInclude.where = {
370 id: options.videoChannelId
374 if (options.filter || options.accountId) {
375 const accountInclude: IncludeOptions = {
377 model: AccountModel.unscoped(),
381 if (options.filter) {
382 accountInclude.include = [
385 model: ActorModel.unscoped(),
387 where: VideoModel.buildActorWhereWithFilter(options.filter)
392 if (options.accountId) {
393 accountInclude.where = { id: options.accountId }
396 videoChannelInclude.include = [ accountInclude ]
399 query.include.push(videoChannelInclude)
402 if (options.followerActorId) {
403 let localVideosReq = ''
404 if (options.includeLocalVideos === true) {
405 localVideosReq = ' UNION ALL ' +
406 'SELECT "video"."id" AS "id" FROM "video" ' +
407 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
408 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
409 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
410 'WHERE "actor"."serverId" IS NULL'
413 // Force actorId to be a number to avoid SQL injections
414 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
417 [ Op.in ]: Sequelize.literal(
419 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
420 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
421 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
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 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
428 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
436 if (options.withFiles === true) {
439 [ Op.in ]: Sequelize.literal(
440 '(SELECT "videoId" FROM "videoFile")'
446 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
447 if (options.tagsAllOf || options.tagsOneOf) {
448 if (options.tagsOneOf) {
451 [ Op.in ]: Sequelize.literal(
453 'SELECT "videoId" FROM "videoTag" ' +
454 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
455 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
462 if (options.tagsAllOf) {
465 [ Op.in ]: Sequelize.literal(
467 'SELECT "videoId" FROM "videoTag" ' +
468 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
469 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
470 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
478 if (options.nsfw === true || options.nsfw === false) {
479 whereAnd.push({ nsfw: options.nsfw })
482 if (options.categoryOneOf) {
485 [ Op.or ]: options.categoryOneOf
490 if (options.licenceOneOf) {
493 [ Op.or ]: options.licenceOneOf
498 if (options.languageOneOf) {
499 let videoLanguages = options.languageOneOf
500 if (options.languageOneOf.find(l => l === '_unknown')) {
501 videoLanguages = videoLanguages.concat([ null ])
508 [ Op.or ]: videoLanguages
513 [ Op.in ]: Sequelize.literal(
515 'SELECT "videoId" FROM "videoCaption" ' +
516 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
525 if (options.trendingDays) {
526 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
528 query.subQuery = false
531 if (options.historyOfUser) {
533 model: UserVideoHistoryModel,
536 userId: options.historyOfUser.id
540 // Even if the relation is n:m, we know that a user only have 0..1 video history
541 // So we won't have multiple rows for the same video
542 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
543 query.subQuery = false
552 [ScopeNames.WITH_BLOCKLIST]: {
555 [ ScopeNames.WITH_THUMBNAILS ]: {
558 model: ThumbnailModel,
563 [ ScopeNames.WITH_USER_ID ]: {
566 attributes: [ 'accountId' ],
567 model: VideoChannelModel.unscoped(),
571 attributes: [ 'userId' ],
572 model: AccountModel.unscoped(),
579 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
582 model: VideoChannelModel.unscoped(),
587 exclude: [ 'privateKey', 'publicKey' ]
589 model: ActorModel.unscoped(),
593 attributes: [ 'host' ],
594 model: ServerModel.unscoped(),
598 model: AvatarModel.unscoped(),
604 model: AccountModel.unscoped(),
608 model: ActorModel.unscoped(),
610 exclude: [ 'privateKey', 'publicKey' ]
615 attributes: [ 'host' ],
616 model: ServerModel.unscoped(),
620 model: AvatarModel.unscoped(),
631 [ ScopeNames.WITH_TAGS ]: {
632 include: [ TagModel ]
634 [ ScopeNames.WITH_BLACKLISTED ]: {
637 attributes: [ 'id', 'reason' ],
638 model: VideoBlacklistModel,
643 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
644 let subInclude: any[] = []
646 if (withRedundancies === true) {
649 attributes: [ 'fileUrl' ],
650 model: VideoRedundancyModel.unscoped(),
659 model: VideoFileModel.unscoped(),
660 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
667 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
668 let subInclude: any[] = []
670 if (withRedundancies === true) {
673 attributes: [ 'fileUrl' ],
674 model: VideoRedundancyModel.unscoped(),
683 model: VideoStreamingPlaylistModel.unscoped(),
684 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
691 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
694 model: ScheduleVideoUpdateModel.unscoped(),
699 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
703 attributes: [ 'currentTime' ],
704 model: UserVideoHistoryModel.unscoped(),
718 export class VideoModel extends Model<VideoModel> {
721 @Default(DataType.UUIDV4)
723 @Column(DataType.UUID)
727 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
733 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
739 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
745 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
746 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
750 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
755 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
761 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
762 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
767 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
768 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
772 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
802 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
803 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
808 commentsEnabled: boolean
812 downloadEnabled: boolean
816 waitTranscoding: boolean
820 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
831 @Default(DataType.NOW)
838 originallyPublishedAt: Date
840 @ForeignKey(() => VideoChannelModel)
844 @BelongsTo(() => VideoChannelModel, {
850 VideoChannel: VideoChannelModel
852 @BelongsToMany(() => TagModel, {
853 foreignKey: 'videoId',
854 through: () => VideoTagModel,
859 @HasMany(() => ThumbnailModel, {
867 Thumbnails: ThumbnailModel[]
869 @HasMany(() => VideoPlaylistElementModel, {
876 VideoPlaylistElements: VideoPlaylistElementModel[]
878 @HasMany(() => VideoAbuseModel, {
885 VideoAbuses: VideoAbuseModel[]
887 @HasMany(() => VideoFileModel, {
895 VideoFiles: VideoFileModel[]
897 @HasMany(() => VideoStreamingPlaylistModel, {
905 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
907 @HasMany(() => VideoShareModel, {
914 VideoShares: VideoShareModel[]
916 @HasMany(() => AccountVideoRateModel, {
923 AccountVideoRates: AccountVideoRateModel[]
925 @HasMany(() => VideoCommentModel, {
933 VideoComments: VideoCommentModel[]
935 @HasMany(() => VideoViewModel, {
942 VideoViews: VideoViewModel[]
944 @HasMany(() => UserVideoHistoryModel, {
951 UserVideoHistories: UserVideoHistoryModel[]
953 @HasOne(() => ScheduleVideoUpdateModel, {
960 ScheduleVideoUpdate: ScheduleVideoUpdateModel
962 @HasOne(() => VideoBlacklistModel, {
969 VideoBlacklist: VideoBlacklistModel
971 @HasOne(() => VideoImportModel, {
978 VideoImport: VideoImportModel
980 @HasMany(() => VideoCaptionModel, {
987 [ 'separate' as any ]: true
989 VideoCaptions: VideoCaptionModel[]
992 static async sendDelete (instance: VideoModel, options) {
993 if (instance.isOwned()) {
994 if (!instance.VideoChannel) {
995 instance.VideoChannel = await instance.$get('VideoChannel', {
999 include: [ ActorModel ]
1002 transaction: options.transaction
1003 }) as VideoChannelModel
1006 return sendDeleteVideo(instance, options.transaction)
1013 static async removeFiles (instance: VideoModel) {
1014 const tasks: Promise<any>[] = []
1016 logger.info('Removing files of video %s.', instance.url)
1018 if (instance.isOwned()) {
1019 if (!Array.isArray(instance.VideoFiles)) {
1020 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1023 // Remove physical files and torrents
1024 instance.VideoFiles.forEach(file => {
1025 tasks.push(instance.removeFile(file))
1026 tasks.push(instance.removeTorrent(file))
1029 // Remove playlists file
1030 tasks.push(instance.removeStreamingPlaylist())
1033 // Do not wait video deletion because we could be in a transaction
1036 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1042 static listLocal () {
1049 return VideoModel.scope([
1050 ScopeNames.WITH_FILES,
1051 ScopeNames.WITH_STREAMING_PLAYLISTS,
1052 ScopeNames.WITH_THUMBNAILS
1056 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1057 function getRawQuery (select: string) {
1058 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1059 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1060 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1061 'WHERE "Account"."actorId" = ' + actorId
1062 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1063 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1064 'WHERE "VideoShare"."actorId" = ' + actorId
1066 return `(${queryVideo}) UNION (${queryVideoShare})`
1069 const rawQuery = getRawQuery('"Video"."id"')
1070 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1076 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1079 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1082 { privacy: VideoPrivacy.PUBLIC },
1083 { privacy: VideoPrivacy.UNLISTED }
1088 attributes: [ 'language' ],
1089 model: VideoCaptionModel.unscoped(),
1093 attributes: [ 'id', 'url' ],
1094 model: VideoShareModel.unscoped(),
1096 // We only want videos shared by this actor
1111 attributes: [ 'id', 'url' ],
1112 model: ActorModel.unscoped()
1117 model: VideoChannelModel.unscoped(),
1121 attributes: [ 'name' ],
1122 model: AccountModel.unscoped(),
1126 attributes: [ 'id', 'url', 'followersUrl' ],
1127 model: ActorModel.unscoped(),
1133 attributes: [ 'id', 'url', 'followersUrl' ],
1134 model: ActorModel.unscoped(),
1144 return Bluebird.all([
1145 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1146 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1147 ]).then(([ rows, totals ]) => {
1148 // totals: totalVideos + totalVideoShares
1150 let totalVideoShares = 0
1151 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1152 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1154 const total = totalVideos + totalVideoShares
1162 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1163 function buildBaseQuery (): FindOptions {
1167 order: getVideoSort(sort),
1170 model: VideoChannelModel,
1174 model: AccountModel,
1186 const countQuery = buildBaseQuery()
1187 const findQuery = buildBaseQuery()
1189 const findScopes = [
1190 ScopeNames.WITH_SCHEDULED_UPDATE,
1191 ScopeNames.WITH_BLACKLISTED,
1192 ScopeNames.WITH_THUMBNAILS
1195 if (withFiles === true) {
1196 findQuery.include.push({
1197 model: VideoFileModel.unscoped(),
1202 return Promise.all([
1203 VideoModel.count(countQuery),
1204 VideoModel.scope(findScopes).findAll(findQuery)
1205 ]).then(([ count, rows ]) => {
1213 static async listForApi (options: {
1218 includeLocalVideos: boolean,
1220 categoryOneOf?: number[],
1221 licenceOneOf?: number[],
1222 languageOneOf?: string[],
1223 tagsOneOf?: string[],
1224 tagsAllOf?: string[],
1225 filter?: VideoFilter,
1227 videoChannelId?: number,
1228 followerActorId?: number
1229 videoPlaylistId?: number,
1230 trendingDays?: number,
1232 historyOfUser?: UserModel
1233 }, countVideos = true) {
1234 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1235 throw new Error('Try to filter all-local but no user has not the see all videos right')
1238 const query: FindOptions & { where?: null } = {
1239 offset: options.start,
1240 limit: options.count,
1241 order: getVideoSort(options.sort)
1244 let trendingDays: number
1245 if (options.sort.endsWith('trending')) {
1246 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1248 query.group = 'VideoModel.id'
1251 const serverActor = await getServerActor()
1253 // followerActorId === null has a meaning, so just check undefined
1254 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1256 const queryOptions = {
1258 serverAccountId: serverActor.Account.id,
1260 categoryOneOf: options.categoryOneOf,
1261 licenceOneOf: options.licenceOneOf,
1262 languageOneOf: options.languageOneOf,
1263 tagsOneOf: options.tagsOneOf,
1264 tagsAllOf: options.tagsAllOf,
1265 filter: options.filter,
1266 withFiles: options.withFiles,
1267 accountId: options.accountId,
1268 videoChannelId: options.videoChannelId,
1269 videoPlaylistId: options.videoPlaylistId,
1270 includeLocalVideos: options.includeLocalVideos,
1272 historyOfUser: options.historyOfUser,
1276 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1279 static async searchAndPopulateAccountAndServer (options: {
1280 includeLocalVideos: boolean
1285 startDate?: string // ISO 8601
1286 endDate?: string // ISO 8601
1287 originallyPublishedStartDate?: string
1288 originallyPublishedEndDate?: string
1290 categoryOneOf?: number[]
1291 licenceOneOf?: number[]
1292 languageOneOf?: string[]
1293 tagsOneOf?: string[]
1294 tagsAllOf?: string[]
1295 durationMin?: number // seconds
1296 durationMax?: number // seconds
1298 filter?: VideoFilter
1302 if (options.startDate || options.endDate) {
1303 const publishedAtRange = {}
1305 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1306 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1308 whereAnd.push({ publishedAt: publishedAtRange })
1311 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1312 const originallyPublishedAtRange = {}
1314 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1315 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1317 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1320 if (options.durationMin || options.durationMax) {
1321 const durationRange = {}
1323 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1324 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1326 whereAnd.push({ duration: durationRange })
1329 const attributesInclude = []
1330 const escapedSearch = VideoModel.sequelize.escape(options.search)
1331 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1332 if (options.search) {
1336 [ Op.in ]: Sequelize.literal(
1338 'SELECT "video"."id" FROM "video" ' +
1340 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1341 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1343 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1344 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1345 'WHERE "tag"."name" = ' + escapedSearch +
1352 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1355 // Cannot search on similarity if we don't have a search
1356 if (!options.search) {
1357 attributesInclude.push(
1358 Sequelize.literal('0 as similarity')
1364 include: attributesInclude
1366 offset: options.start,
1367 limit: options.count,
1368 order: getVideoSort(options.sort)
1371 const serverActor = await getServerActor()
1372 const queryOptions = {
1373 followerActorId: serverActor.id,
1374 serverAccountId: serverActor.Account.id,
1375 includeLocalVideos: options.includeLocalVideos,
1377 categoryOneOf: options.categoryOneOf,
1378 licenceOneOf: options.licenceOneOf,
1379 languageOneOf: options.languageOneOf,
1380 tagsOneOf: options.tagsOneOf,
1381 tagsAllOf: options.tagsAllOf,
1383 filter: options.filter,
1387 return VideoModel.getAvailableForApi(query, queryOptions)
1390 static load (id: number | string, t?: Transaction) {
1391 const where = buildWhereIdOrUUID(id)
1397 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1400 static loadWithRights (id: number | string, t?: Transaction) {
1401 const where = buildWhereIdOrUUID(id)
1407 return VideoModel.scope([
1408 ScopeNames.WITH_BLACKLISTED,
1409 ScopeNames.WITH_USER_ID,
1410 ScopeNames.WITH_THUMBNAILS
1414 static loadOnlyId (id: number | string, t?: Transaction) {
1415 const where = buildWhereIdOrUUID(id)
1418 attributes: [ 'id' ],
1423 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1426 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean) {
1427 const where = buildWhereIdOrUUID(id)
1435 return VideoModel.scope([
1436 ScopeNames.WITH_FILES,
1437 ScopeNames.WITH_STREAMING_PLAYLISTS,
1438 ScopeNames.WITH_THUMBNAILS
1442 static loadByUUID (uuid: string) {
1449 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1452 static loadByUrl (url: string, transaction?: Transaction) {
1453 const query: FindOptions = {
1460 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1463 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1464 const query: FindOptions = {
1471 return VideoModel.scope([
1472 ScopeNames.WITH_ACCOUNT_DETAILS,
1473 ScopeNames.WITH_FILES,
1474 ScopeNames.WITH_STREAMING_PLAYLISTS,
1475 ScopeNames.WITH_THUMBNAILS
1479 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1480 const where = buildWhereIdOrUUID(id)
1483 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1488 const scopes: (string | ScopeOptions)[] = [
1489 ScopeNames.WITH_TAGS,
1490 ScopeNames.WITH_BLACKLISTED,
1491 ScopeNames.WITH_ACCOUNT_DETAILS,
1492 ScopeNames.WITH_SCHEDULED_UPDATE,
1493 ScopeNames.WITH_FILES,
1494 ScopeNames.WITH_STREAMING_PLAYLISTS,
1495 ScopeNames.WITH_THUMBNAILS
1499 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1507 static loadForGetAPI (parameters: {
1508 id: number | string,
1512 const { id, t, userId } = parameters
1513 const where = buildWhereIdOrUUID(id)
1516 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1521 const scopes: (string | ScopeOptions)[] = [
1522 ScopeNames.WITH_TAGS,
1523 ScopeNames.WITH_BLACKLISTED,
1524 ScopeNames.WITH_ACCOUNT_DETAILS,
1525 ScopeNames.WITH_SCHEDULED_UPDATE,
1526 ScopeNames.WITH_THUMBNAILS,
1527 { method: [ ScopeNames.WITH_FILES, true ] },
1528 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1532 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1540 static async getStats () {
1541 const totalLocalVideos = await VideoModel.count({
1546 const totalVideos = await VideoModel.count()
1548 let totalLocalVideoViews = await VideoModel.sum('views', {
1553 // Sequelize could return null...
1554 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1558 totalLocalVideoViews,
1563 static incrementViews (id: number, views: number) {
1564 return VideoModel.increment('views', {
1572 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1573 // Instances only share videos
1574 const query = 'SELECT 1 FROM "videoShare" ' +
1575 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1576 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1580 type: QueryTypes.SELECT,
1581 bind: { followerActorId, videoId },
1585 return VideoModel.sequelize.query(query, options)
1586 .then(results => results.length === 1)
1589 static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) {
1592 channelId: videoChannel.id
1597 return VideoModel.update({ support: videoChannel.support }, options)
1600 static getAllIdsFromChannel (videoChannel: VideoChannelModel) {
1602 attributes: [ 'id' ],
1604 channelId: videoChannel.id
1608 return VideoModel.findAll(query)
1609 .then(videos => videos.map(v => v.id))
1612 // threshold corresponds to how many video the field should have to be returned
1613 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1614 const serverActor = await getServerActor()
1615 const followerActorId = serverActor.id
1617 const scopeOptions: AvailableForListIDsOptions = {
1618 serverAccountId: serverActor.Account.id,
1620 includeLocalVideos: true,
1621 attributesType: 'none' // Don't break aggregation
1624 const query: FindOptions = {
1625 attributes: [ field ],
1628 having: Sequelize.where(
1629 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1631 order: [ (this.sequelize as any).random() ]
1634 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1636 .then(rows => rows.map(r => r[ field ]))
1639 static buildTrendingQuery (trendingDays: number) {
1643 model: VideoViewModel,
1647 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1653 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1654 if (filter && (filter === 'local' || filter === 'all-local')) {
1663 private static async getAvailableForApi (
1664 query: FindOptions & { where?: null }, // Forbid where field in query
1665 options: AvailableForListIDsOptions,
1668 const idsScope: ScopeOptions = {
1670 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1674 // Remove trending sort on count, because it uses a group by
1675 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1676 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1677 const countScope: ScopeOptions = {
1679 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1683 const [ count, ids ] = await Promise.all([
1685 ? VideoModel.scope(countScope).count(countQuery)
1686 : Promise.resolve<number>(undefined),
1688 VideoModel.scope(idsScope)
1690 .then(rows => rows.map(r => r.id))
1693 if (ids.length === 0) return { data: [], total: count }
1695 const secondQuery: FindOptions = {
1698 attributes: query.attributes,
1699 order: [ // Keep original order
1701 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1706 const apiScope: (string | ScopeOptions)[] = []
1709 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1714 ScopeNames.FOR_API, {
1716 withFiles: options.withFiles,
1717 videoPlaylistId: options.videoPlaylistId
1722 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1730 static getCategoryLabel (id: number) {
1731 return VIDEO_CATEGORIES[ id ] || 'Misc'
1734 static getLicenceLabel (id: number) {
1735 return VIDEO_LICENCES[ id ] || 'Unknown'
1738 static getLanguageLabel (id: string) {
1739 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1742 static getPrivacyLabel (id: number) {
1743 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1746 static getStateLabel (id: number) {
1747 return VIDEO_STATES[ id ] || 'Unknown'
1751 return !!this.VideoBlacklist
1755 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1756 this.VideoChannel.Account.isBlocked()
1759 getOriginalFile () {
1760 if (Array.isArray(this.VideoFiles) === false) return undefined
1762 // The original file is the file that have the higher resolution
1763 return maxBy(this.VideoFiles, file => file.resolution)
1766 getFile (resolution: number) {
1767 if (Array.isArray(this.VideoFiles) === false) return undefined
1769 return this.VideoFiles.find(f => f.resolution === resolution)
1772 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1773 thumbnail.videoId = this.id
1775 const savedThumbnail = await thumbnail.save({ transaction })
1777 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1779 // Already have this thumbnail, skip
1780 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1782 this.Thumbnails.push(savedThumbnail)
1785 getVideoFilename (videoFile: VideoFileModel) {
1786 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1789 generateThumbnailName () {
1790 return this.uuid + '.jpg'
1794 if (Array.isArray(this.Thumbnails) === false) return undefined
1796 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1799 generatePreviewName () {
1800 return this.uuid + '.jpg'
1804 if (Array.isArray(this.Thumbnails) === false) return undefined
1806 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1809 getTorrentFileName (videoFile: VideoFileModel) {
1810 const extension = '.torrent'
1811 return this.uuid + '-' + videoFile.resolution + extension
1815 return this.remote === false
1818 getTorrentFilePath (videoFile: VideoFileModel) {
1819 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1822 getVideoFilePath (videoFile: VideoFileModel) {
1823 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1826 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1828 // Keep the extname, it's used by the client to stream the file inside a web browser
1829 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1830 createdBy: 'PeerTube',
1832 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1833 [ WEBSERVER.URL + '/tracker/announce' ]
1835 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1838 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1840 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1841 logger.info('Creating torrent %s.', filePath)
1843 await writeFile(filePath, torrent)
1845 const parsedTorrent = parseTorrent(torrent)
1846 videoFile.infoHash = parsedTorrent.infoHash
1849 getWatchStaticPath () {
1850 return '/videos/watch/' + this.uuid
1853 getEmbedStaticPath () {
1854 return '/videos/embed/' + this.uuid
1857 getMiniatureStaticPath () {
1858 const thumbnail = this.getMiniature()
1859 if (!thumbnail) return null
1861 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1864 getPreviewStaticPath () {
1865 const preview = this.getPreview()
1866 if (!preview) return null
1868 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1869 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1872 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1873 return videoModelToFormattedJSON(this, options)
1876 toFormattedDetailsJSON (): VideoDetails {
1877 return videoModelToFormattedDetailsJSON(this)
1880 getFormattedVideoFilesJSON (): VideoFile[] {
1881 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1884 toActivityPubObject (): VideoTorrentObject {
1885 return videoModelToActivityPubObject(this)
1888 getTruncatedDescription () {
1889 if (!this.description) return null
1891 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1892 return peertubeTruncate(this.description, maxLength)
1895 getOriginalFileResolution () {
1896 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1898 return getVideoFileResolution(originalFilePath)
1901 getDescriptionAPIPath () {
1902 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1906 if (!this.VideoStreamingPlaylists) return undefined
1908 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1911 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1912 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1914 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1915 return remove(filePath)
1916 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1919 removeTorrent (videoFile: VideoFileModel) {
1920 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1921 return remove(torrentPath)
1922 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1925 removeStreamingPlaylist (isRedundancy = false) {
1926 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1928 const filePath = join(baseDir, this.uuid)
1929 return remove(filePath)
1930 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1934 if (this.isOwned()) return false
1936 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1940 this.changed('updatedAt', true)
1949 if (this.isOwned()) {
1950 baseUrlHttp = WEBSERVER.URL
1951 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1953 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1954 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1957 return { baseUrlHttp, baseUrlWs }
1960 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1961 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1962 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1963 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1965 const redundancies = videoFile.RedundancyVideos
1966 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1968 const magnetHash = {
1972 infoHash: videoFile.infoHash,
1976 return magnetUtil.encode(magnetHash)
1979 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1980 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1983 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1984 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1987 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1988 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1991 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1992 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1995 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1996 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1999 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
2000 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2003 getBandwidthBits (videoFile: VideoFileModel) {
2004 return Math.ceil((videoFile.size * 8) / this.duration)