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,
134 model: () => AccountModel,
138 model: () => ActorModel,
140 exclude: [ 'privateKey', 'publicKey' ]
145 model: () => ServerModel,
156 [ScopeNames.WITH_TAGS]: {
157 include: [ () => TagModel ]
159 [ScopeNames.WITH_FILES]: {
162 model: () => VideoFileModel,
167 [ScopeNames.WITH_SHARES]: {
170 model: () => VideoShareModel,
171 include: [ () => ActorModel ]
175 [ScopeNames.WITH_RATES]: {
178 model: () => AccountVideoRateModel,
179 include: [ () => AccountModel ]
183 [ScopeNames.WITH_COMMENTS]: {
186 model: () => VideoCommentModel
198 fields: [ 'createdAt' ]
201 fields: [ 'duration' ]
213 fields: [ 'channelId' ]
216 fields: [ 'id', 'privacy' ]
224 export class VideoModel extends Model<VideoModel> {
227 @Default(DataType.UUIDV4)
229 @Column(DataType.UUID)
233 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
239 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
245 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
251 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
256 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
261 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
267 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
268 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
272 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
302 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
303 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
308 commentsEnabled: boolean
316 @ForeignKey(() => VideoChannelModel)
320 @BelongsTo(() => VideoChannelModel, {
326 VideoChannel: VideoChannelModel
328 @BelongsToMany(() => TagModel, {
329 foreignKey: 'videoId',
330 through: () => VideoTagModel,
335 @HasMany(() => VideoAbuseModel, {
342 VideoAbuses: VideoAbuseModel[]
344 @HasMany(() => VideoFileModel, {
351 VideoFiles: VideoFileModel[]
353 @HasMany(() => VideoShareModel, {
360 VideoShares: VideoShareModel[]
362 @HasMany(() => AccountVideoRateModel, {
369 AccountVideoRates: AccountVideoRateModel[]
371 @HasMany(() => VideoCommentModel, {
379 VideoComments: VideoCommentModel[]
382 static async sendDelete (instance: VideoModel, options) {
383 if (instance.isOwned()) {
384 if (!instance.VideoChannel) {
385 instance.VideoChannel = await instance.$get('VideoChannel', {
389 include: [ ActorModel ]
392 transaction: options.transaction
393 }) as VideoChannelModel
396 logger.debug('Sending delete of video %s.', instance.url)
398 return sendDeleteVideo(instance, options.transaction)
405 static async removeFilesAndSendDelete (instance: VideoModel) {
406 const tasks: Promise<any>[] = []
408 tasks.push(instance.removeThumbnail())
410 if (instance.isOwned()) {
411 if (!Array.isArray(instance.VideoFiles)) {
412 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
415 tasks.push(instance.removePreview())
417 // Remove physical files and torrents
418 instance.VideoFiles.forEach(file => {
419 tasks.push(instance.removeFile(file))
420 tasks.push(instance.removeTorrent(file))
424 return Promise.all(tasks)
426 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err)
431 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
434 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
435 function getRawQuery (select: string) {
436 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
437 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
438 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
439 'WHERE "Account"."actorId" = ' + actorId
440 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
441 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
442 'WHERE "VideoShare"."actorId" = ' + actorId
444 return `(${queryVideo}) UNION (${queryVideoShare})`
447 const rawQuery = getRawQuery('"Video"."id"')
448 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
454 order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ],
457 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
462 model: VideoShareModel,
465 [Sequelize.Op.and]: [
468 [Sequelize.Op.not]: null
484 model: VideoChannelModel,
494 model: AccountVideoRateModel,
495 include: [ AccountModel ]
503 return Bluebird.all([
504 // FIXME: typing issue
505 VideoModel.findAll(query as any),
506 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
507 ]).then(([ rows, totals ]) => {
508 // totals: totalVideos + totalVideoShares
510 let totalVideoShares = 0
511 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
512 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
514 const total = totalVideos + totalVideoShares
522 static listUserVideosForApi (userId: number, start: number, count: number, sort: string) {
526 order: [ getSort(sort) ],
529 model: VideoChannelModel,
544 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
552 static async listForApi (start: number, count: number, sort: string) {
556 order: [ getSort(sort) ]
559 const serverActor = await getServerActor()
561 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
562 .findAndCountAll(query)
563 .then(({ rows, count }) => {
571 static async searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) {
572 const query: IFindOptions<VideoModel> = {
575 order: [ getSort(sort) ],
578 [Sequelize.Op.iLike]: '%' + value + '%'
583 const serverActor = await getServerActor()
585 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST, serverActor.id ] })
586 .findAndCountAll(query).then(({ rows, count }) => {
594 static load (id: number) {
595 return VideoModel.findById(id)
598 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
599 const query: IFindOptions<VideoModel> = {
605 if (t !== undefined) query.transaction = t
607 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
610 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
611 const query: IFindOptions<VideoModel> = {
620 if (t !== undefined) query.transaction = t
622 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
625 static loadAndPopulateAccountAndServerAndTags (id: number) {
627 order: [ [ 'Tags', 'name', 'ASC' ] ]
631 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
632 .findById(id, options)
635 static loadByUUID (uuid: string) {
643 .scope([ ScopeNames.WITH_FILES ])
647 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) {
649 order: [ [ 'Tags', 'name', 'ASC' ] ],
656 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS ])
660 static loadAndPopulateAll (id: number) {
662 order: [ [ 'Tags', 'name', 'ASC' ] ],
670 ScopeNames.WITH_RATES,
671 ScopeNames.WITH_SHARES,
672 ScopeNames.WITH_TAGS,
673 ScopeNames.WITH_FILES,
674 ScopeNames.WITH_ACCOUNT_DETAILS,
675 ScopeNames.WITH_COMMENTS
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 href: this.getVideoFileUrl(file, baseUrlHttp),
930 width: file.resolution,
936 mimeType: 'application/x-bittorrent',
937 href: this.getTorrentUrl(file, baseUrlHttp),
938 width: file.resolution
943 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
944 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
945 width: file.resolution
952 mimeType: 'text/html',
953 href: 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)