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 { createTorrentPromise, 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,
86 createSimilarityAttribute,
91 import { TagModel } from './tag'
92 import { VideoAbuseModel } from './video-abuse'
93 import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel'
94 import { VideoCommentModel } from './video-comment'
95 import { VideoFileModel } from './video-file'
96 import { VideoShareModel } from './video-share'
97 import { VideoTagModel } from './video-tag'
98 import { ScheduleVideoUpdateModel } from './schedule-video-update'
99 import { VideoCaptionModel } from './video-caption'
100 import { VideoBlacklistModel } from './video-blacklist'
101 import { remove, writeFile } from 'fs-extra'
102 import { VideoViewModel } from './video-views'
103 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
105 videoFilesModelToFormattedJSON,
106 VideoFormattingJSONOptions,
107 videoModelToActivityPubObject,
108 videoModelToFormattedDetailsJSON,
109 videoModelToFormattedJSON
110 } from './video-format-utils'
111 import { UserVideoHistoryModel } from '../account/user-video-history'
112 import { UserModel } from '../account/user'
113 import { VideoImportModel } from './video-import'
114 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
115 import { VideoPlaylistElementModel } from './video-playlist-element'
116 import { CONFIG } from '../../initializers/config'
117 import { ThumbnailModel } from './thumbnail'
118 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
120 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
121 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
122 buildTrigramSearchIndex('video_name_trigram', 'name'),
124 { fields: [ 'createdAt' ] },
125 { fields: [ 'publishedAt' ] },
126 { fields: [ 'duration' ] },
127 { fields: [ 'views' ] },
128 { fields: [ 'channelId' ] },
130 fields: [ 'originallyPublishedAt' ],
132 originallyPublishedAt: {
138 fields: [ 'category' ], // We don't care videos with an unknown category
146 fields: [ 'licence' ], // We don't care videos with an unknown licence
154 fields: [ 'language' ], // We don't care videos with an unknown language
162 fields: [ 'nsfw' ], // Most of the videos are not NSFW
168 fields: [ 'remote' ], // Only index local videos
183 export enum ScopeNames {
184 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
186 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
187 WITH_TAGS = 'WITH_TAGS',
188 WITH_FILES = 'WITH_FILES',
189 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
190 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
191 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
192 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
193 WITH_USER_ID = 'WITH_USER_ID',
194 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
197 type ForAPIOptions = {
200 videoPlaylistId?: number
205 type AvailableForListIDsOptions = {
206 serverAccountId: number
207 followerActorId: number
208 includeLocalVideos: boolean
211 categoryOneOf?: number[]
213 licenceOneOf?: number[]
214 languageOneOf?: string[]
221 videoChannelId?: number
223 videoPlaylistId?: number
225 trendingDays?: number
227 historyOfUser?: UserModel
231 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
232 const query: FindOptions = {
235 [ Op.in ]: options.ids // FIXME: sequelize any seems broken
240 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
246 if (options.withFiles === true) {
248 model: VideoFileModel.unscoped(),
253 if (options.videoPlaylistId) {
255 model: VideoPlaylistElementModel.unscoped(),
258 videoPlaylistId: options.videoPlaylistId
265 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
266 const query: FindOptions = {
268 attributes: [ 'id' ],
273 [ Op.notIn ]: Sequelize.literal(
274 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
280 [ Op.notIn ]: Sequelize.literal(
282 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
283 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
292 // Only list public/published videos
293 if (!options.filter || options.filter !== 'all-local') {
294 const privacyWhere = {
295 // Always list public videos
296 privacy: VideoPrivacy.PUBLIC,
297 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
300 state: VideoState.PUBLISHED
304 state: VideoState.TO_TRANSCODE,
305 waitTranscoding: false
311 Object.assign(query.where, privacyWhere)
314 if (options.videoPlaylistId) {
317 model: VideoPlaylistElementModel.unscoped(),
320 videoPlaylistId: options.videoPlaylistId
324 query.subQuery = false
327 if (options.filter || options.accountId || options.videoChannelId) {
328 const videoChannelInclude: IncludeOptions = {
330 model: VideoChannelModel.unscoped(),
334 if (options.videoChannelId) {
335 videoChannelInclude.where = {
336 id: options.videoChannelId
340 if (options.filter || options.accountId) {
341 const accountInclude: IncludeOptions = {
343 model: AccountModel.unscoped(),
347 if (options.filter) {
348 accountInclude.include = [
351 model: ActorModel.unscoped(),
353 where: VideoModel.buildActorWhereWithFilter(options.filter)
358 if (options.accountId) {
359 accountInclude.where = { id: options.accountId }
362 videoChannelInclude.include = [ accountInclude ]
365 query.include.push(videoChannelInclude)
368 if (options.followerActorId) {
369 let localVideosReq = ''
370 if (options.includeLocalVideos === true) {
371 localVideosReq = ' UNION ALL ' +
372 'SELECT "video"."id" AS "id" FROM "video" ' +
373 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
374 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
375 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
376 'WHERE "actor"."serverId" IS NULL'
379 // Force actorId to be a number to avoid SQL injections
380 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
381 query.where[ 'id' ][ Op.and ].push({
382 [ Op.in ]: Sequelize.literal(
384 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
385 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
386 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
388 'SELECT "video"."id" AS "id" FROM "video" ' +
389 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
390 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
391 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
392 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
393 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
400 if (options.withFiles === true) {
401 query.where[ 'id' ][ Op.and ].push({
402 [ Op.in ]: Sequelize.literal(
403 '(SELECT "videoId" FROM "videoFile")'
408 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
409 if (options.tagsAllOf || options.tagsOneOf) {
410 const createTagsIn = (tags: string[]) => {
411 return tags.map(t => VideoModel.sequelize.escape(t))
415 if (options.tagsOneOf) {
416 query.where[ 'id' ][ Op.and ].push({
417 [ Op.in ]: Sequelize.literal(
419 'SELECT "videoId" FROM "videoTag" ' +
420 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
421 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
427 if (options.tagsAllOf) {
428 query.where[ 'id' ][ Op.and ].push({
429 [ Op.in ]: Sequelize.literal(
431 'SELECT "videoId" FROM "videoTag" ' +
432 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
433 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
434 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
441 if (options.nsfw === true || options.nsfw === false) {
442 query.where[ 'nsfw' ] = options.nsfw
445 if (options.categoryOneOf) {
446 query.where[ 'category' ] = {
447 [ Op.or ]: options.categoryOneOf
451 if (options.licenceOneOf) {
452 query.where[ 'licence' ] = {
453 [ Op.or ]: options.licenceOneOf
457 if (options.languageOneOf) {
458 query.where[ 'language' ] = {
459 [ Op.or ]: options.languageOneOf
463 if (options.trendingDays) {
464 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
466 query.subQuery = false
469 if (options.historyOfUser) {
471 model: UserVideoHistoryModel,
474 userId: options.historyOfUser.id
478 // Even if the relation is n:m, we know that a user only have 0..1 video history
479 // So we won't have multiple rows for the same video
480 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
481 query.subQuery = false
486 [ ScopeNames.WITH_THUMBNAILS ]: {
489 model: () => ThumbnailModel,
494 [ ScopeNames.WITH_USER_ID ]: {
497 attributes: [ 'accountId' ],
498 model: () => VideoChannelModel.unscoped(),
502 attributes: [ 'userId' ],
503 model: () => AccountModel.unscoped(),
508 ] as any // FIXME: sequelize typings
510 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
513 model: () => VideoChannelModel.unscoped(),
518 exclude: [ 'privateKey', 'publicKey' ]
520 model: () => ActorModel.unscoped(),
524 attributes: [ 'host' ],
525 model: () => ServerModel.unscoped(),
529 model: () => AvatarModel.unscoped(),
535 model: () => AccountModel.unscoped(),
539 model: () => ActorModel.unscoped(),
541 exclude: [ 'privateKey', 'publicKey' ]
546 attributes: [ 'host' ],
547 model: () => ServerModel.unscoped(),
551 model: () => AvatarModel.unscoped(),
560 ] as any // FIXME: sequelize typings
562 [ ScopeNames.WITH_TAGS ]: {
563 include: [ () => TagModel ]
565 [ ScopeNames.WITH_BLACKLISTED ]: {
568 attributes: [ 'id', 'reason' ],
569 model: () => VideoBlacklistModel,
574 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
575 let subInclude: any[] = []
577 if (withRedundancies === true) {
580 attributes: [ 'fileUrl' ],
581 model: VideoRedundancyModel.unscoped(),
590 model: VideoFileModel.unscoped(),
592 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
599 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
600 let subInclude: any[] = []
602 if (withRedundancies === true) {
605 attributes: [ 'fileUrl' ],
606 model: VideoRedundancyModel.unscoped(),
615 model: VideoStreamingPlaylistModel.unscoped(),
617 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
624 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
627 model: () => ScheduleVideoUpdateModel.unscoped(),
632 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
636 attributes: [ 'currentTime' ],
637 model: UserVideoHistoryModel.unscoped(),
651 export class VideoModel extends Model<VideoModel> {
654 @Default(DataType.UUIDV4)
656 @Column(DataType.UUID)
660 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
666 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
672 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
678 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
679 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
683 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
688 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
694 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
695 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
700 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
701 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
705 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
735 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
736 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
741 commentsEnabled: boolean
745 downloadEnabled: boolean
749 waitTranscoding: boolean
753 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
764 @Default(DataType.NOW)
771 originallyPublishedAt: Date
773 @ForeignKey(() => VideoChannelModel)
777 @BelongsTo(() => VideoChannelModel, {
783 VideoChannel: VideoChannelModel
785 @BelongsToMany(() => TagModel, {
786 foreignKey: 'videoId',
787 through: () => VideoTagModel,
792 @HasMany(() => ThumbnailModel, {
800 Thumbnails: ThumbnailModel[]
802 @HasMany(() => VideoPlaylistElementModel, {
809 VideoPlaylistElements: VideoPlaylistElementModel[]
811 @HasMany(() => VideoAbuseModel, {
818 VideoAbuses: VideoAbuseModel[]
820 @HasMany(() => VideoFileModel, {
828 VideoFiles: VideoFileModel[]
830 @HasMany(() => VideoStreamingPlaylistModel, {
838 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
840 @HasMany(() => VideoShareModel, {
847 VideoShares: VideoShareModel[]
849 @HasMany(() => AccountVideoRateModel, {
856 AccountVideoRates: AccountVideoRateModel[]
858 @HasMany(() => VideoCommentModel, {
866 VideoComments: VideoCommentModel[]
868 @HasMany(() => VideoViewModel, {
875 VideoViews: VideoViewModel[]
877 @HasMany(() => UserVideoHistoryModel, {
884 UserVideoHistories: UserVideoHistoryModel[]
886 @HasOne(() => ScheduleVideoUpdateModel, {
893 ScheduleVideoUpdate: ScheduleVideoUpdateModel
895 @HasOne(() => VideoBlacklistModel, {
902 VideoBlacklist: VideoBlacklistModel
904 @HasOne(() => VideoImportModel, {
911 VideoImport: VideoImportModel
913 @HasMany(() => VideoCaptionModel, {
920 [ 'separate' as any ]: true
922 VideoCaptions: VideoCaptionModel[]
925 static async sendDelete (instance: VideoModel, options) {
926 if (instance.isOwned()) {
927 if (!instance.VideoChannel) {
928 instance.VideoChannel = await instance.$get('VideoChannel', {
932 include: [ ActorModel ]
935 transaction: options.transaction
936 }) as VideoChannelModel
939 return sendDeleteVideo(instance, options.transaction)
946 static async removeFiles (instance: VideoModel) {
947 const tasks: Promise<any>[] = []
949 logger.info('Removing files of video %s.', instance.url)
951 if (instance.isOwned()) {
952 if (!Array.isArray(instance.VideoFiles)) {
953 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
956 // Remove physical files and torrents
957 instance.VideoFiles.forEach(file => {
958 tasks.push(instance.removeFile(file))
959 tasks.push(instance.removeTorrent(file))
962 // Remove playlists file
963 tasks.push(instance.removeStreamingPlaylist())
966 // Do not wait video deletion because we could be in a transaction
969 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
975 static listLocal () {
982 return VideoModel.scope([
983 ScopeNames.WITH_FILES,
984 ScopeNames.WITH_STREAMING_PLAYLISTS,
985 ScopeNames.WITH_THUMBNAILS
989 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
990 function getRawQuery (select: string) {
991 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
992 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
993 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
994 'WHERE "Account"."actorId" = ' + actorId
995 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
996 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
997 'WHERE "VideoShare"."actorId" = ' + actorId
999 return `(${queryVideo}) UNION (${queryVideoShare})`
1002 const rawQuery = getRawQuery('"Video"."id"')
1003 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1009 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1012 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1015 { privacy: VideoPrivacy.PUBLIC },
1016 { privacy: VideoPrivacy.UNLISTED }
1021 attributes: [ 'language' ],
1022 model: VideoCaptionModel.unscoped(),
1026 attributes: [ 'id', 'url' ],
1027 model: VideoShareModel.unscoped(),
1029 // We only want videos shared by this actor
1044 attributes: [ 'id', 'url' ],
1045 model: ActorModel.unscoped()
1050 model: VideoChannelModel.unscoped(),
1054 attributes: [ 'name' ],
1055 model: AccountModel.unscoped(),
1059 attributes: [ 'id', 'url', 'followersUrl' ],
1060 model: ActorModel.unscoped(),
1066 attributes: [ 'id', 'url', 'followersUrl' ],
1067 model: ActorModel.unscoped(),
1077 return Bluebird.all([
1078 // FIXME: typing issue
1079 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query as any),
1080 VideoModel.sequelize.query<{ total: number }>(rawCountQuery, { type: QueryTypes.SELECT })
1081 ]).then(([ rows, totals ]) => {
1082 // totals: totalVideos + totalVideoShares
1084 let totalVideoShares = 0
1085 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total + '', 10)
1086 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total + '', 10)
1088 const total = totalVideos + totalVideoShares
1096 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1097 const query: FindOptions = {
1100 order: getVideoSort(sort),
1103 model: VideoChannelModel,
1107 model: AccountModel,
1116 model: ScheduleVideoUpdateModel,
1120 model: VideoBlacklistModel,
1126 if (withFiles === true) {
1127 query.include.push({
1128 model: VideoFileModel.unscoped(),
1133 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS)
1134 .findAndCountAll(query)
1135 .then(({ rows, count }) => {
1143 static async listForApi (options: {
1148 includeLocalVideos: boolean,
1150 categoryOneOf?: number[],
1151 licenceOneOf?: number[],
1152 languageOneOf?: string[],
1153 tagsOneOf?: string[],
1154 tagsAllOf?: string[],
1155 filter?: VideoFilter,
1157 videoChannelId?: number,
1158 followerActorId?: number
1159 videoPlaylistId?: number,
1160 trendingDays?: number,
1162 historyOfUser?: UserModel
1163 }, countVideos = true) {
1164 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1165 throw new Error('Try to filter all-local but no user has not the see all videos right')
1168 const query: FindOptions = {
1169 offset: options.start,
1170 limit: options.count,
1171 order: getVideoSort(options.sort)
1174 let trendingDays: number
1175 if (options.sort.endsWith('trending')) {
1176 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1178 query.group = 'VideoModel.id'
1181 const serverActor = await getServerActor()
1183 // followerActorId === null has a meaning, so just check undefined
1184 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1186 const queryOptions = {
1188 serverAccountId: serverActor.Account.id,
1190 categoryOneOf: options.categoryOneOf,
1191 licenceOneOf: options.licenceOneOf,
1192 languageOneOf: options.languageOneOf,
1193 tagsOneOf: options.tagsOneOf,
1194 tagsAllOf: options.tagsAllOf,
1195 filter: options.filter,
1196 withFiles: options.withFiles,
1197 accountId: options.accountId,
1198 videoChannelId: options.videoChannelId,
1199 videoPlaylistId: options.videoPlaylistId,
1200 includeLocalVideos: options.includeLocalVideos,
1202 historyOfUser: options.historyOfUser,
1206 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1209 static async searchAndPopulateAccountAndServer (options: {
1210 includeLocalVideos: boolean
1215 startDate?: string // ISO 8601
1216 endDate?: string // ISO 8601
1217 originallyPublishedStartDate?: string
1218 originallyPublishedEndDate?: string
1220 categoryOneOf?: number[]
1221 licenceOneOf?: number[]
1222 languageOneOf?: string[]
1223 tagsOneOf?: string[]
1224 tagsAllOf?: string[]
1225 durationMin?: number // seconds
1226 durationMax?: number // seconds
1228 filter?: VideoFilter
1232 if (options.startDate || options.endDate) {
1233 const publishedAtRange = {}
1235 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1236 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1238 whereAnd.push({ publishedAt: publishedAtRange })
1241 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1242 const originallyPublishedAtRange = {}
1244 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1245 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1247 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1250 if (options.durationMin || options.durationMax) {
1251 const durationRange = {}
1253 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1254 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1256 whereAnd.push({ duration: durationRange })
1259 const attributesInclude = []
1260 const escapedSearch = VideoModel.sequelize.escape(options.search)
1261 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1262 if (options.search) {
1266 [ Op.in ]: Sequelize.literal(
1268 'SELECT "video"."id" FROM "video" ' +
1270 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1271 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1273 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1274 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1275 'WHERE "tag"."name" = ' + escapedSearch +
1282 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1285 // Cannot search on similarity if we don't have a search
1286 if (!options.search) {
1287 attributesInclude.push(
1288 Sequelize.literal('0 as similarity')
1292 const query: FindOptions = {
1294 include: attributesInclude
1296 offset: options.start,
1297 limit: options.count,
1298 order: getVideoSort(options.sort),
1300 [ Op.and ]: whereAnd
1304 const serverActor = await getServerActor()
1305 const queryOptions = {
1306 followerActorId: serverActor.id,
1307 serverAccountId: serverActor.Account.id,
1308 includeLocalVideos: options.includeLocalVideos,
1310 categoryOneOf: options.categoryOneOf,
1311 licenceOneOf: options.licenceOneOf,
1312 languageOneOf: options.languageOneOf,
1313 tagsOneOf: options.tagsOneOf,
1314 tagsAllOf: options.tagsAllOf,
1316 filter: options.filter
1319 return VideoModel.getAvailableForApi(query, queryOptions)
1322 static load (id: number | string, t?: Transaction) {
1323 const where = buildWhereIdOrUUID(id)
1329 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1332 static loadWithRights (id: number | string, t?: Transaction) {
1333 const where = buildWhereIdOrUUID(id)
1339 return VideoModel.scope([
1340 ScopeNames.WITH_BLACKLISTED,
1341 ScopeNames.WITH_USER_ID,
1342 ScopeNames.WITH_THUMBNAILS
1346 static loadOnlyId (id: number | string, t?: Transaction) {
1347 const where = buildWhereIdOrUUID(id)
1350 attributes: [ 'id' ],
1355 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1358 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1359 return VideoModel.scope([
1360 ScopeNames.WITH_FILES,
1361 ScopeNames.WITH_STREAMING_PLAYLISTS,
1362 ScopeNames.WITH_THUMBNAILS
1363 ]).findByPk(id, { transaction: t, logging })
1366 static loadByUUIDWithFile (uuid: string) {
1373 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1376 static loadByUrl (url: string, transaction?: Transaction) {
1377 const query: FindOptions = {
1384 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1387 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1388 const query: FindOptions = {
1395 return VideoModel.scope([
1396 ScopeNames.WITH_ACCOUNT_DETAILS,
1397 ScopeNames.WITH_FILES,
1398 ScopeNames.WITH_STREAMING_PLAYLISTS,
1399 ScopeNames.WITH_THUMBNAILS
1403 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1404 const where = buildWhereIdOrUUID(id)
1407 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1413 ScopeNames.WITH_TAGS,
1414 ScopeNames.WITH_BLACKLISTED,
1415 ScopeNames.WITH_ACCOUNT_DETAILS,
1416 ScopeNames.WITH_SCHEDULED_UPDATE,
1417 ScopeNames.WITH_FILES,
1418 ScopeNames.WITH_STREAMING_PLAYLISTS,
1419 ScopeNames.WITH_THUMBNAILS
1423 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1431 static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) {
1432 const where = buildWhereIdOrUUID(id)
1435 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1441 ScopeNames.WITH_TAGS,
1442 ScopeNames.WITH_BLACKLISTED,
1443 ScopeNames.WITH_ACCOUNT_DETAILS,
1444 ScopeNames.WITH_SCHEDULED_UPDATE,
1445 ScopeNames.WITH_THUMBNAILS,
1446 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1447 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1451 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1459 static async getStats () {
1460 const totalLocalVideos = await VideoModel.count({
1465 const totalVideos = await VideoModel.count()
1467 let totalLocalVideoViews = await VideoModel.sum('views', {
1472 // Sequelize could return null...
1473 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1477 totalLocalVideoViews,
1482 static incrementViews (id: number, views: number) {
1483 return VideoModel.increment('views', {
1491 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1492 // Instances only share videos
1493 const query = 'SELECT 1 FROM "videoShare" ' +
1494 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1495 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1499 type: QueryTypes.SELECT,
1500 bind: { followerActorId, videoId },
1504 return VideoModel.sequelize.query(query, options)
1505 .then(results => results.length === 1)
1508 // threshold corresponds to how many video the field should have to be returned
1509 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1510 const serverActor = await getServerActor()
1511 const followerActorId = serverActor.id
1513 const scopeOptions: AvailableForListIDsOptions = {
1514 serverAccountId: serverActor.Account.id,
1516 includeLocalVideos: true
1519 const query: FindOptions = {
1520 attributes: [ field ],
1523 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1524 [ Op.gte ]: threshold
1525 }) as any, // FIXME: typings
1526 order: [ (this.sequelize as any).random() ]
1529 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1531 .then(rows => rows.map(r => r[ field ]))
1534 static buildTrendingQuery (trendingDays: number) {
1538 model: VideoViewModel,
1542 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1548 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1549 if (filter && (filter === 'local' || filter === 'all-local')) {
1558 private static async getAvailableForApi (
1560 options: AvailableForListIDsOptions,
1563 const idsScope: ScopeOptions = {
1565 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1569 // Remove trending sort on count, because it uses a group by
1570 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1571 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1572 const countScope: ScopeOptions = {
1574 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1578 const [ count, rowsId ] = await Promise.all([
1579 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1580 VideoModel.scope(idsScope).findAll(query)
1582 const ids = rowsId.map(r => r.id)
1584 if (ids.length === 0) return { data: [], total: count }
1586 const secondQuery: FindOptions = {
1589 attributes: query.attributes,
1590 order: [ // Keep original order
1592 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1598 const apiScope: any[] = [ ScopeNames.WITH_THUMBNAILS ]
1601 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1603 // Even if the relation is n:m, we know that a user only have 0..1 video history
1604 // So we won't have multiple rows for the same video
1605 // A subquery adds some bugs in our query so disable it
1606 secondQuery.subQuery = false
1611 ScopeNames.FOR_API, {
1613 withFiles: options.withFiles,
1614 videoPlaylistId: options.videoPlaylistId
1619 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1627 static getCategoryLabel (id: number) {
1628 return VIDEO_CATEGORIES[ id ] || 'Misc'
1631 static getLicenceLabel (id: number) {
1632 return VIDEO_LICENCES[ id ] || 'Unknown'
1635 static getLanguageLabel (id: string) {
1636 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1639 static getPrivacyLabel (id: number) {
1640 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1643 static getStateLabel (id: number) {
1644 return VIDEO_STATES[ id ] || 'Unknown'
1647 getOriginalFile () {
1648 if (Array.isArray(this.VideoFiles) === false) return undefined
1650 // The original file is the file that have the higher resolution
1651 return maxBy(this.VideoFiles, file => file.resolution)
1654 addThumbnail (thumbnail: ThumbnailModel) {
1655 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1657 // Already have this thumbnail, skip
1658 if (this.Thumbnails.find(t => t.id === thumbnail.id)) return
1660 this.Thumbnails.push(thumbnail)
1663 getVideoFilename (videoFile: VideoFileModel) {
1664 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1667 generateThumbnailName () {
1668 return this.uuid + '.jpg'
1672 if (Array.isArray(this.Thumbnails) === false) return undefined
1674 return this.Thumbnails.find(t => t.type === ThumbnailType.THUMBNAIL)
1677 generatePreviewName () {
1678 return this.uuid + '.jpg'
1682 if (Array.isArray(this.Thumbnails) === false) return undefined
1684 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1687 getTorrentFileName (videoFile: VideoFileModel) {
1688 const extension = '.torrent'
1689 return this.uuid + '-' + videoFile.resolution + extension
1693 return this.remote === false
1696 getTorrentFilePath (videoFile: VideoFileModel) {
1697 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1700 getVideoFilePath (videoFile: VideoFileModel) {
1701 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1704 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1706 // Keep the extname, it's used by the client to stream the file inside a web browser
1707 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1708 createdBy: 'PeerTube',
1710 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1711 [ WEBSERVER.URL + '/tracker/announce' ]
1713 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1716 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1718 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1719 logger.info('Creating torrent %s.', filePath)
1721 await writeFile(filePath, torrent)
1723 const parsedTorrent = parseTorrent(torrent)
1724 videoFile.infoHash = parsedTorrent.infoHash
1727 getWatchStaticPath () {
1728 return '/videos/watch/' + this.uuid
1731 getEmbedStaticPath () {
1732 return '/videos/embed/' + this.uuid
1735 getThumbnailStaticPath () {
1736 const thumbnail = this.getThumbnail()
1737 if (!thumbnail) return null
1739 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1742 getPreviewStaticPath () {
1743 const preview = this.getPreview()
1744 if (!preview) return null
1746 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1747 return join(STATIC_PATHS.PREVIEWS, preview.filename)
1750 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1751 return videoModelToFormattedJSON(this, options)
1754 toFormattedDetailsJSON (): VideoDetails {
1755 return videoModelToFormattedDetailsJSON(this)
1758 getFormattedVideoFilesJSON (): VideoFile[] {
1759 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1762 toActivityPubObject (): VideoTorrentObject {
1763 return videoModelToActivityPubObject(this)
1766 getTruncatedDescription () {
1767 if (!this.description) return null
1769 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1770 return peertubeTruncate(this.description, maxLength)
1773 getOriginalFileResolution () {
1774 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1776 return getVideoFileResolution(originalFilePath)
1779 getDescriptionAPIPath () {
1780 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1783 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1784 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1786 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1787 return remove(filePath)
1788 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1791 removeTorrent (videoFile: VideoFileModel) {
1792 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1793 return remove(torrentPath)
1794 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1797 removeStreamingPlaylist (isRedundancy = false) {
1798 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1800 const filePath = join(baseDir, this.uuid)
1801 return remove(filePath)
1802 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1806 if (this.isOwned()) return false
1808 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1812 this.changed('updatedAt', true)
1821 if (this.isOwned()) {
1822 baseUrlHttp = WEBSERVER.URL
1823 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1825 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1826 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1829 return { baseUrlHttp, baseUrlWs }
1832 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1833 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1834 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1835 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1837 const redundancies = videoFile.RedundancyVideos
1838 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1840 const magnetHash = {
1844 infoHash: videoFile.infoHash,
1848 return magnetUtil.encode(magnetHash)
1851 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1852 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1855 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1856 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1859 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1860 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1863 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1864 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1867 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1868 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1871 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1872 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1875 getBandwidthBits (videoFile: VideoFileModel) {
1876 return Math.ceil((videoFile.size * 8) / this.duration)