From 2d873d5b6c5130f4c609c9a866255564ea9e2e70 Mon Sep 17 00:00:00 2001 From: Scott Cooper Date: Sun, 16 Dec 2018 20:56:51 -0800 Subject: [PATCH] feat: allow more methods of adding torrents --- src/index.ts | 17 ++++++++++++----- test/index.spec.ts | 14 +++++++++++++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index f23e58f..2b01128 100644 --- a/src/index.ts +++ b/src/index.ts @@ -164,16 +164,23 @@ export class Deluge { return req.body; } - async upload(filePath: string): Promise { + async upload(torrent: string | Buffer): Promise { await this.validateAuth(); const isConnected = await this.connected(); if (!isConnected) { await this.connect(); } - const f = fs.createReadStream(filePath); const form = new FormData(); - form.append('file', f); + if (typeof torrent === 'string') { + if (fs.existsSync(torrent)) { + form.append('file', Buffer.from(fs.readFileSync(torrent))); + } else { + form.append('file', Buffer.from(torrent, 'base64')); + } + } else { + form.append('file', torrent); + } const url = resolve(this.config.baseURL, 'upload'); const res = await got.post(url, { @@ -183,8 +190,8 @@ export class Deluge { return JSON.parse(res.body); } - async addTorrent(filePath: string, config: Partial = {}) { - const upload = await this.upload(filePath); + async addTorrent(torrent: string | Buffer, config: Partial = {}) { + const upload = await this.upload(torrent); if (!upload.success || !upload.files.length) { throw new Error('Failed to upload'); } diff --git a/test/index.spec.ts b/test/index.spec.ts index c33239b..f264c8e 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -1,5 +1,6 @@ import path from 'path'; import pWaitFor from 'p-wait-for'; +import fs from 'fs'; import { Deluge } from '../src/index'; @@ -128,11 +129,22 @@ describe('Deluge', () => { expect(res.files.length).toBe(1); expect(res.success).toBe(true); }); - it('should add torrent', async () => { + it('should add torrent from file path string', async () => { const deluge = new Deluge({ baseURL }); const res = await deluge.addTorrent(torrentFile); expect(res.result).toBe(true); }); + it('should add torrent from file buffer', async () => { + const deluge = new Deluge({ baseURL }); + const res = await deluge.addTorrent(fs.readFileSync(torrentFile)); + expect(res.result).toBe(true); + }); + it('should add torrent from file contents base64', async () => { + const deluge = new Deluge({ baseURL }); + const contents = Buffer.from(fs.readFileSync(torrentFile)).toString('base64'); + const res = await deluge.addTorrent(contents); + expect(res.result).toBe(true); + }); it('should get torrent status', async () => { const deluge = new Deluge({ baseURL }); const res = await setupTorrent(deluge);