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'
98 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99 const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
125 export enum ScopeNames {
126 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
133 WITH_USER_HISTORY = 'WITH_USER_HISTORY'
136 type ForAPIOptions = {
141 type AvailableForListIDsOptions = {
143 includeLocalVideos: boolean
145 categoryOneOf?: number[]
147 licenceOneOf?: number[]
148 languageOneOf?: string[]
153 videoChannelId?: number
154 trendingDays?: number
158 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
159 const accountInclude = {
160 attributes: [ 'id', 'name' ],
161 model: AccountModel.unscoped(),
165 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
166 model: ActorModel.unscoped(),
170 attributes: [ 'host' ],
171 model: ServerModel.unscoped(),
175 model: AvatarModel.unscoped(),
183 const videoChannelInclude = {
184 attributes: [ 'name', 'description', 'id' ],
185 model: VideoChannelModel.unscoped(),
189 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
190 model: ActorModel.unscoped(),
194 attributes: [ 'host' ],
195 model: ServerModel.unscoped(),
199 model: AvatarModel.unscoped(),
208 const query: IFindOptions<VideoModel> = {
211 [ Sequelize.Op.any ]: options.ids
214 include: [ videoChannelInclude ]
217 if (options.withFiles === true) {
219 model: VideoFileModel.unscoped(),
226 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
227 const query: IFindOptions<VideoModel> = {
229 attributes: [ 'id' ],
232 [ Sequelize.Op.and ]: [
234 [ Sequelize.Op.notIn ]: Sequelize.literal(
235 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
240 // Always list public videos
241 privacy: VideoPrivacy.PUBLIC,
242 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
243 [ Sequelize.Op.or ]: [
245 state: VideoState.PUBLISHED
248 [ Sequelize.Op.and ]: {
249 state: VideoState.TO_TRANSCODE,
250 waitTranscoding: false
258 if (options.filter || options.accountId || options.videoChannelId) {
259 const videoChannelInclude: IIncludeOptions = {
261 model: VideoChannelModel.unscoped(),
265 if (options.videoChannelId) {
266 videoChannelInclude.where = {
267 id: options.videoChannelId
271 if (options.filter || options.accountId) {
272 const accountInclude: IIncludeOptions = {
274 model: AccountModel.unscoped(),
278 if (options.filter) {
279 accountInclude.include = [
282 model: ActorModel.unscoped(),
284 where: VideoModel.buildActorWhereWithFilter(options.filter)
289 if (options.accountId) {
290 accountInclude.where = { id: options.accountId }
293 videoChannelInclude.include = [ accountInclude ]
296 query.include.push(videoChannelInclude)
299 if (options.actorId) {
300 let localVideosReq = ''
301 if (options.includeLocalVideos === true) {
302 localVideosReq = ' UNION ALL ' +
303 'SELECT "video"."id" AS "id" FROM "video" ' +
304 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
305 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
306 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
307 'WHERE "actor"."serverId" IS NULL'
310 // Force actorId to be a number to avoid SQL injections
311 const actorIdNumber = parseInt(options.actorId.toString(), 10)
312 query.where[ 'id' ][ Sequelize.Op.and ].push({
313 [ Sequelize.Op.in ]: Sequelize.literal(
315 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
316 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
317 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
319 'SELECT "video"."id" AS "id" FROM "video" ' +
320 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
321 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
322 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
323 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
324 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
331 if (options.withFiles === true) {
332 query.where[ 'id' ][ Sequelize.Op.and ].push({
333 [ Sequelize.Op.in ]: Sequelize.literal(
334 '(SELECT "videoId" FROM "videoFile")'
339 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
340 if (options.tagsAllOf || options.tagsOneOf) {
341 const createTagsIn = (tags: string[]) => {
342 return tags.map(t => VideoModel.sequelize.escape(t))
346 if (options.tagsOneOf) {
347 query.where[ 'id' ][ Sequelize.Op.and ].push({
348 [ Sequelize.Op.in ]: Sequelize.literal(
350 'SELECT "videoId" FROM "videoTag" ' +
351 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
352 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
358 if (options.tagsAllOf) {
359 query.where[ 'id' ][ Sequelize.Op.and ].push({
360 [ Sequelize.Op.in ]: Sequelize.literal(
362 'SELECT "videoId" FROM "videoTag" ' +
363 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
364 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
365 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
372 if (options.nsfw === true || options.nsfw === false) {
373 query.where[ 'nsfw' ] = options.nsfw
376 if (options.categoryOneOf) {
377 query.where[ 'category' ] = {
378 [ Sequelize.Op.or ]: options.categoryOneOf
382 if (options.licenceOneOf) {
383 query.where[ 'licence' ] = {
384 [ Sequelize.Op.or ]: options.licenceOneOf
388 if (options.languageOneOf) {
389 query.where[ 'language' ] = {
390 [ Sequelize.Op.or ]: options.languageOneOf
394 if (options.trendingDays) {
395 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
397 query.subQuery = false
402 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
405 model: () => VideoChannelModel.unscoped(),
410 exclude: [ 'privateKey', 'publicKey' ]
412 model: () => ActorModel.unscoped(),
416 attributes: [ 'host' ],
417 model: () => ServerModel.unscoped(),
421 model: () => AvatarModel.unscoped(),
427 model: () => AccountModel.unscoped(),
431 model: () => ActorModel.unscoped(),
433 exclude: [ 'privateKey', 'publicKey' ]
438 attributes: [ 'host' ],
439 model: () => ServerModel.unscoped(),
443 model: () => AvatarModel.unscoped(),
454 [ ScopeNames.WITH_TAGS ]: {
455 include: [ () => TagModel ]
457 [ ScopeNames.WITH_BLACKLISTED ]: {
460 attributes: [ 'id', 'reason' ],
461 model: () => VideoBlacklistModel,
466 [ ScopeNames.WITH_FILES ]: {
469 model: () => VideoFileModel.unscoped(),
471 [ 'separate' as any ]: true, // We may have multiple files, having multiple redundancies so let's separate this join
475 attributes: [ 'fileUrl' ],
476 model: () => VideoRedundancyModel.unscoped(),
483 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
486 model: () => ScheduleVideoUpdateModel.unscoped(),
491 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
495 attributes: [ 'currentTime' ],
496 model: UserVideoHistoryModel.unscoped(),
510 export class VideoModel extends Model<VideoModel> {
513 @Default(DataType.UUIDV4)
515 @Column(DataType.UUID)
519 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
525 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
531 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
537 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
538 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
542 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
547 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
553 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
554 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
559 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
560 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
564 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
594 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
595 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
600 commentsEnabled: boolean
604 waitTranscoding: boolean
608 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
619 @Default(Sequelize.NOW)
623 @ForeignKey(() => VideoChannelModel)
627 @BelongsTo(() => VideoChannelModel, {
633 VideoChannel: VideoChannelModel
635 @BelongsToMany(() => TagModel, {
636 foreignKey: 'videoId',
637 through: () => VideoTagModel,
642 @HasMany(() => VideoAbuseModel, {
649 VideoAbuses: VideoAbuseModel[]
651 @HasMany(() => VideoFileModel, {
659 VideoFiles: VideoFileModel[]
661 @HasMany(() => VideoShareModel, {
668 VideoShares: VideoShareModel[]
670 @HasMany(() => AccountVideoRateModel, {
677 AccountVideoRates: AccountVideoRateModel[]
679 @HasMany(() => VideoCommentModel, {
687 VideoComments: VideoCommentModel[]
689 @HasMany(() => VideoViewModel, {
696 VideoViews: VideoViewModel[]
698 @HasMany(() => UserVideoHistoryModel, {
705 UserVideoHistories: UserVideoHistoryModel[]
707 @HasOne(() => ScheduleVideoUpdateModel, {
714 ScheduleVideoUpdate: ScheduleVideoUpdateModel
716 @HasOne(() => VideoBlacklistModel, {
723 VideoBlacklist: VideoBlacklistModel
725 @HasMany(() => VideoCaptionModel, {
732 [ 'separate' as any ]: true
734 VideoCaptions: VideoCaptionModel[]
737 static async sendDelete (instance: VideoModel, options) {
738 if (instance.isOwned()) {
739 if (!instance.VideoChannel) {
740 instance.VideoChannel = await instance.$get('VideoChannel', {
744 include: [ ActorModel ]
747 transaction: options.transaction
748 }) as VideoChannelModel
751 return sendDeleteVideo(instance, options.transaction)
758 static async removeFiles (instance: VideoModel) {
759 const tasks: Promise<any>[] = []
761 logger.info('Removing files of video %s.', instance.url)
763 tasks.push(instance.removeThumbnail())
765 if (instance.isOwned()) {
766 if (!Array.isArray(instance.VideoFiles)) {
767 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
770 tasks.push(instance.removePreview())
772 // Remove physical files and torrents
773 instance.VideoFiles.forEach(file => {
774 tasks.push(instance.removeFile(file))
775 tasks.push(instance.removeTorrent(file))
779 // Do not wait video deletion because we could be in a transaction
782 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
789 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
792 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
793 function getRawQuery (select: string) {
794 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
795 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
796 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
797 'WHERE "Account"."actorId" = ' + actorId
798 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
799 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
800 'WHERE "VideoShare"."actorId" = ' + actorId
802 return `(${queryVideo}) UNION (${queryVideoShare})`
805 const rawQuery = getRawQuery('"Video"."id"')
806 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
812 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
815 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
817 [ Sequelize.Op.or ]: [
818 { privacy: VideoPrivacy.PUBLIC },
819 { privacy: VideoPrivacy.UNLISTED }
824 attributes: [ 'language' ],
825 model: VideoCaptionModel.unscoped(),
829 attributes: [ 'id', 'url' ],
830 model: VideoShareModel.unscoped(),
832 // We only want videos shared by this actor
834 [ Sequelize.Op.and ]: [
837 [ Sequelize.Op.not ]: null
847 attributes: [ 'id', 'url' ],
848 model: ActorModel.unscoped()
853 model: VideoChannelModel.unscoped(),
857 attributes: [ 'name' ],
858 model: AccountModel.unscoped(),
862 attributes: [ 'id', 'url', 'followersUrl' ],
863 model: ActorModel.unscoped(),
869 attributes: [ 'id', 'url', 'followersUrl' ],
870 model: ActorModel.unscoped(),
880 return Bluebird.all([
881 // FIXME: typing issue
882 VideoModel.findAll(query as any),
883 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
884 ]).then(([ rows, totals ]) => {
885 // totals: totalVideos + totalVideoShares
887 let totalVideoShares = 0
888 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
889 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
891 const total = totalVideos + totalVideoShares
899 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
900 const query: IFindOptions<VideoModel> = {
903 order: getVideoSort(sort),
906 model: VideoChannelModel,
919 model: ScheduleVideoUpdateModel,
923 model: VideoBlacklistModel,
929 if (withFiles === true) {
931 model: VideoFileModel.unscoped(),
936 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
944 static async listForApi (options: {
949 includeLocalVideos: boolean,
951 categoryOneOf?: number[],
952 licenceOneOf?: number[],
953 languageOneOf?: string[],
954 tagsOneOf?: string[],
955 tagsAllOf?: string[],
956 filter?: VideoFilter,
958 videoChannelId?: number,
960 trendingDays?: number,
962 }, countVideos = true) {
963 const query: IFindOptions<VideoModel> = {
964 offset: options.start,
965 limit: options.count,
966 order: getVideoSort(options.sort)
969 let trendingDays: number
970 if (options.sort.endsWith('trending')) {
971 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
973 query.group = 'VideoModel.id'
976 // actorId === null has a meaning, so just check undefined
977 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
979 const queryOptions = {
982 categoryOneOf: options.categoryOneOf,
983 licenceOneOf: options.licenceOneOf,
984 languageOneOf: options.languageOneOf,
985 tagsOneOf: options.tagsOneOf,
986 tagsAllOf: options.tagsAllOf,
987 filter: options.filter,
988 withFiles: options.withFiles,
989 accountId: options.accountId,
990 videoChannelId: options.videoChannelId,
991 includeLocalVideos: options.includeLocalVideos,
992 userId: options.userId,
996 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
999 static async searchAndPopulateAccountAndServer (options: {
1000 includeLocalVideos: boolean
1005 startDate?: string // ISO 8601
1006 endDate?: string // ISO 8601
1008 categoryOneOf?: number[]
1009 licenceOneOf?: number[]
1010 languageOneOf?: string[]
1011 tagsOneOf?: string[]
1012 tagsAllOf?: string[]
1013 durationMin?: number // seconds
1014 durationMax?: number // seconds
1019 if (options.startDate || options.endDate) {
1020 const publishedAtRange = {}
1022 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
1023 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
1025 whereAnd.push({ publishedAt: publishedAtRange })
1028 if (options.durationMin || options.durationMax) {
1029 const durationRange = {}
1031 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1032 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1034 whereAnd.push({ duration: durationRange })
1037 const attributesInclude = []
1038 const escapedSearch = VideoModel.sequelize.escape(options.search)
1039 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1040 if (options.search) {
1044 [ Sequelize.Op.in ]: Sequelize.literal(
1046 'SELECT "video"."id" FROM "video" ' +
1048 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1049 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1051 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1052 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1053 'WHERE "tag"."name" = ' + escapedSearch +
1060 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1063 // Cannot search on similarity if we don't have a search
1064 if (!options.search) {
1065 attributesInclude.push(
1066 Sequelize.literal('0 as similarity')
1070 const query: IFindOptions<VideoModel> = {
1072 include: attributesInclude
1074 offset: options.start,
1075 limit: options.count,
1076 order: getVideoSort(options.sort),
1078 [ Sequelize.Op.and ]: whereAnd
1082 const serverActor = await getServerActor()
1083 const queryOptions = {
1084 actorId: serverActor.id,
1085 includeLocalVideos: options.includeLocalVideos,
1087 categoryOneOf: options.categoryOneOf,
1088 licenceOneOf: options.licenceOneOf,
1089 languageOneOf: options.languageOneOf,
1090 tagsOneOf: options.tagsOneOf,
1091 tagsAllOf: options.tagsAllOf,
1092 userId: options.userId
1095 return VideoModel.getAvailableForApi(query, queryOptions)
1098 static load (id: number | string, t?: Sequelize.Transaction) {
1099 const where = VideoModel.buildWhereIdOrUUID(id)
1105 return VideoModel.findOne(options)
1108 static loadOnlyId (id: number | string, t?: Sequelize.Transaction) {
1109 const where = VideoModel.buildWhereIdOrUUID(id)
1112 attributes: [ 'id' ],
1117 return VideoModel.findOne(options)
1120 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1121 return VideoModel.scope(ScopeNames.WITH_FILES)
1122 .findById(id, { transaction: t, logging })
1125 static loadByUUIDWithFile (uuid: string) {
1133 .scope([ ScopeNames.WITH_FILES ])
1137 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
1138 const query: IFindOptions<VideoModel> = {
1145 return VideoModel.findOne(query)
1148 static loadByUrlAndPopulateAccount (url: string, transaction?: Sequelize.Transaction) {
1149 const query: IFindOptions<VideoModel> = {
1156 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1159 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Sequelize.Transaction, userId?: number) {
1160 const where = VideoModel.buildWhereIdOrUUID(id)
1163 order: [ [ 'Tags', 'name', 'ASC' ] ],
1169 ScopeNames.WITH_TAGS,
1170 ScopeNames.WITH_BLACKLISTED,
1171 ScopeNames.WITH_FILES,
1172 ScopeNames.WITH_ACCOUNT_DETAILS,
1173 ScopeNames.WITH_SCHEDULED_UPDATE
1177 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] } as any) // FIXME: typings
1185 static async getStats () {
1186 const totalLocalVideos = await VideoModel.count({
1191 const totalVideos = await VideoModel.count()
1193 let totalLocalVideoViews = await VideoModel.sum('views', {
1198 // Sequelize could return null...
1199 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1203 totalLocalVideoViews,
1208 static incrementViews (id: number, views: number) {
1209 return VideoModel.increment('views', {
1217 // threshold corresponds to how many video the field should have to be returned
1218 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1219 const actorId = (await getServerActor()).id
1221 const scopeOptions = {
1223 includeLocalVideos: true
1226 const query: IFindOptions<VideoModel> = {
1227 attributes: [ field ],
1230 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1231 [ Sequelize.Op.gte ]: threshold
1232 }) as any, // FIXME: typings
1233 order: [ this.sequelize.random() ]
1236 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1238 .then(rows => rows.map(r => r[ field ]))
1241 static buildTrendingQuery (trendingDays: number) {
1245 model: VideoViewModel,
1249 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1255 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1256 if (filter && filter === 'local') {
1265 private static async getAvailableForApi (
1266 query: IFindOptions<VideoModel>,
1267 options: AvailableForListIDsOptions & { userId?: number},
1272 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1276 // Remove trending sort on count, because it uses a group by
1277 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1278 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1279 const countScope = {
1281 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1285 const [ count, rowsId ] = await Promise.all([
1286 countVideos ? VideoModel.scope(countScope).count(countQuery) : Promise.resolve(undefined),
1287 VideoModel.scope(idsScope).findAll(query)
1289 const ids = rowsId.map(r => r.id)
1291 if (ids.length === 0) return { data: [], total: count }
1294 const apiScope: any[] = [
1296 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1300 if (options.userId) {
1301 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.userId ] })
1304 const secondQuery = {
1307 attributes: query.attributes,
1308 order: [ // Keep original order
1310 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1314 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1322 static getCategoryLabel (id: number) {
1323 return VIDEO_CATEGORIES[ id ] || 'Misc'
1326 static getLicenceLabel (id: number) {
1327 return VIDEO_LICENCES[ id ] || 'Unknown'
1330 static getLanguageLabel (id: string) {
1331 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1334 static getPrivacyLabel (id: number) {
1335 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1338 static getStateLabel (id: number) {
1339 return VIDEO_STATES[ id ] || 'Unknown'
1342 static buildWhereIdOrUUID (id: number | string) {
1343 return validator.isInt('' + id) ? { id } : { uuid: id }
1346 getOriginalFile () {
1347 if (Array.isArray(this.VideoFiles) === false) return undefined
1349 // The original file is the file that have the higher resolution
1350 return maxBy(this.VideoFiles, file => file.resolution)
1353 getVideoFilename (videoFile: VideoFileModel) {
1354 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1357 getThumbnailName () {
1358 // We always have a copy of the thumbnail
1359 const extension = '.jpg'
1360 return this.uuid + extension
1364 const extension = '.jpg'
1365 return this.uuid + extension
1368 getTorrentFileName (videoFile: VideoFileModel) {
1369 const extension = '.torrent'
1370 return this.uuid + '-' + videoFile.resolution + extension
1374 return this.remote === false
1377 createPreview (videoFile: VideoFileModel) {
1378 return generateImageFromVideoFile(
1379 this.getVideoFilePath(videoFile),
1380 CONFIG.STORAGE.PREVIEWS_DIR,
1381 this.getPreviewName(),
1386 createThumbnail (videoFile: VideoFileModel) {
1387 return generateImageFromVideoFile(
1388 this.getVideoFilePath(videoFile),
1389 CONFIG.STORAGE.THUMBNAILS_DIR,
1390 this.getThumbnailName(),
1395 getTorrentFilePath (videoFile: VideoFileModel) {
1396 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1399 getVideoFilePath (videoFile: VideoFileModel) {
1400 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1403 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1405 // Keep the extname, it's used by the client to stream the file inside a web browser
1406 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1407 createdBy: 'PeerTube',
1409 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1410 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1412 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1415 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1417 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1418 logger.info('Creating torrent %s.', filePath)
1420 await writeFile(filePath, torrent)
1422 const parsedTorrent = parseTorrent(torrent)
1423 videoFile.infoHash = parsedTorrent.infoHash
1426 getEmbedStaticPath () {
1427 return '/videos/embed/' + this.uuid
1430 getThumbnailStaticPath () {
1431 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1434 getPreviewStaticPath () {
1435 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1438 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1439 return videoModelToFormattedJSON(this, options)
1442 toFormattedDetailsJSON (): VideoDetails {
1443 return videoModelToFormattedDetailsJSON(this)
1446 getFormattedVideoFilesJSON (): VideoFile[] {
1447 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1450 toActivityPubObject (): VideoTorrentObject {
1451 return videoModelToActivityPubObject(this)
1454 getTruncatedDescription () {
1455 if (!this.description) return null
1457 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1458 return peertubeTruncate(this.description, maxLength)
1461 getOriginalFileResolution () {
1462 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1464 return getVideoFileResolution(originalFilePath)
1467 getDescriptionAPIPath () {
1468 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1471 removeThumbnail () {
1472 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1473 return remove(thumbnailPath)
1474 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1478 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1479 return remove(previewPath)
1480 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1483 removeFile (videoFile: VideoFileModel) {
1484 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1485 return remove(filePath)
1486 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1489 removeTorrent (videoFile: VideoFileModel) {
1490 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1491 return remove(torrentPath)
1492 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1496 if (this.isOwned()) return false
1498 const now = Date.now()
1499 const createdAtTime = this.createdAt.getTime()
1500 const updatedAtTime = this.updatedAt.getTime()
1502 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1503 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1510 if (this.isOwned()) {
1511 baseUrlHttp = CONFIG.WEBSERVER.URL
1512 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1514 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1515 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1518 return { baseUrlHttp, baseUrlWs }
1521 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1522 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1523 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1524 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1526 const redundancies = videoFile.RedundancyVideos
1527 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1529 const magnetHash = {
1533 infoHash: videoFile.infoHash,
1537 return magnetUtil.encode(magnetHash)
1540 getThumbnailUrl (baseUrlHttp: string) {
1541 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1544 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1545 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1548 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1549 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1552 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1553 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1556 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1557 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)