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'
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,
70 } from '../../initializers'
72 getVideoCommentsActivityPubUrl,
73 getVideoDislikesActivityPubUrl,
74 getVideoLikesActivityPubUrl,
75 getVideoSharesActivityPubUrl
76 } from '../../lib/activitypub'
77 import { sendDeleteVideo } from '../../lib/activitypub/send'
78 import { AccountModel } from '../account/account'
79 import { AccountVideoRateModel } from '../account/account-video-rate'
80 import { ActorModel } from '../activitypub/actor'
81 import { AvatarModel } from '../avatar/avatar'
82 import { ServerModel } from '../server/server'
83 import { getSort, throwIfNotValid } from '../utils'
84 import { TagModel } from './tag'
85 import { VideoAbuseModel } from './video-abuse'
86 import { VideoChannelModel } from './video-channel'
87 import { VideoCommentModel } from './video-comment'
88 import { VideoFileModel } from './video-file'
89 import { VideoShareModel } from './video-share'
90 import { VideoTagModel } from './video-tag'
93 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
94 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
95 WITH_TAGS = 'WITH_TAGS',
96 WITH_FILES = 'WITH_FILES',
97 WITH_SHARES = 'WITH_SHARES',
98 WITH_RATES = 'WITH_RATES',
99 WITH_COMMENTS = 'WITH_COMMENTS'
103 [ScopeNames.AVAILABLE_FOR_LIST]: (options: {
106 filter?: VideoFilter,
109 videoChannelId?: number
111 const accountInclude = {
112 attributes: [ 'id', 'name' ],
113 model: AccountModel.unscoped(),
118 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
119 model: ActorModel.unscoped(),
121 where: VideoModel.buildActorWhereWithFilter(options.filter),
124 attributes: [ 'host' ],
125 model: ServerModel.unscoped(),
129 model: AvatarModel.unscoped(),
137 const videoChannelInclude = {
138 attributes: [ 'name', 'description', 'id' ],
139 model: VideoChannelModel.unscoped(),
144 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
145 model: ActorModel.unscoped(),
149 attributes: [ 'host' ],
150 model: ServerModel.unscoped(),
154 model: AvatarModel.unscoped(),
163 // Force actorId to be a number to avoid SQL injections
164 const actorIdNumber = parseInt(options.actorId.toString(), 10)
165 const query: IFindOptions<VideoModel> = {
168 [Sequelize.Op.notIn]: Sequelize.literal(
169 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
171 [ Sequelize.Op.in ]: Sequelize.literal(
173 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
174 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
175 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
177 'SELECT "video"."id" AS "id" FROM "video" ' +
178 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
179 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
180 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
181 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
182 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
186 privacy: VideoPrivacy.PUBLIC
188 include: [ videoChannelInclude ]
191 if (options.withFiles === true) {
193 model: VideoFileModel.unscoped(),
199 if (options.hideNSFW === true) {
200 query.where['nsfw'] = false
203 if (options.accountId) {
204 accountInclude.where = {
205 id: options.accountId
209 if (options.videoChannelId) {
210 videoChannelInclude.where = {
211 id: options.videoChannelId
217 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
220 model: () => VideoChannelModel.unscoped(),
225 exclude: [ 'privateKey', 'publicKey' ]
227 model: () => ActorModel.unscoped(),
231 attributes: [ 'host' ],
232 model: () => ServerModel.unscoped(),
238 model: () => AccountModel.unscoped(),
242 model: () => ActorModel.unscoped(),
244 exclude: [ 'privateKey', 'publicKey' ]
249 attributes: [ 'host' ],
250 model: () => ServerModel.unscoped(),
254 model: () => AvatarModel.unscoped(),
265 [ScopeNames.WITH_TAGS]: {
266 include: [ () => TagModel ]
268 [ScopeNames.WITH_FILES]: {
271 model: () => VideoFileModel.unscoped(),
276 [ScopeNames.WITH_SHARES]: {
279 ['separate' as any]: true,
280 model: () => VideoShareModel.unscoped()
284 [ScopeNames.WITH_RATES]: {
287 ['separate' as any]: true,
288 model: () => AccountVideoRateModel,
291 model: () => AccountModel.unscoped(),
295 attributes: [ 'url' ],
296 model: () => ActorModel.unscoped()
304 [ScopeNames.WITH_COMMENTS]: {
307 ['separate' as any]: true,
308 model: () => VideoCommentModel.unscoped()
320 fields: [ 'createdAt' ]
323 fields: [ 'duration' ]
335 fields: [ 'channelId' ]
338 fields: [ 'id', 'privacy' ]
346 export class VideoModel extends Model<VideoModel> {
349 @Default(DataType.UUIDV4)
351 @Column(DataType.UUID)
355 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
361 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
367 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
373 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
374 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
378 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
383 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
389 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
390 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
395 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
396 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
400 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
430 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
431 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
436 commentsEnabled: boolean
445 @Default(Sequelize.NOW)
449 @ForeignKey(() => VideoChannelModel)
453 @BelongsTo(() => VideoChannelModel, {
459 VideoChannel: VideoChannelModel
461 @BelongsToMany(() => TagModel, {
462 foreignKey: 'videoId',
463 through: () => VideoTagModel,
468 @HasMany(() => VideoAbuseModel, {
475 VideoAbuses: VideoAbuseModel[]
477 @HasMany(() => VideoFileModel, {
484 VideoFiles: VideoFileModel[]
486 @HasMany(() => VideoShareModel, {
493 VideoShares: VideoShareModel[]
495 @HasMany(() => AccountVideoRateModel, {
502 AccountVideoRates: AccountVideoRateModel[]
504 @HasMany(() => VideoCommentModel, {
512 VideoComments: VideoCommentModel[]
515 static async sendDelete (instance: VideoModel, options) {
516 if (instance.isOwned()) {
517 if (!instance.VideoChannel) {
518 instance.VideoChannel = await instance.$get('VideoChannel', {
522 include: [ ActorModel ]
525 transaction: options.transaction
526 }) as VideoChannelModel
529 logger.debug('Sending delete of video %s.', instance.url)
531 return sendDeleteVideo(instance, options.transaction)
538 static async removeFilesAndSendDelete (instance: VideoModel) {
539 const tasks: Promise<any>[] = []
541 logger.debug('Removing files of video %s.', instance.url)
543 tasks.push(instance.removeThumbnail())
545 if (instance.isOwned()) {
546 if (!Array.isArray(instance.VideoFiles)) {
547 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
550 tasks.push(instance.removePreview())
552 // Remove physical files and torrents
553 instance.VideoFiles.forEach(file => {
554 tasks.push(instance.removeFile(file))
555 tasks.push(instance.removeTorrent(file))
559 // Do not wait video deletion because we could be in a transaction
562 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
569 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
572 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
573 function getRawQuery (select: string) {
574 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
575 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
576 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
577 'WHERE "Account"."actorId" = ' + actorId
578 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
579 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
580 'WHERE "VideoShare"."actorId" = ' + actorId
582 return `(${queryVideo}) UNION (${queryVideoShare})`
585 const rawQuery = getRawQuery('"Video"."id"')
586 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
592 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
595 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
598 { privacy: VideoPrivacy.PUBLIC },
599 { privacy: VideoPrivacy.UNLISTED }
604 attributes: [ 'id', 'url' ],
605 model: VideoShareModel.unscoped(),
607 // We only want videos shared by this actor
609 [Sequelize.Op.and]: [
612 [Sequelize.Op.not]: null
622 attributes: [ 'id', 'url' ],
623 model: ActorModel.unscoped()
628 model: VideoChannelModel.unscoped(),
632 attributes: [ 'name' ],
633 model: AccountModel.unscoped(),
637 attributes: [ 'id', 'url', 'followersUrl' ],
638 model: ActorModel.unscoped(),
644 attributes: [ 'id', 'url', 'followersUrl' ],
645 model: ActorModel.unscoped(),
655 return Bluebird.all([
656 // FIXME: typing issue
657 VideoModel.findAll(query as any),
658 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
659 ]).then(([ rows, totals ]) => {
660 // totals: totalVideos + totalVideoShares
662 let totalVideoShares = 0
663 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
664 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
666 const total = totalVideos + totalVideoShares
674 static listAccountVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
675 const query: IFindOptions<VideoModel> = {
678 order: getSort(sort),
681 model: VideoChannelModel,
696 if (withFiles === true) {
698 model: VideoFileModel.unscoped(),
703 if (hideNSFW === true) {
709 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
717 static async listForApi (options: {
723 filter?: VideoFilter,
725 videoChannelId?: number
728 offset: options.start,
729 limit: options.count,
730 order: getSort(options.sort)
733 const serverActor = await getServerActor()
736 ScopeNames.AVAILABLE_FOR_LIST, {
737 actorId: serverActor.id,
738 hideNSFW: options.hideNSFW,
739 filter: options.filter,
740 withFiles: options.withFiles,
741 accountId: options.accountId,
742 videoChannelId: options.videoChannelId
747 return VideoModel.scope(scopes)
748 .findAndCountAll(query)
749 .then(({ rows, count }) => {
757 static async searchAndPopulateAccountAndServer (value: string, start: number, count: number, sort: string, hideNSFW: boolean) {
758 const query: IFindOptions<VideoModel> = {
761 order: getSort(sort),
766 [ Sequelize.Op.iLike ]: '%' + value + '%'
770 preferredUsernameChannel: Sequelize.where(Sequelize.col('VideoChannel->Actor.preferredUsername'), {
771 [ Sequelize.Op.iLike ]: '%' + value + '%'
775 preferredUsernameAccount: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor.preferredUsername'), {
776 [ Sequelize.Op.iLike ]: '%' + value + '%'
780 host: Sequelize.where(Sequelize.col('VideoChannel->Account->Actor->Server.host'), {
781 [ Sequelize.Op.iLike ]: '%' + value + '%'
788 const serverActor = await getServerActor()
791 ScopeNames.AVAILABLE_FOR_LIST, {
792 actorId: serverActor.id,
798 return VideoModel.scope(scopes)
799 .findAndCountAll(query)
800 .then(({ rows, count }) => {
808 static load (id: number) {
809 return VideoModel.findById(id)
812 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
813 const query: IFindOptions<VideoModel> = {
819 if (t !== undefined) query.transaction = t
821 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
824 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
825 const query: IFindOptions<VideoModel> = {
834 if (t !== undefined) query.transaction = t
836 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
839 static loadAndPopulateAccountAndServerAndTags (id: number) {
841 order: [ [ 'Tags', 'name', 'ASC' ] ]
845 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
846 .findById(id, options)
849 static loadByUUID (uuid: string) {
857 .scope([ ScopeNames.WITH_FILES ])
861 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
863 order: [ [ 'Tags', 'name', 'ASC' ] ],
870 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
874 static async getStats () {
875 const totalLocalVideos = await VideoModel.count({
880 const totalVideos = await VideoModel.count()
882 let totalLocalVideoViews = await VideoModel.sum('views', {
887 // Sequelize could return null...
888 if (!totalLocalVideoViews) totalLocalVideoViews = 0
892 totalLocalVideoViews,
897 private static buildActorWhereWithFilter (filter?: VideoFilter) {
898 if (filter && filter === 'local') {
907 private static getCategoryLabel (id: number) {
908 let categoryLabel = VIDEO_CATEGORIES[id]
909 if (!categoryLabel) categoryLabel = 'Misc'
914 private static getLicenceLabel (id: number) {
915 let licenceLabel = VIDEO_LICENCES[id]
916 if (!licenceLabel) licenceLabel = 'Unknown'
921 private static getLanguageLabel (id: string) {
922 let languageLabel = VIDEO_LANGUAGES[id]
923 if (!languageLabel) languageLabel = 'Unknown'
928 private static getPrivacyLabel (id: number) {
929 let privacyLabel = VIDEO_PRIVACIES[id]
930 if (!privacyLabel) privacyLabel = 'Unknown'
936 if (Array.isArray(this.VideoFiles) === false) return undefined
938 // The original file is the file that have the higher resolution
939 return maxBy(this.VideoFiles, file => file.resolution)
942 getVideoFilename (videoFile: VideoFileModel) {
943 return this.uuid + '-' + videoFile.resolution + videoFile.extname
946 getThumbnailName () {
947 // We always have a copy of the thumbnail
948 const extension = '.jpg'
949 return this.uuid + extension
953 const extension = '.jpg'
954 return this.uuid + extension
957 getTorrentFileName (videoFile: VideoFileModel) {
958 const extension = '.torrent'
959 return this.uuid + '-' + videoFile.resolution + extension
963 return this.remote === false
966 createPreview (videoFile: VideoFileModel) {
967 return generateImageFromVideoFile(
968 this.getVideoFilePath(videoFile),
969 CONFIG.STORAGE.PREVIEWS_DIR,
970 this.getPreviewName(),
975 createThumbnail (videoFile: VideoFileModel) {
976 return generateImageFromVideoFile(
977 this.getVideoFilePath(videoFile),
978 CONFIG.STORAGE.THUMBNAILS_DIR,
979 this.getThumbnailName(),
984 getTorrentFilePath (videoFile: VideoFileModel) {
985 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
988 getVideoFilePath (videoFile: VideoFileModel) {
989 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
992 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
994 // Keep the extname, it's used by the client to stream the file inside a web browser
995 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
996 createdBy: 'PeerTube',
998 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
999 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1002 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1006 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1008 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1009 logger.info('Creating torrent %s.', filePath)
1011 await writeFilePromise(filePath, torrent)
1013 const parsedTorrent = parseTorrent(torrent)
1014 videoFile.infoHash = parsedTorrent.infoHash
1018 return '/videos/embed/' + this.uuid
1021 getThumbnailPath () {
1022 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1026 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1029 toFormattedJSON (): Video {
1030 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1031 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1039 label: VideoModel.getCategoryLabel(this.category)
1043 label: VideoModel.getLicenceLabel(this.licence)
1047 label: VideoModel.getLanguageLabel(this.language)
1051 label: VideoModel.getPrivacyLabel(this.privacy)
1054 description: this.getTruncatedDescription(),
1055 isLocal: this.isOwned(),
1056 duration: this.duration,
1059 dislikes: this.dislikes,
1060 thumbnailPath: this.getThumbnailPath(),
1061 previewPath: this.getPreviewPath(),
1062 embedPath: this.getEmbedPath(),
1063 createdAt: this.createdAt,
1064 updatedAt: this.updatedAt,
1065 publishedAt: this.publishedAt,
1067 id: formattedAccount.id,
1068 uuid: formattedAccount.uuid,
1069 name: formattedAccount.name,
1070 displayName: formattedAccount.displayName,
1071 url: formattedAccount.url,
1072 host: formattedAccount.host,
1073 avatar: formattedAccount.avatar
1076 id: formattedVideoChannel.id,
1077 uuid: formattedVideoChannel.uuid,
1078 name: formattedVideoChannel.name,
1079 displayName: formattedVideoChannel.displayName,
1080 url: formattedVideoChannel.url,
1081 host: formattedVideoChannel.host,
1082 avatar: formattedVideoChannel.avatar
1087 toFormattedDetailsJSON (): VideoDetails {
1088 const formattedJson = this.toFormattedJSON()
1090 const detailsJson = {
1091 support: this.support,
1092 descriptionPath: this.getDescriptionPath(),
1093 channel: this.VideoChannel.toFormattedJSON(),
1094 account: this.VideoChannel.Account.toFormattedJSON(),
1095 tags: map(this.Tags, 'name'),
1096 commentsEnabled: this.commentsEnabled,
1100 // Format and sort video files
1101 detailsJson.files = this.getFormattedVideoFilesJSON()
1103 return Object.assign(formattedJson, detailsJson)
1106 getFormattedVideoFilesJSON (): VideoFile[] {
1107 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1109 return this.VideoFiles
1111 let resolutionLabel = videoFile.resolution + 'p'
1115 id: videoFile.resolution,
1116 label: resolutionLabel
1118 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1119 size: videoFile.size,
1120 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1121 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1122 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1123 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1127 if (a.resolution.id < b.resolution.id) return 1
1128 if (a.resolution.id === b.resolution.id) return 0
1133 toActivityPubObject (): VideoTorrentObject {
1134 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1135 if (!this.Tags) this.Tags = []
1137 const tag = this.Tags.map(t => ({
1138 type: 'Hashtag' as 'Hashtag',
1143 if (this.language) {
1145 identifier: this.language,
1146 name: VideoModel.getLanguageLabel(this.language)
1151 if (this.category) {
1153 identifier: this.category + '',
1154 name: VideoModel.getCategoryLabel(this.category)
1161 identifier: this.licence + '',
1162 name: VideoModel.getLicenceLabel(this.licence)
1167 for (const file of this.VideoFiles) {
1170 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1171 href: this.getVideoFileUrl(file, baseUrlHttp),
1172 width: file.resolution,
1178 mimeType: 'application/x-bittorrent',
1179 href: this.getTorrentUrl(file, baseUrlHttp),
1180 width: file.resolution
1185 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1186 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1187 width: file.resolution
1191 // Add video url too
1194 mimeType: 'text/html',
1195 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1199 type: 'Video' as 'Video',
1202 duration: this.getActivityStreamDuration(),
1209 sensitive: this.nsfw,
1210 commentsEnabled: this.commentsEnabled,
1211 published: this.publishedAt.toISOString(),
1212 updated: this.updatedAt.toISOString(),
1213 mediaType: 'text/markdown',
1214 content: this.getTruncatedDescription(),
1215 support: this.support,
1218 url: this.getThumbnailUrl(baseUrlHttp),
1219 mediaType: 'image/jpeg',
1220 width: THUMBNAILS_SIZE.width,
1221 height: THUMBNAILS_SIZE.height
1224 likes: getVideoLikesActivityPubUrl(this),
1225 dislikes: getVideoDislikesActivityPubUrl(this),
1226 shares: getVideoSharesActivityPubUrl(this),
1227 comments: getVideoCommentsActivityPubUrl(this),
1231 id: this.VideoChannel.Account.Actor.url
1235 id: this.VideoChannel.Actor.url
1241 getTruncatedDescription () {
1242 if (!this.description) return null
1244 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1245 return peertubeTruncate(this.description, maxLength)
1248 async optimizeOriginalVideofile () {
1249 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1250 const newExtname = '.mp4'
1251 const inputVideoFile = this.getOriginalFile()
1252 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1253 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1255 const transcodeOptions = {
1256 inputPath: videoInputPath,
1257 outputPath: videoOutputPath
1260 // Could be very long!
1261 await transcode(transcodeOptions)
1264 await unlinkPromise(videoInputPath)
1266 // Important to do this before getVideoFilename() to take in account the new file extension
1267 inputVideoFile.set('extname', newExtname)
1269 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1270 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1272 inputVideoFile.set('size', stats.size)
1274 await this.createTorrentAndSetInfoHash(inputVideoFile)
1275 await inputVideoFile.save()
1278 // Auto destruction...
1279 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1285 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1286 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1287 const extname = '.mp4'
1289 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1290 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1292 const newVideoFile = new VideoFileModel({
1298 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1300 const transcodeOptions = {
1301 inputPath: videoInputPath,
1302 outputPath: videoOutputPath,
1307 await transcode(transcodeOptions)
1309 const stats = await statPromise(videoOutputPath)
1311 newVideoFile.set('size', stats.size)
1313 await this.createTorrentAndSetInfoHash(newVideoFile)
1315 await newVideoFile.save()
1317 this.VideoFiles.push(newVideoFile)
1320 async importVideoFile (inputFilePath: string) {
1321 let updatedVideoFile = new VideoFileModel({
1322 resolution: (await getVideoFileResolution(inputFilePath)).videoFileResolution,
1323 extname: extname(inputFilePath),
1324 size: (await statPromise(inputFilePath)).size,
1328 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1330 if (currentVideoFile) {
1331 // Remove old file and old torrent
1332 await this.removeFile(currentVideoFile)
1333 await this.removeTorrent(currentVideoFile)
1334 // Remove the old video file from the array
1335 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1337 // Update the database
1338 currentVideoFile.set('extname', updatedVideoFile.extname)
1339 currentVideoFile.set('size', updatedVideoFile.size)
1341 updatedVideoFile = currentVideoFile
1344 const outputPath = this.getVideoFilePath(updatedVideoFile)
1345 await copyFilePromise(inputFilePath, outputPath)
1347 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1349 await updatedVideoFile.save()
1351 this.VideoFiles.push(updatedVideoFile)
1354 getOriginalFileResolution () {
1355 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1357 return getVideoFileResolution(originalFilePath)
1360 getDescriptionPath () {
1361 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1364 removeThumbnail () {
1365 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1366 return unlinkPromise(thumbnailPath)
1370 // Same name than video thumbnail
1371 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1374 removeFile (videoFile: VideoFileModel) {
1375 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1376 return unlinkPromise(filePath)
1379 removeTorrent (videoFile: VideoFileModel) {
1380 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1381 return unlinkPromise(torrentPath)
1384 getActivityStreamDuration () {
1385 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1386 return 'PT' + this.duration + 'S'
1389 private getBaseUrls () {
1393 if (this.isOwned()) {
1394 baseUrlHttp = CONFIG.WEBSERVER.URL
1395 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1397 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1398 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1401 return { baseUrlHttp, baseUrlWs }
1404 private getThumbnailUrl (baseUrlHttp: string) {
1405 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1408 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1409 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1412 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1413 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1416 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1417 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1420 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1421 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1424 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1425 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1426 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1427 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1429 const magnetHash = {
1433 infoHash: videoFile.infoHash,
1437 return magnetUtil.encode(magnetHash)