forked from noelportugal/google-home-notifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-home-notifier.js
110 lines (99 loc) · 2.73 KB
/
google-home-notifier.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
var Client = require('castv2-client').Client;
var DefaultMediaReceiver = require('castv2-client').DefaultMediaReceiver;
var mdns = require('mdns');
var browser = mdns.createBrowser(mdns.tcp('googlecast'));
var deviceAddress;
var language;
var device = function(name, lang = 'en') {
device = name;
language = lang;
return this;
};
var ip = function(ip) {
deviceAddress = ip;
return this;
}
var googletts = require('google-tts-api');
var googlettsaccent = 'us';
var accent = function(accent) {
googlettsaccent = accent;
return this;
}
var notify = function(message, callback) {
if (!deviceAddress){
browser.start();
browser.on('serviceUp', function(service) {
console.log('Device "%s" at %s:%d', service.name, service.addresses[0], service.port);
if (service.name.includes(device.replace(' ', '-'))){
deviceAddress = service.addresses[0];
getSpeechUrl(message, deviceAddress, function(res) {
callback(res);
});
}
browser.stop();
});
}else {
getSpeechUrl(message, deviceAddress, function(res) {
callback(res);
});
}
};
var play = function(mp3_url, callback) {
if (!deviceAddress){
browser.start();
browser.on('serviceUp', function(service) {
console.log('Device "%s" at %s:%d', service.name, service.addresses[0], service.port);
if (service.name.includes(device.replace(' ', '-'))){
deviceAddress = service.addresses[0];
getPlayUrl(mp3_url, deviceAddress, function(res) {
callback(res);
});
}
browser.stop();
});
}else {
getPlayUrl(mp3_url, deviceAddress, function(res) {
callback(res);
});
}
};
var getSpeechUrl = function(text, host, callback) {
googletts(text, language, 1, 1000, googlettsaccent).then(function (url) {
onDeviceUp(host, url, function(res){
callback(res)
});
}).catch(function (err) {
console.error(err.stack);
});
};
var getPlayUrl = function(url, host, callback) {
onDeviceUp(host, url, function(res){
callback(res)
});
};
var onDeviceUp = function(host, url, callback) {
var client = new Client();
client.connect(host, function() {
client.launch(DefaultMediaReceiver, function(err, player) {
var media = {
contentId: url,
contentType: 'audio/mp3',
streamType: 'BUFFERED' // or LIVE
};
player.load(media, { autoplay: true }, function(err, status) {
client.close();
callback('Device notified');
});
});
});
client.on('error', function(err) {
console.log('Error: %s', err.message);
client.close();
callback('error');
});
};
exports.ip = ip;
exports.device = device;
exports.accent = accent;
exports.notify = notify;
exports.play = play;