1 import * as Bluebird from 'bluebird'
2 import { map, maxBy, truncate } 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'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails } from '../../../shared/models/videos'
32 import { activityPubCollection } from '../../helpers/activitypub'
33 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
34 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
35 import { isBooleanValid } from '../../helpers/custom-validators/misc'
38 isVideoDescriptionValid,
44 } from '../../helpers/custom-validators/videos'
45 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
46 import { logger } from '../../helpers/logger'
47 import { getServerActor } from '../../helpers/utils'
60 } from '../../initializers'
62 getVideoCommentsActivityPubUrl,
63 getVideoDislikesActivityPubUrl,
64 getVideoLikesActivityPubUrl,
65 getVideoSharesActivityPubUrl
66 } from '../../lib/activitypub'
67 import { sendDeleteVideo } from '../../lib/activitypub/send'
68 import { AccountModel } from '../account/account'
69 import { AccountVideoRateModel } from '../account/account-video-rate'
70 import { ActorModel } from '../activitypub/actor'
71 import { ServerModel } from '../server/server'
72 import { getSort, throwIfNotValid } from '../utils'
73 import { TagModel } from './tag'
74 import { VideoAbuseModel } from './video-abuse'
75 import { VideoChannelModel } from './video-channel'
76 import { VideoCommentModel } from './video-comment'
77 import { VideoFileModel } from './video-file'
78 import { VideoShareModel } from './video-share'
79 import { VideoTagModel } from './video-tag'
82 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
83 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
84 WITH_TAGS = 'WITH_TAGS',
85 WITH_FILES = 'WITH_FILES',
86 WITH_SHARES = 'WITH_SHARES',
87 WITH_RATES = 'WITH_RATES',
88 WITH_COMMENTS = 'WITH_COMMENTS'
92 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
95 [Sequelize.Op.notIn]: Sequelize.literal(
96 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
98 [ Sequelize.Op.in ]: Sequelize.literal(
100 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
101 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
102 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
104 'SELECT "video"."id" AS "id" FROM "video" ' +
105 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
106 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
107 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
108 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
109 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
113 privacy: VideoPrivacy.PUBLIC
117 attributes: [ 'name', 'description' ],
118 model: VideoChannelModel.unscoped(),
122 attributes: [ 'name' ],
123 model: AccountModel.unscoped(),
127 attributes: [ 'serverId' ],
128 model: ActorModel.unscoped(),
132 attributes: [ 'host' ],
133 model: ServerModel.unscoped()
143 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
146 model: () => VideoChannelModel.unscoped(),
151 exclude: [ 'privateKey', 'publicKey' ]
153 model: () => ActorModel.unscoped(),
157 attributes: [ 'host' ],
158 model: () => ServerModel.unscoped(),
164 model: () => AccountModel.unscoped(),
168 model: () => ActorModel.unscoped(),
170 exclude: [ 'privateKey', 'publicKey' ]
175 attributes: [ 'host' ],
176 model: () => ServerModel.unscoped(),
187 [ScopeNames.WITH_TAGS]: {
188 include: [ () => TagModel ]
190 [ScopeNames.WITH_FILES]: {
193 model: () => VideoFileModel,
198 [ScopeNames.WITH_SHARES]: {
201 model: () => VideoShareModel,
202 include: [ () => ActorModel ]
206 [ScopeNames.WITH_RATES]: {
209 model: () => AccountVideoRateModel,
210 include: [ () => AccountModel ]
214 [ScopeNames.WITH_COMMENTS]: {
217 model: () => VideoCommentModel
229 fields: [ 'createdAt' ]
232 fields: [ 'duration' ]
244 fields: [ 'channelId' ]
247 fields: [ 'id', 'privacy' ]
255 export class VideoModel extends Model<VideoModel> {
258 @Default(DataType.UUIDV4)
260 @Column(DataType.UUID)
264 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
270 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
276 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
282 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
287 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
292 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
298 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
299 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
303 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
333 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
334 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
339 commentsEnabled: boolean
347 @ForeignKey(() => VideoChannelModel)
351 @BelongsTo(() => VideoChannelModel, {
357 VideoChannel: VideoChannelModel
359 @BelongsToMany(() => TagModel, {
360 foreignKey: 'videoId',
361 through: () => VideoTagModel,
366 @HasMany(() => VideoAbuseModel, {
373 VideoAbuses: VideoAbuseModel[]
375 @HasMany(() => VideoFileModel, {
382 VideoFiles: VideoFileModel[]
384 @HasMany(() => VideoShareModel, {
391 VideoShares: VideoShareModel[]
393 @HasMany(() => AccountVideoRateModel, {
400 AccountVideoRates: AccountVideoRateModel[]
402 @HasMany(() => VideoCommentModel, {
410 VideoComments: VideoCommentModel[]
413 static async sendDelete (instance: VideoModel, options) {
414 if (instance.isOwned()) {
415 if (!instance.VideoChannel) {
416 instance.VideoChannel = await instance.$get('VideoChannel', {
420 include: [ ActorModel ]
423 transaction: options.transaction
424 }) as VideoChannelModel
427 logger.debug('Sending delete of video %s.', instance.url)
429 return sendDeleteVideo(instance, options.transaction)
436 static async removeFilesAndSendDelete (instance: VideoModel) {
437 const tasks: Promise<any>[] = []
439 tasks.push(instance.removeThumbnail())
441 if (instance.isOwned()) {
442 if (!Array.isArray(instance.VideoFiles)) {
443 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
446 tasks.push(instance.removePreview())
448 // Remove physical files and torrents
449 instance.VideoFiles.forEach(file => {
450 tasks.push(instance.removeFile(file))
451 tasks.push(instance.removeTorrent(file))
455 return Promise.all(tasks)
457 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
462 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
465 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
466 function getRawQuery (select: string) {
467 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
468 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
469 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
470 'WHERE "Account"."actorId" = ' + actorId
471 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
472 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
473 'WHERE "VideoShare"."actorId" = ' + actorId
475 return `(${queryVideo}) UNION (${queryVideoShare})`
478 const rawQuery = getRawQuery('"Video"."id"')
479 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
485 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
488 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
491 { privacy: VideoPrivacy.PUBLIC },
492 { privacy: VideoPrivacy.UNLISTED }
497 attributes: [ 'id', 'url' ],
498 model: VideoShareModel.unscoped(),
501 [Sequelize.Op.and]: [
504 [Sequelize.Op.not]: null
514 attributes: [ 'id', 'url' ],
515 model: ActorModel.unscoped()
520 model: VideoChannelModel.unscoped(),
524 attributes: [ 'name' ],
525 model: AccountModel.unscoped(),
529 attributes: [ 'id', 'url' ],
530 model: ActorModel.unscoped(),
536 attributes: [ 'id', 'url' ],
537 model: ActorModel.unscoped(),
543 attributes: [ 'type' ],
544 model: AccountVideoRateModel,
548 attributes: [ 'id' ],
549 model: AccountModel.unscoped(),
552 attributes: [ 'url' ],
553 model: ActorModel.unscoped(),
556 attributes: [ 'host' ],
567 attributes: [ 'url' ],
568 model: VideoCommentModel,
576 return Bluebird.all([
577 // FIXME: typing issue
578 VideoModel.findAll(query as any),
579 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
580 ]).then(([ rows, totals ]) => {
581 // totals: totalVideos + totalVideoShares
583 let totalVideoShares = 0
584 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
585 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
587 const total = totalVideos + totalVideoShares
595 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
599 order: [ getSort(sort) ],
602 model: VideoChannelModel,
617 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
625 static async listForApi (start: number, count: number, sort: string) {
629 order: [ getSort(sort) ]
632 const serverActor = await getServerActor()
634 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
635 .findAndCountAll(query)
636 .then(({ rows, count }) => {
644 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
645 const query: IFindOptions<VideoModel> = {
648 order: [ getSort(sort) ],
651 [Sequelize.Op.iLike]: '%' + value + '%'
656 const serverActor = await getServerActor()
658 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
659 .findAndCountAll(query).then(({ rows, count }) => {
667 static load (id: number) {
668 return VideoModel.findById(id)
671 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
672 const query: IFindOptions<VideoModel> = {
678 if (t !== undefined) query.transaction = t
680 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
683 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
684 const query: IFindOptions<VideoModel> = {
693 if (t !== undefined) query.transaction = t
695 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
698 static loadAndPopulateAccountAndServerAndTags (id: number) {
700 order: [ [ 'Tags', 'name', 'ASC' ] ]
704 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
705 .findById(id, options)
708 static loadByUUID (uuid: string) {
716 .scope([ ScopeNames.WITH_FILES ])
720 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
722 order: [ [ 'Tags', 'name', 'ASC' ] ],
729 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
733 static loadAndPopulateAll (id: number) {
735 order: [ [ 'Tags', 'name', 'ASC' ] ],
743 ScopeNames.WITH_RATES,
744 ScopeNames.WITH_SHARES,
745 ScopeNames.WITH_TAGS,
746 ScopeNames.WITH_FILES,
747 ScopeNames.WITH_ACCOUNT_DETAILS,
748 ScopeNames.WITH_COMMENTS
754 if (Array.isArray(this.VideoFiles) === false) return undefined
756 // The original file is the file that have the higher resolution
757 return maxBy(this.VideoFiles, file => file.resolution)
760 getVideoFilename (videoFile: VideoFileModel) {
761 return this.uuid + '-' + videoFile.resolution + videoFile.extname
764 getThumbnailName () {
765 // We always have a copy of the thumbnail
766 const extension = '.jpg'
767 return this.uuid + extension
771 const extension = '.jpg'
772 return this.uuid + extension
775 getTorrentFileName (videoFile: VideoFileModel) {
776 const extension = '.torrent'
777 return this.uuid + '-' + videoFile.resolution + extension
781 return this.remote === false
784 createPreview (videoFile: VideoFileModel) {
785 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
787 return generateImageFromVideoFile(
788 this.getVideoFilePath(videoFile),
789 CONFIG.STORAGE.PREVIEWS_DIR,
790 this.getPreviewName(),
795 createThumbnail (videoFile: VideoFileModel) {
796 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
798 return generateImageFromVideoFile(
799 this.getVideoFilePath(videoFile),
800 CONFIG.STORAGE.THUMBNAILS_DIR,
801 this.getThumbnailName(),
806 getVideoFilePath (videoFile: VideoFileModel) {
807 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
810 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
813 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
814 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
817 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
821 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
823 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
824 logger.info('Creating torrent %s.', filePath)
826 await writeFilePromise(filePath, torrent)
828 const parsedTorrent = parseTorrent(torrent)
829 videoFile.infoHash = parsedTorrent.infoHash
833 return '/videos/embed/' + this.uuid
836 getThumbnailPath () {
837 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
841 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
847 if (this.VideoChannel.Account.Actor.Server) {
848 serverHost = this.VideoChannel.Account.Actor.Server.host
850 // It means it's our video
851 serverHost = CONFIG.WEBSERVER.HOST
858 category: this.category,
859 categoryLabel: this.getCategoryLabel(),
860 licence: this.licence,
861 licenceLabel: this.getLicenceLabel(),
862 language: this.language,
863 languageLabel: this.getLanguageLabel(),
865 description: this.getTruncatedDescription(),
867 isLocal: this.isOwned(),
868 accountName: this.VideoChannel.Account.name,
869 duration: this.duration,
872 dislikes: this.dislikes,
873 thumbnailPath: this.getThumbnailPath(),
874 previewPath: this.getPreviewPath(),
875 embedPath: this.getEmbedPath(),
876 createdAt: this.createdAt,
877 updatedAt: this.updatedAt
881 toFormattedDetailsJSON () {
882 const formattedJson = this.toFormattedJSON()
884 // Maybe our server is not up to date and there are new privacy settings since our version
885 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
886 if (!privacyLabel) privacyLabel = 'Unknown'
888 const detailsJson = {
890 privacy: this.privacy,
891 descriptionPath: this.getDescriptionPath(),
892 channel: this.VideoChannel.toFormattedJSON(),
893 account: this.VideoChannel.Account.toFormattedJSON(),
894 tags: map<TagModel, string>(this.Tags, 'name'),
895 commentsEnabled: this.commentsEnabled,
899 // Format and sort video files
900 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
901 detailsJson.files = this.VideoFiles
903 let resolutionLabel = videoFile.resolution + 'p'
906 resolution: videoFile.resolution,
908 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
909 size: videoFile.size,
910 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
911 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
915 if (a.resolution < b.resolution) return 1
916 if (a.resolution === b.resolution) return 0
920 return Object.assign(formattedJson, detailsJson) as VideoDetails
923 toActivityPubObject (): VideoTorrentObject {
924 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
925 if (!this.Tags) this.Tags = []
927 const tag = this.Tags.map(t => ({
928 type: 'Hashtag' as 'Hashtag',
935 identifier: this.language + '',
936 name: this.getLanguageLabel()
943 identifier: this.category + '',
944 name: this.getCategoryLabel()
951 identifier: this.licence + '',
952 name: this.getLicenceLabel()
959 if (Array.isArray(this.AccountVideoRates)) {
960 const likes: string[] = []
961 const dislikes: string[] = []
963 for (const rate of this.AccountVideoRates) {
964 if (rate.type === 'like') {
965 likes.push(rate.Account.Actor.url)
966 } else if (rate.type === 'dislike') {
967 dislikes.push(rate.Account.Actor.url)
971 const res = this.toRatesActivityPubObjects()
972 likesObject = res.likesObject
973 dislikesObject = res.dislikesObject
977 if (Array.isArray(this.VideoShares)) {
978 sharesObject = this.toAnnouncesActivityPubObject()
982 if (Array.isArray(this.VideoComments)) {
983 commentsObject = this.toCommentsActivityPubObject()
987 for (const file of this.VideoFiles) {
990 mimeType: 'video/' + file.extname.replace('.', ''),
991 href: this.getVideoFileUrl(file, baseUrlHttp),
992 width: file.resolution,
998 mimeType: 'application/x-bittorrent',
999 href: this.getTorrentUrl(file, baseUrlHttp),
1000 width: file.resolution
1005 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1006 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1007 width: file.resolution
1011 // Add video url too
1014 mimeType: 'text/html',
1015 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1019 type: 'Video' as 'Video',
1022 duration: this.getActivityStreamDuration(),
1029 sensitive: this.nsfw,
1030 commentsEnabled: this.commentsEnabled,
1031 published: this.createdAt.toISOString(),
1032 updated: this.updatedAt.toISOString(),
1033 mediaType: 'text/markdown',
1034 content: this.getTruncatedDescription(),
1037 url: this.getThumbnailUrl(baseUrlHttp),
1038 mediaType: 'image/jpeg',
1039 width: THUMBNAILS_SIZE.width,
1040 height: THUMBNAILS_SIZE.height
1044 dislikes: dislikesObject,
1045 shares: sharesObject,
1046 comments: commentsObject,
1050 id: this.VideoChannel.Actor.url
1054 id: this.VideoChannel.Account.Actor.url
1060 toAnnouncesActivityPubObject () {
1061 const shares: string[] = []
1063 for (const videoShare of this.VideoShares) {
1064 shares.push(videoShare.url)
1067 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1070 toCommentsActivityPubObject () {
1071 const comments: string[] = []
1073 for (const videoComment of this.VideoComments) {
1074 comments.push(videoComment.url)
1077 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1080 toRatesActivityPubObjects () {
1081 const likes: string[] = []
1082 const dislikes: string[] = []
1084 for (const rate of this.AccountVideoRates) {
1085 if (rate.type === 'like') {
1086 likes.push(rate.Account.Actor.url)
1087 } else if (rate.type === 'dislike') {
1088 dislikes.push(rate.Account.Actor.url)
1092 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1093 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1095 return { likesObject, dislikesObject }
1098 getTruncatedDescription () {
1099 if (!this.description) return null
1102 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1105 return truncate(this.description, options)
1108 optimizeOriginalVideofile = async function () {
1109 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1110 const newExtname = '.mp4'
1111 const inputVideoFile = this.getOriginalFile()
1112 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1113 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1115 const transcodeOptions = {
1116 inputPath: videoInputPath,
1117 outputPath: videoOutputPath
1121 // Could be very long!
1122 await transcode(transcodeOptions)
1124 await unlinkPromise(videoInputPath)
1126 // Important to do this before getVideoFilename() to take in account the new file extension
1127 inputVideoFile.set('extname', newExtname)
1129 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1130 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1132 inputVideoFile.set('size', stats.size)
1134 await this.createTorrentAndSetInfoHash(inputVideoFile)
1135 await inputVideoFile.save()
1138 // Auto destruction...
1139 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1145 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1146 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1147 const extname = '.mp4'
1149 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1150 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1152 const newVideoFile = new VideoFileModel({
1158 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1160 const transcodeOptions = {
1161 inputPath: videoInputPath,
1162 outputPath: videoOutputPath,
1166 await transcode(transcodeOptions)
1168 const stats = await statPromise(videoOutputPath)
1170 newVideoFile.set('size', stats.size)
1172 await this.createTorrentAndSetInfoHash(newVideoFile)
1174 await newVideoFile.save()
1176 this.VideoFiles.push(newVideoFile)
1179 getOriginalFileHeight () {
1180 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1182 return getVideoFileHeight(originalFilePath)
1185 getDescriptionPath () {
1186 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1189 getCategoryLabel () {
1190 let categoryLabel = VIDEO_CATEGORIES[this.category]
1191 if (!categoryLabel) categoryLabel = 'Misc'
1193 return categoryLabel
1196 getLicenceLabel () {
1197 let licenceLabel = VIDEO_LICENCES[this.licence]
1198 if (!licenceLabel) licenceLabel = 'Unknown'
1203 getLanguageLabel () {
1204 let languageLabel = VIDEO_LANGUAGES[this.language]
1205 if (!languageLabel) languageLabel = 'Unknown'
1207 return languageLabel
1210 removeThumbnail () {
1211 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1212 return unlinkPromise(thumbnailPath)
1216 // Same name than video thumbnail
1217 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1220 removeFile (videoFile: VideoFileModel) {
1221 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1222 return unlinkPromise(filePath)
1225 removeTorrent (videoFile: VideoFileModel) {
1226 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1227 return unlinkPromise(torrentPath)
1230 getActivityStreamDuration () {
1231 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1232 return 'PT' + this.duration + 'S'
1235 private getBaseUrls () {
1239 if (this.isOwned()) {
1240 baseUrlHttp = CONFIG.WEBSERVER.URL
1241 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1243 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1244 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1247 return { baseUrlHttp, baseUrlWs }
1250 private getThumbnailUrl (baseUrlHttp: string) {
1251 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1254 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1255 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1258 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1259 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1262 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1263 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1264 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1265 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1267 const magnetHash = {
1271 infoHash: videoFile.infoHash,
1275 return magnetUtil.encode(magnetHash)