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 { join, extname } from 'path'
6 import * as Sequelize from 'sequelize'
27 } from 'sequelize-typescript'
28 import { VideoPrivacy, VideoResolution } from '../../../shared'
29 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
30 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
31 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
40 } from '../../helpers/core-utils'
41 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
42 import { isBooleanValid } from '../../helpers/custom-validators/misc'
45 isVideoDescriptionValid,
52 } from '../../helpers/custom-validators/videos'
53 import { generateImageFromVideoFile, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
54 import { logger } from '../../helpers/logger'
55 import { getServerActor } from '../../helpers/utils'
62 STATIC_DOWNLOAD_PATHS,
69 } from '../../initializers'
71 getVideoCommentsActivityPubUrl,
72 getVideoDislikesActivityPubUrl,
73 getVideoLikesActivityPubUrl,
74 getVideoSharesActivityPubUrl
75 } from '../../lib/activitypub'
76 import { sendDeleteVideo } from '../../lib/activitypub/send'
77 import { AccountModel } from '../account/account'
78 import { AccountVideoRateModel } from '../account/account-video-rate'
79 import { ActorModel } from '../activitypub/actor'
80 import { AvatarModel } from '../avatar/avatar'
81 import { ServerModel } from '../server/server'
82 import { getSort, throwIfNotValid } from '../utils'
83 import { TagModel } from './tag'
84 import { VideoAbuseModel } from './video-abuse'
85 import { VideoChannelModel } from './video-channel'
86 import { VideoCommentModel } from './video-comment'
87 import { VideoFileModel } from './video-file'
88 import { VideoShareModel } from './video-share'
89 import { VideoTagModel } from './video-tag'
92 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
93 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
94 WITH_TAGS = 'WITH_TAGS',
95 WITH_FILES = 'WITH_FILES',
96 WITH_SHARES = 'WITH_SHARES',
97 WITH_RATES = 'WITH_RATES',
98 WITH_COMMENTS = 'WITH_COMMENTS'
102 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
105 filter?: VideoFilter,
108 videoChannelId?: number
110 const accountInclude = {
111 attributes: [ 'id', 'name' ],
112 model: AccountModel.unscoped(),
117 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
118 model: ActorModel.unscoped(),
120 where: VideoModel.buildActorWhereWithFilter(options.filter),
123 attributes: [ 'host' ],
124 model: ServerModel.unscoped(),
128 model: AvatarModel.unscoped(),
136 const videoChannelInclude = {
137 attributes: [ 'name', 'description', 'id' ],
138 model: VideoChannelModel.unscoped(),
143 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
144 model: ActorModel.unscoped(),
148 attributes: [ 'host' ],
149 model: ServerModel.unscoped(),
153 model: AvatarModel.unscoped(),
162 // Force actorId to be a number to avoid SQL injections
163 const actorIdNumber = parseInt(options.actorId.toString(), 10)
164 const query: IFindOptions<VideoModel> = {
167 [Sequelize.Op.notIn]: Sequelize.literal(
168 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
170 [ Sequelize.Op.in ]: Sequelize.literal(
172 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
173 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
174 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
176 'SELECT "video"."id" AS "id" FROM "video" ' +
177 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
178 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
179 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
180 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
181 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
185 privacy: VideoPrivacy.PUBLIC
187 include: [ videoChannelInclude ]
190 if (options.withFiles === true) {
192 model: VideoFileModel.unscoped(),
198 if (options.hideNSFW === true) {
199 query.where['nsfw'] = false
202 if (options.accountId) {
203 accountInclude.where = {
204 id: options.accountId
208 if (options.videoChannelId) {
209 videoChannelInclude.where = {
210 id: options.videoChannelId
216 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
219 model: () => VideoChannelModel.unscoped(),
224 exclude: [ 'privateKey', 'publicKey' ]
226 model: () => ActorModel.unscoped(),
230 attributes: [ 'host' ],
231 model: () => ServerModel.unscoped(),
237 model: () => AccountModel.unscoped(),
241 model: () => ActorModel.unscoped(),
243 exclude: [ 'privateKey', 'publicKey' ]
248 attributes: [ 'host' ],
249 model: () => ServerModel.unscoped(),
253 model: () => AvatarModel.unscoped(),
264 [ScopeNames.WITH_TAGS]: {
265 include: [ () => TagModel ]
267 [ScopeNames.WITH_FILES]: {
270 model: () => VideoFileModel.unscoped(),
275 [ScopeNames.WITH_SHARES]: {
278 ['separate' as any]: true,
279 model: () => VideoShareModel.unscoped()
283 [ScopeNames.WITH_RATES]: {
286 ['separate' as any]: true,
287 model: () => AccountVideoRateModel,
290 model: () => AccountModel.unscoped(),
294 attributes: [ 'url' ],
295 model: () => ActorModel.unscoped()
303 [ScopeNames.WITH_COMMENTS]: {
306 ['separate' as any]: true,
307 model: () => VideoCommentModel.unscoped()
319 fields: [ 'createdAt' ]
322 fields: [ 'duration' ]
334 fields: [ 'channelId' ]
337 fields: [ 'id', 'privacy' ]
345 export class VideoModel extends Model<VideoModel> {
348 @Default(DataType.UUIDV4)
350 @Column(DataType.UUID)
354 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
360 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
366 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
372 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
373 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
377 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
382 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
388 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
389 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
394 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
395 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
399 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
429 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
430 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
435 commentsEnabled: boolean
444 @Default(Sequelize.NOW)
448 @ForeignKey(() => VideoChannelModel)
452 @BelongsTo(() => VideoChannelModel, {
458 VideoChannel: VideoChannelModel
460 @BelongsToMany(() => TagModel, {
461 foreignKey: 'videoId',
462 through: () => VideoTagModel,
467 @HasMany(() => VideoAbuseModel, {
474 VideoAbuses: VideoAbuseModel[]
476 @HasMany(() => VideoFileModel, {
483 VideoFiles: VideoFileModel[]
485 @HasMany(() => VideoShareModel, {
492 VideoShares: VideoShareModel[]
494 @HasMany(() => AccountVideoRateModel, {
501 AccountVideoRates: AccountVideoRateModel[]
503 @HasMany(() => VideoCommentModel, {
511 VideoComments: VideoCommentModel[]
514 static async sendDelete (instance: VideoModel, options) {
515 if (instance.isOwned()) {
516 if (!instance.VideoChannel) {
517 instance.VideoChannel = await instance.$get('VideoChannel', {
521 include: [ ActorModel ]
524 transaction: options.transaction
525 }) as VideoChannelModel
528 logger.debug('Sending delete of video %s.', instance.url)
530 return sendDeleteVideo(instance, options.transaction)
537 static async removeFilesAndSendDelete (instance: VideoModel) {
538 const tasks: Promise<any>[] = []
540 logger.debug('Removing files of video %s.', instance.url)
542 tasks.push(instance.removeThumbnail())
544 if (instance.isOwned()) {
545 if (!Array.isArray(instance.VideoFiles)) {
546 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
549 tasks.push(instance.removePreview())
551 // Remove physical files and torrents
552 instance.VideoFiles.forEach(file => {
553 tasks.push(instance.removeFile(file))
554 tasks.push(instance.removeTorrent(file))
558 // Do not wait video deletion because we could be in a transaction
561 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
568 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
571 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
572 function getRawQuery (select: string) {
573 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
574 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
575 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
576 'WHERE "Account"."actorId" = ' + actorId
577 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
578 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
579 'WHERE "VideoShare"."actorId" = ' + actorId
581 return `(${queryVideo}) UNION (${queryVideoShare})`
584 const rawQuery = getRawQuery('"Video"."id"')
585 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
591 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
594 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
597 { privacy: VideoPrivacy.PUBLIC },
598 { privacy: VideoPrivacy.UNLISTED }
603 attributes: [ 'id', 'url' ],
604 model: VideoShareModel.unscoped(),
606 // We only want videos shared by this actor
608 [Sequelize.Op.and]: [
611 [Sequelize.Op.not]: null
621 attributes: [ 'id', 'url' ],
622 model: ActorModel.unscoped()
627 model: VideoChannelModel.unscoped(),
631 attributes: [ 'name' ],
632 model: AccountModel.unscoped(),
636 attributes: [ 'id', 'url', 'followersUrl' ],
637 model: ActorModel.unscoped(),
643 attributes: [ 'id', 'url', 'followersUrl' ],
644 model: ActorModel.unscoped(),
654 return Bluebird.all([
655 // FIXME: typing issue
656 VideoModel.findAll(query as any),
657 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
658 ]).then(([ rows, totals ]) => {
659 // totals: totalVideos + totalVideoShares
661 let totalVideoShares = 0
662 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
663 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
665 const total = totalVideos + totalVideoShares
673 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
674 const query: IFindOptions<VideoModel> = {
677 order: getSort(sort),
680 model: VideoChannelModel,
695 if (withFiles === true) {
697 model: VideoFileModel.unscoped(),
702 if (hideNSFW === true) {
708 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
716 static async listForApi (options: {
722 filter?: VideoFilter,
724 videoChannelId?: number
727 offset: options.start,
728 limit: options.count,
729 order: getSort(options.sort)
732 const serverActor = await getServerActor()
735 ScopeNames.AVAILABLE_FOR_LIST, {
736 actorId: serverActor.id,
737 hideNSFW: options.hideNSFW,
738 filter: options.filter,
739 withFiles: options.withFiles,
740 accountId: options.accountId,
741 videoChannelId: options.videoChannelId
746 return VideoModel.scope(scopes)
747 .findAndCountAll(query)
748 .then(({ rows, count }) => {
756 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
757 const query: IFindOptions<VideoModel> = {
760 order: getSort(sort),
765 [ Sequelize.Op.iLike ]: '%' + value + '%'
769 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
770 [ Sequelize.Op.iLike ]: '%' + value + '%'
774 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
775 [ Sequelize.Op.iLike ]: '%' + value + '%'
779 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
780 [ Sequelize.Op.iLike ]: '%' + value + '%'
787 const serverActor = await getServerActor()
790 ScopeNames.AVAILABLE_FOR_LIST, {
791 actorId: serverActor.id,
797 return VideoModel.scope(scopes)
798 .findAndCountAll(query)
799 .then(({ rows, count }) => {
807 static load (id: number) {
808 return VideoModel.findById(id)
811 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
812 const query: IFindOptions<VideoModel> = {
818 if (t !== undefined) query.transaction = t
820 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
823 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
824 const query: IFindOptions<VideoModel> = {
833 if (t !== undefined) query.transaction = t
835 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
838 static loadAndPopulateAccountAndServerAndTags (id: number) {
840 order: [ [ 'Tags', 'name', 'ASC' ] ]
844 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
845 .findById(id, options)
848 static loadByUUID (uuid: string) {
856 .scope([ ScopeNames.WITH_FILES ])
860 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
862 order: [ [ 'Tags', 'name', 'ASC' ] ],
869 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
873 static async getStats () {
874 const totalLocalVideos = await VideoModel.count({
879 const totalVideos = await VideoModel.count()
881 let totalLocalVideoViews = await VideoModel.sum('views', {
886 // Sequelize could return null...
887 if (!totalLocalVideoViews) totalLocalVideoViews = 0
891 totalLocalVideoViews,
896 private static buildActorWhereWithFilter (filter?: VideoFilter) {
897 if (filter && filter === 'local') {
906 private static getCategoryLabel (id: number) {
907 let categoryLabel = VIDEO_CATEGORIES[id]
908 if (!categoryLabel) categoryLabel = 'Misc'
913 private static getLicenceLabel (id: number) {
914 let licenceLabel = VIDEO_LICENCES[id]
915 if (!licenceLabel) licenceLabel = 'Unknown'
920 private static getLanguageLabel (id: string) {
921 let languageLabel = VIDEO_LANGUAGES[id]
922 if (!languageLabel) languageLabel = 'Unknown'
927 private static getPrivacyLabel (id: number) {
928 let privacyLabel = VIDEO_PRIVACIES[id]
929 if (!privacyLabel) privacyLabel = 'Unknown'
935 if (Array.isArray(this.VideoFiles) === false) return undefined
937 // The original file is the file that have the higher resolution
938 return maxBy(this.VideoFiles, file => file.resolution)
941 getVideoFilename (videoFile: VideoFileModel) {
942 return this.uuid + '-' + videoFile.resolution + videoFile.extname
945 getThumbnailName () {
946 // We always have a copy of the thumbnail
947 const extension = '.jpg'
948 return this.uuid + extension
952 const extension = '.jpg'
953 return this.uuid + extension
956 getTorrentFileName (videoFile: VideoFileModel) {
957 const extension = '.torrent'
958 return this.uuid + '-' + videoFile.resolution + extension
962 return this.remote === false
965 createPreview (videoFile: VideoFileModel) {
966 return generateImageFromVideoFile(
967 this.getVideoFilePath(videoFile),
968 CONFIG.STORAGE.PREVIEWS_DIR,
969 this.getPreviewName(),
974 createThumbnail (videoFile: VideoFileModel) {
975 return generateImageFromVideoFile(
976 this.getVideoFilePath(videoFile),
977 CONFIG.STORAGE.THUMBNAILS_DIR,
978 this.getThumbnailName(),
983 getTorrentFilePath (videoFile: VideoFileModel) {
984 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
987 getVideoFilePath (videoFile: VideoFileModel) {
988 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
991 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
993 // Keep the extname, it's used by the client to stream the file inside a web browser
994 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
995 createdBy: 'PeerTube',
997 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
998 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1001 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1005 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1007 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1008 logger.info('Creating torrent %s.', filePath)
1010 await writeFilePromise(filePath, torrent)
1012 const parsedTorrent = parseTorrent(torrent)
1013 videoFile.infoHash = parsedTorrent.infoHash
1017 return '/videos/embed/' + this.uuid
1020 getThumbnailPath () {
1021 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1025 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1028 toFormattedJSON (): Video {
1029 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1030 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1038 label: VideoModel.getCategoryLabel(this.category)
1042 label: VideoModel.getLicenceLabel(this.licence)
1046 label: VideoModel.getLanguageLabel(this.language)
1050 label: VideoModel.getPrivacyLabel(this.privacy)
1053 description: this.getTruncatedDescription(),
1054 isLocal: this.isOwned(),
1055 duration: this.duration,
1058 dislikes: this.dislikes,
1059 thumbnailPath: this.getThumbnailPath(),
1060 previewPath: this.getPreviewPath(),
1061 embedPath: this.getEmbedPath(),
1062 createdAt: this.createdAt,
1063 updatedAt: this.updatedAt,
1064 publishedAt: this.publishedAt,
1066 id: formattedAccount.id,
1067 uuid: formattedAccount.uuid,
1068 name: formattedAccount.name,
1069 displayName: formattedAccount.displayName,
1070 url: formattedAccount.url,
1071 host: formattedAccount.host,
1072 avatar: formattedAccount.avatar
1075 id: formattedVideoChannel.id,
1076 uuid: formattedVideoChannel.uuid,
1077 name: formattedVideoChannel.name,
1078 displayName: formattedVideoChannel.displayName,
1079 url: formattedVideoChannel.url,
1080 host: formattedVideoChannel.host,
1081 avatar: formattedVideoChannel.avatar
1086 toFormattedDetailsJSON (): VideoDetails {
1087 const formattedJson = this.toFormattedJSON()
1089 const detailsJson = {
1090 support: this.support,
1091 descriptionPath: this.getDescriptionPath(),
1092 channel: this.VideoChannel.toFormattedJSON(),
1093 account: this.VideoChannel.Account.toFormattedJSON(),
1094 tags: map(this.Tags, 'name'),
1095 commentsEnabled: this.commentsEnabled,
1099 // Format and sort video files
1100 detailsJson.files = this.getFormattedVideoFilesJSON()
1102 return Object.assign(formattedJson, detailsJson)
1105 getFormattedVideoFilesJSON (): VideoFile[] {
1106 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1108 return this.VideoFiles
1110 let resolutionLabel = videoFile.resolution + 'p'
1114 id: videoFile.resolution,
1115 label: resolutionLabel
1117 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1118 size: videoFile.size,
1119 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1120 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1121 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1122 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1126 if (a.resolution.id < b.resolution.id) return 1
1127 if (a.resolution.id === b.resolution.id) return 0
1132 toActivityPubObject (): VideoTorrentObject {
1133 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1134 if (!this.Tags) this.Tags = []
1136 const tag = this.Tags.map(t => ({
1137 type: 'Hashtag' as 'Hashtag',
1142 if (this.language) {
1144 identifier: this.language,
1145 name: VideoModel.getLanguageLabel(this.language)
1150 if (this.category) {
1152 identifier: this.category + '',
1153 name: VideoModel.getCategoryLabel(this.category)
1160 identifier: this.licence + '',
1161 name: VideoModel.getLicenceLabel(this.licence)
1166 for (const file of this.VideoFiles) {
1169 mimeType: 'video/' + file.extname.replace('.', ''),
1170 href: this.getVideoFileUrl(file, baseUrlHttp),
1171 width: file.resolution,
1177 mimeType: 'application/x-bittorrent',
1178 href: this.getTorrentUrl(file, baseUrlHttp),
1179 width: file.resolution
1184 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1185 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1186 width: file.resolution
1190 // Add video url too
1193 mimeType: 'text/html',
1194 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1198 type: 'Video' as 'Video',
1201 duration: this.getActivityStreamDuration(),
1208 sensitive: this.nsfw,
1209 commentsEnabled: this.commentsEnabled,
1210 published: this.publishedAt.toISOString(),
1211 updated: this.updatedAt.toISOString(),
1212 mediaType: 'text/markdown',
1213 content: this.getTruncatedDescription(),
1214 support: this.support,
1217 url: this.getThumbnailUrl(baseUrlHttp),
1218 mediaType: 'image/jpeg',
1219 width: THUMBNAILS_SIZE.width,
1220 height: THUMBNAILS_SIZE.height
1223 likes: getVideoLikesActivityPubUrl(this),
1224 dislikes: getVideoDislikesActivityPubUrl(this),
1225 shares: getVideoSharesActivityPubUrl(this),
1226 comments: getVideoCommentsActivityPubUrl(this),
1230 id: this.VideoChannel.Account.Actor.url
1234 id: this.VideoChannel.Actor.url
1240 getTruncatedDescription () {
1241 if (!this.description) return null
1243 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1244 return peertubeTruncate(this.description, maxLength)
1247 async optimizeOriginalVideofile () {
1248 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1249 const newExtname = '.mp4'
1250 const inputVideoFile = this.getOriginalFile()
1251 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1252 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1254 const transcodeOptions = {
1255 inputPath: videoInputPath,
1256 outputPath: videoOutputPath
1259 // Could be very long!
1260 await transcode(transcodeOptions)
1263 await unlinkPromise(videoInputPath)
1265 // Important to do this before getVideoFilename() to take in account the new file extension
1266 inputVideoFile.set('extname', newExtname)
1268 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1269 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1271 inputVideoFile.set('size', stats.size)
1273 await this.createTorrentAndSetInfoHash(inputVideoFile)
1274 await inputVideoFile.save()
1277 // Auto destruction...
1278 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1284 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1285 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1286 const extname = '.mp4'
1288 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1289 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1291 const newVideoFile = new VideoFileModel({
1297 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1299 const transcodeOptions = {
1300 inputPath: videoInputPath,
1301 outputPath: videoOutputPath,
1306 await transcode(transcodeOptions)
1308 const stats = await statPromise(videoOutputPath)
1310 newVideoFile.set('size', stats.size)
1312 await this.createTorrentAndSetInfoHash(newVideoFile)
1314 await newVideoFile.save()
1316 this.VideoFiles.push(newVideoFile)
1319 async importVideoFile (inputFilePath: string) {
1320 let updatedVideoFile = new VideoFileModel({
1321 resolution: (await getVideoFileResolution(inputFilePath)).videoFileResolution,
1322 extname: extname(inputFilePath),
1323 size: (await statPromise(inputFilePath)).size,
1327 const outputPath = this.getVideoFilePath(updatedVideoFile)
1328 await copyFilePromise(inputFilePath, outputPath)
1330 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1331 const isNewVideoFile = !currentVideoFile
1333 if (!isNewVideoFile) {
1334 if (currentVideoFile.extname !== updatedVideoFile.extname) {
1335 await this.removeFile(currentVideoFile)
1336 currentVideoFile.set('extname', updatedVideoFile.extname)
1338 currentVideoFile.set('size', updatedVideoFile.size)
1339 updatedVideoFile = currentVideoFile
1342 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1344 await updatedVideoFile.save()
1346 if (isNewVideoFile) {
1347 this.VideoFiles.push(updatedVideoFile)
1351 getOriginalFileResolution () {
1352 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1354 return getVideoFileResolution(originalFilePath)
1357 getDescriptionPath () {
1358 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1361 removeThumbnail () {
1362 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1363 return unlinkPromise(thumbnailPath)
1367 // Same name than video thumbnail
1368 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1371 removeFile (videoFile: VideoFileModel) {
1372 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1373 return unlinkPromise(filePath)
1376 removeTorrent (videoFile: VideoFileModel) {
1377 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1378 return unlinkPromise(torrentPath)
1381 getActivityStreamDuration () {
1382 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1383 return 'PT' + this.duration + 'S'
1386 private getBaseUrls () {
1390 if (this.isOwned()) {
1391 baseUrlHttp = CONFIG.WEBSERVER.URL
1392 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1394 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1395 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1398 return { baseUrlHttp, baseUrlWs }
1401 private getThumbnailUrl (baseUrlHttp: string) {
1402 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1405 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1406 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1409 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1410 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1413 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1414 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1417 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1418 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1421 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1422 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1423 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1424 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1426 const magnetHash = {
1430 infoHash: videoFile.infoHash,
1434 return magnetUtil.encode(magnetHash)