1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
38 } from 'sequelize-typescript'
39 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
40 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
56 } from '../../helpers/custom-validators/videos'
57 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
58 import { logger } from '../../helpers/logger'
59 import { getServerActor } from '../../helpers/utils'
64 HLS_REDUNDANCY_DIRECTORY,
65 HLS_STREAMING_PLAYLIST_DIRECTORY,
68 STATIC_DOWNLOAD_PATHS,
76 } from '../../initializers/constants'
77 import { sendDeleteVideo } from '../../lib/activitypub/send'
78 import { AccountModel } from '../account/account'
79 import { AccountVideoRateModel } from '../account/account-video-rate'
80 import { ActorModel } from '../activitypub/actor'
81 import { AvatarModel } from '../avatar/avatar'
82 import { ServerModel } from '../server/server'
84 buildBlockedAccountSQL,
85 buildTrigramSearchIndex,
88 createSimilarityAttribute,
93 import { TagModel } from './tag'
94 import { VideoAbuseModel } from './video-abuse'
95 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
96 import { VideoCommentModel } from './video-comment'
97 import { VideoFileModel } from './video-file'
98 import { VideoShareModel } from './video-share'
99 import { VideoTagModel } from './video-tag'
100 import { ScheduleVideoUpdateModel } from './schedule-video-update'
101 import { VideoCaptionModel } from './video-caption'
102 import { VideoBlacklistModel } from './video-blacklist'
103 import { remove, writeFile } from 'fs-extra'
104 import { VideoViewModel } from './video-views'
105 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 videoFilesModelToFormattedJSON,
108 VideoFormattingJSONOptions,
109 videoModelToActivityPubObject,
110 videoModelToFormattedDetailsJSON,
111 videoModelToFormattedJSON
112 } from './video-format-utils'
113 import { UserVideoHistoryModel } from '../account/user-video-history'
114 import { VideoImportModel } from './video-import'
115 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
116 import { VideoPlaylistElementModel } from './video-playlist-element'
117 import { CONFIG } from '../../initializers/config'
118 import { ThumbnailModel } from './thumbnail'
119 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 import { createTorrentPromise } from '../../helpers/webtorrent'
121 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
124 MChannelAccountDefault,
129 MVideoAccountLightBlacklistAllFiles,
133 MVideoFormattableDetails,
138 MVideoThumbnailBlacklist,
142 } from '../../typings/models'
143 import { MVideoFile, MVideoFileRedundanciesOpt } from '../../typings/models/video/video-file'
144 import { MThumbnail } from '../../typings/models/video/thumbnail'
146 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
147 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
148 buildTrigramSearchIndex('video_name_trigram', 'name'),
150 { fields: [ 'createdAt' ] },
151 { fields: [ 'publishedAt' ] },
152 { fields: [ 'duration' ] },
153 { fields: [ 'views' ] },
154 { fields: [ 'channelId' ] },
156 fields: [ 'originallyPublishedAt' ],
158 originallyPublishedAt: {
164 fields: [ 'category' ], // We don't care videos with an unknown category
172 fields: [ 'licence' ], // We don't care videos with an unknown licence
180 fields: [ 'language' ], // We don't care videos with an unknown language
188 fields: [ 'nsfw' ], // Most of the videos are not NSFW
194 fields: [ 'remote' ], // Only index local videos
209 export enum ScopeNames {
210 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
212 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
213 WITH_TAGS = 'WITH_TAGS',
214 WITH_FILES = 'WITH_FILES',
215 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
216 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
217 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
218 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
219 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
220 WITH_USER_ID = 'WITH_USER_ID',
221 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
224 export type ForAPIOptions = {
227 videoPlaylistId?: number
231 withAccountBlockerIds?: number[]
234 export type AvailableForListIDsOptions = {
235 serverAccountId: number
236 followerActorId: number
237 includeLocalVideos: boolean
239 attributesType?: 'none' | 'id' | 'all'
242 categoryOneOf?: number[]
244 licenceOneOf?: number[]
245 languageOneOf?: string[]
252 videoChannelId?: number
254 videoPlaylistId?: number
256 trendingDays?: number
257 user?: MUserAccountId
258 historyOfUser?: MUserId
260 baseWhere?: WhereOptions[]
264 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
265 const query: FindOptions = {
268 model: VideoChannelModel.scope({
270 VideoChannelScopeNames.SUMMARY, {
272 withAccountBlockerIds: options.withAccountBlockerIds
279 attributes: [ 'type', 'filename' ],
280 model: ThumbnailModel,
289 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
294 if (options.withFiles === true) {
296 model: VideoFileModel.unscoped(),
301 if (options.videoPlaylistId) {
303 model: VideoPlaylistElementModel.unscoped(),
306 videoPlaylistId: options.videoPlaylistId
313 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
314 const whereAnd = options.baseWhere ? options.baseWhere : []
316 const query: FindOptions = {
321 const attributesType = options.attributesType || 'id'
323 if (attributesType === 'id') query.attributes = [ 'id' ]
324 else if (attributesType === 'none') query.attributes = [ ]
328 [ Op.notIn ]: Sequelize.literal(
329 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
334 if (options.serverAccountId) {
337 [ Op.notIn ]: Sequelize.literal(
339 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
340 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
348 // Only list public/published videos
349 if (!options.filter || options.filter !== 'all-local') {
350 const privacyWhere = {
351 // Always list public videos
352 privacy: VideoPrivacy.PUBLIC,
353 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
356 state: VideoState.PUBLISHED
360 state: VideoState.TO_TRANSCODE,
361 waitTranscoding: false
367 whereAnd.push(privacyWhere)
370 if (options.videoPlaylistId) {
373 model: VideoPlaylistElementModel.unscoped(),
376 videoPlaylistId: options.videoPlaylistId
380 query.subQuery = false
383 if (options.filter || options.accountId || options.videoChannelId) {
384 const videoChannelInclude: IncludeOptions = {
386 model: VideoChannelModel.unscoped(),
390 if (options.videoChannelId) {
391 videoChannelInclude.where = {
392 id: options.videoChannelId
396 if (options.filter || options.accountId) {
397 const accountInclude: IncludeOptions = {
399 model: AccountModel.unscoped(),
403 if (options.filter) {
404 accountInclude.include = [
407 model: ActorModel.unscoped(),
409 where: VideoModel.buildActorWhereWithFilter(options.filter)
414 if (options.accountId) {
415 accountInclude.where = { id: options.accountId }
418 videoChannelInclude.include = [ accountInclude ]
421 query.include.push(videoChannelInclude)
424 if (options.followerActorId) {
425 let localVideosReq = ''
426 if (options.includeLocalVideos === true) {
427 localVideosReq = ' UNION ALL ' +
428 'SELECT "video"."id" AS "id" FROM "video" ' +
429 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
430 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
431 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
432 'WHERE "actor"."serverId" IS NULL'
435 // Force actorId to be a number to avoid SQL injections
436 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
439 [ Op.in ]: Sequelize.literal(
441 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
442 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
443 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
445 'SELECT "video"."id" AS "id" FROM "video" ' +
446 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
447 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
448 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
449 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
450 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
458 if (options.withFiles === true) {
461 [ Op.in ]: Sequelize.literal(
462 '(SELECT "videoId" FROM "videoFile")'
468 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
469 if (options.tagsAllOf || options.tagsOneOf) {
470 if (options.tagsOneOf) {
471 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
475 [ Op.in ]: Sequelize.literal(
477 'SELECT "videoId" FROM "videoTag" ' +
478 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
479 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
486 if (options.tagsAllOf) {
487 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
491 [ Op.in ]: Sequelize.literal(
493 'SELECT "videoId" FROM "videoTag" ' +
494 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
495 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
496 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
504 if (options.nsfw === true || options.nsfw === false) {
505 whereAnd.push({ nsfw: options.nsfw })
508 if (options.categoryOneOf) {
511 [ Op.or ]: options.categoryOneOf
516 if (options.licenceOneOf) {
519 [ Op.or ]: options.licenceOneOf
524 if (options.languageOneOf) {
525 let videoLanguages = options.languageOneOf
526 if (options.languageOneOf.find(l => l === '_unknown')) {
527 videoLanguages = videoLanguages.concat([ null ])
534 [ Op.or ]: videoLanguages
539 [ Op.in ]: Sequelize.literal(
541 'SELECT "videoId" FROM "videoCaption" ' +
542 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
551 if (options.trendingDays) {
552 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
554 query.subQuery = false
557 if (options.historyOfUser) {
559 model: UserVideoHistoryModel,
562 userId: options.historyOfUser.id
566 // Even if the relation is n:m, we know that a user only have 0..1 video history
567 // So we won't have multiple rows for the same video
568 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
569 query.subQuery = false
578 [ScopeNames.WITH_BLOCKLIST]: {
581 [ ScopeNames.WITH_THUMBNAILS ]: {
584 model: ThumbnailModel,
589 [ ScopeNames.WITH_USER_ID ]: {
592 attributes: [ 'accountId' ],
593 model: VideoChannelModel.unscoped(),
597 attributes: [ 'userId' ],
598 model: AccountModel.unscoped(),
605 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
608 model: VideoChannelModel.unscoped(),
613 exclude: [ 'privateKey', 'publicKey' ]
615 model: ActorModel.unscoped(),
619 attributes: [ 'host' ],
620 model: ServerModel.unscoped(),
624 model: AvatarModel.unscoped(),
630 model: AccountModel.unscoped(),
634 model: ActorModel.unscoped(),
636 exclude: [ 'privateKey', 'publicKey' ]
641 attributes: [ 'host' ],
642 model: ServerModel.unscoped(),
646 model: AvatarModel.unscoped(),
657 [ ScopeNames.WITH_TAGS ]: {
658 include: [ TagModel ]
660 [ ScopeNames.WITH_BLACKLISTED ]: {
663 attributes: [ 'id', 'reason', 'unfederated' ],
664 model: VideoBlacklistModel,
669 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
670 let subInclude: any[] = []
672 if (withRedundancies === true) {
675 attributes: [ 'fileUrl' ],
676 model: VideoRedundancyModel.unscoped(),
685 model: VideoFileModel.unscoped(),
686 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
693 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
694 let subInclude: any[] = []
696 if (withRedundancies === true) {
699 attributes: [ 'fileUrl' ],
700 model: VideoRedundancyModel.unscoped(),
709 model: VideoStreamingPlaylistModel.unscoped(),
710 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
717 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
720 model: ScheduleVideoUpdateModel.unscoped(),
725 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
729 attributes: [ 'currentTime' ],
730 model: UserVideoHistoryModel.unscoped(),
744 export class VideoModel extends Model<VideoModel> {
747 @Default(DataType.UUIDV4)
749 @Column(DataType.UUID)
753 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
759 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
765 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
771 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
772 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
776 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
781 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
787 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
788 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
793 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
794 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
798 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
828 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
829 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
834 commentsEnabled: boolean
838 downloadEnabled: boolean
842 waitTranscoding: boolean
846 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
857 @Default(DataType.NOW)
864 originallyPublishedAt: Date
866 @ForeignKey(() => VideoChannelModel)
870 @BelongsTo(() => VideoChannelModel, {
876 VideoChannel: VideoChannelModel
878 @BelongsToMany(() => TagModel, {
879 foreignKey: 'videoId',
880 through: () => VideoTagModel,
885 @HasMany(() => ThumbnailModel, {
893 Thumbnails: ThumbnailModel[]
895 @HasMany(() => VideoPlaylistElementModel, {
902 VideoPlaylistElements: VideoPlaylistElementModel[]
904 @HasMany(() => VideoAbuseModel, {
911 VideoAbuses: VideoAbuseModel[]
913 @HasMany(() => VideoFileModel, {
921 VideoFiles: VideoFileModel[]
923 @HasMany(() => VideoStreamingPlaylistModel, {
931 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
933 @HasMany(() => VideoShareModel, {
940 VideoShares: VideoShareModel[]
942 @HasMany(() => AccountVideoRateModel, {
949 AccountVideoRates: AccountVideoRateModel[]
951 @HasMany(() => VideoCommentModel, {
959 VideoComments: VideoCommentModel[]
961 @HasMany(() => VideoViewModel, {
968 VideoViews: VideoViewModel[]
970 @HasMany(() => UserVideoHistoryModel, {
977 UserVideoHistories: UserVideoHistoryModel[]
979 @HasOne(() => ScheduleVideoUpdateModel, {
986 ScheduleVideoUpdate: ScheduleVideoUpdateModel
988 @HasOne(() => VideoBlacklistModel, {
995 VideoBlacklist: VideoBlacklistModel
997 @HasOne(() => VideoImportModel, {
1002 onDelete: 'set null'
1004 VideoImport: VideoImportModel
1006 @HasMany(() => VideoCaptionModel, {
1011 onDelete: 'cascade',
1013 [ 'separate' as any ]: true
1015 VideoCaptions: VideoCaptionModel[]
1018 static async sendDelete (instance: MVideoAccountLight, options) {
1019 if (instance.isOwned()) {
1020 if (!instance.VideoChannel) {
1021 instance.VideoChannel = await instance.$get('VideoChannel', {
1026 transaction: options.transaction
1027 }) as MChannelAccountDefault
1030 return sendDeleteVideo(instance, options.transaction)
1037 static async removeFiles (instance: VideoModel) {
1038 const tasks: Promise<any>[] = []
1040 logger.info('Removing files of video %s.', instance.url)
1042 if (instance.isOwned()) {
1043 if (!Array.isArray(instance.VideoFiles)) {
1044 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1047 // Remove physical files and torrents
1048 instance.VideoFiles.forEach(file => {
1049 tasks.push(instance.removeFile(file))
1050 tasks.push(instance.removeTorrent(file))
1053 // Remove playlists file
1054 tasks.push(instance.removeStreamingPlaylist())
1057 // Do not wait video deletion because we could be in a transaction
1060 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1066 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1073 return VideoModel.scope([
1074 ScopeNames.WITH_FILES,
1075 ScopeNames.WITH_STREAMING_PLAYLISTS,
1076 ScopeNames.WITH_THUMBNAILS
1080 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1081 function getRawQuery (select: string) {
1082 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1083 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1084 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1085 'WHERE "Account"."actorId" = ' + actorId
1086 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1087 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1088 'WHERE "VideoShare"."actorId" = ' + actorId
1090 return `(${queryVideo}) UNION (${queryVideoShare})`
1093 const rawQuery = getRawQuery('"Video"."id"')
1094 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1100 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1103 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1106 { privacy: VideoPrivacy.PUBLIC },
1107 { privacy: VideoPrivacy.UNLISTED }
1112 attributes: [ 'language' ],
1113 model: VideoCaptionModel.unscoped(),
1117 attributes: [ 'id', 'url' ],
1118 model: VideoShareModel.unscoped(),
1120 // We only want videos shared by this actor
1135 attributes: [ 'id', 'url' ],
1136 model: ActorModel.unscoped()
1141 model: VideoChannelModel.unscoped(),
1145 attributes: [ 'name' ],
1146 model: AccountModel.unscoped(),
1150 attributes: [ 'id', 'url', 'followersUrl' ],
1151 model: ActorModel.unscoped(),
1157 attributes: [ 'id', 'url', 'followersUrl' ],
1158 model: ActorModel.unscoped(),
1168 return Bluebird.all([
1169 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1170 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1171 ]).then(([ rows, totals ]) => {
1172 // totals: totalVideos + totalVideoShares
1174 let totalVideoShares = 0
1175 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1176 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1178 const total = totalVideos + totalVideoShares
1186 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1187 function buildBaseQuery (): FindOptions {
1191 order: getVideoSort(sort),
1194 model: VideoChannelModel,
1198 model: AccountModel,
1210 const countQuery = buildBaseQuery()
1211 const findQuery = buildBaseQuery()
1213 const findScopes = [
1214 ScopeNames.WITH_SCHEDULED_UPDATE,
1215 ScopeNames.WITH_BLACKLISTED,
1216 ScopeNames.WITH_THUMBNAILS
1219 return Promise.all([
1220 VideoModel.count(countQuery),
1221 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1222 ]).then(([ count, rows ]) => {
1230 static async listForApi (options: {
1235 includeLocalVideos: boolean,
1237 categoryOneOf?: number[],
1238 licenceOneOf?: number[],
1239 languageOneOf?: string[],
1240 tagsOneOf?: string[],
1241 tagsAllOf?: string[],
1242 filter?: VideoFilter,
1244 videoChannelId?: number,
1245 followerActorId?: number
1246 videoPlaylistId?: number,
1247 trendingDays?: number,
1248 user?: MUserAccountId,
1249 historyOfUser?: MUserId
1250 }, countVideos = true) {
1251 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1252 throw new Error('Try to filter all-local but no user has not the see all videos right')
1255 const query: FindOptions & { where?: null } = {
1256 offset: options.start,
1257 limit: options.count,
1258 order: getVideoSort(options.sort)
1261 let trendingDays: number
1262 if (options.sort.endsWith('trending')) {
1263 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1265 query.group = 'VideoModel.id'
1268 const serverActor = await getServerActor()
1270 // followerActorId === null has a meaning, so just check undefined
1271 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1273 const queryOptions = {
1275 serverAccountId: serverActor.Account.id,
1277 categoryOneOf: options.categoryOneOf,
1278 licenceOneOf: options.licenceOneOf,
1279 languageOneOf: options.languageOneOf,
1280 tagsOneOf: options.tagsOneOf,
1281 tagsAllOf: options.tagsAllOf,
1282 filter: options.filter,
1283 withFiles: options.withFiles,
1284 accountId: options.accountId,
1285 videoChannelId: options.videoChannelId,
1286 videoPlaylistId: options.videoPlaylistId,
1287 includeLocalVideos: options.includeLocalVideos,
1289 historyOfUser: options.historyOfUser,
1293 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1296 static async searchAndPopulateAccountAndServer (options: {
1297 includeLocalVideos: boolean
1302 startDate?: string // ISO 8601
1303 endDate?: string // ISO 8601
1304 originallyPublishedStartDate?: string
1305 originallyPublishedEndDate?: string
1307 categoryOneOf?: number[]
1308 licenceOneOf?: number[]
1309 languageOneOf?: string[]
1310 tagsOneOf?: string[]
1311 tagsAllOf?: string[]
1312 durationMin?: number // seconds
1313 durationMax?: number // seconds
1314 user?: MUserAccountId,
1315 filter?: VideoFilter
1319 if (options.startDate || options.endDate) {
1320 const publishedAtRange = {}
1322 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1323 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1325 whereAnd.push({ publishedAt: publishedAtRange })
1328 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1329 const originallyPublishedAtRange = {}
1331 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1332 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1334 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1337 if (options.durationMin || options.durationMax) {
1338 const durationRange = {}
1340 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1341 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1343 whereAnd.push({ duration: durationRange })
1346 const attributesInclude = []
1347 const escapedSearch = VideoModel.sequelize.escape(options.search)
1348 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1349 if (options.search) {
1353 [ Op.in ]: Sequelize.literal(
1355 'SELECT "video"."id" FROM "video" ' +
1357 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1358 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1360 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1361 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1362 'WHERE "tag"."name" = ' + escapedSearch +
1369 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1372 // Cannot search on similarity if we don't have a search
1373 if (!options.search) {
1374 attributesInclude.push(
1375 Sequelize.literal('0 as similarity')
1381 include: attributesInclude
1383 offset: options.start,
1384 limit: options.count,
1385 order: getVideoSort(options.sort)
1388 const serverActor = await getServerActor()
1389 const queryOptions = {
1390 followerActorId: serverActor.id,
1391 serverAccountId: serverActor.Account.id,
1392 includeLocalVideos: options.includeLocalVideos,
1394 categoryOneOf: options.categoryOneOf,
1395 licenceOneOf: options.licenceOneOf,
1396 languageOneOf: options.languageOneOf,
1397 tagsOneOf: options.tagsOneOf,
1398 tagsAllOf: options.tagsAllOf,
1400 filter: options.filter,
1404 return VideoModel.getAvailableForApi(query, queryOptions)
1407 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1408 const where = buildWhereIdOrUUID(id)
1414 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1417 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1418 const where = buildWhereIdOrUUID(id)
1424 return VideoModel.scope([
1425 ScopeNames.WITH_THUMBNAILS,
1426 ScopeNames.WITH_BLACKLISTED
1430 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1431 const where = buildWhereIdOrUUID(id)
1437 return VideoModel.scope([
1438 ScopeNames.WITH_BLACKLISTED,
1439 ScopeNames.WITH_USER_ID,
1440 ScopeNames.WITH_THUMBNAILS
1444 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1445 const where = buildWhereIdOrUUID(id)
1448 attributes: [ 'id' ],
1453 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1456 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1457 const where = buildWhereIdOrUUID(id)
1465 return VideoModel.scope([
1466 ScopeNames.WITH_FILES,
1467 ScopeNames.WITH_STREAMING_PLAYLISTS,
1468 ScopeNames.WITH_THUMBNAILS
1472 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1479 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1482 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1483 const query: FindOptions = {
1490 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1493 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1494 const query: FindOptions = {
1501 return VideoModel.scope([
1502 ScopeNames.WITH_ACCOUNT_DETAILS,
1503 ScopeNames.WITH_FILES,
1504 ScopeNames.WITH_STREAMING_PLAYLISTS,
1505 ScopeNames.WITH_THUMBNAILS,
1506 ScopeNames.WITH_BLACKLISTED
1510 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1511 const where = buildWhereIdOrUUID(id)
1514 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1519 const scopes: (string | ScopeOptions)[] = [
1520 ScopeNames.WITH_TAGS,
1521 ScopeNames.WITH_BLACKLISTED,
1522 ScopeNames.WITH_ACCOUNT_DETAILS,
1523 ScopeNames.WITH_SCHEDULED_UPDATE,
1524 ScopeNames.WITH_FILES,
1525 ScopeNames.WITH_STREAMING_PLAYLISTS,
1526 ScopeNames.WITH_THUMBNAILS
1530 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1538 static loadForGetAPI (parameters: {
1539 id: number | string,
1542 }): Bluebird<MVideoDetails> {
1543 const { id, t, userId } = parameters
1544 const where = buildWhereIdOrUUID(id)
1547 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1552 const scopes: (string | ScopeOptions)[] = [
1553 ScopeNames.WITH_TAGS,
1554 ScopeNames.WITH_BLACKLISTED,
1555 ScopeNames.WITH_ACCOUNT_DETAILS,
1556 ScopeNames.WITH_SCHEDULED_UPDATE,
1557 ScopeNames.WITH_THUMBNAILS,
1558 { method: [ ScopeNames.WITH_FILES, true ] },
1559 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1563 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1571 static async getStats () {
1572 const totalLocalVideos = await VideoModel.count({
1577 const totalVideos = await VideoModel.count()
1579 let totalLocalVideoViews = await VideoModel.sum('views', {
1584 // Sequelize could return null...
1585 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1589 totalLocalVideoViews,
1594 static incrementViews (id: number, views: number) {
1595 return VideoModel.increment('views', {
1603 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1604 // Instances only share videos
1605 const query = 'SELECT 1 FROM "videoShare" ' +
1606 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1607 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1611 type: QueryTypes.SELECT,
1612 bind: { followerActorId, videoId },
1616 return VideoModel.sequelize.query(query, options)
1617 .then(results => results.length === 1)
1620 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1623 channelId: videoChannel.id
1628 return VideoModel.update({ support: videoChannel.support }, options)
1631 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1633 attributes: [ 'id' ],
1635 channelId: videoChannel.id
1639 return VideoModel.findAll(query)
1640 .then(videos => videos.map(v => v.id))
1643 // threshold corresponds to how many video the field should have to be returned
1644 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1645 const serverActor = await getServerActor()
1646 const followerActorId = serverActor.id
1648 const scopeOptions: AvailableForListIDsOptions = {
1649 serverAccountId: serverActor.Account.id,
1651 includeLocalVideos: true,
1652 attributesType: 'none' // Don't break aggregation
1655 const query: FindOptions = {
1656 attributes: [ field ],
1659 having: Sequelize.where(
1660 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1662 order: [ (this.sequelize as any).random() ]
1665 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1667 .then(rows => rows.map(r => r[ field ]))
1670 static buildTrendingQuery (trendingDays: number) {
1674 model: VideoViewModel,
1678 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1684 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1685 if (filter && (filter === 'local' || filter === 'all-local')) {
1694 private static async getAvailableForApi (
1695 query: FindOptions & { where?: null }, // Forbid where field in query
1696 options: AvailableForListIDsOptions,
1699 const idsScope: ScopeOptions = {
1701 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1705 // Remove trending sort on count, because it uses a group by
1706 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1707 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1708 const countScope: ScopeOptions = {
1710 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1714 const [ count, ids ] = await Promise.all([
1716 ? VideoModel.scope(countScope).count(countQuery)
1717 : Promise.resolve<number>(undefined),
1719 VideoModel.scope(idsScope)
1721 .then(rows => rows.map(r => r.id))
1724 if (ids.length === 0) return { data: [], total: count }
1726 const secondQuery: FindOptions = {
1729 attributes: query.attributes,
1730 order: [ // Keep original order
1732 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1737 const apiScope: (string | ScopeOptions)[] = []
1740 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1745 ScopeNames.FOR_API, {
1747 withFiles: options.withFiles,
1748 videoPlaylistId: options.videoPlaylistId
1753 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1761 static getCategoryLabel (id: number) {
1762 return VIDEO_CATEGORIES[ id ] || 'Misc'
1765 static getLicenceLabel (id: number) {
1766 return VIDEO_LICENCES[ id ] || 'Unknown'
1769 static getLanguageLabel (id: string) {
1770 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1773 static getPrivacyLabel (id: number) {
1774 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1777 static getStateLabel (id: number) {
1778 return VIDEO_STATES[ id ] || 'Unknown'
1782 return !!this.VideoBlacklist
1786 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1787 this.VideoChannel.Account.isBlocked()
1790 getOriginalFile <T extends MVideoWithFile> (this: T) {
1791 if (Array.isArray(this.VideoFiles) === false) return undefined
1793 // The original file is the file that have the higher resolution
1794 return maxBy(this.VideoFiles, file => file.resolution)
1797 getFile <T extends MVideoWithFile> (this: T, resolution: number) {
1798 if (Array.isArray(this.VideoFiles) === false) return undefined
1800 return this.VideoFiles.find(f => f.resolution === resolution)
1803 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1804 thumbnail.videoId = this.id
1806 const savedThumbnail = await thumbnail.save({ transaction })
1808 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1810 // Already have this thumbnail, skip
1811 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1813 this.Thumbnails.push(savedThumbnail)
1816 getVideoFilename (videoFile: MVideoFile) {
1817 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1820 generateThumbnailName () {
1821 return this.uuid + '.jpg'
1825 if (Array.isArray(this.Thumbnails) === false) return undefined
1827 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1830 generatePreviewName () {
1831 return this.uuid + '.jpg'
1835 if (Array.isArray(this.Thumbnails) === false) return undefined
1837 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1840 getTorrentFileName (videoFile: MVideoFile) {
1841 const extension = '.torrent'
1842 return this.uuid + '-' + videoFile.resolution + extension
1846 return this.remote === false
1849 getTorrentFilePath (videoFile: MVideoFile) {
1850 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1853 getVideoFilePath (videoFile: MVideoFile) {
1854 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1857 async createTorrentAndSetInfoHash (videoFile: MVideoFile) {
1859 // Keep the extname, it's used by the client to stream the file inside a web browser
1860 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1861 createdBy: 'PeerTube',
1863 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1864 [ WEBSERVER.URL + '/tracker/announce' ]
1866 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1869 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1871 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1872 logger.info('Creating torrent %s.', filePath)
1874 await writeFile(filePath, torrent)
1876 const parsedTorrent = parseTorrent(torrent)
1877 videoFile.infoHash = parsedTorrent.infoHash
1880 getWatchStaticPath () {
1881 return '/videos/watch/' + this.uuid
1884 getEmbedStaticPath () {
1885 return '/videos/embed/' + this.uuid
1888 getMiniatureStaticPath () {
1889 const thumbnail = this.getMiniature()
1890 if (!thumbnail) return null
1892 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1895 getPreviewStaticPath () {
1896 const preview = this.getPreview()
1897 if (!preview) return null
1899 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1900 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1903 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1904 return videoModelToFormattedJSON(this, options)
1907 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1908 return videoModelToFormattedDetailsJSON(this)
1911 getFormattedVideoFilesJSON (): VideoFile[] {
1912 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1915 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1916 return videoModelToActivityPubObject(this)
1919 getTruncatedDescription () {
1920 if (!this.description) return null
1922 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1923 return peertubeTruncate(this.description, maxLength)
1926 getOriginalFileResolution () {
1927 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1929 return getVideoFileResolution(originalFilePath)
1932 getDescriptionAPIPath () {
1933 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1937 if (!this.VideoStreamingPlaylists) return undefined
1939 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1942 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1943 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1945 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1946 return remove(filePath)
1947 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1950 removeTorrent (videoFile: MVideoFile) {
1951 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1952 return remove(torrentPath)
1953 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1956 removeStreamingPlaylist (isRedundancy = false) {
1957 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1959 const filePath = join(baseDir, this.uuid)
1960 return remove(filePath)
1961 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1965 if (this.isOwned()) return false
1967 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1971 this.changed('updatedAt', true)
1980 if (this.isOwned()) {
1981 baseUrlHttp = WEBSERVER.URL
1982 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1984 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1985 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1988 return { baseUrlHttp, baseUrlWs }
1991 generateMagnetUri (videoFile: MVideoFileRedundanciesOpt, baseUrlHttp: string, baseUrlWs: string) {
1992 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1993 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1994 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1996 const redundancies = videoFile.RedundancyVideos
1997 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1999 const magnetHash = {
2003 infoHash: videoFile.infoHash,
2007 return magnetUtil.encode(magnetHash)
2010 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2011 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2014 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2015 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2018 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2019 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2022 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2023 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
2026 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2027 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
2030 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2031 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2034 getBandwidthBits (videoFile: MVideoFile) {
2035 return Math.ceil((videoFile.size * 8) / this.duration)