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'
6 import * as Sequelize from 'sequelize'
29 } from 'sequelize-typescript'
30 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
56 HLS_STREAMING_PLAYLIST_DIRECTORY,
57 HLS_REDUNDANCY_DIRECTORY,
60 STATIC_DOWNLOAD_PATHS,
68 } from '../../initializers'
69 import { sendDeleteVideo } from '../../lib/activitypub/send'
70 import { AccountModel } from '../account/account'
71 import { AccountVideoRateModel } from '../account/account-video-rate'
72 import { ActorModel } from '../activitypub/actor'
73 import { AvatarModel } from '../avatar/avatar'
74 import { ServerModel } from '../server/server'
76 buildBlockedAccountSQL,
77 buildTrigramSearchIndex,
79 createSimilarityAttribute,
80 getVideoSort, isOutdated,
83 import { TagModel } from './tag'
84 import { VideoAbuseModel } from './video-abuse'
85 import { VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel'
86 import { VideoCommentModel } from './video-comment'
87 import { VideoFileModel } from './video-file'
88 import { VideoShareModel } from './video-share'
89 import { VideoTagModel } from './video-tag'
90 import { ScheduleVideoUpdateModel } from './schedule-video-update'
91 import { VideoCaptionModel } from './video-caption'
92 import { VideoBlacklistModel } from './video-blacklist'
93 import { remove, writeFile } from 'fs-extra'
94 import { VideoViewModel } from './video-views'
95 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
97 videoFilesModelToFormattedJSON,
98 VideoFormattingJSONOptions,
99 videoModelToActivityPubObject,
100 videoModelToFormattedDetailsJSON,
101 videoModelToFormattedJSON
102 } from './video-format-utils'
103 import { UserVideoHistoryModel } from '../account/user-video-history'
104 import { UserModel } from '../account/user'
105 import { VideoImportModel } from './video-import'
106 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
107 import { VideoPlaylistElementModel } from './video-playlist-element'
109 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
110 const indexes: Sequelize.DefineIndexesOptions[] = [
111 buildTrigramSearchIndex('video_name_trigram', 'name'),
113 { fields: [ 'createdAt' ] },
114 { fields: [ 'publishedAt' ] },
115 { fields: [ 'duration' ] },
116 { fields: [ 'views' ] },
117 { fields: [ 'channelId' ] },
119 fields: [ 'originallyPublishedAt' ],
121 originallyPublishedAt: {
122 [Sequelize.Op.ne]: null
127 fields: [ 'category' ], // We don't care videos with an unknown category
130 [Sequelize.Op.ne]: null
135 fields: [ 'licence' ], // We don't care videos with an unknown licence
138 [Sequelize.Op.ne]: null
143 fields: [ 'language' ], // We don't care videos with an unknown language
146 [Sequelize.Op.ne]: null
151 fields: [ 'nsfw' ], // Most of the videos are not NSFW
157 fields: [ 'remote' ], // Only index local videos
172 export enum ScopeNames {
173 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
175 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
176 WITH_TAGS = 'WITH_TAGS',
177 WITH_FILES = 'WITH_FILES',
178 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
179 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
180 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
181 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
182 WITH_USER_ID = 'WITH_USER_ID'
185 type ForAPIOptions = {
188 videoPlaylistId?: number
193 type AvailableForListIDsOptions = {
194 serverAccountId: number
195 followerActorId: number
196 includeLocalVideos: boolean
199 categoryOneOf?: number[]
201 licenceOneOf?: number[]
202 languageOneOf?: string[]
209 videoChannelId?: number
211 videoPlaylistId?: number
213 trendingDays?: number
215 historyOfUser?: UserModel
219 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
220 const query: IFindOptions<VideoModel> = {
223 [ Sequelize.Op.any ]: options.ids
228 model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }),
234 if (options.withFiles === true) {
236 model: VideoFileModel.unscoped(),
241 if (options.videoPlaylistId) {
243 model: VideoPlaylistElementModel.unscoped(),
246 videoPlaylistId: options.videoPlaylistId
253 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
254 const query: IFindOptions<VideoModel> = {
256 attributes: [ 'id' ],
259 [ Sequelize.Op.and ]: [
261 [ Sequelize.Op.notIn ]: Sequelize.literal(
262 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
268 [ Sequelize.Op.notIn ]: Sequelize.literal(
270 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
271 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
280 // Only list public/published videos
281 if (!options.filter || options.filter !== 'all-local') {
282 const privacyWhere = {
283 // Always list public videos
284 privacy: VideoPrivacy.PUBLIC,
285 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
286 [ Sequelize.Op.or ]: [
288 state: VideoState.PUBLISHED
291 [ Sequelize.Op.and ]: {
292 state: VideoState.TO_TRANSCODE,
293 waitTranscoding: false
299 Object.assign(query.where, privacyWhere)
302 if (options.videoPlaylistId) {
305 model: VideoPlaylistElementModel.unscoped(),
308 videoPlaylistId: options.videoPlaylistId
312 query.subQuery = false
315 if (options.filter || options.accountId || options.videoChannelId) {
316 const videoChannelInclude: IIncludeOptions = {
318 model: VideoChannelModel.unscoped(),
322 if (options.videoChannelId) {
323 videoChannelInclude.where = {
324 id: options.videoChannelId
328 if (options.filter || options.accountId) {
329 const accountInclude: IIncludeOptions = {
331 model: AccountModel.unscoped(),
335 if (options.filter) {
336 accountInclude.include = [
339 model: ActorModel.unscoped(),
341 where: VideoModel.buildActorWhereWithFilter(options.filter)
346 if (options.accountId) {
347 accountInclude.where = { id: options.accountId }
350 videoChannelInclude.include = [ accountInclude ]
353 query.include.push(videoChannelInclude)
356 if (options.followerActorId) {
357 let localVideosReq = ''
358 if (options.includeLocalVideos === true) {
359 localVideosReq = ' UNION ALL ' +
360 'SELECT "video"."id" AS "id" FROM "video" ' +
361 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
362 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
363 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
364 'WHERE "actor"."serverId" IS NULL'
367 // Force actorId to be a number to avoid SQL injections
368 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
369 query.where[ 'id' ][ Sequelize.Op.and ].push({
370 [ Sequelize.Op.in ]: Sequelize.literal(
372 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
373 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
374 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
376 'SELECT "video"."id" AS "id" FROM "video" ' +
377 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
378 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
379 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
380 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
381 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
388 if (options.withFiles === true) {
389 query.where[ 'id' ][ Sequelize.Op.and ].push({
390 [ Sequelize.Op.in ]: Sequelize.literal(
391 '(SELECT "videoId" FROM "videoFile")'
396 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
397 if (options.tagsAllOf || options.tagsOneOf) {
398 const createTagsIn = (tags: string[]) => {
399 return tags.map(t => VideoModel.sequelize.escape(t))
403 if (options.tagsOneOf) {
404 query.where[ 'id' ][ Sequelize.Op.and ].push({
405 [ Sequelize.Op.in ]: Sequelize.literal(
407 'SELECT "videoId" FROM "videoTag" ' +
408 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
409 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
415 if (options.tagsAllOf) {
416 query.where[ 'id' ][ Sequelize.Op.and ].push({
417 [ Sequelize.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.tagsAllOf) + ')' +
422 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
429 if (options.nsfw === true || options.nsfw === false) {
430 query.where[ 'nsfw' ] = options.nsfw
433 if (options.categoryOneOf) {
434 query.where[ 'category' ] = {
435 [ Sequelize.Op.or ]: options.categoryOneOf
439 if (options.licenceOneOf) {
440 query.where[ 'licence' ] = {
441 [ Sequelize.Op.or ]: options.licenceOneOf
445 if (options.languageOneOf) {
446 query.where[ 'language' ] = {
447 [ Sequelize.Op.or ]: options.languageOneOf
451 if (options.trendingDays) {
452 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
454 query.subQuery = false
457 if (options.historyOfUser) {
459 model: UserVideoHistoryModel,
462 userId: options.historyOfUser.id
466 // Even if the relation is n:m, we know that a user only have 0..1 video history
467 // So we won't have multiple rows for the same video
468 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
469 query.subQuery = false
474 [ ScopeNames.WITH_USER_ID ]: {
477 attributes: [ 'accountId' ],
478 model: () => VideoChannelModel.unscoped(),
482 attributes: [ 'userId' ],
483 model: () => AccountModel.unscoped(),
490 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
493 model: () => VideoChannelModel.unscoped(),
498 exclude: [ 'privateKey', 'publicKey' ]
500 model: () => ActorModel.unscoped(),
504 attributes: [ 'host' ],
505 model: () => ServerModel.unscoped(),
509 model: () => AvatarModel.unscoped(),
515 model: () => AccountModel.unscoped(),
519 model: () => ActorModel.unscoped(),
521 exclude: [ 'privateKey', 'publicKey' ]
526 attributes: [ 'host' ],
527 model: () => ServerModel.unscoped(),
531 model: () => AvatarModel.unscoped(),
542 [ ScopeNames.WITH_TAGS ]: {
543 include: [ () => TagModel ]
545 [ ScopeNames.WITH_BLACKLISTED ]: {
548 attributes: [ 'id', 'reason' ],
549 model: () => VideoBlacklistModel,
554 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
555 let subInclude: any[] = []
557 if (withRedundancies === true) {
560 attributes: [ 'fileUrl' ],
561 model: VideoRedundancyModel.unscoped(),
570 model: VideoFileModel.unscoped(),
572 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
579 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
580 let subInclude: any[] = []
582 if (withRedundancies === true) {
585 attributes: [ 'fileUrl' ],
586 model: VideoRedundancyModel.unscoped(),
595 model: VideoStreamingPlaylistModel.unscoped(),
597 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
604 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
607 model: () => ScheduleVideoUpdateModel.unscoped(),
612 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
616 attributes: [ 'currentTime' ],
617 model: UserVideoHistoryModel.unscoped(),
631 export class VideoModel extends Model<VideoModel> {
634 @Default(DataType.UUIDV4)
636 @Column(DataType.UUID)
640 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
646 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
652 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
658 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
659 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
663 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
668 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
674 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
675 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
680 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
681 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
685 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
715 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
716 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
721 commentsEnabled: boolean
725 downloadEnabled: boolean
729 waitTranscoding: boolean
733 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
744 @Default(Sequelize.NOW)
751 originallyPublishedAt: Date
753 @ForeignKey(() => VideoChannelModel)
757 @BelongsTo(() => VideoChannelModel, {
763 VideoChannel: VideoChannelModel
765 @BelongsToMany(() => TagModel, {
766 foreignKey: 'videoId',
767 through: () => VideoTagModel,
772 @HasMany(() => VideoPlaylistElementModel, {
779 VideoPlaylistElements: VideoPlaylistElementModel[]
781 @HasMany(() => VideoAbuseModel, {
788 VideoAbuses: VideoAbuseModel[]
790 @HasMany(() => VideoFileModel, {
798 VideoFiles: VideoFileModel[]
800 @HasMany(() => VideoStreamingPlaylistModel, {
808 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
810 @HasMany(() => VideoShareModel, {
817 VideoShares: VideoShareModel[]
819 @HasMany(() => AccountVideoRateModel, {
826 AccountVideoRates: AccountVideoRateModel[]
828 @HasMany(() => VideoCommentModel, {
836 VideoComments: VideoCommentModel[]
838 @HasMany(() => VideoViewModel, {
845 VideoViews: VideoViewModel[]
847 @HasMany(() => UserVideoHistoryModel, {
854 UserVideoHistories: UserVideoHistoryModel[]
856 @HasOne(() => ScheduleVideoUpdateModel, {
863 ScheduleVideoUpdate: ScheduleVideoUpdateModel
865 @HasOne(() => VideoBlacklistModel, {
872 VideoBlacklist: VideoBlacklistModel
874 @HasOne(() => VideoImportModel, {
881 VideoImport: VideoImportModel
883 @HasMany(() => VideoCaptionModel, {
890 [ 'separate' as any ]: true
892 VideoCaptions: VideoCaptionModel[]
895 static async sendDelete (instance: VideoModel, options) {
896 if (instance.isOwned()) {
897 if (!instance.VideoChannel) {
898 instance.VideoChannel = await instance.$get('VideoChannel', {
902 include: [ ActorModel ]
905 transaction: options.transaction
906 }) as VideoChannelModel
909 return sendDeleteVideo(instance, options.transaction)
916 static async removeFiles (instance: VideoModel) {
917 const tasks: Promise<any>[] = []
919 logger.info('Removing files of video %s.', instance.url)
921 tasks.push(instance.removeThumbnail())
923 if (instance.isOwned()) {
924 if (!Array.isArray(instance.VideoFiles)) {
925 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
928 tasks.push(instance.removePreview())
930 // Remove physical files and torrents
931 instance.VideoFiles.forEach(file => {
932 tasks.push(instance.removeFile(file))
933 tasks.push(instance.removeTorrent(file))
936 // Remove playlists file
937 tasks.push(instance.removeStreamingPlaylist())
940 // Do not wait video deletion because we could be in a transaction
943 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
949 static listLocal () {
956 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
959 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
960 function getRawQuery (select: string) {
961 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
962 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
963 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
964 'WHERE "Account"."actorId" = ' + actorId
965 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
966 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
967 'WHERE "VideoShare"."actorId" = ' + actorId
969 return `(${queryVideo}) UNION (${queryVideoShare})`
972 const rawQuery = getRawQuery('"Video"."id"')
973 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
979 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
982 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
984 [ Sequelize.Op.or ]: [
985 { privacy: VideoPrivacy.PUBLIC },
986 { privacy: VideoPrivacy.UNLISTED }
991 attributes: [ 'language' ],
992 model: VideoCaptionModel.unscoped(),
996 attributes: [ 'id', 'url' ],
997 model: VideoShareModel.unscoped(),
999 // We only want videos shared by this actor
1001 [ Sequelize.Op.and ]: [
1004 [ Sequelize.Op.not ]: null
1014 attributes: [ 'id', 'url' ],
1015 model: ActorModel.unscoped()
1020 model: VideoChannelModel.unscoped(),
1024 attributes: [ 'name' ],
1025 model: AccountModel.unscoped(),
1029 attributes: [ 'id', 'url', 'followersUrl' ],
1030 model: ActorModel.unscoped(),
1036 attributes: [ 'id', 'url', 'followersUrl' ],
1037 model: ActorModel.unscoped(),
1047 return Bluebird.all([
1048 // FIXME: typing issue
1049 VideoModel.findAll(query as any),
1050 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1051 ]).then(([ rows, totals ]) => {
1052 // totals: totalVideos + totalVideoShares
1054 let totalVideoShares = 0
1055 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1056 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1058 const total = totalVideos + totalVideoShares
1066 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1067 const query: IFindOptions<VideoModel> = {
1070 order: getVideoSort(sort),
1073 model: VideoChannelModel,
1077 model: AccountModel,
1086 model: ScheduleVideoUpdateModel,
1090 model: VideoBlacklistModel,
1096 if (withFiles === true) {
1097 query.include.push({
1098 model: VideoFileModel.unscoped(),
1103 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1111 static async listForApi (options: {
1116 includeLocalVideos: boolean,
1118 categoryOneOf?: number[],
1119 licenceOneOf?: number[],
1120 languageOneOf?: string[],
1121 tagsOneOf?: string[],
1122 tagsAllOf?: string[],
1123 filter?: VideoFilter,
1125 videoChannelId?: number,
1126 followerActorId?: number
1127 videoPlaylistId?: number,
1128 trendingDays?: number,
1130 historyOfUser?: UserModel
1131 }, countVideos = true) {
1132 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1133 throw new Error('Try to filter all-local but no user has not the see all videos right')
1136 const query: IFindOptions<VideoModel> = {
1137 offset: options.start,
1138 limit: options.count,
1139 order: getVideoSort(options.sort)
1142 let trendingDays: number
1143 if (options.sort.endsWith('trending')) {
1144 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1146 query.group = 'VideoModel.id'
1149 const serverActor = await getServerActor()
1151 // followerActorId === null has a meaning, so just check undefined
1152 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1154 const queryOptions = {
1156 serverAccountId: serverActor.Account.id,
1158 categoryOneOf: options.categoryOneOf,
1159 licenceOneOf: options.licenceOneOf,
1160 languageOneOf: options.languageOneOf,
1161 tagsOneOf: options.tagsOneOf,
1162 tagsAllOf: options.tagsAllOf,
1163 filter: options.filter,
1164 withFiles: options.withFiles,
1165 accountId: options.accountId,
1166 videoChannelId: options.videoChannelId,
1167 videoPlaylistId: options.videoPlaylistId,
1168 includeLocalVideos: options.includeLocalVideos,
1170 historyOfUser: options.historyOfUser,
1174 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1177 static async searchAndPopulateAccountAndServer (options: {
1178 includeLocalVideos: boolean
1183 startDate?: string // ISO 8601
1184 endDate?: string // ISO 8601
1185 originallyPublishedStartDate?: string
1186 originallyPublishedEndDate?: string
1188 categoryOneOf?: number[]
1189 licenceOneOf?: number[]
1190 languageOneOf?: string[]
1191 tagsOneOf?: string[]
1192 tagsAllOf?: string[]
1193 durationMin?: number // seconds
1194 durationMax?: number // seconds
1196 filter?: VideoFilter
1200 if (options.startDate || options.endDate) {
1201 const publishedAtRange = {}
1203 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1204 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1206 whereAnd.push({ publishedAt: publishedAtRange })
1209 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1210 const originallyPublishedAtRange = {}
1212 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1213 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1215 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1218 if (options.durationMin || options.durationMax) {
1219 const durationRange = {}
1221 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1222 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1224 whereAnd.push({ duration: durationRange })
1227 const attributesInclude = []
1228 const escapedSearch = VideoModel.sequelize.escape(options.search)
1229 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1230 if (options.search) {
1234 [ Sequelize.Op.in ]: Sequelize.literal(
1236 'SELECT "video"."id" FROM "video" ' +
1238 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1239 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1241 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1242 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1243 'WHERE "tag"."name" = ' + escapedSearch +
1250 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1253 // Cannot search on similarity if we don't have a search
1254 if (!options.search) {
1255 attributesInclude.push(
1256 Sequelize.literal('0 as similarity')
1260 const query: IFindOptions<VideoModel> = {
1262 include: attributesInclude
1264 offset: options.start,
1265 limit: options.count,
1266 order: getVideoSort(options.sort),
1268 [ Sequelize.Op.and ]: whereAnd
1272 const serverActor = await getServerActor()
1273 const queryOptions = {
1274 followerActorId: serverActor.id,
1275 serverAccountId: serverActor.Account.id,
1276 includeLocalVideos: options.includeLocalVideos,
1278 categoryOneOf: options.categoryOneOf,
1279 licenceOneOf: options.licenceOneOf,
1280 languageOneOf: options.languageOneOf,
1281 tagsOneOf: options.tagsOneOf,
1282 tagsAllOf: options.tagsAllOf,
1284 filter: options.filter
1287 return VideoModel.getAvailableForApi(query, queryOptions)
1290 static load (id: number | string, t?: Sequelize.Transaction) {
1291 const where = buildWhereIdOrUUID(id)
1297 return VideoModel.findOne(options)
1300 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1301 const where = buildWhereIdOrUUID(id)
1307 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1310 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1311 const where = buildWhereIdOrUUID(id)
1314 attributes: [ 'id' ],
1319 return VideoModel.findOne(options)
1322 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1323 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1324 .findByPk(id, { transaction: t, logging })
1327 static loadByUUIDWithFile (uuid: string) {
1334 return VideoModel.findOne(options)
1337 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1338 const query: IFindOptions<VideoModel> = {
1345 return VideoModel.findOne(query)
1348 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1349 const query: IFindOptions<VideoModel> = {
1356 return VideoModel.scope([
1357 ScopeNames.WITH_ACCOUNT_DETAILS,
1358 ScopeNames.WITH_FILES,
1359 ScopeNames.WITH_STREAMING_PLAYLISTS
1363 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1364 const where = buildWhereIdOrUUID(id)
1367 order: [ [ 'Tags', 'name', 'ASC' ] ],
1373 ScopeNames.WITH_TAGS,
1374 ScopeNames.WITH_BLACKLISTED,
1375 ScopeNames.WITH_ACCOUNT_DETAILS,
1376 ScopeNames.WITH_SCHEDULED_UPDATE,
1377 ScopeNames.WITH_FILES,
1378 ScopeNames.WITH_STREAMING_PLAYLISTS
1382 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1390 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1391 const where = buildWhereIdOrUUID(id)
1394 order: [ [ 'Tags', 'name', 'ASC' ] ],
1400 ScopeNames.WITH_TAGS,
1401 ScopeNames.WITH_BLACKLISTED,
1402 ScopeNames.WITH_ACCOUNT_DETAILS,
1403 ScopeNames.WITH_SCHEDULED_UPDATE,
1404 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1405 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1409 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1417 static async getStats () {
1418 const totalLocalVideos = await VideoModel.count({
1423 const totalVideos = await VideoModel.count()
1425 let totalLocalVideoViews = await VideoModel.sum('views', {
1430 // Sequelize could return null...
1431 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1435 totalLocalVideoViews,
1440 static incrementViews (id: number, views: number) {
1441 return VideoModel.increment('views', {
1449 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1450 // Instances only share videos
1451 const query = 'SELECT 1 FROM "videoShare" ' +
1452 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1453 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1457 type: Sequelize.QueryTypes.SELECT,
1458 bind: { followerActorId, videoId },
1462 return VideoModel.sequelize.query(query, options)
1463 .then(results => results.length === 1)
1466 // threshold corresponds to how many video the field should have to be returned
1467 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1468 const serverActor = await getServerActor()
1469 const followerActorId = serverActor.id
1471 const scopeOptions: AvailableForListIDsOptions = {
1472 serverAccountId: serverActor.Account.id,
1474 includeLocalVideos: true
1477 const query: IFindOptions<VideoModel> = {
1478 attributes: [ field ],
1481 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1482 [ Sequelize.Op.gte ]: threshold
1483 }) as any, // FIXME: typings
1484 order: [ this.sequelize.random() ]
1487 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1489 .then(rows => rows.map(r => r[ field ]))
1492 static buildTrendingQuery (trendingDays: number) {
1496 model: VideoViewModel,
1500 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1506 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1507 if (filter && (filter === 'local' || filter === 'all-local')) {
1516 private static async getAvailableForApi (
1517 query: IFindOptions<VideoModel>,
1518 options: AvailableForListIDsOptions,
1523 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1527 // Remove trending sort on count, because it uses a group by
1528 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1529 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1530 const countScope = {
1532 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1536 const [ count, rowsId ] = await Promise.all([
1537 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1538 VideoModel.scope(idsScope).findAll(query)
1540 const ids = rowsId.map(r => r.id)
1542 if (ids.length === 0) return { data: [], total: count }
1544 const secondQuery: IFindOptions<VideoModel> = {
1547 attributes: query.attributes,
1548 order: [ // Keep original order
1550 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1556 const apiScope: any[] = []
1559 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1561 // Even if the relation is n:m, we know that a user only have 0..1 video history
1562 // So we won't have multiple rows for the same video
1563 // A subquery adds some bugs in our query so disable it
1564 secondQuery.subQuery = false
1569 ScopeNames.FOR_API, {
1571 withFiles: options.withFiles,
1572 videoPlaylistId: options.videoPlaylistId
1577 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1585 static getCategoryLabel (id: number) {
1586 return VIDEO_CATEGORIES[ id ] || 'Misc'
1589 static getLicenceLabel (id: number) {
1590 return VIDEO_LICENCES[ id ] || 'Unknown'
1593 static getLanguageLabel (id: string) {
1594 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1597 static getPrivacyLabel (id: number) {
1598 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1601 static getStateLabel (id: number) {
1602 return VIDEO_STATES[ id ] || 'Unknown'
1605 getOriginalFile () {
1606 if (Array.isArray(this.VideoFiles) === false) return undefined
1608 // The original file is the file that have the higher resolution
1609 return maxBy(this.VideoFiles, file => file.resolution)
1612 getVideoFilename (videoFile: VideoFileModel) {
1613 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1616 getThumbnailName () {
1617 const extension = '.jpg'
1618 return this.uuid + extension
1622 const extension = '.jpg'
1623 return this.uuid + extension
1626 getTorrentFileName (videoFile: VideoFileModel) {
1627 const extension = '.torrent'
1628 return this.uuid + '-' + videoFile.resolution + extension
1632 return this.remote === false
1635 createPreview (videoFile: VideoFileModel) {
1636 return generateImageFromVideoFile(
1637 this.getVideoFilePath(videoFile),
1638 CONFIG.STORAGE.PREVIEWS_DIR,
1639 this.getPreviewName(),
1644 createThumbnail (videoFile: VideoFileModel) {
1645 return generateImageFromVideoFile(
1646 this.getVideoFilePath(videoFile),
1647 CONFIG.STORAGE.THUMBNAILS_DIR,
1648 this.getThumbnailName(),
1653 getTorrentFilePath (videoFile: VideoFileModel) {
1654 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1657 getVideoFilePath (videoFile: VideoFileModel) {
1658 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1661 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1663 // Keep the extname, it's used by the client to stream the file inside a web browser
1664 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1665 createdBy: 'PeerTube',
1667 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1668 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1670 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1673 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1675 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1676 logger.info('Creating torrent %s.', filePath)
1678 await writeFile(filePath, torrent)
1680 const parsedTorrent = parseTorrent(torrent)
1681 videoFile.infoHash = parsedTorrent.infoHash
1684 getWatchStaticPath () {
1685 return '/videos/watch/' + this.uuid
1688 getEmbedStaticPath () {
1689 return '/videos/embed/' + this.uuid
1692 getThumbnailStaticPath () {
1693 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1696 getPreviewStaticPath () {
1697 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1700 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1701 return videoModelToFormattedJSON(this, options)
1704 toFormattedDetailsJSON (): VideoDetails {
1705 return videoModelToFormattedDetailsJSON(this)
1708 getFormattedVideoFilesJSON (): VideoFile[] {
1709 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1712 toActivityPubObject (): VideoTorrentObject {
1713 return videoModelToActivityPubObject(this)
1716 getTruncatedDescription () {
1717 if (!this.description) return null
1719 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1720 return peertubeTruncate(this.description, maxLength)
1723 getOriginalFileResolution () {
1724 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1726 return getVideoFileResolution(originalFilePath)
1729 getDescriptionAPIPath () {
1730 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1733 removeThumbnail () {
1734 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1735 return remove(thumbnailPath)
1736 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1740 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1741 return remove(previewPath)
1742 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1745 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1746 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1748 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1749 return remove(filePath)
1750 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1753 removeTorrent (videoFile: VideoFileModel) {
1754 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1755 return remove(torrentPath)
1756 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1759 removeStreamingPlaylist (isRedundancy = false) {
1760 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1762 const filePath = join(baseDir, this.uuid)
1763 return remove(filePath)
1764 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1768 if (this.isOwned()) return false
1770 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1774 this.changed('updatedAt', true)
1783 if (this.isOwned()) {
1784 baseUrlHttp = CONFIG.WEBSERVER.URL
1785 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1787 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1788 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1791 return { baseUrlHttp, baseUrlWs }
1794 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1795 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1796 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1797 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1799 const redundancies = videoFile.RedundancyVideos
1800 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1802 const magnetHash = {
1806 infoHash: videoFile.infoHash,
1810 return magnetUtil.encode(magnetHash)
1813 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1814 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1817 getThumbnailUrl (baseUrlHttp: string) {
1818 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1821 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1822 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1825 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1826 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1829 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1830 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1833 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1834 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1837 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1838 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1841 getBandwidthBits (videoFile: VideoFileModel) {
1842 return Math.ceil((videoFile.size * 8) / this.duration)