-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcaller_id.js
469 lines (386 loc) · 11.6 KB
/
caller_id.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
var Freebox = require('node-freeboxos');
var script = require('commander');
var request = require('request');
var doT = require('dot');
var fs = require('fs');
var airtunes = require('airtunes');
var spawn = require('child_process').spawn;
var winston = require('winston');
script.version('0.8.0');
const logger = winston.createLogger({
level: 'info',
format: winston.format.simple(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// This must be set before the require
process.env.NODE_CONFIG_DIR= require('path').resolve(__dirname, 'config');
var config = require('config');
doT.templateSettings.varname = 'call';
var infos = require('path').resolve(__dirname, 'freebox.json');
var smsAPI = 'https://smsapi.free-mobile.fr/sendmsg?';
const DELAY = 1000;
const DEFAULT_TEMPLATE = "Appel Freebox : {{? call.number==''}}Anonyme{{??}}{{=call.number}} ({{=call.name}}){{?}}";
const VOICE_PATH = './voice.wav';
const VOICES_PATH = './voices.wav';
const FREEBOX_SERVER = 'mafreebox.freebox.fr';
const FREEBOX_VOLUME = 100;
const FFMPEG = '/usr/bin/ffmpeg';
const PICO2WAVE = '/usr/bin/pico2wave';
const SOX = '/usr/bin/sox';
var lastCallID = 0;
script.command('init').description("Requests authorization").action( ()=> {
var freeboxConf=fillConfig();
var freebox=new Freebox(freeboxConf);
freebox.waitApplicationGranted(1000*60*2, (error, app) => {
if (error) {
console.error(JSON.stringify(error));
process.exit(0);
}
freebox.saveJSON(infos, (error) => {
if (error) {
console.error(JSON.stringify(error));
process.exit(0);
}
console.log('freebox.json saved with success');
process.exit(0);
});
});
});
script.command('calls').description("Return calls").action( ()=> {
getCalls(function(error, calls) {
if (error && error.canRetry) console.error("Try again, this error should disappear");
if (error) return console.error("error=",error);
console.log(calls);
process.exit(0);
});
});
script.command('lastcall').description("Return last call").action( ()=> {
getCalls(function(error, calls) {
if (error && error.canRetry) console.error("Try again, this error should disappear");
if (error) return console.error("error=",error);
if (calls == null || calls.length == 0) return console.log("No call");
console.log(calls[0]);
process.exit(0);
});
});
script.parse(process.argv);
// Main run, when no parameter passed
if (!script.args.length) run();
function run() {
getCalls(function(error, calls) {
if (error) {
if (!error.canRetry) logger.error(error);
return setTimeout(run, DELAY);
}
if (calls == null || calls.length == 0) return setTimeout(run, DELAY);
// Get last call
var call = calls[0];
// Is the call currently ringing?
if (call.type == 'missed' && call.duration == 0) {
logger.info(JSON.stringify(call));
// If we already notified for this call...
if (lastCallID == call.id) {
logger.info('Already sent');
return setTimeout(run, DELAY);
}
// We don't want to send the same SMS every seconds...
lastCallID = call.id;
sendNotifications(call, function(error) {
if (error) {
logger.error(error); // Just log..
}
return setTimeout(run, DELAY);
});
} else {
return setTimeout(run, DELAY);
}
});
}
function sendNotifications(call, callback) {
logger.info('Sending notifications...');
var remaining=0;
if (config.has('httpget')) {
sendAllHTTPGet(call, config.get('httpget'), done);
remaining++;
}
if (config.has('freemobile')) {
sendAllSMS(call, done);
remaining++;
}
if (config.has('voice2freebox')) {
sendVoice2Freebox(call, config.get('voice2freebox'), done);
remaining++;
}
// No notifications at all configured
if (remaining==0) return callback();
function done(err) {
remaining--;
if (remaining == 0) {
// We're done sending all notifications
logger.info('All notifications sent');
return callback();
}
}
}
function sendAllHTTPGet(call, confs, callback) {
var remaining = 0;
var errors = null;
if (confs) {
var conf;
remaining = confs.length;
logger.info('Sending ' + remaining + ' http get...');
for (var i=0; i< confs.length; i++) {
conf = confs[i];
sendHTTPGet(call, conf, done);
}
} else {
return callback();
}
function sendHTTPGet(call, conf, callback) {
var template = '';
if (!conf.hasOwnProperty('url')) {
return callback(new Error('Parameter url required'));
}
if (conf.hasOwnProperty('template')) {
template = conf['template'];
} else {
template = DEFAULT_TEMPLATE;
}
var data = {
number: call.number,
type: call.type,
id: call.id,
duration: call.duration,
datetime: call.datetime,
contact_id: call.contact_id,
line_id: call.line_id,
name: call.name,
new: call.new
};
var templateFn = doT.template(template);
var url = conf['url'] + encodeURIComponent(templateFn(data));
if (conf.hasOwnProperty('username') && conf.hasOwnProperty('password')) {
request.get(url, {
'auth': {
'user': conf['username'],
'pass': conf['password']
}
}, function (error, response, body) {
if (error) {
callback(error);
}
callback(null);
});
} else {
request.get(url, function(error, response, body) {
if (error) {
callback(error);
}
callback(null);
});
}
}
function done(error) {
if (error) {
errors += error;
logger.error('Error: ' + error);
} else {
logger.info('http get sent');
}
remaining--;
if (remaining == 0) {
// We're done sending all http get
logger.info('All http get sent');
return callback(errors);
}
}
}
function sendVoice2Freebox(call, conf, callback) {
genSound(call.name, conf, function() {
logger.info('Sending voice...');
var ffmpegBin = conf.hasOwnProperty('ffmpeg') ? conf['ffmpeg'] : FFMPEG;
sendSound(VOICES_PATH, ffmpegBin);
return callback();
});
}
function sendAllSMS(call, callback) {
var remaining = 0;
var errors = null;
// Check if config OK
if (config.has('freemobile')) {
var mobile;
remaining = config.get('freemobile').length;
logger.info('Sending ' + remaining + ' SMS...');
for (var i=0; i< config.get('freemobile').length; i++) {
mobile = config.get('freemobile')[i];
sendSMS(call, mobile, done);
}
} else {
return callback();
}
function sendSMS(call, mobile, callback) {
var template = '';
if (mobile.hasOwnProperty('template')) {
template = mobile['template'];
} else {
template = DEFAULT_TEMPLATE;
}
var templateFn = doT.template(template);
if (!(mobile.hasOwnProperty('login') && mobile.hasOwnProperty('pass') )) return setTimeout(run, DELAY);
var data = {
number: call.number,
type: call.type,
id: call.id,
duration: call.duration,
datetime: call.datetime,
contact_id: call.contact_id,
line_id: call.line_id,
name: call.name,
new: call.new
};
request({uri: smsAPI + 'user=' + mobile['login'] + '&pass=' + mobile['pass'] + '&msg=' + encodeURIComponent(templateFn(data))}, function(error, response, body) {
if (error) {
callback(error);
}
callback(null);
});
}
function done(error) {
if (error) {
errors += error;
logger.error('error: ' + error);
} else {
logger.info('SMS sent');
}
remaining--;
if (remaining == 0) {
// We're done sending all SMS
logger.info('All SMS sent');
return callback(errors);
}
}
}
function getCalls(callback) {
var freeboxConf=fillConfig();
freeboxConf.jsonPath = infos;
freeboxConf.jsonAutoSave = true;
var freebox = new Freebox(freeboxConf);
freebox.calls((error, calls) => {
if (error) {
return callback(error,null);
}
return callback(null, calls);
});
}
function genSound(words, conf, callback) {
var pico2waveBin = conf.hasOwnProperty('pico2wave') ? conf['pico2wave'] : PICO2WAVE;
var soxBin = conf.hasOwnProperty('sox') ? conf['sox'] : SOX;
var repeat = conf.hasOwnProperty('repeat') ? conf['repeat'] : 1;
var before = conf.hasOwnProperty('before') ? conf['before'] : null;
var middle = conf.hasOwnProperty('middle') ? conf['middle'] : null;
var after = conf.hasOwnProperty('after') ? conf['after'] : null;
pico2wave(words, 'fr-FR', VOICE_PATH, function() {
sox(VOICE_PATH, VOICES_PATH, repeat || 1, before, middle, after, function() {
callback();
});
});
function pico2wave(text, lang, path, cb) {
var pico2wave = spawn(pico2waveBin, [
'-w', path,
'-l', lang,
text
]);
pico2wave.on('close', (code) => {
cb();
});
pico2wave.stderr.setEncoding('utf8');
pico2wave.stderr.on('data', function(data) {
logger.error(data);
});
}
function sox(input, output, repeat, before, middle, after, cb) {
var parameters = ['-v', '1.2'];
if (before != null) parameters.push(before);
for(var i=0; i < repeat; i++) {
parameters.push(input);
if (middle != null) parameters.push(middle);
}
if (after != null) parameters.push(after);
parameters.push(output);
var sox = spawn(soxBin, parameters);
sox.on('close', (code) => {
cb();
});
sox.stderr.setEncoding('utf8');
sox.stderr.on('data', function(data) {
logger.error(data);
});
}
}
function sendSound(path, ffmpegBin) {
var device = airtunes.add(FREEBOX_SERVER, {volume:FREEBOX_VOLUME});
// when the device is online, spawn ffmpeg to transcode the file
device.on('status', function(status) {
logger.info('status: ' + status);
if(status !== 'ready')
return;
var ffmpeg = spawn(ffmpegBin, [
'-i', path,
'-f', 's16le', // PCM 16bits, little-endian
'-ar', '44100', // Sampling rate
'-ac', 2, // Stereo
'pipe:1' // Output on stdout
]);
// pipe data to AirTunes
ffmpeg.stdout.pipe(airtunes);
// detect if ffmpeg was not spawned correctly
ffmpeg.stderr.setEncoding('utf8');
ffmpeg.stderr.on('data', function(data) {
if(/^execvp\(\)/.test(data)) {
logger.error('failed to start ' + ffmpegBin);
process.exit(1);
}
});
});
// monitor buffer events
airtunes.on('buffer', function(status) {
logger.info('buffer ' + status);
// after the playback ends, give some time to AirTunes devices
if(status === 'end') {
logger.info('playback ended, waiting for AirTunes devices');
setTimeout(function() {
airtunes.stopAll(function() {
logger.info('end');
airtunes.reset();
});
}, 2000);
}
});
}
function fillConfig() {
// Will be shown on the Freebox LCD screen
var app = {
app_id : "callerid",
app_name : "Caller ID",
app_version : "0.8.0",
device_name : "Server"
};
var freeboxConf = {'app': app};
return freeboxConf;
}