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 } 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'
32 import { activityPubCollectionPagination } from '../../helpers/activitypub'
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'
68 } from '../../initializers'
70 getVideoCommentsActivityPubUrl,
71 getVideoDislikesActivityPubUrl,
72 getVideoLikesActivityPubUrl,
73 getVideoSharesActivityPubUrl
74 } from '../../lib/activitypub'
75 import { sendDeleteVideo } from '../../lib/activitypub/send'
76 import { AccountModel } from '../account/account'
77 import { AccountVideoRateModel } from '../account/account-video-rate'
78 import { ActorModel } from '../activitypub/actor'
79 import { AvatarModel } from '../avatar/avatar'
80 import { ServerModel } from '../server/server'
81 import { getSort, throwIfNotValid } from '../utils'
82 import { TagModel } from './tag'
83 import { VideoAbuseModel } from './video-abuse'
84 import { VideoChannelModel } from './video-channel'
85 import { VideoCommentModel } from './video-comment'
86 import { VideoFileModel } from './video-file'
87 import { VideoShareModel } from './video-share'
88 import { VideoTagModel } from './video-tag'
91 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
92 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
93 WITH_TAGS = 'WITH_TAGS',
94 WITH_FILES = 'WITH_FILES',
95 WITH_SHARES = 'WITH_SHARES',
96 WITH_RATES = 'WITH_RATES',
97 WITH_COMMENTS = 'WITH_COMMENTS'
101 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
104 filter?: VideoFilter,
107 videoChannelId?: number
109 const accountInclude = {
110 attributes: [ 'id', 'name' ],
111 model: AccountModel.unscoped(),
116 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
117 model: ActorModel.unscoped(),
119 where: VideoModel.buildActorWhereWithFilter(options.filter),
122 attributes: [ 'host' ],
123 model: ServerModel.unscoped(),
127 model: AvatarModel.unscoped(),
135 const videoChannelInclude = {
136 attributes: [ 'name', 'description', 'id' ],
137 model: VideoChannelModel.unscoped(),
142 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
143 model: ActorModel.unscoped(),
147 attributes: [ 'host' ],
148 model: ServerModel.unscoped(),
152 model: AvatarModel.unscoped(),
161 // Force actorId to be a number to avoid SQL injections
162 const actorIdNumber = parseInt(options.actorId.toString(), 10)
163 const query: IFindOptions<VideoModel> = {
166 [Sequelize.Op.notIn]: Sequelize.literal(
167 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
169 [ Sequelize.Op.in ]: Sequelize.literal(
171 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
172 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
173 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
175 'SELECT "video"."id" AS "id" FROM "video" ' +
176 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
177 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
178 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
179 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
180 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
184 privacy: VideoPrivacy.PUBLIC
186 include: [ videoChannelInclude ]
189 if (options.withFiles === true) {
191 model: VideoFileModel.unscoped(),
197 if (options.hideNSFW === true) {
198 query.where['nsfw'] = false
201 if (options.accountId) {
202 accountInclude.where = {
203 id: options.accountId
207 if (options.videoChannelId) {
208 videoChannelInclude.where = {
209 id: options.videoChannelId
215 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
218 model: () => VideoChannelModel.unscoped(),
223 exclude: [ 'privateKey', 'publicKey' ]
225 model: () => ActorModel.unscoped(),
229 attributes: [ 'host' ],
230 model: () => ServerModel.unscoped(),
236 model: () => AccountModel.unscoped(),
240 model: () => ActorModel.unscoped(),
242 exclude: [ 'privateKey', 'publicKey' ]
247 attributes: [ 'host' ],
248 model: () => ServerModel.unscoped(),
252 model: () => AvatarModel.unscoped(),
263 [ScopeNames.WITH_TAGS]: {
264 include: [ () => TagModel ]
266 [ScopeNames.WITH_FILES]: {
269 model: () => VideoFileModel.unscoped(),
274 [ScopeNames.WITH_SHARES]: {
277 ['separate' as any]: true,
278 model: () => VideoShareModel.unscoped()
282 [ScopeNames.WITH_RATES]: {
285 ['separate' as any]: true,
286 model: () => AccountVideoRateModel,
289 model: () => AccountModel.unscoped(),
293 attributes: [ 'url' ],
294 model: () => ActorModel.unscoped()
302 [ScopeNames.WITH_COMMENTS]: {
305 ['separate' as any]: true,
306 model: () => VideoCommentModel.unscoped()
318 fields: [ 'createdAt' ]
321 fields: [ 'duration' ]
333 fields: [ 'channelId' ]
336 fields: [ 'id', 'privacy' ]
344 export class VideoModel extends Model<VideoModel> {
347 @Default(DataType.UUIDV4)
349 @Column(DataType.UUID)
353 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
359 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
365 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
371 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
372 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
376 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
381 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
387 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
388 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
393 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
394 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
398 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
428 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
429 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
434 commentsEnabled: boolean
443 @Default(Sequelize.NOW)
447 @ForeignKey(() => VideoChannelModel)
451 @BelongsTo(() => VideoChannelModel, {
457 VideoChannel: VideoChannelModel
459 @BelongsToMany(() => TagModel, {
460 foreignKey: 'videoId',
461 through: () => VideoTagModel,
466 @HasMany(() => VideoAbuseModel, {
473 VideoAbuses: VideoAbuseModel[]
475 @HasMany(() => VideoFileModel, {
482 VideoFiles: VideoFileModel[]
484 @HasMany(() => VideoShareModel, {
491 VideoShares: VideoShareModel[]
493 @HasMany(() => AccountVideoRateModel, {
500 AccountVideoRates: AccountVideoRateModel[]
502 @HasMany(() => VideoCommentModel, {
510 VideoComments: VideoCommentModel[]
513 static async sendDelete (instance: VideoModel, options) {
514 if (instance.isOwned()) {
515 if (!instance.VideoChannel) {
516 instance.VideoChannel = await instance.$get('VideoChannel', {
520 include: [ ActorModel ]
523 transaction: options.transaction
524 }) as VideoChannelModel
527 logger.debug('Sending delete of video %s.', instance.url)
529 return sendDeleteVideo(instance, options.transaction)
536 static async removeFilesAndSendDelete (instance: VideoModel) {
537 const tasks: Promise<any>[] = []
539 logger.debug('Removing files of video %s.', instance.url)
541 tasks.push(instance.removeThumbnail())
543 if (instance.isOwned()) {
544 if (!Array.isArray(instance.VideoFiles)) {
545 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
548 tasks.push(instance.removePreview())
550 // Remove physical files and torrents
551 instance.VideoFiles.forEach(file => {
552 tasks.push(instance.removeFile(file))
553 tasks.push(instance.removeTorrent(file))
557 // Do not wait video deletion because we could be in a transaction
560 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
567 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
570 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
571 function getRawQuery (select: string) {
572 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
573 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
574 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
575 'WHERE "Account"."actorId" = ' + actorId
576 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
577 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
578 'WHERE "VideoShare"."actorId" = ' + actorId
580 return `(${queryVideo}) UNION (${queryVideoShare})`
583 const rawQuery = getRawQuery('"Video"."id"')
584 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
590 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
593 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
596 { privacy: VideoPrivacy.PUBLIC },
597 { privacy: VideoPrivacy.UNLISTED }
602 attributes: [ 'id', 'url' ],
603 model: VideoShareModel.unscoped(),
605 // We only want videos shared by this actor
607 [Sequelize.Op.and]: [
610 [Sequelize.Op.not]: null
620 attributes: [ 'id', 'url' ],
621 model: ActorModel.unscoped()
626 model: VideoChannelModel.unscoped(),
630 attributes: [ 'name' ],
631 model: AccountModel.unscoped(),
635 attributes: [ 'id', 'url', 'followersUrl' ],
636 model: ActorModel.unscoped(),
642 attributes: [ 'id', 'url', 'followersUrl' ],
643 model: ActorModel.unscoped(),
653 return Bluebird.all([
654 // FIXME: typing issue
655 VideoModel.findAll(query as any),
656 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
657 ]).then(([ rows, totals ]) => {
658 // totals: totalVideos + totalVideoShares
660 let totalVideoShares = 0
661 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
662 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
664 const total = totalVideos + totalVideoShares
672 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
673 const query: IFindOptions<VideoModel> = {
676 order: getSort(sort),
679 model: VideoChannelModel,
694 if (withFiles === true) {
696 model: VideoFileModel.unscoped(),
701 if (hideNSFW === true) {
707 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
715 static async listForApi (options: {
721 filter?: VideoFilter,
723 videoChannelId?: number
726 offset: options.start,
727 limit: options.count,
728 order: getSort(options.sort)
731 const serverActor = await getServerActor()
734 ScopeNames.AVAILABLE_FOR_LIST, {
735 actorId: serverActor.id,
736 hideNSFW: options.hideNSFW,
737 filter: options.filter,
738 withFiles: options.withFiles,
739 accountId: options.accountId,
740 videoChannelId: options.videoChannelId
745 return VideoModel.scope(scopes)
746 .findAndCountAll(query)
747 .then(({ rows, count }) => {
755 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
756 const query: IFindOptions<VideoModel> = {
759 order: getSort(sort),
764 [ Sequelize.Op.iLike ]: '%' + value + '%'
768 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
769 [ Sequelize.Op.iLike ]: '%' + value + '%'
773 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
774 [ Sequelize.Op.iLike ]: '%' + value + '%'
778 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
779 [ Sequelize.Op.iLike ]: '%' + value + '%'
786 const serverActor = await getServerActor()
789 ScopeNames.AVAILABLE_FOR_LIST, {
790 actorId: serverActor.id,
796 return VideoModel.scope(scopes)
797 .findAndCountAll(query)
798 .then(({ rows, count }) => {
806 static load (id: number) {
807 return VideoModel.findById(id)
810 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
811 const query: IFindOptions<VideoModel> = {
817 if (t !== undefined) query.transaction = t
819 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
822 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
823 const query: IFindOptions<VideoModel> = {
832 if (t !== undefined) query.transaction = t
834 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
837 static loadAndPopulateAccountAndServerAndTags (id: number) {
839 order: [ [ 'Tags', 'name', 'ASC' ] ]
843 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
844 .findById(id, options)
847 static loadByUUID (uuid: string) {
855 .scope([ ScopeNames.WITH_FILES ])
859 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
861 order: [ [ 'Tags', 'name', 'ASC' ] ],
868 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
872 static async getStats () {
873 const totalLocalVideos = await VideoModel.count({
878 const totalVideos = await VideoModel.count()
880 let totalLocalVideoViews = await VideoModel.sum('views', {
885 // Sequelize could return null...
886 if (!totalLocalVideoViews) totalLocalVideoViews = 0
890 totalLocalVideoViews,
895 private static buildActorWhereWithFilter (filter?: VideoFilter) {
896 if (filter && filter === 'local') {
905 private static getCategoryLabel (id: number) {
906 let categoryLabel = VIDEO_CATEGORIES[id]
907 if (!categoryLabel) categoryLabel = 'Misc'
912 private static getLicenceLabel (id: number) {
913 let licenceLabel = VIDEO_LICENCES[id]
914 if (!licenceLabel) licenceLabel = 'Unknown'
919 private static getLanguageLabel (id: string) {
920 let languageLabel = VIDEO_LANGUAGES[id]
921 if (!languageLabel) languageLabel = 'Unknown'
926 private static getPrivacyLabel (id: number) {
927 let privacyLabel = VIDEO_PRIVACIES[id]
928 if (!privacyLabel) privacyLabel = 'Unknown'
934 if (Array.isArray(this.VideoFiles) === false) return undefined
936 // The original file is the file that have the higher resolution
937 return maxBy(this.VideoFiles, file => file.resolution)
940 getVideoFilename (videoFile: VideoFileModel) {
941 return this.uuid + '-' + videoFile.resolution + videoFile.extname
944 getThumbnailName () {
945 // We always have a copy of the thumbnail
946 const extension = '.jpg'
947 return this.uuid + extension
951 const extension = '.jpg'
952 return this.uuid + extension
955 getTorrentFileName (videoFile: VideoFileModel) {
956 const extension = '.torrent'
957 return this.uuid + '-' + videoFile.resolution + extension
961 return this.remote === false
964 createPreview (videoFile: VideoFileModel) {
965 return generateImageFromVideoFile(
966 this.getVideoFilePath(videoFile),
967 CONFIG.STORAGE.PREVIEWS_DIR,
968 this.getPreviewName(),
973 createThumbnail (videoFile: VideoFileModel) {
974 return generateImageFromVideoFile(
975 this.getVideoFilePath(videoFile),
976 CONFIG.STORAGE.THUMBNAILS_DIR,
977 this.getThumbnailName(),
982 getVideoFilePath (videoFile: VideoFileModel) {
983 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
986 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
988 // Keep the extname, it's used by the client to stream the file inside a web browser
989 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
990 createdBy: 'PeerTube',
992 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
993 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
996 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1000 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1002 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1003 logger.info('Creating torrent %s.', filePath)
1005 await writeFilePromise(filePath, torrent)
1007 const parsedTorrent = parseTorrent(torrent)
1008 videoFile.infoHash = parsedTorrent.infoHash
1012 return '/videos/embed/' + this.uuid
1015 getThumbnailPath () {
1016 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1020 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1023 toFormattedJSON (): Video {
1024 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1025 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1033 label: VideoModel.getCategoryLabel(this.category)
1037 label: VideoModel.getLicenceLabel(this.licence)
1041 label: VideoModel.getLanguageLabel(this.language)
1045 label: VideoModel.getPrivacyLabel(this.privacy)
1048 description: this.getTruncatedDescription(),
1049 isLocal: this.isOwned(),
1050 duration: this.duration,
1053 dislikes: this.dislikes,
1054 thumbnailPath: this.getThumbnailPath(),
1055 previewPath: this.getPreviewPath(),
1056 embedPath: this.getEmbedPath(),
1057 createdAt: this.createdAt,
1058 updatedAt: this.updatedAt,
1059 publishedAt: this.publishedAt,
1061 id: formattedAccount.id,
1062 uuid: formattedAccount.uuid,
1063 name: formattedAccount.name,
1064 displayName: formattedAccount.displayName,
1065 url: formattedAccount.url,
1066 host: formattedAccount.host,
1067 avatar: formattedAccount.avatar
1070 id: formattedVideoChannel.id,
1071 uuid: formattedVideoChannel.uuid,
1072 name: formattedVideoChannel.name,
1073 displayName: formattedVideoChannel.displayName,
1074 url: formattedVideoChannel.url,
1075 host: formattedVideoChannel.host,
1076 avatar: formattedVideoChannel.avatar
1081 toFormattedDetailsJSON (): VideoDetails {
1082 const formattedJson = this.toFormattedJSON()
1084 const detailsJson = {
1085 support: this.support,
1086 descriptionPath: this.getDescriptionPath(),
1087 channel: this.VideoChannel.toFormattedJSON(),
1088 account: this.VideoChannel.Account.toFormattedJSON(),
1089 tags: map(this.Tags, 'name'),
1090 commentsEnabled: this.commentsEnabled,
1094 // Format and sort video files
1095 detailsJson.files = this.getFormattedVideoFilesJSON()
1097 return Object.assign(formattedJson, detailsJson)
1100 getFormattedVideoFilesJSON (): VideoFile[] {
1101 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1103 return this.VideoFiles
1105 let resolutionLabel = videoFile.resolution + 'p'
1109 id: videoFile.resolution,
1110 label: resolutionLabel
1112 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1113 size: videoFile.size,
1114 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1115 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
1119 if (a.resolution.id < b.resolution.id) return 1
1120 if (a.resolution.id === b.resolution.id) return 0
1125 toActivityPubObject (): VideoTorrentObject {
1126 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1127 if (!this.Tags) this.Tags = []
1129 const tag = this.Tags.map(t => ({
1130 type: 'Hashtag' as 'Hashtag',
1135 if (this.language) {
1137 identifier: this.language,
1138 name: VideoModel.getLanguageLabel(this.language)
1143 if (this.category) {
1145 identifier: this.category + '',
1146 name: VideoModel.getCategoryLabel(this.category)
1153 identifier: this.licence + '',
1154 name: VideoModel.getLicenceLabel(this.licence)
1159 for (const file of this.VideoFiles) {
1162 mimeType: 'video/' + file.extname.replace('.', ''),
1163 href: this.getVideoFileUrl(file, baseUrlHttp),
1164 width: file.resolution,
1170 mimeType: 'application/x-bittorrent',
1171 href: this.getTorrentUrl(file, baseUrlHttp),
1172 width: file.resolution
1177 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1178 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1179 width: file.resolution
1183 // Add video url too
1186 mimeType: 'text/html',
1187 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1191 type: 'Video' as 'Video',
1194 duration: this.getActivityStreamDuration(),
1201 sensitive: this.nsfw,
1202 commentsEnabled: this.commentsEnabled,
1203 published: this.publishedAt.toISOString(),
1204 updated: this.updatedAt.toISOString(),
1205 mediaType: 'text/markdown',
1206 content: this.getTruncatedDescription(),
1207 support: this.support,
1210 url: this.getThumbnailUrl(baseUrlHttp),
1211 mediaType: 'image/jpeg',
1212 width: THUMBNAILS_SIZE.width,
1213 height: THUMBNAILS_SIZE.height
1216 likes: getVideoLikesActivityPubUrl(this),
1217 dislikes: getVideoDislikesActivityPubUrl(this),
1218 shares: getVideoSharesActivityPubUrl(this),
1219 comments: getVideoCommentsActivityPubUrl(this),
1223 id: this.VideoChannel.Account.Actor.url
1227 id: this.VideoChannel.Actor.url
1233 getTruncatedDescription () {
1234 if (!this.description) return null
1236 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1237 return peertubeTruncate(this.description, maxLength)
1240 async optimizeOriginalVideofile () {
1241 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1242 const newExtname = '.mp4'
1243 const inputVideoFile = this.getOriginalFile()
1244 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1245 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1247 const transcodeOptions = {
1248 inputPath: videoInputPath,
1249 outputPath: videoOutputPath
1252 // Could be very long!
1253 await transcode(transcodeOptions)
1256 await unlinkPromise(videoInputPath)
1258 // Important to do this before getVideoFilename() to take in account the new file extension
1259 inputVideoFile.set('extname', newExtname)
1261 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1262 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1264 inputVideoFile.set('size', stats.size)
1266 await this.createTorrentAndSetInfoHash(inputVideoFile)
1267 await inputVideoFile.save()
1270 // Auto destruction...
1271 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1277 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1278 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1279 const extname = '.mp4'
1281 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1282 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1284 const newVideoFile = new VideoFileModel({
1290 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1292 const transcodeOptions = {
1293 inputPath: videoInputPath,
1294 outputPath: videoOutputPath,
1299 await transcode(transcodeOptions)
1301 const stats = await statPromise(videoOutputPath)
1303 newVideoFile.set('size', stats.size)
1305 await this.createTorrentAndSetInfoHash(newVideoFile)
1307 await newVideoFile.save()
1309 this.VideoFiles.push(newVideoFile)
1312 getOriginalFileResolution () {
1313 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1315 return getVideoFileResolution(originalFilePath)
1318 getDescriptionPath () {
1319 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1322 removeThumbnail () {
1323 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1324 return unlinkPromise(thumbnailPath)
1328 // Same name than video thumbnail
1329 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1332 removeFile (videoFile: VideoFileModel) {
1333 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1334 return unlinkPromise(filePath)
1337 removeTorrent (videoFile: VideoFileModel) {
1338 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1339 return unlinkPromise(torrentPath)
1342 getActivityStreamDuration () {
1343 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1344 return 'PT' + this.duration + 'S'
1347 private getBaseUrls () {
1351 if (this.isOwned()) {
1352 baseUrlHttp = CONFIG.WEBSERVER.URL
1353 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1355 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1356 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1359 return { baseUrlHttp, baseUrlWs }
1362 private getThumbnailUrl (baseUrlHttp: string) {
1363 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1366 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1367 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1370 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1371 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1374 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1375 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1376 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1377 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1379 const magnetHash = {
1383 infoHash: videoFile.infoHash,
1387 return magnetUtil.encode(magnetHash)