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 { AvatarModel } from '../avatar/avatar'
72 import { ServerModel } from '../server/server'
73 import { getSort, throwIfNotValid } from '../utils'
74 import { TagModel } from './tag'
75 import { VideoAbuseModel } from './video-abuse'
76 import { VideoChannelModel } from './video-channel'
77 import { VideoCommentModel } from './video-comment'
78 import { VideoFileModel } from './video-file'
79 import { VideoShareModel } from './video-share'
80 import { VideoTagModel } from './video-tag'
83 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
84 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
85 WITH_TAGS = 'WITH_TAGS',
86 WITH_FILES = 'WITH_FILES',
87 WITH_SHARES = 'WITH_SHARES',
88 WITH_RATES = 'WITH_RATES',
89 WITH_COMMENTS = 'WITH_COMMENTS'
93 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
96 [Sequelize.Op.notIn]: Sequelize.literal(
97 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
99 [ Sequelize.Op.in ]: Sequelize.literal(
101 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
102 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
103 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
105 'SELECT "video"."id" AS "id" FROM "video" ' +
106 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
107 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
108 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
109 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
110 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
114 privacy: VideoPrivacy.PUBLIC
118 attributes: [ 'name', 'description' ],
119 model: VideoChannelModel.unscoped(),
123 attributes: [ 'name' ],
124 model: AccountModel.unscoped(),
128 attributes: [ 'serverId' ],
129 model: ActorModel.unscoped(),
133 attributes: [ 'host' ],
134 model: ServerModel.unscoped()
144 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
147 model: () => VideoChannelModel.unscoped(),
152 exclude: [ 'privateKey', 'publicKey' ]
154 model: () => ActorModel.unscoped(),
158 attributes: [ 'host' ],
159 model: () => ServerModel.unscoped(),
165 model: () => AccountModel.unscoped(),
169 model: () => ActorModel.unscoped(),
171 exclude: [ 'privateKey', 'publicKey' ]
176 attributes: [ 'host' ],
177 model: () => ServerModel.unscoped(),
181 model: () => AvatarModel.unscoped(),
192 [ScopeNames.WITH_TAGS]: {
193 include: [ () => TagModel ]
195 [ScopeNames.WITH_FILES]: {
198 model: () => VideoFileModel,
203 [ScopeNames.WITH_SHARES]: {
206 model: () => VideoShareModel,
207 include: [ () => ActorModel ]
211 [ScopeNames.WITH_RATES]: {
214 model: () => AccountVideoRateModel,
215 include: [ () => AccountModel ]
219 [ScopeNames.WITH_COMMENTS]: {
222 model: () => VideoCommentModel
234 fields: [ 'createdAt' ]
237 fields: [ 'duration' ]
249 fields: [ 'channelId' ]
252 fields: [ 'id', 'privacy' ]
260 export class VideoModel extends Model<VideoModel> {
263 @Default(DataType.UUIDV4)
265 @Column(DataType.UUID)
269 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
275 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
281 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
287 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
292 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
297 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
303 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
304 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
309 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
310 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
314 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
344 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
345 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
350 commentsEnabled: boolean
358 @ForeignKey(() => VideoChannelModel)
362 @BelongsTo(() => VideoChannelModel, {
368 VideoChannel: VideoChannelModel
370 @BelongsToMany(() => TagModel, {
371 foreignKey: 'videoId',
372 through: () => VideoTagModel,
377 @HasMany(() => VideoAbuseModel, {
384 VideoAbuses: VideoAbuseModel[]
386 @HasMany(() => VideoFileModel, {
393 VideoFiles: VideoFileModel[]
395 @HasMany(() => VideoShareModel, {
402 VideoShares: VideoShareModel[]
404 @HasMany(() => AccountVideoRateModel, {
411 AccountVideoRates: AccountVideoRateModel[]
413 @HasMany(() => VideoCommentModel, {
421 VideoComments: VideoCommentModel[]
424 static async sendDelete (instance: VideoModel, options) {
425 if (instance.isOwned()) {
426 if (!instance.VideoChannel) {
427 instance.VideoChannel = await instance.$get('VideoChannel', {
431 include: [ ActorModel ]
434 transaction: options.transaction
435 }) as VideoChannelModel
438 logger.debug('Sending delete of video %s.', instance.url)
440 return sendDeleteVideo(instance, options.transaction)
447 static async removeFilesAndSendDelete (instance: VideoModel) {
448 const tasks: Promise<any>[] = []
450 tasks.push(instance.removeThumbnail())
452 if (instance.isOwned()) {
453 if (!Array.isArray(instance.VideoFiles)) {
454 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
457 tasks.push(instance.removePreview())
459 // Remove physical files and torrents
460 instance.VideoFiles.forEach(file => {
461 tasks.push(instance.removeFile(file))
462 tasks.push(instance.removeTorrent(file))
466 return Promise.all(tasks)
468 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
473 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
476 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
477 function getRawQuery (select: string) {
478 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
479 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
480 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
481 'WHERE "Account"."actorId" = ' + actorId
482 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
483 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
484 'WHERE "VideoShare"."actorId" = ' + actorId
486 return `(${queryVideo}) UNION (${queryVideoShare})`
489 const rawQuery = getRawQuery('"Video"."id"')
490 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
496 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
499 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
502 { privacy: VideoPrivacy.PUBLIC },
503 { privacy: VideoPrivacy.UNLISTED }
508 attributes: [ 'id', 'url' ],
509 model: VideoShareModel.unscoped(),
512 [Sequelize.Op.and]: [
515 [Sequelize.Op.not]: null
525 attributes: [ 'id', 'url' ],
526 model: ActorModel.unscoped()
531 model: VideoChannelModel.unscoped(),
535 attributes: [ 'name' ],
536 model: AccountModel.unscoped(),
540 attributes: [ 'id', 'url' ],
541 model: ActorModel.unscoped(),
547 attributes: [ 'id', 'url' ],
548 model: ActorModel.unscoped(),
554 attributes: [ 'type' ],
555 model: AccountVideoRateModel,
559 attributes: [ 'id' ],
560 model: AccountModel.unscoped(),
563 attributes: [ 'url' ],
564 model: ActorModel.unscoped(),
567 attributes: [ 'host' ],
578 attributes: [ 'url' ],
579 model: VideoCommentModel,
587 return Bluebird.all([
588 // FIXME: typing issue
589 VideoModel.findAll(query as any),
590 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
591 ]).then(([ rows, totals ]) => {
592 // totals: totalVideos + totalVideoShares
594 let totalVideoShares = 0
595 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
596 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
598 const total = totalVideos + totalVideoShares
606 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
610 order: getSort(sort),
613 model: VideoChannelModel,
628 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
636 static async listForApi (start: number, count: number, sort: string) {
643 const serverActor = await getServerActor()
645 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
646 .findAndCountAll(query)
647 .then(({ rows, count }) => {
655 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
656 const query: IFindOptions<VideoModel> = {
659 order: getSort(sort),
662 [Sequelize.Op.iLike]: '%' + value + '%'
667 const serverActor = await getServerActor()
669 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
670 .findAndCountAll(query).then(({ rows, count }) => {
678 static load (id: number) {
679 return VideoModel.findById(id)
682 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
683 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 loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
695 const query: IFindOptions<VideoModel> = {
704 if (t !== undefined) query.transaction = t
706 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
709 static loadAndPopulateAccountAndServerAndTags (id: number) {
711 order: [ [ 'Tags', 'name', 'ASC' ] ]
715 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
716 .findById(id, options)
719 static loadByUUID (uuid: string) {
727 .scope([ ScopeNames.WITH_FILES ])
731 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
733 order: [ [ 'Tags', 'name', 'ASC' ] ],
740 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
744 static loadAndPopulateAll (id: number) {
746 order: [ [ 'Tags', 'name', 'ASC' ] ],
754 ScopeNames.WITH_RATES,
755 ScopeNames.WITH_SHARES,
756 ScopeNames.WITH_TAGS,
757 ScopeNames.WITH_FILES,
758 ScopeNames.WITH_ACCOUNT_DETAILS,
759 ScopeNames.WITH_COMMENTS
765 if (Array.isArray(this.VideoFiles) === false) return undefined
767 // The original file is the file that have the higher resolution
768 return maxBy(this.VideoFiles, file => file.resolution)
771 getVideoFilename (videoFile: VideoFileModel) {
772 return this.uuid + '-' + videoFile.resolution + videoFile.extname
775 getThumbnailName () {
776 // We always have a copy of the thumbnail
777 const extension = '.jpg'
778 return this.uuid + extension
782 const extension = '.jpg'
783 return this.uuid + extension
786 getTorrentFileName (videoFile: VideoFileModel) {
787 const extension = '.torrent'
788 return this.uuid + '-' + videoFile.resolution + extension
792 return this.remote === false
795 createPreview (videoFile: VideoFileModel) {
796 return generateImageFromVideoFile(
797 this.getVideoFilePath(videoFile),
798 CONFIG.STORAGE.PREVIEWS_DIR,
799 this.getPreviewName(),
804 createThumbnail (videoFile: VideoFileModel) {
805 return generateImageFromVideoFile(
806 this.getVideoFilePath(videoFile),
807 CONFIG.STORAGE.THUMBNAILS_DIR,
808 this.getThumbnailName(),
813 getVideoFilePath (videoFile: VideoFileModel) {
814 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
817 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
820 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
821 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
824 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
828 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
830 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
831 logger.info('Creating torrent %s.', filePath)
833 await writeFilePromise(filePath, torrent)
835 const parsedTorrent = parseTorrent(torrent)
836 videoFile.infoHash = parsedTorrent.infoHash
840 return '/videos/embed/' + this.uuid
843 getThumbnailPath () {
844 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
848 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
851 toFormattedJSON (): Video {
854 if (this.VideoChannel.Account.Actor.Server) {
855 serverHost = this.VideoChannel.Account.Actor.Server.host
857 // It means it's our video
858 serverHost = CONFIG.WEBSERVER.HOST
865 category: this.category,
866 categoryLabel: this.getCategoryLabel(),
867 licence: this.licence,
868 licenceLabel: this.getLicenceLabel(),
869 language: this.language,
870 languageLabel: this.getLanguageLabel(),
872 description: this.getTruncatedDescription(),
874 isLocal: this.isOwned(),
875 accountName: this.VideoChannel.Account.name,
876 duration: this.duration,
879 dislikes: this.dislikes,
880 thumbnailPath: this.getThumbnailPath(),
881 previewPath: this.getPreviewPath(),
882 embedPath: this.getEmbedPath(),
883 createdAt: this.createdAt,
884 updatedAt: this.updatedAt
888 toFormattedDetailsJSON (): VideoDetails {
889 const formattedJson = this.toFormattedJSON()
891 // Maybe our server is not up to date and there are new privacy settings since our version
892 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
893 if (!privacyLabel) privacyLabel = 'Unknown'
895 const detailsJson = {
897 privacy: this.privacy,
898 support: this.support,
899 descriptionPath: this.getDescriptionPath(),
900 channel: this.VideoChannel.toFormattedJSON(),
901 account: this.VideoChannel.Account.toFormattedJSON(),
902 tags: map<TagModel, string>(this.Tags, 'name'),
903 commentsEnabled: this.commentsEnabled,
907 // Format and sort video files
908 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
909 detailsJson.files = this.VideoFiles
911 let resolutionLabel = videoFile.resolution + 'p'
914 resolution: videoFile.resolution,
916 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
917 size: videoFile.size,
918 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
919 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
923 if (a.resolution < b.resolution) return 1
924 if (a.resolution === b.resolution) return 0
928 return Object.assign(formattedJson, detailsJson)
931 toActivityPubObject (): VideoTorrentObject {
932 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
933 if (!this.Tags) this.Tags = []
935 const tag = this.Tags.map(t => ({
936 type: 'Hashtag' as 'Hashtag',
943 identifier: this.language + '',
944 name: this.getLanguageLabel()
951 identifier: this.category + '',
952 name: this.getCategoryLabel()
959 identifier: this.licence + '',
960 name: this.getLicenceLabel()
967 if (Array.isArray(this.AccountVideoRates)) {
968 const res = this.toRatesActivityPubObjects()
969 likesObject = res.likesObject
970 dislikesObject = res.dislikesObject
974 if (Array.isArray(this.VideoShares)) {
975 sharesObject = this.toAnnouncesActivityPubObject()
979 if (Array.isArray(this.VideoComments)) {
980 commentsObject = this.toCommentsActivityPubObject()
984 for (const file of this.VideoFiles) {
987 mimeType: 'video/' + file.extname.replace('.', ''),
988 href: this.getVideoFileUrl(file, baseUrlHttp),
989 width: file.resolution,
995 mimeType: 'application/x-bittorrent',
996 href: this.getTorrentUrl(file, baseUrlHttp),
997 width: file.resolution
1002 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1003 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1004 width: file.resolution
1008 // Add video url too
1011 mimeType: 'text/html',
1012 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1016 type: 'Video' as 'Video',
1019 duration: this.getActivityStreamDuration(),
1026 sensitive: this.nsfw,
1027 commentsEnabled: this.commentsEnabled,
1028 published: this.createdAt.toISOString(),
1029 updated: this.updatedAt.toISOString(),
1030 mediaType: 'text/markdown',
1031 content: this.getTruncatedDescription(),
1032 support: this.support,
1035 url: this.getThumbnailUrl(baseUrlHttp),
1036 mediaType: 'image/jpeg',
1037 width: THUMBNAILS_SIZE.width,
1038 height: THUMBNAILS_SIZE.height
1042 dislikes: dislikesObject,
1043 shares: sharesObject,
1044 comments: commentsObject,
1048 id: this.VideoChannel.Actor.url
1052 id: this.VideoChannel.Account.Actor.url
1058 toAnnouncesActivityPubObject () {
1059 const shares: string[] = []
1061 for (const videoShare of this.VideoShares) {
1062 shares.push(videoShare.url)
1065 return activityPubCollection(getVideoSharesActivityPubUrl(this), shares)
1068 toCommentsActivityPubObject () {
1069 const comments: string[] = []
1071 for (const videoComment of this.VideoComments) {
1072 comments.push(videoComment.url)
1075 return activityPubCollection(getVideoCommentsActivityPubUrl(this), comments)
1078 toRatesActivityPubObjects () {
1079 const likes: string[] = []
1080 const dislikes: string[] = []
1082 for (const rate of this.AccountVideoRates) {
1083 if (rate.type === 'like') {
1084 likes.push(rate.Account.Actor.url)
1085 } else if (rate.type === 'dislike') {
1086 dislikes.push(rate.Account.Actor.url)
1090 const likesObject = activityPubCollection(getVideoLikesActivityPubUrl(this), likes)
1091 const dislikesObject = activityPubCollection(getVideoDislikesActivityPubUrl(this), dislikes)
1093 return { likesObject, dislikesObject }
1096 getTruncatedDescription () {
1097 if (!this.description) return null
1100 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1103 return truncate(this.description, options)
1106 optimizeOriginalVideofile = async function () {
1107 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1108 const newExtname = '.mp4'
1109 const inputVideoFile = this.getOriginalFile()
1110 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1111 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1113 const transcodeOptions = {
1114 inputPath: videoInputPath,
1115 outputPath: videoOutputPath
1119 // Could be very long!
1120 await transcode(transcodeOptions)
1122 await unlinkPromise(videoInputPath)
1124 // Important to do this before getVideoFilename() to take in account the new file extension
1125 inputVideoFile.set('extname', newExtname)
1127 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1128 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1130 inputVideoFile.set('size', stats.size)
1132 await this.createTorrentAndSetInfoHash(inputVideoFile)
1133 await inputVideoFile.save()
1136 // Auto destruction...
1137 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1143 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1144 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1145 const extname = '.mp4'
1147 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1148 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1150 const newVideoFile = new VideoFileModel({
1156 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1158 const transcodeOptions = {
1159 inputPath: videoInputPath,
1160 outputPath: videoOutputPath,
1164 await transcode(transcodeOptions)
1166 const stats = await statPromise(videoOutputPath)
1168 newVideoFile.set('size', stats.size)
1170 await this.createTorrentAndSetInfoHash(newVideoFile)
1172 await newVideoFile.save()
1174 this.VideoFiles.push(newVideoFile)
1177 getOriginalFileHeight () {
1178 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1180 return getVideoFileHeight(originalFilePath)
1183 getDescriptionPath () {
1184 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1187 getCategoryLabel () {
1188 let categoryLabel = VIDEO_CATEGORIES[this.category]
1189 if (!categoryLabel) categoryLabel = 'Misc'
1191 return categoryLabel
1194 getLicenceLabel () {
1195 let licenceLabel = VIDEO_LICENCES[this.licence]
1196 if (!licenceLabel) licenceLabel = 'Unknown'
1201 getLanguageLabel () {
1202 let languageLabel = VIDEO_LANGUAGES[this.language]
1203 if (!languageLabel) languageLabel = 'Unknown'
1205 return languageLabel
1208 removeThumbnail () {
1209 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1210 return unlinkPromise(thumbnailPath)
1214 // Same name than video thumbnail
1215 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1218 removeFile (videoFile: VideoFileModel) {
1219 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1220 return unlinkPromise(filePath)
1223 removeTorrent (videoFile: VideoFileModel) {
1224 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1225 return unlinkPromise(torrentPath)
1228 getActivityStreamDuration () {
1229 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1230 return 'PT' + this.duration + 'S'
1233 private getBaseUrls () {
1237 if (this.isOwned()) {
1238 baseUrlHttp = CONFIG.WEBSERVER.URL
1239 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1241 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1242 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1245 return { baseUrlHttp, baseUrlWs }
1248 private getThumbnailUrl (baseUrlHttp: string) {
1249 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1252 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1253 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1256 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1257 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1260 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1261 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1262 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1263 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1265 const magnetHash = {
1269 infoHash: videoFile.infoHash,
1273 return magnetUtil.encode(magnetHash)