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 loadAndPopulateAccount (id: number) {
511 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS ]).findById(id)
514 static loadByUrl (url: string, t?: Sequelize.Transaction) {
515 const query: IFindOptions<VideoModel> = {
521 if (t !== undefined) query.transaction = t
523 return VideoModel.findOne(query)
526 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
527 const query: IFindOptions<VideoModel> = {
533 if (t !== undefined) query.transaction = t
535 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
538 static loadByUUIDOrURL (uuid: string, url: string, t?: Sequelize.Transaction) {
539 const query: IFindOptions<VideoModel> = {
548 if (t !== undefined) query.transaction = t
550 return VideoModel.scope(ScopeNames.WITH_FILES).findOne(query)
553 static loadAndPopulateAccountAndServerAndTags (id: number) {
555 order: [ [ 'Tags', 'name', 'ASC' ] ]
559 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
560 .findById(id, options)
563 static loadByUUID (uuid: string) {
571 .scope([ ScopeNames.WITH_FILES ])
575 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
577 order: [ [ 'Tags', 'name', 'ASC' ] ],
584 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
588 static loadAndPopulateAll (id: number) {
590 order: [ [ 'Tags', 'name', 'ASC' ] ],
598 ScopeNames.WITH_RATES,
599 ScopeNames.WITH_SHARES,
600 ScopeNames.WITH_TAGS,
601 ScopeNames.WITH_FILES,
602 ScopeNames.WITH_ACCOUNT_DETAILS,
603 ScopeNames.WITH_COMMENTS
608 static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
609 const serverInclude: IIncludeOptions = {
614 const accountInclude: IIncludeOptions = {
620 include: [ serverInclude ]
625 const videoChannelInclude: IIncludeOptions = {
626 model: VideoChannelModel,
627 include: [ accountInclude ],
631 const tagInclude: IIncludeOptions = {
635 const query: IFindOptions<VideoModel> = {
636 distinct: true, // Because we have tags
639 order: [ getSort(sort) ],
643 // TODO: search on tags too
644 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
645 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
646 // `(SELECT "VideoTags"."videoId"
648 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
649 // WHERE name ILIKE ${escapedValue}
653 // TODO: search on account too
654 // accountInclude.where = {
656 // [Sequelize.Op.iLike]: '%' + value + '%'
659 query.where['name'] = {
660 [Sequelize.Op.iLike]: '%' + value + '%'
664 videoChannelInclude, tagInclude
667 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST ])
668 .findAndCountAll(query).then(({ rows, count }) => {
677 if (Array.isArray(this.VideoFiles) === false) return undefined
679 // The original file is the file that have the higher resolution
680 return maxBy(this.VideoFiles, file => file.resolution)
683 getVideoFilename (videoFile: VideoFileModel) {
684 return this.uuid + '-' + videoFile.resolution + videoFile.extname
687 getThumbnailName () {
688 // We always have a copy of the thumbnail
689 const extension = '.jpg'
690 return this.uuid + extension
694 const extension = '.jpg'
695 return this.uuid + extension
698 getTorrentFileName (videoFile: VideoFileModel) {
699 const extension = '.torrent'
700 return this.uuid + '-' + videoFile.resolution + extension
704 return this.remote === false
707 createPreview (videoFile: VideoFileModel) {
708 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
710 return generateImageFromVideoFile(
711 this.getVideoFilePath(videoFile),
712 CONFIG.STORAGE.PREVIEWS_DIR,
713 this.getPreviewName(),
718 createThumbnail (videoFile: VideoFileModel) {
719 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
721 return generateImageFromVideoFile(
722 this.getVideoFilePath(videoFile),
723 CONFIG.STORAGE.THUMBNAILS_DIR,
724 this.getThumbnailName(),
729 getVideoFilePath (videoFile: VideoFileModel) {
730 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
733 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
736 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
739 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
743 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
745 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
746 logger.info('Creating torrent %s.', filePath)
748 await writeFilePromise(filePath, torrent)
750 const parsedTorrent = parseTorrent(torrent)
751 videoFile.infoHash = parsedTorrent.infoHash
755 return '/videos/embed/' + this.uuid
758 getThumbnailPath () {
759 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
763 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
769 if (this.VideoChannel.Account.Actor.Server) {
770 serverHost = this.VideoChannel.Account.Actor.Server.host
772 // It means it's our video
773 serverHost = CONFIG.WEBSERVER.HOST
780 category: this.category,
781 categoryLabel: this.getCategoryLabel(),
782 licence: this.licence,
783 licenceLabel: this.getLicenceLabel(),
784 language: this.language,
785 languageLabel: this.getLanguageLabel(),
787 description: this.getTruncatedDescription(),
789 isLocal: this.isOwned(),
790 accountName: this.VideoChannel.Account.name,
791 duration: this.duration,
794 dislikes: this.dislikes,
795 thumbnailPath: this.getThumbnailPath(),
796 previewPath: this.getPreviewPath(),
797 embedPath: this.getEmbedPath(),
798 createdAt: this.createdAt,
799 updatedAt: this.updatedAt
803 toFormattedDetailsJSON () {
804 const formattedJson = this.toFormattedJSON()
806 // Maybe our server is not up to date and there are new privacy settings since our version
807 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
808 if (!privacyLabel) privacyLabel = 'Unknown'
810 const detailsJson = {
812 privacy: this.privacy,
813 descriptionPath: this.getDescriptionPath(),
814 channel: this.VideoChannel.toFormattedJSON(),
815 account: this.VideoChannel.Account.toFormattedJSON(),
816 tags: map<TagModel, string>(this.Tags, 'name'),
817 commentsEnabled: this.commentsEnabled,
821 // Format and sort video files
822 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
823 detailsJson.files = this.VideoFiles
825 let resolutionLabel = videoFile.resolution + 'p'
828 resolution: videoFile.resolution,
830 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
831 size: videoFile.size,
832 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
833 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
837 if (a.resolution < b.resolution) return 1
838 if (a.resolution === b.resolution) return 0
842 return Object.assign(formattedJson, detailsJson) as VideoDetails
845 toActivityPubObject (): VideoTorrentObject {
846 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
847 if (!this.Tags) this.Tags = []
849 const tag = this.Tags.map(t => ({
850 type: 'Hashtag' as 'Hashtag',
857 identifier: this.language + '',
858 name: this.getLanguageLabel()
865 identifier: this.category + '',
866 name: this.getCategoryLabel()
873 identifier: this.licence + '',
874 name: this.getLicenceLabel()
881 if (Array.isArray(this.AccountVideoRates)) {
882 const likes: string[] = []
883 const dislikes: string[] = []
885 for (const rate of this.AccountVideoRates) {
886 if (rate.type === 'like') {
887 likes.push(rate.Account.Actor.url)
888 } else if (rate.type === 'dislike') {
889 dislikes.push(rate.Account.Actor.url)
893 likesObject = activityPubCollection(likes)
894 dislikesObject = activityPubCollection(dislikes)
898 if (Array.isArray(this.VideoShares)) {
899 const shares: string[] = []
901 for (const videoShare of this.VideoShares) {
902 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
903 shares.push(shareUrl)
906 sharesObject = activityPubCollection(shares)
910 if (Array.isArray(this.VideoComments)) {
911 const comments: string[] = []
913 for (const videoComment of this.VideoComments) {
914 comments.push(videoComment.url)
917 commentsObject = activityPubCollection(comments)
921 for (const file of this.VideoFiles) {
924 mimeType: 'video/' + file.extname.replace('.', ''),
925 url: this.getVideoFileUrl(file, baseUrlHttp),
926 width: file.resolution,
932 mimeType: 'application/x-bittorrent',
933 url: this.getTorrentUrl(file, baseUrlHttp),
934 width: file.resolution
939 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
940 url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
941 width: file.resolution
948 mimeType: 'text/html',
949 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
953 type: 'Video' as 'Video',
956 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
957 duration: 'PT' + this.duration + 'S',
965 commentsEnabled: this.commentsEnabled,
966 published: this.createdAt.toISOString(),
967 updated: this.updatedAt.toISOString(),
968 mediaType: 'text/markdown',
969 content: this.getTruncatedDescription(),
972 url: this.getThumbnailUrl(baseUrlHttp),
973 mediaType: 'image/jpeg',
974 width: THUMBNAILS_SIZE.width,
975 height: THUMBNAILS_SIZE.height
979 dislikes: dislikesObject,
980 shares: sharesObject,
981 comments: commentsObject,
985 id: this.VideoChannel.Actor.url
991 getTruncatedDescription () {
992 if (!this.description) return null
995 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
998 return truncate(this.description, options)
1001 optimizeOriginalVideofile = async function () {
1002 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1003 const newExtname = '.mp4'
1004 const inputVideoFile = this.getOriginalFile()
1005 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1006 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1008 const transcodeOptions = {
1009 inputPath: videoInputPath,
1010 outputPath: videoOutputPath
1014 // Could be very long!
1015 await transcode(transcodeOptions)
1017 await unlinkPromise(videoInputPath)
1019 // Important to do this before getVideoFilename() to take in account the new file extension
1020 inputVideoFile.set('extname', newExtname)
1022 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1023 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1025 inputVideoFile.set('size', stats.size)
1027 await this.createTorrentAndSetInfoHash(inputVideoFile)
1028 await inputVideoFile.save()
1031 // Auto destruction...
1032 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1038 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1039 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1040 const extname = '.mp4'
1042 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1043 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1045 const newVideoFile = new VideoFileModel({
1051 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1053 const transcodeOptions = {
1054 inputPath: videoInputPath,
1055 outputPath: videoOutputPath,
1059 await transcode(transcodeOptions)
1061 const stats = await statPromise(videoOutputPath)
1063 newVideoFile.set('size', stats.size)
1065 await this.createTorrentAndSetInfoHash(newVideoFile)
1067 await newVideoFile.save()
1069 this.VideoFiles.push(newVideoFile)
1072 getOriginalFileHeight () {
1073 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1075 return getVideoFileHeight(originalFilePath)
1078 getDescriptionPath () {
1079 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1082 getCategoryLabel () {
1083 let categoryLabel = VIDEO_CATEGORIES[this.category]
1084 if (!categoryLabel) categoryLabel = 'Misc'
1086 return categoryLabel
1089 getLicenceLabel () {
1090 let licenceLabel = VIDEO_LICENCES[this.licence]
1091 if (!licenceLabel) licenceLabel = 'Unknown'
1096 getLanguageLabel () {
1097 let languageLabel = VIDEO_LANGUAGES[this.language]
1098 if (!languageLabel) languageLabel = 'Unknown'
1100 return languageLabel
1103 removeThumbnail () {
1104 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1105 return unlinkPromise(thumbnailPath)
1109 // Same name than video thumbnail
1110 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1113 removeFile (videoFile: VideoFileModel) {
1114 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1115 return unlinkPromise(filePath)
1118 removeTorrent (videoFile: VideoFileModel) {
1119 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1120 return unlinkPromise(torrentPath)
1123 private getBaseUrls () {
1127 if (this.isOwned()) {
1128 baseUrlHttp = CONFIG.WEBSERVER.URL
1129 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1131 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1132 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1135 return { baseUrlHttp, baseUrlWs }
1138 private getThumbnailUrl (baseUrlHttp: string) {
1139 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1142 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1143 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1146 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1147 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1150 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1151 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1152 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1153 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1155 const magnetHash = {
1159 infoHash: videoFile.infoHash,
1163 return magnetUtil.encode(magnetHash)