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,
43 isVideoPrivacyValid, isVideoSupportValid
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))
304 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
305 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
309 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
339 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
340 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
345 commentsEnabled: boolean
353 @ForeignKey(() => VideoChannelModel)
357 @BelongsTo(() => VideoChannelModel, {
363 VideoChannel: VideoChannelModel
365 @BelongsToMany(() => TagModel, {
366 foreignKey: 'videoId',
367 through: () => VideoTagModel,
372 @HasMany(() => VideoAbuseModel, {
379 VideoAbuses: VideoAbuseModel[]
381 @HasMany(() => VideoFileModel, {
388 VideoFiles: VideoFileModel[]
390 @HasMany(() => VideoShareModel, {
397 VideoShares: VideoShareModel[]
399 @HasMany(() => AccountVideoRateModel, {
406 AccountVideoRates: AccountVideoRateModel[]
408 @HasMany(() => VideoCommentModel, {
416 VideoComments: VideoCommentModel[]
419 static async sendDelete (instance: VideoModel, options) {
420 if (instance.isOwned()) {
421 if (!instance.VideoChannel) {
422 instance.VideoChannel = await instance.$get('VideoChannel', {
426 include: [ ActorModel ]
429 transaction: options.transaction
430 }) as VideoChannelModel
433 logger.debug('Sending delete of video %s.', instance.url)
435 return sendDeleteVideo(instance, options.transaction)
442 static async removeFilesAndSendDelete (instance: VideoModel) {
443 const tasks: Promise<any>[] = []
445 tasks.push(instance.removeThumbnail())
447 if (instance.isOwned()) {
448 if (!Array.isArray(instance.VideoFiles)) {
449 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
452 tasks.push(instance.removePreview())
454 // Remove physical files and torrents
455 instance.VideoFiles.forEach(file => {
456 tasks.push(instance.removeFile(file))
457 tasks.push(instance.removeTorrent(file))
461 return Promise.all(tasks)
463 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
468 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
471 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
472 function getRawQuery (select: string) {
473 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
474 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
475 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
476 'WHERE "Account"."actorId" = ' + actorId
477 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
478 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
479 'WHERE "VideoShare"."actorId" = ' + actorId
481 return `(${queryVideo}) UNION (${queryVideoShare})`
484 const rawQuery = getRawQuery('"Video"."id"')
485 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
491 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
494 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
497 { privacy: VideoPrivacy.PUBLIC },
498 { privacy: VideoPrivacy.UNLISTED }
503 attributes: [ 'id', 'url' ],
504 model: VideoShareModel.unscoped(),
507 [Sequelize.Op.and]: [
510 [Sequelize.Op.not]: null
520 attributes: [ 'id', 'url' ],
521 model: ActorModel.unscoped()
526 model: VideoChannelModel.unscoped(),
530 attributes: [ 'name' ],
531 model: AccountModel.unscoped(),
535 attributes: [ 'id', 'url' ],
536 model: ActorModel.unscoped(),
542 attributes: [ 'id', 'url' ],
543 model: ActorModel.unscoped(),
549 attributes: [ 'type' ],
550 model: AccountVideoRateModel,
554 attributes: [ 'id' ],
555 model: AccountModel.unscoped(),
558 attributes: [ 'url' ],
559 model: ActorModel.unscoped(),
562 attributes: [ 'host' ],
573 attributes: [ 'url' ],
574 model: VideoCommentModel,
582 return Bluebird.all([
583 // FIXME: typing issue
584 VideoModel.findAll(query as any),
585 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
586 ]).then(([ rows, totals ]) => {
587 // totals: totalVideos + totalVideoShares
589 let totalVideoShares = 0
590 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
591 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
593 const total = totalVideos + totalVideoShares
601 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
605 order: [ getSort(sort) ],
608 model: VideoChannelModel,
623 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
631 static async listForApi (start: number, count: number, sort: string) {
635 order: [ getSort(sort) ]
638 const serverActor = await getServerActor()
640 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
641 .findAndCountAll(query)
642 .then(({ rows, count }) => {
650 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
651 const query: IFindOptions<VideoModel> = {
654 order: [ getSort(sort) ],
657 [Sequelize.Op.iLike]: '%' + value + '%'
662 const serverActor = await getServerActor()
664 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
665 .findAndCountAll(query).then(({ rows, count }) => {
673 static load (id: number) {
674 return VideoModel.findById(id)
677 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
678 const query: IFindOptions<VideoModel> = {
684 if (t !== undefined) query.transaction = t
686 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
689 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
690 const query: IFindOptions<VideoModel> = {
699 if (t !== undefined) query.transaction = t
701 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
704 static loadAndPopulateAccountAndServerAndTags (id: number) {
706 order: [ [ 'Tags', 'name', 'ASC' ] ]
710 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
711 .findById(id, options)
714 static loadByUUID (uuid: string) {
722 .scope([ ScopeNames.WITH_FILES ])
726 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
728 order: [ [ 'Tags', 'name', 'ASC' ] ],
735 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
739 static loadAndPopulateAll (id: number) {
741 order: [ [ 'Tags', 'name', 'ASC' ] ],
749 ScopeNames.WITH_RATES,
750 ScopeNames.WITH_SHARES,
751 ScopeNames.WITH_TAGS,
752 ScopeNames.WITH_FILES,
753 ScopeNames.WITH_ACCOUNT_DETAILS,
754 ScopeNames.WITH_COMMENTS
760 if (Array.isArray(this.VideoFiles) === false) return undefined
762 // The original file is the file that have the higher resolution
763 return maxBy(this.VideoFiles, file => file.resolution)
766 getVideoFilename (videoFile: VideoFileModel) {
767 return this.uuid + '-' + videoFile.resolution + videoFile.extname
770 getThumbnailName () {
771 // We always have a copy of the thumbnail
772 const extension = '.jpg'
773 return this.uuid + extension
777 const extension = '.jpg'
778 return this.uuid + extension
781 getTorrentFileName (videoFile: VideoFileModel) {
782 const extension = '.torrent'
783 return this.uuid + '-' + videoFile.resolution + extension
787 return this.remote === false
790 createPreview (videoFile: VideoFileModel) {
791 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
793 return generateImageFromVideoFile(
794 this.getVideoFilePath(videoFile),
795 CONFIG.STORAGE.PREVIEWS_DIR,
796 this.getPreviewName(),
801 createThumbnail (videoFile: VideoFileModel) {
802 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
804 return generateImageFromVideoFile(
805 this.getVideoFilePath(videoFile),
806 CONFIG.STORAGE.THUMBNAILS_DIR,
807 this.getThumbnailName(),
812 getVideoFilePath (videoFile: VideoFileModel) {
813 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
816 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
819 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
820 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
823 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
827 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
829 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
830 logger.info('Creating torrent %s.', filePath)
832 await writeFilePromise(filePath, torrent)
834 const parsedTorrent = parseTorrent(torrent)
835 videoFile.infoHash = parsedTorrent.infoHash
839 return '/videos/embed/' + this.uuid
842 getThumbnailPath () {
843 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
847 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
850 toFormattedJSON (): Video {
853 if (this.VideoChannel.Account.Actor.Server) {
854 serverHost = this.VideoChannel.Account.Actor.Server.host
856 // It means it's our video
857 serverHost = CONFIG.WEBSERVER.HOST
864 category: this.category,
865 categoryLabel: this.getCategoryLabel(),
866 licence: this.licence,
867 licenceLabel: this.getLicenceLabel(),
868 language: this.language,
869 languageLabel: this.getLanguageLabel(),
871 description: this.getTruncatedDescription(),
873 isLocal: this.isOwned(),
874 accountName: this.VideoChannel.Account.name,
875 duration: this.duration,
878 dislikes: this.dislikes,
879 thumbnailPath: this.getThumbnailPath(),
880 previewPath: this.getPreviewPath(),
881 embedPath: this.getEmbedPath(),
882 createdAt: this.createdAt,
883 updatedAt: this.updatedAt
887 toFormattedDetailsJSON (): VideoDetails {
888 const formattedJson = this.toFormattedJSON()
890 // Maybe our server is not up to date and there are new privacy settings since our version
891 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
892 if (!privacyLabel) privacyLabel = 'Unknown'
894 const detailsJson = {
896 privacy: this.privacy,
897 support: this.support,
898 descriptionPath: this.getDescriptionPath(),
899 channel: this.VideoChannel.toFormattedJSON(),
900 account: this.VideoChannel.Account.toFormattedJSON(),
901 tags: map<TagModel, string>(this.Tags, 'name'),
902 commentsEnabled: this.commentsEnabled,
906 // Format and sort video files
907 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
908 detailsJson.files = this.VideoFiles
910 let resolutionLabel = videoFile.resolution + 'p'
913 resolution: videoFile.resolution,
915 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
916 size: videoFile.size,
917 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
918 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
922 if (a.resolution < b.resolution) return 1
923 if (a.resolution === b.resolution) return 0
927 return Object.assign(formattedJson, detailsJson)
930 toActivityPubObject (): VideoTorrentObject {
931 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
932 if (!this.Tags) this.Tags = []
934 const tag = this.Tags.map(t => ({
935 type: 'Hashtag' as 'Hashtag',
942 identifier: this.language + '',
943 name: this.getLanguageLabel()
950 identifier: this.category + '',
951 name: this.getCategoryLabel()
958 identifier: this.licence + '',
959 name: this.getLicenceLabel()
966 if (Array.isArray(this.AccountVideoRates)) {
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(),
1031 support: this.support,
1034 url: this.getThumbnailUrl(baseUrlHttp),
1035 mediaType: 'image/jpeg',
1036 width: THUMBNAILS_SIZE.width,
1037 height: THUMBNAILS_SIZE.height
1041 dislikes: dislikesObject,
1042 shares: sharesObject,
1043 comments: commentsObject,
1047 id: this.VideoChannel.Actor.url
1051 id: this.VideoChannel.Account.Actor.url
1057 toAnnouncesActivityPubObject () {
1058 const shares: string[] = []
1060 for (const videoShare of this.VideoShares) {
1061 shares.push(videoShare.url)
1064 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1067 toCommentsActivityPubObject () {
1068 const comments: string[] = []
1070 for (const videoComment of this.VideoComments) {
1071 comments.push(videoComment.url)
1074 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1077 toRatesActivityPubObjects () {
1078 const likes: string[] = []
1079 const dislikes: string[] = []
1081 for (const rate of this.AccountVideoRates) {
1082 if (rate.type === 'like') {
1083 likes.push(rate.Account.Actor.url)
1084 } else if (rate.type === 'dislike') {
1085 dislikes.push(rate.Account.Actor.url)
1089 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1090 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1092 return { likesObject, dislikesObject }
1095 getTruncatedDescription () {
1096 if (!this.description) return null
1099 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1102 return truncate(this.description, options)
1105 optimizeOriginalVideofile = async function () {
1106 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1107 const newExtname = '.mp4'
1108 const inputVideoFile = this.getOriginalFile()
1109 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1110 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1112 const transcodeOptions = {
1113 inputPath: videoInputPath,
1114 outputPath: videoOutputPath
1118 // Could be very long!
1119 await transcode(transcodeOptions)
1121 await unlinkPromise(videoInputPath)
1123 // Important to do this before getVideoFilename() to take in account the new file extension
1124 inputVideoFile.set('extname', newExtname)
1126 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1127 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1129 inputVideoFile.set('size', stats.size)
1131 await this.createTorrentAndSetInfoHash(inputVideoFile)
1132 await inputVideoFile.save()
1135 // Auto destruction...
1136 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1142 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1143 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1144 const extname = '.mp4'
1146 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1147 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1149 const newVideoFile = new VideoFileModel({
1155 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1157 const transcodeOptions = {
1158 inputPath: videoInputPath,
1159 outputPath: videoOutputPath,
1163 await transcode(transcodeOptions)
1165 const stats = await statPromise(videoOutputPath)
1167 newVideoFile.set('size', stats.size)
1169 await this.createTorrentAndSetInfoHash(newVideoFile)
1171 await newVideoFile.save()
1173 this.VideoFiles.push(newVideoFile)
1176 getOriginalFileHeight () {
1177 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1179 return getVideoFileHeight(originalFilePath)
1182 getDescriptionPath () {
1183 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1186 getCategoryLabel () {
1187 let categoryLabel = VIDEO_CATEGORIES[this.category]
1188 if (!categoryLabel) categoryLabel = 'Misc'
1190 return categoryLabel
1193 getLicenceLabel () {
1194 let licenceLabel = VIDEO_LICENCES[this.licence]
1195 if (!licenceLabel) licenceLabel = 'Unknown'
1200 getLanguageLabel () {
1201 let languageLabel = VIDEO_LANGUAGES[this.language]
1202 if (!languageLabel) languageLabel = 'Unknown'
1204 return languageLabel
1207 removeThumbnail () {
1208 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1209 return unlinkPromise(thumbnailPath)
1213 // Same name than video thumbnail
1214 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1217 removeFile (videoFile: VideoFileModel) {
1218 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1219 return unlinkPromise(filePath)
1222 removeTorrent (videoFile: VideoFileModel) {
1223 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1224 return unlinkPromise(torrentPath)
1227 getActivityStreamDuration () {
1228 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1229 return 'PT' + this.duration + 'S'
1232 private getBaseUrls () {
1236 if (this.isOwned()) {
1237 baseUrlHttp = CONFIG.WEBSERVER.URL
1238 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1240 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1241 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1244 return { baseUrlHttp, baseUrlWs }
1247 private getThumbnailUrl (baseUrlHttp: string) {
1248 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1251 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1252 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1255 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1256 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1259 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1260 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1261 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1262 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1264 const magnetHash = {
1268 infoHash: videoFile.infoHash,
1272 return magnetUtil.encode(magnetHash)