-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPlugIn.cs
503 lines (437 loc) · 17.9 KB
/
PlugIn.cs
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
using HomeSeerAPI;
using Hspi.Chromecast;
using Hspi.Exceptions;
using Hspi.Pages;
using Hspi.Utils;
using Hspi.Voice;
using Hspi.Web;
using NullGuard;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.FormattableString;
namespace Hspi
{
/// <summary>
/// Plugin class for Chromecast Speak
/// </summary>
/// <seealso cref="Hspi.HspiBase" />
[NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
internal class Plugin : HspiBase
{
public Plugin()
: base(PluginData.PlugInName)
{
}
public override string InitIO(string port)
{
string result = string.Empty;
try
{
pluginConfig = new PluginConfig(HS);
configPage = new ConfigPage(HS, pluginConfig);
webServerManager = new MediaWebServerManager(ShutdownCancellationToken);
LogInfo("Starting Plugin");
#if DEBUG
pluginConfig.DebugLogging = true;
#endif
pluginConfig.ConfigChanged += PluginConfig_ConfigChanged;
Task.Factory.StartNew(StartWebServer);
RegisterPages();
Callback.RegisterProxySpeakPlug(PluginData.PlugInName, string.Empty);
LogInfo("Plugin Started");
}
catch (Exception ex)
{
result = Invariant($"Failed to initialize PlugIn With {ex.GetFullMessage()}");
LogError(result);
}
return result;
}
private async Task StartWebServer()
{
try
{
var address = pluginConfig.CalculateServerIPAddress();
var port = pluginConfig.WebServerPort;
await webServerManager.StartupServer(address, port).ConfigureAwait(false);
}
catch (Exception ex)
{
LogError(Invariant($"Failed to start Web Server with Error:{ExceptionHelper.GetFullMessage(ex)}"));
}
}
private void PluginConfig_ConfigChanged(object sender, EventArgs e)
{
Task.Factory.StartNew(StartWebServer);
}
public override void LogDebug(string message)
{
if ((pluginConfig != null) && pluginConfig.DebugLogging)
{
base.LogDebug(message);
}
}
public override string GetPagePlugin(string page, [AllowNull]string user, int userRights, [AllowNull]string queryString)
{
if (page == ConfigPage.Name)
{
return configPage.GetWebPage(queryString);
}
return string.Empty;
}
public override string PostBackProc(string page, string data, [AllowNull]string user, int userRights)
{
if (page == ConfigPage.Name)
{
return configPage.PostBackProc(data, user, userRights);
}
return string.Empty;
}
public override void SpeakIn(int deviceId, string text, bool wait, [AllowNull]string host)
{
try
{
host = (host != null) ? host.Trim() : string.Empty;
var hostsList = host.Split(',');
IDictionary<string, ChromecastDevice> selectedDevices = new Dictionary<string, ChromecastDevice>();
var chromecastDevices = pluginConfig.Devices;
foreach (var individualHost in hostsList)
{
var individualHostReal = individualHost.Trim();
if (string.IsNullOrWhiteSpace(host) || individualHostReal == "*" || individualHostReal == "*:*")
{
foreach (var chromecastDevice in chromecastDevices)
{
selectedDevices.Add(chromecastDevice);
}
break;
}
else
{
string name = individualHost.Split(':').FirstOrDefault();
foreach (var chromecastDevice in chromecastDevices)
{
string deviceName = chromecastDevice.Value.Name;
if (string.Compare(name, deviceName, StringComparison.OrdinalIgnoreCase) == 0)
{
selectedDevices.Add(deviceName, chromecastDevice.Value);
}
}
}
}
if (selectedDevices.Count > 0)
{
Task speakTask = Speak(text, selectedDevices.Values);
if (wait)
{
speakTask.Wait(ShutdownCancellationToken);
}
}
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to Speak [{text}] With: {ex.GetFullMessage()}"));
}
if (pluginConfig.ForwardSpeach)
{
HS.SpeakProxy(deviceId, text, wait, host);
}
}
private async Task Speak(string text, IEnumerable<ChromecastDevice> devices)
{
var stopTokenSource = new CancellationTokenSource();
try
{
bool isFileName = IsReferingToFile(text);
VoiceData voiceData;
if (isFileName)
{
voiceData = await VoiceDataFromFile.LoadFromFile(text, ShutdownCancellationToken).ConfigureAwait(false);
}
else
{
var voiceGenerator = new VoiceGenerator(text, pluginConfig.SAPIVoice);
voiceData = await voiceGenerator.GenerateVoiceAsWavFile(ShutdownCancellationToken).ConfigureAwait(false);
}
Trace.WriteLine(Invariant($"Voice for [{text}] is {voiceData.Data.Length} bytes with duration of {voiceData.Duration} of type {voiceData.Extension}"));
if (voiceData.Data.Length == 0)
{
throw new VoiceGenerationException(Invariant($"Data for [{text}] is Zero Bytes. Check Voice Text or File."));
}
var uri = await webServerManager.Add(voiceData.Data, voiceData.Extension, voiceData.Duration).ConfigureAwait(false);
var combinedStopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stopTokenSource.Token, ShutdownCancellationToken);
TimeSpan timeout = MediaWebServerManager.FileEntryExpiry;
if (voiceData.Duration.HasValue)
{
timeout.Add(voiceData.Duration.Value);
}
stopTokenSource.CancelAfter(timeout);
var playTasks = new List<Task>();
foreach (var device in devices)
{
var chromecast = new SimpleChromecast(device, uri, duration: voiceData.Duration, volume: device.Volume);
playTasks.Add(chromecast.Play(true, combinedStopTokenSource.Token));
}
await Task.WhenAll(playTasks.ToArray()).ConfigureAwait(false);
}
catch (TaskCanceledException ex)
{
if (stopTokenSource.IsCancellationRequested)
{
Trace.TraceWarning(Invariant($"Failed to Speak [{text}] With Timeout Error: {ex.GetFullMessage()}"));
}
else
{
Trace.TraceWarning(Invariant($"Failed to Speak [{text}] With: {ex.GetFullMessage()}"));
}
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to Speak [{text}] With: {ex.GetFullMessage()}"));
}
}
private bool IsReferingToFile(string text)
{
switch (HS.GetOSType())
{
case eOSType.windows:
return (text.Length > 2) && text.Substring(1, 2).Equals(":\\");
case eOSType.linux:
return (text.Length > 1) && text.Substring(0, 1).Equals("/");
default:
throw new ArgumentException("Unknown OS Type");
}
}
private void RegisterPages()
{
string configLink = ConfigPage.Name;
HS.RegisterPage(configLink, Name, string.Empty);
HomeSeerAPI.WebPageDesc wpd = new HomeSeerAPI.WebPageDesc()
{
plugInName = Name,
link = configLink,
linktext = "Configuration",
page_title = Invariant($"{PluginData.PlugInName} Configuration"),
};
Callback.RegisterConfigLink(wpd);
Callback.RegisterLink(wpd);
}
#region "Action Override"
private const int ActionChromecastCastTANumber = 1;
public override string ActionBuildUI([AllowNull]string uniqueControlId, IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionChromecastCastTANumber:
using (var actionPage = new ActionPage(HS, pluginConfig))
{
return actionPage.GetRefreshActionUI(uniqueControlId ?? string.Empty, actionInfo);
}
default:
return base.ActionBuildUI(uniqueControlId, actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to give build Action UI with {ex.GetFullMessage()}"));
throw;
}
}
public override bool ActionConfigured(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionChromecastCastTANumber:
if (actionInfo.DataIn != null)
{
var action = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as ChromecastCastAction;
return action != null && action.IsValid();
}
return false;
default:
return base.ActionConfigured(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionConfigured with {ex.GetFullMessage()}"));
return false;
}
}
public override int ActionCount()
{
return 1;
}
public override string ActionFormatUI(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionChromecastCastTANumber:
if (actionInfo.DataIn != null)
{
var action = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as ChromecastCastAction;
if (action != null)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(@"Play ");
stringBuilder.Append(action.Url ?? string.Empty);
stringBuilder.Append(" on ");
if ((action != null) && pluginConfig.Devices.TryGetValue(action.ChromecastDeviceId, out var device))
{
stringBuilder.Append(device.Name);
}
else
{
stringBuilder.Append(@"Unknown");
}
return stringBuilder.ToString();
}
}
return Invariant($"{PluginData.PlugInName} Unknown Chromecast play");
default:
return base.ActionFormatUI(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionFormatUI with {ex.GetFullMessage()}"));
throw;
}
}
public override IPlugInAPI.strMultiReturn ActionProcessPostUI([AllowNull] NameValueCollection postData, IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionChromecastCastTANumber:
using (var actionPage = new ActionPage(HS, pluginConfig))
{
return actionPage.GetRefreshActionPostUI(postData, actionInfo);
}
default:
return base.ActionProcessPostUI(postData, actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionProcessPostUI with {ex.GetFullMessage()}"));
throw;
}
}
public override bool ActionReferencesDevice(IPlugInAPI.strTrigActInfo actionInfo, int deviceId)
{
return false;
}
public override string get_ActionName(int actionNumber)
{
try
{
switch (actionNumber)
{
case ActionChromecastCastTANumber:
return @"Chromecast Cast Action";
default:
return base.get_ActionName(actionNumber);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to give Action Name with {ex.GetFullMessage()}"));
throw;
}
}
public override bool HandleAction(IPlugInAPI.strTrigActInfo actionInfo)
{
using (var stopTokenSource = new CancellationTokenSource())
{
try
{
switch (actionInfo.TANumber)
{
case ActionChromecastCastTANumber:
if (actionInfo.DataIn != null)
{
var action = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as ChromecastCastAction;
if ((action != null) && (action.IsValid()))
{
if (pluginConfig.Devices.TryGetValue(action.ChromecastDeviceId, out var device))
{
using (var combinedStopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(stopTokenSource.Token, ShutdownCancellationToken))
{
stopTokenSource.CancelAfter(60 * 1000);
var chromecast = new SimpleChromecast(device, new System.Uri(action.Url), action.ContentType, action.Live);
chromecast.Play(false, combinedStopTokenSource.Token).Wait();
return true;
}
}
}
}
Trace.TraceWarning(Invariant($"Failed to execute action with invalid action"));
return false;
default:
return base.HandleAction(actionInfo);
}
}
catch (TaskCanceledException ex)
{
if (stopTokenSource.IsCancellationRequested)
{
Trace.TraceWarning(Invariant($"Failed to execute action with timeout Error: {ex.GetFullMessage()}"));
}
else
{
Trace.TraceWarning(Invariant($"Failed to execute action with: {ex.GetFullMessage()}"));
}
return false;
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to execute action with {ex.GetFullMessage()}"));
return false;
}
}
}
#endregion "Action Override"
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!disposedValue)
{
if (pluginConfig != null)
{
pluginConfig.ConfigChanged -= PluginConfig_ConfigChanged;
}
if (configPage != null)
{
configPage.Dispose();
}
if (webServerManager != null)
{
webServerManager.Dispose();
}
disposedValue = true;
}
base.Dispose(disposing);
}
private MediaWebServerManager webServerManager;
private ConfigPage configPage;
private PluginConfig pluginConfig;
private bool disposedValue = false;
}
}