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) {
473 [ Op.in ]: Sequelize.literal(
475 'SELECT "videoId" FROM "videoTag" ' +
476 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
477 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
484 if (options.tagsAllOf) {
487 [ Op.in ]: Sequelize.literal(
489 'SELECT "videoId" FROM "videoTag" ' +
490 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
491 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
492 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
500 if (options.nsfw === true || options.nsfw === false) {
501 whereAnd.push({ nsfw: options.nsfw })
504 if (options.categoryOneOf) {
507 [ Op.or ]: options.categoryOneOf
512 if (options.licenceOneOf) {
515 [ Op.or ]: options.licenceOneOf
520 if (options.languageOneOf) {
521 let videoLanguages = options.languageOneOf
522 if (options.languageOneOf.find(l => l === '_unknown')) {
523 videoLanguages = videoLanguages.concat([ null ])
530 [ Op.or ]: videoLanguages
535 [ Op.in ]: Sequelize.literal(
537 'SELECT "videoId" FROM "videoCaption" ' +
538 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
547 if (options.trendingDays) {
548 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
550 query.subQuery = false
553 if (options.historyOfUser) {
555 model: UserVideoHistoryModel,
558 userId: options.historyOfUser.id
562 // Even if the relation is n:m, we know that a user only have 0..1 video history
563 // So we won't have multiple rows for the same video
564 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
565 query.subQuery = false
574 [ScopeNames.WITH_BLOCKLIST]: {
577 [ ScopeNames.WITH_THUMBNAILS ]: {
580 model: ThumbnailModel,
585 [ ScopeNames.WITH_USER_ID ]: {
588 attributes: [ 'accountId' ],
589 model: VideoChannelModel.unscoped(),
593 attributes: [ 'userId' ],
594 model: AccountModel.unscoped(),
601 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
604 model: VideoChannelModel.unscoped(),
609 exclude: [ 'privateKey', 'publicKey' ]
611 model: ActorModel.unscoped(),
615 attributes: [ 'host' ],
616 model: ServerModel.unscoped(),
620 model: AvatarModel.unscoped(),
626 model: AccountModel.unscoped(),
630 model: ActorModel.unscoped(),
632 exclude: [ 'privateKey', 'publicKey' ]
637 attributes: [ 'host' ],
638 model: ServerModel.unscoped(),
642 model: AvatarModel.unscoped(),
653 [ ScopeNames.WITH_TAGS ]: {
654 include: [ TagModel ]
656 [ ScopeNames.WITH_BLACKLISTED ]: {
659 attributes: [ 'id', 'reason', 'unfederated' ],
660 model: VideoBlacklistModel,
665 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
666 let subInclude: any[] = []
668 if (withRedundancies === true) {
671 attributes: [ 'fileUrl' ],
672 model: VideoRedundancyModel.unscoped(),
681 model: VideoFileModel.unscoped(),
682 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
689 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
690 let subInclude: any[] = []
692 if (withRedundancies === true) {
695 attributes: [ 'fileUrl' ],
696 model: VideoRedundancyModel.unscoped(),
705 model: VideoStreamingPlaylistModel.unscoped(),
706 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
713 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
716 model: ScheduleVideoUpdateModel.unscoped(),
721 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
725 attributes: [ 'currentTime' ],
726 model: UserVideoHistoryModel.unscoped(),
740 export class VideoModel extends Model<VideoModel> {
743 @Default(DataType.UUIDV4)
745 @Column(DataType.UUID)
749 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
755 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
761 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
767 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
768 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
772 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
777 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
783 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
784 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
789 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
790 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
794 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
824 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
825 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
830 commentsEnabled: boolean
834 downloadEnabled: boolean
838 waitTranscoding: boolean
842 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
853 @Default(DataType.NOW)
860 originallyPublishedAt: Date
862 @ForeignKey(() => VideoChannelModel)
866 @BelongsTo(() => VideoChannelModel, {
872 VideoChannel: VideoChannelModel
874 @BelongsToMany(() => TagModel, {
875 foreignKey: 'videoId',
876 through: () => VideoTagModel,
881 @HasMany(() => ThumbnailModel, {
889 Thumbnails: ThumbnailModel[]
891 @HasMany(() => VideoPlaylistElementModel, {
898 VideoPlaylistElements: VideoPlaylistElementModel[]
900 @HasMany(() => VideoAbuseModel, {
907 VideoAbuses: VideoAbuseModel[]
909 @HasMany(() => VideoFileModel, {
917 VideoFiles: VideoFileModel[]
919 @HasMany(() => VideoStreamingPlaylistModel, {
927 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
929 @HasMany(() => VideoShareModel, {
936 VideoShares: VideoShareModel[]
938 @HasMany(() => AccountVideoRateModel, {
945 AccountVideoRates: AccountVideoRateModel[]
947 @HasMany(() => VideoCommentModel, {
955 VideoComments: VideoCommentModel[]
957 @HasMany(() => VideoViewModel, {
964 VideoViews: VideoViewModel[]
966 @HasMany(() => UserVideoHistoryModel, {
973 UserVideoHistories: UserVideoHistoryModel[]
975 @HasOne(() => ScheduleVideoUpdateModel, {
982 ScheduleVideoUpdate: ScheduleVideoUpdateModel
984 @HasOne(() => VideoBlacklistModel, {
991 VideoBlacklist: VideoBlacklistModel
993 @HasOne(() => VideoImportModel, {
1000 VideoImport: VideoImportModel
1002 @HasMany(() => VideoCaptionModel, {
1007 onDelete: 'cascade',
1009 [ 'separate' as any ]: true
1011 VideoCaptions: VideoCaptionModel[]
1014 static async sendDelete (instance: MVideoAccountLight, options) {
1015 if (instance.isOwned()) {
1016 if (!instance.VideoChannel) {
1017 instance.VideoChannel = await instance.$get('VideoChannel', {
1022 transaction: options.transaction
1023 }) as MChannelAccountDefault
1026 return sendDeleteVideo(instance, options.transaction)
1033 static async removeFiles (instance: VideoModel) {
1034 const tasks: Promise<any>[] = []
1036 logger.info('Removing files of video %s.', instance.url)
1038 if (instance.isOwned()) {
1039 if (!Array.isArray(instance.VideoFiles)) {
1040 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1043 // Remove physical files and torrents
1044 instance.VideoFiles.forEach(file => {
1045 tasks.push(instance.removeFile(file))
1046 tasks.push(instance.removeTorrent(file))
1049 // Remove playlists file
1050 tasks.push(instance.removeStreamingPlaylist())
1053 // Do not wait video deletion because we could be in a transaction
1056 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1062 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1069 return VideoModel.scope([
1070 ScopeNames.WITH_FILES,
1071 ScopeNames.WITH_STREAMING_PLAYLISTS,
1072 ScopeNames.WITH_THUMBNAILS
1076 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1077 function getRawQuery (select: string) {
1078 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1079 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1080 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1081 'WHERE "Account"."actorId" = ' + actorId
1082 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1083 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1084 'WHERE "VideoShare"."actorId" = ' + actorId
1086 return `(${queryVideo}) UNION (${queryVideoShare})`
1089 const rawQuery = getRawQuery('"Video"."id"')
1090 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1096 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1099 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1102 { privacy: VideoPrivacy.PUBLIC },
1103 { privacy: VideoPrivacy.UNLISTED }
1108 attributes: [ 'language' ],
1109 model: VideoCaptionModel.unscoped(),
1113 attributes: [ 'id', 'url' ],
1114 model: VideoShareModel.unscoped(),
1116 // We only want videos shared by this actor
1131 attributes: [ 'id', 'url' ],
1132 model: ActorModel.unscoped()
1137 model: VideoChannelModel.unscoped(),
1141 attributes: [ 'name' ],
1142 model: AccountModel.unscoped(),
1146 attributes: [ 'id', 'url', 'followersUrl' ],
1147 model: ActorModel.unscoped(),
1153 attributes: [ 'id', 'url', 'followersUrl' ],
1154 model: ActorModel.unscoped(),
1164 return Bluebird.all([
1165 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1166 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1167 ]).then(([ rows, totals ]) => {
1168 // totals: totalVideos + totalVideoShares
1170 let totalVideoShares = 0
1171 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1172 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1174 const total = totalVideos + totalVideoShares
1182 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1183 function buildBaseQuery (): FindOptions {
1187 order: getVideoSort(sort),
1190 model: VideoChannelModel,
1194 model: AccountModel,
1206 const countQuery = buildBaseQuery()
1207 const findQuery = buildBaseQuery()
1209 const findScopes = [
1210 ScopeNames.WITH_SCHEDULED_UPDATE,
1211 ScopeNames.WITH_BLACKLISTED,
1212 ScopeNames.WITH_THUMBNAILS
1215 return Promise.all([
1216 VideoModel.count(countQuery),
1217 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1218 ]).then(([ count, rows ]) => {
1226 static async listForApi (options: {
1231 includeLocalVideos: boolean,
1233 categoryOneOf?: number[],
1234 licenceOneOf?: number[],
1235 languageOneOf?: string[],
1236 tagsOneOf?: string[],
1237 tagsAllOf?: string[],
1238 filter?: VideoFilter,
1240 videoChannelId?: number,
1241 followerActorId?: number
1242 videoPlaylistId?: number,
1243 trendingDays?: number,
1244 user?: MUserAccountId,
1245 historyOfUser?: MUserId
1246 }, countVideos = true) {
1247 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1248 throw new Error('Try to filter all-local but no user has not the see all videos right')
1251 const query: FindOptions & { where?: null } = {
1252 offset: options.start,
1253 limit: options.count,
1254 order: getVideoSort(options.sort)
1257 let trendingDays: number
1258 if (options.sort.endsWith('trending')) {
1259 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1261 query.group = 'VideoModel.id'
1264 const serverActor = await getServerActor()
1266 // followerActorId === null has a meaning, so just check undefined
1267 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1269 const queryOptions = {
1271 serverAccountId: serverActor.Account.id,
1273 categoryOneOf: options.categoryOneOf,
1274 licenceOneOf: options.licenceOneOf,
1275 languageOneOf: options.languageOneOf,
1276 tagsOneOf: options.tagsOneOf,
1277 tagsAllOf: options.tagsAllOf,
1278 filter: options.filter,
1279 withFiles: options.withFiles,
1280 accountId: options.accountId,
1281 videoChannelId: options.videoChannelId,
1282 videoPlaylistId: options.videoPlaylistId,
1283 includeLocalVideos: options.includeLocalVideos,
1285 historyOfUser: options.historyOfUser,
1289 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1292 static async searchAndPopulateAccountAndServer (options: {
1293 includeLocalVideos: boolean
1298 startDate?: string // ISO 8601
1299 endDate?: string // ISO 8601
1300 originallyPublishedStartDate?: string
1301 originallyPublishedEndDate?: string
1303 categoryOneOf?: number[]
1304 licenceOneOf?: number[]
1305 languageOneOf?: string[]
1306 tagsOneOf?: string[]
1307 tagsAllOf?: string[]
1308 durationMin?: number // seconds
1309 durationMax?: number // seconds
1310 user?: MUserAccountId,
1311 filter?: VideoFilter
1315 if (options.startDate || options.endDate) {
1316 const publishedAtRange = {}
1318 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1319 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1321 whereAnd.push({ publishedAt: publishedAtRange })
1324 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1325 const originallyPublishedAtRange = {}
1327 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1328 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1330 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1333 if (options.durationMin || options.durationMax) {
1334 const durationRange = {}
1336 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1337 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1339 whereAnd.push({ duration: durationRange })
1342 const attributesInclude = []
1343 const escapedSearch = VideoModel.sequelize.escape(options.search)
1344 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1345 if (options.search) {
1349 [ Op.in ]: Sequelize.literal(
1351 'SELECT "video"."id" FROM "video" ' +
1353 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1354 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1356 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1357 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1358 'WHERE "tag"."name" = ' + escapedSearch +
1365 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1368 // Cannot search on similarity if we don't have a search
1369 if (!options.search) {
1370 attributesInclude.push(
1371 Sequelize.literal('0 as similarity')
1377 include: attributesInclude
1379 offset: options.start,
1380 limit: options.count,
1381 order: getVideoSort(options.sort)
1384 const serverActor = await getServerActor()
1385 const queryOptions = {
1386 followerActorId: serverActor.id,
1387 serverAccountId: serverActor.Account.id,
1388 includeLocalVideos: options.includeLocalVideos,
1390 categoryOneOf: options.categoryOneOf,
1391 licenceOneOf: options.licenceOneOf,
1392 languageOneOf: options.languageOneOf,
1393 tagsOneOf: options.tagsOneOf,
1394 tagsAllOf: options.tagsAllOf,
1396 filter: options.filter,
1400 return VideoModel.getAvailableForApi(query, queryOptions)
1403 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1404 const where = buildWhereIdOrUUID(id)
1410 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1413 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1414 const where = buildWhereIdOrUUID(id)
1420 return VideoModel.scope([
1421 ScopeNames.WITH_THUMBNAILS,
1422 ScopeNames.WITH_BLACKLISTED
1426 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1427 const where = buildWhereIdOrUUID(id)
1433 return VideoModel.scope([
1434 ScopeNames.WITH_BLACKLISTED,
1435 ScopeNames.WITH_USER_ID,
1436 ScopeNames.WITH_THUMBNAILS
1440 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1441 const where = buildWhereIdOrUUID(id)
1444 attributes: [ 'id' ],
1449 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1452 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1453 const where = buildWhereIdOrUUID(id)
1461 return VideoModel.scope([
1462 ScopeNames.WITH_FILES,
1463 ScopeNames.WITH_STREAMING_PLAYLISTS,
1464 ScopeNames.WITH_THUMBNAILS
1468 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1475 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1478 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1479 const query: FindOptions = {
1486 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1489 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1490 const query: FindOptions = {
1497 return VideoModel.scope([
1498 ScopeNames.WITH_ACCOUNT_DETAILS,
1499 ScopeNames.WITH_FILES,
1500 ScopeNames.WITH_STREAMING_PLAYLISTS,
1501 ScopeNames.WITH_THUMBNAILS,
1502 ScopeNames.WITH_BLACKLISTED
1506 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1507 const where = buildWhereIdOrUUID(id)
1510 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1515 const scopes: (string | ScopeOptions)[] = [
1516 ScopeNames.WITH_TAGS,
1517 ScopeNames.WITH_BLACKLISTED,
1518 ScopeNames.WITH_ACCOUNT_DETAILS,
1519 ScopeNames.WITH_SCHEDULED_UPDATE,
1520 ScopeNames.WITH_FILES,
1521 ScopeNames.WITH_STREAMING_PLAYLISTS,
1522 ScopeNames.WITH_THUMBNAILS
1526 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1534 static loadForGetAPI (parameters: {
1535 id: number | string,
1538 }): Bluebird<MVideoDetails> {
1539 const { id, t, userId } = parameters
1540 const where = buildWhereIdOrUUID(id)
1543 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1548 const scopes: (string | ScopeOptions)[] = [
1549 ScopeNames.WITH_TAGS,
1550 ScopeNames.WITH_BLACKLISTED,
1551 ScopeNames.WITH_ACCOUNT_DETAILS,
1552 ScopeNames.WITH_SCHEDULED_UPDATE,
1553 ScopeNames.WITH_THUMBNAILS,
1554 { method: [ ScopeNames.WITH_FILES, true ] },
1555 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1559 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1567 static async getStats () {
1568 const totalLocalVideos = await VideoModel.count({
1573 const totalVideos = await VideoModel.count()
1575 let totalLocalVideoViews = await VideoModel.sum('views', {
1580 // Sequelize could return null...
1581 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1585 totalLocalVideoViews,
1590 static incrementViews (id: number, views: number) {
1591 return VideoModel.increment('views', {
1599 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1600 // Instances only share videos
1601 const query = 'SELECT 1 FROM "videoShare" ' +
1602 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1603 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1607 type: QueryTypes.SELECT,
1608 bind: { followerActorId, videoId },
1612 return VideoModel.sequelize.query(query, options)
1613 .then(results => results.length === 1)
1616 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1619 channelId: videoChannel.id
1624 return VideoModel.update({ support: videoChannel.support }, options)
1627 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1629 attributes: [ 'id' ],
1631 channelId: videoChannel.id
1635 return VideoModel.findAll(query)
1636 .then(videos => videos.map(v => v.id))
1639 // threshold corresponds to how many video the field should have to be returned
1640 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1641 const serverActor = await getServerActor()
1642 const followerActorId = serverActor.id
1644 const scopeOptions: AvailableForListIDsOptions = {
1645 serverAccountId: serverActor.Account.id,
1647 includeLocalVideos: true,
1648 attributesType: 'none' // Don't break aggregation
1651 const query: FindOptions = {
1652 attributes: [ field ],
1655 having: Sequelize.where(
1656 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1658 order: [ (this.sequelize as any).random() ]
1661 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1663 .then(rows => rows.map(r => r[ field ]))
1666 static buildTrendingQuery (trendingDays: number) {
1670 model: VideoViewModel,
1674 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1680 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1681 if (filter && (filter === 'local' || filter === 'all-local')) {
1690 private static async getAvailableForApi (
1691 query: FindOptions & { where?: null }, // Forbid where field in query
1692 options: AvailableForListIDsOptions,
1695 const idsScope: ScopeOptions = {
1697 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1701 // Remove trending sort on count, because it uses a group by
1702 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1703 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1704 const countScope: ScopeOptions = {
1706 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1710 const [ count, ids ] = await Promise.all([
1712 ? VideoModel.scope(countScope).count(countQuery)
1713 : Promise.resolve<number>(undefined),
1715 VideoModel.scope(idsScope)
1717 .then(rows => rows.map(r => r.id))
1720 if (ids.length === 0) return { data: [], total: count }
1722 const secondQuery: FindOptions = {
1725 attributes: query.attributes,
1726 order: [ // Keep original order
1728 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1733 const apiScope: (string | ScopeOptions)[] = []
1736 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1741 ScopeNames.FOR_API, {
1743 withFiles: options.withFiles,
1744 videoPlaylistId: options.videoPlaylistId
1749 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1757 static getCategoryLabel (id: number) {
1758 return VIDEO_CATEGORIES[ id ] || 'Misc'
1761 static getLicenceLabel (id: number) {
1762 return VIDEO_LICENCES[ id ] || 'Unknown'
1765 static getLanguageLabel (id: string) {
1766 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1769 static getPrivacyLabel (id: number) {
1770 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1773 static getStateLabel (id: number) {
1774 return VIDEO_STATES[ id ] || 'Unknown'
1778 return !!this.VideoBlacklist
1782 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1783 this.VideoChannel.Account.isBlocked()
1786 getOriginalFile <T extends MVideoWithFile> (this: T) {
1787 if (Array.isArray(this.VideoFiles) === false) return undefined
1789 // The original file is the file that have the higher resolution
1790 return maxBy(this.VideoFiles, file => file.resolution)
1793 getFile <T extends MVideoWithFile> (this: T, resolution: number) {
1794 if (Array.isArray(this.VideoFiles) === false) return undefined
1796 return this.VideoFiles.find(f => f.resolution === resolution)
1799 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1800 thumbnail.videoId = this.id
1802 const savedThumbnail = await thumbnail.save({ transaction })
1804 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1806 // Already have this thumbnail, skip
1807 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1809 this.Thumbnails.push(savedThumbnail)
1812 getVideoFilename (videoFile: MVideoFile) {
1813 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1816 generateThumbnailName () {
1817 return this.uuid + '.jpg'
1821 if (Array.isArray(this.Thumbnails) === false) return undefined
1823 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1826 generatePreviewName () {
1827 return this.uuid + '.jpg'
1831 if (Array.isArray(this.Thumbnails) === false) return undefined
1833 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1836 getTorrentFileName (videoFile: MVideoFile) {
1837 const extension = '.torrent'
1838 return this.uuid + '-' + videoFile.resolution + extension
1842 return this.remote === false
1845 getTorrentFilePath (videoFile: MVideoFile) {
1846 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1849 getVideoFilePath (videoFile: MVideoFile) {
1850 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1853 async createTorrentAndSetInfoHash (videoFile: MVideoFile) {
1855 // Keep the extname, it's used by the client to stream the file inside a web browser
1856 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1857 createdBy: 'PeerTube',
1859 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1860 [ WEBSERVER.URL + '/tracker/announce' ]
1862 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1865 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1867 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1868 logger.info('Creating torrent %s.', filePath)
1870 await writeFile(filePath, torrent)
1872 const parsedTorrent = parseTorrent(torrent)
1873 videoFile.infoHash = parsedTorrent.infoHash
1876 getWatchStaticPath () {
1877 return '/videos/watch/' + this.uuid
1880 getEmbedStaticPath () {
1881 return '/videos/embed/' + this.uuid
1884 getMiniatureStaticPath () {
1885 const thumbnail = this.getMiniature()
1886 if (!thumbnail) return null
1888 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1891 getPreviewStaticPath () {
1892 const preview = this.getPreview()
1893 if (!preview) return null
1895 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1896 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1899 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1900 return videoModelToFormattedJSON(this, options)
1903 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1904 return videoModelToFormattedDetailsJSON(this)
1907 getFormattedVideoFilesJSON (): VideoFile[] {
1908 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1911 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1912 return videoModelToActivityPubObject(this)
1915 getTruncatedDescription () {
1916 if (!this.description) return null
1918 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1919 return peertubeTruncate(this.description, maxLength)
1922 getOriginalFileResolution () {
1923 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1925 return getVideoFileResolution(originalFilePath)
1928 getDescriptionAPIPath () {
1929 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1933 if (!this.VideoStreamingPlaylists) return undefined
1935 return this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1938 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1939 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1941 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1942 return remove(filePath)
1943 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1946 removeTorrent (videoFile: MVideoFile) {
1947 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1948 return remove(torrentPath)
1949 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1952 removeStreamingPlaylist (isRedundancy = false) {
1953 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1955 const filePath = join(baseDir, this.uuid)
1956 return remove(filePath)
1957 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1961 if (this.isOwned()) return false
1963 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1967 this.changed('updatedAt', true)
1976 if (this.isOwned()) {
1977 baseUrlHttp = WEBSERVER.URL
1978 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1980 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1981 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1984 return { baseUrlHttp, baseUrlWs }
1987 generateMagnetUri (videoFile: MVideoFileRedundanciesOpt, baseUrlHttp: string, baseUrlWs: string) {
1988 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1989 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1990 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1992 const redundancies = videoFile.RedundancyVideos
1993 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1995 const magnetHash = {
1999 infoHash: videoFile.infoHash,
2003 return magnetUtil.encode(magnetHash)
2006 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2007 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2010 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2011 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2014 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2015 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
2018 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2019 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
2022 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2023 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
2026 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2027 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
2030 getBandwidthBits (videoFile: MVideoFile) {
2031 return Math.ceil((videoFile.size * 8) / this.duration)