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")'
239 // Always list public videos
240 privacy: VideoPrivacy.PUBLIC,
241 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
242 [ Sequelize.Op.or ]: [
244 state: VideoState.PUBLISHED
247 [ Sequelize.Op.and ]: {
248 state: VideoState.TO_TRANSCODE,
249 waitTranscoding: false
257 if (options.filter || options.accountId || options.videoChannelId) {
258 const videoChannelInclude: IIncludeOptions = {
260 model: VideoChannelModel.unscoped(),
264 if (options.videoChannelId) {
265 videoChannelInclude.where = {
266 id: options.videoChannelId
270 if (options.filter || options.accountId) {
271 const accountInclude: IIncludeOptions = {
273 model: AccountModel.unscoped(),
277 if (options.filter) {
278 accountInclude.include = [
281 model: ActorModel.unscoped(),
283 where: VideoModel.buildActorWhereWithFilter(options.filter)
288 if (options.accountId) {
289 accountInclude.where = { id: options.accountId }
292 videoChannelInclude.include = [ accountInclude ]
295 query.include.push(videoChannelInclude)
298 if (options.actorId) {
299 let localVideosReq = ''
300 if (options.includeLocalVideos === true) {
301 localVideosReq = ' UNION ALL ' +
302 'SELECT "video"."id" AS "id" FROM "video" ' +
303 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
304 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
305 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
306 'WHERE "actor"."serverId" IS NULL'
309 // Force actorId to be a number to avoid SQL injections
310 const actorIdNumber = parseInt(options.actorId.toString(), 10)
311 query.where[ 'id' ][ Sequelize.Op.and ].push({
312 [ Sequelize.Op.in ]: Sequelize.literal(
314 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
315 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
316 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
318 'SELECT "video"."id" AS "id" FROM "video" ' +
319 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
320 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
321 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
322 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
323 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
330 if (options.withFiles === true) {
331 query.where[ 'id' ][ Sequelize.Op.and ].push({
332 [ Sequelize.Op.in ]: Sequelize.literal(
333 '(SELECT "videoId" FROM "videoFile")'
338 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
339 if (options.tagsAllOf || options.tagsOneOf) {
340 const createTagsIn = (tags: string[]) => {
341 return tags.map(t => VideoModel.sequelize.escape(t))
345 if (options.tagsOneOf) {
346 query.where[ 'id' ][ Sequelize.Op.and ].push({
347 [ Sequelize.Op.in ]: Sequelize.literal(
349 'SELECT "videoId" FROM "videoTag" ' +
350 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
351 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
357 if (options.tagsAllOf) {
358 query.where[ 'id' ][ Sequelize.Op.and ].push({
359 [ Sequelize.Op.in ]: Sequelize.literal(
361 'SELECT "videoId" FROM "videoTag" ' +
362 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
363 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
364 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
371 if (options.nsfw === true || options.nsfw === false) {
372 query.where[ 'nsfw' ] = options.nsfw
375 if (options.categoryOneOf) {
376 query.where[ 'category' ] = {
377 [ Sequelize.Op.or ]: options.categoryOneOf
381 if (options.licenceOneOf) {
382 query.where[ 'licence' ] = {
383 [ Sequelize.Op.or ]: options.licenceOneOf
387 if (options.languageOneOf) {
388 query.where[ 'language' ] = {
389 [ Sequelize.Op.or ]: options.languageOneOf
393 if (options.trendingDays) {
394 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
396 query.subQuery = false
401 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
404 model: () => VideoChannelModel.unscoped(),
409 exclude: [ 'privateKey', 'publicKey' ]
411 model: () => ActorModel.unscoped(),
415 attributes: [ 'host' ],
416 model: () => ServerModel.unscoped(),
420 model: () => AvatarModel.unscoped(),
426 model: () => AccountModel.unscoped(),
430 model: () => ActorModel.unscoped(),
432 exclude: [ 'privateKey', 'publicKey' ]
437 attributes: [ 'host' ],
438 model: () => ServerModel.unscoped(),
442 model: () => AvatarModel.unscoped(),
453 [ ScopeNames.WITH_TAGS ]: {
454 include: [ () => TagModel ]
456 [ ScopeNames.WITH_BLACKLISTED ]: {
459 attributes: [ 'id', 'reason' ],
460 model: () => VideoBlacklistModel,
465 [ ScopeNames.WITH_FILES ]: {
468 model: () => VideoFileModel.unscoped(),
470 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
474 attributes: [ 'fileUrl' ],
475 model: () => VideoRedundancyModel.unscoped(),
482 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
485 model: () => ScheduleVideoUpdateModel.unscoped(),
490 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
494 attributes: [ 'currentTime' ],
495 model: UserVideoHistoryModel.unscoped(),
509 export class VideoModel extends Model<VideoModel> {
512 @Default(DataType.UUIDV4)
514 @Column(DataType.UUID)
518 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
524 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
530 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
536 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
537 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
541 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
546 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
552 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
553 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
558 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
559 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
563 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
593 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
594 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
599 commentsEnabled: boolean
603 downloadEnabled: boolean
607 waitTranscoding: boolean
611 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
622 @Default(Sequelize.NOW)
626 @ForeignKey(() => VideoChannelModel)
630 @BelongsTo(() => VideoChannelModel, {
636 VideoChannel: VideoChannelModel
638 @BelongsToMany(() => TagModel, {
639 foreignKey: 'videoId',
640 through: () => VideoTagModel,
645 @HasMany(() => VideoAbuseModel, {
652 VideoAbuses: VideoAbuseModel[]
654 @HasMany(() => VideoFileModel, {
662 VideoFiles: VideoFileModel[]
664 @HasMany(() => VideoShareModel, {
671 VideoShares: VideoShareModel[]
673 @HasMany(() => AccountVideoRateModel, {
680 AccountVideoRates: AccountVideoRateModel[]
682 @HasMany(() => VideoCommentModel, {
690 VideoComments: VideoCommentModel[]
692 @HasMany(() => VideoViewModel, {
699 VideoViews: VideoViewModel[]
701 @HasMany(() => UserVideoHistoryModel, {
708 UserVideoHistories: UserVideoHistoryModel[]
710 @HasOne(() => ScheduleVideoUpdateModel, {
717 ScheduleVideoUpdate: ScheduleVideoUpdateModel
719 @HasOne(() => VideoBlacklistModel, {
726 VideoBlacklist: VideoBlacklistModel
728 @HasMany(() => VideoCaptionModel, {
735 [ 'separate' as any ]: true
737 VideoCaptions: VideoCaptionModel[]
740 static async sendDelete (instance: VideoModel, options) {
741 if (instance.isOwned()) {
742 if (!instance.VideoChannel) {
743 instance.VideoChannel = await instance.$get('VideoChannel', {
747 include: [ ActorModel ]
750 transaction: options.transaction
751 }) as VideoChannelModel
754 return sendDeleteVideo(instance, options.transaction)
761 static async removeFiles (instance: VideoModel) {
762 const tasks: Promise<any>[] = []
764 logger.info('Removing files of video %s.', instance.url)
766 tasks.push(instance.removeThumbnail())
768 if (instance.isOwned()) {
769 if (!Array.isArray(instance.VideoFiles)) {
770 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
773 tasks.push(instance.removePreview())
775 // Remove physical files and torrents
776 instance.VideoFiles.forEach(file => {
777 tasks.push(instance.removeFile(file))
778 tasks.push(instance.removeTorrent(file))
782 // Do not wait video deletion because we could be in a transaction
785 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
792 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
795 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
796 function getRawQuery (select: string) {
797 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
798 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
799 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
800 'WHERE "Account"."actorId" = ' + actorId
801 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
802 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
803 'WHERE "VideoShare"."actorId" = ' + actorId
805 return `(${queryVideo}) UNION (${queryVideoShare})`
808 const rawQuery = getRawQuery('"Video"."id"')
809 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
815 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
818 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
820 [ Sequelize.Op.or ]: [
821 { privacy: VideoPrivacy.PUBLIC },
822 { privacy: VideoPrivacy.UNLISTED }
827 attributes: [ 'language' ],
828 model: VideoCaptionModel.unscoped(),
832 attributes: [ 'id', 'url' ],
833 model: VideoShareModel.unscoped(),
835 // We only want videos shared by this actor
837 [ Sequelize.Op.and ]: [
840 [ Sequelize.Op.not ]: null
850 attributes: [ 'id', 'url' ],
851 model: ActorModel.unscoped()
856 model: VideoChannelModel.unscoped(),
860 attributes: [ 'name' ],
861 model: AccountModel.unscoped(),
865 attributes: [ 'id', 'url', 'followersUrl' ],
866 model: ActorModel.unscoped(),
872 attributes: [ 'id', 'url', 'followersUrl' ],
873 model: ActorModel.unscoped(),
883 return Bluebird.all([
884 // FIXME: typing issue
885 VideoModel.findAll(query as any),
886 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
887 ]).then(([ rows, totals ]) => {
888 // totals: totalVideos + totalVideoShares
890 let totalVideoShares = 0
891 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
892 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
894 const total = totalVideos + totalVideoShares
902 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
903 const query: IFindOptions<VideoModel> = {
906 order: getVideoSort(sort),
909 model: VideoChannelModel,
922 model: ScheduleVideoUpdateModel,
926 model: VideoBlacklistModel,
932 if (withFiles === true) {
934 model: VideoFileModel.unscoped(),
939 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
947 static async listForApi (options: {
952 includeLocalVideos: boolean,
954 categoryOneOf?: number[],
955 licenceOneOf?: number[],
956 languageOneOf?: string[],
957 tagsOneOf?: string[],
958 tagsAllOf?: string[],
959 filter?: VideoFilter,
961 videoChannelId?: number,
963 trendingDays?: number,
965 }, countVideos = true) {
966 const query: IFindOptions<VideoModel> = {
967 offset: options.start,
968 limit: options.count,
969 order: getVideoSort(options.sort)
972 let trendingDays: number
973 if (options.sort.endsWith('trending')) {
974 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
976 query.group = 'VideoModel.id'
979 // actorId === null has a meaning, so just check undefined
980 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
982 const queryOptions = {
985 categoryOneOf: options.categoryOneOf,
986 licenceOneOf: options.licenceOneOf,
987 languageOneOf: options.languageOneOf,
988 tagsOneOf: options.tagsOneOf,
989 tagsAllOf: options.tagsAllOf,
990 filter: options.filter,
991 withFiles: options.withFiles,
992 accountId: options.accountId,
993 videoChannelId: options.videoChannelId,
994 includeLocalVideos: options.includeLocalVideos,
995 userId: options.userId,
999 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1002 static async searchAndPopulateAccountAndServer (options: {
1003 includeLocalVideos: boolean
1008 startDate?: string // ISO 8601
1009 endDate?: string // ISO 8601
1011 categoryOneOf?: number[]
1012 licenceOneOf?: number[]
1013 languageOneOf?: string[]
1014 tagsOneOf?: string[]
1015 tagsAllOf?: string[]
1016 durationMin?: number // seconds
1017 durationMax?: number // seconds
1022 if (options.startDate || options.endDate) {
1023 const publishedAtRange = {}
1025 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1026 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1028 whereAnd.push({ publishedAt: publishedAtRange })
1031 if (options.durationMin || options.durationMax) {
1032 const durationRange = {}
1034 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1035 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1037 whereAnd.push({ duration: durationRange })
1040 const attributesInclude = []
1041 const escapedSearch = VideoModel.sequelize.escape(options.search)
1042 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1043 if (options.search) {
1047 [ Sequelize.Op.in ]: Sequelize.literal(
1049 'SELECT "video"."id" FROM "video" ' +
1051 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1052 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1054 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1055 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1056 'WHERE "tag"."name" = ' + escapedSearch +
1063 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1066 // Cannot search on similarity if we don't have a search
1067 if (!options.search) {
1068 attributesInclude.push(
1069 Sequelize.literal('0 as similarity')
1073 const query: IFindOptions<VideoModel> = {
1075 include: attributesInclude
1077 offset: options.start,
1078 limit: options.count,
1079 order: getVideoSort(options.sort),
1081 [ Sequelize.Op.and ]: whereAnd
1085 const serverActor = await getServerActor()
1086 const queryOptions = {
1087 actorId: serverActor.id,
1088 includeLocalVideos: options.includeLocalVideos,
1090 categoryOneOf: options.categoryOneOf,
1091 licenceOneOf: options.licenceOneOf,
1092 languageOneOf: options.languageOneOf,
1093 tagsOneOf: options.tagsOneOf,
1094 tagsAllOf: options.tagsAllOf,
1095 userId: options.userId
1098 return VideoModel.getAvailableForApi(query, queryOptions)
1101 static load (id: number | string, t?: Sequelize.Transaction) {
1102 const where = VideoModel.buildWhereIdOrUUID(id)
1108 return VideoModel.findOne(options)
1111 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1112 const where = VideoModel.buildWhereIdOrUUID(id)
1115 attributes: [ 'id' ],
1120 return VideoModel.findOne(options)
1123 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1124 return VideoModel.scope(ScopeNames.WITH_FILES)
1125 .findById(id, { transaction: t, logging })
1128 static loadByUUIDWithFile (uuid: string) {
1136 .scope([ ScopeNames.WITH_FILES ])
1140 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1141 const query: IFindOptions<VideoModel> = {
1148 return VideoModel.findOne(query)
1151 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1152 const query: IFindOptions<VideoModel> = {
1159 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1162 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1163 const where = VideoModel.buildWhereIdOrUUID(id)
1166 order: [ [ 'Tags', 'name', 'ASC' ] ],
1172 ScopeNames.WITH_TAGS,
1173 ScopeNames.WITH_BLACKLISTED,
1174 ScopeNames.WITH_FILES,
1175 ScopeNames.WITH_ACCOUNT_DETAILS,
1176 ScopeNames.WITH_SCHEDULED_UPDATE
1180 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1188 static async getStats () {
1189 const totalLocalVideos = await VideoModel.count({
1194 const totalVideos = await VideoModel.count()
1196 let totalLocalVideoViews = await VideoModel.sum('views', {
1201 // Sequelize could return null...
1202 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1206 totalLocalVideoViews,
1211 static incrementViews (id: number, views: number) {
1212 return VideoModel.increment('views', {
1220 // threshold corresponds to how many video the field should have to be returned
1221 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1222 const actorId = (await getServerActor()).id
1224 const scopeOptions = {
1226 includeLocalVideos: true
1229 const query: IFindOptions<VideoModel> = {
1230 attributes: [ field ],
1233 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1234 [ Sequelize.Op.gte ]: threshold
1235 }) as any, // FIXME: typings
1236 order: [ this.sequelize.random() ]
1239 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1241 .then(rows => rows.map(r => r[ field ]))
1244 static buildTrendingQuery (trendingDays: number) {
1248 model: VideoViewModel,
1252 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1258 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1259 if (filter && filter === 'local') {
1268 private static async getAvailableForApi (
1269 query: IFindOptions<VideoModel>,
1270 options: AvailableForListIDsOptions & { userId?: number},
1275 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1279 // Remove trending sort on count, because it uses a group by
1280 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1281 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1282 const countScope = {
1284 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1288 const [ count, rowsId ] = await Promise.all([
1289 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve(undefined),
1290 VideoModel.scope(idsScope).findAll(query)
1292 const ids = rowsId.map(r => r.id)
1294 if (ids.length === 0) return { data: [], total: count }
1297 const apiScope: any[] = [
1299 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1303 if (options.userId) {
1304 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.userId ] })
1307 const secondQuery = {
1310 attributes: query.attributes,
1311 order: [ // Keep original order
1313 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1317 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1325 static getCategoryLabel (id: number) {
1326 return VIDEO_CATEGORIES[ id ] || 'Misc'
1329 static getLicenceLabel (id: number) {
1330 return VIDEO_LICENCES[ id ] || 'Unknown'
1333 static getLanguageLabel (id: string) {
1334 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1337 static getPrivacyLabel (id: number) {
1338 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1341 static getStateLabel (id: number) {
1342 return VIDEO_STATES[ id ] || 'Unknown'
1345 static buildWhereIdOrUUID (id: number | string) {
1346 return validator.isInt('' + id) ? { id } : { uuid: id }
1349 getOriginalFile () {
1350 if (Array.isArray(this.VideoFiles) === false) return undefined
1352 // The original file is the file that have the higher resolution
1353 return maxBy(this.VideoFiles, file => file.resolution)
1356 getVideoFilename (videoFile: VideoFileModel) {
1357 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1360 getThumbnailName () {
1361 // We always have a copy of the thumbnail
1362 const extension = '.jpg'
1363 return this.uuid + extension
1367 const extension = '.jpg'
1368 return this.uuid + extension
1371 getTorrentFileName (videoFile: VideoFileModel) {
1372 const extension = '.torrent'
1373 return this.uuid + '-' + videoFile.resolution + extension
1377 return this.remote === false
1380 createPreview (videoFile: VideoFileModel) {
1381 return generateImageFromVideoFile(
1382 this.getVideoFilePath(videoFile),
1383 CONFIG.STORAGE.PREVIEWS_DIR,
1384 this.getPreviewName(),
1389 createThumbnail (videoFile: VideoFileModel) {
1390 return generateImageFromVideoFile(
1391 this.getVideoFilePath(videoFile),
1392 CONFIG.STORAGE.THUMBNAILS_DIR,
1393 this.getThumbnailName(),
1398 getTorrentFilePath (videoFile: VideoFileModel) {
1399 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1402 getVideoFilePath (videoFile: VideoFileModel) {
1403 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1406 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1408 // Keep the extname, it's used by the client to stream the file inside a web browser
1409 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1410 createdBy: 'PeerTube',
1412 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1413 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1415 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1418 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1420 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1421 logger.info('Creating torrent %s.', filePath)
1423 await writeFile(filePath, torrent)
1425 const parsedTorrent = parseTorrent(torrent)
1426 videoFile.infoHash = parsedTorrent.infoHash
1429 getEmbedStaticPath () {
1430 return '/videos/embed/' + this.uuid
1433 getThumbnailStaticPath () {
1434 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1437 getPreviewStaticPath () {
1438 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1441 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1442 return videoModelToFormattedJSON(this, options)
1445 toFormattedDetailsJSON (): VideoDetails {
1446 return videoModelToFormattedDetailsJSON(this)
1449 getFormattedVideoFilesJSON (): VideoFile[] {
1450 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1453 toActivityPubObject (): VideoTorrentObject {
1454 return videoModelToActivityPubObject(this)
1457 getTruncatedDescription () {
1458 if (!this.description) return null
1460 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1461 return peertubeTruncate(this.description, maxLength)
1464 getOriginalFileResolution () {
1465 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1467 return getVideoFileResolution(originalFilePath)
1470 getDescriptionAPIPath () {
1471 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1474 removeThumbnail () {
1475 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1476 return remove(thumbnailPath)
1477 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1481 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1482 return remove(previewPath)
1483 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1486 removeFile (videoFile: VideoFileModel) {
1487 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1488 return remove(filePath)
1489 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1492 removeTorrent (videoFile: VideoFileModel) {
1493 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1494 return remove(torrentPath)
1495 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1499 if (this.isOwned()) return false
1501 const now = Date.now()
1502 const createdAtTime = this.createdAt.getTime()
1503 const updatedAtTime = this.updatedAt.getTime()
1505 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1506 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1513 if (this.isOwned()) {
1514 baseUrlHttp = CONFIG.WEBSERVER.URL
1515 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1517 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1518 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1521 return { baseUrlHttp, baseUrlWs }
1524 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1525 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1526 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1527 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1529 const redundancies = videoFile.RedundancyVideos
1530 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1532 const magnetHash = {
1536 infoHash: videoFile.infoHash,
1540 return magnetUtil.encode(magnetHash)
1543 getThumbnailUrl (baseUrlHttp: string) {
1544 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1547 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1548 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1551 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1552 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1555 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1556 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1559 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1560 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)