forked from greghesp/assistant-relay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
251 lines (213 loc) · 6.87 KB
/
index.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
'use strict'
const SSDP = require('node-ssdp').Server;
const path = require('path');
const express = require('express');
const GoogleAssistant = require('google-assistant');
const GRConfig = require('./config.json');
const async = require('async');
const ip = require('ip')
//Define SSDP Server Configuration
const ssdpServer = new SSDP({
location: 'http://' + require('ip').address() + ':3000/desc.xml',
sourcePort: 1900,
ssdpTtl: 3,
});
const authKeys = GRConfig.users;
const config = {
conversation: {
lang: GRConfig.language,
},
users: {},
assistants: {},
port: GRConfig.port
}
const defaultAudio = false;
let returnAudio;
let assistant;
if(Object.keys(authKeys).length === 0){
return console.log('No users configured, exiting..');
}
Object.keys(authKeys).forEach(function(k){
config.users[k] = {};
config.users[k].keyFilePath = authKeys[k].keyFilePath;
config.users[k].savedTokensPath = authKeys[k].savedTokensPath;
})
//Define SSDP USN type
ssdpServer.addUSN('urn:greghesp-com:device:GAssist:1');
const app = express()
app.use(express.static(path.join(__dirname, 'xml')));
app.use(express.static(path.join(__dirname, 'audio')));
//Start SSDP Server
ssdpServer.start(function(){
console.log('Fired up the SSDP Server for network discovery...')
});
// Endpoint API
app.post('/custom', function (req, res) {
const converse = req.query.converse;
const command = req.query.command;
const user = req.query.user;
//Check the converse parameter
if(converse) returnAudio = true;
sendTextInput(command, user)
res.status(200).json({
message: `Custom command executed`,
command: `${command}`
});
})
app.get('/customBroadcast', function (req, res) {
const command = req.query.text;
const user = req.query.user;
sendTextInput(`broadcast ${command}`, user);
res.status(200).json({
message: `Custom broadcast command executed`,
command: `broadcast ${command}`
});
})
app.post('/nestStream', function (req, res) {
if(req.query.converse) returnAudio = true;
if(req.query.stop) {
sendTextInput(`Stop ${req.query.chromecast}`);
return res.status(200).json({
message: `Nest stream command executed`,
command: `Stop ${req.query.chromecast}`
});
}
sendTextInput(`Show ${req.query.camera} on ${req.query.chromecast}`, req.query.user)
res.status(200).json({
message: `Nest stream command executed`,
command: `Show ${req.query.camera} on ${req.query.chromecast}`
});
})
app.post('/broadcast', function (req, res) {
const preset = req.query.preset;
const user = req.query.user;
if(req.query.converse) returnAudio = true;
switch(preset) {
case 'wakeup':
sendTextInput(`broadcast wake up everyone`, user);
break;
case 'breakfast':
sendTextInput(`broadcast breakfast is ready`, user);
break;
case 'lunch':
sendTextInput(`broadcast it's lunch time`, user);
break;
case 'dinner':
sendTextInput('broadcast dinner is served', user);
break;
case 'timetoleave':
sendTextInput(`broadcast its time to leave`, user);
break;
case 'arrivedhome':
sendTextInput(`broadcast i'm home`, user);
break;
case 'ontheway':
sendTextInput(`broadcast i'm on the way`, user);
break;
case 'movietime':
sendTextInput(`broadcast the movie is about to start`, user);
break;
case 'tvtime':
sendTextInput(`broadcast the show is about to start`, user);
break;
case 'bedtime':
sendTextInput(`broadcast we should go to bed`, user);
break;
default:
sendTextInput(`broadcast you selected a preset broadcast, but didn't say which one`, user);
}
res.status(200).json({
message: `Predefined command executed`,
command: `${req.query.preset}`
});
})
//Start Express Web Server
app.listen(config.port, () => console.log(`Firing up the Web Server for communication on address ${ip.address()}:${config.port}`))
let users;
let numberUsers = Object.keys(config.users).length;
if( numberUsers > 1){
Object.keys(config.users).forEach(function(i, idx, array){
if(idx === 0){
return users = `${i} `
}
if (idx === array.length - 1){
return users = users + `and ${i}`
} else {
users = users + `${i} `
}
})
} else {
Object.keys(config.users).forEach(i => {
users = i
})
}
async.forEachOfLimit(config.users, 1, function(i, k, cb){
let auth = i;
config.assistants[k] = new GoogleAssistant(i)
let assistant = config.assistants[k];
assistant.on('ready', () => cb());
assistant.on('error', (e) => {
console.log(`Assistant Error when activating user ${k}. Trying next user`);
return cb();
})
}, function(err){
if(err) return console.log(err.message);
console.log(`Assistant Relay is now setup and running for ${users}`)
//sendTextInput(`broadcast Assistant Relay is now setup and running for ${users}`)
})
function checkUser(user) {
const users = Object.keys(GRConfig.users);
return users.includes(user.toLowerCase());
}
//Assistant Integration
function startConversation(conversation) {
conversation
//.on('audio-data', data => console.log('Got some audio data'))
.on('response', (text) => {
if (text) {
console.log('Google Assistant:', text)
var newLineSplit = text.split("\n")
// Ignore lines if Assistant responds with extra interactive data (such as a "See More" web URL)
if (newLineSplit.length > 1) text = newLineSplit[0]
if(returnAudio) {
//console.log(`sendTextInput ${text}`)
sendTextInput(`broadcast ${text}`);
returnAudio = false;
}
}
})
//.on('volume-percent', percent => console.log('New Volume Percent:', percent))
//.on('device-action', action => console.log('Device Action:', action))
.on('ended', (error, continueConversation) => {
if (error) {
console.log('Conversation Ended Error:', error);
} else if (continueConversation) {
//console.log('Support for Actions on Google are not yet supported by Assistant Relay');
conversation.end();
} else {
//console.log('Conversation Complete');
conversation.end();
}
})
.on('error', (error) => {
console.log('Conversation Error:', error);
});
}
function sendTextInput(text, n) {
console.log(`Received command ${text}`);
assistant = Object.keys(config.assistants)[0];
assistant = config.assistants[`${assistant}`];
config.conversation.textQuery = text;
if(n) {
if(!checkUser(n)) {
console.log(`User not found, using ${Object.keys(config.assistants)[0]}`)
} else {
n = n.toLowerCase();
console.log(`User specified was ${n}`)
assistant = config.assistants[`${n}`]
}
} else {
console.log(`No user specified, using ${Object.keys(config.assistants)[0]}`)
}
assistant.start(config.conversation, startConversation);
}