forked from paviro/MMM-FRITZ-Box-Callmonitor
-
Notifications
You must be signed in to change notification settings - Fork 2
/
node_helper.js
268 lines (235 loc) · 7.64 KB
/
node_helper.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
"use strict";
const NodeHelper = require("node_helper");
const CallMonitor = require("node-fritzbox-callmonitor");
const vcard = require("vcard-json");
const phoneFormatter = require("phone-formatter");
const xml2js = require("xml2js");
const moment = require('moment');
const exec = require('child_process').exec;
const PythonShell = require('python-shell');
const path = require("path");
const CALL_TYPE = Object.freeze({
INCOMING: "1",
MISSED: "2",
OUTGOING: "3"
})
// outgoing missed calls are not in the list
module.exports = NodeHelper.create({
// Subclass start method.
start: function () {
this.ownNumbers = []
this.started = false;
//create adressbook dictionary
this.AddressBook = {};
console.log("Starting module: " + this.name);
},
normalizePhoneNumber(number) {
return phoneFormatter.normalize(number.replace(/\s/g, ""));
},
getName: function (number) {
//Normalize number
var number_formatted = this.normalizePhoneNumber(number);
//Check if number is in AdressBook if yes return the name
if (number_formatted in this.AddressBook) {
return this.AddressBook[number_formatted];
} else {
//Not in AdressBook return original number
return number;
}
},
socketNotificationReceived: function (notification, payload) {
//Received config from client
if (notification === "CONFIG") {
//set config to config send by client
this.config = payload;
//if monitor has not been started before (makes sure it does not get started again if the web interface is reloaded)
if (!this.started) {
//set started to true, so it won't start again
this.started = true;
console.log("Received config for " + this.name);
this.parseVcardFile();
this.setupMonitor();
};
//send fresh data to front end (page might have been refreshed)
if (this.config.password !== "") {
this.loadDataFromAPI();
}
}
if (notification === "RELOAD_CALLS") {
this.loadDataFromAPI("--calls-only");
}
if (notification === "RELOAD_CONTACTS") {
this.loadDataFromAPI("--contacts-only");
}
},
setupMonitor: function () {
//helper variable so that the module-this is available inside our callbacks
var self = this;
//Set up CallMonitor with config received from client
var monitor = new CallMonitor(this.config.fritzIP, this.config.fritzPort);
//Incoming call
monitor.on("inbound", function (call) {
//If caller is not empty
if (call.caller != "") {
self.sendSocketNotification("call", self.getName(call.caller));
};
});
monitor.on("outbound", function (call) {
//Save own number (call.caller) to ownNumbers Array to distinguish inbound/outbound on "connected" handler
if (!self.ownNumbers.includes(call.caller))
self.ownNumbers.push(call.caller)
self.sendSocketNotification("outbound", call.called);
});
//Call accepted
monitor.on("connected", function (call) {
if (self.ownNumbers.includes(call.caller))
var name = self.getName(call.called)
else
var name = self.getName(call.caller)
self.sendSocketNotification("connected", name);
});
//Caller disconnected
monitor.on("disconnected", function (call) {
if (call.type === 'outbound')
var name = self.getName(call.called)
else
var name = self.getName(call.caller)
//send clear command to interface
self.sendSocketNotification("disconnected", { "caller": name, "duration": call.duration });
});
console.log(this.name + " is waiting for incoming calls.");
},
parseVcardFile: function () {
var self = this;
if (!this.config.vCard) {
return;
}
vcard.parseVcardFile(self.config.vCard, function (err, data) {
//In case there is an error reading the vcard file
if (err) {
self.sendSocketNotification("error", "vcf_parse_error");
if (self.config.debug) {
console.log("[" + self.name + "] error while parsing vCard " + err);
}
return
}
//For each contact in vcf file
for (var i = 0; i < data.length; i++) {
//For each phone number in contact
for (var a = 0; a < data[i].phone.length; a++) {
//normalize and add to AddressBook
self.AddressBook[self.normalizePhoneNumber(data[i].phone[a].value)] = data[i].fullname;
}
}
self.sendSocketNotification("contacts_loaded", Object.keys(self.AddressBook).length);
});
},
loadCallList: function (body) {
var self = this;
xml2js.parseString(body, function (err, result) {
if (err) {
self.sendSocketNotification("error", "calllist_parse_error");
console.error(self.name + " error while parsing call list: " + err);
return;
}
var callArray = result.root.Call;
var callHistory = []
for (var index in callArray) {
var call = callArray[index];
var type = call.Type[0];
if (type == CALL_TYPE.MISSED || type == CALL_TYPE.INCOMING)
var name = self.getName(call.Caller[0])
else
var name = self.getName(call.Called[0])
if (type == CALL_TYPE.INCOMING && self.config.deviceFilter && self.config.deviceFilter.indexOf(call.Device[0]) > -1) {
continue;
}
var callInfo = { "time": moment(call.Date[0], "DD.MM.YY HH:mm"), "caller": name, "type": type };
if (call.Name[0]) {
callInfo.caller = call.Name[0];
}
callHistory.push(callInfo)
}
self.sendSocketNotification("call_history", callHistory);
});
},
loadPhonebook: function (body) {
var self = this;
xml2js.parseString(body, function (err, result) {
if (err) {
self.sendSocketNotification("error", "phonebook_parse_error");
if (self.config.debug) {
console.error(self.name + " error while parsing phonebook: " + err);
}
return;
}
var contactsArray = result.phonebooks.phonebook[0].contact;
for (var index in contactsArray) {
var contact = contactsArray[index];
var contactNumbers = contact.telephony[0].number;
var contactName = contact.person[0].realName;
for (var index in contactNumbers) {
var currentNumber = self.normalizePhoneNumber(contactNumbers[index]._);
self.AddressBook[currentNumber] = contactName[0];
}
}
self.sendSocketNotification("contacts_loaded", Object.keys(self.AddressBook).length);
});
},
loadDataFromAPI: function (additionalOption) {
var self = this;
if (self.config.debug) {
console.log('Starting access to FRITZ!Box...');
}
var args = ['-i', self.config.fritzIP, '-p', self.config.password];
if (self.config.username !== "") {
args.push('-u');
args.push(self.config.username);
}
if (additionalOption) {
args.push(additionalOption);
}
var options = {
mode: 'json',
scriptPath: path.resolve(__dirname),
args: args
};
var pyshell = new PythonShell('fritz_access.py', options);
pyshell.on('message', function (message) {
if (message.filename.indexOf("calls") !== -1) {
// call list file
self.loadCallList(message.content);
} else {
// phone book file
self.loadPhonebook(message.content);
}
});
// end the input stream and allow the process to exit
pyshell.end(function (error) {
if (error) {
var errorUnknown = true;
if (error.traceback.indexOf("XMLSyntaxError") !== -1) {
// password is probably wrong
self.sendSocketNotification("error", "login_error");
errorUnknown = false;
}
if (error.traceback.indexOf("failed to load external entity") !== -1) {
// probably no network connection
self.sendSocketNotification("error", "network_error");
errorUnknown = false;
}
if (errorUnknown) {
self.sendSocketNotification("error", "unknown_error");
}
if (self.config.debug) {
console.error(self.name + " error while accessing FRITZ!Box: ");
console.error(error.traceback);
}
return;
}
if (self.config.debug) {
console.log('Access to FRITZ!Box finished.');
}
});
}
});