forked from rwaldron/enterprise-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
82 lines (68 loc) · 1.91 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
process.chdir(__dirname);
require.paths.push('/usr/local/lib/node');
var express = require('express')
, hl = require("highlight").Highlight
, io = require('socket.io');
var app = express.createServer()
, socket = io.listen(app);
app.configure(function () {
app.use(express.methodOverride());
app.use(express.bodyDecoder());
app.use(app.router);
app.use(express.staticProvider(__dirname + '/public'));
});
// Colors
var colors = 'ff0090,ffff00,0bff00,08e3ff,ff460d'.split(',');
// Tips
var tips = require('./tips');
// Make 'em sexy
tips.forEach(function (tip) {
if (tip.example) {
// Wrap it in script tags to trigger JavaScript highlighting...sigh
tip.example = hl('<script>\n' + tip.example.join('\n') + '\n</script>');
// Unwrap (hax)
tip.example = tip.example.replace('<span class="tag"><<span class="keyword">script</span>></span><span class="javascript">', '');
tip.example = tip.example.replace('</span><span class="tag"></<span class="keyword">script</span>></span>', '');
}
});
// Routes
app.get('/', function (req, res) {
showTip(req, res, generateRandomIndex());
});
app.get('/:permalink', function (req, res) {
var index = req.params.permalink;
if (tips[index - 1]) {
showTip(req, res, index);
} else {
res.redirect('/');
}
});
// WebSocket
socket.on('connection', function(client){
client.on('message', function (action) {
if (action === 'refresh') {
client.send(JSON.stringify(generateTip(generateRandomIndex())));
}
});
});
// Utilities
function showTip (req, res, index) {
res.render('index.jade', {
locals: {
tip: tips[index - 1],
color: colors[Math.floor(Math.random() * colors.length)],
index: index
}
});
}
function generateTip (index) {
return {
tip: tips[index - 1],
color: colors[Math.floor(Math.random() * colors.length)],
index: index
};
}
function generateRandomIndex() {
return Math.ceil(Math.random() * tips.length);
}
app.listen(3002);