forked from i8beef/node-red-contrib-castv2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcastv2-sender.js
377 lines (344 loc) · 15.2 KB
/
castv2-sender.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
module.exports = function(RED) {
"use strict";
const util = require('util');
const Client = require("castv2-client").Client;
const DefaultMediaReceiver = require("castv2-client").DefaultMediaReceiver;
const Application = require('castv2-client').Application;
const googletts = require("google-tts-api");
function CastV2SenderNode(config) {
RED.nodes.createNode(this, config);
// Settings
this.name = config.name;
this.host = config.host;
let node = this;
// Initialize status
this.status({ fill: "green", shape: "dot", text: "idle" });
/*
* Volume handler
*/
this.onVolumeAsync = function(volume) {
node.context().set("volume", volume);
// Update the node status
node.client.getStatusAsync = util.promisify(node.client.getStatus);
return node.client.getStatusAsync();
};
/*
* Media command handler
*/
this.sendMediaCommandAsync = function(receiver, command) {
receiver.getStatusAsync = util.promisify(receiver.getStatus);
receiver.loadAsync = util.promisify(receiver.load);
receiver.queueLoadAsync = util.promisify(receiver.queueLoad);
receiver.pauseAsync = util.promisify(receiver.pause);
receiver.playAsync = util.promisify(receiver.play);
receiver.seekAsync = util.promisify(receiver.seek);
receiver.stopAsync = util.promisify(receiver.stop);
// Check for load commands
if (command.type === "MEDIA") {
// Load or queue media command
if (command.media) {
if (Array.isArray(command.media)) {
// Queue handling
let mediaOptions = command.mediaOptions || { startIndex: 0, repeatMode: "REPEAT_OFF" };
let queueItems = node.buildQueueItems(command.media);
return receiver.queueLoadAsync(queueItems, mediaOptions);
} else {
// Single media handling
let mediaOptions = command.mediaOptions || { autoplay: true };
return receiver.loadAsync(node.buildMediaObject(command.media), mediaOptions);
}
}
} else if (command.type === "TTS") {
// Text to speech
if (command.text) {
let speed = command.speed || 1;
let language = command.language || "en";
// Get castable URL
return googletts(command.text, language, speed)
.then(url => node.buildMediaObject({ url: url, contentType: "audio/mp3", title: command.metadata && command.metadata.title ? command.metadata.title : "tts" }))
.then(media => receiver.loadAsync(media, { autoplay: true }));
}
} else {
// Initialize media controller by calling getStatus first
return receiver.getStatusAsync()
.then(status => {
// Theres not actually anything playing, exit gracefully
if (!status) throw new Error("not playing");
/*
* Execute media control command
* status.supportedMediaCommands bitmask
* 1 Pause
* 2 Seek
* 4 Stream volume
* 8 Stream mute
* 16 Skip forward
* 32 Skip backward
* 64 Queue Next
* 128 Queue Prev
* 256 Queue Shuffle
* 1024 Queue Repeat All
* 2048 Queue Repeat One
* 3072 Queue Repeat
*/
switch (command.type) {
case "PAUSE":
if (status.supportedMediaCommands & 1) {
return receiver.pauseAsync();
}
break;
case "PLAY":
return receiver.playAsync();
break;
case "SEEK":
if (command.time && status.supportedMediaCommands & 2) {
return receiver.seekAsync(command.time);
}
break;
case "STOP":
return receiver.stopAsync();
break;
default:
throw new Error("Malformed media control command");
break;
}
});
}
};
/*
* Cast command handler
*/
this.sendCastCommandAsync = function(receiver, command) {
node.client.getStatusAsync = util.promisify(node.client.getStatus);
node.client.getVolumeAsync = util.promisify(node.client.getVolume);
node.client.setVolumeAsync = util.promisify(node.client.setVolume);
node.client.stopAsync = util.promisify(node.client.stop);
node.status({ fill: "yellow", shape: "dot", text: "sending" });
// Check for platform commands first
switch (command.type) {
case "CLOSE":
return node.client.stopAsync(receiver);
break;
case "GET_VOLUME":
return node.client.getVolumeAsync(receiver)
.then(volume => node.onVolumeAsync(volume));
break;
case "GET_STATUS":
return node.client.getStatusAsync();
break;
case "MUTE":
return node.client.setVolumeAsync({ muted: true })
.then(volume => node.onVolumeAsync(volume));
break;
case "UNMUTE":
return node.client.setVolumeAsync({ muted: false })
.then(volume => node.onVolumeAsync(volume));
break;
case "VOLUME":
if (command.volume && command.volume >= 0 && command.volume <= 100) {
return node.client.setVolumeAsync({ level: command.volume / 100 })
.then(volume => node.onVolumeAsync(volume));
}
break;
default:
// If media receiver attempt to execute media commands
if (receiver instanceof DefaultMediaReceiver) {
return node.sendMediaCommandAsync(receiver, command);
} else {
// If it got this far just error
throw new Error("Malformed command");
}
break;
}
};
/*
* Cleanup open connections
*/
this.cleanup = function() {
if (node.client) {
try {
node.client.close();
} catch (exception) {
// Swallow close exceptions
}
}
};
/*
* Node-red input handler
*/
this.on("input", function(msg, send, done) {
// For maximum backwards compatibility, check that send exists.
// If this node is installed in Node-RED 0.x, it will need to
// fallback to using `node.send`
send = send || function() { node.send.apply(node, arguments); };
const errorHandler = function(error) {
node.status({ fill: "red", shape: "dot", text: "error" });
node.cleanup();
if (done) {
done(error);
} else {
node.error(error, error.message);
}
};
try {
// Validate incoming message
if (msg.payload == null || typeof msg.payload !== "object") {
msg.payload = { type: "GET_STATUS" };
}
// Setup client
node.client = new Client();
node.client.on("error", errorHandler);
node.client.connectAsync = connectOptions => new Promise(resolve => node.client.connect(connectOptions, resolve));
node.client.getAppAvailabilityAsync = util.promisify(node.client.getAppAvailability);
node.client.getSessionsAsync = util.promisify(node.client.getSessions);
node.client.joinAsync = util.promisify(node.client.join);
node.client.launchAsync = util.promisify(node.client.launch);
let app = DefaultMediaReceiver;
const connectOptions = { host: msg.host || node.host };
node.client.connectAsync(connectOptions)
.then(() => {
node.status({ fill: "green", shape: "dot", text: "connected" });
// Allow for override of app to start / command
if (msg.appId && msg.appId !== "") {
// Build a generic application to pass into castv2 that will only support launch and close
let GenericApplication = function(client, session) { Application.apply(this, arguments); };
util.inherits(GenericApplication, Application);
GenericApplication.APP_ID = msg.appId;
app = GenericApplication;
}
return node.client.getAppAvailabilityAsync(app.APP_ID);
})
.then(availability => {
// Only attempt to use the app if its available
if (!availability || !(app.APP_ID in availability) || availability[app.APP_ID] === false) {
throw new Error("unavailable");
}
return node.client.getSessionsAsync();
})
.then(sessions => {
// Join or launch new session
let activeSession = sessions.find(session => session.appId === app.APP_ID);
if (activeSession) {
return node.client.joinAsync(activeSession, app);
} else {
return node.client.launchAsync(app);
}
})
.then(receiver => {
node.status({ fill: "green", shape: "dot", text: "joined" });
return node.sendCastCommandAsync(receiver, msg.payload);
})
.then(status => {
node.context().set("status", status);
node.status({ fill: "green", shape: "dot", text: "idle" });
node.cleanup();
if (status) send({ payload: status });
if (done) done();
})
.catch(error => errorHandler(error));
} catch (exception) { errorHandler(exception); }
});
/*
* Node-red close handler
*/
this.on('close', function() {
node.cleanup();
});
/*
* Build a media object
*/
this.buildMediaObject = function(media) {
let urlParts = media.url.split("/");
let fileName = urlParts.slice(-1)[0].split("?")[0];
let defaultMetadata = {
metadataType: 0,
title: fileName,
subtitle: null,
images: [
{ url: "https://nodered.org/node-red-icon.png" }
]
};
let metadata = Object.assign({}, defaultMetadata, media.metadata);
return {
contentId : media.url,
contentType: media.contentType || node.getContentType(fileName),
streamType: media.streamType || "BUFFERED",
metadata: metadata,
textTrackStyle: media.textTrackStyle,
tracks: media.tracks
};
};
/*
* Builds a queue item list from passed media arguments
*/
this.buildQueueItems = function(media) {
return media.map((item, index) => {
return {
autoplay: true,
preloadTime: 5,
orderId: index,
activeTrackIds: [],
media: node.buildMediaObject(item)
};
})
};
/*
* Get content type for a URL
*/
this.getContentType = function(fileName) {
const contentTypeMap = {
"3gp": "video/3gpp",
aac: "video/mp4",
aif: "audio/x-aiff",
aiff: "audio/x-aiff",
aifc: "audio/x-aiff",
avi: "video/x-msvideo",
au: "audio/basic",
bmp: "image/bmp",
flv: "video/x-flv",
gif: "image/gif",
ico: "image/x-icon",
jpe: "image/jpeg",
jpeg: "image/jpeg",
jpg: "image/jpeg",
m3u: "audio/x-mpegurl",
m3u8: "application/x-mpegURL",
m4a: "audio/mp4",
mid: "audio/mid",
midi: "audio/mid",
mov: "video/quicktime",
movie: "video/x-sgi-movie",
mpa: "audio/mpeg",
mp2: "audio/x-mpeg",
mp3: "audio/mp3",
mp4: "audio/mp4",
mjpg: "video/x-motion-jpeg",
mjpeg: "video/x-motion-jpeg",
mpe: "video/mpeg",
mpeg: "video/mpeg",
mpg: "video/mpeg",
ogg: "audio/ogg",
ogv: "audio/ogg",
png: "image/png",
qt: "video/quicktime",
ra: "audio/vnd.rn-realaudio",
ram: "audio/x-pn-realaudio",
rmi: "audio/mid",
rpm: "audio/x-pn-realaudio-plugin",
snd: "audio/basic",
stream: "audio/x-qt-stream",
svg: "image/svg",
tif: "image/tiff",
tiff: "image/tiff",
vp8: "video/webm",
wav: "audio/vnd.wav",
webm: "video/webm",
webp: "image/webp",
wmv: "video/x-ms-wmv"
};
let ext = fileName.split(".").slice(-1)[0];
let contentType = contentTypeMap[ext.toLowerCase()];
return contentType || "audio/basic";
};
}
RED.nodes.registerType("castv2-sender", CastV2SenderNode);
}