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 { 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 { 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'
97 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
98 const indexes: Sequelize.DefineIndexesOptions[] = [
99 buildTrigramSearchIndex('video_name_trigram', 'name'),
101 { fields: [ 'createdAt' ] },
102 { fields: [ 'publishedAt' ] },
103 { fields: [ 'duration' ] },
104 { fields: [ 'category' ] },
105 { fields: [ 'licence' ] },
106 { fields: [ 'nsfw' ] },
107 { fields: [ 'language' ] },
108 { fields: [ 'waitTranscoding' ] },
109 { fields: [ 'state' ] },
110 { fields: [ 'remote' ] },
111 { fields: [ 'views' ] },
112 { fields: [ 'likes' ] },
113 { fields: [ 'channelId' ] },
124 export enum ScopeNames {
125 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
127 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
128 WITH_TAGS = 'WITH_TAGS',
129 WITH_FILES = 'WITH_FILES',
130 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
131 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
132 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
135 type ForAPIOptions = {
140 type AvailableForListIDsOptions = {
142 includeLocalVideos: boolean
144 categoryOneOf?: number[]
146 licenceOneOf?: number[]
147 languageOneOf?: string[]
152 videoChannelId?: number
153 trendingDays?: number
157 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
158 const accountInclude = {
159 attributes: [ 'id', 'name' ],
160 model: AccountModel.unscoped(),
164 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
165 model: ActorModel.unscoped(),
169 attributes: [ 'host' ],
170 model: ServerModel.unscoped(),
174 model: AvatarModel.unscoped(),
182 const videoChannelInclude = {
183 attributes: [ 'name', 'description', 'id' ],
184 model: VideoChannelModel.unscoped(),
188 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
189 model: ActorModel.unscoped(),
193 attributes: [ 'host' ],
194 model: ServerModel.unscoped(),
198 model: AvatarModel.unscoped(),
207 const query: IFindOptions<VideoModel> = {
210 [ Sequelize.Op.any ]: options.ids
213 include: [ videoChannelInclude ]
216 if (options.withFiles === true) {
218 model: VideoFileModel.unscoped(),
225 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
226 const query: IFindOptions<VideoModel> = {
228 attributes: [ 'id' ],
231 [ Sequelize.Op.and ]: [
233 [ Sequelize.Op.notIn ]: Sequelize.literal(
234 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
243 // Only list public/published videos
244 if (!options.filter || options.filter !== 'all-local') {
245 const privacyWhere = {
246 // Always list public videos
247 privacy: VideoPrivacy.PUBLIC,
248 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
249 [ Sequelize.Op.or ]: [
251 state: VideoState.PUBLISHED
254 [ Sequelize.Op.and ]: {
255 state: VideoState.TO_TRANSCODE,
256 waitTranscoding: false
262 Object.assign(query.where, privacyWhere)
265 if (options.filter || options.accountId || options.videoChannelId) {
266 const videoChannelInclude: IIncludeOptions = {
268 model: VideoChannelModel.unscoped(),
272 if (options.videoChannelId) {
273 videoChannelInclude.where = {
274 id: options.videoChannelId
278 if (options.filter || options.accountId) {
279 const accountInclude: IIncludeOptions = {
281 model: AccountModel.unscoped(),
285 if (options.filter) {
286 accountInclude.include = [
289 model: ActorModel.unscoped(),
291 where: VideoModel.buildActorWhereWithFilter(options.filter)
296 if (options.accountId) {
297 accountInclude.where = { id: options.accountId }
300 videoChannelInclude.include = [ accountInclude ]
303 query.include.push(videoChannelInclude)
306 if (options.actorId) {
307 let localVideosReq = ''
308 if (options.includeLocalVideos === true) {
309 localVideosReq = ' UNION ALL ' +
310 'SELECT "video"."id" AS "id" FROM "video" ' +
311 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
312 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
313 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
314 'WHERE "actor"."serverId" IS NULL'
317 // Force actorId to be a number to avoid SQL injections
318 const actorIdNumber = parseInt(options.actorId.toString(), 10)
319 query.where[ 'id' ][ Sequelize.Op.and ].push({
320 [ Sequelize.Op.in ]: Sequelize.literal(
322 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
323 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
324 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
326 'SELECT "video"."id" AS "id" FROM "video" ' +
327 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
328 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
329 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
330 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
331 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
338 if (options.withFiles === true) {
339 query.where[ 'id' ][ Sequelize.Op.and ].push({
340 [ Sequelize.Op.in ]: Sequelize.literal(
341 '(SELECT "videoId" FROM "videoFile")'
346 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
347 if (options.tagsAllOf || options.tagsOneOf) {
348 const createTagsIn = (tags: string[]) => {
349 return tags.map(t => VideoModel.sequelize.escape(t))
353 if (options.tagsOneOf) {
354 query.where[ 'id' ][ Sequelize.Op.and ].push({
355 [ Sequelize.Op.in ]: Sequelize.literal(
357 'SELECT "videoId" FROM "videoTag" ' +
358 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
359 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
365 if (options.tagsAllOf) {
366 query.where[ 'id' ][ Sequelize.Op.and ].push({
367 [ Sequelize.Op.in ]: Sequelize.literal(
369 'SELECT "videoId" FROM "videoTag" ' +
370 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
371 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
372 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
379 if (options.nsfw === true || options.nsfw === false) {
380 query.where[ 'nsfw' ] = options.nsfw
383 if (options.categoryOneOf) {
384 query.where[ 'category' ] = {
385 [ Sequelize.Op.or ]: options.categoryOneOf
389 if (options.licenceOneOf) {
390 query.where[ 'licence' ] = {
391 [ Sequelize.Op.or ]: options.licenceOneOf
395 if (options.languageOneOf) {
396 query.where[ 'language' ] = {
397 [ Sequelize.Op.or ]: options.languageOneOf
401 if (options.trendingDays) {
402 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
404 query.subQuery = false
409 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
412 model: () => VideoChannelModel.unscoped(),
417 exclude: [ 'privateKey', 'publicKey' ]
419 model: () => ActorModel.unscoped(),
423 attributes: [ 'host' ],
424 model: () => ServerModel.unscoped(),
428 model: () => AvatarModel.unscoped(),
434 model: () => AccountModel.unscoped(),
438 model: () => ActorModel.unscoped(),
440 exclude: [ 'privateKey', 'publicKey' ]
445 attributes: [ 'host' ],
446 model: () => ServerModel.unscoped(),
450 model: () => AvatarModel.unscoped(),
461 [ ScopeNames.WITH_TAGS ]: {
462 include: [ () => TagModel ]
464 [ ScopeNames.WITH_BLACKLISTED ]: {
467 attributes: [ 'id', 'reason' ],
468 model: () => VideoBlacklistModel,
473 [ ScopeNames.WITH_FILES ]: {
476 model: () => VideoFileModel.unscoped(),
478 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
482 attributes: [ 'fileUrl' ],
483 model: () => VideoRedundancyModel.unscoped(),
490 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
493 model: () => ScheduleVideoUpdateModel.unscoped(),
498 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
502 attributes: [ 'currentTime' ],
503 model: UserVideoHistoryModel.unscoped(),
517 export class VideoModel extends Model<VideoModel> {
520 @Default(DataType.UUIDV4)
522 @Column(DataType.UUID)
526 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
532 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
538 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
544 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
545 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
549 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
554 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
560 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
561 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
566 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
567 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
571 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
601 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
602 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
607 commentsEnabled: boolean
611 waitTranscoding: boolean
615 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
626 @Default(Sequelize.NOW)
630 @ForeignKey(() => VideoChannelModel)
634 @BelongsTo(() => VideoChannelModel, {
640 VideoChannel: VideoChannelModel
642 @BelongsToMany(() => TagModel, {
643 foreignKey: 'videoId',
644 through: () => VideoTagModel,
649 @HasMany(() => VideoAbuseModel, {
656 VideoAbuses: VideoAbuseModel[]
658 @HasMany(() => VideoFileModel, {
666 VideoFiles: VideoFileModel[]
668 @HasMany(() => VideoShareModel, {
675 VideoShares: VideoShareModel[]
677 @HasMany(() => AccountVideoRateModel, {
684 AccountVideoRates: AccountVideoRateModel[]
686 @HasMany(() => VideoCommentModel, {
694 VideoComments: VideoCommentModel[]
696 @HasMany(() => VideoViewModel, {
703 VideoViews: VideoViewModel[]
705 @HasMany(() => UserVideoHistoryModel, {
712 UserVideoHistories: UserVideoHistoryModel[]
714 @HasOne(() => ScheduleVideoUpdateModel, {
721 ScheduleVideoUpdate: ScheduleVideoUpdateModel
723 @HasOne(() => VideoBlacklistModel, {
730 VideoBlacklist: VideoBlacklistModel
732 @HasMany(() => VideoCaptionModel, {
739 [ 'separate' as any ]: true
741 VideoCaptions: VideoCaptionModel[]
744 static async sendDelete (instance: VideoModel, options) {
745 if (instance.isOwned()) {
746 if (!instance.VideoChannel) {
747 instance.VideoChannel = await instance.$get('VideoChannel', {
751 include: [ ActorModel ]
754 transaction: options.transaction
755 }) as VideoChannelModel
758 return sendDeleteVideo(instance, options.transaction)
765 static async removeFiles (instance: VideoModel) {
766 const tasks: Promise<any>[] = []
768 logger.info('Removing files of video %s.', instance.url)
770 tasks.push(instance.removeThumbnail())
772 if (instance.isOwned()) {
773 if (!Array.isArray(instance.VideoFiles)) {
774 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
777 tasks.push(instance.removePreview())
779 // Remove physical files and torrents
780 instance.VideoFiles.forEach(file => {
781 tasks.push(instance.removeFile(file))
782 tasks.push(instance.removeTorrent(file))
786 // Do not wait video deletion because we could be in a transaction
789 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
796 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
799 static listLocal () {
806 return VideoModel.scope(ScopeNames.WITH_FILES).findAll(query)
809 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
810 function getRawQuery (select: string) {
811 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
812 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
813 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
814 'WHERE "Account"."actorId" = ' + actorId
815 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
816 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
817 'WHERE "VideoShare"."actorId" = ' + actorId
819 return `(${queryVideo}) UNION (${queryVideoShare})`
822 const rawQuery = getRawQuery('"Video"."id"')
823 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
829 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
832 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
834 [ Sequelize.Op.or ]: [
835 { privacy: VideoPrivacy.PUBLIC },
836 { privacy: VideoPrivacy.UNLISTED }
841 attributes: [ 'language' ],
842 model: VideoCaptionModel.unscoped(),
846 attributes: [ 'id', 'url' ],
847 model: VideoShareModel.unscoped(),
849 // We only want videos shared by this actor
851 [ Sequelize.Op.and ]: [
854 [ Sequelize.Op.not ]: null
864 attributes: [ 'id', 'url' ],
865 model: ActorModel.unscoped()
870 model: VideoChannelModel.unscoped(),
874 attributes: [ 'name' ],
875 model: AccountModel.unscoped(),
879 attributes: [ 'id', 'url', 'followersUrl' ],
880 model: ActorModel.unscoped(),
886 attributes: [ 'id', 'url', 'followersUrl' ],
887 model: ActorModel.unscoped(),
897 return Bluebird.all([
898 // FIXME: typing issue
899 VideoModel.findAll(query as any),
900 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
901 ]).then(([ rows, totals ]) => {
902 // totals: totalVideos + totalVideoShares
904 let totalVideoShares = 0
905 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
906 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
908 const total = totalVideos + totalVideoShares
916 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
917 const query: IFindOptions<VideoModel> = {
920 order: getVideoSort(sort),
923 model: VideoChannelModel,
936 model: ScheduleVideoUpdateModel,
940 model: VideoBlacklistModel,
946 if (withFiles === true) {
948 model: VideoFileModel.unscoped(),
953 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
961 static async listForApi (options: {
966 includeLocalVideos: boolean,
968 categoryOneOf?: number[],
969 licenceOneOf?: number[],
970 languageOneOf?: string[],
971 tagsOneOf?: string[],
972 tagsAllOf?: string[],
973 filter?: VideoFilter,
975 videoChannelId?: number,
977 trendingDays?: number,
979 }, countVideos = true) {
980 if (options.filter && options.filter === 'all-local' && !options.userId) {
981 throw new Error('Try to filter all-local but no userId is provided')
984 const query: IFindOptions<VideoModel> = {
985 offset: options.start,
986 limit: options.count,
987 order: getVideoSort(options.sort)
990 let trendingDays: number
991 if (options.sort.endsWith('trending')) {
992 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
994 query.group = 'VideoModel.id'
997 // actorId === null has a meaning, so just check undefined
998 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
1000 const queryOptions = {
1003 categoryOneOf: options.categoryOneOf,
1004 licenceOneOf: options.licenceOneOf,
1005 languageOneOf: options.languageOneOf,
1006 tagsOneOf: options.tagsOneOf,
1007 tagsAllOf: options.tagsAllOf,
1008 filter: options.filter,
1009 withFiles: options.withFiles,
1010 accountId: options.accountId,
1011 videoChannelId: options.videoChannelId,
1012 includeLocalVideos: options.includeLocalVideos,
1013 userId: options.userId,
1017 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1020 static async searchAndPopulateAccountAndServer (options: {
1021 includeLocalVideos: boolean
1026 startDate?: string // ISO 8601
1027 endDate?: string // ISO 8601
1029 categoryOneOf?: number[]
1030 licenceOneOf?: number[]
1031 languageOneOf?: string[]
1032 tagsOneOf?: string[]
1033 tagsAllOf?: string[]
1034 durationMin?: number // seconds
1035 durationMax?: number // seconds
1037 filter?: VideoFilter
1041 if (options.startDate || options.endDate) {
1042 const publishedAtRange = {}
1044 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1045 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1047 whereAnd.push({ publishedAt: publishedAtRange })
1050 if (options.durationMin || options.durationMax) {
1051 const durationRange = {}
1053 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1054 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1056 whereAnd.push({ duration: durationRange })
1059 const attributesInclude = []
1060 const escapedSearch = VideoModel.sequelize.escape(options.search)
1061 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1062 if (options.search) {
1066 [ Sequelize.Op.in ]: Sequelize.literal(
1068 'SELECT "video"."id" FROM "video" ' +
1070 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1071 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1073 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1074 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1075 'WHERE "tag"."name" = ' + escapedSearch +
1082 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1085 // Cannot search on similarity if we don't have a search
1086 if (!options.search) {
1087 attributesInclude.push(
1088 Sequelize.literal('0 as similarity')
1092 const query: IFindOptions<VideoModel> = {
1094 include: attributesInclude
1096 offset: options.start,
1097 limit: options.count,
1098 order: getVideoSort(options.sort),
1100 [ Sequelize.Op.and ]: whereAnd
1104 const serverActor = await getServerActor()
1105 const queryOptions = {
1106 actorId: serverActor.id,
1107 includeLocalVideos: options.includeLocalVideos,
1109 categoryOneOf: options.categoryOneOf,
1110 licenceOneOf: options.licenceOneOf,
1111 languageOneOf: options.languageOneOf,
1112 tagsOneOf: options.tagsOneOf,
1113 tagsAllOf: options.tagsAllOf,
1114 userId: options.userId,
1115 filter: options.filter
1118 return VideoModel.getAvailableForApi(query, queryOptions)
1121 static load (id: number | string, t?: Sequelize.Transaction) {
1122 const where = VideoModel.buildWhereIdOrUUID(id)
1128 return VideoModel.findOne(options)
1131 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1132 const where = VideoModel.buildWhereIdOrUUID(id)
1135 attributes: [ 'id' ],
1140 return VideoModel.findOne(options)
1143 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1144 return VideoModel.scope(ScopeNames.WITH_FILES)
1145 .findById(id, { transaction: t, logging })
1148 static loadByUUIDWithFile (uuid: string) {
1156 .scope([ ScopeNames.WITH_FILES ])
1160 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1161 const query: IFindOptions<VideoModel> = {
1168 return VideoModel.findOne(query)
1171 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1172 const query: IFindOptions<VideoModel> = {
1179 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1182 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1183 const where = VideoModel.buildWhereIdOrUUID(id)
1186 order: [ [ 'Tags', 'name', 'ASC' ] ],
1192 ScopeNames.WITH_TAGS,
1193 ScopeNames.WITH_BLACKLISTED,
1194 ScopeNames.WITH_FILES,
1195 ScopeNames.WITH_ACCOUNT_DETAILS,
1196 ScopeNames.WITH_SCHEDULED_UPDATE
1200 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1208 static async getStats () {
1209 const totalLocalVideos = await VideoModel.count({
1214 const totalVideos = await VideoModel.count()
1216 let totalLocalVideoViews = await VideoModel.sum('views', {
1221 // Sequelize could return null...
1222 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1226 totalLocalVideoViews,
1231 static incrementViews (id: number, views: number) {
1232 return VideoModel.increment('views', {
1240 // threshold corresponds to how many video the field should have to be returned
1241 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1242 const actorId = (await getServerActor()).id
1244 const scopeOptions = {
1246 includeLocalVideos: true
1249 const query: IFindOptions<VideoModel> = {
1250 attributes: [ field ],
1253 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1254 [ Sequelize.Op.gte ]: threshold
1255 }) as any, // FIXME: typings
1256 order: [ this.sequelize.random() ]
1259 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1261 .then(rows => rows.map(r => r[ field ]))
1264 static buildTrendingQuery (trendingDays: number) {
1268 model: VideoViewModel,
1272 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1278 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1279 if (filter && (filter === 'local' || filter === 'all-local')) {
1288 private static async getAvailableForApi (
1289 query: IFindOptions<VideoModel>,
1290 options: AvailableForListIDsOptions & { userId?: number},
1295 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1299 // Remove trending sort on count, because it uses a group by
1300 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1301 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1302 const countScope = {
1304 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1308 const [ count, rowsId ] = await Promise.all([
1309 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve(undefined),
1310 VideoModel.scope(idsScope).findAll(query)
1312 const ids = rowsId.map(r => r.id)
1314 if (ids.length === 0) return { data: [], total: count }
1317 const apiScope: any[] = [
1319 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1323 if (options.userId) {
1324 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.userId ] })
1327 const secondQuery = {
1330 attributes: query.attributes,
1331 order: [ // Keep original order
1333 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1337 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1345 static getCategoryLabel (id: number) {
1346 return VIDEO_CATEGORIES[ id ] || 'Misc'
1349 static getLicenceLabel (id: number) {
1350 return VIDEO_LICENCES[ id ] || 'Unknown'
1353 static getLanguageLabel (id: string) {
1354 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1357 static getPrivacyLabel (id: number) {
1358 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1361 static getStateLabel (id: number) {
1362 return VIDEO_STATES[ id ] || 'Unknown'
1365 static buildWhereIdOrUUID (id: number | string) {
1366 return validator.isInt('' + id) ? { id } : { uuid: id }
1369 getOriginalFile () {
1370 if (Array.isArray(this.VideoFiles) === false) return undefined
1372 // The original file is the file that have the higher resolution
1373 return maxBy(this.VideoFiles, file => file.resolution)
1376 getVideoFilename (videoFile: VideoFileModel) {
1377 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1380 getThumbnailName () {
1381 // We always have a copy of the thumbnail
1382 const extension = '.jpg'
1383 return this.uuid + extension
1387 const extension = '.jpg'
1388 return this.uuid + extension
1391 getTorrentFileName (videoFile: VideoFileModel) {
1392 const extension = '.torrent'
1393 return this.uuid + '-' + videoFile.resolution + extension
1397 return this.remote === false
1400 createPreview (videoFile: VideoFileModel) {
1401 return generateImageFromVideoFile(
1402 this.getVideoFilePath(videoFile),
1403 CONFIG.STORAGE.PREVIEWS_DIR,
1404 this.getPreviewName(),
1409 createThumbnail (videoFile: VideoFileModel) {
1410 return generateImageFromVideoFile(
1411 this.getVideoFilePath(videoFile),
1412 CONFIG.STORAGE.THUMBNAILS_DIR,
1413 this.getThumbnailName(),
1418 getTorrentFilePath (videoFile: VideoFileModel) {
1419 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1422 getVideoFilePath (videoFile: VideoFileModel) {
1423 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1426 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1428 // Keep the extname, it's used by the client to stream the file inside a web browser
1429 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1430 createdBy: 'PeerTube',
1432 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1433 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1435 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1438 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1440 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1441 logger.info('Creating torrent %s.', filePath)
1443 await writeFile(filePath, torrent)
1445 const parsedTorrent = parseTorrent(torrent)
1446 videoFile.infoHash = parsedTorrent.infoHash
1449 getEmbedStaticPath () {
1450 return '/videos/embed/' + this.uuid
1453 getThumbnailStaticPath () {
1454 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1457 getPreviewStaticPath () {
1458 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1461 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1462 return videoModelToFormattedJSON(this, options)
1465 toFormattedDetailsJSON (): VideoDetails {
1466 return videoModelToFormattedDetailsJSON(this)
1469 getFormattedVideoFilesJSON (): VideoFile[] {
1470 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1473 toActivityPubObject (): VideoTorrentObject {
1474 return videoModelToActivityPubObject(this)
1477 getTruncatedDescription () {
1478 if (!this.description) return null
1480 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1481 return peertubeTruncate(this.description, maxLength)
1484 getOriginalFileResolution () {
1485 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1487 return getVideoFileResolution(originalFilePath)
1490 getDescriptionAPIPath () {
1491 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1494 removeThumbnail () {
1495 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1496 return remove(thumbnailPath)
1497 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1501 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1502 return remove(previewPath)
1503 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1506 removeFile (videoFile: VideoFileModel) {
1507 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1508 return remove(filePath)
1509 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1512 removeTorrent (videoFile: VideoFileModel) {
1513 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1514 return remove(torrentPath)
1515 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1519 if (this.isOwned()) return false
1521 const now = Date.now()
1522 const createdAtTime = this.createdAt.getTime()
1523 const updatedAtTime = this.updatedAt.getTime()
1525 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1526 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1533 if (this.isOwned()) {
1534 baseUrlHttp = CONFIG.WEBSERVER.URL
1535 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1537 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1538 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1541 return { baseUrlHttp, baseUrlWs }
1544 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1545 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1546 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1547 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1549 const redundancies = videoFile.RedundancyVideos
1550 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1552 const magnetHash = {
1556 infoHash: videoFile.infoHash,
1560 return magnetUtil.encode(magnetHash)
1563 getThumbnailUrl (baseUrlHttp: string) {
1564 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1567 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1568 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1571 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1572 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1575 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1576 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1579 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1580 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)