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