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'
8 AfterDestroy, AllowNull, BeforeDestroy, BelongsTo, BelongsToMany, Column, CreatedAt, DataType, Default, ForeignKey, HasMany,
9 IFindOptions, Is, IsInt, IsUUID, Min, Model, Scopes, Table, UpdatedAt
10 } from 'sequelize-typescript'
11 import { VideoPrivacy, VideoResolution } from '../../../shared'
12 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
13 import { Video, VideoDetails } from '../../../shared/models/videos'
14 import { activityPubCollection } from '../../helpers/activitypub'
15 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
16 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
17 import { isBooleanValid } from '../../helpers/custom-validators/misc'
19 isVideoCategoryValid, isVideoDescriptionValid, isVideoDurationValid, isVideoLanguageValid, isVideoLicenceValid, isVideoNameValid,
21 } from '../../helpers/custom-validators/videos'
22 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
23 import { logger } from '../../helpers/logger'
24 import { getServerActor } from '../../helpers/utils'
26 API_VERSION, CONFIG, CONSTRAINTS_FIELDS, PREVIEWS_SIZE, REMOTE_SCHEME, STATIC_PATHS, THUMBNAILS_SIZE, VIDEO_CATEGORIES,
27 VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES
28 } from '../../initializers'
29 import { getAnnounceActivityPubUrl } from '../../lib/activitypub'
30 import { sendDeleteVideo } from '../../lib/activitypub/send'
31 import { AccountModel } from '../account/account'
32 import { AccountVideoRateModel } from '../account/account-video-rate'
33 import { ActorModel } from '../activitypub/actor'
34 import { ActorFollowModel } from '../activitypub/actor-follow'
35 import { ServerModel } from '../server/server'
36 import { getSort, throwIfNotValid } from '../utils'
37 import { TagModel } from './tag'
38 import { VideoAbuseModel } from './video-abuse'
39 import { VideoChannelModel } from './video-channel'
40 import { VideoCommentModel } from './video-comment'
41 import { VideoFileModel } from './video-file'
42 import { VideoShareModel } from './video-share'
43 import { VideoTagModel } from './video-tag'
46 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
47 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
48 WITH_TAGS = 'WITH_TAGS',
49 WITH_FILES = 'WITH_FILES',
50 WITH_SHARES = 'WITH_SHARES',
51 WITH_RATES = 'WITH_RATES',
52 WITH_COMMENTS = 'WITH_COMMENTS'
56 [ScopeNames.AVAILABLE_FOR_LIST]: (actorId: number) => ({
60 [Sequelize.Op.notIn]: Sequelize.literal(
61 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
64 privacy: VideoPrivacy.PUBLIC,
67 '$VideoChannel.Account.Actor.serverId$': null
70 '$VideoChannel.Account.Actor.ActorFollowers.actorId$': actorId
74 [ Sequelize.Op.in ]: Sequelize.literal(
76 'SELECT "videoShare"."videoId" FROM "videoShare" ' +
77 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
78 'WHERE "actorFollow"."actorId" = ' + parseInt(actorId.toString(), 10) +
87 attributes: [ 'name', 'description' ],
88 model: VideoChannelModel.unscoped(),
92 attributes: [ 'name' ],
93 model: AccountModel.unscoped(),
97 attributes: [ 'serverId' ],
98 model: ActorModel.unscoped(),
102 attributes: [ 'host' ],
103 model: ServerModel.unscoped(),
108 model: ActorFollowModel.unscoped(),
109 as: 'ActorFollowers',
120 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
123 model: () => VideoChannelModel.unscoped(),
128 exclude: [ 'privateKey', 'publicKey' ]
130 model: () => ActorModel.unscoped(),
134 attributes: [ 'host' ],
135 model: () => ServerModel.unscoped(),
141 model: () => AccountModel.unscoped(),
145 model: () => ActorModel.unscoped(),
147 exclude: [ 'privateKey', 'publicKey' ]
152 attributes: [ 'host' ],
153 model: () => ServerModel.unscoped(),
164 [ScopeNames.WITH_TAGS]: {
165 include: [ () => TagModel ]
167 [ScopeNames.WITH_FILES]: {
170 model: () => VideoFileModel,
175 [ScopeNames.WITH_SHARES]: {
178 model: () => VideoShareModel,
179 include: [ () => ActorModel ]
183 [ScopeNames.WITH_RATES]: {
186 model: () => AccountVideoRateModel,
187 include: [ () => AccountModel ]
191 [ScopeNames.WITH_COMMENTS]: {
194 model: () => VideoCommentModel
206 fields: [ 'createdAt' ]
209 fields: [ 'duration' ]
221 fields: [ 'channelId' ]
224 fields: [ 'id', 'privacy' ]
232 export class VideoModel extends Model<VideoModel> {
235 @Default(DataType.UUIDV4)
237 @Column(DataType.UUID)
241 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
247 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
253 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
259 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
264 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
269 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
275 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
276 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
280 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
310 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
311 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
316 commentsEnabled: boolean
324 @ForeignKey(() => VideoChannelModel)
328 @BelongsTo(() => VideoChannelModel, {
334 VideoChannel: VideoChannelModel
336 @BelongsToMany(() => TagModel, {
337 foreignKey: 'videoId',
338 through: () => VideoTagModel,
343 @HasMany(() => VideoAbuseModel, {
350 VideoAbuses: VideoAbuseModel[]
352 @HasMany(() => VideoFileModel, {
359 VideoFiles: VideoFileModel[]
361 @HasMany(() => VideoShareModel, {
368 VideoShares: VideoShareModel[]
370 @HasMany(() => AccountVideoRateModel, {
377 AccountVideoRates: AccountVideoRateModel[]
379 @HasMany(() => VideoCommentModel, {
387 VideoComments: VideoCommentModel[]
390 static async sendDelete (instance: VideoModel, options) {
391 if (instance.isOwned()) {
392 if (!instance.VideoChannel) {
393 instance.VideoChannel = await instance.$get('VideoChannel', {
397 include: [ ActorModel ]
400 transaction: options.transaction
401 }) as VideoChannelModel
404 logger.debug('Sending delete of video %s.', instance.url)
406 return sendDeleteVideo(instance, options.transaction)
413 static async removeFilesAndSendDelete (instance: VideoModel) {
414 const tasks: Promise<any>[] = []
416 tasks.push(instance.removeThumbnail())
418 if (instance.isOwned()) {
419 if (!Array.isArray(instance.VideoFiles)) {
420 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
423 tasks.push(instance.removePreview())
425 // Remove physical files and torrents
426 instance.VideoFiles.forEach(file => {
427 tasks.push(instance.removeFile(file))
428 tasks.push(instance.removeTorrent(file))
432 return Promise.all(tasks)
434 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
439 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
442 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
443 function getRawQuery (select: string) {
444 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
445 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
446 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
447 'WHERE "Account"."actorId" = ' + actorId
448 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
449 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
450 'WHERE "VideoShare"."actorId" = ' + actorId
452 return `(${queryVideo}) UNION (${queryVideoShare})`
455 const rawQuery = getRawQuery('"Video"."id"')
456 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
462 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
465 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
470 attributes: [ 'id' ],
471 model: VideoShareModel.unscoped(),
474 [Sequelize.Op.and]: [
477 [Sequelize.Op.not]: null
487 attributes: [ 'id', 'url' ],
488 model: ActorModel.unscoped()
493 model: VideoChannelModel.unscoped(),
497 attributes: [ 'name' ],
498 model: AccountModel.unscoped(),
502 attributes: [ 'id', 'url' ],
503 model: ActorModel.unscoped(),
509 attributes: [ 'id', 'url' ],
510 model: ActorModel.unscoped(),
516 attributes: [ 'type' ],
517 model: AccountVideoRateModel,
521 attributes: [ 'id' ],
522 model: AccountModel.unscoped(),
525 attributes: [ 'url' ],
526 model: ActorModel.unscoped(),
529 attributes: [ 'host' ],
540 attributes: [ 'url' ],
541 model: VideoCommentModel,
549 return Bluebird.all([
550 // FIXME: typing issue
551 VideoModel.findAll(query as any),
552 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
553 ]).then(([ rows, totals ]) => {
554 // totals: totalVideos + totalVideoShares
556 let totalVideoShares = 0
557 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
558 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
560 const total = totalVideos + totalVideoShares
568 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
572 order: [ getSort(sort) ],
575 model: VideoChannelModel,
590 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
598 static async listForApi (start: number, count: number, sort: string) {
602 order: [ getSort(sort) ]
605 const serverActor = await getServerActor()
607 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
608 .findAndCountAll(query)
609 .then(({ rows, count }) => {
617 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
618 const query: IFindOptions<VideoModel> = {
621 order: [ getSort(sort) ],
624 [Sequelize.Op.iLike]: '%' + value + '%'
629 const serverActor = await getServerActor()
631 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
632 .findAndCountAll(query).then(({ rows, count }) => {
640 static load (id: number) {
641 return VideoModel.findById(id)
644 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
645 const query: IFindOptions<VideoModel> = {
651 if (t !== undefined) query.transaction = t
653 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
656 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
657 const query: IFindOptions<VideoModel> = {
666 if (t !== undefined) query.transaction = t
668 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
671 static loadAndPopulateAccountAndServerAndTags (id: number) {
673 order: [ [ 'Tags', 'name', 'ASC' ] ]
677 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
678 .findById(id, options)
681 static loadByUUID (uuid: string) {
689 .scope([ ScopeNames.WITH_FILES ])
693 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
695 order: [ [ 'Tags', 'name', 'ASC' ] ],
702 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
706 static loadAndPopulateAll (id: number) {
708 order: [ [ 'Tags', 'name', 'ASC' ] ],
716 ScopeNames.WITH_RATES,
717 ScopeNames.WITH_SHARES,
718 ScopeNames.WITH_TAGS,
719 ScopeNames.WITH_FILES,
720 ScopeNames.WITH_ACCOUNT_DETAILS,
721 ScopeNames.WITH_COMMENTS
727 if (Array.isArray(this.VideoFiles) === false) return undefined
729 // The original file is the file that have the higher resolution
730 return maxBy(this.VideoFiles, file => file.resolution)
733 getVideoFilename (videoFile: VideoFileModel) {
734 return this.uuid + '-' + videoFile.resolution + videoFile.extname
737 getThumbnailName () {
738 // We always have a copy of the thumbnail
739 const extension = '.jpg'
740 return this.uuid + extension
744 const extension = '.jpg'
745 return this.uuid + extension
748 getTorrentFileName (videoFile: VideoFileModel) {
749 const extension = '.torrent'
750 return this.uuid + '-' + videoFile.resolution + extension
754 return this.remote === false
757 createPreview (videoFile: VideoFileModel) {
758 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
760 return generateImageFromVideoFile(
761 this.getVideoFilePath(videoFile),
762 CONFIG.STORAGE.PREVIEWS_DIR,
763 this.getPreviewName(),
768 createThumbnail (videoFile: VideoFileModel) {
769 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
771 return generateImageFromVideoFile(
772 this.getVideoFilePath(videoFile),
773 CONFIG.STORAGE.THUMBNAILS_DIR,
774 this.getThumbnailName(),
779 getVideoFilePath (videoFile: VideoFileModel) {
780 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
783 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
786 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
789 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
793 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
795 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
796 logger.info('Creating torrent %s.', filePath)
798 await writeFilePromise(filePath, torrent)
800 const parsedTorrent = parseTorrent(torrent)
801 videoFile.infoHash = parsedTorrent.infoHash
805 return '/videos/embed/' + this.uuid
808 getThumbnailPath () {
809 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
813 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
819 if (this.VideoChannel.Account.Actor.Server) {
820 serverHost = this.VideoChannel.Account.Actor.Server.host
822 // It means it's our video
823 serverHost = CONFIG.WEBSERVER.HOST
830 category: this.category,
831 categoryLabel: this.getCategoryLabel(),
832 licence: this.licence,
833 licenceLabel: this.getLicenceLabel(),
834 language: this.language,
835 languageLabel: this.getLanguageLabel(),
837 description: this.getTruncatedDescription(),
839 isLocal: this.isOwned(),
840 accountName: this.VideoChannel.Account.name,
841 duration: this.duration,
844 dislikes: this.dislikes,
845 thumbnailPath: this.getThumbnailPath(),
846 previewPath: this.getPreviewPath(),
847 embedPath: this.getEmbedPath(),
848 createdAt: this.createdAt,
849 updatedAt: this.updatedAt
853 toFormattedDetailsJSON () {
854 const formattedJson = this.toFormattedJSON()
856 // Maybe our server is not up to date and there are new privacy settings since our version
857 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
858 if (!privacyLabel) privacyLabel = 'Unknown'
860 const detailsJson = {
862 privacy: this.privacy,
863 descriptionPath: this.getDescriptionPath(),
864 channel: this.VideoChannel.toFormattedJSON(),
865 account: this.VideoChannel.Account.toFormattedJSON(),
866 tags: map<TagModel, string>(this.Tags, 'name'),
867 commentsEnabled: this.commentsEnabled,
871 // Format and sort video files
872 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
873 detailsJson.files = this.VideoFiles
875 let resolutionLabel = videoFile.resolution + 'p'
878 resolution: videoFile.resolution,
880 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
881 size: videoFile.size,
882 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
883 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
887 if (a.resolution < b.resolution) return 1
888 if (a.resolution === b.resolution) return 0
892 return Object.assign(formattedJson, detailsJson) as VideoDetails
895 toActivityPubObject (): VideoTorrentObject {
896 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
897 if (!this.Tags) this.Tags = []
899 const tag = this.Tags.map(t => ({
900 type: 'Hashtag' as 'Hashtag',
907 identifier: this.language + '',
908 name: this.getLanguageLabel()
915 identifier: this.category + '',
916 name: this.getCategoryLabel()
923 identifier: this.licence + '',
924 name: this.getLicenceLabel()
931 if (Array.isArray(this.AccountVideoRates)) {
932 const likes: string[] = []
933 const dislikes: string[] = []
935 for (const rate of this.AccountVideoRates) {
936 if (rate.type === 'like') {
937 likes.push(rate.Account.Actor.url)
938 } else if (rate.type === 'dislike') {
939 dislikes.push(rate.Account.Actor.url)
943 likesObject = activityPubCollection(likes)
944 dislikesObject = activityPubCollection(dislikes)
948 if (Array.isArray(this.VideoShares)) {
949 const shares: string[] = []
951 for (const videoShare of this.VideoShares) {
952 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
953 shares.push(shareUrl)
956 sharesObject = activityPubCollection(shares)
960 if (Array.isArray(this.VideoComments)) {
961 const comments: string[] = []
963 for (const videoComment of this.VideoComments) {
964 comments.push(videoComment.url)
967 commentsObject = activityPubCollection(comments)
971 for (const file of this.VideoFiles) {
974 mimeType: 'video/' + file.extname.replace('.', ''),
975 href: this.getVideoFileUrl(file, baseUrlHttp),
976 width: file.resolution,
982 mimeType: 'application/x-bittorrent',
983 href: this.getTorrentUrl(file, baseUrlHttp),
984 width: file.resolution
989 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
990 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
991 width: file.resolution
998 mimeType: 'text/html',
999 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1003 type: 'Video' as 'Video',
1006 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1007 duration: 'PT' + this.duration + 'S',
1015 commentsEnabled: this.commentsEnabled,
1016 published: this.createdAt.toISOString(),
1017 updated: this.updatedAt.toISOString(),
1018 mediaType: 'text/markdown',
1019 content: this.getTruncatedDescription(),
1022 url: this.getThumbnailUrl(baseUrlHttp),
1023 mediaType: 'image/jpeg',
1024 width: THUMBNAILS_SIZE.width,
1025 height: THUMBNAILS_SIZE.height
1029 dislikes: dislikesObject,
1030 shares: sharesObject,
1031 comments: commentsObject,
1035 id: this.VideoChannel.Actor.url
1039 id: this.VideoChannel.Account.Actor.url
1045 getTruncatedDescription () {
1046 if (!this.description) return null
1049 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1052 return truncate(this.description, options)
1055 optimizeOriginalVideofile = async function () {
1056 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1057 const newExtname = '.mp4'
1058 const inputVideoFile = this.getOriginalFile()
1059 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1060 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1062 const transcodeOptions = {
1063 inputPath: videoInputPath,
1064 outputPath: videoOutputPath
1068 // Could be very long!
1069 await transcode(transcodeOptions)
1071 await unlinkPromise(videoInputPath)
1073 // Important to do this before getVideoFilename() to take in account the new file extension
1074 inputVideoFile.set('extname', newExtname)
1076 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1077 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1079 inputVideoFile.set('size', stats.size)
1081 await this.createTorrentAndSetInfoHash(inputVideoFile)
1082 await inputVideoFile.save()
1085 // Auto destruction...
1086 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1092 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1093 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1094 const extname = '.mp4'
1096 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1097 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1099 const newVideoFile = new VideoFileModel({
1105 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1107 const transcodeOptions = {
1108 inputPath: videoInputPath,
1109 outputPath: videoOutputPath,
1113 await transcode(transcodeOptions)
1115 const stats = await statPromise(videoOutputPath)
1117 newVideoFile.set('size', stats.size)
1119 await this.createTorrentAndSetInfoHash(newVideoFile)
1121 await newVideoFile.save()
1123 this.VideoFiles.push(newVideoFile)
1126 getOriginalFileHeight () {
1127 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1129 return getVideoFileHeight(originalFilePath)
1132 getDescriptionPath () {
1133 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1136 getCategoryLabel () {
1137 let categoryLabel = VIDEO_CATEGORIES[this.category]
1138 if (!categoryLabel) categoryLabel = 'Misc'
1140 return categoryLabel
1143 getLicenceLabel () {
1144 let licenceLabel = VIDEO_LICENCES[this.licence]
1145 if (!licenceLabel) licenceLabel = 'Unknown'
1150 getLanguageLabel () {
1151 let languageLabel = VIDEO_LANGUAGES[this.language]
1152 if (!languageLabel) languageLabel = 'Unknown'
1154 return languageLabel
1157 removeThumbnail () {
1158 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1159 return unlinkPromise(thumbnailPath)
1163 // Same name than video thumbnail
1164 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1167 removeFile (videoFile: VideoFileModel) {
1168 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1169 return unlinkPromise(filePath)
1172 removeTorrent (videoFile: VideoFileModel) {
1173 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1174 return unlinkPromise(torrentPath)
1177 private getBaseUrls () {
1181 if (this.isOwned()) {
1182 baseUrlHttp = CONFIG.WEBSERVER.URL
1183 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1185 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1186 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1189 return { baseUrlHttp, baseUrlWs }
1192 private getThumbnailUrl (baseUrlHttp: string) {
1193 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1196 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1197 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1200 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1201 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1204 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1205 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1206 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1207 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1209 const magnetHash = {
1213 infoHash: videoFile.infoHash,
1217 return magnetUtil.encode(magnetHash)