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, BelongsTo, BelongsToMany, Column, CreatedAt, DataType, Default, ForeignKey, HasMany, IFindOptions, Is,
9 IsInt, IsUUID, Min, Model, Scopes, Table, UpdatedAt
10 } from 'sequelize-typescript'
11 import { IIncludeOptions } from 'sequelize-typescript/lib/interfaces/IIncludeOptions'
12 import { VideoPrivacy, VideoResolution } from '../../../shared'
13 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
14 import { Video, VideoDetails } from '../../../shared/models/videos'
15 import { activityPubCollection } from '../../helpers/activitypub'
16 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
17 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
18 import { isBooleanValid } from '../../helpers/custom-validators/misc'
20 isVideoCategoryValid, isVideoDescriptionValid, isVideoDurationValid, isVideoLanguageValid, isVideoLicenceValid, isVideoNameValid,
22 } from '../../helpers/custom-validators/videos'
23 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
24 import { logger } from '../../helpers/logger'
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 { ServerModel } from '../server/server'
35 import { getSort, throwIfNotValid } from '../utils'
36 import { TagModel } from './tag'
37 import { VideoAbuseModel } from './video-abuse'
38 import { VideoChannelModel } from './video-channel'
39 import { VideoCommentModel } from './video-comment'
40 import { VideoFileModel } from './video-file'
41 import { VideoShareModel } from './video-share'
42 import { VideoTagModel } from './video-tag'
45 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
46 WITH_ACCOUNT_API = 'WITH_ACCOUNT_API',
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]: {
59 [Sequelize.Op.notIn]: Sequelize.literal(
60 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
63 privacy: VideoPrivacy.PUBLIC
66 [ScopeNames.WITH_ACCOUNT_API]: {
69 model: () => VideoChannelModel.unscoped(),
73 attributes: [ 'name' ],
74 model: () => AccountModel.unscoped(),
78 attributes: [ 'serverId' ],
79 model: () => ActorModel.unscoped(),
83 model: () => ServerModel.unscoped(),
94 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
97 model: () => VideoChannelModel.unscoped(),
102 exclude: [ 'privateKey', 'publicKey' ]
104 model: () => ActorModel,
108 model: () => AccountModel,
112 model: () => ActorModel,
114 exclude: [ 'privateKey', 'publicKey' ]
119 model: () => ServerModel,
130 [ScopeNames.WITH_TAGS]: {
131 include: [ () => TagModel ]
133 [ScopeNames.WITH_FILES]: {
136 model: () => VideoFileModel,
141 [ScopeNames.WITH_SHARES]: {
144 model: () => VideoShareModel,
145 include: [ () => ActorModel ]
149 [ScopeNames.WITH_RATES]: {
152 model: () => AccountVideoRateModel,
153 include: [ () => AccountModel ]
157 [ScopeNames.WITH_COMMENTS]: {
160 model: () => VideoCommentModel
172 fields: [ 'createdAt' ]
175 fields: [ 'duration' ]
187 fields: [ 'channelId' ]
190 fields: [ 'id', 'privacy' ]
198 export class VideoModel extends Model<VideoModel> {
201 @Default(DataType.UUIDV4)
203 @Column(DataType.UUID)
207 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
213 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
219 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
225 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
230 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
235 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
241 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
242 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
246 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
276 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
277 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
282 commentsEnabled: boolean
290 @ForeignKey(() => VideoChannelModel)
294 @BelongsTo(() => VideoChannelModel, {
300 VideoChannel: VideoChannelModel
302 @BelongsToMany(() => TagModel, {
303 foreignKey: 'videoId',
304 through: () => VideoTagModel,
309 @HasMany(() => VideoAbuseModel, {
316 VideoAbuses: VideoAbuseModel[]
318 @HasMany(() => VideoFileModel, {
325 VideoFiles: VideoFileModel[]
327 @HasMany(() => VideoShareModel, {
334 VideoShares: VideoShareModel[]
336 @HasMany(() => AccountVideoRateModel, {
343 AccountVideoRates: AccountVideoRateModel[]
345 @HasMany(() => VideoCommentModel, {
352 VideoComments: VideoCommentModel[]
355 static removeFilesAndSendDelete (instance: VideoModel) {
359 instance.removeThumbnail()
362 if (instance.isOwned()) {
364 instance.removePreview(),
365 sendDeleteVideo(instance, undefined)
368 // Remove physical files and torrents
369 instance.VideoFiles.forEach(file => {
370 tasks.push(instance.removeFile(file))
371 tasks.push(instance.removeTorrent(file))
375 return Promise.all(tasks)
377 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
382 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
385 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
386 function getRawQuery (select: string) {
387 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
388 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
389 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
390 'WHERE "Account"."actorId" = ' + actorId
391 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
392 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
393 'WHERE "VideoShare"."actorId" = ' + actorId
395 return `(${queryVideo}) UNION (${queryVideoShare})`
398 const rawQuery = getRawQuery('"Video"."id"')
399 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
405 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
408 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
413 model: VideoShareModel,
416 [Sequelize.Op.and]: [
419 [Sequelize.Op.not]: null
435 model: VideoChannelModel,
445 model: AccountVideoRateModel,
446 include: [ AccountModel ]
454 return Bluebird.all([
455 // FIXME: typing issue
456 VideoModel.findAll(query as any),
457 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
458 ]).then(([ rows, totals ]) => {
459 // totals: totalVideos + totalVideoShares
461 let totalVideoShares = 0
462 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
463 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
465 const total = totalVideos + totalVideoShares
473 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
477 order: [ getSort(sort) ],
480 model: VideoChannelModel,
495 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
503 static listForApi (start: number, count: number, sort: string) {
507 order: [ getSort(sort) ]
510 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST, ScopeNames.WITH_ACCOUNT_API ])
511 .findAndCountAll(query)
512 .then(({ rows, count }) => {
520 static load (id: number) {
521 return VideoModel.findById(id)
524 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
525 const query: IFindOptions<VideoModel> = {
531 if (t !== undefined) query.transaction = t
533 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
536 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
537 const query: IFindOptions<VideoModel> = {
546 if (t !== undefined) query.transaction = t
548 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
551 static loadAndPopulateAccountAndServerAndTags (id: number) {
553 order: [ [ 'Tags', 'name', 'ASC' ] ]
557 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
558 .findById(id, options)
561 static loadByUUID (uuid: string) {
569 .scope([ ScopeNames.WITH_FILES ])
573 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
575 order: [ [ 'Tags', 'name', 'ASC' ] ],
582 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
586 static loadAndPopulateAll (id: number) {
588 order: [ [ 'Tags', 'name', 'ASC' ] ],
596 ScopeNames.WITH_RATES,
597 ScopeNames.WITH_SHARES,
598 ScopeNames.WITH_TAGS,
599 ScopeNames.WITH_FILES,
600 ScopeNames.WITH_ACCOUNT_DETAILS,
601 ScopeNames.WITH_COMMENTS
606 static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
607 const serverInclude: IIncludeOptions = {
612 const accountInclude: IIncludeOptions = {
618 include: [ serverInclude ]
623 const videoChannelInclude: IIncludeOptions = {
624 model: VideoChannelModel,
625 include: [ accountInclude ],
629 const tagInclude: IIncludeOptions = {
633 const query: IFindOptions<VideoModel> = {
634 distinct: true, // Because we have tags
637 order: [ getSort(sort) ],
641 // TODO: search on tags too
642 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
643 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
644 // `(SELECT "VideoTags"."videoId"
646 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
647 // WHERE name ILIKE ${escapedValue}
651 // TODO: search on account too
652 // accountInclude.where = {
654 // [Sequelize.Op.iLike]: '%' + value + '%'
657 query.where['name'] = {
658 [Sequelize.Op.iLike]: '%' + value + '%'
662 videoChannelInclude, tagInclude
665 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST ])
666 .findAndCountAll(query).then(({ rows, count }) => {
675 if (Array.isArray(this.VideoFiles) === false) return undefined
677 // The original file is the file that have the higher resolution
678 return maxBy(this.VideoFiles, file => file.resolution)
681 getVideoFilename (videoFile: VideoFileModel) {
682 return this.uuid + '-' + videoFile.resolution + videoFile.extname
685 getThumbnailName () {
686 // We always have a copy of the thumbnail
687 const extension = '.jpg'
688 return this.uuid + extension
692 const extension = '.jpg'
693 return this.uuid + extension
696 getTorrentFileName (videoFile: VideoFileModel) {
697 const extension = '.torrent'
698 return this.uuid + '-' + videoFile.resolution + extension
702 return this.remote === false
705 createPreview (videoFile: VideoFileModel) {
706 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
708 return generateImageFromVideoFile(
709 this.getVideoFilePath(videoFile),
710 CONFIG.STORAGE.PREVIEWS_DIR,
711 this.getPreviewName(),
716 createThumbnail (videoFile: VideoFileModel) {
717 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
719 return generateImageFromVideoFile(
720 this.getVideoFilePath(videoFile),
721 CONFIG.STORAGE.THUMBNAILS_DIR,
722 this.getThumbnailName(),
727 getVideoFilePath (videoFile: VideoFileModel) {
728 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
731 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
734 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
737 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
741 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
743 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
744 logger.info('Creating torrent %s.', filePath)
746 await writeFilePromise(filePath, torrent)
748 const parsedTorrent = parseTorrent(torrent)
749 videoFile.infoHash = parsedTorrent.infoHash
753 return '/videos/embed/' + this.uuid
756 getThumbnailPath () {
757 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
761 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
767 if (this.VideoChannel.Account.Actor.Server) {
768 serverHost = this.VideoChannel.Account.Actor.Server.host
770 // It means it's our video
771 serverHost = CONFIG.WEBSERVER.HOST
778 category: this.category,
779 categoryLabel: this.getCategoryLabel(),
780 licence: this.licence,
781 licenceLabel: this.getLicenceLabel(),
782 language: this.language,
783 languageLabel: this.getLanguageLabel(),
785 description: this.getTruncatedDescription(),
787 isLocal: this.isOwned(),
788 accountName: this.VideoChannel.Account.name,
789 duration: this.duration,
792 dislikes: this.dislikes,
793 thumbnailPath: this.getThumbnailPath(),
794 previewPath: this.getPreviewPath(),
795 embedPath: this.getEmbedPath(),
796 createdAt: this.createdAt,
797 updatedAt: this.updatedAt
801 toFormattedDetailsJSON () {
802 const formattedJson = this.toFormattedJSON()
804 // Maybe our server is not up to date and there are new privacy settings since our version
805 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
806 if (!privacyLabel) privacyLabel = 'Unknown'
808 const detailsJson = {
810 privacy: this.privacy,
811 descriptionPath: this.getDescriptionPath(),
812 channel: this.VideoChannel.toFormattedJSON(),
813 account: this.VideoChannel.Account.toFormattedJSON(),
814 tags: map<TagModel, string>(this.Tags, 'name'),
815 commentsEnabled: this.commentsEnabled,
819 // Format and sort video files
820 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
821 detailsJson.files = this.VideoFiles
823 let resolutionLabel = videoFile.resolution + 'p'
826 resolution: videoFile.resolution,
828 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
829 size: videoFile.size,
830 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
831 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
835 if (a.resolution < b.resolution) return 1
836 if (a.resolution === b.resolution) return 0
840 return Object.assign(formattedJson, detailsJson) as VideoDetails
843 toActivityPubObject (): VideoTorrentObject {
844 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
845 if (!this.Tags) this.Tags = []
847 const tag = this.Tags.map(t => ({
848 type: 'Hashtag' as 'Hashtag',
855 identifier: this.language + '',
856 name: this.getLanguageLabel()
863 identifier: this.category + '',
864 name: this.getCategoryLabel()
871 identifier: this.licence + '',
872 name: this.getLicenceLabel()
879 if (Array.isArray(this.AccountVideoRates)) {
880 const likes: string[] = []
881 const dislikes: string[] = []
883 for (const rate of this.AccountVideoRates) {
884 if (rate.type === 'like') {
885 likes.push(rate.Account.Actor.url)
886 } else if (rate.type === 'dislike') {
887 dislikes.push(rate.Account.Actor.url)
891 likesObject = activityPubCollection(likes)
892 dislikesObject = activityPubCollection(dislikes)
896 if (Array.isArray(this.VideoShares)) {
897 const shares: string[] = []
899 for (const videoShare of this.VideoShares) {
900 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
901 shares.push(shareUrl)
904 sharesObject = activityPubCollection(shares)
908 if (Array.isArray(this.VideoComments)) {
909 const comments: string[] = []
911 for (const videoComment of this.VideoComments) {
912 comments.push(videoComment.url)
915 commentsObject = activityPubCollection(comments)
919 for (const file of this.VideoFiles) {
922 mimeType: 'video/' + file.extname.replace('.', ''),
923 url: this.getVideoFileUrl(file, baseUrlHttp),
924 width: file.resolution,
930 mimeType: 'application/x-bittorrent',
931 url: this.getTorrentUrl(file, baseUrlHttp),
932 width: file.resolution
937 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
938 url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
939 width: file.resolution
946 mimeType: 'text/html',
947 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
951 type: 'Video' as 'Video',
954 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
955 duration: 'PT' + this.duration + 'S',
963 commentsEnabled: this.commentsEnabled,
964 published: this.createdAt.toISOString(),
965 updated: this.updatedAt.toISOString(),
966 mediaType: 'text/markdown',
967 content: this.getTruncatedDescription(),
970 url: this.getThumbnailUrl(baseUrlHttp),
971 mediaType: 'image/jpeg',
972 width: THUMBNAILS_SIZE.width,
973 height: THUMBNAILS_SIZE.height
977 dislikes: dislikesObject,
978 shares: sharesObject,
979 comments: commentsObject,
983 id: this.VideoChannel.Actor.url
987 id: this.VideoChannel.Account.Actor.url
993 getTruncatedDescription () {
994 if (!this.description) return null
997 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1000 return truncate(this.description, options)
1003 optimizeOriginalVideofile = async function () {
1004 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1005 const newExtname = '.mp4'
1006 const inputVideoFile = this.getOriginalFile()
1007 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1008 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1010 const transcodeOptions = {
1011 inputPath: videoInputPath,
1012 outputPath: videoOutputPath
1016 // Could be very long!
1017 await transcode(transcodeOptions)
1019 await unlinkPromise(videoInputPath)
1021 // Important to do this before getVideoFilename() to take in account the new file extension
1022 inputVideoFile.set('extname', newExtname)
1024 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1025 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1027 inputVideoFile.set('size', stats.size)
1029 await this.createTorrentAndSetInfoHash(inputVideoFile)
1030 await inputVideoFile.save()
1033 // Auto destruction...
1034 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1040 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1041 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1042 const extname = '.mp4'
1044 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1045 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1047 const newVideoFile = new VideoFileModel({
1053 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1055 const transcodeOptions = {
1056 inputPath: videoInputPath,
1057 outputPath: videoOutputPath,
1061 await transcode(transcodeOptions)
1063 const stats = await statPromise(videoOutputPath)
1065 newVideoFile.set('size', stats.size)
1067 await this.createTorrentAndSetInfoHash(newVideoFile)
1069 await newVideoFile.save()
1071 this.VideoFiles.push(newVideoFile)
1074 getOriginalFileHeight () {
1075 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1077 return getVideoFileHeight(originalFilePath)
1080 getDescriptionPath () {
1081 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1084 getCategoryLabel () {
1085 let categoryLabel = VIDEO_CATEGORIES[this.category]
1086 if (!categoryLabel) categoryLabel = 'Misc'
1088 return categoryLabel
1091 getLicenceLabel () {
1092 let licenceLabel = VIDEO_LICENCES[this.licence]
1093 if (!licenceLabel) licenceLabel = 'Unknown'
1098 getLanguageLabel () {
1099 let languageLabel = VIDEO_LANGUAGES[this.language]
1100 if (!languageLabel) languageLabel = 'Unknown'
1102 return languageLabel
1105 removeThumbnail () {
1106 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1107 return unlinkPromise(thumbnailPath)
1111 // Same name than video thumbnail
1112 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1115 removeFile (videoFile: VideoFileModel) {
1116 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1117 return unlinkPromise(filePath)
1120 removeTorrent (videoFile: VideoFileModel) {
1121 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1122 return unlinkPromise(torrentPath)
1125 private getBaseUrls () {
1129 if (this.isOwned()) {
1130 baseUrlHttp = CONFIG.WEBSERVER.URL
1131 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1133 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1134 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1137 return { baseUrlHttp, baseUrlWs }
1140 private getThumbnailUrl (baseUrlHttp: string) {
1141 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1144 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1145 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1148 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1149 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1152 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1153 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1154 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1155 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1157 const magnetHash = {
1161 infoHash: videoFile.infoHash,
1165 return magnetUtil.encode(magnetHash)