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,
101 model: () => AccountModel,
105 model: () => ActorModel,
109 model: () => ServerModel,
120 [ScopeNames.WITH_TAGS]: {
121 include: [ () => TagModel ]
123 [ScopeNames.WITH_FILES]: {
126 model: () => VideoFileModel,
131 [ScopeNames.WITH_SHARES]: {
134 model: () => VideoShareModel,
135 include: [ () => ActorModel ]
139 [ScopeNames.WITH_RATES]: {
142 model: () => AccountVideoRateModel,
143 include: [ () => AccountModel ]
147 [ScopeNames.WITH_COMMENTS]: {
150 model: () => VideoCommentModel
162 fields: [ 'createdAt' ]
165 fields: [ 'duration' ]
177 fields: [ 'channelId' ]
180 fields: [ 'id', 'privacy' ]
184 export class VideoModel extends Model<VideoModel> {
187 @Default(DataType.UUIDV4)
189 @Column(DataType.UUID)
193 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
199 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
205 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
211 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
216 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
221 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
227 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
228 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
232 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
262 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
263 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
268 commentsEnabled: boolean
276 @ForeignKey(() => VideoChannelModel)
280 @BelongsTo(() => VideoChannelModel, {
286 VideoChannel: VideoChannelModel
288 @BelongsToMany(() => TagModel, {
289 foreignKey: 'videoId',
290 through: () => VideoTagModel,
295 @HasMany(() => VideoAbuseModel, {
302 VideoAbuses: VideoAbuseModel[]
304 @HasMany(() => VideoFileModel, {
311 VideoFiles: VideoFileModel[]
313 @HasMany(() => VideoShareModel, {
320 VideoShares: VideoShareModel[]
322 @HasMany(() => AccountVideoRateModel, {
329 AccountVideoRates: AccountVideoRateModel[]
331 @HasMany(() => VideoCommentModel, {
338 VideoComments: VideoCommentModel[]
341 static removeFilesAndSendDelete (instance: VideoModel) {
345 instance.removeThumbnail()
348 if (instance.isOwned()) {
350 instance.removePreview(),
351 sendDeleteVideo(instance, undefined)
354 // Remove physical files and torrents
355 instance.VideoFiles.forEach(file => {
356 tasks.push(instance.removeFile(file))
357 tasks.push(instance.removeTorrent(file))
361 return Promise.all(tasks)
363 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
368 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
371 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
372 function getRawQuery (select: string) {
373 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
374 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
375 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
376 'WHERE "Account"."actorId" = ' + actorId
377 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
378 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
379 'WHERE "VideoShare"."actorId" = ' + actorId
381 return `(${queryVideo}) UNION (${queryVideoShare})`
384 const rawQuery = getRawQuery('"Video"."id"')
385 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
391 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
394 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
399 model: VideoShareModel,
402 [Sequelize.Op.and]: [
405 [Sequelize.Op.not]: null
421 model: VideoChannelModel,
431 model: AccountVideoRateModel,
432 include: [ AccountModel ]
440 return Bluebird.all([
441 // FIXME: typing issue
442 VideoModel.findAll(query as any),
443 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
444 ]).then(([ rows, totals ]) => {
445 // totals: totalVideos + totalVideoShares
447 let totalVideoShares = 0
448 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
449 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
451 const total = totalVideos + totalVideoShares
459 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
463 order: [ getSort(sort) ],
466 model: VideoChannelModel,
481 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
489 static listForApi (start: number, count: number, sort: string) {
493 order: [ getSort(sort) ]
496 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST, ScopeNames.WITH_ACCOUNT_API ])
497 .findAndCountAll(query)
498 .then(({ rows, count }) => {
506 static load (id: number) {
507 return VideoModel.findById(id)
510 static loadByUrl (url: string, t?: Sequelize.Transaction) {
511 const query: IFindOptions<VideoModel> = {
517 if (t !== undefined) query.transaction = t
519 return VideoModel.findOne(query)
522 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
523 const query: IFindOptions<VideoModel> = {
529 if (t !== undefined) query.transaction = t
531 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
534 static loadByUUIDOrURL (uuid: string, url: string, t?: Sequelize.Transaction) {
535 const query: IFindOptions<VideoModel> = {
544 if (t !== undefined) query.transaction = t
546 return VideoModel.scope(ScopeNames.WITH_FILES).findOne(query)
549 static loadAndPopulateAccountAndServerAndTags (id: number) {
551 order: [ [ 'Tags', 'name', 'ASC' ] ]
555 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
556 .findById(id, options)
559 static loadByUUID (uuid: string) {
567 .scope([ ScopeNames.WITH_FILES ])
571 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
573 order: [ [ 'Tags', 'name', 'ASC' ] ],
580 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
584 static loadAndPopulateAll (id: number) {
586 order: [ [ 'Tags', 'name', 'ASC' ] ],
594 ScopeNames.WITH_RATES,
595 ScopeNames.WITH_SHARES,
596 ScopeNames.WITH_TAGS,
597 ScopeNames.WITH_FILES,
598 ScopeNames.WITH_ACCOUNT_DETAILS,
599 ScopeNames.WITH_COMMENTS
604 static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
605 const serverInclude: IIncludeOptions = {
610 const accountInclude: IIncludeOptions = {
616 include: [ serverInclude ]
621 const videoChannelInclude: IIncludeOptions = {
622 model: VideoChannelModel,
623 include: [ accountInclude ],
627 const tagInclude: IIncludeOptions = {
631 const query: IFindOptions<VideoModel> = {
632 distinct: true, // Because we have tags
635 order: [ getSort(sort) ],
639 // TODO: search on tags too
640 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
641 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
642 // `(SELECT "VideoTags"."videoId"
644 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
645 // WHERE name ILIKE ${escapedValue}
649 // TODO: search on account too
650 // accountInclude.where = {
652 // [Sequelize.Op.iLike]: '%' + value + '%'
655 query.where['name'] = {
656 [Sequelize.Op.iLike]: '%' + value + '%'
660 videoChannelInclude, tagInclude
663 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST ])
664 .findAndCountAll(query).then(({ rows, count }) => {
673 if (Array.isArray(this.VideoFiles) === false) return undefined
675 // The original file is the file that have the higher resolution
676 return maxBy(this.VideoFiles, file => file.resolution)
679 getVideoFilename (videoFile: VideoFileModel) {
680 return this.uuid + '-' + videoFile.resolution + videoFile.extname
683 getThumbnailName () {
684 // We always have a copy of the thumbnail
685 const extension = '.jpg'
686 return this.uuid + extension
690 const extension = '.jpg'
691 return this.uuid + extension
694 getTorrentFileName (videoFile: VideoFileModel) {
695 const extension = '.torrent'
696 return this.uuid + '-' + videoFile.resolution + extension
700 return this.remote === false
703 createPreview (videoFile: VideoFileModel) {
704 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
706 return generateImageFromVideoFile(
707 this.getVideoFilePath(videoFile),
708 CONFIG.STORAGE.PREVIEWS_DIR,
709 this.getPreviewName(),
714 createThumbnail (videoFile: VideoFileModel) {
715 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
717 return generateImageFromVideoFile(
718 this.getVideoFilePath(videoFile),
719 CONFIG.STORAGE.THUMBNAILS_DIR,
720 this.getThumbnailName(),
725 getVideoFilePath (videoFile: VideoFileModel) {
726 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
729 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
732 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
735 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
739 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
741 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
742 logger.info('Creating torrent %s.', filePath)
744 await writeFilePromise(filePath, torrent)
746 const parsedTorrent = parseTorrent(torrent)
747 videoFile.infoHash = parsedTorrent.infoHash
751 return '/videos/embed/' + this.uuid
754 getThumbnailPath () {
755 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
759 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
765 if (this.VideoChannel.Account.Actor.Server) {
766 serverHost = this.VideoChannel.Account.Actor.Server.host
768 // It means it's our video
769 serverHost = CONFIG.WEBSERVER.HOST
776 category: this.category,
777 categoryLabel: this.getCategoryLabel(),
778 licence: this.licence,
779 licenceLabel: this.getLicenceLabel(),
780 language: this.language,
781 languageLabel: this.getLanguageLabel(),
783 description: this.getTruncatedDescription(),
785 isLocal: this.isOwned(),
786 accountName: this.VideoChannel.Account.name,
787 duration: this.duration,
790 dislikes: this.dislikes,
791 thumbnailPath: this.getThumbnailPath(),
792 previewPath: this.getPreviewPath(),
793 embedPath: this.getEmbedPath(),
794 createdAt: this.createdAt,
795 updatedAt: this.updatedAt
799 toFormattedDetailsJSON () {
800 const formattedJson = this.toFormattedJSON()
802 // Maybe our server is not up to date and there are new privacy settings since our version
803 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
804 if (!privacyLabel) privacyLabel = 'Unknown'
806 const detailsJson = {
808 privacy: this.privacy,
809 descriptionPath: this.getDescriptionPath(),
810 channel: this.VideoChannel.toFormattedJSON(),
811 account: this.VideoChannel.Account.toFormattedJSON(),
812 tags: map<TagModel, string>(this.Tags, 'name'),
813 commentsEnabled: this.commentsEnabled,
817 // Format and sort video files
818 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
819 detailsJson.files = this.VideoFiles
821 let resolutionLabel = videoFile.resolution + 'p'
824 resolution: videoFile.resolution,
826 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
827 size: videoFile.size,
828 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
829 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
833 if (a.resolution < b.resolution) return 1
834 if (a.resolution === b.resolution) return 0
838 return Object.assign(formattedJson, detailsJson) as VideoDetails
841 toActivityPubObject (): VideoTorrentObject {
842 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
843 if (!this.Tags) this.Tags = []
845 const tag = this.Tags.map(t => ({
846 type: 'Hashtag' as 'Hashtag',
853 identifier: this.language + '',
854 name: this.getLanguageLabel()
861 identifier: this.category + '',
862 name: this.getCategoryLabel()
869 identifier: this.licence + '',
870 name: this.getLicenceLabel()
877 if (Array.isArray(this.AccountVideoRates)) {
878 const likes: string[] = []
879 const dislikes: string[] = []
881 for (const rate of this.AccountVideoRates) {
882 if (rate.type === 'like') {
883 likes.push(rate.Account.Actor.url)
884 } else if (rate.type === 'dislike') {
885 dislikes.push(rate.Account.Actor.url)
889 likesObject = activityPubCollection(likes)
890 dislikesObject = activityPubCollection(dislikes)
894 if (Array.isArray(this.VideoShares)) {
895 const shares: string[] = []
897 for (const videoShare of this.VideoShares) {
898 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
899 shares.push(shareUrl)
902 sharesObject = activityPubCollection(shares)
906 if (Array.isArray(this.VideoComments)) {
907 const comments: string[] = []
909 for (const videoComment of this.VideoComments) {
910 comments.push(videoComment.url)
913 commentsObject = activityPubCollection(comments)
917 for (const file of this.VideoFiles) {
920 mimeType: 'video/' + file.extname.replace('.', ''),
921 url: this.getVideoFileUrl(file, baseUrlHttp),
922 width: file.resolution,
928 mimeType: 'application/x-bittorrent',
929 url: this.getTorrentUrl(file, baseUrlHttp),
930 width: file.resolution
935 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
936 url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
937 width: file.resolution
944 mimeType: 'text/html',
945 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
949 type: 'Video' as 'Video',
952 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
953 duration: 'PT' + this.duration + 'S',
961 commentsEnabled: this.commentsEnabled,
962 published: this.createdAt.toISOString(),
963 updated: this.updatedAt.toISOString(),
964 mediaType: 'text/markdown',
965 content: this.getTruncatedDescription(),
968 url: this.getThumbnailUrl(baseUrlHttp),
969 mediaType: 'image/jpeg',
970 width: THUMBNAILS_SIZE.width,
971 height: THUMBNAILS_SIZE.height
975 dislikes: dislikesObject,
976 shares: sharesObject,
977 comments: commentsObject,
981 id: this.VideoChannel.Actor.url
987 getTruncatedDescription () {
988 if (!this.description) return null
991 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
994 return truncate(this.description, options)
997 optimizeOriginalVideofile = async function () {
998 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
999 const newExtname = '.mp4'
1000 const inputVideoFile = this.getOriginalFile()
1001 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1002 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1004 const transcodeOptions = {
1005 inputPath: videoInputPath,
1006 outputPath: videoOutputPath
1010 // Could be very long!
1011 await transcode(transcodeOptions)
1013 await unlinkPromise(videoInputPath)
1015 // Important to do this before getVideoFilename() to take in account the new file extension
1016 inputVideoFile.set('extname', newExtname)
1018 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1019 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1021 inputVideoFile.set('size', stats.size)
1023 await this.createTorrentAndSetInfoHash(inputVideoFile)
1024 await inputVideoFile.save()
1027 // Auto destruction...
1028 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1034 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1035 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1036 const extname = '.mp4'
1038 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1039 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1041 const newVideoFile = new VideoFileModel({
1047 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1049 const transcodeOptions = {
1050 inputPath: videoInputPath,
1051 outputPath: videoOutputPath,
1055 await transcode(transcodeOptions)
1057 const stats = await statPromise(videoOutputPath)
1059 newVideoFile.set('size', stats.size)
1061 await this.createTorrentAndSetInfoHash(newVideoFile)
1063 await newVideoFile.save()
1065 this.VideoFiles.push(newVideoFile)
1068 getOriginalFileHeight () {
1069 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1071 return getVideoFileHeight(originalFilePath)
1074 getDescriptionPath () {
1075 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1078 getCategoryLabel () {
1079 let categoryLabel = VIDEO_CATEGORIES[this.category]
1080 if (!categoryLabel) categoryLabel = 'Misc'
1082 return categoryLabel
1085 getLicenceLabel () {
1086 let licenceLabel = VIDEO_LICENCES[this.licence]
1087 if (!licenceLabel) licenceLabel = 'Unknown'
1092 getLanguageLabel () {
1093 let languageLabel = VIDEO_LANGUAGES[this.language]
1094 if (!languageLabel) languageLabel = 'Unknown'
1096 return languageLabel
1099 removeThumbnail () {
1100 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1101 return unlinkPromise(thumbnailPath)
1105 // Same name than video thumbnail
1106 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1109 removeFile (videoFile: VideoFileModel) {
1110 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1111 return unlinkPromise(filePath)
1114 removeTorrent (videoFile: VideoFileModel) {
1115 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1116 return unlinkPromise(torrentPath)
1119 private getBaseUrls () {
1123 if (this.isOwned()) {
1124 baseUrlHttp = CONFIG.WEBSERVER.URL
1125 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1127 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1128 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1131 return { baseUrlHttp, baseUrlWs }
1134 private getThumbnailUrl (baseUrlHttp: string) {
1135 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1138 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1139 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1142 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1143 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1146 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1147 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1148 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1149 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1151 const magnetHash = {
1155 infoHash: videoFile.infoHash,
1159 return magnetUtil.encode(magnetHash)