Skip to content

Commit

Permalink
feat: allow more methods of adding torrents
Browse files Browse the repository at this point in the history
  • Loading branch information
scttcper committed Dec 17, 2018
1 parent 9658004 commit 2d873d5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
17 changes: 12 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,16 +164,23 @@ export class Deluge {
return req.body;
}

async upload(filePath: string): Promise<UploadResponse> {
async upload(torrent: string | Buffer): Promise<UploadResponse> {
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, {
Expand All @@ -183,8 +190,8 @@ export class Deluge {
return JSON.parse(res.body);
}

async addTorrent(filePath: string, config: Partial<AddTorrentOptions> = {}) {
const upload = await this.upload(filePath);
async addTorrent(torrent: string | Buffer, config: Partial<AddTorrentOptions> = {}) {
const upload = await this.upload(torrent);
if (!upload.success || !upload.files.length) {
throw new Error('Failed to upload');
}
Expand Down
14 changes: 13 additions & 1 deletion test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import pWaitFor from 'p-wait-for';
import fs from 'fs';

import { Deluge } from '../src/index';

Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 2d873d5

Please sign in to comment.