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 + ')')
493 attributes: [ 'id' ],
494 model: VideoShareModel.unscoped(),
497 [Sequelize.Op.and]: [
500 [Sequelize.Op.not]: null
510 attributes: [ 'id', 'url' ],
511 model: ActorModel.unscoped()
516 model: VideoChannelModel.unscoped(),
520 attributes: [ 'name' ],
521 model: AccountModel.unscoped(),
525 attributes: [ 'id', 'url' ],
526 model: ActorModel.unscoped(),
532 attributes: [ 'id', 'url' ],
533 model: ActorModel.unscoped(),
539 attributes: [ 'type' ],
540 model: AccountVideoRateModel,
544 attributes: [ 'id' ],
545 model: AccountModel.unscoped(),
548 attributes: [ 'url' ],
549 model: ActorModel.unscoped(),
552 attributes: [ 'host' ],
563 attributes: [ 'url' ],
564 model: VideoCommentModel,
572 return Bluebird.all([
573 // FIXME: typing issue
574 VideoModel.findAll(query as any),
575 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
576 ]).then(([ rows, totals ]) => {
577 // totals: totalVideos + totalVideoShares
579 let totalVideoShares = 0
580 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
581 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
583 const total = totalVideos + totalVideoShares
591 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
595 order: [ getSort(sort) ],
598 model: VideoChannelModel,
613 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
621 static async listForApi (start: number, count: number, sort: string) {
625 order: [ getSort(sort) ]
628 const serverActor = await getServerActor()
630 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
631 .findAndCountAll(query)
632 .then(({ rows, count }) => {
640 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
641 const query: IFindOptions<VideoModel> = {
644 order: [ getSort(sort) ],
647 [Sequelize.Op.iLike]: '%' + value + '%'
652 const serverActor = await getServerActor()
654 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
655 .findAndCountAll(query).then(({ rows, count }) => {
663 static load (id: number) {
664 return VideoModel.findById(id)
667 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
668 const query: IFindOptions<VideoModel> = {
674 if (t !== undefined) query.transaction = t
676 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
679 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
680 const query: IFindOptions<VideoModel> = {
689 if (t !== undefined) query.transaction = t
691 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
694 static loadAndPopulateAccountAndServerAndTags (id: number) {
696 order: [ [ 'Tags', 'name', 'ASC' ] ]
700 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
701 .findById(id, options)
704 static loadByUUID (uuid: string) {
712 .scope([ ScopeNames.WITH_FILES ])
716 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
718 order: [ [ 'Tags', 'name', 'ASC' ] ],
725 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
729 static loadAndPopulateAll (id: number) {
731 order: [ [ 'Tags', 'name', 'ASC' ] ],
739 ScopeNames.WITH_RATES,
740 ScopeNames.WITH_SHARES,
741 ScopeNames.WITH_TAGS,
742 ScopeNames.WITH_FILES,
743 ScopeNames.WITH_ACCOUNT_DETAILS,
744 ScopeNames.WITH_COMMENTS
750 if (Array.isArray(this.VideoFiles) === false) return undefined
752 // The original file is the file that have the higher resolution
753 return maxBy(this.VideoFiles, file => file.resolution)
756 getVideoFilename (videoFile: VideoFileModel) {
757 return this.uuid + '-' + videoFile.resolution + videoFile.extname
760 getThumbnailName () {
761 // We always have a copy of the thumbnail
762 const extension = '.jpg'
763 return this.uuid + extension
767 const extension = '.jpg'
768 return this.uuid + extension
771 getTorrentFileName (videoFile: VideoFileModel) {
772 const extension = '.torrent'
773 return this.uuid + '-' + videoFile.resolution + extension
777 return this.remote === false
780 createPreview (videoFile: VideoFileModel) {
781 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
783 return generateImageFromVideoFile(
784 this.getVideoFilePath(videoFile),
785 CONFIG.STORAGE.PREVIEWS_DIR,
786 this.getPreviewName(),
791 createThumbnail (videoFile: VideoFileModel) {
792 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
794 return generateImageFromVideoFile(
795 this.getVideoFilePath(videoFile),
796 CONFIG.STORAGE.THUMBNAILS_DIR,
797 this.getThumbnailName(),
802 getVideoFilePath (videoFile: VideoFileModel) {
803 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
806 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
809 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
810 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
813 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
817 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
819 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
820 logger.info('Creating torrent %s.', filePath)
822 await writeFilePromise(filePath, torrent)
824 const parsedTorrent = parseTorrent(torrent)
825 videoFile.infoHash = parsedTorrent.infoHash
829 return '/videos/embed/' + this.uuid
832 getThumbnailPath () {
833 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
837 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
843 if (this.VideoChannel.Account.Actor.Server) {
844 serverHost = this.VideoChannel.Account.Actor.Server.host
846 // It means it's our video
847 serverHost = CONFIG.WEBSERVER.HOST
854 category: this.category,
855 categoryLabel: this.getCategoryLabel(),
856 licence: this.licence,
857 licenceLabel: this.getLicenceLabel(),
858 language: this.language,
859 languageLabel: this.getLanguageLabel(),
861 description: this.getTruncatedDescription(),
863 isLocal: this.isOwned(),
864 accountName: this.VideoChannel.Account.name,
865 duration: this.duration,
868 dislikes: this.dislikes,
869 thumbnailPath: this.getThumbnailPath(),
870 previewPath: this.getPreviewPath(),
871 embedPath: this.getEmbedPath(),
872 createdAt: this.createdAt,
873 updatedAt: this.updatedAt
877 toFormattedDetailsJSON () {
878 const formattedJson = this.toFormattedJSON()
880 // Maybe our server is not up to date and there are new privacy settings since our version
881 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
882 if (!privacyLabel) privacyLabel = 'Unknown'
884 const detailsJson = {
886 privacy: this.privacy,
887 descriptionPath: this.getDescriptionPath(),
888 channel: this.VideoChannel.toFormattedJSON(),
889 account: this.VideoChannel.Account.toFormattedJSON(),
890 tags: map<TagModel, string>(this.Tags, 'name'),
891 commentsEnabled: this.commentsEnabled,
895 // Format and sort video files
896 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
897 detailsJson.files = this.VideoFiles
899 let resolutionLabel = videoFile.resolution + 'p'
902 resolution: videoFile.resolution,
904 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
905 size: videoFile.size,
906 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
907 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
911 if (a.resolution < b.resolution) return 1
912 if (a.resolution === b.resolution) return 0
916 return Object.assign(formattedJson, detailsJson) as VideoDetails
919 toActivityPubObject (): VideoTorrentObject {
920 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
921 if (!this.Tags) this.Tags = []
923 const tag = this.Tags.map(t => ({
924 type: 'Hashtag' as 'Hashtag',
931 identifier: this.language + '',
932 name: this.getLanguageLabel()
939 identifier: this.category + '',
940 name: this.getCategoryLabel()
947 identifier: this.licence + '',
948 name: this.getLicenceLabel()
955 if (Array.isArray(this.AccountVideoRates)) {
956 const likes: string[] = []
957 const dislikes: string[] = []
959 for (const rate of this.AccountVideoRates) {
960 if (rate.type === 'like') {
961 likes.push(rate.Account.Actor.url)
962 } else if (rate.type === 'dislike') {
963 dislikes.push(rate.Account.Actor.url)
967 const res = this.toRatesActivityPubObjects()
968 likesObject = res.likesObject
969 dislikesObject = res.dislikesObject
973 if (Array.isArray(this.VideoShares)) {
974 sharesObject = this.toAnnouncesActivityPubObject()
978 if (Array.isArray(this.VideoComments)) {
979 commentsObject = this.toCommentsActivityPubObject()
983 for (const file of this.VideoFiles) {
986 mimeType: 'video/' + file.extname.replace('.', ''),
987 href: this.getVideoFileUrl(file, baseUrlHttp),
988 width: file.resolution,
994 mimeType: 'application/x-bittorrent',
995 href: this.getTorrentUrl(file, baseUrlHttp),
996 width: file.resolution
1001 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1002 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1003 width: file.resolution
1007 // Add video url too
1010 mimeType: 'text/html',
1011 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1015 type: 'Video' as 'Video',
1018 duration: this.getActivityStreamDuration(),
1025 sensitive: this.nsfw,
1026 commentsEnabled: this.commentsEnabled,
1027 published: this.createdAt.toISOString(),
1028 updated: this.updatedAt.toISOString(),
1029 mediaType: 'text/markdown',
1030 content: this.getTruncatedDescription(),
1033 url: this.getThumbnailUrl(baseUrlHttp),
1034 mediaType: 'image/jpeg',
1035 width: THUMBNAILS_SIZE.width,
1036 height: THUMBNAILS_SIZE.height
1040 dislikes: dislikesObject,
1041 shares: sharesObject,
1042 comments: commentsObject,
1046 id: this.VideoChannel.Actor.url
1050 id: this.VideoChannel.Account.Actor.url
1056 toAnnouncesActivityPubObject () {
1057 const shares: string[] = []
1059 for (const videoShare of this.VideoShares) {
1060 shares.push(videoShare.url)
1063 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1066 toCommentsActivityPubObject () {
1067 const comments: string[] = []
1069 for (const videoComment of this.VideoComments) {
1070 comments.push(videoComment.url)
1073 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1076 toRatesActivityPubObjects () {
1077 const likes: string[] = []
1078 const dislikes: string[] = []
1080 for (const rate of this.AccountVideoRates) {
1081 if (rate.type === 'like') {
1082 likes.push(rate.Account.Actor.url)
1083 } else if (rate.type === 'dislike') {
1084 dislikes.push(rate.Account.Actor.url)
1088 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1089 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1091 return { likesObject, dislikesObject }
1094 getTruncatedDescription () {
1095 if (!this.description) return null
1098 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1101 return truncate(this.description, options)
1104 optimizeOriginalVideofile = async function () {
1105 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1106 const newExtname = '.mp4'
1107 const inputVideoFile = this.getOriginalFile()
1108 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1109 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1111 const transcodeOptions = {
1112 inputPath: videoInputPath,
1113 outputPath: videoOutputPath
1117 // Could be very long!
1118 await transcode(transcodeOptions)
1120 await unlinkPromise(videoInputPath)
1122 // Important to do this before getVideoFilename() to take in account the new file extension
1123 inputVideoFile.set('extname', newExtname)
1125 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1126 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1128 inputVideoFile.set('size', stats.size)
1130 await this.createTorrentAndSetInfoHash(inputVideoFile)
1131 await inputVideoFile.save()
1134 // Auto destruction...
1135 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1141 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1142 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1143 const extname = '.mp4'
1145 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1146 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1148 const newVideoFile = new VideoFileModel({
1154 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1156 const transcodeOptions = {
1157 inputPath: videoInputPath,
1158 outputPath: videoOutputPath,
1162 await transcode(transcodeOptions)
1164 const stats = await statPromise(videoOutputPath)
1166 newVideoFile.set('size', stats.size)
1168 await this.createTorrentAndSetInfoHash(newVideoFile)
1170 await newVideoFile.save()
1172 this.VideoFiles.push(newVideoFile)
1175 getOriginalFileHeight () {
1176 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1178 return getVideoFileHeight(originalFilePath)
1181 getDescriptionPath () {
1182 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1185 getCategoryLabel () {
1186 let categoryLabel = VIDEO_CATEGORIES[this.category]
1187 if (!categoryLabel) categoryLabel = 'Misc'
1189 return categoryLabel
1192 getLicenceLabel () {
1193 let licenceLabel = VIDEO_LICENCES[this.licence]
1194 if (!licenceLabel) licenceLabel = 'Unknown'
1199 getLanguageLabel () {
1200 let languageLabel = VIDEO_LANGUAGES[this.language]
1201 if (!languageLabel) languageLabel = 'Unknown'
1203 return languageLabel
1206 removeThumbnail () {
1207 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1208 return unlinkPromise(thumbnailPath)
1212 // Same name than video thumbnail
1213 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1216 removeFile (videoFile: VideoFileModel) {
1217 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1218 return unlinkPromise(filePath)
1221 removeTorrent (videoFile: VideoFileModel) {
1222 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1223 return unlinkPromise(torrentPath)
1226 getActivityStreamDuration () {
1227 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1228 return 'PT' + this.duration + 'S'
1231 private getBaseUrls () {
1235 if (this.isOwned()) {
1236 baseUrlHttp = CONFIG.WEBSERVER.URL
1237 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1239 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1240 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1243 return { baseUrlHttp, baseUrlWs }
1246 private getThumbnailUrl (baseUrlHttp: string) {
1247 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1250 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1251 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1254 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1255 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1258 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1259 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1260 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1261 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1263 const magnetHash = {
1267 infoHash: videoFile.infoHash,
1271 return magnetUtil.encode(magnetHash)