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'
96 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
97 const indexes: Sequelize.DefineIndexesOptions[] = [
98 buildTrigramSearchIndex('video_name_trigram', 'name'),
100 { fields: [ 'createdAt' ] },
101 { fields: [ 'publishedAt' ] },
102 { fields: [ 'duration' ] },
103 { fields: [ 'category' ] },
104 { fields: [ 'licence' ] },
105 { fields: [ 'nsfw' ] },
106 { fields: [ 'language' ] },
107 { fields: [ 'waitTranscoding' ] },
108 { fields: [ 'state' ] },
109 { fields: [ 'remote' ] },
110 { fields: [ 'views' ] },
111 { fields: [ 'likes' ] },
112 { fields: [ 'channelId' ] },
123 export enum ScopeNames {
124 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
126 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
127 WITH_TAGS = 'WITH_TAGS',
128 WITH_FILES = 'WITH_FILES',
129 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
130 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
133 type ForAPIOptions = {
138 type AvailableForListIDsOptions = {
140 includeLocalVideos: boolean
142 categoryOneOf?: number[]
144 licenceOneOf?: number[]
145 languageOneOf?: string[]
150 videoChannelId?: number
151 trendingDays?: number
155 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
156 const accountInclude = {
157 attributes: [ 'id', 'name' ],
158 model: AccountModel.unscoped(),
162 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
163 model: ActorModel.unscoped(),
167 attributes: [ 'host' ],
168 model: ServerModel.unscoped(),
172 model: AvatarModel.unscoped(),
180 const videoChannelInclude = {
181 attributes: [ 'name', 'description', 'id' ],
182 model: VideoChannelModel.unscoped(),
186 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
187 model: ActorModel.unscoped(),
191 attributes: [ 'host' ],
192 model: ServerModel.unscoped(),
196 model: AvatarModel.unscoped(),
205 const query: IFindOptions<VideoModel> = {
208 [ Sequelize.Op.any ]: options.ids
211 include: [ videoChannelInclude ]
214 if (options.withFiles === true) {
216 model: VideoFileModel.unscoped(),
223 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
224 const query: IFindOptions<VideoModel> = {
226 attributes: [ 'id' ],
229 [ Sequelize.Op.and ]: [
231 [ Sequelize.Op.notIn ]: Sequelize.literal(
232 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
237 // Always list public videos
238 privacy: VideoPrivacy.PUBLIC,
239 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
240 [ Sequelize.Op.or ]: [
242 state: VideoState.PUBLISHED
245 [ Sequelize.Op.and ]: {
246 state: VideoState.TO_TRANSCODE,
247 waitTranscoding: false
255 if (options.filter || options.accountId || options.videoChannelId) {
256 const videoChannelInclude: IIncludeOptions = {
258 model: VideoChannelModel.unscoped(),
262 if (options.videoChannelId) {
263 videoChannelInclude.where = {
264 id: options.videoChannelId
268 if (options.filter || options.accountId) {
269 const accountInclude: IIncludeOptions = {
271 model: AccountModel.unscoped(),
275 if (options.filter) {
276 accountInclude.include = [
279 model: ActorModel.unscoped(),
281 where: VideoModel.buildActorWhereWithFilter(options.filter)
286 if (options.accountId) {
287 accountInclude.where = { id: options.accountId }
290 videoChannelInclude.include = [ accountInclude ]
293 query.include.push(videoChannelInclude)
296 if (options.actorId) {
297 let localVideosReq = ''
298 if (options.includeLocalVideos === true) {
299 localVideosReq = ' UNION ALL ' +
300 'SELECT "video"."id" AS "id" FROM "video" ' +
301 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
302 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
303 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
304 'WHERE "actor"."serverId" IS NULL'
307 // Force actorId to be a number to avoid SQL injections
308 const actorIdNumber = parseInt(options.actorId.toString(), 10)
309 query.where[ 'id' ][ Sequelize.Op.and ].push({
310 [ Sequelize.Op.in ]: Sequelize.literal(
312 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
313 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
314 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
316 'SELECT "video"."id" AS "id" FROM "video" ' +
317 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
318 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
319 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
320 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
321 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
328 if (options.withFiles === true) {
329 query.where[ 'id' ][ Sequelize.Op.and ].push({
330 [ Sequelize.Op.in ]: Sequelize.literal(
331 '(SELECT "videoId" FROM "videoFile")'
336 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
337 if (options.tagsAllOf || options.tagsOneOf) {
338 const createTagsIn = (tags: string[]) => {
339 return tags.map(t => VideoModel.sequelize.escape(t))
343 if (options.tagsOneOf) {
344 query.where[ 'id' ][ Sequelize.Op.and ].push({
345 [ Sequelize.Op.in ]: Sequelize.literal(
347 'SELECT "videoId" FROM "videoTag" ' +
348 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
349 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
355 if (options.tagsAllOf) {
356 query.where[ 'id' ][ Sequelize.Op.and ].push({
357 [ Sequelize.Op.in ]: Sequelize.literal(
359 'SELECT "videoId" FROM "videoTag" ' +
360 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
361 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
362 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
369 if (options.nsfw === true || options.nsfw === false) {
370 query.where[ 'nsfw' ] = options.nsfw
373 if (options.categoryOneOf) {
374 query.where[ 'category' ] = {
375 [ Sequelize.Op.or ]: options.categoryOneOf
379 if (options.licenceOneOf) {
380 query.where[ 'licence' ] = {
381 [ Sequelize.Op.or ]: options.licenceOneOf
385 if (options.languageOneOf) {
386 query.where[ 'language' ] = {
387 [ Sequelize.Op.or ]: options.languageOneOf
391 if (options.trendingDays) {
392 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
394 query.subQuery = false
399 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
402 model: () => VideoChannelModel.unscoped(),
407 exclude: [ 'privateKey', 'publicKey' ]
409 model: () => ActorModel.unscoped(),
413 attributes: [ 'host' ],
414 model: () => ServerModel.unscoped(),
418 model: () => AvatarModel.unscoped(),
424 model: () => AccountModel.unscoped(),
428 model: () => ActorModel.unscoped(),
430 exclude: [ 'privateKey', 'publicKey' ]
435 attributes: [ 'host' ],
436 model: () => ServerModel.unscoped(),
440 model: () => AvatarModel.unscoped(),
451 [ ScopeNames.WITH_TAGS ]: {
452 include: [ () => TagModel ]
454 [ ScopeNames.WITH_BLACKLISTED ]: {
457 attributes: [ 'id', 'reason' ],
458 model: () => VideoBlacklistModel,
463 [ ScopeNames.WITH_FILES ]: {
466 model: () => VideoFileModel.unscoped(),
470 attributes: [ 'fileUrl' ],
471 model: () => VideoRedundancyModel.unscoped(),
478 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
481 model: () => ScheduleVideoUpdateModel.unscoped(),
491 export class VideoModel extends Model<VideoModel> {
494 @Default(DataType.UUIDV4)
496 @Column(DataType.UUID)
500 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
506 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
512 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
518 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
519 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
523 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
528 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
534 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
535 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
540 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
541 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
545 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
575 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
576 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
581 commentsEnabled: boolean
585 waitTranscoding: boolean
589 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
600 @Default(Sequelize.NOW)
604 @ForeignKey(() => VideoChannelModel)
608 @BelongsTo(() => VideoChannelModel, {
614 VideoChannel: VideoChannelModel
616 @BelongsToMany(() => TagModel, {
617 foreignKey: 'videoId',
618 through: () => VideoTagModel,
623 @HasMany(() => VideoAbuseModel, {
630 VideoAbuses: VideoAbuseModel[]
632 @HasMany(() => VideoFileModel, {
640 VideoFiles: VideoFileModel[]
642 @HasMany(() => VideoShareModel, {
649 VideoShares: VideoShareModel[]
651 @HasMany(() => AccountVideoRateModel, {
658 AccountVideoRates: AccountVideoRateModel[]
660 @HasMany(() => VideoCommentModel, {
668 VideoComments: VideoCommentModel[]
670 @HasMany(() => VideoViewModel, {
678 VideoViews: VideoViewModel[]
680 @HasOne(() => ScheduleVideoUpdateModel, {
687 ScheduleVideoUpdate: ScheduleVideoUpdateModel
689 @HasOne(() => VideoBlacklistModel, {
696 VideoBlacklist: VideoBlacklistModel
698 @HasMany(() => VideoCaptionModel, {
705 [ 'separate' as any ]: true
707 VideoCaptions: VideoCaptionModel[]
710 static async sendDelete (instance: VideoModel, options) {
711 if (instance.isOwned()) {
712 if (!instance.VideoChannel) {
713 instance.VideoChannel = await instance.$get('VideoChannel', {
717 include: [ ActorModel ]
720 transaction: options.transaction
721 }) as VideoChannelModel
724 return sendDeleteVideo(instance, options.transaction)
731 static async removeFiles (instance: VideoModel) {
732 const tasks: Promise<any>[] = []
734 logger.info('Removing files of video %s.', instance.url)
736 tasks.push(instance.removeThumbnail())
738 if (instance.isOwned()) {
739 if (!Array.isArray(instance.VideoFiles)) {
740 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
743 tasks.push(instance.removePreview())
745 // Remove physical files and torrents
746 instance.VideoFiles.forEach(file => {
747 tasks.push(instance.removeFile(file))
748 tasks.push(instance.removeTorrent(file))
752 // Do not wait video deletion because we could be in a transaction
755 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
762 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
765 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
766 function getRawQuery (select: string) {
767 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
768 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
769 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
770 'WHERE "Account"."actorId" = ' + actorId
771 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
772 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
773 'WHERE "VideoShare"."actorId" = ' + actorId
775 return `(${queryVideo}) UNION (${queryVideoShare})`
778 const rawQuery = getRawQuery('"Video"."id"')
779 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
785 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
788 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
790 [ Sequelize.Op.or ]: [
791 { privacy: VideoPrivacy.PUBLIC },
792 { privacy: VideoPrivacy.UNLISTED }
797 attributes: [ 'language' ],
798 model: VideoCaptionModel.unscoped(),
802 attributes: [ 'id', 'url' ],
803 model: VideoShareModel.unscoped(),
805 // We only want videos shared by this actor
807 [ Sequelize.Op.and ]: [
810 [ Sequelize.Op.not ]: null
820 attributes: [ 'id', 'url' ],
821 model: ActorModel.unscoped()
826 model: VideoChannelModel.unscoped(),
830 attributes: [ 'name' ],
831 model: AccountModel.unscoped(),
835 attributes: [ 'id', 'url', 'followersUrl' ],
836 model: ActorModel.unscoped(),
842 attributes: [ 'id', 'url', 'followersUrl' ],
843 model: ActorModel.unscoped(),
853 return Bluebird.all([
854 // FIXME: typing issue
855 VideoModel.findAll(query as any),
856 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
857 ]).then(([ rows, totals ]) => {
858 // totals: totalVideos + totalVideoShares
860 let totalVideoShares = 0
861 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
862 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
864 const total = totalVideos + totalVideoShares
872 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
873 const query: IFindOptions<VideoModel> = {
876 order: getVideoSort(sort),
879 model: VideoChannelModel,
892 model: ScheduleVideoUpdateModel,
896 model: VideoBlacklistModel,
902 if (withFiles === true) {
904 model: VideoFileModel.unscoped(),
909 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
917 static async listForApi (options: {
922 includeLocalVideos: boolean,
924 categoryOneOf?: number[],
925 licenceOneOf?: number[],
926 languageOneOf?: string[],
927 tagsOneOf?: string[],
928 tagsAllOf?: string[],
929 filter?: VideoFilter,
931 videoChannelId?: number,
933 trendingDays?: number
934 }, countVideos = true) {
935 const query: IFindOptions<VideoModel> = {
936 offset: options.start,
937 limit: options.count,
938 order: getVideoSort(options.sort)
941 let trendingDays: number
942 if (options.sort.endsWith('trending')) {
943 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
945 query.group = 'VideoModel.id'
948 // actorId === null has a meaning, so just check undefined
949 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
951 const queryOptions = {
954 categoryOneOf: options.categoryOneOf,
955 licenceOneOf: options.licenceOneOf,
956 languageOneOf: options.languageOneOf,
957 tagsOneOf: options.tagsOneOf,
958 tagsAllOf: options.tagsAllOf,
959 filter: options.filter,
960 withFiles: options.withFiles,
961 accountId: options.accountId,
962 videoChannelId: options.videoChannelId,
963 includeLocalVideos: options.includeLocalVideos,
967 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
970 static async searchAndPopulateAccountAndServer (options: {
971 includeLocalVideos: boolean
976 startDate?: string // ISO 8601
977 endDate?: string // ISO 8601
979 categoryOneOf?: number[]
980 licenceOneOf?: number[]
981 languageOneOf?: string[]
984 durationMin?: number // seconds
985 durationMax?: number // seconds
989 if (options.startDate || options.endDate) {
990 const publishedAtRange = {}
992 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
993 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
995 whereAnd.push({ publishedAt: publishedAtRange })
998 if (options.durationMin || options.durationMax) {
999 const durationRange = {}
1001 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1002 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1004 whereAnd.push({ duration: durationRange })
1007 const attributesInclude = []
1008 const escapedSearch = VideoModel.sequelize.escape(options.search)
1009 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1010 if (options.search) {
1014 [ Sequelize.Op.in ]: Sequelize.literal(
1016 'SELECT "video"."id" FROM "video" ' +
1018 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1019 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1021 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1022 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1023 'WHERE "tag"."name" = ' + escapedSearch +
1030 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1033 // Cannot search on similarity if we don't have a search
1034 if (!options.search) {
1035 attributesInclude.push(
1036 Sequelize.literal('0 as similarity')
1040 const query: IFindOptions<VideoModel> = {
1042 include: attributesInclude
1044 offset: options.start,
1045 limit: options.count,
1046 order: getVideoSort(options.sort),
1048 [ Sequelize.Op.and ]: whereAnd
1052 const serverActor = await getServerActor()
1053 const queryOptions = {
1054 actorId: serverActor.id,
1055 includeLocalVideos: options.includeLocalVideos,
1057 categoryOneOf: options.categoryOneOf,
1058 licenceOneOf: options.licenceOneOf,
1059 languageOneOf: options.languageOneOf,
1060 tagsOneOf: options.tagsOneOf,
1061 tagsAllOf: options.tagsAllOf
1064 return VideoModel.getAvailableForApi(query, queryOptions)
1067 static load (id: number | string, t?: Sequelize.Transaction) {
1068 const where = VideoModel.buildWhereIdOrUUID(id)
1074 return VideoModel.findOne(options)
1077 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1078 const where = VideoModel.buildWhereIdOrUUID(id)
1081 attributes: [ 'id' ],
1086 return VideoModel.findOne(options)
1089 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1090 return VideoModel.scope(ScopeNames.WITH_FILES)
1091 .findById(id, { transaction: t, logging })
1094 static loadByUUIDWithFile (uuid: string) {
1102 .scope([ ScopeNames.WITH_FILES ])
1106 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1107 const query: IFindOptions<VideoModel> = {
1114 return VideoModel.findOne(query)
1117 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1118 const query: IFindOptions<VideoModel> = {
1125 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1128 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction) {
1129 const where = VideoModel.buildWhereIdOrUUID(id)
1132 order: [ [ 'Tags', 'name', 'ASC' ] ],
1139 ScopeNames.WITH_TAGS,
1140 ScopeNames.WITH_BLACKLISTED,
1141 ScopeNames.WITH_FILES,
1142 ScopeNames.WITH_ACCOUNT_DETAILS,
1143 ScopeNames.WITH_SCHEDULED_UPDATE
1148 static async getStats () {
1149 const totalLocalVideos = await VideoModel.count({
1154 const totalVideos = await VideoModel.count()
1156 let totalLocalVideoViews = await VideoModel.sum('views', {
1161 // Sequelize could return null...
1162 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1166 totalLocalVideoViews,
1171 static incrementViews (id: number, views: number) {
1172 return VideoModel.increment('views', {
1180 // threshold corresponds to how many video the field should have to be returned
1181 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1182 const actorId = (await getServerActor()).id
1184 const scopeOptions = {
1186 includeLocalVideos: true
1189 const query: IFindOptions<VideoModel> = {
1190 attributes: [ field ],
1193 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1194 [ Sequelize.Op.gte ]: threshold
1195 }) as any, // FIXME: typings
1196 order: [ this.sequelize.random() ]
1199 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1201 .then(rows => rows.map(r => r[ field ]))
1204 static buildTrendingQuery (trendingDays: number) {
1208 model: VideoViewModel,
1212 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1218 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1219 if (filter && filter === 'local') {
1228 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions, countVideos = true) {
1231 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1235 // Remove trending sort on count, because it uses a group by
1236 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1237 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1238 const countScope = {
1240 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1244 const [ count, rowsId ] = await Promise.all([
1245 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve(undefined),
1246 VideoModel.scope(idsScope).findAll(query)
1248 const ids = rowsId.map(r => r.id)
1250 if (ids.length === 0) return { data: [], total: count }
1253 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1256 const secondQuery = {
1259 attributes: query.attributes,
1260 order: [ // Keep original order
1262 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1266 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1274 static getCategoryLabel (id: number) {
1275 return VIDEO_CATEGORIES[ id ] || 'Misc'
1278 static getLicenceLabel (id: number) {
1279 return VIDEO_LICENCES[ id ] || 'Unknown'
1282 static getLanguageLabel (id: string) {
1283 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1286 static getPrivacyLabel (id: number) {
1287 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1290 static getStateLabel (id: number) {
1291 return VIDEO_STATES[ id ] || 'Unknown'
1294 static buildWhereIdOrUUID (id: number | string) {
1295 return validator.isInt('' + id) ? { id } : { uuid: id }
1298 getOriginalFile () {
1299 if (Array.isArray(this.VideoFiles) === false) return undefined
1301 // The original file is the file that have the higher resolution
1302 return maxBy(this.VideoFiles, file => file.resolution)
1305 getVideoFilename (videoFile: VideoFileModel) {
1306 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1309 getThumbnailName () {
1310 // We always have a copy of the thumbnail
1311 const extension = '.jpg'
1312 return this.uuid + extension
1316 const extension = '.jpg'
1317 return this.uuid + extension
1320 getTorrentFileName (videoFile: VideoFileModel) {
1321 const extension = '.torrent'
1322 return this.uuid + '-' + videoFile.resolution + extension
1326 return this.remote === false
1329 createPreview (videoFile: VideoFileModel) {
1330 return generateImageFromVideoFile(
1331 this.getVideoFilePath(videoFile),
1332 CONFIG.STORAGE.PREVIEWS_DIR,
1333 this.getPreviewName(),
1338 createThumbnail (videoFile: VideoFileModel) {
1339 return generateImageFromVideoFile(
1340 this.getVideoFilePath(videoFile),
1341 CONFIG.STORAGE.THUMBNAILS_DIR,
1342 this.getThumbnailName(),
1347 getTorrentFilePath (videoFile: VideoFileModel) {
1348 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1351 getVideoFilePath (videoFile: VideoFileModel) {
1352 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1355 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1357 // Keep the extname, it's used by the client to stream the file inside a web browser
1358 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1359 createdBy: 'PeerTube',
1361 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1362 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1364 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1367 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1369 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1370 logger.info('Creating torrent %s.', filePath)
1372 await writeFile(filePath, torrent)
1374 const parsedTorrent = parseTorrent(torrent)
1375 videoFile.infoHash = parsedTorrent.infoHash
1378 getEmbedStaticPath () {
1379 return '/videos/embed/' + this.uuid
1382 getThumbnailStaticPath () {
1383 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1386 getPreviewStaticPath () {
1387 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1390 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1391 return videoModelToFormattedJSON(this, options)
1394 toFormattedDetailsJSON (): VideoDetails {
1395 return videoModelToFormattedDetailsJSON(this)
1398 getFormattedVideoFilesJSON (): VideoFile[] {
1399 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1402 toActivityPubObject (): VideoTorrentObject {
1403 return videoModelToActivityPubObject(this)
1406 getTruncatedDescription () {
1407 if (!this.description) return null
1409 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1410 return peertubeTruncate(this.description, maxLength)
1413 getOriginalFileResolution () {
1414 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1416 return getVideoFileResolution(originalFilePath)
1419 getDescriptionAPIPath () {
1420 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1423 removeThumbnail () {
1424 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1425 return remove(thumbnailPath)
1426 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1430 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1431 return remove(previewPath)
1432 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1435 removeFile (videoFile: VideoFileModel) {
1436 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1437 return remove(filePath)
1438 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1441 removeTorrent (videoFile: VideoFileModel) {
1442 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1443 return remove(torrentPath)
1444 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1448 if (this.isOwned()) return false
1450 const now = Date.now()
1451 const createdAtTime = this.createdAt.getTime()
1452 const updatedAtTime = this.updatedAt.getTime()
1454 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1455 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1462 if (this.isOwned()) {
1463 baseUrlHttp = CONFIG.WEBSERVER.URL
1464 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1466 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1467 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1470 return { baseUrlHttp, baseUrlWs }
1473 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1474 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1475 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1476 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1478 const redundancies = videoFile.RedundancyVideos
1479 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1481 const magnetHash = {
1485 infoHash: videoFile.infoHash,
1489 return magnetUtil.encode(magnetHash)
1492 getThumbnailUrl (baseUrlHttp: string) {
1493 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1496 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1497 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1500 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1501 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1504 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1505 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1508 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1509 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)