-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
304 lines (245 loc) · 6.17 KB
/
app.js
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
* Module dependencies.
*/
var express = require('express')
, stylus = require('stylus')
, sio = require('socket.io')
, base60 = require('./base60')
, jadevu = require('jadevu')
, crypto = require('crypto')
, url = require('url')
, nib = require('nib')
, fs = require('fs')
/**
* Determine environment.
*/
var env = process.env.NODE_ENV || 'development';
/**
* Create db.
*/
redis = require('redis').createClient(
process.env.SHORTY_REDIS_URL
);
/**
* Redis lock.
* Uses "shorty-lock" as the key name.
* Default timeout of 10 seconds.
*/
var lock = require('redis-lock')(redis).bind(null, 'shorty-lock', 10000);
/**
* Create app.
*/
app = module.exports = express.createServer();
/**
* Basic middleware.
*/
if ('development' == env) {
app.use(express.logger('dev'));
}
if (process.env.SHORTY_BASIC_AUTH) {
app.use(express.basicAuth.apply(null, process.env.SHORTY_BASIC_AUTH.split(':')));
}
app.use(express.bodyParser());
app.use(stylus.middleware({ src: __dirname + '/public/', compile: css }));
app.use(express.static(__dirname + '/public'));
/**
* Socket.IO
*/
var io = sio.listen(app);
// quiet :)
io.set('log level', 0);
/**
* Reads a file
*
* @api private
*/
function read (file) {
return fs.readFileSync(__dirname + '/' + file, 'utf8');
}
/**
* Stylus compiler
*/
function css (str, path) {
return stylus(str)
.set('filename', path)
.set('compress', 'production' == env)
.use(nib())
.import('nib');
};
/**
* Configure app.
*/
app.configure(function () {
app.set('views', __dirname);
app.set('view engine', 'jade');
app.set('domain', process.env.SHORTY_DOMAIN || 'https://lrn.cc');
});
/**
* Development configuration.
*/
app.configure('development', function () {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
/**
* Production configuration.
*/
app.configure('production', function () {
app.use(express.errorHandler());
});
/**
* GET index page.
*/
app.get('/', function (req, res, next) {
redis.hlen('urls', function (err, length) {
if (err) return next(err);
res.render('index', { count: length });
});
});
/**
* POST a url.
*/
app.post('/', validate, exists, function (req, res, next) {
var url = req.body.url
, parsed = req.body.parsed
, private = req.body.private
, length
, short
, obj
lock(function (unlock) {
// get count of urls
redis.hlen('urls', onLenth);
function onLenth (err, len) {
if (err) return next(500);
length = len;
if (private) {
short = crypto.randomBytes(20).toString('hex');
} else {
short = base60.toString(length ? length + 1 : 0);
}
// next save the short url with the original url to the "urls" hash
redis.hset('urls', short, url, onUrlsSet);
}
function onUrlsSet (err) {
if (err) return next(err);
// next save the original url with the short url to the "urls-hash" hash
redis.hset('urls-hash', url, short, onUrlsHashSet);
}
function onUrlsHashSet (err) {
if (err) return next(err);
// finally create a "transaction" object for this action
obj = {
type: 'url created'
, url: url
, short: short
, date: new Date
};
// push the transaction object to the "transitions" list
redis.lpush('transactions', JSON.stringify(obj), onTransactions);
}
function onTransactions (err) {
if (err) return next(500);
obj.parsed = parsed;
io.of('/main').volatile.emit('total', length + 1);
io.of('/stats').volatile.emit('url created', short, parsed, Date.now());
res.send({ short: app.set('domain') + '/' + short });
process.nextTick(unlock);
}
});
});
/**
* Checkes that the URL is valid
*/
function validate (req, res, next) {
var parsed = req.body.parsed = url.parse(req.body.url);
if (!req.body.url || !parsed.protocol || !parsed.host) {
return res.send(400, { error: 'Bad `url` field' });
}
next();
};
/**
* Content negotiation.
*/
function accept(type) {
return function(req, res, next){
if (req.accepts(type)) return next();
next('route');
}
}
/**
* Checks that the URL doesnt exist already
*/
function exists (req, res, next) {
if (req.body.private) {
// for "private" links, always return a new one
return next();
}
redis.hget('urls-hash', req.body.url, function (err, val) {
if (err) return next(err);
if (val) return res.send({ short: app.set('domain') + '/' + val });
next();
});
}
/**
* GET statistics.
*/
app.get('/stats', accept('html'), function (req, res, next) {
redis.lrange('transactions', 0, 100, function (err, vals) {
if (err) return next(err);
res.render('stats', { transactions: vals ? vals.map(function (v) {
v = JSON.parse(v);
v.parsed = url.parse(v.url);
delete v.url;
return v;
}).reverse() : [] });
});
});
/**
* GET JSON statistics.
*/
app.get('/stats', accept('json'), function (req, res, next) {
redis.lrange('transactions', 0, 100, function (err, vals) {
if (err) return next(err);
res.send(vals.map(JSON.parse));
});
});
/**
* GET :short url to perform redirect.
*/
app.get('/:short', function (req, res, next) {
redis.hget('urls', req.params.short, function (err, val) {
if (err) return next(err);
if (!val) return res.render('404');
lock(function (unlock) {
redis.lpush('transactions', JSON.stringify({
type: 'url visited'
, url: val
, short: req.params.short
, date: Date.now()
, ip: req.socket.remoteAddress
, headers: req.headers
}), function (err) {
if (err) console.error(err);
});
io.of('/stats').volatile.emit(
'url visited'
, req.params.short
, url.parse(val)
, Date.now()
);
res.redirect(val);
process.nextTick(unlock);
});
});
});
/**
* Listen.
*/
if (!module.parent) {
app.listen(process.env.PORT || 3000, function () {
var addr = app.address();
console.error(' app listening on ' + addr.address + ':' + addr.port);
});
process.on('uncaughtException', function (e) {
console.error(e && e.stack ? e.stack : e);
});
}