]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/webtorrent.ts
Add ability to search by uuids/actor names
[github/Chocobozzz/PeerTube.git] / server / helpers / webtorrent.ts
CommitLineData
30ff39e7 1import * as createTorrent from 'create-torrent'
90a8bd30 2import { createWriteStream, ensureDir, remove, writeFile } from 'fs-extra'
d7a25329 3import * as magnetUtil from 'magnet-uri'
90a8bd30
C
4import * as parseTorrent from 'parse-torrent'
5import { dirname, join } from 'path'
6import * as WebTorrent from 'webtorrent'
d7a25329 7import { isArray } from '@server/helpers/custom-validators/misc'
90a8bd30
C
8import { WEBSERVER } from '@server/initializers/constants'
9import { generateTorrentFileName, getVideoFilePath } from '@server/lib/video-paths'
8efc27bf 10import { MVideo } from '@server/types/models/video/video'
90a8bd30
C
11import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file'
12import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist'
13import { CONFIG } from '../initializers/config'
14import { promisify2 } from './core-utils'
15import { logger } from './logger'
16import { generateVideoImportTmpPath } from './utils'
8efc27bf 17import { extractVideo } from './video'
d7a25329
C
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
a1587156 42 for (const file of torrent.files) {
e37c85e9
C
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
a1587156 50 file = torrent.files[0]
a71de50b
C
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
a1587156 57 safeWebtorrentDestroy(webtorrent, torrentId, { directoryPath, filepath: file.path }, target.torrentName)
a71de50b 58 .then(() => res(path))
a1587156 59 .catch(err => logger.error('Cannot destroy webtorrent.', { err }))
69fa54a0 60 })
a71de50b
C
61
62 file.createReadStream().pipe(writeStream)
3e17515e 63 })
ce33919c
C
64
65 torrent.on('error', err => rej(err))
c48e82b5 66
a1587156
C
67 timer = setTimeout(() => {
68 const err = new Error('Webtorrent download timeout.')
69
70 safeWebtorrentDestroy(webtorrent, torrentId, file ? { directoryPath, filepath: file.path } : undefined, target.torrentName)
71 .then(() => rej(err))
72 .catch(destroyErr => {
73 logger.error('Cannot destroy webtorrent.', { err: destroyErr })
74 rej(err)
75 })
76
cf9166cf 77 }, timeout)
ce33919c
C
78 })
79}
80
90a8bd30
C
81async function createTorrentAndSetInfoHash (
82 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
90a8bd30
C
83 videoFile: MVideoFile
84) {
8efc27bf
C
85 const video = extractVideo(videoOrPlaylist)
86
d7a25329
C
87 const options = {
88 // Keep the extname, it's used by the client to stream the file inside a web browser
89 name: `${video.name} ${videoFile.resolution}p${videoFile.extname}`,
90 createdBy: 'PeerTube',
91 announceList: [
92 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
93 [ WEBSERVER.URL + '/tracker/announce' ]
94 ],
90a8bd30 95 urlList: [ videoFile.getFileUrl(video) ]
d7a25329
C
96 }
97
98 const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options)
99
90a8bd30
C
100 const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution)
101 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename)
102 logger.info('Creating torrent %s.', torrentPath)
d7a25329 103
90a8bd30 104 await writeFile(torrentPath, torrent)
d7a25329 105
764b1a14
C
106 // Remove old torrent file if it existed
107 if (videoFile.hasTorrent()) {
108 await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename))
109 }
110
d7a25329
C
111 const parsedTorrent = parseTorrent(torrent)
112 videoFile.infoHash = parsedTorrent.infoHash
90a8bd30 113 videoFile.torrentFilename = torrentFilename
d7a25329
C
114}
115
116function generateMagnetUri (
8efc27bf 117 video: MVideo,
d7a25329 118 videoFile: MVideoFileRedundanciesOpt,
d9a2a031 119 trackerUrls: string[]
d7a25329 120) {
90a8bd30 121 const xs = videoFile.getTorrentUrl()
d9a2a031 122 const announce = trackerUrls
90a8bd30 123 let urlList = [ videoFile.getFileUrl(video) ]
d7a25329
C
124
125 const redundancies = videoFile.RedundancyVideos
126 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
127
128 const magnetHash = {
129 xs,
130 announce,
131 urlList,
132 infoHash: videoFile.infoHash,
133 name: video.name
134 }
135
136 return magnetUtil.encode(magnetHash)
137}
30ff39e7 138
ce33919c
C
139// ---------------------------------------------------------------------------
140
141export {
d441f2ed 142 createTorrentPromise,
d7a25329
C
143 createTorrentAndSetInfoHash,
144 generateMagnetUri,
ce33919c
C
145 downloadWebTorrentVideo
146}
c48e82b5
C
147
148// ---------------------------------------------------------------------------
149
d0b52b52
C
150function safeWebtorrentDestroy (
151 webtorrent: WebTorrent.Instance,
152 torrentId: string,
153 downloadedFile?: { directoryPath: string, filepath: string },
154 torrentName?: string
155) {
ba5a8d89 156 return new Promise<void>(res => {
c48e82b5
C
157 webtorrent.destroy(err => {
158 // Delete torrent file
159 if (torrentName) {
d0b52b52 160 logger.debug('Removing %s torrent after webtorrent download.', torrentId)
c48e82b5
C
161 remove(torrentId)
162 .catch(err => logger.error('Cannot remove torrent %s in webtorrent download.', torrentId, { err }))
163 }
164
165 // Delete downloaded file
e37c85e9 166 if (downloadedFile) deleteDownloadedFile(downloadedFile)
c48e82b5 167
e37c85e9 168 if (err) logger.warn('Cannot destroy webtorrent in timeout.', { err })
c48e82b5
C
169
170 return res()
171 })
172 })
173}
e37c85e9
C
174
175function deleteDownloadedFile (downloadedFile: { directoryPath: string, filepath: string }) {
176 // We want to delete the base directory
177 let pathToDelete = dirname(downloadedFile.filepath)
178 if (pathToDelete === '.') pathToDelete = downloadedFile.filepath
179
180 const toRemovePath = join(downloadedFile.directoryPath, pathToDelete)
181
182 logger.debug('Removing %s after webtorrent download.', toRemovePath)
183 remove(toRemovePath)
184 .catch(err => logger.error('Cannot remove torrent file %s in webtorrent download.', toRemovePath, { err }))
185}