-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfritzbox.js
81 lines (71 loc) · 2.11 KB
/
fritzbox.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
const fetch = require('node-fetch')
const xml2js = require('xml2js')
const crypto = require('crypto')
class FritzBox {
constructor (config) {
this.config = config
}
async toggleWlan24 (toggle) {
const settings = await this.getSettings()
return this.applySettings({
ssid: settings.data.wlanSettings.ssid,
apActive: toggle ? 1 : 0
})
}
async getSettings () {
return this.querySettings()
}
applySettings (settings) {
return this.querySettings({
apply: 1,
...settings
})
}
async querySettings (options) {
await this.refreshSession()
return this.query('/data.lua', {
xhr: 1,
page: 'wSet',
sid: this.sid,
...options || {}
})
}
async refreshSession () {
var response = await this.query(`/login_sid.lua?sid=${this.sid}`)
if (!this.setSidFromResponse(response)) {
response = await this.createSession(response.SessionInfo.Challenge[0])
if (!this.setSidFromResponse(response)) {
console.log(response)
throw new Error('Session creation with FritzBox failed.')
}
}
}
createSession (challenge) {
const combination = Buffer.from(`${challenge}-${this.config.password}`, 'utf16le')
const hash = crypto.createHash('md5').update(combination).digest('hex')
const response = `${challenge}-${hash}`
return this.query(`/login_sid.lua?username=${this.config.username}&response=${response}`)
}
query (path, data) {
return fetch(`${this.config.host}${path}`, {
method: data ? 'POST' : 'GET',
body: data ? new URLSearchParams(data) : null,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(async response => {
if (response.headers.get('content-type') === 'text/xml') {
const parser = new xml2js.Parser()
const text = await response.text()
return parser.parseStringPromise(text)
}
return response.json()
})
}
setSidFromResponse (response) {
this.sid = response.SessionInfo.SID[0]
if (this.sid !== '0000000000000000') return true
}
}
module.exports = FritzBox