-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathLgApi.js
67 lines (57 loc) · 1.98 KB
/
LgApi.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
import fetch from 'node-fetch';
import parse from 'xml-parser';
import isReachable from 'is-reachable';
import controls from './controls.json';
import config from './config.json';
/* eslint max-len: 0 */
const API = {
tv: `http://${config.ip}:8080/udap/api/`,
code: config.code,
headers: {
'User-Agent': 'Apple iOS UDAP/2.0 Connect SDK',
'Content-Type': 'text/xml'
},
command(name) {
const body = `<?xml version="1.0" encoding="utf-8"?><envelope><api type="command"><name>HandleKeyInput</name><value>${controls[name]}</value></api></envelope>`;
return API.sendRequest(body, 'command')
.then((res) => (res.status === 401) ? API.authenticate(API.command.bind(this, name)) : res.status);
},
info(name) {
return fetch(`${this.tv}data?target=${name}`, {
headers: this.headers
})
.then((res) => res.text())
.then((xml) => parse(xml).root.children[0]);
},
pair() {
const body = '<?xml version="1.0" encoding="utf-8"?> <envelope> <api type="pairing"> <name>showKey</name> </api> </envelope>';
return API.sendRequest(body, 'pairing').then(() => {
setTimeout(API.finishPairing, 1000);
});
},
finishPairing() {
const body = `<?xml version="1.0" encoding="utf-8"?><envelope> <api type="pairing"> <name>hello</name><value>${API.code}</value> <port>8080</port> </api> </envelope>`;
return API.sendRequest(body, 'pairing');
},
authenticate(callback) {
const body = `<?xml version="1.0" encoding="utf-8"?> <envelope> <api type="pairing"> <name>hello</name> <value>${API.code}</value> <port>8080</port> </api> </envelope>`;
return API.sendRequest(body, 'pairing')
.then((res) => {
if (res.status === 200) {
return callback();
}
});
},
sendRequest(body, path) {
return fetch(`${this.tv}${path}`, {
method: 'POST',
headers: this.headers,
body
});
},
isAlive() {
return isReachable(this.tv)
.then(reachable => reachable);
}
};
export default API;