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: [ 'duration' ] },
106 { fields: [ 'views' ] },
107 { fields: [ 'channelId' ] },
109 fields: [ 'category' ], // We don't care videos with an unknown category
112 [Sequelize.Op.ne]: null
117 fields: [ 'licence' ], // We don't care videos with an unknown licence
120 [Sequelize.Op.ne]: null
125 fields: [ 'language' ], // We don't care videos with an unknown language
128 [Sequelize.Op.ne]: null
133 fields: [ 'nsfw' ], // Most of the videos are not NSFW
139 fields: [ 'remote' ], // Only index local videos
154 export enum ScopeNames {
155 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
157 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
158 WITH_TAGS = 'WITH_TAGS',
159 WITH_FILES = 'WITH_FILES',
160 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
161 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
162 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
165 type ForAPIOptions = {
170 type AvailableForListIDsOptions = {
171 serverAccountId: number
172 followerActorId: number
173 includeLocalVideos: boolean
175 categoryOneOf?: number[]
177 licenceOneOf?: number[]
178 languageOneOf?: string[]
183 videoChannelId?: number
184 trendingDays?: number
186 historyOfUser?: UserModel
190 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
191 const accountInclude = {
192 attributes: [ 'id', 'name' ],
193 model: AccountModel.unscoped(),
197 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
198 model: ActorModel.unscoped(),
202 attributes: [ 'host' ],
203 model: ServerModel.unscoped(),
207 model: AvatarModel.unscoped(),
215 const videoChannelInclude = {
216 attributes: [ 'name', 'description', 'id' ],
217 model: VideoChannelModel.unscoped(),
221 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
222 model: ActorModel.unscoped(),
226 attributes: [ 'host' ],
227 model: ServerModel.unscoped(),
231 model: AvatarModel.unscoped(),
240 const query: IFindOptions<VideoModel> = {
243 [ Sequelize.Op.any ]: options.ids
246 include: [ videoChannelInclude ]
249 if (options.withFiles === true) {
251 model: VideoFileModel.unscoped(),
258 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
259 const query: IFindOptions<VideoModel> = {
261 attributes: [ 'id' ],
264 [ Sequelize.Op.and ]: [
266 [ Sequelize.Op.notIn ]: Sequelize.literal(
267 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
273 [ Sequelize.Op.notIn ]: Sequelize.literal(
275 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
276 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
285 // Only list public/published videos
286 if (!options.filter || options.filter !== 'all-local') {
287 const privacyWhere = {
288 // Always list public videos
289 privacy: VideoPrivacy.PUBLIC,
290 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
291 [ Sequelize.Op.or ]: [
293 state: VideoState.PUBLISHED
296 [ Sequelize.Op.and ]: {
297 state: VideoState.TO_TRANSCODE,
298 waitTranscoding: false
304 Object.assign(query.where, privacyWhere)
307 if (options.filter || options.accountId || options.videoChannelId) {
308 const videoChannelInclude: IIncludeOptions = {
310 model: VideoChannelModel.unscoped(),
314 if (options.videoChannelId) {
315 videoChannelInclude.where = {
316 id: options.videoChannelId
320 if (options.filter || options.accountId) {
321 const accountInclude: IIncludeOptions = {
323 model: AccountModel.unscoped(),
327 if (options.filter) {
328 accountInclude.include = [
331 model: ActorModel.unscoped(),
333 where: VideoModel.buildActorWhereWithFilter(options.filter)
338 if (options.accountId) {
339 accountInclude.where = { id: options.accountId }
342 videoChannelInclude.include = [ accountInclude ]
345 query.include.push(videoChannelInclude)
348 if (options.followerActorId) {
349 let localVideosReq = ''
350 if (options.includeLocalVideos === true) {
351 localVideosReq = ' UNION ALL ' +
352 'SELECT "video"."id" AS "id" FROM "video" ' +
353 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
354 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
355 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
356 'WHERE "actor"."serverId" IS NULL'
359 // Force actorId to be a number to avoid SQL injections
360 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
361 query.where[ 'id' ][ Sequelize.Op.and ].push({
362 [ Sequelize.Op.in ]: Sequelize.literal(
364 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
365 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
366 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
368 'SELECT "video"."id" AS "id" FROM "video" ' +
369 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
370 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
371 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
372 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
373 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
380 if (options.withFiles === true) {
381 query.where[ 'id' ][ Sequelize.Op.and ].push({
382 [ Sequelize.Op.in ]: Sequelize.literal(
383 '(SELECT "videoId" FROM "videoFile")'
388 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
389 if (options.tagsAllOf || options.tagsOneOf) {
390 const createTagsIn = (tags: string[]) => {
391 return tags.map(t => VideoModel.sequelize.escape(t))
395 if (options.tagsOneOf) {
396 query.where[ 'id' ][ Sequelize.Op.and ].push({
397 [ Sequelize.Op.in ]: Sequelize.literal(
399 'SELECT "videoId" FROM "videoTag" ' +
400 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
401 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
407 if (options.tagsAllOf) {
408 query.where[ 'id' ][ Sequelize.Op.and ].push({
409 [ Sequelize.Op.in ]: Sequelize.literal(
411 'SELECT "videoId" FROM "videoTag" ' +
412 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
413 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
414 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
421 if (options.nsfw === true || options.nsfw === false) {
422 query.where[ 'nsfw' ] = options.nsfw
425 if (options.categoryOneOf) {
426 query.where[ 'category' ] = {
427 [ Sequelize.Op.or ]: options.categoryOneOf
431 if (options.licenceOneOf) {
432 query.where[ 'licence' ] = {
433 [ Sequelize.Op.or ]: options.licenceOneOf
437 if (options.languageOneOf) {
438 query.where[ 'language' ] = {
439 [ Sequelize.Op.or ]: options.languageOneOf
443 if (options.trendingDays) {
444 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
446 query.subQuery = false
449 if (options.historyOfUser) {
451 model: UserVideoHistoryModel,
454 userId: options.historyOfUser.id
458 // Even if the relation is n:m, we know that a user only have 0..1 video history
459 // So we won't have multiple rows for the same video
460 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
461 query.subQuery = false
466 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
469 model: () => VideoChannelModel.unscoped(),
474 exclude: [ 'privateKey', 'publicKey' ]
476 model: () => ActorModel.unscoped(),
480 attributes: [ 'host' ],
481 model: () => ServerModel.unscoped(),
485 model: () => AvatarModel.unscoped(),
491 model: () => AccountModel.unscoped(),
495 model: () => ActorModel.unscoped(),
497 exclude: [ 'privateKey', 'publicKey' ]
502 attributes: [ 'host' ],
503 model: () => ServerModel.unscoped(),
507 model: () => AvatarModel.unscoped(),
518 [ ScopeNames.WITH_TAGS ]: {
519 include: [ () => TagModel ]
521 [ ScopeNames.WITH_BLACKLISTED ]: {
524 attributes: [ 'id', 'reason' ],
525 model: () => VideoBlacklistModel,
530 [ ScopeNames.WITH_FILES ]: {
533 model: () => VideoFileModel.unscoped(),
535 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
539 attributes: [ 'fileUrl' ],
540 model: () => VideoRedundancyModel.unscoped(),
547 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
550 model: () => ScheduleVideoUpdateModel.unscoped(),
555 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
559 attributes: [ 'currentTime' ],
560 model: UserVideoHistoryModel.unscoped(),
574 export class VideoModel extends Model<VideoModel> {
577 @Default(DataType.UUIDV4)
579 @Column(DataType.UUID)
583 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
589 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
595 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
601 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
602 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
606 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
611 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
617 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
618 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
623 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
624 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
628 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
658 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
659 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
664 commentsEnabled: boolean
668 waitTranscoding: boolean
672 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
683 @Default(Sequelize.NOW)
687 @ForeignKey(() => VideoChannelModel)
691 @BelongsTo(() => VideoChannelModel, {
697 VideoChannel: VideoChannelModel
699 @BelongsToMany(() => TagModel, {
700 foreignKey: 'videoId',
701 through: () => VideoTagModel,
706 @HasMany(() => VideoAbuseModel, {
713 VideoAbuses: VideoAbuseModel[]
715 @HasMany(() => VideoFileModel, {
723 VideoFiles: VideoFileModel[]
725 @HasMany(() => VideoShareModel, {
732 VideoShares: VideoShareModel[]
734 @HasMany(() => AccountVideoRateModel, {
741 AccountVideoRates: AccountVideoRateModel[]
743 @HasMany(() => VideoCommentModel, {
751 VideoComments: VideoCommentModel[]
753 @HasMany(() => VideoViewModel, {
760 VideoViews: VideoViewModel[]
762 @HasMany(() => UserVideoHistoryModel, {
769 UserVideoHistories: UserVideoHistoryModel[]
771 @HasOne(() => ScheduleVideoUpdateModel, {
778 ScheduleVideoUpdate: ScheduleVideoUpdateModel
780 @HasOne(() => VideoBlacklistModel, {
787 VideoBlacklist: VideoBlacklistModel
789 @HasOne(() => VideoImportModel, {
796 VideoImport: VideoImportModel
798 @HasMany(() => VideoCaptionModel, {
805 [ 'separate' as any ]: true
807 VideoCaptions: VideoCaptionModel[]
810 static async sendDelete (instance: VideoModel, options) {
811 if (instance.isOwned()) {
812 if (!instance.VideoChannel) {
813 instance.VideoChannel = await instance.$get('VideoChannel', {
817 include: [ ActorModel ]
820 transaction: options.transaction
821 }) as VideoChannelModel
824 return sendDeleteVideo(instance, options.transaction)
831 static async removeFiles (instance: VideoModel) {
832 const tasks: Promise<any>[] = []
834 logger.info('Removing files of video %s.', instance.url)
836 tasks.push(instance.removeThumbnail())
838 if (instance.isOwned()) {
839 if (!Array.isArray(instance.VideoFiles)) {
840 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
843 tasks.push(instance.removePreview())
845 // Remove physical files and torrents
846 instance.VideoFiles.forEach(file => {
847 tasks.push(instance.removeFile(file))
848 tasks.push(instance.removeTorrent(file))
852 // Do not wait video deletion because we could be in a transaction
855 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
862 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
865 static listLocal () {
872 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
875 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
876 function getRawQuery (select: string) {
877 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
878 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
879 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
880 'WHERE "Account"."actorId" = ' + actorId
881 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
882 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
883 'WHERE "VideoShare"."actorId" = ' + actorId
885 return `(${queryVideo}) UNION (${queryVideoShare})`
888 const rawQuery = getRawQuery('"Video"."id"')
889 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
895 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
898 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
900 [ Sequelize.Op.or ]: [
901 { privacy: VideoPrivacy.PUBLIC },
902 { privacy: VideoPrivacy.UNLISTED }
907 attributes: [ 'language' ],
908 model: VideoCaptionModel.unscoped(),
912 attributes: [ 'id', 'url' ],
913 model: VideoShareModel.unscoped(),
915 // We only want videos shared by this actor
917 [ Sequelize.Op.and ]: [
920 [ Sequelize.Op.not ]: null
930 attributes: [ 'id', 'url' ],
931 model: ActorModel.unscoped()
936 model: VideoChannelModel.unscoped(),
940 attributes: [ 'name' ],
941 model: AccountModel.unscoped(),
945 attributes: [ 'id', 'url', 'followersUrl' ],
946 model: ActorModel.unscoped(),
952 attributes: [ 'id', 'url', 'followersUrl' ],
953 model: ActorModel.unscoped(),
963 return Bluebird.all([
964 // FIXME: typing issue
965 VideoModel.findAll(query as any),
966 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
967 ]).then(([ rows, totals ]) => {
968 // totals: totalVideos + totalVideoShares
970 let totalVideoShares = 0
971 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
972 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
974 const total = totalVideos + totalVideoShares
982 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
983 const query: IFindOptions<VideoModel> = {
986 order: getVideoSort(sort),
989 model: VideoChannelModel,
1002 model: ScheduleVideoUpdateModel,
1006 model: VideoBlacklistModel,
1012 if (withFiles === true) {
1013 query.include.push({
1014 model: VideoFileModel.unscoped(),
1019 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
1027 static async listForApi (options: {
1032 includeLocalVideos: boolean,
1034 categoryOneOf?: number[],
1035 licenceOneOf?: number[],
1036 languageOneOf?: string[],
1037 tagsOneOf?: string[],
1038 tagsAllOf?: string[],
1039 filter?: VideoFilter,
1041 videoChannelId?: number,
1042 followerActorId?: number
1043 trendingDays?: number,
1045 historyOfUser?: UserModel
1046 }, countVideos = true) {
1047 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1048 throw new Error('Try to filter all-local but no user has not the see all videos right')
1051 const query: IFindOptions<VideoModel> = {
1052 offset: options.start,
1053 limit: options.count,
1054 order: getVideoSort(options.sort)
1057 let trendingDays: number
1058 if (options.sort.endsWith('trending')) {
1059 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1061 query.group = 'VideoModel.id'
1064 const serverActor = await getServerActor()
1066 // followerActorId === null has a meaning, so just check undefined
1067 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1069 const queryOptions = {
1071 serverAccountId: serverActor.Account.id,
1073 categoryOneOf: options.categoryOneOf,
1074 licenceOneOf: options.licenceOneOf,
1075 languageOneOf: options.languageOneOf,
1076 tagsOneOf: options.tagsOneOf,
1077 tagsAllOf: options.tagsAllOf,
1078 filter: options.filter,
1079 withFiles: options.withFiles,
1080 accountId: options.accountId,
1081 videoChannelId: options.videoChannelId,
1082 includeLocalVideos: options.includeLocalVideos,
1084 historyOfUser: options.historyOfUser,
1088 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1091 static async searchAndPopulateAccountAndServer (options: {
1092 includeLocalVideos: boolean
1097 startDate?: string // ISO 8601
1098 endDate?: string // ISO 8601
1100 categoryOneOf?: number[]
1101 licenceOneOf?: number[]
1102 languageOneOf?: string[]
1103 tagsOneOf?: string[]
1104 tagsAllOf?: string[]
1105 durationMin?: number // seconds
1106 durationMax?: number // seconds
1108 filter?: VideoFilter
1112 if (options.startDate || options.endDate) {
1113 const publishedAtRange = {}
1115 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1116 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1118 whereAnd.push({ publishedAt: publishedAtRange })
1121 if (options.durationMin || options.durationMax) {
1122 const durationRange = {}
1124 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1125 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1127 whereAnd.push({ duration: durationRange })
1130 const attributesInclude = []
1131 const escapedSearch = VideoModel.sequelize.escape(options.search)
1132 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1133 if (options.search) {
1137 [ Sequelize.Op.in ]: Sequelize.literal(
1139 'SELECT "video"."id" FROM "video" ' +
1141 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1142 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1144 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1145 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1146 'WHERE "tag"."name" = ' + escapedSearch +
1153 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1156 // Cannot search on similarity if we don't have a search
1157 if (!options.search) {
1158 attributesInclude.push(
1159 Sequelize.literal('0 as similarity')
1163 const query: IFindOptions<VideoModel> = {
1165 include: attributesInclude
1167 offset: options.start,
1168 limit: options.count,
1169 order: getVideoSort(options.sort),
1171 [ Sequelize.Op.and ]: whereAnd
1175 const serverActor = await getServerActor()
1176 const queryOptions = {
1177 followerActorId: serverActor.id,
1178 serverAccountId: serverActor.Account.id,
1179 includeLocalVideos: options.includeLocalVideos,
1181 categoryOneOf: options.categoryOneOf,
1182 licenceOneOf: options.licenceOneOf,
1183 languageOneOf: options.languageOneOf,
1184 tagsOneOf: options.tagsOneOf,
1185 tagsAllOf: options.tagsAllOf,
1187 filter: options.filter
1190 return VideoModel.getAvailableForApi(query, queryOptions)
1193 static load (id: number | string, t?: Sequelize.Transaction) {
1194 const where = VideoModel.buildWhereIdOrUUID(id)
1200 return VideoModel.findOne(options)
1203 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1204 const where = VideoModel.buildWhereIdOrUUID(id)
1207 attributes: [ 'id' ],
1212 return VideoModel.findOne(options)
1215 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1216 return VideoModel.scope(ScopeNames.WITH_FILES)
1217 .findById(id, { transaction: t, logging })
1220 static loadByUUIDWithFile (uuid: string) {
1228 .scope([ ScopeNames.WITH_FILES ])
1232 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1233 const query: IFindOptions<VideoModel> = {
1240 return VideoModel.findOne(query)
1243 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1244 const query: IFindOptions<VideoModel> = {
1251 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1254 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1255 const where = VideoModel.buildWhereIdOrUUID(id)
1258 order: [ [ 'Tags', 'name', 'ASC' ] ],
1264 ScopeNames.WITH_TAGS,
1265 ScopeNames.WITH_BLACKLISTED,
1266 ScopeNames.WITH_FILES,
1267 ScopeNames.WITH_ACCOUNT_DETAILS,
1268 ScopeNames.WITH_SCHEDULED_UPDATE
1272 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1280 static async getStats () {
1281 const totalLocalVideos = await VideoModel.count({
1286 const totalVideos = await VideoModel.count()
1288 let totalLocalVideoViews = await VideoModel.sum('views', {
1293 // Sequelize could return null...
1294 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1298 totalLocalVideoViews,
1303 static incrementViews (id: number, views: number) {
1304 return VideoModel.increment('views', {
1312 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1313 // Instances only share videos
1314 const query = 'SELECT 1 FROM "videoShare" ' +
1315 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1316 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1320 type: Sequelize.QueryTypes.SELECT,
1321 bind: { followerActorId, videoId },
1325 return VideoModel.sequelize.query(query, options)
1326 .then(results => results.length === 1)
1329 // threshold corresponds to how many video the field should have to be returned
1330 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1331 const serverActor = await getServerActor()
1332 const followerActorId = serverActor.id
1334 const scopeOptions: AvailableForListIDsOptions = {
1335 serverAccountId: serverActor.Account.id,
1337 includeLocalVideos: true
1340 const query: IFindOptions<VideoModel> = {
1341 attributes: [ field ],
1344 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1345 [ Sequelize.Op.gte ]: threshold
1346 }) as any, // FIXME: typings
1347 order: [ this.sequelize.random() ]
1350 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1352 .then(rows => rows.map(r => r[ field ]))
1355 static buildTrendingQuery (trendingDays: number) {
1359 model: VideoViewModel,
1363 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1369 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1370 if (filter && (filter === 'local' || filter === 'all-local')) {
1379 private static async getAvailableForApi (
1380 query: IFindOptions<VideoModel>,
1381 options: AvailableForListIDsOptions,
1386 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1390 // Remove trending sort on count, because it uses a group by
1391 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1392 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1393 const countScope = {
1395 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1399 const [ count, rowsId ] = await Promise.all([
1400 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1401 VideoModel.scope(idsScope).findAll(query)
1403 const ids = rowsId.map(r => r.id)
1405 if (ids.length === 0) return { data: [], total: count }
1408 const apiScope: any[] = [
1410 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1415 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1418 const secondQuery = {
1421 attributes: query.attributes,
1422 order: [ // Keep original order
1424 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1428 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1436 static getCategoryLabel (id: number) {
1437 return VIDEO_CATEGORIES[ id ] || 'Misc'
1440 static getLicenceLabel (id: number) {
1441 return VIDEO_LICENCES[ id ] || 'Unknown'
1444 static getLanguageLabel (id: string) {
1445 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1448 static getPrivacyLabel (id: number) {
1449 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1452 static getStateLabel (id: number) {
1453 return VIDEO_STATES[ id ] || 'Unknown'
1456 static buildWhereIdOrUUID (id: number | string) {
1457 return validator.isInt('' + id) ? { id } : { uuid: id }
1460 getOriginalFile () {
1461 if (Array.isArray(this.VideoFiles) === false) return undefined
1463 // The original file is the file that have the higher resolution
1464 return maxBy(this.VideoFiles, file => file.resolution)
1467 getVideoFilename (videoFile: VideoFileModel) {
1468 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1471 getThumbnailName () {
1472 // We always have a copy of the thumbnail
1473 const extension = '.jpg'
1474 return this.uuid + extension
1478 const extension = '.jpg'
1479 return this.uuid + extension
1482 getTorrentFileName (videoFile: VideoFileModel) {
1483 const extension = '.torrent'
1484 return this.uuid + '-' + videoFile.resolution + extension
1488 return this.remote === false
1491 createPreview (videoFile: VideoFileModel) {
1492 return generateImageFromVideoFile(
1493 this.getVideoFilePath(videoFile),
1494 CONFIG.STORAGE.PREVIEWS_DIR,
1495 this.getPreviewName(),
1500 createThumbnail (videoFile: VideoFileModel) {
1501 return generateImageFromVideoFile(
1502 this.getVideoFilePath(videoFile),
1503 CONFIG.STORAGE.THUMBNAILS_DIR,
1504 this.getThumbnailName(),
1509 getTorrentFilePath (videoFile: VideoFileModel) {
1510 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1513 getVideoFilePath (videoFile: VideoFileModel) {
1514 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1517 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1519 // Keep the extname, it's used by the client to stream the file inside a web browser
1520 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1521 createdBy: 'PeerTube',
1523 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1524 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1526 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1529 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1531 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1532 logger.info('Creating torrent %s.', filePath)
1534 await writeFile(filePath, torrent)
1536 const parsedTorrent = parseTorrent(torrent)
1537 videoFile.infoHash = parsedTorrent.infoHash
1540 getWatchStaticPath () {
1541 return '/videos/watch/' + this.uuid
1544 getEmbedStaticPath () {
1545 return '/videos/embed/' + this.uuid
1548 getThumbnailStaticPath () {
1549 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1552 getPreviewStaticPath () {
1553 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1556 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1557 return videoModelToFormattedJSON(this, options)
1560 toFormattedDetailsJSON (): VideoDetails {
1561 return videoModelToFormattedDetailsJSON(this)
1564 getFormattedVideoFilesJSON (): VideoFile[] {
1565 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1568 toActivityPubObject (): VideoTorrentObject {
1569 return videoModelToActivityPubObject(this)
1572 getTruncatedDescription () {
1573 if (!this.description) return null
1575 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1576 return peertubeTruncate(this.description, maxLength)
1579 getOriginalFileResolution () {
1580 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1582 return getVideoFileResolution(originalFilePath)
1585 getDescriptionAPIPath () {
1586 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1589 removeThumbnail () {
1590 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1591 return remove(thumbnailPath)
1592 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1596 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1597 return remove(previewPath)
1598 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1601 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1602 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1604 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1605 return remove(filePath)
1606 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1609 removeTorrent (videoFile: VideoFileModel) {
1610 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1611 return remove(torrentPath)
1612 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1616 if (this.isOwned()) return false
1618 const now = Date.now()
1619 const createdAtTime = this.createdAt.getTime()
1620 const updatedAtTime = this.updatedAt.getTime()
1622 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1623 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1627 this.changed('updatedAt', true)
1636 if (this.isOwned()) {
1637 baseUrlHttp = CONFIG.WEBSERVER.URL
1638 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1640 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1641 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1644 return { baseUrlHttp, baseUrlWs }
1647 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1648 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1649 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1650 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1652 const redundancies = videoFile.RedundancyVideos
1653 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1655 const magnetHash = {
1659 infoHash: videoFile.infoHash,
1663 return magnetUtil.encode(magnetHash)
1666 getThumbnailUrl (baseUrlHttp: string) {
1667 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1670 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1671 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1674 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1675 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1678 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1679 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1682 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1683 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1686 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1687 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)