Browse Source

(feat) create magnet form & refactor

Feature - Create magnet form & Refactor
pull/2/head
Muthu Kumar 5 years ago
committed by GitHub
parent
commit
c5917818bf
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 13
      package-lock.json
  2. 6
      public/index.html
  3. 31
      routes/index.js
  4. 58
      routes/magnet.js

13
package-lock.json

@ -1,6 +1,6 @@
{ {
"name": "magnet", "name": "@codefeathers/magnet",
"version": "0.0.0", "version": "0.5.0",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@ -138,15 +138,6 @@
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
"integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=" "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s="
}, },
"cookie-parser": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.3.tgz",
"integrity": "sha1-D+MfoZ0AC5X0qt8fU/3CuKIDuqU=",
"requires": {
"cookie": "0.3.1",
"cookie-signature": "1.0.6"
}
},
"cookie-signature": { "cookie-signature": {
"version": "1.0.6", "version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",

6
public/index.html

@ -7,6 +7,12 @@
<body> <body>
<h1>⚡ :magnet:</h1> <h1>⚡ :magnet:</h1>
<form action="/api" method="POST">
<p>URI: <input type="text" name="uri"><br/></p>
<p>Title (optional): <input type="text" name="title"><br/></p>
<button type="submit">Create</button>
</form>
<hr />
<p>POST to <code>/api</code> with this request body: <p>POST to <code>/api</code> with this request body:
<pre> <pre>
{ {

31
routes/index.js

@ -4,25 +4,40 @@ const router = express.Router();
const db = require('../modules/db'); const db = require('../modules/db');
const magnet = require('./magnet'); const magnet = require('./magnet');
template = (magnet, meta) => (` const foundTemplate = (magnet, meta) => (`
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>${meta.title}</title> <title> ${meta.title}</title>
<meta http-equiv="refresh" content="0; url=${magnet}"> <meta http-equiv="refresh" content="0; url=${magnet}">
<link rel="stylesheet" href="/stylesheets/style.css"> <link rel="stylesheet" href="/stylesheets/style.css">
</head> </head>
<body> <body>
<h1> :magnet:</h1> <h1>${meta.title} </h1>
<pre>${magnet}</pre> <pre>${magnet}</pre>
</p> </p>
</body> </body>
</html> </html>
`) `)
router.get('/:shortlink', (req, res, next) => { const notFoundTemplate = () => (`
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Not Found</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1 style="text-align: center;"> Oops! Nothing found here.</h1>
</body>
</html>
`)
router.get('/:shortlink', (req, res) => {
db.get(req.params.shortlink) db.get(req.params.shortlink)
.then(record => { .then(record => {
const r = String(record); const r = String(record);
@ -30,16 +45,16 @@ router.get('/:shortlink', (req, res, next) => {
const meta = { const meta = {
title: title ? '⚡ ' + title : '⚡ :magnet:' title: title ? '⚡ ' + title : '⚡ :magnet:'
} }
res.send(template(magnet, meta)) res.send(foundTemplate(magnet, meta))
}) })
.catch(e => { .catch(e => {
console.log(`[ERR!] Occured while retrieving shortlink`, e.stack); console.log(`[ERR!] Occured while retrieving shortlink`, e.stack);
res.end('Invalid shortlink') res.send(notFoundTemplate())
});
}); });
})
/* GET home page. */ /* GET home page. */
router.get('/', function(req, res, next) { router.get('/', function (req, res) {
res.render('index', { title: ':magnet: ⚡️' }); res.render('index', { title: ':magnet: ⚡️' });
}); });

58
routes/magnet.js

@ -3,47 +3,59 @@ const router = express.Router();
const db = require('../modules/db'); const db = require('../modules/db');
const createMagnet = (uri, title, baseUrl, ctx) => { const handleSuccess = ({ res, baseUrl, key }) => res.json({ status: 'OK', uri: baseUrl + '/' + key })
const key = Math.random().toString(36).slice(4);
if (!uri.match(/magnet:\?xt=urn:.*/i)) { const handleError = ({ res, uri }, err) => {
switch (err.message) {
case "ERR_NO_URI": {
console.log(`[ERR!] Invalid request ${uri}`);
return res.status(400).json({
err: 'No magnet URI found'
});
}
case "ERR_INVALID_URI": {
console.log(`[ERR!] Invalid request ${uri}`); console.log(`[ERR!] Invalid request ${uri}`);
ctx.res.status(400); return res.status(400).json({
ctx.res.json({
err: 'Invalid magnet URI' err: 'Invalid magnet URI'
}); });
return;
} }
default: {
const value = title ? uri + '@@title@@' + title : uri;
db.put(key, value)
.then(() => ctx.res.json({
status: 'OK',
uri: baseUrl + '/' + key
}))
.catch(e => {
console.log(`[ERR!] Occured while creating new shortlink`, e.stack); console.log(`[ERR!] Occured while creating new shortlink`, e.stack);
ctx.res.status(520); return res.status(520).json({
ctx.res.json({
err: 'Unknown err! Please try again' err: 'Unknown err! Please try again'
}); });
}) }
}
}
const createMagnet = (uri, title, baseUrl, res) => {
if (!uri)
return Promise.reject(new Error("ERR_NO_URI"));
if (!uri.match(/magnet:\?xt=urn:.*/i))
return Promise.reject(new Error("ERR_INVALID_URI"));
const key = Math.random().toString(36).slice(4);
const value = title ? uri + '@@title@@' + title : uri;
return db.put(key, value)
.then(() => handleSuccess({ res, baseUrl, key }))
.catch(handleError.bind(undefined, { res, uri }));
} }
router.get('/:body', (req, res, next) => { router.get('/:body', (req, res) => {
const body = req.originalUrl.split('/api/')[1]; const body = req.originalUrl.split('/api/')[1];
const [uri, title] = body.split('@@title@@'); const [uri, title] = body.split('@@title@@');
const baseUrl = req.protocol + '://' + req.get('host'); const baseUrl = req.protocol + '://' + req.get('host');
return createMagnet(uri, title, baseUrl, { req, res }); return createMagnet(uri, title, baseUrl, res);
}) });
/* POST magnet link. */ /* POST magnet link. */
router.post('/', (req, res, next) => { router.post('/', (req, res) => {
const { uri, title } = req.body; const { uri, title } = req.body;
const baseUrl = req.protocol + '://' + req.get('host'); const baseUrl = req.protocol + '://' + req.get('host');
return createMagnet(uri, title, baseUrl, { req, res }); return createMagnet(uri, title, baseUrl, res);
}); });
module.exports = router; module.exports = router;
Loading…
Cancel
Save