1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
29 } from 'sequelize-typescript'
30 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileResolution } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
58 STATIC_DOWNLOAD_PATHS,
66 } from '../../initializers'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { buildBlockedAccountSQL, buildTrigramSearchIndex, createSimilarityAttribute, getVideoSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
81 import { ScheduleVideoUpdateModel } from './schedule-video-update'
82 import { VideoCaptionModel } from './video-caption'
83 import { VideoBlacklistModel } from './video-blacklist'
84 import { remove, writeFile } from 'fs-extra'
85 import { VideoViewModel } from './video-views'
86 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
88 videoFilesModelToFormattedJSON,
89 VideoFormattingJSONOptions,
90 videoModelToActivityPubObject,
91 videoModelToFormattedDetailsJSON,
92 videoModelToFormattedJSON
93 } from './video-format-utils'
94 import * as validator from 'validator'
95 import { UserVideoHistoryModel } from '../account/user-video-history'
96 import { UserModel } from '../account/user'
98 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99 const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
125 export enum ScopeNames {
126 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
136 type ForAPIOptions = {
141 type AvailableForListIDsOptions = {
142 serverAccountId: number
143 followerActorId: number
144 includeLocalVideos: boolean
146 categoryOneOf?: number[]
148 licenceOneOf?: number[]
149 languageOneOf?: string[]
154 videoChannelId?: number
155 trendingDays?: number
157 historyOfUser?: UserModel
161 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
162 const accountInclude = {
163 attributes: [ 'id', 'name' ],
164 model: AccountModel.unscoped(),
168 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
169 model: ActorModel.unscoped(),
173 attributes: [ 'host' ],
174 model: ServerModel.unscoped(),
178 model: AvatarModel.unscoped(),
186 const videoChannelInclude = {
187 attributes: [ 'name', 'description', 'id' ],
188 model: VideoChannelModel.unscoped(),
192 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
193 model: ActorModel.unscoped(),
197 attributes: [ 'host' ],
198 model: ServerModel.unscoped(),
202 model: AvatarModel.unscoped(),
211 const query: IFindOptions<VideoModel> = {
214 [ Sequelize.Op.any ]: options.ids
217 include: [ videoChannelInclude ]
220 if (options.withFiles === true) {
222 model: VideoFileModel.unscoped(),
229 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
230 const query: IFindOptions<VideoModel> = {
232 attributes: [ 'id' ],
235 [ Sequelize.Op.and ]: [
237 [ Sequelize.Op.notIn ]: Sequelize.literal(
238 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
244 [ Sequelize.Op.notIn ]: Sequelize.literal(
246 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
247 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
256 // Only list public/published videos
257 if (!options.filter || options.filter !== 'all-local') {
258 const privacyWhere = {
259 // Always list public videos
260 privacy: VideoPrivacy.PUBLIC,
261 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
262 [ Sequelize.Op.or ]: [
264 state: VideoState.PUBLISHED
267 [ Sequelize.Op.and ]: {
268 state: VideoState.TO_TRANSCODE,
269 waitTranscoding: false
275 Object.assign(query.where, privacyWhere)
278 if (options.filter || options.accountId || options.videoChannelId) {
279 const videoChannelInclude: IIncludeOptions = {
281 model: VideoChannelModel.unscoped(),
285 if (options.videoChannelId) {
286 videoChannelInclude.where = {
287 id: options.videoChannelId
291 if (options.filter || options.accountId) {
292 const accountInclude: IIncludeOptions = {
294 model: AccountModel.unscoped(),
298 if (options.filter) {
299 accountInclude.include = [
302 model: ActorModel.unscoped(),
304 where: VideoModel.buildActorWhereWithFilter(options.filter)
309 if (options.accountId) {
310 accountInclude.where = { id: options.accountId }
313 videoChannelInclude.include = [ accountInclude ]
316 query.include.push(videoChannelInclude)
319 if (options.followerActorId) {
320 let localVideosReq = ''
321 if (options.includeLocalVideos === true) {
322 localVideosReq = ' UNION ALL ' +
323 'SELECT "video"."id" AS "id" FROM "video" ' +
324 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
325 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
326 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
327 'WHERE "actor"."serverId" IS NULL'
330 // Force actorId to be a number to avoid SQL injections
331 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
332 query.where[ 'id' ][ Sequelize.Op.and ].push({
333 [ Sequelize.Op.in ]: Sequelize.literal(
335 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
336 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
337 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
339 'SELECT "video"."id" AS "id" FROM "video" ' +
340 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
341 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
342 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
343 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
344 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
351 if (options.withFiles === true) {
352 query.where[ 'id' ][ Sequelize.Op.and ].push({
353 [ Sequelize.Op.in ]: Sequelize.literal(
354 '(SELECT "videoId" FROM "videoFile")'
359 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
360 if (options.tagsAllOf || options.tagsOneOf) {
361 const createTagsIn = (tags: string[]) => {
362 return tags.map(t => VideoModel.sequelize.escape(t))
366 if (options.tagsOneOf) {
367 query.where[ 'id' ][ Sequelize.Op.and ].push({
368 [ Sequelize.Op.in ]: Sequelize.literal(
370 'SELECT "videoId" FROM "videoTag" ' +
371 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
372 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
378 if (options.tagsAllOf) {
379 query.where[ 'id' ][ Sequelize.Op.and ].push({
380 [ Sequelize.Op.in ]: Sequelize.literal(
382 'SELECT "videoId" FROM "videoTag" ' +
383 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
384 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
385 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
392 if (options.nsfw === true || options.nsfw === false) {
393 query.where[ 'nsfw' ] = options.nsfw
396 if (options.categoryOneOf) {
397 query.where[ 'category' ] = {
398 [ Sequelize.Op.or ]: options.categoryOneOf
402 if (options.licenceOneOf) {
403 query.where[ 'licence' ] = {
404 [ Sequelize.Op.or ]: options.licenceOneOf
408 if (options.languageOneOf) {
409 query.where[ 'language' ] = {
410 [ Sequelize.Op.or ]: options.languageOneOf
414 if (options.trendingDays) {
415 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
417 query.subQuery = false
420 if (options.historyOfUser) {
422 model: UserVideoHistoryModel,
425 userId: options.historyOfUser.id
432 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
435 model: () => VideoChannelModel.unscoped(),
440 exclude: [ 'privateKey', 'publicKey' ]
442 model: () => ActorModel.unscoped(),
446 attributes: [ 'host' ],
447 model: () => ServerModel.unscoped(),
451 model: () => AvatarModel.unscoped(),
457 model: () => AccountModel.unscoped(),
461 model: () => ActorModel.unscoped(),
463 exclude: [ 'privateKey', 'publicKey' ]
468 attributes: [ 'host' ],
469 model: () => ServerModel.unscoped(),
473 model: () => AvatarModel.unscoped(),
484 [ ScopeNames.WITH_TAGS ]: {
485 include: [ () => TagModel ]
487 [ ScopeNames.WITH_BLACKLISTED ]: {
490 attributes: [ 'id', 'reason' ],
491 model: () => VideoBlacklistModel,
496 [ ScopeNames.WITH_FILES ]: {
499 model: () => VideoFileModel.unscoped(),
501 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
505 attributes: [ 'fileUrl' ],
506 model: () => VideoRedundancyModel.unscoped(),
513 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
516 model: () => ScheduleVideoUpdateModel.unscoped(),
521 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
525 attributes: [ 'currentTime' ],
526 model: UserVideoHistoryModel.unscoped(),
540 export class VideoModel extends Model<VideoModel> {
543 @Default(DataType.UUIDV4)
545 @Column(DataType.UUID)
549 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
555 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
561 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
567 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
568 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
572 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
577 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
583 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
584 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
589 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
590 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
594 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
624 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
625 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
630 commentsEnabled: boolean
634 waitTranscoding: boolean
638 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
649 @Default(Sequelize.NOW)
653 @ForeignKey(() => VideoChannelModel)
657 @BelongsTo(() => VideoChannelModel, {
663 VideoChannel: VideoChannelModel
665 @BelongsToMany(() => TagModel, {
666 foreignKey: 'videoId',
667 through: () => VideoTagModel,
672 @HasMany(() => VideoAbuseModel, {
679 VideoAbuses: VideoAbuseModel[]
681 @HasMany(() => VideoFileModel, {
689 VideoFiles: VideoFileModel[]
691 @HasMany(() => VideoShareModel, {
698 VideoShares: VideoShareModel[]
700 @HasMany(() => AccountVideoRateModel, {
707 AccountVideoRates: AccountVideoRateModel[]
709 @HasMany(() => VideoCommentModel, {
717 VideoComments: VideoCommentModel[]
719 @HasMany(() => VideoViewModel, {
726 VideoViews: VideoViewModel[]
728 @HasMany(() => UserVideoHistoryModel, {
735 UserVideoHistories: UserVideoHistoryModel[]
737 @HasOne(() => ScheduleVideoUpdateModel, {
744 ScheduleVideoUpdate: ScheduleVideoUpdateModel
746 @HasOne(() => VideoBlacklistModel, {
753 VideoBlacklist: VideoBlacklistModel
755 @HasMany(() => VideoCaptionModel, {
762 [ 'separate' as any ]: true
764 VideoCaptions: VideoCaptionModel[]
767 static async sendDelete (instance: VideoModel, options) {
768 if (instance.isOwned()) {
769 if (!instance.VideoChannel) {
770 instance.VideoChannel = await instance.$get('VideoChannel', {
774 include: [ ActorModel ]
777 transaction: options.transaction
778 }) as VideoChannelModel
781 return sendDeleteVideo(instance, options.transaction)
788 static async removeFiles (instance: VideoModel) {
789 const tasks: Promise<any>[] = []
791 logger.info('Removing files of video %s.', instance.url)
793 tasks.push(instance.removeThumbnail())
795 if (instance.isOwned()) {
796 if (!Array.isArray(instance.VideoFiles)) {
797 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
800 tasks.push(instance.removePreview())
802 // Remove physical files and torrents
803 instance.VideoFiles.forEach(file => {
804 tasks.push(instance.removeFile(file))
805 tasks.push(instance.removeTorrent(file))
809 // Do not wait video deletion because we could be in a transaction
812 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
819 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
822 static listLocal () {
829 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
832 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
833 function getRawQuery (select: string) {
834 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
835 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
836 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
837 'WHERE "Account"."actorId" = ' + actorId
838 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
839 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
840 'WHERE "VideoShare"."actorId" = ' + actorId
842 return `(${queryVideo}) UNION (${queryVideoShare})`
845 const rawQuery = getRawQuery('"Video"."id"')
846 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
852 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
855 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
857 [ Sequelize.Op.or ]: [
858 { privacy: VideoPrivacy.PUBLIC },
859 { privacy: VideoPrivacy.UNLISTED }
864 attributes: [ 'language' ],
865 model: VideoCaptionModel.unscoped(),
869 attributes: [ 'id', 'url' ],
870 model: VideoShareModel.unscoped(),
872 // We only want videos shared by this actor
874 [ Sequelize.Op.and ]: [
877 [ Sequelize.Op.not ]: null
887 attributes: [ 'id', 'url' ],
888 model: ActorModel.unscoped()
893 model: VideoChannelModel.unscoped(),
897 attributes: [ 'name' ],
898 model: AccountModel.unscoped(),
902 attributes: [ 'id', 'url', 'followersUrl' ],
903 model: ActorModel.unscoped(),
909 attributes: [ 'id', 'url', 'followersUrl' ],
910 model: ActorModel.unscoped(),
920 return Bluebird.all([
921 // FIXME: typing issue
922 VideoModel.findAll(query as any),
923 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
924 ]).then(([ rows, totals ]) => {
925 // totals: totalVideos + totalVideoShares
927 let totalVideoShares = 0
928 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
929 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
931 const total = totalVideos + totalVideoShares
939 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
940 const query: IFindOptions<VideoModel> = {
943 order: getVideoSort(sort),
946 model: VideoChannelModel,
959 model: ScheduleVideoUpdateModel,
963 model: VideoBlacklistModel,
969 if (withFiles === true) {
971 model: VideoFileModel.unscoped(),
976 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
984 static async listForApi (options: {
989 includeLocalVideos: boolean,
991 categoryOneOf?: number[],
992 licenceOneOf?: number[],
993 languageOneOf?: string[],
994 tagsOneOf?: string[],
995 tagsAllOf?: string[],
996 filter?: VideoFilter,
998 videoChannelId?: number,
999 followerActorId?: number
1000 trendingDays?: number,
1002 historyOfUser?: UserModel
1003 }, countVideos = true) {
1004 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1005 throw new Error('Try to filter all-local but no user has not the see all videos right')
1008 const query: IFindOptions<VideoModel> = {
1009 offset: options.start,
1010 limit: options.count,
1011 order: getVideoSort(options.sort)
1014 let trendingDays: number
1015 if (options.sort.endsWith('trending')) {
1016 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1018 query.group = 'VideoModel.id'
1021 const serverActor = await getServerActor()
1023 // followerActorId === null has a meaning, so just check undefined
1024 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1026 const queryOptions = {
1028 serverAccountId: serverActor.Account.id,
1030 categoryOneOf: options.categoryOneOf,
1031 licenceOneOf: options.licenceOneOf,
1032 languageOneOf: options.languageOneOf,
1033 tagsOneOf: options.tagsOneOf,
1034 tagsAllOf: options.tagsAllOf,
1035 filter: options.filter,
1036 withFiles: options.withFiles,
1037 accountId: options.accountId,
1038 videoChannelId: options.videoChannelId,
1039 includeLocalVideos: options.includeLocalVideos,
1041 historyOfUser: options.historyOfUser,
1045 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1048 static async searchAndPopulateAccountAndServer (options: {
1049 includeLocalVideos: boolean
1054 startDate?: string // ISO 8601
1055 endDate?: string // ISO 8601
1057 categoryOneOf?: number[]
1058 licenceOneOf?: number[]
1059 languageOneOf?: string[]
1060 tagsOneOf?: string[]
1061 tagsAllOf?: string[]
1062 durationMin?: number // seconds
1063 durationMax?: number // seconds
1065 filter?: VideoFilter
1069 if (options.startDate || options.endDate) {
1070 const publishedAtRange = {}
1072 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1073 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1075 whereAnd.push({ publishedAt: publishedAtRange })
1078 if (options.durationMin || options.durationMax) {
1079 const durationRange = {}
1081 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1082 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1084 whereAnd.push({ duration: durationRange })
1087 const attributesInclude = []
1088 const escapedSearch = VideoModel.sequelize.escape(options.search)
1089 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1090 if (options.search) {
1094 [ Sequelize.Op.in ]: Sequelize.literal(
1096 'SELECT "video"."id" FROM "video" ' +
1098 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1099 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1101 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1102 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1103 'WHERE "tag"."name" = ' + escapedSearch +
1110 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1113 // Cannot search on similarity if we don't have a search
1114 if (!options.search) {
1115 attributesInclude.push(
1116 Sequelize.literal('0 as similarity')
1120 const query: IFindOptions<VideoModel> = {
1122 include: attributesInclude
1124 offset: options.start,
1125 limit: options.count,
1126 order: getVideoSort(options.sort),
1128 [ Sequelize.Op.and ]: whereAnd
1132 const serverActor = await getServerActor()
1133 const queryOptions = {
1134 followerActorId: serverActor.id,
1135 serverAccountId: serverActor.Account.id,
1136 includeLocalVideos: options.includeLocalVideos,
1138 categoryOneOf: options.categoryOneOf,
1139 licenceOneOf: options.licenceOneOf,
1140 languageOneOf: options.languageOneOf,
1141 tagsOneOf: options.tagsOneOf,
1142 tagsAllOf: options.tagsAllOf,
1144 filter: options.filter
1147 return VideoModel.getAvailableForApi(query, queryOptions)
1150 static load (id: number | string, t?: Sequelize.Transaction) {
1151 const where = VideoModel.buildWhereIdOrUUID(id)
1157 return VideoModel.findOne(options)
1160 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1161 const where = VideoModel.buildWhereIdOrUUID(id)
1164 attributes: [ 'id' ],
1169 return VideoModel.findOne(options)
1172 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1173 return VideoModel.scope(ScopeNames.WITH_FILES)
1174 .findById(id, { transaction: t, logging })
1177 static loadByUUIDWithFile (uuid: string) {
1185 .scope([ ScopeNames.WITH_FILES ])
1189 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1190 const query: IFindOptions<VideoModel> = {
1197 return VideoModel.findOne(query)
1200 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1201 const query: IFindOptions<VideoModel> = {
1208 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1211 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1212 const where = VideoModel.buildWhereIdOrUUID(id)
1215 order: [ [ 'Tags', 'name', 'ASC' ] ],
1221 ScopeNames.WITH_TAGS,
1222 ScopeNames.WITH_BLACKLISTED,
1223 ScopeNames.WITH_FILES,
1224 ScopeNames.WITH_ACCOUNT_DETAILS,
1225 ScopeNames.WITH_SCHEDULED_UPDATE
1229 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1237 static async getStats () {
1238 const totalLocalVideos = await VideoModel.count({
1243 const totalVideos = await VideoModel.count()
1245 let totalLocalVideoViews = await VideoModel.sum('views', {
1250 // Sequelize could return null...
1251 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1255 totalLocalVideoViews,
1260 static incrementViews (id: number, views: number) {
1261 return VideoModel.increment('views', {
1269 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1270 // Instances only share videos
1271 const query = 'SELECT 1 FROM "videoShare" ' +
1272 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1273 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1277 type: Sequelize.QueryTypes.SELECT,
1278 bind: { followerActorId, videoId },
1282 return VideoModel.sequelize.query(query, options)
1283 .then(results => results.length === 1)
1286 // threshold corresponds to how many video the field should have to be returned
1287 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1288 const serverActor = await getServerActor()
1289 const followerActorId = serverActor.id
1291 const scopeOptions: AvailableForListIDsOptions = {
1292 serverAccountId: serverActor.Account.id,
1294 includeLocalVideos: true
1297 const query: IFindOptions<VideoModel> = {
1298 attributes: [ field ],
1301 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1302 [ Sequelize.Op.gte ]: threshold
1303 }) as any, // FIXME: typings
1304 order: [ this.sequelize.random() ]
1307 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1309 .then(rows => rows.map(r => r[ field ]))
1312 static buildTrendingQuery (trendingDays: number) {
1316 model: VideoViewModel,
1320 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1326 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1327 if (filter && (filter === 'local' || filter === 'all-local')) {
1336 private static async getAvailableForApi (
1337 query: IFindOptions<VideoModel>,
1338 options: AvailableForListIDsOptions,
1343 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1347 // Remove trending sort on count, because it uses a group by
1348 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1349 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1350 const countScope = {
1352 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1356 const [ count, rowsId ] = await Promise.all([
1357 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve<number>(undefined),
1358 VideoModel.scope(idsScope).findAll(query)
1360 const ids = rowsId.map(r => r.id)
1362 if (ids.length === 0) return { data: [], total: count }
1365 const apiScope: any[] = [
1367 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1372 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1375 const secondQuery = {
1378 attributes: query.attributes,
1379 order: [ // Keep original order
1381 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1385 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1393 static getCategoryLabel (id: number) {
1394 return VIDEO_CATEGORIES[ id ] || 'Misc'
1397 static getLicenceLabel (id: number) {
1398 return VIDEO_LICENCES[ id ] || 'Unknown'
1401 static getLanguageLabel (id: string) {
1402 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1405 static getPrivacyLabel (id: number) {
1406 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1409 static getStateLabel (id: number) {
1410 return VIDEO_STATES[ id ] || 'Unknown'
1413 static buildWhereIdOrUUID (id: number | string) {
1414 return validator.isInt('' + id) ? { id } : { uuid: id }
1417 getOriginalFile () {
1418 if (Array.isArray(this.VideoFiles) === false) return undefined
1420 // The original file is the file that have the higher resolution
1421 return maxBy(this.VideoFiles, file => file.resolution)
1424 getVideoFilename (videoFile: VideoFileModel) {
1425 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1428 getThumbnailName () {
1429 // We always have a copy of the thumbnail
1430 const extension = '.jpg'
1431 return this.uuid + extension
1435 const extension = '.jpg'
1436 return this.uuid + extension
1439 getTorrentFileName (videoFile: VideoFileModel) {
1440 const extension = '.torrent'
1441 return this.uuid + '-' + videoFile.resolution + extension
1445 return this.remote === false
1448 createPreview (videoFile: VideoFileModel) {
1449 return generateImageFromVideoFile(
1450 this.getVideoFilePath(videoFile),
1451 CONFIG.STORAGE.PREVIEWS_DIR,
1452 this.getPreviewName(),
1457 createThumbnail (videoFile: VideoFileModel) {
1458 return generateImageFromVideoFile(
1459 this.getVideoFilePath(videoFile),
1460 CONFIG.STORAGE.THUMBNAILS_DIR,
1461 this.getThumbnailName(),
1466 getTorrentFilePath (videoFile: VideoFileModel) {
1467 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1470 getVideoFilePath (videoFile: VideoFileModel) {
1471 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1474 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1476 // Keep the extname, it's used by the client to stream the file inside a web browser
1477 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1478 createdBy: 'PeerTube',
1480 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1481 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1483 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1486 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1488 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1489 logger.info('Creating torrent %s.', filePath)
1491 await writeFile(filePath, torrent)
1493 const parsedTorrent = parseTorrent(torrent)
1494 videoFile.infoHash = parsedTorrent.infoHash
1497 getEmbedStaticPath () {
1498 return '/videos/embed/' + this.uuid
1501 getThumbnailStaticPath () {
1502 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1505 getPreviewStaticPath () {
1506 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1509 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1510 return videoModelToFormattedJSON(this, options)
1513 toFormattedDetailsJSON (): VideoDetails {
1514 return videoModelToFormattedDetailsJSON(this)
1517 getFormattedVideoFilesJSON (): VideoFile[] {
1518 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1521 toActivityPubObject (): VideoTorrentObject {
1522 return videoModelToActivityPubObject(this)
1525 getTruncatedDescription () {
1526 if (!this.description) return null
1528 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1529 return peertubeTruncate(this.description, maxLength)
1532 getOriginalFileResolution () {
1533 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1535 return getVideoFileResolution(originalFilePath)
1538 getDescriptionAPIPath () {
1539 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1542 removeThumbnail () {
1543 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1544 return remove(thumbnailPath)
1545 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1549 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1550 return remove(previewPath)
1551 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1554 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1555 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1557 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1558 return remove(filePath)
1559 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1562 removeTorrent (videoFile: VideoFileModel) {
1563 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1564 return remove(torrentPath)
1565 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1569 if (this.isOwned()) return false
1571 const now = Date.now()
1572 const createdAtTime = this.createdAt.getTime()
1573 const updatedAtTime = this.updatedAt.getTime()
1575 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1576 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1580 this.changed('updatedAt', true)
1589 if (this.isOwned()) {
1590 baseUrlHttp = CONFIG.WEBSERVER.URL
1591 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1593 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1594 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1597 return { baseUrlHttp, baseUrlWs }
1600 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1601 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1602 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1603 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1605 const redundancies = videoFile.RedundancyVideos
1606 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1608 const magnetHash = {
1612 infoHash: videoFile.infoHash,
1616 return magnetUtil.encode(magnetHash)
1619 getThumbnailUrl (baseUrlHttp: string) {
1620 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1623 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1624 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1627 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1628 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1631 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1632 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1635 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1636 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1639 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1640 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)