forked from alexbain/lirc_web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
342 lines (283 loc) · 9.12 KB
/
app.js
File metadata and controls
342 lines (283 loc) · 9.12 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#! /usr/bin/env node
// Requirements
var express = require('express');
var logger = require('morgan');
var compress = require('compression');
var lircNode = require('lirc_node');
var consolidate = require('consolidate');
var swig = require('swig');
var labels = require('./lib/labels');
var https = require('https');
var fs = require('fs');
var macros = require('./lib/macros');
var leven = require('leven');
var context = {
appname: 'Amazon Echo / Alexa LIRC Skill Server',
server: null,
intent: null,
query: null,
request: null,
response: null,
statement: null
};
var INTENTS = {
MUTE: "mute",
POWER: "power",
TV_CHANNEL: "tvChannel",
UNKNOWN: ""
}
var PROMPTS = {
NONE: -1
};
// Precompile templates
var JST = {
index: swig.compileFile(__dirname + '/templates/index.swig'),
appcache: swig.compileFile(__dirname + '/templates/appcache.swig'),
};
// Set bootup time as the cache busting hash for the app cache manifest
var bootupTime = Date.now();
// Create app
var app = module.exports = express();
// lirc_web configuration
var config = {};
// Server & SSL options
var port = 3000;
var sslOptions = {
key: null,
cert: null,
};
var labelFor = {};
// App configuration
app.engine('.html', consolidate.swig);
app.use(logger('combined'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(compress());
app.use(express.static(__dirname + '/static'));
function _init() {
var home = process.env.HOME;
lircNode.init();
// Config file is optional
try {
try {
config = require(__dirname + '/config.json');
} catch (e) {
config = require(home + '/.lirc_web_config.json');
}
} catch (e) {
console.log('DEBUG:', e);
console.log('WARNING: Cannot find config.json!');
}
if (config.socket) {
lircNode.setSocket(config.socket);
}
// Refresh the app cache manifest hash
bootupTime = Date.now();
}
function refineRemotes(myRemotes) {
var newRemotes = {};
var newRemoteCommands = null;
var remote = null;
function isBlacklistExisting(remoteName) {
return config.blacklists && config.blacklists[remoteName];
}
function getCommandsForRemote(remoteName) {
var remoteCommands = myRemotes[remoteName];
var blacklist = null;
if (isBlacklistExisting(remoteName)) {
blacklist = config.blacklists[remoteName];
remoteCommands = remoteCommands.filter(function (command) {
return blacklist.indexOf(command) < 0;
});
}
return remoteCommands;
}
for (remote in myRemotes) {
newRemoteCommands = getCommandsForRemote(remote);
newRemotes[remote] = newRemoteCommands;
}
return newRemotes;
}
// Based on node environment, initialize connection to lircNode or use test data
if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
lircNode.remotes = require(__dirname + '/test/fixtures/remotes.json');
config = require(__dirname + '/test/fixtures/config.json');
} else {
_init();
}
// initialize Labels for remotes / commands
labelFor = labels(config.remoteLabels, config.commandLabels);
// Routes
// Index
app.get('/', function (req, res) {
var refinedRemotes = refineRemotes(lircNode.remotes);
res.send(JST.index({
remotes: refinedRemotes,
macros: config.macros,
repeaters: config.repeaters,
labelForRemote: labelFor.remote,
labelForCommand: labelFor.command,
}));
});
// application cache manifest
app.get('/app.appcache', function (req, res) {
res.send(JST.appcache({
hash: bootupTime,
}));
});
app.get('/echo', function (req, res) {
context.intent = getIntentFromRequest(req);
context.request = req;
context.statement = context.intent.query;
//Figure out what to do with the request.
parseIntent(function () {
if (context.cancel) {
context.prompt = PROMPTS.NONE;
context.userPrompted = false;
context.cancel = false;
context.intent.responseEnd = true;
}
//Respond to the AWS lambda service
res.json({
text: context.intent.responseText,
shouldEndSession: context.intent.responseEnd
});
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////
//// Parse intent to determine what to do.
///////////////////////////////////////////////////////////////////////////////////////////////////////
function parseIntent(callback) {
if (context.intent.responseEnd && !context.cancel) {
context.userPrompted = false;
context.cancel = true;
context.intent.responseEnd = true;
context.intent.cancel = true;
runAMacro(callback);
}
}
function runAMacro(callback) {
if(context.intent.intentName == INTENTS.TV_CHANNEL) {
// If the macro exists, execute it
for(child in config.macros){
if(leven(child, context.statement) < 4) {
macros.exec(config.macros[child], lircNode);
context.intent.responseText = "OK. The TV remote changed the channel to " + child + ".";
break;
}
}
} else if(context.intent.intentName == INTENTS.MUTE) {
macros.exec(config.macros[INTENTS.MUTE], lircNode);
context.intent.responseText = "OK. The TV remote pushed the mute button";
} else if(context.intent.intentName == INTENTS.POWER) {
macros.exec(config.macros[INTENTS.POWER], lircNode);
context.intent.responseText = "OK. The TV remote pushed the power button";
}
if(context.intent.responseText == '') {
context.intent.responseText = "Sorry, I'm not sure I can get the TV remote to do that.";
}
callback(context);
}
// Refresh
app.get('/refresh', function (req, res) {
_init();
res.redirect('/');
});
// List all remotes in JSON format
app.get('/remotes.json', function (req, res) {
res.json(refineRemotes(lircNode.remotes));
});
// List all commands for :remote in JSON format
app.get('/remotes/:remote.json', function (req, res) {
if (lircNode.remotes[req.params.remote]) {
res.json(refineRemotes(lircNode.remotes)[req.params.remote]);
} else {
res.sendStatus(404);
}
});
// List all macros in JSON format
app.get('/macros.json', function (req, res) {
res.json(config.macros);
});
// List all commands for :macro in JSON format
app.get('/macros/:macro.json', function (req, res) {
if (config.macros && config.macros[req.params.macro]) {
res.json(config.macros[req.params.macro]);
} else {
res.sendStatus(404);
}
});
// Send :remote/:command one time
app.post('/remotes/:remote/:command', function (req, res) {
lircNode.irsend.send_once(req.params.remote, req.params.command, function () {});
res.setHeader('Cache-Control', 'no-cache');
res.sendStatus(200);
});
// Start sending :remote/:command repeatedly
app.post('/remotes/:remote/:command/send_start', function (req, res) {
lircNode.irsend.send_start(req.params.remote, req.params.command, function () {});
res.setHeader('Cache-Control', 'no-cache');
res.sendStatus(200);
});
// Stop sending :remote/:command repeatedly
app.post('/remotes/:remote/:command/send_stop', function (req, res) {
lircNode.irsend.send_stop(req.params.remote, req.params.command, function () {});
res.setHeader('Cache-Control', 'no-cache');
res.sendStatus(200);
});
// Execute a macro (a collection of commands to one or more remotes)
app.post('/macros/:macro', function (req, res) {
// If the macro exists, execute it
if (config.macros && config.macros[req.params.macro]) {
macros.exec(config.macros[req.params.macro], lircNode);
res.setHeader('Cache-Control', 'no-cache');
res.sendStatus(200);
} else {
res.setHeader('Cache-Control', 'no-cache');
res.sendStatus(404);
}
});
// Listen (http)
if (config.server && config.server.port) {
port = config.server.port;
}
// only start server, when called as application
if (!module.parent) {
app.listen(port);
console.log('Open Source Universal Remote UI + API has started on port ' + port + ' (http).');
}
// Listen (https)
if (config.server && config.server.ssl && config.server.ssl_cert && config.server.ssl_key && config.server.ssl_port) {
sslOptions = {
key: fs.readFileSync(config.server.ssl_key),
cert: fs.readFileSync(config.server.ssl_cert),
};
https.createServer(sslOptions, app).listen(config.server.ssl_port);
console.log('Open Source Universal Remote UI + API has started on port ' + config.server.ssl_port + ' (https).');
}
function getIntentFromRequest(req) {
var query = getQueryFromRequest(req);
var json = query && query.json != undefined && query.json != 'undefined' ? JSON.parse(query.json) : null;
var queryText = '';
if(json && json.slots && json.slots.Question) {
var queryText = json.slots.Question.value;
}
var intentName = json ? json.name : INTENTS.UNKNOWN;
var responseEnd = true;
var responseText = '';
return {
query: queryText,
intentName: intentName,
responseText: responseText,
responseEnd: responseEnd
};
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
//// Utility
///////////////////////////////////////////////////////////////////////////////////////////////////////
function getQueryFromRequest(req) {
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
return query;
}