]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Add ability to disable webtorrent
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
ce33919c 1import { logger } from './logger'
6040f87d 2import { generateVideoImportTmpPath } from './utils'
ce33919c 3import * as WebTorrent from 'webtorrent'
d7a25329 4import { createWriteStream, ensureDir, remove, writeFile } from 'fs-extra'
6dd9de95 5import { CONFIG } from '../initializers/config'
d0b52b52 6import { dirname, join } from 'path'
30ff39e7
C
7import * as createTorrent from 'create-torrent'
8import { promisify2 } from './core-utils'
d7a25329
C
9import { MVideo } from '@server/typings/models/video/video'
10import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/typings/models/video/video-file'
11import { isStreamingPlaylist, MStreamingPlaylistVideo } from '@server/typings/models/video/video-streaming-playlist'
12import { STATIC_PATHS, WEBSERVER } from '@server/initializers/constants'
13import * as parseTorrent from 'parse-torrent'
14import * as magnetUtil from 'magnet-uri'
15import { isArray } from '@server/helpers/custom-validators/misc'
16import { extractVideo } from '@server/lib/videos'
17import { getTorrentFileName, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
18
19const createTorrentPromise = promisify2<string, any, any>(createTorrent)
ce33919c 20
cf9166cf 21async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName?: string }, timeout: number) {
990b6a0b 22 const id = target.magnetUri || target.torrentName
c48e82b5 23 let timer
ce33919c 24
6040f87d 25 const path = generateVideoImportTmpPath(id)
990b6a0b 26 logger.info('Importing torrent video %s', id)
ce33919c 27
6040f87d 28 const directoryPath = join(CONFIG.STORAGE.TMP_DIR, 'webtorrent')
a71de50b
C
29 await ensureDir(directoryPath)
30
ce33919c
C
31 return new Promise<string>((res, rej) => {
32 const webtorrent = new WebTorrent()
c48e82b5 33 let file: WebTorrent.TorrentFile
ce33919c 34
990b6a0b 35 const torrentId = target.magnetUri || join(CONFIG.STORAGE.TORRENTS_DIR, target.torrentName)
541006e3 36
a71de50b 37 const options = { path: directoryPath }
541006e3 38 const torrent = webtorrent.add(torrentId, options, torrent => {
c48e82b5
C
39 if (torrent.files.length !== 1) {
40 if (timer) clearTimeout(timer)
ce33919c 41
e37c85e9
C
42 for (let file of torrent.files) {
43 deleteDownloadedFile({ directoryPath, filepath: file.path })
44 }
45
46 return safeWebtorrentDestroy(webtorrent, torrentId, undefined, target.torrentName)
dae4a1c0 47 .then(() => rej(new Error('Cannot import torrent ' + torrentId + ': there are multiple files in it')))
c48e82b5
C
48 }
49
a71de50b
C
50 file = torrent.files[ 0 ]
51
52 // FIXME: avoid creating another stream when https://github.com/webtorrent/webtorrent/issues/1517 is fixed
53 const writeStream = createWriteStream(path)
54 writeStream.on('finish', () => {
55 if (timer) clearTimeout(timer)
56
d0b52b52 57 return safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 58 .then(() => res(path))
69fa54a0 59 })
a71de50b
C
60
61 file.createReadStream().pipe(writeStream)
3e17515e 62 })
ce33919c
C
63
64 torrent.on('error', err => rej(err))
c48e82b5 65
cf9166cf
C
66 timer = setTimeout(async () => {
67 return safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
68 .then(() => rej(new Error('Webtorrent download timeout.')))
69 }, timeout)
ce33919c
C
70 })
71}
72
d7a25329
C
73async function createTorrentAndSetInfoHash (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) {
74 const video = extractVideo(videoOrPlaylist)
75
76 const options = {
77 // Keep the extname, it's used by the client to stream the file inside a web browser
78 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
79 createdBy: 'PeerTube',
80 announceList: [
81 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
82 [ WEBSERVER.URL + '/tracker/announce' ]
83 ],
84 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + getVideoFilename(videoOrPlaylist, videoFile) ]
85 }
86
87 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
88
89 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, getTorrentFileName(videoOrPlaylist, videoFile))
90 logger.info('Creating torrent %s.', filePath)
91
92 await writeFile(filePath, torrent)
93
94 const parsedTorrent = parseTorrent(torrent)
95 videoFile.infoHash = parsedTorrent.infoHash
96}
97
98function generateMagnetUri (
99 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
100 videoFile: MVideoFileRedundanciesOpt,
101 baseUrlHttp: string,
102 baseUrlWs: string
103) {
104 const video = isStreamingPlaylist(videoOrPlaylist)
105 ? videoOrPlaylist.Video
106 : videoOrPlaylist
107
108 const xs = videoOrPlaylist.getTorrentUrl(videoFile, baseUrlHttp)
109 const announce = videoOrPlaylist.getTrackerUrls(baseUrlHttp, baseUrlWs)
110 let urlList = [ videoOrPlaylist.getVideoFileUrl(videoFile, baseUrlHttp) ]
111
112 const redundancies = videoFile.RedundancyVideos
113 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
114
115 const magnetHash = {
116 xs,
117 announce,
118 urlList,
119 infoHash: videoFile.infoHash,
120 name: video.name
121 }
122
123 return magnetUtil.encode(magnetHash)
124}
30ff39e7 125
ce33919c
C
126// ---------------------------------------------------------------------------
127
128export {
d7a25329
C
129 createTorrentAndSetInfoHash,
130 generateMagnetUri,
ce33919c
C
131 downloadWebTorrentVideo
132}
c48e82b5
C
133
134// ---------------------------------------------------------------------------
135
d0b52b52
C
136function safeWebtorrentDestroy (
137 webtorrent: WebTorrent.Instance,
138 torrentId: string,
139 downloadedFile?: { directoryPath: string, filepath: string },
140 torrentName?: string
141) {
c48e82b5
C
142 return new Promise(res => {
143 webtorrent.destroy(err => {
144 // Delete torrent file
145 if (torrentName) {
d0b52b52 146 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
147 remove(torrentId)
148 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
149 }
150
151 // Delete downloaded file
e37c85e9 152 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 153
e37c85e9 154 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
155
156 return res()
157 })
158 })
159}
e37c85e9
C
160
161function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
162 // We want to delete the base directory
163 let pathToDelete = dirname(downloadedFile.filepath)
164 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
165
166 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
167
168 logger.debug('Removing %s after webtorrent download.', toRemovePath)
169 remove(toRemovePath)
170 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
171}