-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoogleTV.js
317 lines (285 loc) · 10.2 KB
/
GoogleTV.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
305
306
307
308
309
310
311
312
313
314
315
316
317
const fs = require ( "fs");
const path = require ( 'path');
const { createLogger,transports,format} = require ( 'winston');
const { combine, timestamp, json } = format;
const logger = createLogger({
defaultMeta: { component: 'G-TV' },
format: format.combine(
format.timestamp({
format: 'YYMMDD-HH:mm:ss'
}),
format.json(),
format.printf(info => {
return `${info.timestamp} ${info.level}: ${info.message}`;
})
),
transports: [
new transports.Console({ level: 'debug' })
]
});
const express = require ( 'express');
const server = express();
const bodyParser = require ( 'body-parser');
const {
AndroidRemote,
RemoteKeyCode,
RemoteDirection
} = require ( "androidtv-remote");
const { resolve } = require ( "path");
var Connections = []
var myAndroidRemote;
var MyHost;
var MyCert = {cert: "",key:""}
var NewCode
var Coderequested=false;
async function getSession(MyHost,MyCerts) {
return new Promise(function (resolve, reject) {
let host = MyHost
let options = {
pairing_port : 6467,
remote_port : 6466,
name : 'androidtv-remote',
cert : MyCerts}
myAndroidRemote = new AndroidRemote(host, options)
myAndroidRemote.on('secret', () => {
logger.debug(`We need a new secret; provide this via web interface please (for example: port http://10.0.0.1:6468/secret?secret=1cba6d )`);
logger.debug(`replace 10.0.01 with the ip-address of meta, and fill in code that is shown on screen`);
Coderequested=true; // set signal that we need a secret code (provided via web-interface of this container)
}
)
myAndroidRemote.on('powered', (powered) => {
logger.debug(`Powered: ${powered}`);
});
myAndroidRemote.on('volume', (volume) => {
logger.debug(`Volume: ${volume.level} / ${volume.maximum} | Muted : " + ${volume.muted}`);
});
myAndroidRemote.on('current_app', (current_app) => {
logger.debug(`Current App : ${current_app}`);
});
myAndroidRemote.on('error', (error) => {
logger.debug(`Error: ${error}`);
});
myAndroidRemote.on('unpaired', () => {
logger.debug(`Unpaired`);
});
myAndroidRemote.on('ready', () => {
logger.debug(`Connection with GoogleTV is ready`);
resolve(myAndroidRemote)
});
myAndroidRemote.start().then (() => {
})
})
}
async function HandleDownload(MyType,MyElement,res)
{
MyType = MyType.toLowerCase();
if (["images","irdevices","devices","firmware"].includes(MyType))
{var Path = "/opt/meta/NoCloud/"+MyType
var FilePath = Path + "/"+MyElement
var ResolvedPath = path.resolve(FilePath); // Resolve the path that is defined to the actual path
if (ResolvedPath.substring(0,Path.length) == Path) // And check to see if the path is not manipulated to download files that aren;t supposed to.
{logger.info(`Request to download type ${MyType} ${MyElement}`)
//var myFile = new File(ResolvedPath);
if (fs.existsSync(ResolvedPath))
{logger.info(`File successfully downloaded: ${ResolvedPath}`)
res.download(ResolvedPath)
}
else
{logger.error(`File not found: ${ResolvedPath}`)
res.status(404).json({"Status": "fail",error: 404, reason: "File not found"});
}
}
else
{logger.error(`Manipulation found: ${MyType} ${MyElement}`)
res.status(505).json({"Status": "fail",error: 505, reason: "Invalid path manipulation"});
}
}
else
{logger.error(`Invalid type: ${MyType} ${MyElement}`)
res.status(506).json({"Status": "fail",error: 506, reason: "Type not allowed"});
}
}
async function FillInCodeRequest(code)
{
logger.info("Sending code");
logger.info(code);
myAndroidRemote.sendCode(code);
logger.info("Need to get new certificate")
let NewCert = MyCert;
if (NewCert.key.length == 0) {
logger.info("Need to get new certificate")
NewCert = myAndroidRemote.getCertificate();
logger.info(`Writing certificates to .ssh`)
fs.writeFile('/opt/meta/.ssh/GoogleCert.pem', JSON.stringify(NewCert.cert), (err) =>
{ if (err)
throw err;
logger.info('Write cert complete');
});
fs.writeFile('/opt/meta/.ssh/GoogleKey.pem', JSON.stringify(NewCert.key), (err) =>
{if (err)
throw err;
logger.info('Write key complete');
});
}
}
async function LoadCert()
{
fs.access('/opt/meta/.ssh/GoogleCert.pem', fs.constants.F_OK | fs.constants.W_OK, (err) => {
if (err) {
logger.info("No certificates to load")
} else {
logger.info("Certificates available, we will now load them")
let cert = fs.readFileSync('/opt/meta/.ssh/GoogleCert.pem')
let key = fs.readFileSync('/opt/meta/.ssh/GoogleKey.pem')
MyCert.cert = JSON.parse(cert)
MyCert.key = JSON.parse(key)
logger.info("Certificates loaded") }
});
}
async function Handle_NewSecretCode(Newcode)
{let MyMessage;
//http://10.0.0.99:6468/secret?secret=fced8e
logger.info(`Received secret code: ${Newcode}`);
if (Coderequested == true)
{ MyMessage = "Thank you for code " + Newcode;
FillInCodeRequest(Newcode);
Coderequested = false;
}
else
MyMessage = "Thanks for providing this code, but no pairing code was asked for....";
logger.info(MyMessage);
return MyMessage;
}
async function main() {
//var Return = getSession()
await LoadCert();
logger.info(`Loaded cert: ${MyCert}`)
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: true
}));
let config = {
"webPort" : 6468,
"friendlyDeviceName" : "GoogleTV"
}
await server.listen(config.webPort, () => {
logger.info(`Webserver running on port: ${config.webPort}`);
});
server.get("/shutdown", (req, res, next) => {
res.sendFile(__dirname + '/index.html');
});
server.post("/secret", async (req, res, next) => {
NewCode=req.body.secret
let MyResult = await Handle_NewSecretCode(NewCode);
res.json({"Type": "Post", "Status": MyResult});
});
server.get("/secret", async (req, res, next) => {
NewCode=req.query.secret;
let MyResult = await Handle_NewSecretCode(NewCode);
res.json({"Status": MyResult});
});
server.get("/api", (req, res, next) => {
logger.info(`GTV: ${req.query}`)
MyHost = req.query.host
logger.info(`GET GoogleTV Call for ${MyHost}`)
HandleApi(req,res,next)
});
server.get("/dapi", (req, res, next) => {
logger.info(`GTV: ${req.query}`)
MyHost = req.query.host
logger.info(`GET download Call for ${MyHost}`)
//HandleApi(req,res,next)
});
server.get("/download", (req, res, next) => {
var MyType=req.query.type;
logger.info(`GET (download) ${MyType}`)
if (MyType != undefined && MyType != "")
{var MyName = req.query.name;
if (MyName != undefined && MyName != "")
HandleDownload(MyType,MyName,res);
else
{logger.error(`Missing object name: ${MyType} ${MyElement}`)
res.status(404).json({
error: 404,
message: "Route not found."
})
res.status(504).json({"Status": "fail",error:504, reason: "Object name not given"});
}
}
else
{logger.error(`Missing object Type: ${MyType} ${MyElement}`)
res.json({"Status": "fail",reason: "Type of object not given"});
}
});
server.post("/api", (req, res, next) => {
logger.info(`GTV: ${req.body}`)
MyHost = req.body.host
logger.info(`POST GoogleTV Call for ${MyHost}`)
HandleApi(req,res,next)
});
}
async function sendPower() {
GetConnection(MyHost).then ((androidRemote) => {
logger.info("Toggling power");
androidRemote.sendPower();
})
};
async function sendKey(key) {
logger.debug(`Send key: ${key}; ${RemoteKeyCode[key]}`);
GetConnection(MyHost).then ((androidRemote) => {
androidRemote.sendKey(RemoteKeyCode[key], RemoteDirection.SHORT);
})
};
async function sendAppLink(AppLink) {
logger.debug(`Send appLink: ${AppLink}`);
GetConnection(MyHost).then ((androidRemote) => {
androidRemote.sendAppLink(AppLink);
})
};
function HandleApi(req,res,next)
{
switch(req.body.action){
case 'sendKey':
sendKey(req.body.key);
break;
case 'sendAction':
sendKey(req.body.theAction);
break;
case 'sendPower':
sendPower();
break;
case 'sendAppLink':
sendAppLink(req.body.AppLink);
break;
// am start -a android.intent.action.VIEW -n org.xbmc.kodi/.Splash
default:
res.json({"Status": "Error"});
logger.info(`resolve default`)
return;
break;
}
res.json({"Status": "Ok"});
}
function GetConnection(MyHost) {
return new Promise(function (resolve, reject) {
logger.debug(`Checking availability of connection`);
let connectionIndex = Connections.findIndex((con) => {return con.Host == MyHost});
if (connectionIndex < 0) {
logger.debug(`Connection not yet created, doing now for: ${MyHost}`)
getSession(MyHost,MyCert).then ((Connection) => {
GotSession(Connection);
myAndroidRemote = Connection;
resolve(Connection);
})
}
else {
myAndroidRemote = Connections[connectionIndex].Connector
resolve(myAndroidRemote)
}
})
}
function GotSession(Connection) {
myAndroidRemote = Connection
Connections.push({"Host": MyHost, "Connector": Connection});
}
main();