forked from remy/remote-tilt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
206 lines (169 loc) · 4.84 KB
/
Copy pathserver.js
File metadata and controls
206 lines (169 loc) · 4.84 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
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
var express = require('express'),
ws = require('websocket.io'),
fs = require('fs'),
connections = {},
parse = require('url').parse,
path = require('path'),
dict = [];
function generatePassword(limit, inclNumbers) {
var vowels = 'aeiou'.split('');
var constonants = 'bcdfghjklmnpqrstvwxyz'.split('');
var word = '', i, num;
if (!limit) limit = 8;
for (i = 0; i < (inclNumbers ? limit - 3 : limit); i++) {
if (i % 2 == 0) { // even = vowels
word += vowels[Math.floor(Math.random() * 4)];
} else {
word += constonants[Math.floor(Math.random() * 20)];
}
}
if (inclNumbers) {
num = Math.floor(Math.random() * 99) + '';
if (num.length == 1) num = '00' + num;
else if (num.length == 2) num = '0' + num;
word += num;
}
return word.substr(0, limit);
}
function loadDict() {
fs.readFile('/usr/share/dict/words', function (err, data) {
if (err) return;
var words = data.toString().split(/\n/),
length = words.length;
for (var i = 0; i < length; i++) {
var len = words[i].length;
if (len > 3 && len < 8) {
dict.push(words[i].toLowerCase());
}
}
console.log('dictionary loaded: ' + dict.length + ' words');
});
}
function removeConnection(res) {
var i = connections[res.key].indexOf(res);
if (i !== -1) {
connections[res.key].splice(i, 1);
if (connections[res.key] == 0) {
delete connections[res.key];
}
}
}
function sendSSE(res, id, event, message) {
var data = '';
if (event) {
data += 'event: ' + event + '\n';
}
// blank id resets the id counter
if (id) {
data += 'id: ' + id + '\n';
} else {
data += 'id\n';
}
if (message) {
data += 'data: ' + message.split(/\n/).join('\ndata:') + '\n';
}
data += '\n'; // final part of message
res.write(data);
if (res.hasOwnProperty('xhr')) {
clearTimeout(res.xhr);
res.xhr = setTimeout(function () {
res.end();
removeConnection(res);
}, 250);
}
}
var app = express.createServer();
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.listen(process.env.PORT || process.argv[2] || 8000);
// routes
app.get('/', function (req, res) {
res.render('index');
});
app.post('/register', function (req, res) {
res.redirect('/' + req.body.key);
});
app.get('/getkey', function (req, res) {
var key = '';
for (var i = 0; i < 10; i++) { // try 10 times, then make it up
key = dict[dict.length * Math.random() | 0];
if (!connections[key]) break;
key = ''; // nasty
}
if (!key) key = generatePassword(5); // chance of being in use? less than testing
// send as json
res.writeHead(200, {
'Content-Type' : 'application/json',
'Access-Control-Allow-Origin': '*' // we love you all
});
console.log('new key: ' + key + ' - ' + req.headers.referer + ' - ' + (new Date));
res.end(JSON.stringify({ key: key }));
});
app.get('/:key', function (req, res, next) {
var key = req.params.key;
if (connections[key]) {
res.render('remote', {
key: key
});
} else {
res.render('index', {
error: 'The key requested "' + key + '" is not being listened for. Fire up your client again.'
});
}
});
var server = ws.attach(app),
LISTEN = 1,
SERVE = 2;
server.on('connection', function (socket) {
var url = parse(socket.req.url);
var key = path.basename(url.pathname),
type = LISTEN;
if (url.pathname.indexOf('/listen/') === 0) {
if (!connections[key]) connections[key] = [];
connections[key].push(socket);
} else if (url.pathname.indexOf('/serve/') === 0) {
type = SERVE;
}
console.log((type == LISTEN ? 'listening: ' : 'serving: ') + key + ' - ' + (new Date));
socket.on('message', function (message) {
if (type == SERVE) {
// broadcast to listen sockets on the same key
if (connections[key] && connections[key].length) {
connections[key].forEach(function (socket) {
socket.send(message);
});
}
}
});
socket.on('close', function () {
if (connections[key]) {
var i = connections[key].indexOf(socket);
if (i !== -1) {
connections[key].splice(i, 1);
if (connections[key] == 0) {
delete connections[key];
}
}
}
});
});
loadDict();
console.log('%s mode listening on http://' + app.address().address + ':' + app.address().port, app.settings.env);
/*
if popup can't open, offer to create connection to remote-tilt.com
if agree - connect an eventsource session given a particular key
server: prompt for key
if key matches a sesssion, offer up the remote control
and send message to session
*/