Skip to content

Commit

Permalink
Add await/async
Browse files Browse the repository at this point in the history
  • Loading branch information
johackim committed Mar 23, 2017
1 parent 1c2a88c commit 3b18c94
Show file tree
Hide file tree
Showing 11 changed files with 463 additions and 584 deletions.
2 changes: 1 addition & 1 deletion .babelrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "presets": ["es2015"] }
{ "presets": ["es2015", "es2017"] }
2 changes: 1 addition & 1 deletion makefile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ debug: ## Run with babel (with debug)

test: ## Run unit tests
@ cp -n config/test.json.dist config/test.json
@ NODE_ENV=test ./node_modules/.bin/mocha --compilers js:babel-core/register --require babel-polyfill test/setup.js test/specs/*.spec.js
@ NODE_ENV=test ./node_modules/.bin/mocha -t 9999999 --compilers js:babel-core/register --require babel-polyfill test/setup.js test/specs/*.spec.js

deploy: ## Deploy
npm publish
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,15 @@
"request": "^2.81.0",
"request-progress": "^3.0.0",
"request-promise": "^4.2.0",
"node-fetch": "^1.6.3",
"url": "^0.11.0"
},
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-core": "^6.24.0",
"babel-preset-es2015": "^6.24.0",
"babel-preset-es2017": "^6.22.0",
"body-parser": "^1.17.1",
"co-mocha": "^1.2.0",
"eslint": "^3.18.0",
"eslint-config-airbnb": "^14.1.0",
"eslint-plugin-import": "^2.2.0",
Expand Down
17 changes: 8 additions & 9 deletions src/connect.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import config from 'config';
import debug from 'debug';
import { request } from './utils';
import fetch from 'node-fetch';

const log = debug('connect');

export default function* getToken(username, password) {
export default async function getToken(username, password) {
log('connect to real-debrid.com');

const options = {
const url = `${config.apiBaseUrl}/oauth/v2/token`;
const res = await fetch(url, {
method: 'POST',
uri: `${config.apiBaseUrl}/oauth/v2/token`,
form: {
body: JSON.stringify({
username,
password,
client_id: config.clientId,
grant_type: 'password',
},
json: true,
};
}),
});

return (yield request(options)).access_token;
return (await res.json()).access_token;
}
108 changes: 37 additions & 71 deletions src/torrent.js
Original file line number Diff line number Diff line change
@@ -1,127 +1,93 @@
import rp from 'request-promise';
import config from 'config';
import debug from 'debug';
import fs from 'fs';
import ora from 'ora';
import sleep from 'co-sleep';
import { handleErrorMessage } from './utils';
import fetch from 'node-fetch';

const log = debug('torrent');

export function* getInfosTorrent(idTorrent, token) {
export const getInfosTorrent = async (idTorrent, token) => {
log(`get infos torrent ${idTorrent}`);

const options = {
uri: `${config.apiEndpoint}/torrents/info/${idTorrent}?auth_token=${token}`,
json: true,
};

let data;
yield rp(options).then((body) => {
data = body;
}).catch(handleErrorMessage);
const res = await fetch(`${config.apiEndpoint}/torrents/info/${idTorrent}?auth_token=${token}`);
const data = await res.json();

return data;
}
};

export function* getTorrentList(token) {
export const getTorrentList = async (token) => {
log('get torrent list');

const options = {
uri: `${config.apiEndpoint}/torrents?auth_token=${token}`,
json: true,
};

let data;
yield rp(options).then((body) => {
data = body;
}).catch(handleErrorMessage);
const res = await fetch(`${config.apiEndpoint}/torrents?auth_token=${token}`);
const data = await res.json();

return data;
}
};

export function* selectFile(idTorrent, token, files = 'all') {
export const selectFile = async (idTorrent, token, files = 'all') => {
log(`select file ${idTorrent}`);

const options = {
await fetch(`${config.apiEndpoint}/torrents/selectFiles/${idTorrent}?auth_token=${token}`, {
method: 'POST',
uri: `${config.apiEndpoint}/torrents/selectFiles/${idTorrent}?auth_token=${token}`,
json: true,
form: {
files,
},
};

let data;
yield rp(options).then((body) => {
data = body;
}).catch(handleErrorMessage);

return data;
}
body: JSON.stringify({ files }),
});
};

export function* addMagnet(magnet, token) {
export const addMagnet = async (magnet, token) => {
log(`add magnet ${magnet}`);

const options = {
const res = await fetch(`${config.apiEndpoint}/torrents/addMagnet?auth_token=${token}`, {
method: 'POST',
uri: `${config.apiEndpoint}/torrents/addMagnet?auth_token=${token}`,
json: true,
form: {
body: JSON.stringify({
magnet: encodeURI(magnet),
host: 'uptobox.com',
},
};
}),
});

let data;
yield rp(options).then((body) => {
data = body;
}).catch(handleErrorMessage);
const data = (await res.json()).id;

return data.id;
}
return data;
};

export function* addTorrent(torrent, token) {
export const addTorrent = async (torrent, token) => {
log(`add torrent ${torrent}`);

const options = {
uri: `${config.apiEndpoint}/torrents/addTorrent?auth_token=${token}`,
json: true,
};

let data;
yield fs.createReadStream(torrent).pipe(rp.put(options)).then((body) => {
data = body;
const res = await fetch(`${config.apiEndpoint}/torrents/addTorrent?auth_token=${token}`, {
method: 'PUT',
body: await fs.createReadStream(torrent),
});

return data.id;
}
const data = (await res.json()).id;

return data;
};

export function* convertTorrent(torrent, token) {
export const convertTorrent = async (torrent, token) => {
log(`convert torrent ${torrent}`);

let idTorrent;
if (torrent.match(/^magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{20,50}/i)) {
idTorrent = yield addMagnet(torrent, token);
idTorrent = await addMagnet(torrent, token);
} else {
idTorrent = yield addTorrent(torrent, token);
idTorrent = await addTorrent(torrent, token);
}
yield selectFile(idTorrent, token);
await selectFile(idTorrent, token);

let link = [];
let status = 'wait';
let progressConvert = 0;
const spinner = ora(`Convert torrent progress: ${progressConvert}% (${status})`).start();
while (!link.length) {
const infos = yield getInfosTorrent(idTorrent, token);
const infos = await getInfosTorrent(idTorrent, token); // eslint-disable-line
status = infos.status;
link = infos.links;
progressConvert = Number(infos.progress);
spinner.text = `Convert torrent progress: ${progressConvert}% (${status})`;
yield sleep(config.requestDelay);
await sleep(config.requestDelay); // eslint-disable-line
}
spinner.stop();

console.log(`Convert finish: ${link.toString()}`);
return link.toString();
}
};
20 changes: 10 additions & 10 deletions src/unrestrict.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import config from 'config';
import debug from 'debug';
import { request } from './utils';
import fetch from 'node-fetch';

const log = debug('unrestrict');

export default function* unrestrict(link, token) {
export default async (link, token) => {
log(`unrestrict link ${link}`);

const options = {
const url = `${config.apiEndpoint}/unrestrict/link?auth_token=${token}`;
const res = await fetch(url, {
method: 'POST',
uri: `${config.apiEndpoint}/unrestrict/link?auth_token=${token}`,
form: {
body: JSON.stringify({
link,
},
json: true,
};
}),
headers: { 'Content-Type': 'application/json' },
});

return (yield request(options)).download;
}
return (await res.json()).download;
};
8 changes: 1 addition & 7 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import rp from 'request-promise';

export function handleErrorMessage(error) {
export default function handleErrorMessage(error) {
const errorCode = error.error.error_code;

switch (errorCode) {
Expand All @@ -27,7 +25,3 @@ export function handleErrorMessage(error) {
}
}

export function* request(options) {
return yield rp(options).catch(handleErrorMessage);
}

8 changes: 4 additions & 4 deletions test/specs/connect.spec.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import getToken from '../../src/connect';

describe('connect', () => {
it('should return access token', function* () {
it('should return access token', async () => {
server.post('/oauth/v2/token', (req, res) => res.json({
access_token: 'APS7T57AXM7G3U7KCT57NYCVAY',
expires_in: 3600,
Expand All @@ -12,11 +12,11 @@ describe('connect', () => {
const username = 'username';
const password = 'password';

const token = yield getToken(username, password);
const token = await getToken(username, password);
assert.equal(token, 'APS7T57AXM7G3U7KCT57NYCVAY');
});

it.skip('should return error if bad logins', function* () {
it.skip('should return error if bad logins', async () => {
server.post('/oauth/v2/token', (req, res) => res.status(403).json({
error: 'invalid_login',
error_code: 12,
Expand All @@ -25,7 +25,7 @@ describe('connect', () => {
const username = 'username';
const password = 'password';

assert.throws(yield getToken(username, password, Error, 'Invalid login'));
assert.throws(await getToken(username, password, Error, 'Invalid login'));
});

afterEach(() => {
Expand Down
28 changes: 14 additions & 14 deletions test/specs/torrent.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,53 +62,53 @@ const torrentInfos = {
const token = 'APS7T57AXM7G3U7KCT57NYCVAY';

describe('torrent', () => {
it('should return torrent informations', function* () {
it('should return torrent informations', async () => {
server.get('/torrents/info/:id', (req, res) => res.json(torrentInfos));

const id = 'JKLJOIIA4545Z';
const infos = yield getInfosTorrent(id, token);
const infos = await getInfosTorrent(id, token);
assert.equal(infos.filename, 'test.rar');
});

it('should get torrent list', function* () {
it('should get torrent list', async () => {
server.get('/torrents', (req, res) => res.json(torrentList));

const infos = yield getTorrentList(token);
const infos = await getTorrentList(token);
assert.equal(infos.length, 2);
assert.equal(infos[0].host, '1fichier.com');
});

it('should select file', function* () {
it('should select file', async () => {
server.post('/torrents/selectFiles/:id', (req, res) => res.json());
const id = 'NLBUIGAEOXYYC';
yield selectFile(id, token);
await selectFile(id, token);
});

it('should add magnet', function* () {
it('should add magnet', async () => {
server.get('/torrents/info/:id', (req, res) => res.json(torrentInfos));
server.post('/torrents/addMagnet', (req, res) => res.json({
id: 'NLBUIGAEOXYYC',
uri: 'https://api.real-debrid.com/torrents/info/NLBUIGAEOXYYC',
}));

const magnet = 'magnet:?xt=urn:btih:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const id = yield addMagnet(magnet, token);
const id = await addMagnet(magnet, token);
assert.equal(id, 'NLBUIGAEOXYYC');
});

it('should add torrent', function* () {
it('should add torrent', async () => {
server.get('/torrents/info/:id', (req, res) => res.json(torrentInfos));
server.put('/torrents/addTorrent', (req, res) => res.json({
id: 'JHGTA554AZEDF',
uri: 'https://api.real-debrid.com/torrents/info/JHGTA554AZEDF',
}));

const torrentFile = `${__dirname}/../fixtures/test.torrent`;
const id = yield addTorrent(torrentFile, token);
const id = await addTorrent(torrentFile, token);
assert.equal(id, 'JHGTA554AZEDF');
});

it('should convert magnet to ddl file', function* () {
it('should convert magnet to ddl file', async () => {
server.post('/torrents/selectFiles/:id', (req, res) => res.json());
server.get('/torrents', (req, res) => res.json(torrentList));
server.get('/torrents/info/:id', (req, res) => res.json(torrentInfos));
Expand All @@ -118,11 +118,11 @@ describe('torrent', () => {
}));

const magnet = 'magnet:?xt=urn:btih:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const link = yield convertTorrent(magnet, token);
const link = await convertTorrent(magnet, token);
assert.equal(link, 'http://uptobox.com/xxxxxxxxxxxx');
});

it('should convert torrent to ddl file', function* () {
it('should convert torrent to ddl file', async () => {
server.post('/torrents/selectFiles/:id', (req, res) => res.json());
server.get('/torrents', (req, res) => res.json(torrentList));
server.get('/torrents/info/:id', (req, res) => res.json(torrentInfos));
Expand All @@ -132,7 +132,7 @@ describe('torrent', () => {
}));

const torrentFile = `${__dirname}/../fixtures/test.torrent`;
const link = yield convertTorrent(torrentFile, token);
const link = await convertTorrent(torrentFile, token);
assert.equal(link, 'http://uptobox.com/xxxxxxxxxxxx');
});
});
Loading

0 comments on commit 3b18c94

Please sign in to comment.