forked from DaveBben/nodecast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
233 lines (197 loc) · 6.77 KB
/
server.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
var ssdp = require("peer-ssdp"),
peer = ssdp.createPeer(),
uuid = require('node-uuid'),
myUuid = uuid.v4(),
fs = require('fs'),
express = require('express'),
http = require('http'),
app = express(),
querystring = require('querystring'),
request = require('superagent')
logger = require('morgan')
bodyParser = require('body-parser')
methodOverride = require('method-override');
var os = require("os");
// var argv = require('optimist')
// .usage('Usage: $0 --name [name]')
// .demand(['name'])
// .argv;
var hostname = os.hostname();
var name = hostname;
app.set('port', 8008);
app.use(function(req, res, next) {
var data = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
next();
});
});
app.disable('x-powered-by');
app.use(express.static(__dirname + '/public'));
app.use(logger());
app.use(bodyParser());
app.use(methodOverride());
app.use(function (req, res, next) {
res.removeHeader("Connection");
next();
});
app.disable('x-powered-by');
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var WebSocketServer = require('websocket').server;
var WebSocketRouter = require('websocket').router;
var wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
var wssRouter = new WebSocketRouter();
wssRouter.attachServer(wsServer);
wsServer.on('request', function(request) {
});
wssRouter.mount('/stage','', function(request) {
global.stageConnection = request.accept(request.origin);
global.stageConnection.send(JSON.stringify({
cmd: "idle"
}));
});
wssRouter.mount('/system/control','', function(request) {
var connection = request.accept(request.origin);
console.log("system/control");
});
wssRouter.mount('/connection','', function(request) {
var connection = request.accept(request.origin);
var name;
connection.on('message', function(message) {
var cmd = JSON.parse(message.utf8Data);
if(cmd.type == "REGISTER") {
name = cmd.name;
connection.send(JSON.stringify({
type: "CHANNELREQUEST",
"senderId": 1,
"requestId": 1
}));
wssRouter.mount("/receiver/"+cmd.name, '', function(request) {
var receiverConnection = request.accept(request.origin);
var appName = request.resourceURL.pathname.replace('/receiver/','').replace('Dev','');
Apps.registered[appName].registerReceiver(receiverConnection);
});
} else if(cmd.type == "CHANNELRESPONSE") {
connection.send(JSON.stringify({
type: "NEWCHANNEL",
"senderId": 1,
"requestId": 1,
"URL": "ws://localhost:8008/receiver/"+name
}));
}
});
});
var regex = new RegExp('^/session/.*$');
wssRouter.mount(regex, '', function(request) {
var sessionConn = request.accept(request.origin);
console.log("Session up");
var appName = request.resourceURL.pathname.replace('/session/','');
var sessionId = request.resourceURL.search.replace('?','');
var targetApp = Apps.registered[appName];
if(targetApp) {
targetApp.registerSession(sessionConn);
}
});
function getIPAddress() {
var n = require('os').networkInterfaces();
var ip = []
for (var k in n) {
var inter = n[k];
for (var j in inter) {
if (inter[j].family === 'IPv4' && !inter[j].internal) {
return inter[j].address
}
}
}
}
var addr = getIPAddress();
console.log(addr);
setupApps(addr);
setupRoutes(addr);
setupSSDP(addr);
var Apps;
function setupApps(addr) {
Apps = require('./apps/apps.js');
Apps.init(fs, app);
Apps.registerApp(app, addr, "ChromeCast", "https://www.gstatic.com/cv/receiver.html?$query", "");
Apps.registerApp(app, addr, "YouTube", "https://www.youtube.com/tv?$query", "");
Apps.registerApp(app, addr, "PlayMovies", "https://play.google.com/video/avi/eureka?$query", "");
Apps.registerApp(app, addr, "GoogleMusic", "https://jmt17.google.com/sjdev/cast/player", "");
Apps.registerApp(app, addr, "GoogleCastSampleApp", "http://anzymrcvr.appspot.com/receiver/anzymrcvr.html", "");
Apps.registerApp(app, addr, "GoogleCastPlayer", "https://www.gstatic.com/eureka/html/gcp.html", "");
Apps.registerApp(app, addr, "Fling", "$query", "");
Apps.registerApp(app, addr, "TicTacToe", "http://www.gstatic.com/eureka/sample/tictactoe/tictactoe.html", "");
}
function setupRoutes(addr) {
app.get("/ssdp/device-desc.xml", function(req, res) {
//console.log(process.resourcesPath);
//This is going to throw error in development because reource changes
fs.readFile(`${process.resourcesPath}/app/device-desc.xml`, 'utf8', function (err,data) {
console.log(data);
data = data.replace("#uuid#", myUuid).replace("#base#","http://"+req.headers.host).replace("#name#", name);
res.type('xml');
res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Expose-Headers", "Location");
res.setHeader("Application-Url", "http://"+req.headers.host+"/apps");
res.send(data);
});
});
app.post('/connection/:app', function(req, res) {
console.log("Connecting App "+ req.params.app);
res.setHeader("Access-Control-Allow-Method", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.type("json");
res.send(JSON.stringify({
URL: "ws://"+addr+":8008/session/"+req.params.app+"?1",
pingInterval: 3
}))
});
app.get('/apps', function(req, res){
for (var key in Apps.registered) {
if(Apps.registered[key].config.state == "running") {
console.log("Redirecting to"+ key);
res.redirect('/apps/'+key);
return;
}
}
res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Expose-Headers", "Location");
res.setHeader("Content-Length", "0");
res.setHeader("Content-Type", "text/html; charset=UTF-8");
res.send(204, "");
});
}
function setupSSDP(addr) {
peer.on("ready",function(){
});
peer.on("notify",function(headers, address){
});
peer.on("search",function(headers, address){
if(headers.ST.indexOf("dial-multiscreen-org:service:dial:1") != -1) {
peer.reply({
LOCATION: "http://"+addr+":8008/ssdp/device-desc.xml",
ST: "urn:dial-multiscreen-org:service:dial:1",
"CONFIGID.UPNP.ORG": 7337,
"BOOTID.UPNP.ORG": 7337,
USN: "uuid:"+myUuid
}, address);
}
});
peer.start();
}
//