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: [ 'views' ] },
106 { fields: [ 'channelId' ] },
108 fields: [ 'category' ], // We don't care videos with an unknown category
111 [Sequelize.Op.ne]: null
116 fields: [ 'licence' ], // We don't care videos with an unknown licence
119 [Sequelize.Op.ne]: null
124 fields: [ 'language' ], // We don't care videos with an unknown language
127 [Sequelize.Op.ne]: null
132 fields: [ 'nsfw' ], // Most of the videos are not NSFW
138 fields: [ 'remote' ], // Only index local videos
153 export enum ScopeNames {
154 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
156 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
157 WITH_TAGS = 'WITH_TAGS',
158 WITH_FILES = 'WITH_FILES',
159 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
160 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
161 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
164 type ForAPIOptions = {
169 type AvailableForListIDsOptions = {
170 serverAccountId: number
171 followerActorId: number
172 includeLocalVideos: boolean
174 categoryOneOf?: number[]
176 licenceOneOf?: number[]
177 languageOneOf?: string[]
182 videoChannelId?: number
183 trendingDays?: number
185 historyOfUser?: UserModel
189 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
190 const accountInclude = {
191 attributes: [ 'id', 'name' ],
192 model: AccountModel.unscoped(),
196 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
197 model: ActorModel.unscoped(),
201 attributes: [ 'host' ],
202 model: ServerModel.unscoped(),
206 model: AvatarModel.unscoped(),
214 const videoChannelInclude = {
215 attributes: [ 'name', 'description', 'id' ],
216 model: VideoChannelModel.unscoped(),
220 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
221 model: ActorModel.unscoped(),
225 attributes: [ 'host' ],
226 model: ServerModel.unscoped(),
230 model: AvatarModel.unscoped(),
239 const query: IFindOptions<VideoModel> = {
242 [ Sequelize.Op.any ]: options.ids
245 include: [ videoChannelInclude ]
248 if (options.withFiles === true) {
250 model: VideoFileModel.unscoped(),
257 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
258 const query: IFindOptions<VideoModel> = {
260 attributes: [ 'id' ],
263 [ Sequelize.Op.and ]: [
265 [ Sequelize.Op.notIn ]: Sequelize.literal(
266 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
272 [ Sequelize.Op.notIn ]: Sequelize.literal(
274 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
275 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
284 // Only list public/published videos
285 if (!options.filter || options.filter !== 'all-local') {
286 const privacyWhere = {
287 // Always list public videos
288 privacy: VideoPrivacy.PUBLIC,
289 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
290 [ Sequelize.Op.or ]: [
292 state: VideoState.PUBLISHED
295 [ Sequelize.Op.and ]: {
296 state: VideoState.TO_TRANSCODE,
297 waitTranscoding: false
303 Object.assign(query.where, privacyWhere)
306 if (options.filter || options.accountId || options.videoChannelId) {
307 const videoChannelInclude: IIncludeOptions = {
309 model: VideoChannelModel.unscoped(),
313 if (options.videoChannelId) {
314 videoChannelInclude.where = {
315 id: options.videoChannelId
319 if (options.filter || options.accountId) {
320 const accountInclude: IIncludeOptions = {
322 model: AccountModel.unscoped(),
326 if (options.filter) {
327 accountInclude.include = [
330 model: ActorModel.unscoped(),
332 where: VideoModel.buildActorWhereWithFilter(options.filter)
337 if (options.accountId) {
338 accountInclude.where = { id: options.accountId }
341 videoChannelInclude.include = [ accountInclude ]
344 query.include.push(videoChannelInclude)
347 if (options.followerActorId) {
348 let localVideosReq = ''
349 if (options.includeLocalVideos === true) {
350 localVideosReq = ' UNION ALL ' +
351 'SELECT "video"."id" AS "id" FROM "video" ' +
352 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
353 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
354 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
355 'WHERE "actor"."serverId" IS NULL'
358 // Force actorId to be a number to avoid SQL injections
359 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
360 query.where[ 'id' ][ Sequelize.Op.and ].push({
361 [ Sequelize.Op.in ]: Sequelize.literal(
363 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
364 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
365 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
367 'SELECT "video"."id" AS "id" FROM "video" ' +
368 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
369 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
370 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
371 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
372 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
379 if (options.withFiles === true) {
380 query.where[ 'id' ][ Sequelize.Op.and ].push({
381 [ Sequelize.Op.in ]: Sequelize.literal(
382 '(SELECT "videoId" FROM "videoFile")'
387 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
388 if (options.tagsAllOf || options.tagsOneOf) {
389 const createTagsIn = (tags: string[]) => {
390 return tags.map(t => VideoModel.sequelize.escape(t))
394 if (options.tagsOneOf) {
395 query.where[ 'id' ][ Sequelize.Op.and ].push({
396 [ Sequelize.Op.in ]: Sequelize.literal(
398 'SELECT "videoId" FROM "videoTag" ' +
399 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
400 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
406 if (options.tagsAllOf) {
407 query.where[ 'id' ][ Sequelize.Op.and ].push({
408 [ Sequelize.Op.in ]: Sequelize.literal(
410 'SELECT "videoId" FROM "videoTag" ' +
411 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
412 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
413 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
420 if (options.nsfw === true || options.nsfw === false) {
421 query.where[ 'nsfw' ] = options.nsfw
424 if (options.categoryOneOf) {
425 query.where[ 'category' ] = {
426 [ Sequelize.Op.or ]: options.categoryOneOf
430 if (options.licenceOneOf) {
431 query.where[ 'licence' ] = {
432 [ Sequelize.Op.or ]: options.licenceOneOf
436 if (options.languageOneOf) {
437 query.where[ 'language' ] = {
438 [ Sequelize.Op.or ]: options.languageOneOf
442 if (options.trendingDays) {
443 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
445 query.subQuery = false
448 if (options.historyOfUser) {
450 model: UserVideoHistoryModel,
453 userId: options.historyOfUser.id
457 // Even if the relation is n:m, we know that a user only have 0..1 video history
458 // So we won't have multiple rows for the same video
459 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
460 query.subQuery = false
465 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
468 model: () => VideoChannelModel.unscoped(),
473 exclude: [ 'privateKey', 'publicKey' ]
475 model: () => ActorModel.unscoped(),
479 attributes: [ 'host' ],
480 model: () => ServerModel.unscoped(),
484 model: () => AvatarModel.unscoped(),
490 model: () => AccountModel.unscoped(),
494 model: () => ActorModel.unscoped(),
496 exclude: [ 'privateKey', 'publicKey' ]
501 attributes: [ 'host' ],
502 model: () => ServerModel.unscoped(),
506 model: () => AvatarModel.unscoped(),
517 [ ScopeNames.WITH_TAGS ]: {
518 include: [ () => TagModel ]
520 [ ScopeNames.WITH_BLACKLISTED ]: {
523 attributes: [ 'id', 'reason' ],
524 model: () => VideoBlacklistModel,
529 [ ScopeNames.WITH_FILES ]: {
532 model: () => VideoFileModel.unscoped(),
534 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
538 attributes: [ 'fileUrl' ],
539 model: () => VideoRedundancyModel.unscoped(),
546 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
549 model: () => ScheduleVideoUpdateModel.unscoped(),
554 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
558 attributes: [ 'currentTime' ],
559 model: UserVideoHistoryModel.unscoped(),
573 export class VideoModel extends Model<VideoModel> {
576 @Default(DataType.UUIDV4)
578 @Column(DataType.UUID)
582 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
588 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
594 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
600 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
601 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
605 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
610 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
616 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
617 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
622 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
623 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
627 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
657 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
658 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
663 commentsEnabled: boolean
667 waitTranscoding: boolean
671 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
682 @Default(Sequelize.NOW)
686 @ForeignKey(() => VideoChannelModel)
690 @BelongsTo(() => VideoChannelModel, {
696 VideoChannel: VideoChannelModel
698 @BelongsToMany(() => TagModel, {
699 foreignKey: 'videoId',
700 through: () => VideoTagModel,
705 @HasMany(() => VideoAbuseModel, {
712 VideoAbuses: VideoAbuseModel[]
714 @HasMany(() => VideoFileModel, {
722 VideoFiles: VideoFileModel[]
724 @HasMany(() => VideoShareModel, {
731 VideoShares: VideoShareModel[]
733 @HasMany(() => AccountVideoRateModel, {
740 AccountVideoRates: AccountVideoRateModel[]
742 @HasMany(() => VideoCommentModel, {
750 VideoComments: VideoCommentModel[]
752 @HasMany(() => VideoViewModel, {
759 VideoViews: VideoViewModel[]
761 @HasMany(() => UserVideoHistoryModel, {
768 UserVideoHistories: UserVideoHistoryModel[]
770 @HasOne(() => ScheduleVideoUpdateModel, {
777 ScheduleVideoUpdate: ScheduleVideoUpdateModel
779 @HasOne(() => VideoBlacklistModel, {
786 VideoBlacklist: VideoBlacklistModel
788 @HasMany(() => VideoCaptionModel, {
795 [ 'separate' as any ]: true
797 VideoCaptions: VideoCaptionModel[]
800 static async sendDelete (instance: VideoModel, options) {
801 if (instance.isOwned()) {
802 if (!instance.VideoChannel) {
803 instance.VideoChannel = await instance.$get('VideoChannel', {
807 include: [ ActorModel ]
810 transaction: options.transaction
811 }) as VideoChannelModel
814 return sendDeleteVideo(instance, options.transaction)
821 static async removeFiles (instance: VideoModel) {
822 const tasks: Promise<any>[] = []
824 logger.info('Removing files of video %s.', instance.url)
826 tasks.push(instance.removeThumbnail())
828 if (instance.isOwned()) {
829 if (!Array.isArray(instance.VideoFiles)) {
830 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
833 tasks.push(instance.removePreview())
835 // Remove physical files and torrents
836 instance.VideoFiles.forEach(file => {
837 tasks.push(instance.removeFile(file))
838 tasks.push(instance.removeTorrent(file))
842 // Do not wait video deletion because we could be in a transaction
845 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
852 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
855 static listLocal () {
862 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
865 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
866 function getRawQuery (select: string) {
867 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
868 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
869 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
870 'WHERE "Account"."actorId" = ' + actorId
871 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
872 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
873 'WHERE "VideoShare"."actorId" = ' + actorId
875 return `(${queryVideo}) UNION (${queryVideoShare})`
878 const rawQuery = getRawQuery('"Video"."id"')
879 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
885 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
888 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
890 [ Sequelize.Op.or ]: [
891 { privacy: VideoPrivacy.PUBLIC },
892 { privacy: VideoPrivacy.UNLISTED }
897 attributes: [ 'language' ],
898 model: VideoCaptionModel.unscoped(),
902 attributes: [ 'id', 'url' ],
903 model: VideoShareModel.unscoped(),
905 // We only want videos shared by this actor
907 [ Sequelize.Op.and ]: [
910 [ Sequelize.Op.not ]: null
920 attributes: [ 'id', 'url' ],
921 model: ActorModel.unscoped()
926 model: VideoChannelModel.unscoped(),
930 attributes: [ 'name' ],
931 model: AccountModel.unscoped(),
935 attributes: [ 'id', 'url', 'followersUrl' ],
936 model: ActorModel.unscoped(),
942 attributes: [ 'id', 'url', 'followersUrl' ],
943 model: ActorModel.unscoped(),
953 return Bluebird.all([
954 // FIXME: typing issue
955 VideoModel.findAll(query as any),
956 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
957 ]).then(([ rows, totals ]) => {
958 // totals: totalVideos + totalVideoShares
960 let totalVideoShares = 0
961 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
962 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
964 const total = totalVideos + totalVideoShares
972 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
973 const query: IFindOptions<VideoModel> = {
976 order: getVideoSort(sort),
979 model: VideoChannelModel,
992 model: ScheduleVideoUpdateModel,
996 model: VideoBlacklistModel,
1002 if (withFiles === true) {
1003 query.include.push({
1004 model: VideoFileModel.unscoped(),
1009 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1017 static async listForApi (options: {
1022 includeLocalVideos: boolean,
1024 categoryOneOf?: number[],
1025 licenceOneOf?: number[],
1026 languageOneOf?: string[],
1027 tagsOneOf?: string[],
1028 tagsAllOf?: string[],
1029 filter?: VideoFilter,
1031 videoChannelId?: number,
1032 followerActorId?: number
1033 trendingDays?: number,
1035 historyOfUser?: UserModel
1036 }, countVideos = true) {
1037 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1038 throw new Error('Try to filter all-local but no user has not the see all videos right')
1041 const query: IFindOptions<VideoModel> = {
1042 offset: options.start,
1043 limit: options.count,
1044 order: getVideoSort(options.sort)
1047 let trendingDays: number
1048 if (options.sort.endsWith('trending')) {
1049 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1051 query.group = 'VideoModel.id'
1054 const serverActor = await getServerActor()
1056 // followerActorId === null has a meaning, so just check undefined
1057 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1059 const queryOptions = {
1061 serverAccountId: serverActor.Account.id,
1063 categoryOneOf: options.categoryOneOf,
1064 licenceOneOf: options.licenceOneOf,
1065 languageOneOf: options.languageOneOf,
1066 tagsOneOf: options.tagsOneOf,
1067 tagsAllOf: options.tagsAllOf,
1068 filter: options.filter,
1069 withFiles: options.withFiles,
1070 accountId: options.accountId,
1071 videoChannelId: options.videoChannelId,
1072 includeLocalVideos: options.includeLocalVideos,
1074 historyOfUser: options.historyOfUser,
1078 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1081 static async searchAndPopulateAccountAndServer (options: {
1082 includeLocalVideos: boolean
1087 startDate?: string // ISO 8601
1088 endDate?: string // ISO 8601
1090 categoryOneOf?: number[]
1091 licenceOneOf?: number[]
1092 languageOneOf?: string[]
1093 tagsOneOf?: string[]
1094 tagsAllOf?: string[]
1095 durationMin?: number // seconds
1096 durationMax?: number // seconds
1098 filter?: VideoFilter
1102 if (options.startDate || options.endDate) {
1103 const publishedAtRange = {}
1105 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1106 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1108 whereAnd.push({ publishedAt: publishedAtRange })
1111 if (options.durationMin || options.durationMax) {
1112 const durationRange = {}
1114 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1115 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1117 whereAnd.push({ duration: durationRange })
1120 const attributesInclude = []
1121 const escapedSearch = VideoModel.sequelize.escape(options.search)
1122 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1123 if (options.search) {
1127 [ Sequelize.Op.in ]: Sequelize.literal(
1129 'SELECT "video"."id" FROM "video" ' +
1131 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1132 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1134 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1135 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1136 'WHERE "tag"."name" = ' + escapedSearch +
1143 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1146 // Cannot search on similarity if we don't have a search
1147 if (!options.search) {
1148 attributesInclude.push(
1149 Sequelize.literal('0 as similarity')
1153 const query: IFindOptions<VideoModel> = {
1155 include: attributesInclude
1157 offset: options.start,
1158 limit: options.count,
1159 order: getVideoSort(options.sort),
1161 [ Sequelize.Op.and ]: whereAnd
1165 const serverActor = await getServerActor()
1166 const queryOptions = {
1167 followerActorId: serverActor.id,
1168 serverAccountId: serverActor.Account.id,
1169 includeLocalVideos: options.includeLocalVideos,
1171 categoryOneOf: options.categoryOneOf,
1172 licenceOneOf: options.licenceOneOf,
1173 languageOneOf: options.languageOneOf,
1174 tagsOneOf: options.tagsOneOf,
1175 tagsAllOf: options.tagsAllOf,
1177 filter: options.filter
1180 return VideoModel.getAvailableForApi(query, queryOptions)
1183 static load (id: number | string, t?: Sequelize.Transaction) {
1184 const where = VideoModel.buildWhereIdOrUUID(id)
1190 return VideoModel.findOne(options)
1193 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1194 const where = VideoModel.buildWhereIdOrUUID(id)
1197 attributes: [ 'id' ],
1202 return VideoModel.findOne(options)
1205 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1206 return VideoModel.scope(ScopeNames.WITH_FILES)
1207 .findById(id, { transaction: t, logging })
1210 static loadByUUIDWithFile (uuid: string) {
1218 .scope([ ScopeNames.WITH_FILES ])
1222 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1223 const query: IFindOptions<VideoModel> = {
1230 return VideoModel.findOne(query)
1233 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1234 const query: IFindOptions<VideoModel> = {
1241 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1244 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1245 const where = VideoModel.buildWhereIdOrUUID(id)
1248 order: [ [ 'Tags', 'name', 'ASC' ] ],
1254 ScopeNames.WITH_TAGS,
1255 ScopeNames.WITH_BLACKLISTED,
1256 ScopeNames.WITH_FILES,
1257 ScopeNames.WITH_ACCOUNT_DETAILS,
1258 ScopeNames.WITH_SCHEDULED_UPDATE
1262 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1270 static async getStats () {
1271 const totalLocalVideos = await VideoModel.count({
1276 const totalVideos = await VideoModel.count()
1278 let totalLocalVideoViews = await VideoModel.sum('views', {
1283 // Sequelize could return null...
1284 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1288 totalLocalVideoViews,
1293 static incrementViews (id: number, views: number) {
1294 return VideoModel.increment('views', {
1302 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1303 // Instances only share videos
1304 const query = 'SELECT 1 FROM "videoShare" ' +
1305 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1306 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1310 type: Sequelize.QueryTypes.SELECT,
1311 bind: { followerActorId, videoId },
1315 return VideoModel.sequelize.query(query, options)
1316 .then(results => results.length === 1)
1319 // threshold corresponds to how many video the field should have to be returned
1320 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1321 const serverActor = await getServerActor()
1322 const followerActorId = serverActor.id
1324 const scopeOptions: AvailableForListIDsOptions = {
1325 serverAccountId: serverActor.Account.id,
1327 includeLocalVideos: true
1330 const query: IFindOptions<VideoModel> = {
1331 attributes: [ field ],
1334 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1335 [ Sequelize.Op.gte ]: threshold
1336 }) as any, // FIXME: typings
1337 order: [ this.sequelize.random() ]
1340 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1342 .then(rows => rows.map(r => r[ field ]))
1345 static buildTrendingQuery (trendingDays: number) {
1349 model: VideoViewModel,
1353 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1359 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1360 if (filter && (filter === 'local' || filter === 'all-local')) {
1369 private static async getAvailableForApi (
1370 query: IFindOptions<VideoModel>,
1371 options: AvailableForListIDsOptions,
1376 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1380 // Remove trending sort on count, because it uses a group by
1381 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1382 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1383 const countScope = {
1385 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1389 const [ count, rowsId ] = await Promise.all([
1390 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1391 VideoModel.scope(idsScope).findAll(query)
1393 const ids = rowsId.map(r => r.id)
1395 if (ids.length === 0) return { data: [], total: count }
1398 const apiScope: any[] = [
1400 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1405 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1408 const secondQuery = {
1411 attributes: query.attributes,
1412 order: [ // Keep original order
1414 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1418 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1426 static getCategoryLabel (id: number) {
1427 return VIDEO_CATEGORIES[ id ] || 'Misc'
1430 static getLicenceLabel (id: number) {
1431 return VIDEO_LICENCES[ id ] || 'Unknown'
1434 static getLanguageLabel (id: string) {
1435 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1438 static getPrivacyLabel (id: number) {
1439 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1442 static getStateLabel (id: number) {
1443 return VIDEO_STATES[ id ] || 'Unknown'
1446 static buildWhereIdOrUUID (id: number | string) {
1447 return validator.isInt('' + id) ? { id } : { uuid: id }
1450 getOriginalFile () {
1451 if (Array.isArray(this.VideoFiles) === false) return undefined
1453 // The original file is the file that have the higher resolution
1454 return maxBy(this.VideoFiles, file => file.resolution)
1457 getVideoFilename (videoFile: VideoFileModel) {
1458 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1461 getThumbnailName () {
1462 // We always have a copy of the thumbnail
1463 const extension = '.jpg'
1464 return this.uuid + extension
1468 const extension = '.jpg'
1469 return this.uuid + extension
1472 getTorrentFileName (videoFile: VideoFileModel) {
1473 const extension = '.torrent'
1474 return this.uuid + '-' + videoFile.resolution + extension
1478 return this.remote === false
1481 createPreview (videoFile: VideoFileModel) {
1482 return generateImageFromVideoFile(
1483 this.getVideoFilePath(videoFile),
1484 CONFIG.STORAGE.PREVIEWS_DIR,
1485 this.getPreviewName(),
1490 createThumbnail (videoFile: VideoFileModel) {
1491 return generateImageFromVideoFile(
1492 this.getVideoFilePath(videoFile),
1493 CONFIG.STORAGE.THUMBNAILS_DIR,
1494 this.getThumbnailName(),
1499 getTorrentFilePath (videoFile: VideoFileModel) {
1500 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1503 getVideoFilePath (videoFile: VideoFileModel) {
1504 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1507 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1509 // Keep the extname, it's used by the client to stream the file inside a web browser
1510 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1511 createdBy: 'PeerTube',
1513 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1514 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1516 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1519 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1521 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1522 logger.info('Creating torrent %s.', filePath)
1524 await writeFile(filePath, torrent)
1526 const parsedTorrent = parseTorrent(torrent)
1527 videoFile.infoHash = parsedTorrent.infoHash
1530 getWatchStaticPath () {
1531 return '/videos/watch/' + this.uuid
1534 getEmbedStaticPath () {
1535 return '/videos/embed/' + this.uuid
1538 getThumbnailStaticPath () {
1539 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1542 getPreviewStaticPath () {
1543 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1546 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1547 return videoModelToFormattedJSON(this, options)
1550 toFormattedDetailsJSON (): VideoDetails {
1551 return videoModelToFormattedDetailsJSON(this)
1554 getFormattedVideoFilesJSON (): VideoFile[] {
1555 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1558 toActivityPubObject (): VideoTorrentObject {
1559 return videoModelToActivityPubObject(this)
1562 getTruncatedDescription () {
1563 if (!this.description) return null
1565 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1566 return peertubeTruncate(this.description, maxLength)
1569 getOriginalFileResolution () {
1570 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1572 return getVideoFileResolution(originalFilePath)
1575 getDescriptionAPIPath () {
1576 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1579 removeThumbnail () {
1580 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1581 return remove(thumbnailPath)
1582 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1586 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1587 return remove(previewPath)
1588 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1591 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1592 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1594 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1595 return remove(filePath)
1596 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1599 removeTorrent (videoFile: VideoFileModel) {
1600 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1601 return remove(torrentPath)
1602 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1606 if (this.isOwned()) return false
1608 const now = Date.now()
1609 const createdAtTime = this.createdAt.getTime()
1610 const updatedAtTime = this.updatedAt.getTime()
1612 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1613 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1617 this.changed('updatedAt', true)
1626 if (this.isOwned()) {
1627 baseUrlHttp = CONFIG.WEBSERVER.URL
1628 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1630 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1631 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1634 return { baseUrlHttp, baseUrlWs }
1637 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1638 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1639 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1640 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1642 const redundancies = videoFile.RedundancyVideos
1643 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1645 const magnetHash = {
1649 infoHash: videoFile.infoHash,
1653 return magnetUtil.encode(magnetHash)
1656 getThumbnailUrl (baseUrlHttp: string) {
1657 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1660 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1661 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1664 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1665 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1668 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1669 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1672 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1673 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1676 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1677 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)