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' ]
188 export class VideoModel extends Model<VideoModel> {
191 @Default(DataType.UUIDV4)
193 @Column(DataType.UUID)
197 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
203 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
209 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
215 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
220 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
225 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
231 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
232 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
236 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
266 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
267 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
272 commentsEnabled: boolean
280 @ForeignKey(() => VideoChannelModel)
284 @BelongsTo(() => VideoChannelModel, {
290 VideoChannel: VideoChannelModel
292 @BelongsToMany(() => TagModel, {
293 foreignKey: 'videoId',
294 through: () => VideoTagModel,
299 @HasMany(() => VideoAbuseModel, {
306 VideoAbuses: VideoAbuseModel[]
308 @HasMany(() => VideoFileModel, {
315 VideoFiles: VideoFileModel[]
317 @HasMany(() => VideoShareModel, {
324 VideoShares: VideoShareModel[]
326 @HasMany(() => AccountVideoRateModel, {
333 AccountVideoRates: AccountVideoRateModel[]
335 @HasMany(() => VideoCommentModel, {
342 VideoComments: VideoCommentModel[]
345 static removeFilesAndSendDelete (instance: VideoModel) {
349 instance.removeThumbnail()
352 if (instance.isOwned()) {
354 instance.removePreview(),
355 sendDeleteVideo(instance, undefined)
358 // Remove physical files and torrents
359 instance.VideoFiles.forEach(file => {
360 tasks.push(instance.removeFile(file))
361 tasks.push(instance.removeTorrent(file))
365 return Promise.all(tasks)
367 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
372 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
375 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
376 function getRawQuery (select: string) {
377 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
378 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
379 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
380 'WHERE "Account"."actorId" = ' + actorId
381 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
382 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
383 'WHERE "VideoShare"."actorId" = ' + actorId
385 return `(${queryVideo}) UNION (${queryVideoShare})`
388 const rawQuery = getRawQuery('"Video"."id"')
389 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
395 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
398 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
403 model: VideoShareModel,
406 [Sequelize.Op.and]: [
409 [Sequelize.Op.not]: null
425 model: VideoChannelModel,
435 model: AccountVideoRateModel,
436 include: [ AccountModel ]
444 return Bluebird.all([
445 // FIXME: typing issue
446 VideoModel.findAll(query as any),
447 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
448 ]).then(([ rows, totals ]) => {
449 // totals: totalVideos + totalVideoShares
451 let totalVideoShares = 0
452 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
453 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
455 const total = totalVideos + totalVideoShares
463 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
467 order: [ getSort(sort) ],
470 model: VideoChannelModel,
485 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
493 static listForApi (start: number, count: number, sort: string) {
497 order: [ getSort(sort) ]
500 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST, ScopeNames.WITH_ACCOUNT_API ])
501 .findAndCountAll(query)
502 .then(({ rows, count }) => {
510 static load (id: number) {
511 return VideoModel.findById(id)
514 static loadAndPopulateAccount (id: number) {
515 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS ]).findById(id)
518 static loadByUrl (url: string, t?: Sequelize.Transaction) {
519 const query: IFindOptions<VideoModel> = {
525 if (t !== undefined) query.transaction = t
527 return VideoModel.findOne(query)
530 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
531 const query: IFindOptions<VideoModel> = {
537 if (t !== undefined) query.transaction = t
539 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
542 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
543 const query: IFindOptions<VideoModel> = {
552 if (t !== undefined) query.transaction = t
554 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
557 static loadAndPopulateAccountAndServerAndTags (id: number) {
559 order: [ [ 'Tags', 'name', 'ASC' ] ]
563 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
564 .findById(id, options)
567 static loadByUUID (uuid: string) {
575 .scope([ ScopeNames.WITH_FILES ])
579 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
581 order: [ [ 'Tags', 'name', 'ASC' ] ],
588 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
592 static loadAndPopulateAll (id: number) {
594 order: [ [ 'Tags', 'name', 'ASC' ] ],
602 ScopeNames.WITH_RATES,
603 ScopeNames.WITH_SHARES,
604 ScopeNames.WITH_TAGS,
605 ScopeNames.WITH_FILES,
606 ScopeNames.WITH_ACCOUNT_DETAILS,
607 ScopeNames.WITH_COMMENTS
612 static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
613 const serverInclude: IIncludeOptions = {
618 const accountInclude: IIncludeOptions = {
624 include: [ serverInclude ]
629 const videoChannelInclude: IIncludeOptions = {
630 model: VideoChannelModel,
631 include: [ accountInclude ],
635 const tagInclude: IIncludeOptions = {
639 const query: IFindOptions<VideoModel> = {
640 distinct: true, // Because we have tags
643 order: [ getSort(sort) ],
647 // TODO: search on tags too
648 // const escapedValue = Video['sequelize'].escape('%' + value + '%')
649 // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
650 // `(SELECT "VideoTags"."videoId"
652 // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
653 // WHERE name ILIKE ${escapedValue}
657 // TODO: search on account too
658 // accountInclude.where = {
660 // [Sequelize.Op.iLike]: '%' + value + '%'
663 query.where['name'] = {
664 [Sequelize.Op.iLike]: '%' + value + '%'
668 videoChannelInclude, tagInclude
671 return VideoModel.scope([ ScopeNames.AVAILABLE_FOR_LIST ])
672 .findAndCountAll(query).then(({ rows, count }) => {
681 if (Array.isArray(this.VideoFiles) === false) return undefined
683 // The original file is the file that have the higher resolution
684 return maxBy(this.VideoFiles, file => file.resolution)
687 getVideoFilename (videoFile: VideoFileModel) {
688 return this.uuid + '-' + videoFile.resolution + videoFile.extname
691 getThumbnailName () {
692 // We always have a copy of the thumbnail
693 const extension = '.jpg'
694 return this.uuid + extension
698 const extension = '.jpg'
699 return this.uuid + extension
702 getTorrentFileName (videoFile: VideoFileModel) {
703 const extension = '.torrent'
704 return this.uuid + '-' + videoFile.resolution + extension
708 return this.remote === false
711 createPreview (videoFile: VideoFileModel) {
712 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
714 return generateImageFromVideoFile(
715 this.getVideoFilePath(videoFile),
716 CONFIG.STORAGE.PREVIEWS_DIR,
717 this.getPreviewName(),
722 createThumbnail (videoFile: VideoFileModel) {
723 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
725 return generateImageFromVideoFile(
726 this.getVideoFilePath(videoFile),
727 CONFIG.STORAGE.THUMBNAILS_DIR,
728 this.getThumbnailName(),
733 getVideoFilePath (videoFile: VideoFileModel) {
734 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
737 createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) {
740 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
743 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
747 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
749 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
750 logger.info('Creating torrent %s.', filePath)
752 await writeFilePromise(filePath, torrent)
754 const parsedTorrent = parseTorrent(torrent)
755 videoFile.infoHash = parsedTorrent.infoHash
759 return '/videos/embed/' + this.uuid
762 getThumbnailPath () {
763 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
767 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
773 if (this.VideoChannel.Account.Actor.Server) {
774 serverHost = this.VideoChannel.Account.Actor.Server.host
776 // It means it's our video
777 serverHost = CONFIG.WEBSERVER.HOST
784 category: this.category,
785 categoryLabel: this.getCategoryLabel(),
786 licence: this.licence,
787 licenceLabel: this.getLicenceLabel(),
788 language: this.language,
789 languageLabel: this.getLanguageLabel(),
791 description: this.getTruncatedDescription(),
793 isLocal: this.isOwned(),
794 accountName: this.VideoChannel.Account.name,
795 duration: this.duration,
798 dislikes: this.dislikes,
799 thumbnailPath: this.getThumbnailPath(),
800 previewPath: this.getPreviewPath(),
801 embedPath: this.getEmbedPath(),
802 createdAt: this.createdAt,
803 updatedAt: this.updatedAt
807 toFormattedDetailsJSON () {
808 const formattedJson = this.toFormattedJSON()
810 // Maybe our server is not up to date and there are new privacy settings since our version
811 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
812 if (!privacyLabel) privacyLabel = 'Unknown'
814 const detailsJson = {
816 privacy: this.privacy,
817 descriptionPath: this.getDescriptionPath(),
818 channel: this.VideoChannel.toFormattedJSON(),
819 account: this.VideoChannel.Account.toFormattedJSON(),
820 tags: map<TagModel, string>(this.Tags, 'name'),
821 commentsEnabled: this.commentsEnabled,
825 // Format and sort video files
826 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
827 detailsJson.files = this.VideoFiles
829 let resolutionLabel = videoFile.resolution + 'p'
832 resolution: videoFile.resolution,
834 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
835 size: videoFile.size,
836 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
837 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp)
841 if (a.resolution < b.resolution) return 1
842 if (a.resolution === b.resolution) return 0
846 return Object.assign(formattedJson, detailsJson) as VideoDetails
849 toActivityPubObject (): VideoTorrentObject {
850 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
851 if (!this.Tags) this.Tags = []
853 const tag = this.Tags.map(t => ({
854 type: 'Hashtag' as 'Hashtag',
861 identifier: this.language + '',
862 name: this.getLanguageLabel()
869 identifier: this.category + '',
870 name: this.getCategoryLabel()
877 identifier: this.licence + '',
878 name: this.getLicenceLabel()
885 if (Array.isArray(this.AccountVideoRates)) {
886 const likes: string[] = []
887 const dislikes: string[] = []
889 for (const rate of this.AccountVideoRates) {
890 if (rate.type === 'like') {
891 likes.push(rate.Account.Actor.url)
892 } else if (rate.type === 'dislike') {
893 dislikes.push(rate.Account.Actor.url)
897 likesObject = activityPubCollection(likes)
898 dislikesObject = activityPubCollection(dislikes)
902 if (Array.isArray(this.VideoShares)) {
903 const shares: string[] = []
905 for (const videoShare of this.VideoShares) {
906 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Actor)
907 shares.push(shareUrl)
910 sharesObject = activityPubCollection(shares)
914 if (Array.isArray(this.VideoComments)) {
915 const comments: string[] = []
917 for (const videoComment of this.VideoComments) {
918 comments.push(videoComment.url)
921 commentsObject = activityPubCollection(comments)
925 for (const file of this.VideoFiles) {
928 mimeType: 'video/' + file.extname.replace('.', ''),
929 url: this.getVideoFileUrl(file, baseUrlHttp),
930 width: file.resolution,
936 mimeType: 'application/x-bittorrent',
937 url: this.getTorrentUrl(file, baseUrlHttp),
938 width: file.resolution
943 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
944 url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
945 width: file.resolution
952 mimeType: 'text/html',
953 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
957 type: 'Video' as 'Video',
960 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
961 duration: 'PT' + this.duration + 'S',
969 commentsEnabled: this.commentsEnabled,
970 published: this.createdAt.toISOString(),
971 updated: this.updatedAt.toISOString(),
972 mediaType: 'text/markdown',
973 content: this.getTruncatedDescription(),
976 url: this.getThumbnailUrl(baseUrlHttp),
977 mediaType: 'image/jpeg',
978 width: THUMBNAILS_SIZE.width,
979 height: THUMBNAILS_SIZE.height
983 dislikes: dislikesObject,
984 shares: sharesObject,
985 comments: commentsObject,
989 id: this.VideoChannel.Actor.url
993 id: this.VideoChannel.Account.Actor.url
999 getTruncatedDescription () {
1000 if (!this.description) return null
1003 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1006 return truncate(this.description, options)
1009 optimizeOriginalVideofile = async function () {
1010 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1011 const newExtname = '.mp4'
1012 const inputVideoFile = this.getOriginalFile()
1013 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1014 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1016 const transcodeOptions = {
1017 inputPath: videoInputPath,
1018 outputPath: videoOutputPath
1022 // Could be very long!
1023 await transcode(transcodeOptions)
1025 await unlinkPromise(videoInputPath)
1027 // Important to do this before getVideoFilename() to take in account the new file extension
1028 inputVideoFile.set('extname', newExtname)
1030 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
1031 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
1033 inputVideoFile.set('size', stats.size)
1035 await this.createTorrentAndSetInfoHash(inputVideoFile)
1036 await inputVideoFile.save()
1039 // Auto destruction...
1040 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
1046 transcodeOriginalVideofile = async function (resolution: VideoResolution) {
1047 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1048 const extname = '.mp4'
1050 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1051 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1053 const newVideoFile = new VideoFileModel({
1059 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1061 const transcodeOptions = {
1062 inputPath: videoInputPath,
1063 outputPath: videoOutputPath,
1067 await transcode(transcodeOptions)
1069 const stats = await statPromise(videoOutputPath)
1071 newVideoFile.set('size', stats.size)
1073 await this.createTorrentAndSetInfoHash(newVideoFile)
1075 await newVideoFile.save()
1077 this.VideoFiles.push(newVideoFile)
1080 getOriginalFileHeight () {
1081 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1083 return getVideoFileHeight(originalFilePath)
1086 getDescriptionPath () {
1087 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1090 getCategoryLabel () {
1091 let categoryLabel = VIDEO_CATEGORIES[this.category]
1092 if (!categoryLabel) categoryLabel = 'Misc'
1094 return categoryLabel
1097 getLicenceLabel () {
1098 let licenceLabel = VIDEO_LICENCES[this.licence]
1099 if (!licenceLabel) licenceLabel = 'Unknown'
1104 getLanguageLabel () {
1105 let languageLabel = VIDEO_LANGUAGES[this.language]
1106 if (!languageLabel) languageLabel = 'Unknown'
1108 return languageLabel
1111 removeThumbnail () {
1112 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1113 return unlinkPromise(thumbnailPath)
1117 // Same name than video thumbnail
1118 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1121 removeFile (videoFile: VideoFileModel) {
1122 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1123 return unlinkPromise(filePath)
1126 removeTorrent (videoFile: VideoFileModel) {
1127 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1128 return unlinkPromise(torrentPath)
1131 private getBaseUrls () {
1135 if (this.isOwned()) {
1136 baseUrlHttp = CONFIG.WEBSERVER.URL
1137 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1139 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1140 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1143 return { baseUrlHttp, baseUrlWs }
1146 private getThumbnailUrl (baseUrlHttp: string) {
1147 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1150 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1151 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1154 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1155 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1158 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1159 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1160 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1161 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1163 const magnetHash = {
1167 infoHash: videoFile.infoHash,
1171 return magnetUtil.encode(magnetHash)