-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.js
More file actions
114 lines (86 loc) · 2.73 KB
/
api.js
File metadata and controls
114 lines (86 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
var url = require('url');
var config = require('./config');
var util = require('./util');
var db = require('./db');
exports.action = function(req, res) {
if (!req.accepts('json')) {
res.json(new JsonError("Must accept JSON", "mustacceptjson"));
}
var id = req.params.action;
if ("shortenurl" == id) {
return shortenUrl(req, res);
}
if ("expandurl" == id) {
return expandUrl(req, res);
}
res.json(new JsonError("Invalid action: " + id, "invalidaction"));
};
// Shortens a url
function shortenUrl(req, res) {
var link = req.body.link;
if (!link) {
return res.json(new JsonError("Not a valid link", "invalidlink"));
}
if (link && link.substring(0, 'http'.length) != 'http') {
link = 'http://' + link;
}
if (!util.isValidUrl(link)) {
return res.json(new JsonError("Not a valid link", "invalidlink"));
}
for (var index in config.urloptions.disallowed) {
if (~link.indexOf(config.urloptions.disallowed[index])) {
return res.json(new JsonError("That link contains a prohibited domain", "linkprohibited"));
}
}
db.shorten(link, function(response){
if (response.status != 'OK') {
res.json(new JsonError("Unknown error", "unknownerror"));
console.log(response);
return;
}
id = response.id;
res.json(new JsonResponse({
link: link,
id: response.id,
pravius: config.setup.host + '/' + response.id,
secret: response.secret,
existed: response.existed
}));
});
}
// Expands a url
function expandUrl(req, res) {
var id = req.body.id;
if (!id) {
if (!req.body.url) {
return res.json(new JsonError("Neither the 'id' nor the 'url' property were set.", "nodata"));
}
var path = url.parse(req.body.url).pathname;
if (!path || !util.isValidSecret(path.substring(1))) {
return res.json(new JsonError("Invalid URL given", "invalidurl"));
}
id = path.substring(1);
}
db.expand(id, function(response){
if (response.status != 'OK') {
return res.json(new JsonError("The link doesn't exist", "linkgone"));
}
res.json(new JsonResponse({
pravius: config.setup.host + '/' + id,
id: id,
link: response.long
}));
});
}
// Json returns
function JsonError(message, error) {
this.status = "error";
this.message = message;
if (error) {
this.error = error;
}
}
function JsonResponse(data) {
this.status = "ok";
this.data = data;
}