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,
67 STATIC_DOWNLOAD_PATHS,
75 } from '../../initializers/constants'
76 import { sendDeleteVideo } from '../../lib/activitypub/send'
77 import { AccountModel } from '../account/account'
78 import { AccountVideoRateModel } from '../account/account-video-rate'
79 import { ActorModel } from '../activitypub/actor'
80 import { AvatarModel } from '../avatar/avatar'
81 import { ServerModel } from '../server/server'
83 buildBlockedAccountSQL,
84 buildTrigramSearchIndex,
87 createSimilarityAttribute,
92 import { TagModel } from './tag'
93 import { VideoAbuseModel } from './video-abuse'
94 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
95 import { VideoCommentModel } from './video-comment'
96 import { VideoFileModel } from './video-file'
97 import { VideoShareModel } from './video-share'
98 import { VideoTagModel } from './video-tag'
99 import { ScheduleVideoUpdateModel } from './schedule-video-update'
100 import { VideoCaptionModel } from './video-caption'
101 import { VideoBlacklistModel } from './video-blacklist'
102 import { remove, writeFile } from 'fs-extra'
103 import { VideoViewModel } from './video-views'
104 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
106 videoFilesModelToFormattedJSON,
107 VideoFormattingJSONOptions,
108 videoModelToActivityPubObject,
109 videoModelToFormattedDetailsJSON,
110 videoModelToFormattedJSON
111 } from './video-format-utils'
112 import { UserVideoHistoryModel } from '../account/user-video-history'
113 import { UserModel } from '../account/user'
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'
122 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
123 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
124 buildTrigramSearchIndex('video_name_trigram', 'name'),
126 { fields: [ 'createdAt' ] },
127 { fields: [ 'publishedAt' ] },
128 { fields: [ 'duration' ] },
129 { fields: [ 'views' ] },
130 { fields: [ 'channelId' ] },
132 fields: [ 'originallyPublishedAt' ],
134 originallyPublishedAt: {
140 fields: [ 'category' ], // We don't care videos with an unknown category
148 fields: [ 'licence' ], // We don't care videos with an unknown licence
156 fields: [ 'language' ], // We don't care videos with an unknown language
164 fields: [ 'nsfw' ], // Most of the videos are not NSFW
170 fields: [ 'remote' ], // Only index local videos
185 export enum ScopeNames {
186 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
188 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
189 WITH_TAGS = 'WITH_TAGS',
190 WITH_FILES = 'WITH_FILES',
191 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
192 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
193 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
194 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
195 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
196 WITH_USER_ID = 'WITH_USER_ID',
197 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
200 export type ForAPIOptions = {
203 videoPlaylistId?: number
207 withAccountBlockerIds?: number[]
210 export type AvailableForListIDsOptions = {
211 serverAccountId: number
212 followerActorId: number
213 includeLocalVideos: boolean
215 attributesType?: 'none' | 'id' | 'all'
218 categoryOneOf?: number[]
220 licenceOneOf?: number[]
221 languageOneOf?: string[]
228 videoChannelId?: number
230 videoPlaylistId?: number
232 trendingDays?: number
234 historyOfUser?: UserModel
236 baseWhere?: WhereOptions[]
240 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
241 const query: FindOptions = {
244 model: VideoChannelModel.scope({
246 VideoChannelScopeNames.SUMMARY, {
248 withAccountBlockerIds: options.withAccountBlockerIds
255 attributes: [ 'type', 'filename' ],
256 model: ThumbnailModel,
265 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
270 if (options.withFiles === true) {
272 model: VideoFileModel.unscoped(),
277 if (options.videoPlaylistId) {
279 model: VideoPlaylistElementModel.unscoped(),
282 videoPlaylistId: options.videoPlaylistId
289 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
290 const whereAnd = options.baseWhere ? options.baseWhere : []
292 const query: FindOptions = {
297 const attributesType = options.attributesType || 'id'
299 if (attributesType === 'id') query.attributes = [ 'id' ]
300 else if (attributesType === 'none') query.attributes = [ ]
304 [ Op.notIn ]: Sequelize.literal(
305 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
310 if (options.serverAccountId) {
313 [ Op.notIn ]: Sequelize.literal(
315 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
316 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
324 // Only list public/published videos
325 if (!options.filter || options.filter !== 'all-local') {
326 const privacyWhere = {
327 // Always list public videos
328 privacy: VideoPrivacy.PUBLIC,
329 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
332 state: VideoState.PUBLISHED
336 state: VideoState.TO_TRANSCODE,
337 waitTranscoding: false
343 whereAnd.push(privacyWhere)
346 if (options.videoPlaylistId) {
349 model: VideoPlaylistElementModel.unscoped(),
352 videoPlaylistId: options.videoPlaylistId
356 query.subQuery = false
359 if (options.filter || options.accountId || options.videoChannelId) {
360 const videoChannelInclude: IncludeOptions = {
362 model: VideoChannelModel.unscoped(),
366 if (options.videoChannelId) {
367 videoChannelInclude.where = {
368 id: options.videoChannelId
372 if (options.filter || options.accountId) {
373 const accountInclude: IncludeOptions = {
375 model: AccountModel.unscoped(),
379 if (options.filter) {
380 accountInclude.include = [
383 model: ActorModel.unscoped(),
385 where: VideoModel.buildActorWhereWithFilter(options.filter)
390 if (options.accountId) {
391 accountInclude.where = { id: options.accountId }
394 videoChannelInclude.include = [ accountInclude ]
397 query.include.push(videoChannelInclude)
400 if (options.followerActorId) {
401 let localVideosReq = ''
402 if (options.includeLocalVideos === true) {
403 localVideosReq = ' UNION ALL ' +
404 'SELECT "video"."id" AS "id" FROM "video" ' +
405 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
406 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
407 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
408 'WHERE "actor"."serverId" IS NULL'
411 // Force actorId to be a number to avoid SQL injections
412 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
415 [ Op.in ]: Sequelize.literal(
417 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
418 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
419 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
421 'SELECT "video"."id" AS "id" FROM "video" ' +
422 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
423 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
424 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
425 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
426 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
434 if (options.withFiles === true) {
437 [ Op.in ]: Sequelize.literal(
438 '(SELECT "videoId" FROM "videoFile")'
444 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
445 if (options.tagsAllOf || options.tagsOneOf) {
446 if (options.tagsOneOf) {
449 [ Op.in ]: Sequelize.literal(
451 'SELECT "videoId" FROM "videoTag" ' +
452 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
453 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
460 if (options.tagsAllOf) {
463 [ Op.in ]: Sequelize.literal(
465 'SELECT "videoId" FROM "videoTag" ' +
466 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
467 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
468 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
476 if (options.nsfw === true || options.nsfw === false) {
477 whereAnd.push({ nsfw: options.nsfw })
480 if (options.categoryOneOf) {
483 [ Op.or ]: options.categoryOneOf
488 if (options.licenceOneOf) {
491 [ Op.or ]: options.licenceOneOf
496 if (options.languageOneOf) {
497 let videoLanguages = options.languageOneOf
498 if (options.languageOneOf.find(l => l === '_unknown')) {
499 videoLanguages = videoLanguages.concat([ null ])
506 [ Op.or ]: videoLanguages
511 [ Op.in ]: Sequelize.literal(
513 'SELECT "videoId" FROM "videoCaption" ' +
514 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
523 if (options.trendingDays) {
524 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
526 query.subQuery = false
529 if (options.historyOfUser) {
531 model: UserVideoHistoryModel,
534 userId: options.historyOfUser.id
538 // Even if the relation is n:m, we know that a user only have 0..1 video history
539 // So we won't have multiple rows for the same video
540 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
541 query.subQuery = false
550 [ScopeNames.WITH_BLOCKLIST]: {
553 [ ScopeNames.WITH_THUMBNAILS ]: {
556 model: ThumbnailModel,
561 [ ScopeNames.WITH_USER_ID ]: {
564 attributes: [ 'accountId' ],
565 model: VideoChannelModel.unscoped(),
569 attributes: [ 'userId' ],
570 model: AccountModel.unscoped(),
577 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
580 model: VideoChannelModel.unscoped(),
585 exclude: [ 'privateKey', 'publicKey' ]
587 model: ActorModel.unscoped(),
591 attributes: [ 'host' ],
592 model: ServerModel.unscoped(),
596 model: AvatarModel.unscoped(),
602 model: AccountModel.unscoped(),
606 model: ActorModel.unscoped(),
608 exclude: [ 'privateKey', 'publicKey' ]
613 attributes: [ 'host' ],
614 model: ServerModel.unscoped(),
618 model: AvatarModel.unscoped(),
629 [ ScopeNames.WITH_TAGS ]: {
630 include: [ TagModel ]
632 [ ScopeNames.WITH_BLACKLISTED ]: {
635 attributes: [ 'id', 'reason' ],
636 model: VideoBlacklistModel,
641 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
642 let subInclude: any[] = []
644 if (withRedundancies === true) {
647 attributes: [ 'fileUrl' ],
648 model: VideoRedundancyModel.unscoped(),
657 model: VideoFileModel.unscoped(),
658 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
665 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
666 let subInclude: any[] = []
668 if (withRedundancies === true) {
671 attributes: [ 'fileUrl' ],
672 model: VideoRedundancyModel.unscoped(),
681 model: VideoStreamingPlaylistModel.unscoped(),
682 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
689 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
692 model: ScheduleVideoUpdateModel.unscoped(),
697 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
701 attributes: [ 'currentTime' ],
702 model: UserVideoHistoryModel.unscoped(),
716 export class VideoModel extends Model<VideoModel> {
719 @Default(DataType.UUIDV4)
721 @Column(DataType.UUID)
725 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
731 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
737 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
743 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
744 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
748 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
753 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
759 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
760 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
765 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
766 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
770 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
800 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
801 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
806 commentsEnabled: boolean
810 downloadEnabled: boolean
814 waitTranscoding: boolean
818 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
829 @Default(DataType.NOW)
836 originallyPublishedAt: Date
838 @ForeignKey(() => VideoChannelModel)
842 @BelongsTo(() => VideoChannelModel, {
848 VideoChannel: VideoChannelModel
850 @BelongsToMany(() => TagModel, {
851 foreignKey: 'videoId',
852 through: () => VideoTagModel,
857 @HasMany(() => ThumbnailModel, {
865 Thumbnails: ThumbnailModel[]
867 @HasMany(() => VideoPlaylistElementModel, {
874 VideoPlaylistElements: VideoPlaylistElementModel[]
876 @HasMany(() => VideoAbuseModel, {
883 VideoAbuses: VideoAbuseModel[]
885 @HasMany(() => VideoFileModel, {
893 VideoFiles: VideoFileModel[]
895 @HasMany(() => VideoStreamingPlaylistModel, {
903 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
905 @HasMany(() => VideoShareModel, {
912 VideoShares: VideoShareModel[]
914 @HasMany(() => AccountVideoRateModel, {
921 AccountVideoRates: AccountVideoRateModel[]
923 @HasMany(() => VideoCommentModel, {
931 VideoComments: VideoCommentModel[]
933 @HasMany(() => VideoViewModel, {
940 VideoViews: VideoViewModel[]
942 @HasMany(() => UserVideoHistoryModel, {
949 UserVideoHistories: UserVideoHistoryModel[]
951 @HasOne(() => ScheduleVideoUpdateModel, {
958 ScheduleVideoUpdate: ScheduleVideoUpdateModel
960 @HasOne(() => VideoBlacklistModel, {
967 VideoBlacklist: VideoBlacklistModel
969 @HasOne(() => VideoImportModel, {
976 VideoImport: VideoImportModel
978 @HasMany(() => VideoCaptionModel, {
985 [ 'separate' as any ]: true
987 VideoCaptions: VideoCaptionModel[]
990 static async sendDelete (instance: VideoModel, options) {
991 if (instance.isOwned()) {
992 if (!instance.VideoChannel) {
993 instance.VideoChannel = await instance.$get('VideoChannel', {
997 include: [ ActorModel ]
1000 transaction: options.transaction
1001 }) as VideoChannelModel
1004 return sendDeleteVideo(instance, options.transaction)
1011 static async removeFiles (instance: VideoModel) {
1012 const tasks: Promise<any>[] = []
1014 logger.info('Removing files of video %s.', instance.url)
1016 if (instance.isOwned()) {
1017 if (!Array.isArray(instance.VideoFiles)) {
1018 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1021 // Remove physical files and torrents
1022 instance.VideoFiles.forEach(file => {
1023 tasks.push(instance.removeFile(file))
1024 tasks.push(instance.removeTorrent(file))
1027 // Remove playlists file
1028 tasks.push(instance.removeStreamingPlaylist())
1031 // Do not wait video deletion because we could be in a transaction
1034 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1040 static listLocal () {
1047 return VideoModel.scope([
1048 ScopeNames.WITH_FILES,
1049 ScopeNames.WITH_STREAMING_PLAYLISTS,
1050 ScopeNames.WITH_THUMBNAILS
1054 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1055 function getRawQuery (select: string) {
1056 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1057 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1058 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1059 'WHERE "Account"."actorId" = ' + actorId
1060 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1061 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1062 'WHERE "VideoShare"."actorId" = ' + actorId
1064 return `(${queryVideo}) UNION (${queryVideoShare})`
1067 const rawQuery = getRawQuery('"Video"."id"')
1068 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1074 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1077 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1080 { privacy: VideoPrivacy.PUBLIC },
1081 { privacy: VideoPrivacy.UNLISTED }
1086 attributes: [ 'language' ],
1087 model: VideoCaptionModel.unscoped(),
1091 attributes: [ 'id', 'url' ],
1092 model: VideoShareModel.unscoped(),
1094 // We only want videos shared by this actor
1109 attributes: [ 'id', 'url' ],
1110 model: ActorModel.unscoped()
1115 model: VideoChannelModel.unscoped(),
1119 attributes: [ 'name' ],
1120 model: AccountModel.unscoped(),
1124 attributes: [ 'id', 'url', 'followersUrl' ],
1125 model: ActorModel.unscoped(),
1131 attributes: [ 'id', 'url', 'followersUrl' ],
1132 model: ActorModel.unscoped(),
1142 return Bluebird.all([
1143 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1144 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1145 ]).then(([ rows, totals ]) => {
1146 // totals: totalVideos + totalVideoShares
1148 let totalVideoShares = 0
1149 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1150 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1152 const total = totalVideos + totalVideoShares
1160 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1161 function buildBaseQuery (): FindOptions {
1165 order: getVideoSort(sort),
1168 model: VideoChannelModel,
1172 model: AccountModel,
1184 const countQuery = buildBaseQuery()
1185 const findQuery = buildBaseQuery()
1187 const findScopes = [
1188 ScopeNames.WITH_SCHEDULED_UPDATE,
1189 ScopeNames.WITH_BLACKLISTED,
1190 ScopeNames.WITH_THUMBNAILS
1193 if (withFiles === true) {
1194 findQuery.include.push({
1195 model: VideoFileModel.unscoped(),
1200 return Promise.all([
1201 VideoModel.count(countQuery),
1202 VideoModel.scope(findScopes).findAll(findQuery)
1203 ]).then(([ count, rows ]) => {
1211 static async listForApi (options: {
1216 includeLocalVideos: boolean,
1218 categoryOneOf?: number[],
1219 licenceOneOf?: number[],
1220 languageOneOf?: string[],
1221 tagsOneOf?: string[],
1222 tagsAllOf?: string[],
1223 filter?: VideoFilter,
1225 videoChannelId?: number,
1226 followerActorId?: number
1227 videoPlaylistId?: number,
1228 trendingDays?: number,
1230 historyOfUser?: UserModel
1231 }, countVideos = true) {
1232 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1233 throw new Error('Try to filter all-local but no user has not the see all videos right')
1236 const query: FindOptions & { where?: null } = {
1237 offset: options.start,
1238 limit: options.count,
1239 order: getVideoSort(options.sort)
1242 let trendingDays: number
1243 if (options.sort.endsWith('trending')) {
1244 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1246 query.group = 'VideoModel.id'
1249 const serverActor = await getServerActor()
1251 // followerActorId === null has a meaning, so just check undefined
1252 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1254 const queryOptions = {
1256 serverAccountId: serverActor.Account.id,
1258 categoryOneOf: options.categoryOneOf,
1259 licenceOneOf: options.licenceOneOf,
1260 languageOneOf: options.languageOneOf,
1261 tagsOneOf: options.tagsOneOf,
1262 tagsAllOf: options.tagsAllOf,
1263 filter: options.filter,
1264 withFiles: options.withFiles,
1265 accountId: options.accountId,
1266 videoChannelId: options.videoChannelId,
1267 videoPlaylistId: options.videoPlaylistId,
1268 includeLocalVideos: options.includeLocalVideos,
1270 historyOfUser: options.historyOfUser,
1274 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1277 static async searchAndPopulateAccountAndServer (options: {
1278 includeLocalVideos: boolean
1283 startDate?: string // ISO 8601
1284 endDate?: string // ISO 8601
1285 originallyPublishedStartDate?: string
1286 originallyPublishedEndDate?: string
1288 categoryOneOf?: number[]
1289 licenceOneOf?: number[]
1290 languageOneOf?: string[]
1291 tagsOneOf?: string[]
1292 tagsAllOf?: string[]
1293 durationMin?: number // seconds
1294 durationMax?: number // seconds
1296 filter?: VideoFilter
1300 if (options.startDate || options.endDate) {
1301 const publishedAtRange = {}
1303 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1304 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1306 whereAnd.push({ publishedAt: publishedAtRange })
1309 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1310 const originallyPublishedAtRange = {}
1312 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1313 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1315 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1318 if (options.durationMin || options.durationMax) {
1319 const durationRange = {}
1321 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1322 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1324 whereAnd.push({ duration: durationRange })
1327 const attributesInclude = []
1328 const escapedSearch = VideoModel.sequelize.escape(options.search)
1329 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1330 if (options.search) {
1334 [ Op.in ]: Sequelize.literal(
1336 'SELECT "video"."id" FROM "video" ' +
1338 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1339 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1341 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1342 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1343 'WHERE "tag"."name" = ' + escapedSearch +
1350 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1353 // Cannot search on similarity if we don't have a search
1354 if (!options.search) {
1355 attributesInclude.push(
1356 Sequelize.literal('0 as similarity')
1362 include: attributesInclude
1364 offset: options.start,
1365 limit: options.count,
1366 order: getVideoSort(options.sort)
1369 const serverActor = await getServerActor()
1370 const queryOptions = {
1371 followerActorId: serverActor.id,
1372 serverAccountId: serverActor.Account.id,
1373 includeLocalVideos: options.includeLocalVideos,
1375 categoryOneOf: options.categoryOneOf,
1376 licenceOneOf: options.licenceOneOf,
1377 languageOneOf: options.languageOneOf,
1378 tagsOneOf: options.tagsOneOf,
1379 tagsAllOf: options.tagsAllOf,
1381 filter: options.filter,
1385 return VideoModel.getAvailableForApi(query, queryOptions)
1388 static load (id: number | string, t?: Transaction) {
1389 const where = buildWhereIdOrUUID(id)
1395 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1398 static loadWithRights (id: number | string, t?: Transaction) {
1399 const where = buildWhereIdOrUUID(id)
1405 return VideoModel.scope([
1406 ScopeNames.WITH_BLACKLISTED,
1407 ScopeNames.WITH_USER_ID,
1408 ScopeNames.WITH_THUMBNAILS
1412 static loadOnlyId (id: number | string, t?: Transaction) {
1413 const where = buildWhereIdOrUUID(id)
1416 attributes: [ 'id' ],
1421 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1424 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1425 return VideoModel.scope([
1426 ScopeNames.WITH_FILES,
1427 ScopeNames.WITH_STREAMING_PLAYLISTS,
1428 ScopeNames.WITH_THUMBNAILS
1429 ]).findByPk(id, { transaction: t, logging })
1432 static loadByUUIDWithFile (uuid: string) {
1439 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1442 static loadByUrl (url: string, transaction?: Transaction) {
1443 const query: FindOptions = {
1450 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1453 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1454 const query: FindOptions = {
1461 return VideoModel.scope([
1462 ScopeNames.WITH_ACCOUNT_DETAILS,
1463 ScopeNames.WITH_FILES,
1464 ScopeNames.WITH_STREAMING_PLAYLISTS,
1465 ScopeNames.WITH_THUMBNAILS
1469 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1470 const where = buildWhereIdOrUUID(id)
1473 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1478 const scopes: (string | ScopeOptions)[] = [
1479 ScopeNames.WITH_TAGS,
1480 ScopeNames.WITH_BLACKLISTED,
1481 ScopeNames.WITH_ACCOUNT_DETAILS,
1482 ScopeNames.WITH_SCHEDULED_UPDATE,
1483 ScopeNames.WITH_FILES,
1484 ScopeNames.WITH_STREAMING_PLAYLISTS,
1485 ScopeNames.WITH_THUMBNAILS
1489 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1497 static loadForGetAPI (parameters: {
1498 id: number | string,
1502 const { id, t, userId } = parameters
1503 const where = buildWhereIdOrUUID(id)
1506 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1511 const scopes: (string | ScopeOptions)[] = [
1512 ScopeNames.WITH_TAGS,
1513 ScopeNames.WITH_BLACKLISTED,
1514 ScopeNames.WITH_ACCOUNT_DETAILS,
1515 ScopeNames.WITH_SCHEDULED_UPDATE,
1516 ScopeNames.WITH_THUMBNAILS,
1517 { method: [ ScopeNames.WITH_FILES, true ] },
1518 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1522 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1530 static async getStats () {
1531 const totalLocalVideos = await VideoModel.count({
1536 const totalVideos = await VideoModel.count()
1538 let totalLocalVideoViews = await VideoModel.sum('views', {
1543 // Sequelize could return null...
1544 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1548 totalLocalVideoViews,
1553 static incrementViews (id: number, views: number) {
1554 return VideoModel.increment('views', {
1562 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1563 // Instances only share videos
1564 const query = 'SELECT 1 FROM "videoShare" ' +
1565 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1566 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1570 type: QueryTypes.SELECT,
1571 bind: { followerActorId, videoId },
1575 return VideoModel.sequelize.query(query, options)
1576 .then(results => results.length === 1)
1579 static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) {
1582 channelId: videoChannel.id
1587 return VideoModel.update({ support: videoChannel.support }, options)
1590 static getAllIdsFromChannel (videoChannel: VideoChannelModel) {
1592 attributes: [ 'id' ],
1594 channelId: videoChannel.id
1598 return VideoModel.findAll(query)
1599 .then(videos => videos.map(v => v.id))
1602 // threshold corresponds to how many video the field should have to be returned
1603 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1604 const serverActor = await getServerActor()
1605 const followerActorId = serverActor.id
1607 const scopeOptions: AvailableForListIDsOptions = {
1608 serverAccountId: serverActor.Account.id,
1610 includeLocalVideos: true,
1611 attributesType: 'none' // Don't break aggregation
1614 const query: FindOptions = {
1615 attributes: [ field ],
1618 having: Sequelize.where(
1619 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1621 order: [ (this.sequelize as any).random() ]
1624 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1626 .then(rows => rows.map(r => r[ field ]))
1629 static buildTrendingQuery (trendingDays: number) {
1633 model: VideoViewModel,
1637 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1643 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1644 if (filter && (filter === 'local' || filter === 'all-local')) {
1653 private static async getAvailableForApi (
1654 query: FindOptions & { where?: null }, // Forbid where field in query
1655 options: AvailableForListIDsOptions,
1658 const idsScope: ScopeOptions = {
1660 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1664 // Remove trending sort on count, because it uses a group by
1665 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1666 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1667 const countScope: ScopeOptions = {
1669 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1673 const [ count, ids ] = await Promise.all([
1675 ? VideoModel.scope(countScope).count(countQuery)
1676 : Promise.resolve<number>(undefined),
1678 VideoModel.scope(idsScope)
1680 .then(rows => rows.map(r => r.id))
1683 if (ids.length === 0) return { data: [], total: count }
1685 const secondQuery: FindOptions = {
1688 attributes: query.attributes,
1689 order: [ // Keep original order
1691 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1696 const apiScope: (string | ScopeOptions)[] = []
1699 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1704 ScopeNames.FOR_API, {
1706 withFiles: options.withFiles,
1707 videoPlaylistId: options.videoPlaylistId
1712 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1720 static getCategoryLabel (id: number) {
1721 return VIDEO_CATEGORIES[ id ] || 'Misc'
1724 static getLicenceLabel (id: number) {
1725 return VIDEO_LICENCES[ id ] || 'Unknown'
1728 static getLanguageLabel (id: string) {
1729 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1732 static getPrivacyLabel (id: number) {
1733 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1736 static getStateLabel (id: number) {
1737 return VIDEO_STATES[ id ] || 'Unknown'
1741 return !!this.VideoBlacklist
1745 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1746 this.VideoChannel.Account.isBlocked()
1749 getOriginalFile () {
1750 if (Array.isArray(this.VideoFiles) === false) return undefined
1752 // The original file is the file that have the higher resolution
1753 return maxBy(this.VideoFiles, file => file.resolution)
1756 getFile (resolution: VideoResolution) {
1757 if (Array.isArray(this.VideoFiles) === false) return undefined
1759 return this.VideoFiles.find(f => f.resolution === resolution)
1762 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1763 thumbnail.videoId = this.id
1765 const savedThumbnail = await thumbnail.save({ transaction })
1767 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1769 // Already have this thumbnail, skip
1770 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1772 this.Thumbnails.push(savedThumbnail)
1775 getVideoFilename (videoFile: VideoFileModel) {
1776 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1779 generateThumbnailName () {
1780 return this.uuid + '.jpg'
1784 if (Array.isArray(this.Thumbnails) === false) return undefined
1786 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1789 generatePreviewName () {
1790 return this.uuid + '.jpg'
1794 if (Array.isArray(this.Thumbnails) === false) return undefined
1796 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1799 getTorrentFileName (videoFile: VideoFileModel) {
1800 const extension = '.torrent'
1801 return this.uuid + '-' + videoFile.resolution + extension
1805 return this.remote === false
1808 getTorrentFilePath (videoFile: VideoFileModel) {
1809 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1812 getVideoFilePath (videoFile: VideoFileModel) {
1813 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1816 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1818 // Keep the extname, it's used by the client to stream the file inside a web browser
1819 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1820 createdBy: 'PeerTube',
1822 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1823 [ WEBSERVER.URL + '/tracker/announce' ]
1825 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1828 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1830 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1831 logger.info('Creating torrent %s.', filePath)
1833 await writeFile(filePath, torrent)
1835 const parsedTorrent = parseTorrent(torrent)
1836 videoFile.infoHash = parsedTorrent.infoHash
1839 getWatchStaticPath () {
1840 return '/videos/watch/' + this.uuid
1843 getEmbedStaticPath () {
1844 return '/videos/embed/' + this.uuid
1847 getMiniatureStaticPath () {
1848 const thumbnail = this.getMiniature()
1849 if (!thumbnail) return null
1851 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1854 getPreviewStaticPath () {
1855 const preview = this.getPreview()
1856 if (!preview) return null
1858 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1859 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1862 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1863 return videoModelToFormattedJSON(this, options)
1866 toFormattedDetailsJSON (): VideoDetails {
1867 return videoModelToFormattedDetailsJSON(this)
1870 getFormattedVideoFilesJSON (): VideoFile[] {
1871 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1874 toActivityPubObject (): VideoTorrentObject {
1875 return videoModelToActivityPubObject(this)
1878 getTruncatedDescription () {
1879 if (!this.description) return null
1881 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1882 return peertubeTruncate(this.description, maxLength)
1885 getOriginalFileResolution () {
1886 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1888 return getVideoFileResolution(originalFilePath)
1891 getDescriptionAPIPath () {
1892 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1895 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1896 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1898 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1899 return remove(filePath)
1900 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1903 removeTorrent (videoFile: VideoFileModel) {
1904 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1905 return remove(torrentPath)
1906 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1909 removeStreamingPlaylist (isRedundancy = false) {
1910 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1912 const filePath = join(baseDir, this.uuid)
1913 return remove(filePath)
1914 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1918 if (this.isOwned()) return false
1920 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1924 this.changed('updatedAt', true)
1933 if (this.isOwned()) {
1934 baseUrlHttp = WEBSERVER.URL
1935 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1937 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1938 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1941 return { baseUrlHttp, baseUrlWs }
1944 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1945 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1946 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1947 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1949 const redundancies = videoFile.RedundancyVideos
1950 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1952 const magnetHash = {
1956 infoHash: videoFile.infoHash,
1960 return magnetUtil.encode(magnetHash)
1963 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1964 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1967 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1968 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1971 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1972 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1975 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1976 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1979 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1980 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1983 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1984 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1987 getBandwidthBits (videoFile: VideoFileModel) {
1988 return Math.ceil((videoFile.size * 8) / this.duration)