From ef4e41f6f0d5f7ea08c70efcf7c6e4a71d117db4 Mon Sep 17 00:00:00 2001 From: Jesse Chan Date: Sat, 22 May 2021 20:53:50 +0800 Subject: [PATCH] server: don't store created torrents to temp directory Bug: #248 --- server/routes/api/torrents.ts | 86 ++++++++++++++++------------------- 1 file changed, 40 insertions(+), 46 deletions(-) diff --git a/server/routes/api/torrents.ts b/server/routes/api/torrents.ts index 10533bce..df075761 100644 --- a/server/routes/api/torrents.ts +++ b/server/routes/api/torrents.ts @@ -242,56 +242,50 @@ router.post('/create', async (req, res): } const torrentFileName = sanitize(name ?? sanitizedPath.split(path.sep).pop() ?? `${Date.now()}`).concat('.torrent'); - const torrentPath = getTempPath(torrentFileName); - return new Promise((resolve) => { - createTorrent( - sanitizedPath, - { - name, - comment, - createdBy: 'Flood - flood.js.org', - private: isPrivate, - announceList: [trackers], - info: infoSource - ? { - source: infoSource, - } - : undefined, - }, - (err, torrent) => { - if (err) { - const {message} = err; - return resolve(res.status(500).json({message})); - } + let torrent: Buffer; + try { + torrent = await new Promise((resolve, reject) => { + createTorrent( + sanitizedPath, + { + name, + comment, + createdBy: 'Flood - flood.js.org', + private: isPrivate, + announceList: [trackers], + info: infoSource + ? { + source: infoSource, + } + : undefined, + }, + (err, torrent) => (err ? reject(err) : resolve(torrent)), + ); + }); + } catch ({message}) { + return res.status(500).json({message}); + } - fs.promises.writeFile(torrentPath, torrent).then( - () => { - res.attachment(torrentFileName); - res.download(torrentPath); + await req.services.clientGatewayService + .addTorrentsByFile({ + files: [torrent.toString('base64')], + destination: fs.lstatSync(sanitizedPath).isDirectory() ? sanitizedPath : path.dirname(sanitizedPath), + tags: tags ?? [], + isBasePath: true, + isCompleted: true, + isSequential: false, + isInitialSeeding: isInitialSeeding ?? false, + start: start ?? false, + }) + .catch(() => { + // do nothing. + }); - req.services.clientGatewayService - .addTorrentsByFile({ - files: [torrent.toString('base64')], - destination: fs.lstatSync(sanitizedPath).isDirectory() ? sanitizedPath : path.dirname(sanitizedPath), - tags: tags ?? [], - isBasePath: true, - isCompleted: true, - isSequential: false, - isInitialSeeding: isInitialSeeding ?? false, - start: start ?? false, - }) - .catch(() => { - // do nothing. - }); + res.attachment(torrentFileName); + res.contentType('application/x-bittorrent'); - resolve(res); - }, - ({code, message}) => resolve(res.status(500).json({code, message})), - ); - }, - ); - }); + return res.status(200).send(torrent); }); /**