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'
97 import { VideoImportModel } from './video-import'
99 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
100 const indexes: Sequelize.DefineIndexesOptions[] = [
101 buildTrigramSearchIndex('video_name_trigram', 'name'),
103 { fields: [ 'createdAt' ] },
104 { fields: [ 'publishedAt' ] },
105 { fields: [ 'originallyPublishedAt' ] },
106 { fields: [ 'duration' ] },
107 { fields: [ 'views' ] },
108 { fields: [ 'channelId' ] },
110 fields: [ 'category' ], // We don't care videos with an unknown category
113 [Sequelize.Op.ne]: null
118 fields: [ 'licence' ], // We don't care videos with an unknown licence
121 [Sequelize.Op.ne]: null
126 fields: [ 'language' ], // We don't care videos with an unknown language
129 [Sequelize.Op.ne]: null
134 fields: [ 'nsfw' ], // Most of the videos are not NSFW
140 fields: [ 'remote' ], // Only index local videos
155 export enum ScopeNames {
156 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
158 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
159 WITH_TAGS = 'WITH_TAGS',
160 WITH_FILES = 'WITH_FILES',
161 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
162 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
163 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
166 type ForAPIOptions = {
171 type AvailableForListIDsOptions = {
172 serverAccountId: number
173 followerActorId: number
174 includeLocalVideos: boolean
176 categoryOneOf?: number[]
178 licenceOneOf?: number[]
179 languageOneOf?: string[]
184 videoChannelId?: number
185 trendingDays?: number
187 historyOfUser?: UserModel
191 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
192 const accountInclude = {
193 attributes: [ 'id', 'name' ],
194 model: AccountModel.unscoped(),
198 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
199 model: ActorModel.unscoped(),
203 attributes: [ 'host' ],
204 model: ServerModel.unscoped(),
208 model: AvatarModel.unscoped(),
216 const videoChannelInclude = {
217 attributes: [ 'name', 'description', 'id' ],
218 model: VideoChannelModel.unscoped(),
222 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
223 model: ActorModel.unscoped(),
227 attributes: [ 'host' ],
228 model: ServerModel.unscoped(),
232 model: AvatarModel.unscoped(),
241 const query: IFindOptions<VideoModel> = {
244 [ Sequelize.Op.any ]: options.ids
247 include: [ videoChannelInclude ]
250 if (options.withFiles === true) {
252 model: VideoFileModel.unscoped(),
259 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
260 const query: IFindOptions<VideoModel> = {
262 attributes: [ 'id' ],
265 [ Sequelize.Op.and ]: [
267 [ Sequelize.Op.notIn ]: Sequelize.literal(
268 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
274 [ Sequelize.Op.notIn ]: Sequelize.literal(
276 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
277 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
286 // Only list public/published videos
287 if (!options.filter || options.filter !== 'all-local') {
288 const privacyWhere = {
289 // Always list public videos
290 privacy: VideoPrivacy.PUBLIC,
291 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
292 [ Sequelize.Op.or ]: [
294 state: VideoState.PUBLISHED
297 [ Sequelize.Op.and ]: {
298 state: VideoState.TO_TRANSCODE,
299 waitTranscoding: false
305 Object.assign(query.where, privacyWhere)
308 if (options.filter || options.accountId || options.videoChannelId) {
309 const videoChannelInclude: IIncludeOptions = {
311 model: VideoChannelModel.unscoped(),
315 if (options.videoChannelId) {
316 videoChannelInclude.where = {
317 id: options.videoChannelId
321 if (options.filter || options.accountId) {
322 const accountInclude: IIncludeOptions = {
324 model: AccountModel.unscoped(),
328 if (options.filter) {
329 accountInclude.include = [
332 model: ActorModel.unscoped(),
334 where: VideoModel.buildActorWhereWithFilter(options.filter)
339 if (options.accountId) {
340 accountInclude.where = { id: options.accountId }
343 videoChannelInclude.include = [ accountInclude ]
346 query.include.push(videoChannelInclude)
349 if (options.followerActorId) {
350 let localVideosReq = ''
351 if (options.includeLocalVideos === true) {
352 localVideosReq = ' UNION ALL ' +
353 'SELECT "video"."id" AS "id" FROM "video" ' +
354 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
355 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
356 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
357 'WHERE "actor"."serverId" IS NULL'
360 // Force actorId to be a number to avoid SQL injections
361 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
362 query.where[ 'id' ][ Sequelize.Op.and ].push({
363 [ Sequelize.Op.in ]: Sequelize.literal(
365 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
366 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
367 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
369 'SELECT "video"."id" AS "id" FROM "video" ' +
370 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
371 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
372 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
373 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
374 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
381 if (options.withFiles === true) {
382 query.where[ 'id' ][ Sequelize.Op.and ].push({
383 [ Sequelize.Op.in ]: Sequelize.literal(
384 '(SELECT "videoId" FROM "videoFile")'
389 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
390 if (options.tagsAllOf || options.tagsOneOf) {
391 const createTagsIn = (tags: string[]) => {
392 return tags.map(t => VideoModel.sequelize.escape(t))
396 if (options.tagsOneOf) {
397 query.where[ 'id' ][ Sequelize.Op.and ].push({
398 [ Sequelize.Op.in ]: Sequelize.literal(
400 'SELECT "videoId" FROM "videoTag" ' +
401 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
402 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
408 if (options.tagsAllOf) {
409 query.where[ 'id' ][ Sequelize.Op.and ].push({
410 [ Sequelize.Op.in ]: Sequelize.literal(
412 'SELECT "videoId" FROM "videoTag" ' +
413 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
414 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
415 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
422 if (options.nsfw === true || options.nsfw === false) {
423 query.where[ 'nsfw' ] = options.nsfw
426 if (options.categoryOneOf) {
427 query.where[ 'category' ] = {
428 [ Sequelize.Op.or ]: options.categoryOneOf
432 if (options.licenceOneOf) {
433 query.where[ 'licence' ] = {
434 [ Sequelize.Op.or ]: options.licenceOneOf
438 if (options.languageOneOf) {
439 query.where[ 'language' ] = {
440 [ Sequelize.Op.or ]: options.languageOneOf
444 if (options.trendingDays) {
445 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
447 query.subQuery = false
450 if (options.historyOfUser) {
452 model: UserVideoHistoryModel,
455 userId: options.historyOfUser.id
459 // Even if the relation is n:m, we know that a user only have 0..1 video history
460 // So we won't have multiple rows for the same video
461 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
462 query.subQuery = false
467 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
470 model: () => VideoChannelModel.unscoped(),
475 exclude: [ 'privateKey', 'publicKey' ]
477 model: () => ActorModel.unscoped(),
481 attributes: [ 'host' ],
482 model: () => ServerModel.unscoped(),
486 model: () => AvatarModel.unscoped(),
492 model: () => AccountModel.unscoped(),
496 model: () => ActorModel.unscoped(),
498 exclude: [ 'privateKey', 'publicKey' ]
503 attributes: [ 'host' ],
504 model: () => ServerModel.unscoped(),
508 model: () => AvatarModel.unscoped(),
519 [ ScopeNames.WITH_TAGS ]: {
520 include: [ () => TagModel ]
522 [ ScopeNames.WITH_BLACKLISTED ]: {
525 attributes: [ 'id', 'reason' ],
526 model: () => VideoBlacklistModel,
531 [ ScopeNames.WITH_FILES ]: {
534 model: () => VideoFileModel.unscoped(),
536 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
540 attributes: [ 'fileUrl' ],
541 model: () => VideoRedundancyModel.unscoped(),
548 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
551 model: () => ScheduleVideoUpdateModel.unscoped(),
556 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
560 attributes: [ 'currentTime' ],
561 model: UserVideoHistoryModel.unscoped(),
575 export class VideoModel extends Model<VideoModel> {
578 @Default(DataType.UUIDV4)
580 @Column(DataType.UUID)
584 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
590 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
596 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
602 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
603 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
607 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
612 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
618 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
619 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
624 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
625 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
629 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
659 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
660 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
665 commentsEnabled: boolean
669 waitTranscoding: boolean
673 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
684 @Default(Sequelize.NOW)
689 originallyPublishedAt: Date
691 @ForeignKey(() => VideoChannelModel)
695 @BelongsTo(() => VideoChannelModel, {
701 VideoChannel: VideoChannelModel
703 @BelongsToMany(() => TagModel, {
704 foreignKey: 'videoId',
705 through: () => VideoTagModel,
710 @HasMany(() => VideoAbuseModel, {
717 VideoAbuses: VideoAbuseModel[]
719 @HasMany(() => VideoFileModel, {
727 VideoFiles: VideoFileModel[]
729 @HasMany(() => VideoShareModel, {
736 VideoShares: VideoShareModel[]
738 @HasMany(() => AccountVideoRateModel, {
745 AccountVideoRates: AccountVideoRateModel[]
747 @HasMany(() => VideoCommentModel, {
755 VideoComments: VideoCommentModel[]
757 @HasMany(() => VideoViewModel, {
764 VideoViews: VideoViewModel[]
766 @HasMany(() => UserVideoHistoryModel, {
773 UserVideoHistories: UserVideoHistoryModel[]
775 @HasOne(() => ScheduleVideoUpdateModel, {
782 ScheduleVideoUpdate: ScheduleVideoUpdateModel
784 @HasOne(() => VideoBlacklistModel, {
791 VideoBlacklist: VideoBlacklistModel
793 @HasOne(() => VideoImportModel, {
800 VideoImport: VideoImportModel
802 @HasMany(() => VideoCaptionModel, {
809 [ 'separate' as any ]: true
811 VideoCaptions: VideoCaptionModel[]
814 static async sendDelete (instance: VideoModel, options) {
815 if (instance.isOwned()) {
816 if (!instance.VideoChannel) {
817 instance.VideoChannel = await instance.$get('VideoChannel', {
821 include: [ ActorModel ]
824 transaction: options.transaction
825 }) as VideoChannelModel
828 return sendDeleteVideo(instance, options.transaction)
835 static async removeFiles (instance: VideoModel) {
836 const tasks: Promise<any>[] = []
838 logger.info('Removing files of video %s.', instance.url)
840 tasks.push(instance.removeThumbnail())
842 if (instance.isOwned()) {
843 if (!Array.isArray(instance.VideoFiles)) {
844 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
847 tasks.push(instance.removePreview())
849 // Remove physical files and torrents
850 instance.VideoFiles.forEach(file => {
851 tasks.push(instance.removeFile(file))
852 tasks.push(instance.removeTorrent(file))
856 // Do not wait video deletion because we could be in a transaction
859 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
866 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
869 static listLocal () {
876 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
879 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
880 function getRawQuery (select: string) {
881 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
882 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
883 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
884 'WHERE "Account"."actorId" = ' + actorId
885 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
886 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
887 'WHERE "VideoShare"."actorId" = ' + actorId
889 return `(${queryVideo}) UNION (${queryVideoShare})`
892 const rawQuery = getRawQuery('"Video"."id"')
893 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
899 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
902 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
904 [ Sequelize.Op.or ]: [
905 { privacy: VideoPrivacy.PUBLIC },
906 { privacy: VideoPrivacy.UNLISTED }
911 attributes: [ 'language' ],
912 model: VideoCaptionModel.unscoped(),
916 attributes: [ 'id', 'url' ],
917 model: VideoShareModel.unscoped(),
919 // We only want videos shared by this actor
921 [ Sequelize.Op.and ]: [
924 [ Sequelize.Op.not ]: null
934 attributes: [ 'id', 'url' ],
935 model: ActorModel.unscoped()
940 model: VideoChannelModel.unscoped(),
944 attributes: [ 'name' ],
945 model: AccountModel.unscoped(),
949 attributes: [ 'id', 'url', 'followersUrl' ],
950 model: ActorModel.unscoped(),
956 attributes: [ 'id', 'url', 'followersUrl' ],
957 model: ActorModel.unscoped(),
967 return Bluebird.all([
968 // FIXME: typing issue
969 VideoModel.findAll(query as any),
970 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
971 ]).then(([ rows, totals ]) => {
972 // totals: totalVideos + totalVideoShares
974 let totalVideoShares = 0
975 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
976 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
978 const total = totalVideos + totalVideoShares
986 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
987 const query: IFindOptions<VideoModel> = {
990 order: getVideoSort(sort),
993 model: VideoChannelModel,
1006 model: ScheduleVideoUpdateModel,
1010 model: VideoBlacklistModel,
1016 if (withFiles === true) {
1017 query.include.push({
1018 model: VideoFileModel.unscoped(),
1023 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1031 static async listForApi (options: {
1036 includeLocalVideos: boolean,
1038 categoryOneOf?: number[],
1039 licenceOneOf?: number[],
1040 languageOneOf?: string[],
1041 tagsOneOf?: string[],
1042 tagsAllOf?: string[],
1043 filter?: VideoFilter,
1045 videoChannelId?: number,
1046 followerActorId?: number
1047 trendingDays?: number,
1049 historyOfUser?: UserModel
1050 }, countVideos = true) {
1051 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1052 throw new Error('Try to filter all-local but no user has not the see all videos right')
1055 const query: IFindOptions<VideoModel> = {
1056 offset: options.start,
1057 limit: options.count,
1058 order: getVideoSort(options.sort)
1061 let trendingDays: number
1062 if (options.sort.endsWith('trending')) {
1063 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1065 query.group = 'VideoModel.id'
1068 const serverActor = await getServerActor()
1070 // followerActorId === null has a meaning, so just check undefined
1071 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1073 const queryOptions = {
1075 serverAccountId: serverActor.Account.id,
1077 categoryOneOf: options.categoryOneOf,
1078 licenceOneOf: options.licenceOneOf,
1079 languageOneOf: options.languageOneOf,
1080 tagsOneOf: options.tagsOneOf,
1081 tagsAllOf: options.tagsAllOf,
1082 filter: options.filter,
1083 withFiles: options.withFiles,
1084 accountId: options.accountId,
1085 videoChannelId: options.videoChannelId,
1086 includeLocalVideos: options.includeLocalVideos,
1088 historyOfUser: options.historyOfUser,
1092 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1095 static async searchAndPopulateAccountAndServer (options: {
1096 includeLocalVideos: boolean
1101 startDate?: string // ISO 8601
1102 endDate?: string // ISO 8601
1104 categoryOneOf?: number[]
1105 licenceOneOf?: number[]
1106 languageOneOf?: string[]
1107 tagsOneOf?: string[]
1108 tagsAllOf?: string[]
1109 durationMin?: number // seconds
1110 durationMax?: number // seconds
1112 filter?: VideoFilter
1116 if (options.startDate || options.endDate) {
1117 const publishedAtRange = {}
1119 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1120 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1122 whereAnd.push({ publishedAt: publishedAtRange })
1125 if (options.durationMin || options.durationMax) {
1126 const durationRange = {}
1128 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1129 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1131 whereAnd.push({ duration: durationRange })
1134 const attributesInclude = []
1135 const escapedSearch = VideoModel.sequelize.escape(options.search)
1136 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1137 if (options.search) {
1141 [ Sequelize.Op.in ]: Sequelize.literal(
1143 'SELECT "video"."id" FROM "video" ' +
1145 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1146 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1148 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1149 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1150 'WHERE "tag"."name" = ' + escapedSearch +
1157 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1160 // Cannot search on similarity if we don't have a search
1161 if (!options.search) {
1162 attributesInclude.push(
1163 Sequelize.literal('0 as similarity')
1167 const query: IFindOptions<VideoModel> = {
1169 include: attributesInclude
1171 offset: options.start,
1172 limit: options.count,
1173 order: getVideoSort(options.sort),
1175 [ Sequelize.Op.and ]: whereAnd
1179 const serverActor = await getServerActor()
1180 const queryOptions = {
1181 followerActorId: serverActor.id,
1182 serverAccountId: serverActor.Account.id,
1183 includeLocalVideos: options.includeLocalVideos,
1185 categoryOneOf: options.categoryOneOf,
1186 licenceOneOf: options.licenceOneOf,
1187 languageOneOf: options.languageOneOf,
1188 tagsOneOf: options.tagsOneOf,
1189 tagsAllOf: options.tagsAllOf,
1191 filter: options.filter
1194 return VideoModel.getAvailableForApi(query, queryOptions)
1197 static load (id: number | string, t?: Sequelize.Transaction) {
1198 const where = VideoModel.buildWhereIdOrUUID(id)
1204 return VideoModel.findOne(options)
1207 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1208 const where = VideoModel.buildWhereIdOrUUID(id)
1211 attributes: [ 'id' ],
1216 return VideoModel.findOne(options)
1219 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1220 return VideoModel.scope(ScopeNames.WITH_FILES)
1221 .findById(id, { transaction: t, logging })
1224 static loadByUUIDWithFile (uuid: string) {
1232 .scope([ ScopeNames.WITH_FILES ])
1236 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1237 const query: IFindOptions<VideoModel> = {
1244 return VideoModel.findOne(query)
1247 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1248 const query: IFindOptions<VideoModel> = {
1255 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1258 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1259 const where = VideoModel.buildWhereIdOrUUID(id)
1262 order: [ [ 'Tags', 'name', 'ASC' ] ],
1268 ScopeNames.WITH_TAGS,
1269 ScopeNames.WITH_BLACKLISTED,
1270 ScopeNames.WITH_FILES,
1271 ScopeNames.WITH_ACCOUNT_DETAILS,
1272 ScopeNames.WITH_SCHEDULED_UPDATE
1276 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1284 static async getStats () {
1285 const totalLocalVideos = await VideoModel.count({
1290 const totalVideos = await VideoModel.count()
1292 let totalLocalVideoViews = await VideoModel.sum('views', {
1297 // Sequelize could return null...
1298 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1302 totalLocalVideoViews,
1307 static incrementViews (id: number, views: number) {
1308 return VideoModel.increment('views', {
1316 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1317 // Instances only share videos
1318 const query = 'SELECT 1 FROM "videoShare" ' +
1319 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1320 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1324 type: Sequelize.QueryTypes.SELECT,
1325 bind: { followerActorId, videoId },
1329 return VideoModel.sequelize.query(query, options)
1330 .then(results => results.length === 1)
1333 // threshold corresponds to how many video the field should have to be returned
1334 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1335 const serverActor = await getServerActor()
1336 const followerActorId = serverActor.id
1338 const scopeOptions: AvailableForListIDsOptions = {
1339 serverAccountId: serverActor.Account.id,
1341 includeLocalVideos: true
1344 const query: IFindOptions<VideoModel> = {
1345 attributes: [ field ],
1348 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1349 [ Sequelize.Op.gte ]: threshold
1350 }) as any, // FIXME: typings
1351 order: [ this.sequelize.random() ]
1354 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1356 .then(rows => rows.map(r => r[ field ]))
1359 static buildTrendingQuery (trendingDays: number) {
1363 model: VideoViewModel,
1367 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1373 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1374 if (filter && (filter === 'local' || filter === 'all-local')) {
1383 private static async getAvailableForApi (
1384 query: IFindOptions<VideoModel>,
1385 options: AvailableForListIDsOptions,
1390 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1394 // Remove trending sort on count, because it uses a group by
1395 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1396 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1397 const countScope = {
1399 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1403 const [ count, rowsId ] = await Promise.all([
1404 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1405 VideoModel.scope(idsScope).findAll(query)
1407 const ids = rowsId.map(r => r.id)
1409 if (ids.length === 0) return { data: [], total: count }
1412 const apiScope: any[] = [
1414 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1419 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1422 const secondQuery = {
1425 attributes: query.attributes,
1426 order: [ // Keep original order
1428 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1432 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1440 static getCategoryLabel (id: number) {
1441 return VIDEO_CATEGORIES[ id ] || 'Misc'
1444 static getLicenceLabel (id: number) {
1445 return VIDEO_LICENCES[ id ] || 'Unknown'
1448 static getLanguageLabel (id: string) {
1449 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1452 static getPrivacyLabel (id: number) {
1453 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1456 static getStateLabel (id: number) {
1457 return VIDEO_STATES[ id ] || 'Unknown'
1460 static buildWhereIdOrUUID (id: number | string) {
1461 return validator.isInt('' + id) ? { id } : { uuid: id }
1464 getOriginalFile () {
1465 if (Array.isArray(this.VideoFiles) === false) return undefined
1467 // The original file is the file that have the higher resolution
1468 return maxBy(this.VideoFiles, file => file.resolution)
1471 getVideoFilename (videoFile: VideoFileModel) {
1472 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1475 getThumbnailName () {
1476 // We always have a copy of the thumbnail
1477 const extension = '.jpg'
1478 return this.uuid + extension
1482 const extension = '.jpg'
1483 return this.uuid + extension
1486 getTorrentFileName (videoFile: VideoFileModel) {
1487 const extension = '.torrent'
1488 return this.uuid + '-' + videoFile.resolution + extension
1492 return this.remote === false
1495 createPreview (videoFile: VideoFileModel) {
1496 return generateImageFromVideoFile(
1497 this.getVideoFilePath(videoFile),
1498 CONFIG.STORAGE.PREVIEWS_DIR,
1499 this.getPreviewName(),
1504 createThumbnail (videoFile: VideoFileModel) {
1505 return generateImageFromVideoFile(
1506 this.getVideoFilePath(videoFile),
1507 CONFIG.STORAGE.THUMBNAILS_DIR,
1508 this.getThumbnailName(),
1513 getTorrentFilePath (videoFile: VideoFileModel) {
1514 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1517 getVideoFilePath (videoFile: VideoFileModel) {
1518 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1521 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1523 // Keep the extname, it's used by the client to stream the file inside a web browser
1524 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1525 createdBy: 'PeerTube',
1527 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1528 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1530 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1533 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1535 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1536 logger.info('Creating torrent %s.', filePath)
1538 await writeFile(filePath, torrent)
1540 const parsedTorrent = parseTorrent(torrent)
1541 videoFile.infoHash = parsedTorrent.infoHash
1544 getWatchStaticPath () {
1545 return '/videos/watch/' + this.uuid
1548 getEmbedStaticPath () {
1549 return '/videos/embed/' + this.uuid
1552 getThumbnailStaticPath () {
1553 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1556 getPreviewStaticPath () {
1557 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1560 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1561 return videoModelToFormattedJSON(this, options)
1564 toFormattedDetailsJSON (): VideoDetails {
1565 return videoModelToFormattedDetailsJSON(this)
1568 getFormattedVideoFilesJSON (): VideoFile[] {
1569 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1572 toActivityPubObject (): VideoTorrentObject {
1573 return videoModelToActivityPubObject(this)
1576 getTruncatedDescription () {
1577 if (!this.description) return null
1579 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1580 return peertubeTruncate(this.description, maxLength)
1583 getOriginalFileResolution () {
1584 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1586 return getVideoFileResolution(originalFilePath)
1589 getDescriptionAPIPath () {
1590 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1593 removeThumbnail () {
1594 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1595 return remove(thumbnailPath)
1596 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1600 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1601 return remove(previewPath)
1602 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1605 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1606 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1608 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1609 return remove(filePath)
1610 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1613 removeTorrent (videoFile: VideoFileModel) {
1614 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1615 return remove(torrentPath)
1616 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1620 if (this.isOwned()) return false
1622 const now = Date.now()
1623 const createdAtTime = this.createdAt.getTime()
1624 const updatedAtTime = this.updatedAt.getTime()
1626 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1627 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1631 this.changed('updatedAt', true)
1640 if (this.isOwned()) {
1641 baseUrlHttp = CONFIG.WEBSERVER.URL
1642 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1644 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1645 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1648 return { baseUrlHttp, baseUrlWs }
1651 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1652 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1653 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1654 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1656 const redundancies = videoFile.RedundancyVideos
1657 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1659 const magnetHash = {
1663 infoHash: videoFile.infoHash,
1667 return magnetUtil.encode(magnetHash)
1670 getThumbnailUrl (baseUrlHttp: string) {
1671 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1674 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1675 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1678 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1679 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1682 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1683 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1686 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1687 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1690 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1691 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)