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'
58 STATIC_DOWNLOAD_PATHS,
66 } from '../../initializers'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { buildBlockedAccountSQL, buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
81 import { ScheduleVideoUpdateModel } from './schedule-video-update'
82 import { VideoCaptionModel } from './video-caption'
83 import { VideoBlacklistModel } from './video-blacklist'
84 import { remove, writeFile } from 'fs-extra'
85 import { VideoViewModel } from './video-views'
86 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
88 videoFilesModelToFormattedJSON,
89 VideoFormattingJSONOptions,
90 videoModelToActivityPubObject,
91 videoModelToFormattedDetailsJSON,
92 videoModelToFormattedJSON
93 } from './video-format-utils'
94 import * as validator from 'validator'
95 import { UserVideoHistoryModel } from '../account/user-video-history'
96 import { UserModel } from '../account/user'
98 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99 const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
125 export enum ScopeNames {
126 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
136 type ForAPIOptions = {
141 type AvailableForListIDsOptions = {
142 serverAccountId: number
143 followerActorId: number
144 includeLocalVideos: boolean
146 categoryOneOf?: number[]
148 licenceOneOf?: number[]
149 languageOneOf?: string[]
154 videoChannelId?: number
155 trendingDays?: number
157 historyOfUser?: UserModel
161 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
162 const accountInclude = {
163 attributes: [ 'id', 'name' ],
164 model: AccountModel.unscoped(),
168 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
169 model: ActorModel.unscoped(),
173 attributes: [ 'host' ],
174 model: ServerModel.unscoped(),
178 model: AvatarModel.unscoped(),
186 const videoChannelInclude = {
187 attributes: [ 'name', 'description', 'id' ],
188 model: VideoChannelModel.unscoped(),
192 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
193 model: ActorModel.unscoped(),
197 attributes: [ 'host' ],
198 model: ServerModel.unscoped(),
202 model: AvatarModel.unscoped(),
211 const query: IFindOptions<VideoModel> = {
214 [ Sequelize.Op.any ]: options.ids
217 include: [ videoChannelInclude ]
220 if (options.withFiles === true) {
222 model: VideoFileModel.unscoped(),
229 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
230 const query: IFindOptions<VideoModel> = {
232 attributes: [ 'id' ],
235 [ Sequelize.Op.and ]: [
237 [ Sequelize.Op.notIn ]: Sequelize.literal(
238 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
244 [ Sequelize.Op.notIn ]: Sequelize.literal(
246 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
247 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
256 // Only list public/published videos
257 if (!options.filter || options.filter !== 'all-local') {
258 const privacyWhere = {
259 // Always list public videos
260 privacy: VideoPrivacy.PUBLIC,
261 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
262 [ Sequelize.Op.or ]: [
264 state: VideoState.PUBLISHED
267 [ Sequelize.Op.and ]: {
268 state: VideoState.TO_TRANSCODE,
269 waitTranscoding: false
275 Object.assign(query.where, privacyWhere)
278 if (options.filter || options.accountId || options.videoChannelId) {
279 const videoChannelInclude: IIncludeOptions = {
281 model: VideoChannelModel.unscoped(),
285 if (options.videoChannelId) {
286 videoChannelInclude.where = {
287 id: options.videoChannelId
291 if (options.filter || options.accountId) {
292 const accountInclude: IIncludeOptions = {
294 model: AccountModel.unscoped(),
298 if (options.filter) {
299 accountInclude.include = [
302 model: ActorModel.unscoped(),
304 where: VideoModel.buildActorWhereWithFilter(options.filter)
309 if (options.accountId) {
310 accountInclude.where = { id: options.accountId }
313 videoChannelInclude.include = [ accountInclude ]
316 query.include.push(videoChannelInclude)
319 if (options.followerActorId) {
320 let localVideosReq = ''
321 if (options.includeLocalVideos === true) {
322 localVideosReq = ' UNION ALL ' +
323 'SELECT "video"."id" AS "id" FROM "video" ' +
324 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
325 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
326 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
327 'WHERE "actor"."serverId" IS NULL'
330 // Force actorId to be a number to avoid SQL injections
331 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
332 query.where[ 'id' ][ Sequelize.Op.and ].push({
333 [ Sequelize.Op.in ]: Sequelize.literal(
335 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
336 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
337 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
339 'SELECT "video"."id" AS "id" FROM "video" ' +
340 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
341 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
342 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
343 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
344 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
351 if (options.withFiles === true) {
352 query.where[ 'id' ][ Sequelize.Op.and ].push({
353 [ Sequelize.Op.in ]: Sequelize.literal(
354 '(SELECT "videoId" FROM "videoFile")'
359 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
360 if (options.tagsAllOf || options.tagsOneOf) {
361 const createTagsIn = (tags: string[]) => {
362 return tags.map(t => VideoModel.sequelize.escape(t))
366 if (options.tagsOneOf) {
367 query.where[ 'id' ][ Sequelize.Op.and ].push({
368 [ Sequelize.Op.in ]: Sequelize.literal(
370 'SELECT "videoId" FROM "videoTag" ' +
371 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
372 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
378 if (options.tagsAllOf) {
379 query.where[ 'id' ][ Sequelize.Op.and ].push({
380 [ Sequelize.Op.in ]: Sequelize.literal(
382 'SELECT "videoId" FROM "videoTag" ' +
383 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
384 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
385 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
392 if (options.nsfw === true || options.nsfw === false) {
393 query.where[ 'nsfw' ] = options.nsfw
396 if (options.categoryOneOf) {
397 query.where[ 'category' ] = {
398 [ Sequelize.Op.or ]: options.categoryOneOf
402 if (options.licenceOneOf) {
403 query.where[ 'licence' ] = {
404 [ Sequelize.Op.or ]: options.licenceOneOf
408 if (options.languageOneOf) {
409 query.where[ 'language' ] = {
410 [ Sequelize.Op.or ]: options.languageOneOf
414 if (options.trendingDays) {
415 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
417 query.subQuery = false
420 if (options.historyOfUser) {
422 model: UserVideoHistoryModel,
425 userId: options.historyOfUser.id
429 // Even if the relation is n:m, we know that a user only have 0..1 video history
430 // So we won't have multiple rows for the same video
431 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
432 query.subQuery = false
437 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
440 model: () => VideoChannelModel.unscoped(),
445 exclude: [ 'privateKey', 'publicKey' ]
447 model: () => ActorModel.unscoped(),
451 attributes: [ 'host' ],
452 model: () => ServerModel.unscoped(),
456 model: () => AvatarModel.unscoped(),
462 model: () => AccountModel.unscoped(),
466 model: () => ActorModel.unscoped(),
468 exclude: [ 'privateKey', 'publicKey' ]
473 attributes: [ 'host' ],
474 model: () => ServerModel.unscoped(),
478 model: () => AvatarModel.unscoped(),
489 [ ScopeNames.WITH_TAGS ]: {
490 include: [ () => TagModel ]
492 [ ScopeNames.WITH_BLACKLISTED ]: {
495 attributes: [ 'id', 'reason' ],
496 model: () => VideoBlacklistModel,
501 [ ScopeNames.WITH_FILES ]: {
504 model: () => VideoFileModel.unscoped(),
506 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
510 attributes: [ 'fileUrl' ],
511 model: () => VideoRedundancyModel.unscoped(),
518 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
521 model: () => ScheduleVideoUpdateModel.unscoped(),
526 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
530 attributes: [ 'currentTime' ],
531 model: UserVideoHistoryModel.unscoped(),
545 export class VideoModel extends Model<VideoModel> {
548 @Default(DataType.UUIDV4)
550 @Column(DataType.UUID)
554 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
560 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
566 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
572 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
573 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
577 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
582 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
588 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
589 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
594 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
595 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
599 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
629 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
630 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
635 commentsEnabled: boolean
639 waitTranscoding: boolean
643 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
654 @Default(Sequelize.NOW)
658 @ForeignKey(() => VideoChannelModel)
662 @BelongsTo(() => VideoChannelModel, {
668 VideoChannel: VideoChannelModel
670 @BelongsToMany(() => TagModel, {
671 foreignKey: 'videoId',
672 through: () => VideoTagModel,
677 @HasMany(() => VideoAbuseModel, {
684 VideoAbuses: VideoAbuseModel[]
686 @HasMany(() => VideoFileModel, {
694 VideoFiles: VideoFileModel[]
696 @HasMany(() => VideoShareModel, {
703 VideoShares: VideoShareModel[]
705 @HasMany(() => AccountVideoRateModel, {
712 AccountVideoRates: AccountVideoRateModel[]
714 @HasMany(() => VideoCommentModel, {
722 VideoComments: VideoCommentModel[]
724 @HasMany(() => VideoViewModel, {
731 VideoViews: VideoViewModel[]
733 @HasMany(() => UserVideoHistoryModel, {
740 UserVideoHistories: UserVideoHistoryModel[]
742 @HasOne(() => ScheduleVideoUpdateModel, {
749 ScheduleVideoUpdate: ScheduleVideoUpdateModel
751 @HasOne(() => VideoBlacklistModel, {
758 VideoBlacklist: VideoBlacklistModel
760 @HasMany(() => VideoCaptionModel, {
767 [ 'separate' as any ]: true
769 VideoCaptions: VideoCaptionModel[]
772 static async sendDelete (instance: VideoModel, options) {
773 if (instance.isOwned()) {
774 if (!instance.VideoChannel) {
775 instance.VideoChannel = await instance.$get('VideoChannel', {
779 include: [ ActorModel ]
782 transaction: options.transaction
783 }) as VideoChannelModel
786 return sendDeleteVideo(instance, options.transaction)
793 static async removeFiles (instance: VideoModel) {
794 const tasks: Promise<any>[] = []
796 logger.info('Removing files of video %s.', instance.url)
798 tasks.push(instance.removeThumbnail())
800 if (instance.isOwned()) {
801 if (!Array.isArray(instance.VideoFiles)) {
802 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
805 tasks.push(instance.removePreview())
807 // Remove physical files and torrents
808 instance.VideoFiles.forEach(file => {
809 tasks.push(instance.removeFile(file))
810 tasks.push(instance.removeTorrent(file))
814 // Do not wait video deletion because we could be in a transaction
817 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
824 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
827 static listLocal () {
834 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
837 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
838 function getRawQuery (select: string) {
839 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
840 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
841 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
842 'WHERE "Account"."actorId" = ' + actorId
843 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
844 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
845 'WHERE "VideoShare"."actorId" = ' + actorId
847 return `(${queryVideo}) UNION (${queryVideoShare})`
850 const rawQuery = getRawQuery('"Video"."id"')
851 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
857 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
860 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
862 [ Sequelize.Op.or ]: [
863 { privacy: VideoPrivacy.PUBLIC },
864 { privacy: VideoPrivacy.UNLISTED }
869 attributes: [ 'language' ],
870 model: VideoCaptionModel.unscoped(),
874 attributes: [ 'id', 'url' ],
875 model: VideoShareModel.unscoped(),
877 // We only want videos shared by this actor
879 [ Sequelize.Op.and ]: [
882 [ Sequelize.Op.not ]: null
892 attributes: [ 'id', 'url' ],
893 model: ActorModel.unscoped()
898 model: VideoChannelModel.unscoped(),
902 attributes: [ 'name' ],
903 model: AccountModel.unscoped(),
907 attributes: [ 'id', 'url', 'followersUrl' ],
908 model: ActorModel.unscoped(),
914 attributes: [ 'id', 'url', 'followersUrl' ],
915 model: ActorModel.unscoped(),
925 return Bluebird.all([
926 // FIXME: typing issue
927 VideoModel.findAll(query as any),
928 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
929 ]).then(([ rows, totals ]) => {
930 // totals: totalVideos + totalVideoShares
932 let totalVideoShares = 0
933 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
934 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
936 const total = totalVideos + totalVideoShares
944 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
945 const query: IFindOptions<VideoModel> = {
948 order: getVideoSort(sort),
951 model: VideoChannelModel,
964 model: ScheduleVideoUpdateModel,
968 model: VideoBlacklistModel,
974 if (withFiles === true) {
976 model: VideoFileModel.unscoped(),
981 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
989 static async listForApi (options: {
994 includeLocalVideos: boolean,
996 categoryOneOf?: number[],
997 licenceOneOf?: number[],
998 languageOneOf?: string[],
999 tagsOneOf?: string[],
1000 tagsAllOf?: string[],
1001 filter?: VideoFilter,
1003 videoChannelId?: number,
1004 followerActorId?: number
1005 trendingDays?: number,
1007 historyOfUser?: UserModel
1008 }, countVideos = true) {
1009 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1010 throw new Error('Try to filter all-local but no user has not the see all videos right')
1013 const query: IFindOptions<VideoModel> = {
1014 offset: options.start,
1015 limit: options.count,
1016 order: getVideoSort(options.sort)
1019 let trendingDays: number
1020 if (options.sort.endsWith('trending')) {
1021 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1023 query.group = 'VideoModel.id'
1026 const serverActor = await getServerActor()
1028 // followerActorId === null has a meaning, so just check undefined
1029 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1031 const queryOptions = {
1033 serverAccountId: serverActor.Account.id,
1035 categoryOneOf: options.categoryOneOf,
1036 licenceOneOf: options.licenceOneOf,
1037 languageOneOf: options.languageOneOf,
1038 tagsOneOf: options.tagsOneOf,
1039 tagsAllOf: options.tagsAllOf,
1040 filter: options.filter,
1041 withFiles: options.withFiles,
1042 accountId: options.accountId,
1043 videoChannelId: options.videoChannelId,
1044 includeLocalVideos: options.includeLocalVideos,
1046 historyOfUser: options.historyOfUser,
1050 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1053 static async searchAndPopulateAccountAndServer (options: {
1054 includeLocalVideos: boolean
1059 startDate?: string // ISO 8601
1060 endDate?: string // ISO 8601
1062 categoryOneOf?: number[]
1063 licenceOneOf?: number[]
1064 languageOneOf?: string[]
1065 tagsOneOf?: string[]
1066 tagsAllOf?: string[]
1067 durationMin?: number // seconds
1068 durationMax?: number // seconds
1070 filter?: VideoFilter
1074 if (options.startDate || options.endDate) {
1075 const publishedAtRange = {}
1077 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1078 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1080 whereAnd.push({ publishedAt: publishedAtRange })
1083 if (options.durationMin || options.durationMax) {
1084 const durationRange = {}
1086 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1087 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1089 whereAnd.push({ duration: durationRange })
1092 const attributesInclude = []
1093 const escapedSearch = VideoModel.sequelize.escape(options.search)
1094 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1095 if (options.search) {
1099 [ Sequelize.Op.in ]: Sequelize.literal(
1101 'SELECT "video"."id" FROM "video" ' +
1103 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1104 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1106 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1107 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1108 'WHERE "tag"."name" = ' + escapedSearch +
1115 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1118 // Cannot search on similarity if we don't have a search
1119 if (!options.search) {
1120 attributesInclude.push(
1121 Sequelize.literal('0 as similarity')
1125 const query: IFindOptions<VideoModel> = {
1127 include: attributesInclude
1129 offset: options.start,
1130 limit: options.count,
1131 order: getVideoSort(options.sort),
1133 [ Sequelize.Op.and ]: whereAnd
1137 const serverActor = await getServerActor()
1138 const queryOptions = {
1139 followerActorId: serverActor.id,
1140 serverAccountId: serverActor.Account.id,
1141 includeLocalVideos: options.includeLocalVideos,
1143 categoryOneOf: options.categoryOneOf,
1144 licenceOneOf: options.licenceOneOf,
1145 languageOneOf: options.languageOneOf,
1146 tagsOneOf: options.tagsOneOf,
1147 tagsAllOf: options.tagsAllOf,
1149 filter: options.filter
1152 return VideoModel.getAvailableForApi(query, queryOptions)
1155 static load (id: number | string, t?: Sequelize.Transaction) {
1156 const where = VideoModel.buildWhereIdOrUUID(id)
1162 return VideoModel.findOne(options)
1165 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1166 const where = VideoModel.buildWhereIdOrUUID(id)
1169 attributes: [ 'id' ],
1174 return VideoModel.findOne(options)
1177 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1178 return VideoModel.scope(ScopeNames.WITH_FILES)
1179 .findById(id, { transaction: t, logging })
1182 static loadByUUIDWithFile (uuid: string) {
1190 .scope([ ScopeNames.WITH_FILES ])
1194 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1195 const query: IFindOptions<VideoModel> = {
1202 return VideoModel.findOne(query)
1205 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1206 const query: IFindOptions<VideoModel> = {
1213 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1216 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1217 const where = VideoModel.buildWhereIdOrUUID(id)
1220 order: [ [ 'Tags', 'name', 'ASC' ] ],
1226 ScopeNames.WITH_TAGS,
1227 ScopeNames.WITH_BLACKLISTED,
1228 ScopeNames.WITH_FILES,
1229 ScopeNames.WITH_ACCOUNT_DETAILS,
1230 ScopeNames.WITH_SCHEDULED_UPDATE
1234 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1242 static async getStats () {
1243 const totalLocalVideos = await VideoModel.count({
1248 const totalVideos = await VideoModel.count()
1250 let totalLocalVideoViews = await VideoModel.sum('views', {
1255 // Sequelize could return null...
1256 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1260 totalLocalVideoViews,
1265 static incrementViews (id: number, views: number) {
1266 return VideoModel.increment('views', {
1274 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1275 // Instances only share videos
1276 const query = 'SELECT 1 FROM "videoShare" ' +
1277 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1278 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1282 type: Sequelize.QueryTypes.SELECT,
1283 bind: { followerActorId, videoId },
1287 return VideoModel.sequelize.query(query, options)
1288 .then(results => results.length === 1)
1291 // threshold corresponds to how many video the field should have to be returned
1292 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1293 const serverActor = await getServerActor()
1294 const followerActorId = serverActor.id
1296 const scopeOptions: AvailableForListIDsOptions = {
1297 serverAccountId: serverActor.Account.id,
1299 includeLocalVideos: true
1302 const query: IFindOptions<VideoModel> = {
1303 attributes: [ field ],
1306 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1307 [ Sequelize.Op.gte ]: threshold
1308 }) as any, // FIXME: typings
1309 order: [ this.sequelize.random() ]
1312 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1314 .then(rows => rows.map(r => r[ field ]))
1317 static buildTrendingQuery (trendingDays: number) {
1321 model: VideoViewModel,
1325 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1331 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1332 if (filter && (filter === 'local' || filter === 'all-local')) {
1341 private static async getAvailableForApi (
1342 query: IFindOptions<VideoModel>,
1343 options: AvailableForListIDsOptions,
1348 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1352 // Remove trending sort on count, because it uses a group by
1353 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1354 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1355 const countScope = {
1357 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1361 const [ count, rowsId ] = await Promise.all([
1362 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1363 VideoModel.scope(idsScope).findAll(query)
1365 const ids = rowsId.map(r => r.id)
1367 if (ids.length === 0) return { data: [], total: count }
1370 const apiScope: any[] = [
1372 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1377 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1380 const secondQuery = {
1383 attributes: query.attributes,
1384 order: [ // Keep original order
1386 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1390 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1398 static getCategoryLabel (id: number) {
1399 return VIDEO_CATEGORIES[ id ] || 'Misc'
1402 static getLicenceLabel (id: number) {
1403 return VIDEO_LICENCES[ id ] || 'Unknown'
1406 static getLanguageLabel (id: string) {
1407 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1410 static getPrivacyLabel (id: number) {
1411 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1414 static getStateLabel (id: number) {
1415 return VIDEO_STATES[ id ] || 'Unknown'
1418 static buildWhereIdOrUUID (id: number | string) {
1419 return validator.isInt('' + id) ? { id } : { uuid: id }
1422 getOriginalFile () {
1423 if (Array.isArray(this.VideoFiles) === false) return undefined
1425 // The original file is the file that have the higher resolution
1426 return maxBy(this.VideoFiles, file => file.resolution)
1429 getVideoFilename (videoFile: VideoFileModel) {
1430 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1433 getThumbnailName () {
1434 // We always have a copy of the thumbnail
1435 const extension = '.jpg'
1436 return this.uuid + extension
1440 const extension = '.jpg'
1441 return this.uuid + extension
1444 getTorrentFileName (videoFile: VideoFileModel) {
1445 const extension = '.torrent'
1446 return this.uuid + '-' + videoFile.resolution + extension
1450 return this.remote === false
1453 createPreview (videoFile: VideoFileModel) {
1454 return generateImageFromVideoFile(
1455 this.getVideoFilePath(videoFile),
1456 CONFIG.STORAGE.PREVIEWS_DIR,
1457 this.getPreviewName(),
1462 createThumbnail (videoFile: VideoFileModel) {
1463 return generateImageFromVideoFile(
1464 this.getVideoFilePath(videoFile),
1465 CONFIG.STORAGE.THUMBNAILS_DIR,
1466 this.getThumbnailName(),
1471 getTorrentFilePath (videoFile: VideoFileModel) {
1472 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1475 getVideoFilePath (videoFile: VideoFileModel) {
1476 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1479 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1481 // Keep the extname, it's used by the client to stream the file inside a web browser
1482 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1483 createdBy: 'PeerTube',
1485 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1486 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1488 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1491 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1493 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1494 logger.info('Creating torrent %s.', filePath)
1496 await writeFile(filePath, torrent)
1498 const parsedTorrent = parseTorrent(torrent)
1499 videoFile.infoHash = parsedTorrent.infoHash
1502 getEmbedStaticPath () {
1503 return '/videos/embed/' + this.uuid
1506 getThumbnailStaticPath () {
1507 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1510 getPreviewStaticPath () {
1511 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1514 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1515 return videoModelToFormattedJSON(this, options)
1518 toFormattedDetailsJSON (): VideoDetails {
1519 return videoModelToFormattedDetailsJSON(this)
1522 getFormattedVideoFilesJSON (): VideoFile[] {
1523 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1526 toActivityPubObject (): VideoTorrentObject {
1527 return videoModelToActivityPubObject(this)
1530 getTruncatedDescription () {
1531 if (!this.description) return null
1533 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1534 return peertubeTruncate(this.description, maxLength)
1537 getOriginalFileResolution () {
1538 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1540 return getVideoFileResolution(originalFilePath)
1543 getDescriptionAPIPath () {
1544 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1547 removeThumbnail () {
1548 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1549 return remove(thumbnailPath)
1550 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1554 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1555 return remove(previewPath)
1556 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1559 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1560 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1562 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1563 return remove(filePath)
1564 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1567 removeTorrent (videoFile: VideoFileModel) {
1568 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1569 return remove(torrentPath)
1570 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1574 if (this.isOwned()) return false
1576 const now = Date.now()
1577 const createdAtTime = this.createdAt.getTime()
1578 const updatedAtTime = this.updatedAt.getTime()
1580 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1581 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1585 this.changed('updatedAt', true)
1594 if (this.isOwned()) {
1595 baseUrlHttp = CONFIG.WEBSERVER.URL
1596 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1598 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1599 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1602 return { baseUrlHttp, baseUrlWs }
1605 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1606 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1607 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1608 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1610 const redundancies = videoFile.RedundancyVideos
1611 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1613 const magnetHash = {
1617 infoHash: videoFile.infoHash,
1621 return magnetUtil.encode(magnetHash)
1624 getThumbnailUrl (baseUrlHttp: string) {
1625 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1628 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1629 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1632 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1633 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1636 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1637 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1640 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1641 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1644 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1645 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)