1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { extname, join } from 'path'
6 import * as Sequelize from 'sequelize'
29 } from 'sequelize-typescript'
30 import { VideoPrivacy, VideoResolution, 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 { isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
58 STATIC_DOWNLOAD_PATHS,
67 } from '../../initializers'
69 getVideoCommentsActivityPubUrl,
70 getVideoDislikesActivityPubUrl,
71 getVideoLikesActivityPubUrl,
72 getVideoSharesActivityPubUrl
73 } from '../../lib/activitypub'
74 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 import { AccountModel } from '../account/account'
76 import { AccountVideoRateModel } from '../account/account-video-rate'
77 import { ActorModel } from '../activitypub/actor'
78 import { AvatarModel } from '../avatar/avatar'
79 import { ServerModel } from '../server/server'
80 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
81 import { TagModel } from './tag'
82 import { VideoAbuseModel } from './video-abuse'
83 import { VideoChannelModel } from './video-channel'
84 import { VideoCommentModel } from './video-comment'
85 import { VideoFileModel } from './video-file'
86 import { VideoShareModel } from './video-share'
87 import { VideoTagModel } from './video-tag'
88 import { ScheduleVideoUpdateModel } from './schedule-video-update'
89 import { VideoCaptionModel } from './video-caption'
90 import { VideoBlacklistModel } from './video-blacklist'
91 import { copy, remove, rename, stat, writeFile } from 'fs-extra'
92 import { immutableAssign } from '../../tests/utils'
94 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
95 const indexes: Sequelize.DefineIndexesOptions[] = [
96 buildTrigramSearchIndex('video_name_trigram', 'name'),
98 { fields: [ 'createdAt' ] },
99 { fields: [ 'publishedAt' ] },
100 { fields: [ 'duration' ] },
101 { fields: [ 'category' ] },
102 { fields: [ 'licence' ] },
103 { fields: [ 'nsfw' ] },
104 { fields: [ 'language' ] },
105 { fields: [ 'waitTranscoding' ] },
106 { fields: [ 'state' ] },
107 { fields: [ 'remote' ] },
108 { fields: [ 'views' ] },
109 { fields: [ 'likes' ] },
110 { fields: [ 'channelId' ] },
121 export enum ScopeNames {
122 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
124 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
125 WITH_TAGS = 'WITH_TAGS',
126 WITH_FILES = 'WITH_FILES',
127 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
128 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
131 type ForAPIOptions = {
136 type AvailableForListIDsOptions = {
138 includeLocalVideos: boolean
140 categoryOneOf?: number[]
142 licenceOneOf?: number[]
143 languageOneOf?: string[]
148 videoChannelId?: number
152 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
153 const accountInclude = {
154 attributes: [ 'id', 'name' ],
155 model: AccountModel.unscoped(),
159 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
160 model: ActorModel.unscoped(),
164 attributes: [ 'host' ],
165 model: ServerModel.unscoped(),
169 model: AvatarModel.unscoped(),
177 const videoChannelInclude = {
178 attributes: [ 'name', 'description', 'id' ],
179 model: VideoChannelModel.unscoped(),
183 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
184 model: ActorModel.unscoped(),
188 attributes: [ 'host' ],
189 model: ServerModel.unscoped(),
193 model: AvatarModel.unscoped(),
202 const query: IFindOptions<VideoModel> = {
205 [Sequelize.Op.any]: options.ids
208 include: [ videoChannelInclude ]
211 if (options.withFiles === true) {
213 model: VideoFileModel.unscoped(),
220 [ScopeNames.AVAILABLE_FOR_LIST_IDS]: (options: AvailableForListIDsOptions) => {
221 const query: IFindOptions<VideoModel> = {
222 attributes: [ 'id' ],
225 [Sequelize.Op.and]: [
227 [ Sequelize.Op.notIn ]: Sequelize.literal(
228 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
233 // Always list public videos
234 privacy: VideoPrivacy.PUBLIC,
235 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
236 [ Sequelize.Op.or ]: [
238 state: VideoState.PUBLISHED
241 [ Sequelize.Op.and ]: {
242 state: VideoState.TO_TRANSCODE,
243 waitTranscoding: false
251 if (options.filter || options.accountId || options.videoChannelId) {
252 const videoChannelInclude: IIncludeOptions = {
254 model: VideoChannelModel.unscoped(),
258 if (options.videoChannelId) {
259 videoChannelInclude.where = {
260 id: options.videoChannelId
264 if (options.filter || options.accountId) {
265 const accountInclude: IIncludeOptions = {
267 model: AccountModel.unscoped(),
271 if (options.filter) {
272 accountInclude.include = [
275 model: ActorModel.unscoped(),
277 where: VideoModel.buildActorWhereWithFilter(options.filter)
282 if (options.accountId) {
283 accountInclude.where = { id: options.accountId }
286 videoChannelInclude.include = [ accountInclude ]
289 query.include.push(videoChannelInclude)
292 if (options.actorId) {
293 let localVideosReq = ''
294 if (options.includeLocalVideos === true) {
295 localVideosReq = ' UNION ALL ' +
296 'SELECT "video"."id" AS "id" FROM "video" ' +
297 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
298 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
299 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
300 'WHERE "actor"."serverId" IS NULL'
303 // Force actorId to be a number to avoid SQL injections
304 const actorIdNumber = parseInt(options.actorId.toString(), 10)
305 query.where['id'][Sequelize.Op.and].push({
306 [ Sequelize.Op.in ]: Sequelize.literal(
308 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
309 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
310 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
312 'SELECT "video"."id" AS "id" FROM "video" ' +
313 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
314 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
315 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
316 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
317 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
324 if (options.withFiles === true) {
325 query.where['id'][Sequelize.Op.and].push({
326 [ Sequelize.Op.in ]: Sequelize.literal(
327 '(SELECT "videoId" FROM "videoFile")'
332 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
333 if (options.tagsAllOf || options.tagsOneOf) {
334 const createTagsIn = (tags: string[]) => {
335 return tags.map(t => VideoModel.sequelize.escape(t))
339 if (options.tagsOneOf) {
340 query.where['id'][Sequelize.Op.and].push({
341 [Sequelize.Op.in]: Sequelize.literal(
343 'SELECT "videoId" FROM "videoTag" ' +
344 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
345 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
351 if (options.tagsAllOf) {
352 query.where['id'][Sequelize.Op.and].push({
353 [Sequelize.Op.in]: Sequelize.literal(
355 'SELECT "videoId" FROM "videoTag" ' +
356 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
357 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
358 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
365 if (options.nsfw === true || options.nsfw === false) {
366 query.where['nsfw'] = options.nsfw
369 if (options.categoryOneOf) {
370 query.where['category'] = {
371 [Sequelize.Op.or]: options.categoryOneOf
375 if (options.licenceOneOf) {
376 query.where['licence'] = {
377 [Sequelize.Op.or]: options.licenceOneOf
381 if (options.languageOneOf) {
382 query.where['language'] = {
383 [Sequelize.Op.or]: options.languageOneOf
389 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
392 model: () => VideoChannelModel.unscoped(),
397 exclude: [ 'privateKey', 'publicKey' ]
399 model: () => ActorModel.unscoped(),
403 attributes: [ 'host' ],
404 model: () => ServerModel.unscoped(),
408 model: () => AvatarModel.unscoped(),
414 model: () => AccountModel.unscoped(),
418 model: () => ActorModel.unscoped(),
420 exclude: [ 'privateKey', 'publicKey' ]
425 attributes: [ 'host' ],
426 model: () => ServerModel.unscoped(),
430 model: () => AvatarModel.unscoped(),
441 [ScopeNames.WITH_TAGS]: {
442 include: [ () => TagModel ]
444 [ScopeNames.WITH_BLACKLISTED]: {
447 attributes: [ 'id', 'reason' ],
448 model: () => VideoBlacklistModel,
453 [ScopeNames.WITH_FILES]: {
456 model: () => VideoFileModel.unscoped(),
461 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
464 model: () => ScheduleVideoUpdateModel.unscoped(),
474 export class VideoModel extends Model<VideoModel> {
477 @Default(DataType.UUIDV4)
479 @Column(DataType.UUID)
483 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
489 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
495 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
501 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
502 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
506 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
511 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
517 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
523 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
524 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
528 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
558 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
559 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
564 commentsEnabled: boolean
568 waitTranscoding: boolean
572 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
583 @Default(Sequelize.NOW)
587 @ForeignKey(() => VideoChannelModel)
591 @BelongsTo(() => VideoChannelModel, {
597 VideoChannel: VideoChannelModel
599 @BelongsToMany(() => TagModel, {
600 foreignKey: 'videoId',
601 through: () => VideoTagModel,
606 @HasMany(() => VideoAbuseModel, {
613 VideoAbuses: VideoAbuseModel[]
615 @HasMany(() => VideoFileModel, {
622 VideoFiles: VideoFileModel[]
624 @HasMany(() => VideoShareModel, {
631 VideoShares: VideoShareModel[]
633 @HasMany(() => AccountVideoRateModel, {
640 AccountVideoRates: AccountVideoRateModel[]
642 @HasMany(() => VideoCommentModel, {
650 VideoComments: VideoCommentModel[]
652 @HasOne(() => ScheduleVideoUpdateModel, {
659 ScheduleVideoUpdate: ScheduleVideoUpdateModel
661 @HasOne(() => VideoBlacklistModel, {
668 VideoBlacklist: VideoBlacklistModel
670 @HasMany(() => VideoCaptionModel, {
677 ['separate' as any]: true
679 VideoCaptions: VideoCaptionModel[]
682 static async sendDelete (instance: VideoModel, options) {
683 if (instance.isOwned()) {
684 if (!instance.VideoChannel) {
685 instance.VideoChannel = await instance.$get('VideoChannel', {
689 include: [ ActorModel ]
692 transaction: options.transaction
693 }) as VideoChannelModel
696 return sendDeleteVideo(instance, options.transaction)
703 static async removeFiles (instance: VideoModel) {
704 const tasks: Promise<any>[] = []
706 logger.info('Removing files of video %s.', instance.url)
708 tasks.push(instance.removeThumbnail())
710 if (instance.isOwned()) {
711 if (!Array.isArray(instance.VideoFiles)) {
712 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
715 tasks.push(instance.removePreview())
717 // Remove physical files and torrents
718 instance.VideoFiles.forEach(file => {
719 tasks.push(instance.removeFile(file))
720 tasks.push(instance.removeTorrent(file))
724 // Do not wait video deletion because we could be in a transaction
727 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
734 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
737 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
738 function getRawQuery (select: string) {
739 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
740 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
741 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
742 'WHERE "Account"."actorId" = ' + actorId
743 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
744 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
745 'WHERE "VideoShare"."actorId" = ' + actorId
747 return `(${queryVideo}) UNION (${queryVideoShare})`
750 const rawQuery = getRawQuery('"Video"."id"')
751 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
757 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
760 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
763 { privacy: VideoPrivacy.PUBLIC },
764 { privacy: VideoPrivacy.UNLISTED }
769 attributes: [ 'language' ],
770 model: VideoCaptionModel.unscoped(),
774 attributes: [ 'id', 'url' ],
775 model: VideoShareModel.unscoped(),
777 // We only want videos shared by this actor
779 [Sequelize.Op.and]: [
782 [Sequelize.Op.not]: null
792 attributes: [ 'id', 'url' ],
793 model: ActorModel.unscoped()
798 model: VideoChannelModel.unscoped(),
802 attributes: [ 'name' ],
803 model: AccountModel.unscoped(),
807 attributes: [ 'id', 'url', 'followersUrl' ],
808 model: ActorModel.unscoped(),
814 attributes: [ 'id', 'url', 'followersUrl' ],
815 model: ActorModel.unscoped(),
825 return Bluebird.all([
826 // FIXME: typing issue
827 VideoModel.findAll(query as any),
828 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
829 ]).then(([ rows, totals ]) => {
830 // totals: totalVideos + totalVideoShares
832 let totalVideoShares = 0
833 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
834 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
836 const total = totalVideos + totalVideoShares
844 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
845 const query: IFindOptions<VideoModel> = {
848 order: getSort(sort),
851 model: VideoChannelModel,
864 model: ScheduleVideoUpdateModel,
868 model: VideoBlacklistModel,
874 if (withFiles === true) {
876 model: VideoFileModel.unscoped(),
881 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
889 static async listForApi (options: {
894 includeLocalVideos: boolean,
896 categoryOneOf?: number[],
897 licenceOneOf?: number[],
898 languageOneOf?: string[],
899 tagsOneOf?: string[],
900 tagsAllOf?: string[],
901 filter?: VideoFilter,
903 videoChannelId?: number,
907 offset: options.start,
908 limit: options.count,
909 order: getSort(options.sort)
912 // actorId === null has a meaning, so just check undefined
913 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
915 const queryOptions = {
918 categoryOneOf: options.categoryOneOf,
919 licenceOneOf: options.licenceOneOf,
920 languageOneOf: options.languageOneOf,
921 tagsOneOf: options.tagsOneOf,
922 tagsAllOf: options.tagsAllOf,
923 filter: options.filter,
924 withFiles: options.withFiles,
925 accountId: options.accountId,
926 videoChannelId: options.videoChannelId,
927 includeLocalVideos: options.includeLocalVideos
930 return VideoModel.getAvailableForApi(query, queryOptions)
933 static async searchAndPopulateAccountAndServer (options: {
934 includeLocalVideos: boolean
939 startDate?: string // ISO 8601
940 endDate?: string // ISO 8601
942 categoryOneOf?: number[]
943 licenceOneOf?: number[]
944 languageOneOf?: string[]
947 durationMin?: number // seconds
948 durationMax?: number // seconds
952 if (options.startDate || options.endDate) {
953 const publishedAtRange = { }
955 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
956 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
958 whereAnd.push({ publishedAt: publishedAtRange })
961 if (options.durationMin || options.durationMax) {
962 const durationRange = { }
964 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
965 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
967 whereAnd.push({ duration: durationRange })
970 const attributesInclude = []
971 const escapedSearch = VideoModel.sequelize.escape(options.search)
972 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
973 if (options.search) {
977 [ Sequelize.Op.in ]: Sequelize.literal(
979 'SELECT "video"."id" FROM "video" ' +
981 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
982 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
984 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
985 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
986 'WHERE "tag"."name" = ' + escapedSearch +
993 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
996 // Cannot search on similarity if we don't have a search
997 if (!options.search) {
998 attributesInclude.push(
999 Sequelize.literal('0 as similarity')
1003 const query: IFindOptions<VideoModel> = {
1005 include: attributesInclude
1007 offset: options.start,
1008 limit: options.count,
1009 order: getSort(options.sort),
1011 [ Sequelize.Op.and ]: whereAnd
1015 const serverActor = await getServerActor()
1016 const queryOptions = {
1017 actorId: serverActor.id,
1018 includeLocalVideos: options.includeLocalVideos,
1020 categoryOneOf: options.categoryOneOf,
1021 licenceOneOf: options.licenceOneOf,
1022 languageOneOf: options.languageOneOf,
1023 tagsOneOf: options.tagsOneOf,
1024 tagsAllOf: options.tagsAllOf
1027 return VideoModel.getAvailableForApi(query, queryOptions)
1030 static load (id: number, t?: Sequelize.Transaction) {
1031 const options = t ? { transaction: t } : undefined
1033 return VideoModel.findById(id, options)
1036 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1037 const query: IFindOptions<VideoModel> = {
1043 if (t !== undefined) query.transaction = t
1045 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1048 static loadAndPopulateAccountAndServerAndTags (id: number) {
1050 order: [ [ 'Tags', 'name', 'ASC' ] ]
1055 ScopeNames.WITH_TAGS,
1056 ScopeNames.WITH_BLACKLISTED,
1057 ScopeNames.WITH_FILES,
1058 ScopeNames.WITH_ACCOUNT_DETAILS,
1059 ScopeNames.WITH_SCHEDULED_UPDATE
1061 .findById(id, options)
1064 static loadByUUID (uuid: string) {
1072 .scope([ ScopeNames.WITH_FILES ])
1076 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1078 order: [ [ 'Tags', 'name', 'ASC' ] ],
1087 ScopeNames.WITH_TAGS,
1088 ScopeNames.WITH_BLACKLISTED,
1089 ScopeNames.WITH_FILES,
1090 ScopeNames.WITH_ACCOUNT_DETAILS,
1091 ScopeNames.WITH_SCHEDULED_UPDATE
1096 static async getStats () {
1097 const totalLocalVideos = await VideoModel.count({
1102 const totalVideos = await VideoModel.count()
1104 let totalLocalVideoViews = await VideoModel.sum('views', {
1109 // Sequelize could return null...
1110 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1114 totalLocalVideoViews,
1119 static incrementViews (id: number, views: number) {
1120 return VideoModel.increment('views', {
1128 // threshold corresponds to how many video the field should have to be returned
1129 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1130 const query: IFindOptions<VideoModel> = {
1131 attributes: [ field ],
1134 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1135 [Sequelize.Op.gte]: threshold
1136 }) as any, // FIXME: typings
1139 [Sequelize.Op.not]: null
1141 privacy: VideoPrivacy.PUBLIC,
1142 state: VideoState.PUBLISHED
1144 order: [ this.sequelize.random() ]
1147 return VideoModel.findAll(query)
1148 .then(rows => rows.map(r => r[field]))
1151 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1152 if (filter && filter === 'local') {
1161 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1164 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1168 const { count, rows: rowsId } = await VideoModel.scope(idsScope).findAndCountAll(query)
1169 const ids = rowsId.map(r => r.id)
1171 if (ids.length === 0) return { data: [], total: count }
1174 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1177 const secondQuery = {
1181 attributes: query.attributes
1183 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1191 private static getCategoryLabel (id: number) {
1192 return VIDEO_CATEGORIES[id] || 'Misc'
1195 private static getLicenceLabel (id: number) {
1196 return VIDEO_LICENCES[id] || 'Unknown'
1199 private static getLanguageLabel (id: string) {
1200 return VIDEO_LANGUAGES[id] || 'Unknown'
1203 private static getPrivacyLabel (id: number) {
1204 return VIDEO_PRIVACIES[id] || 'Unknown'
1207 private static getStateLabel (id: number) {
1208 return VIDEO_STATES[id] || 'Unknown'
1211 getOriginalFile () {
1212 if (Array.isArray(this.VideoFiles) === false) return undefined
1214 // The original file is the file that have the higher resolution
1215 return maxBy(this.VideoFiles, file => file.resolution)
1218 getVideoFilename (videoFile: VideoFileModel) {
1219 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1222 getThumbnailName () {
1223 // We always have a copy of the thumbnail
1224 const extension = '.jpg'
1225 return this.uuid + extension
1229 const extension = '.jpg'
1230 return this.uuid + extension
1233 getTorrentFileName (videoFile: VideoFileModel) {
1234 const extension = '.torrent'
1235 return this.uuid + '-' + videoFile.resolution + extension
1239 return this.remote === false
1242 createPreview (videoFile: VideoFileModel) {
1243 return generateImageFromVideoFile(
1244 this.getVideoFilePath(videoFile),
1245 CONFIG.STORAGE.PREVIEWS_DIR,
1246 this.getPreviewName(),
1251 createThumbnail (videoFile: VideoFileModel) {
1252 return generateImageFromVideoFile(
1253 this.getVideoFilePath(videoFile),
1254 CONFIG.STORAGE.THUMBNAILS_DIR,
1255 this.getThumbnailName(),
1260 getTorrentFilePath (videoFile: VideoFileModel) {
1261 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1264 getVideoFilePath (videoFile: VideoFileModel) {
1265 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1268 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1270 // Keep the extname, it's used by the client to stream the file inside a web browser
1271 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1272 createdBy: 'PeerTube',
1274 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1275 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1278 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1282 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1284 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1285 logger.info('Creating torrent %s.', filePath)
1287 await writeFile(filePath, torrent)
1289 const parsedTorrent = parseTorrent(torrent)
1290 videoFile.infoHash = parsedTorrent.infoHash
1293 getEmbedStaticPath () {
1294 return '/videos/embed/' + this.uuid
1297 getThumbnailStaticPath () {
1298 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1301 getPreviewStaticPath () {
1302 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1305 toFormattedJSON (options?: {
1306 additionalAttributes: {
1308 waitTranscoding?: boolean,
1309 scheduledUpdate?: boolean,
1310 blacklistInfo?: boolean
1313 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1314 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1316 const videoObject: Video = {
1322 label: VideoModel.getCategoryLabel(this.category)
1326 label: VideoModel.getLicenceLabel(this.licence)
1330 label: VideoModel.getLanguageLabel(this.language)
1334 label: VideoModel.getPrivacyLabel(this.privacy)
1337 description: this.getTruncatedDescription(),
1338 isLocal: this.isOwned(),
1339 duration: this.duration,
1342 dislikes: this.dislikes,
1343 thumbnailPath: this.getThumbnailStaticPath(),
1344 previewPath: this.getPreviewStaticPath(),
1345 embedPath: this.getEmbedStaticPath(),
1346 createdAt: this.createdAt,
1347 updatedAt: this.updatedAt,
1348 publishedAt: this.publishedAt,
1350 id: formattedAccount.id,
1351 uuid: formattedAccount.uuid,
1352 name: formattedAccount.name,
1353 displayName: formattedAccount.displayName,
1354 url: formattedAccount.url,
1355 host: formattedAccount.host,
1356 avatar: formattedAccount.avatar
1359 id: formattedVideoChannel.id,
1360 uuid: formattedVideoChannel.uuid,
1361 name: formattedVideoChannel.name,
1362 displayName: formattedVideoChannel.displayName,
1363 url: formattedVideoChannel.url,
1364 host: formattedVideoChannel.host,
1365 avatar: formattedVideoChannel.avatar
1370 if (options.additionalAttributes.state === true) {
1371 videoObject.state = {
1373 label: VideoModel.getStateLabel(this.state)
1377 if (options.additionalAttributes.waitTranscoding === true) {
1378 videoObject.waitTranscoding = this.waitTranscoding
1381 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1382 videoObject.scheduledUpdate = {
1383 updateAt: this.ScheduleVideoUpdate.updateAt,
1384 privacy: this.ScheduleVideoUpdate.privacy || undefined
1388 if (options.additionalAttributes.blacklistInfo === true) {
1389 videoObject.blacklisted = !!this.VideoBlacklist
1390 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1397 toFormattedDetailsJSON (): VideoDetails {
1398 const formattedJson = this.toFormattedJSON({
1399 additionalAttributes: {
1400 scheduledUpdate: true,
1405 const detailsJson = {
1406 support: this.support,
1407 descriptionPath: this.getDescriptionPath(),
1408 channel: this.VideoChannel.toFormattedJSON(),
1409 account: this.VideoChannel.Account.toFormattedJSON(),
1410 tags: map(this.Tags, 'name'),
1411 commentsEnabled: this.commentsEnabled,
1412 waitTranscoding: this.waitTranscoding,
1415 label: VideoModel.getStateLabel(this.state)
1420 // Format and sort video files
1421 detailsJson.files = this.getFormattedVideoFilesJSON()
1423 return Object.assign(formattedJson, detailsJson)
1426 getFormattedVideoFilesJSON (): VideoFile[] {
1427 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1429 return this.VideoFiles
1431 let resolutionLabel = videoFile.resolution + 'p'
1435 id: videoFile.resolution,
1436 label: resolutionLabel
1438 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1439 size: videoFile.size,
1441 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1442 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1443 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1444 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1448 if (a.resolution.id < b.resolution.id) return 1
1449 if (a.resolution.id === b.resolution.id) return 0
1454 toActivityPubObject (): VideoTorrentObject {
1455 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1456 if (!this.Tags) this.Tags = []
1458 const tag = this.Tags.map(t => ({
1459 type: 'Hashtag' as 'Hashtag',
1464 if (this.language) {
1466 identifier: this.language,
1467 name: VideoModel.getLanguageLabel(this.language)
1472 if (this.category) {
1474 identifier: this.category + '',
1475 name: VideoModel.getCategoryLabel(this.category)
1482 identifier: this.licence + '',
1483 name: VideoModel.getLicenceLabel(this.licence)
1488 for (const file of this.VideoFiles) {
1491 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1492 href: this.getVideoFileUrl(file, baseUrlHttp),
1493 height: file.resolution,
1500 mimeType: 'application/x-bittorrent',
1501 href: this.getTorrentUrl(file, baseUrlHttp),
1502 height: file.resolution
1507 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1508 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1509 height: file.resolution
1513 // Add video url too
1516 mimeType: 'text/html',
1517 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1520 const subtitleLanguage = []
1521 for (const caption of this.VideoCaptions) {
1522 subtitleLanguage.push({
1523 identifier: caption.language,
1524 name: VideoCaptionModel.getLanguageLabel(caption.language)
1529 type: 'Video' as 'Video',
1532 duration: this.getActivityStreamDuration(),
1539 sensitive: this.nsfw,
1540 waitTranscoding: this.waitTranscoding,
1542 commentsEnabled: this.commentsEnabled,
1543 published: this.publishedAt.toISOString(),
1544 updated: this.updatedAt.toISOString(),
1545 mediaType: 'text/markdown',
1546 content: this.getTruncatedDescription(),
1547 support: this.support,
1551 url: this.getThumbnailUrl(baseUrlHttp),
1552 mediaType: 'image/jpeg',
1553 width: THUMBNAILS_SIZE.width,
1554 height: THUMBNAILS_SIZE.height
1557 likes: getVideoLikesActivityPubUrl(this),
1558 dislikes: getVideoDislikesActivityPubUrl(this),
1559 shares: getVideoSharesActivityPubUrl(this),
1560 comments: getVideoCommentsActivityPubUrl(this),
1564 id: this.VideoChannel.Account.Actor.url
1568 id: this.VideoChannel.Actor.url
1574 getTruncatedDescription () {
1575 if (!this.description) return null
1577 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1578 return peertubeTruncate(this.description, maxLength)
1581 async optimizeOriginalVideofile () {
1582 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1583 const newExtname = '.mp4'
1584 const inputVideoFile = this.getOriginalFile()
1585 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1586 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1588 const transcodeOptions = {
1589 inputPath: videoInputPath,
1590 outputPath: videoTranscodedPath
1593 // Could be very long!
1594 await transcode(transcodeOptions)
1597 await remove(videoInputPath)
1599 // Important to do this before getVideoFilename() to take in account the new file extension
1600 inputVideoFile.set('extname', newExtname)
1602 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1603 await rename(videoTranscodedPath, videoOutputPath)
1604 const stats = await stat(videoOutputPath)
1605 const fps = await getVideoFileFPS(videoOutputPath)
1607 inputVideoFile.set('size', stats.size)
1608 inputVideoFile.set('fps', fps)
1610 await this.createTorrentAndSetInfoHash(inputVideoFile)
1611 await inputVideoFile.save()
1614 // Auto destruction...
1615 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1621 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1622 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1623 const extname = '.mp4'
1625 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1626 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1628 const newVideoFile = new VideoFileModel({
1634 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1636 const transcodeOptions = {
1637 inputPath: videoInputPath,
1638 outputPath: videoOutputPath,
1643 await transcode(transcodeOptions)
1645 const stats = await stat(videoOutputPath)
1646 const fps = await getVideoFileFPS(videoOutputPath)
1648 newVideoFile.set('size', stats.size)
1649 newVideoFile.set('fps', fps)
1651 await this.createTorrentAndSetInfoHash(newVideoFile)
1653 await newVideoFile.save()
1655 this.VideoFiles.push(newVideoFile)
1658 async importVideoFile (inputFilePath: string) {
1659 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1660 const { size } = await stat(inputFilePath)
1661 const fps = await getVideoFileFPS(inputFilePath)
1663 let updatedVideoFile = new VideoFileModel({
1664 resolution: videoFileResolution,
1665 extname: extname(inputFilePath),
1671 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1673 if (currentVideoFile) {
1674 // Remove old file and old torrent
1675 await this.removeFile(currentVideoFile)
1676 await this.removeTorrent(currentVideoFile)
1677 // Remove the old video file from the array
1678 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1680 // Update the database
1681 currentVideoFile.set('extname', updatedVideoFile.extname)
1682 currentVideoFile.set('size', updatedVideoFile.size)
1683 currentVideoFile.set('fps', updatedVideoFile.fps)
1685 updatedVideoFile = currentVideoFile
1688 const outputPath = this.getVideoFilePath(updatedVideoFile)
1689 await copy(inputFilePath, outputPath)
1691 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1693 await updatedVideoFile.save()
1695 this.VideoFiles.push(updatedVideoFile)
1698 getOriginalFileResolution () {
1699 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1701 return getVideoFileResolution(originalFilePath)
1704 getDescriptionPath () {
1705 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1708 removeThumbnail () {
1709 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1710 return remove(thumbnailPath)
1711 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1715 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1716 return remove(previewPath)
1717 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1720 removeFile (videoFile: VideoFileModel) {
1721 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1722 return remove(filePath)
1723 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1726 removeTorrent (videoFile: VideoFileModel) {
1727 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1728 return remove(torrentPath)
1729 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1732 getActivityStreamDuration () {
1733 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1734 return 'PT' + this.duration + 'S'
1738 if (this.isOwned()) return false
1740 const now = Date.now()
1741 const createdAtTime = this.createdAt.getTime()
1742 const updatedAtTime = this.updatedAt.getTime()
1744 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1745 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1748 private getBaseUrls () {
1752 if (this.isOwned()) {
1753 baseUrlHttp = CONFIG.WEBSERVER.URL
1754 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1756 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1757 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1760 return { baseUrlHttp, baseUrlWs }
1763 private getThumbnailUrl (baseUrlHttp: string) {
1764 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1767 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1768 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1771 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1772 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1775 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1776 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1779 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1780 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1783 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1784 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1785 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1786 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1788 const magnetHash = {
1792 infoHash: videoFile.infoHash,
1796 return magnetUtil.encode(magnetHash)