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,
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 ] })
233 if (options.withFiles === true) {
235 model: VideoFileModel.unscoped(),
240 if (options.videoPlaylistId) {
242 model: VideoPlaylistElementModel.unscoped(),
245 videoPlaylistId: options.videoPlaylistId
252 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
253 const query: IFindOptions<VideoModel> = {
255 attributes: [ 'id' ],
258 [ Sequelize.Op.and ]: [
260 [ Sequelize.Op.notIn ]: Sequelize.literal(
261 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
267 [ Sequelize.Op.notIn ]: Sequelize.literal(
269 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
270 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
279 // Only list public/published videos
280 if (!options.filter || options.filter !== 'all-local') {
281 const privacyWhere = {
282 // Always list public videos
283 privacy: VideoPrivacy.PUBLIC,
284 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
285 [ Sequelize.Op.or ]: [
287 state: VideoState.PUBLISHED
290 [ Sequelize.Op.and ]: {
291 state: VideoState.TO_TRANSCODE,
292 waitTranscoding: false
298 Object.assign(query.where, privacyWhere)
301 if (options.videoPlaylistId) {
304 model: VideoPlaylistElementModel.unscoped(),
307 videoPlaylistId: options.videoPlaylistId
311 query.subQuery = false
314 if (options.filter || options.accountId || options.videoChannelId) {
315 const videoChannelInclude: IIncludeOptions = {
317 model: VideoChannelModel.unscoped(),
321 if (options.videoChannelId) {
322 videoChannelInclude.where = {
323 id: options.videoChannelId
327 if (options.filter || options.accountId) {
328 const accountInclude: IIncludeOptions = {
330 model: AccountModel.unscoped(),
334 if (options.filter) {
335 accountInclude.include = [
338 model: ActorModel.unscoped(),
340 where: VideoModel.buildActorWhereWithFilter(options.filter)
345 if (options.accountId) {
346 accountInclude.where = { id: options.accountId }
349 videoChannelInclude.include = [ accountInclude ]
352 query.include.push(videoChannelInclude)
355 if (options.followerActorId) {
356 let localVideosReq = ''
357 if (options.includeLocalVideos === true) {
358 localVideosReq = ' UNION ALL ' +
359 'SELECT "video"."id" AS "id" FROM "video" ' +
360 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
361 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
362 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
363 'WHERE "actor"."serverId" IS NULL'
366 // Force actorId to be a number to avoid SQL injections
367 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
368 query.where[ 'id' ][ Sequelize.Op.and ].push({
369 [ Sequelize.Op.in ]: Sequelize.literal(
371 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
372 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
373 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
375 'SELECT "video"."id" AS "id" FROM "video" ' +
376 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
377 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
378 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
379 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
380 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
387 if (options.withFiles === true) {
388 query.where[ 'id' ][ Sequelize.Op.and ].push({
389 [ Sequelize.Op.in ]: Sequelize.literal(
390 '(SELECT "videoId" FROM "videoFile")'
395 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
396 if (options.tagsAllOf || options.tagsOneOf) {
397 const createTagsIn = (tags: string[]) => {
398 return tags.map(t => VideoModel.sequelize.escape(t))
402 if (options.tagsOneOf) {
403 query.where[ 'id' ][ Sequelize.Op.and ].push({
404 [ Sequelize.Op.in ]: Sequelize.literal(
406 'SELECT "videoId" FROM "videoTag" ' +
407 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
408 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
414 if (options.tagsAllOf) {
415 query.where[ 'id' ][ Sequelize.Op.and ].push({
416 [ Sequelize.Op.in ]: Sequelize.literal(
418 'SELECT "videoId" FROM "videoTag" ' +
419 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
420 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
421 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
428 if (options.nsfw === true || options.nsfw === false) {
429 query.where[ 'nsfw' ] = options.nsfw
432 if (options.categoryOneOf) {
433 query.where[ 'category' ] = {
434 [ Sequelize.Op.or ]: options.categoryOneOf
438 if (options.licenceOneOf) {
439 query.where[ 'licence' ] = {
440 [ Sequelize.Op.or ]: options.licenceOneOf
444 if (options.languageOneOf) {
445 query.where[ 'language' ] = {
446 [ Sequelize.Op.or ]: options.languageOneOf
450 if (options.trendingDays) {
451 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
453 query.subQuery = false
456 if (options.historyOfUser) {
458 model: UserVideoHistoryModel,
461 userId: options.historyOfUser.id
465 // Even if the relation is n:m, we know that a user only have 0..1 video history
466 // So we won't have multiple rows for the same video
467 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
468 query.subQuery = false
473 [ ScopeNames.WITH_USER_ID ]: {
476 attributes: [ 'accountId' ],
477 model: () => VideoChannelModel.unscoped(),
481 attributes: [ 'userId' ],
482 model: () => AccountModel.unscoped(),
489 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
492 model: () => VideoChannelModel.unscoped(),
497 exclude: [ 'privateKey', 'publicKey' ]
499 model: () => ActorModel.unscoped(),
503 attributes: [ 'host' ],
504 model: () => ServerModel.unscoped(),
508 model: () => AvatarModel.unscoped(),
514 model: () => AccountModel.unscoped(),
518 model: () => ActorModel.unscoped(),
520 exclude: [ 'privateKey', 'publicKey' ]
525 attributes: [ 'host' ],
526 model: () => ServerModel.unscoped(),
530 model: () => AvatarModel.unscoped(),
541 [ ScopeNames.WITH_TAGS ]: {
542 include: [ () => TagModel ]
544 [ ScopeNames.WITH_BLACKLISTED ]: {
547 attributes: [ 'id', 'reason' ],
548 model: () => VideoBlacklistModel,
553 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
554 let subInclude: any[] = []
556 if (withRedundancies === true) {
559 attributes: [ 'fileUrl' ],
560 model: VideoRedundancyModel.unscoped(),
569 model: VideoFileModel.unscoped(),
571 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
578 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
579 let subInclude: any[] = []
581 if (withRedundancies === true) {
584 attributes: [ 'fileUrl' ],
585 model: VideoRedundancyModel.unscoped(),
594 model: VideoStreamingPlaylistModel.unscoped(),
596 [ 'separate' as any ]: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
603 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
606 model: () => ScheduleVideoUpdateModel.unscoped(),
611 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
615 attributes: [ 'currentTime' ],
616 model: UserVideoHistoryModel.unscoped(),
630 export class VideoModel extends Model<VideoModel> {
633 @Default(DataType.UUIDV4)
635 @Column(DataType.UUID)
639 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
645 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
651 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
657 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
658 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
662 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
667 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
673 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
674 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
679 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
680 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
684 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
714 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
715 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
720 commentsEnabled: boolean
724 downloadEnabled: boolean
728 waitTranscoding: boolean
732 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
743 @Default(Sequelize.NOW)
750 originallyPublishedAt: Date
752 @ForeignKey(() => VideoChannelModel)
756 @BelongsTo(() => VideoChannelModel, {
762 VideoChannel: VideoChannelModel
764 @BelongsToMany(() => TagModel, {
765 foreignKey: 'videoId',
766 through: () => VideoTagModel,
771 @HasMany(() => VideoPlaylistElementModel, {
778 VideoPlaylistElements: VideoPlaylistElementModel[]
780 @HasMany(() => VideoAbuseModel, {
787 VideoAbuses: VideoAbuseModel[]
789 @HasMany(() => VideoFileModel, {
797 VideoFiles: VideoFileModel[]
799 @HasMany(() => VideoStreamingPlaylistModel, {
807 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
809 @HasMany(() => VideoShareModel, {
816 VideoShares: VideoShareModel[]
818 @HasMany(() => AccountVideoRateModel, {
825 AccountVideoRates: AccountVideoRateModel[]
827 @HasMany(() => VideoCommentModel, {
835 VideoComments: VideoCommentModel[]
837 @HasMany(() => VideoViewModel, {
844 VideoViews: VideoViewModel[]
846 @HasMany(() => UserVideoHistoryModel, {
853 UserVideoHistories: UserVideoHistoryModel[]
855 @HasOne(() => ScheduleVideoUpdateModel, {
862 ScheduleVideoUpdate: ScheduleVideoUpdateModel
864 @HasOne(() => VideoBlacklistModel, {
871 VideoBlacklist: VideoBlacklistModel
873 @HasOne(() => VideoImportModel, {
880 VideoImport: VideoImportModel
882 @HasMany(() => VideoCaptionModel, {
889 [ 'separate' as any ]: true
891 VideoCaptions: VideoCaptionModel[]
894 static async sendDelete (instance: VideoModel, options) {
895 if (instance.isOwned()) {
896 if (!instance.VideoChannel) {
897 instance.VideoChannel = await instance.$get('VideoChannel', {
901 include: [ ActorModel ]
904 transaction: options.transaction
905 }) as VideoChannelModel
908 return sendDeleteVideo(instance, options.transaction)
915 static async removeFiles (instance: VideoModel) {
916 const tasks: Promise<any>[] = []
918 logger.info('Removing files of video %s.', instance.url)
920 tasks.push(instance.removeThumbnail())
922 if (instance.isOwned()) {
923 if (!Array.isArray(instance.VideoFiles)) {
924 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
927 tasks.push(instance.removePreview())
929 // Remove physical files and torrents
930 instance.VideoFiles.forEach(file => {
931 tasks.push(instance.removeFile(file))
932 tasks.push(instance.removeTorrent(file))
935 // Remove playlists file
936 tasks.push(instance.removeStreamingPlaylist())
939 // Do not wait video deletion because we could be in a transaction
942 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
948 static listLocal () {
955 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ]).findAll(query)
958 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
959 function getRawQuery (select: string) {
960 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
961 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
962 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
963 'WHERE "Account"."actorId" = ' + actorId
964 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
965 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
966 'WHERE "VideoShare"."actorId" = ' + actorId
968 return `(${queryVideo}) UNION (${queryVideoShare})`
971 const rawQuery = getRawQuery('"Video"."id"')
972 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
978 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
981 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
983 [ Sequelize.Op.or ]: [
984 { privacy: VideoPrivacy.PUBLIC },
985 { privacy: VideoPrivacy.UNLISTED }
990 attributes: [ 'language' ],
991 model: VideoCaptionModel.unscoped(),
995 attributes: [ 'id', 'url' ],
996 model: VideoShareModel.unscoped(),
998 // We only want videos shared by this actor
1000 [ Sequelize.Op.and ]: [
1003 [ Sequelize.Op.not ]: null
1013 attributes: [ 'id', 'url' ],
1014 model: ActorModel.unscoped()
1019 model: VideoChannelModel.unscoped(),
1023 attributes: [ 'name' ],
1024 model: AccountModel.unscoped(),
1028 attributes: [ 'id', 'url', 'followersUrl' ],
1029 model: ActorModel.unscoped(),
1035 attributes: [ 'id', 'url', 'followersUrl' ],
1036 model: ActorModel.unscoped(),
1046 return Bluebird.all([
1047 // FIXME: typing issue
1048 VideoModel.findAll(query as any),
1049 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
1050 ]).then(([ rows, totals ]) => {
1051 // totals: totalVideos + totalVideoShares
1053 let totalVideoShares = 0
1054 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1055 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1057 const total = totalVideos + totalVideoShares
1065 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1066 const query: IFindOptions<VideoModel> = {
1069 order: getVideoSort(sort),
1072 model: VideoChannelModel,
1076 model: AccountModel,
1085 model: ScheduleVideoUpdateModel,
1089 model: VideoBlacklistModel,
1095 if (withFiles === true) {
1096 query.include.push({
1097 model: VideoFileModel.unscoped(),
1102 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1110 static async listForApi (options: {
1115 includeLocalVideos: boolean,
1117 categoryOneOf?: number[],
1118 licenceOneOf?: number[],
1119 languageOneOf?: string[],
1120 tagsOneOf?: string[],
1121 tagsAllOf?: string[],
1122 filter?: VideoFilter,
1124 videoChannelId?: number,
1125 followerActorId?: number
1126 videoPlaylistId?: number,
1127 trendingDays?: number,
1129 historyOfUser?: UserModel
1130 }, countVideos = true) {
1131 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1132 throw new Error('Try to filter all-local but no user has not the see all videos right')
1135 const query: IFindOptions<VideoModel> = {
1136 offset: options.start,
1137 limit: options.count,
1138 order: getVideoSort(options.sort)
1141 let trendingDays: number
1142 if (options.sort.endsWith('trending')) {
1143 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1145 query.group = 'VideoModel.id'
1148 const serverActor = await getServerActor()
1150 // followerActorId === null has a meaning, so just check undefined
1151 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1153 const queryOptions = {
1155 serverAccountId: serverActor.Account.id,
1157 categoryOneOf: options.categoryOneOf,
1158 licenceOneOf: options.licenceOneOf,
1159 languageOneOf: options.languageOneOf,
1160 tagsOneOf: options.tagsOneOf,
1161 tagsAllOf: options.tagsAllOf,
1162 filter: options.filter,
1163 withFiles: options.withFiles,
1164 accountId: options.accountId,
1165 videoChannelId: options.videoChannelId,
1166 videoPlaylistId: options.videoPlaylistId,
1167 includeLocalVideos: options.includeLocalVideos,
1169 historyOfUser: options.historyOfUser,
1173 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1176 static async searchAndPopulateAccountAndServer (options: {
1177 includeLocalVideos: boolean
1182 startDate?: string // ISO 8601
1183 endDate?: string // ISO 8601
1184 originallyPublishedStartDate?: string
1185 originallyPublishedEndDate?: string
1187 categoryOneOf?: number[]
1188 licenceOneOf?: number[]
1189 languageOneOf?: string[]
1190 tagsOneOf?: string[]
1191 tagsAllOf?: string[]
1192 durationMin?: number // seconds
1193 durationMax?: number // seconds
1195 filter?: VideoFilter
1199 if (options.startDate || options.endDate) {
1200 const publishedAtRange = {}
1202 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1203 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1205 whereAnd.push({ publishedAt: publishedAtRange })
1208 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1209 const originallyPublishedAtRange = {}
1211 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Sequelize.Op.gte ] = options.originallyPublishedStartDate
1212 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Sequelize.Op.lte ] = options.originallyPublishedEndDate
1214 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1217 if (options.durationMin || options.durationMax) {
1218 const durationRange = {}
1220 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1221 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1223 whereAnd.push({ duration: durationRange })
1226 const attributesInclude = []
1227 const escapedSearch = VideoModel.sequelize.escape(options.search)
1228 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1229 if (options.search) {
1233 [ Sequelize.Op.in ]: Sequelize.literal(
1235 'SELECT "video"."id" FROM "video" ' +
1237 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1238 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1240 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1241 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1242 'WHERE "tag"."name" = ' + escapedSearch +
1249 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1252 // Cannot search on similarity if we don't have a search
1253 if (!options.search) {
1254 attributesInclude.push(
1255 Sequelize.literal('0 as similarity')
1259 const query: IFindOptions<VideoModel> = {
1261 include: attributesInclude
1263 offset: options.start,
1264 limit: options.count,
1265 order: getVideoSort(options.sort),
1267 [ Sequelize.Op.and ]: whereAnd
1271 const serverActor = await getServerActor()
1272 const queryOptions = {
1273 followerActorId: serverActor.id,
1274 serverAccountId: serverActor.Account.id,
1275 includeLocalVideos: options.includeLocalVideos,
1277 categoryOneOf: options.categoryOneOf,
1278 licenceOneOf: options.licenceOneOf,
1279 languageOneOf: options.languageOneOf,
1280 tagsOneOf: options.tagsOneOf,
1281 tagsAllOf: options.tagsAllOf,
1283 filter: options.filter
1286 return VideoModel.getAvailableForApi(query, queryOptions)
1289 static load (id: number | string, t?: Sequelize.Transaction) {
1290 const where = buildWhereIdOrUUID(id)
1296 return VideoModel.findOne(options)
1299 static loadWithRights (id: number | string, t?: Sequelize.Transaction) {
1300 const where = buildWhereIdOrUUID(id)
1306 return VideoModel.scope([ ScopeNames.WITH_BLACKLISTED, ScopeNames.WITH_USER_ID ]).findOne(options)
1309 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1310 const where = buildWhereIdOrUUID(id)
1313 attributes: [ 'id' ],
1318 return VideoModel.findOne(options)
1321 static loadWithFiles (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1322 return VideoModel.scope([ ScopeNames.WITH_FILES, ScopeNames.WITH_STREAMING_PLAYLISTS ])
1323 .findByPk(id, { transaction: t, logging })
1326 static loadByUUIDWithFile (uuid: string) {
1333 return VideoModel.findOne(options)
1336 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1337 const query: IFindOptions<VideoModel> = {
1344 return VideoModel.findOne(query)
1347 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1348 const query: IFindOptions<VideoModel> = {
1355 return VideoModel.scope([
1356 ScopeNames.WITH_ACCOUNT_DETAILS,
1357 ScopeNames.WITH_FILES,
1358 ScopeNames.WITH_STREAMING_PLAYLISTS
1362 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1363 const where = buildWhereIdOrUUID(id)
1366 order: [ [ 'Tags', 'name', 'ASC' ] ],
1372 ScopeNames.WITH_TAGS,
1373 ScopeNames.WITH_BLACKLISTED,
1374 ScopeNames.WITH_ACCOUNT_DETAILS,
1375 ScopeNames.WITH_SCHEDULED_UPDATE,
1376 ScopeNames.WITH_FILES,
1377 ScopeNames.WITH_STREAMING_PLAYLISTS
1381 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1389 static loadForGetAPI (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1390 const where = buildWhereIdOrUUID(id)
1393 order: [ [ 'Tags', 'name', 'ASC' ] ],
1399 ScopeNames.WITH_TAGS,
1400 ScopeNames.WITH_BLACKLISTED,
1401 ScopeNames.WITH_ACCOUNT_DETAILS,
1402 ScopeNames.WITH_SCHEDULED_UPDATE,
1403 { method: [ ScopeNames.WITH_FILES, true ] } as any, // FIXME: typings
1404 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } as any // FIXME: typings
1408 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1416 static async getStats () {
1417 const totalLocalVideos = await VideoModel.count({
1422 const totalVideos = await VideoModel.count()
1424 let totalLocalVideoViews = await VideoModel.sum('views', {
1429 // Sequelize could return null...
1430 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1434 totalLocalVideoViews,
1439 static incrementViews (id: number, views: number) {
1440 return VideoModel.increment('views', {
1448 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1449 // Instances only share videos
1450 const query = 'SELECT 1 FROM "videoShare" ' +
1451 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1452 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1456 type: Sequelize.QueryTypes.SELECT,
1457 bind: { followerActorId, videoId },
1461 return VideoModel.sequelize.query(query, options)
1462 .then(results => results.length === 1)
1465 // threshold corresponds to how many video the field should have to be returned
1466 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1467 const serverActor = await getServerActor()
1468 const followerActorId = serverActor.id
1470 const scopeOptions: AvailableForListIDsOptions = {
1471 serverAccountId: serverActor.Account.id,
1473 includeLocalVideos: true
1476 const query: IFindOptions<VideoModel> = {
1477 attributes: [ field ],
1480 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1481 [ Sequelize.Op.gte ]: threshold
1482 }) as any, // FIXME: typings
1483 order: [ this.sequelize.random() ]
1486 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1488 .then(rows => rows.map(r => r[ field ]))
1491 static buildTrendingQuery (trendingDays: number) {
1495 model: VideoViewModel,
1499 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1505 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1506 if (filter && (filter === 'local' || filter === 'all-local')) {
1515 private static async getAvailableForApi (
1516 query: IFindOptions<VideoModel>,
1517 options: AvailableForListIDsOptions,
1522 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1526 // Remove trending sort on count, because it uses a group by
1527 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1528 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1529 const countScope = {
1531 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1535 const [ count, rowsId ] = await Promise.all([
1536 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1537 VideoModel.scope(idsScope).findAll(query)
1539 const ids = rowsId.map(r => r.id)
1541 if (ids.length === 0) return { data: [], total: count }
1543 const secondQuery: IFindOptions<VideoModel> = {
1546 attributes: query.attributes,
1547 order: [ // Keep original order
1549 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1555 const apiScope: any[] = []
1558 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1560 // Even if the relation is n:m, we know that a user only have 0..1 video history
1561 // So we won't have multiple rows for the same video
1562 // A subquery adds some bugs in our query so disable it
1563 secondQuery.subQuery = false
1568 ScopeNames.FOR_API, {
1571 videoPlaylistId: options.videoPlaylistId
1576 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1584 static getCategoryLabel (id: number) {
1585 return VIDEO_CATEGORIES[ id ] || 'Misc'
1588 static getLicenceLabel (id: number) {
1589 return VIDEO_LICENCES[ id ] || 'Unknown'
1592 static getLanguageLabel (id: string) {
1593 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1596 static getPrivacyLabel (id: number) {
1597 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1600 static getStateLabel (id: number) {
1601 return VIDEO_STATES[ id ] || 'Unknown'
1604 getOriginalFile () {
1605 if (Array.isArray(this.VideoFiles) === false) return undefined
1607 // The original file is the file that have the higher resolution
1608 return maxBy(this.VideoFiles, file => file.resolution)
1611 getVideoFilename (videoFile: VideoFileModel) {
1612 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1615 getThumbnailName () {
1616 const extension = '.jpg'
1617 return this.uuid + extension
1621 const extension = '.jpg'
1622 return this.uuid + extension
1625 getTorrentFileName (videoFile: VideoFileModel) {
1626 const extension = '.torrent'
1627 return this.uuid + '-' + videoFile.resolution + extension
1631 return this.remote === false
1634 createPreview (videoFile: VideoFileModel) {
1635 return generateImageFromVideoFile(
1636 this.getVideoFilePath(videoFile),
1637 CONFIG.STORAGE.PREVIEWS_DIR,
1638 this.getPreviewName(),
1643 createThumbnail (videoFile: VideoFileModel) {
1644 return generateImageFromVideoFile(
1645 this.getVideoFilePath(videoFile),
1646 CONFIG.STORAGE.THUMBNAILS_DIR,
1647 this.getThumbnailName(),
1652 getTorrentFilePath (videoFile: VideoFileModel) {
1653 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1656 getVideoFilePath (videoFile: VideoFileModel) {
1657 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1660 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1662 // Keep the extname, it's used by the client to stream the file inside a web browser
1663 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1664 createdBy: 'PeerTube',
1666 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1667 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1669 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1672 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1674 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1675 logger.info('Creating torrent %s.', filePath)
1677 await writeFile(filePath, torrent)
1679 const parsedTorrent = parseTorrent(torrent)
1680 videoFile.infoHash = parsedTorrent.infoHash
1683 getWatchStaticPath () {
1684 return '/videos/watch/' + this.uuid
1687 getEmbedStaticPath () {
1688 return '/videos/embed/' + this.uuid
1691 getThumbnailStaticPath () {
1692 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1695 getPreviewStaticPath () {
1696 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1699 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1700 return videoModelToFormattedJSON(this, options)
1703 toFormattedDetailsJSON (): VideoDetails {
1704 return videoModelToFormattedDetailsJSON(this)
1707 getFormattedVideoFilesJSON (): VideoFile[] {
1708 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1711 toActivityPubObject (): VideoTorrentObject {
1712 return videoModelToActivityPubObject(this)
1715 getTruncatedDescription () {
1716 if (!this.description) return null
1718 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1719 return peertubeTruncate(this.description, maxLength)
1722 getOriginalFileResolution () {
1723 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1725 return getVideoFileResolution(originalFilePath)
1728 getDescriptionAPIPath () {
1729 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1732 removeThumbnail () {
1733 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1734 return remove(thumbnailPath)
1735 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1739 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1740 return remove(previewPath)
1741 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1744 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1745 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1747 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1748 return remove(filePath)
1749 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1752 removeTorrent (videoFile: VideoFileModel) {
1753 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1754 return remove(torrentPath)
1755 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1758 removeStreamingPlaylist (isRedundancy = false) {
1759 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1761 const filePath = join(baseDir, this.uuid)
1762 return remove(filePath)
1763 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1767 if (this.isOwned()) return false
1769 const now = Date.now()
1770 const createdAtTime = this.createdAt.getTime()
1771 const updatedAtTime = this.updatedAt.getTime()
1773 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1774 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1778 this.changed('updatedAt', true)
1787 if (this.isOwned()) {
1788 baseUrlHttp = CONFIG.WEBSERVER.URL
1789 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1791 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1792 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1795 return { baseUrlHttp, baseUrlWs }
1798 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1799 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1800 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1801 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1803 const redundancies = videoFile.RedundancyVideos
1804 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1806 const magnetHash = {
1810 infoHash: videoFile.infoHash,
1814 return magnetUtil.encode(magnetHash)
1817 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1818 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1821 getThumbnailUrl (baseUrlHttp: string) {
1822 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1825 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1826 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1829 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1830 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1833 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1834 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1837 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1838 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1841 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1842 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1845 getBandwidthBits (videoFile: VideoFileModel) {
1846 return Math.ceil((videoFile.size * 8) / this.duration)