-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.cs
971 lines (837 loc) · 39.3 KB
/
Server.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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//#define USE_COMPRESSION
#if USE_COMPRESSION
using ICSharpCode.SharpZipLib.Zip;
#endif
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
namespace ConsoleChromeSpeechProxy
{
class Server
{
const string APP_CMD = @"C:\Windows\System32\cmd.exe";
const string APP_CHROME_WIN_32 = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
const string APP_CHROME_WIN_64 = @"C:\Program Files\Google\Chrome\Application\chrome.exe";
const string APP_BASH_MAC = "/bin/bash";
const string APP_CHROME_MAC = @"/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome";
const string KEY_CHROME_SPEECH_PROXY = "CHROME_SPEECH_PROXY";
const string KEY_APP_NAME = "appName";
const string KEY_INSTALL_DIRECTORY = "installDirectory";
const string KEY_PROXY_PORT = "proxyPort";
const string PATH_ROOT = "/";
const string PATH_CROSS_DOMAIN_POLICY = "/crossdomain.xml";
const string PATH_PROXY_DATA = "/ProxyData";
const string PATH_CLOSE_BROWSER_TAB = "/CloseBrowserTab";
const string PATH_CLOSE_PROXY = "/CloseProxy";
const string PATH_OPEN_BROWSER_TAB = "/OpenBrowserTab";
const string PATH_SET_PROXY_PORT = "/SetProxyPort";
const string PATH_SPEECH_DETECTION_START_RECOGNITION = "/SpeechDetectionStartRecognition";
const string PATH_SPEECH_DETECTION_STOP_RECOGNITION = "/SpeechDetectionStopRecognition";
const string PATH_SPEECH_DETECTION_ABORT = "/SpeechDetectionAbort";
const string PATH_SPEECH_DETECTION_INIT = "/SpeechDetectionInit";
const string PATH_SPEECH_DETECTION_GET_LANGUAGES = "/SpeechDetectionGetLanguages";
const string PATH_SPEECH_DETECTION_GET_RESULT = "/SpeechDetectionGetResult";
const string PATH_SPEECH_DETECTION_SET_LANGUAGE = "/SpeechDetectionSetLanguage";
const string PATH_SPEECH_SYNTHESIS_CANCEL = "/SpeechSynthesisCancel";
const string PATH_SPEECH_SYNTHESIS_CONNECT = "/SpeechSynthesisConnect";
const string PATH_SPEECH_SYNTHESIS_CREATE_SPEECH_SYNTHESIS_UTTERANCE = "/SpeechSynthesisCreateSpeechSynthesisUtterance";
const string PATH_SPEECH_SYNTHESIS_GET_VOICES = "/SpeechSynthesisGetVoices";
const string PATH_SPEECH_SYNTHESIS_PROXY_ON_END = "/SpeechSynthesisProxyOnEnd";
const string PATH_SPEECH_SYNTHESIS_PROXY_UTTERANCE = "/SpeechSynthesisProxyUtterance";
const string PATH_SPEECH_SYNTHESIS_PROXY_VOICES = "/SpeechSynthesisProxyVoices";
const string PATH_SPEECH_SYNTHESIS_SET_PITCH = "/SpeechSynthesisSetPitch";
const string PATH_SPEECH_SYNTHESIS_SET_RATE = "/SpeechSynthesisSetRate";
const string PATH_SPEECH_SYNTHESIS_SET_TEXT = "/SpeechSynthesisSetText";
const string PATH_SPEECH_SYNTHESIS_SET_VOICE = "/SpeechSynthesisSetVoice";
const string PATH_SPEECH_SYNTHESIS_SET_VOLUME = "/SpeechSynthesisSetVolume";
const string PATH_SPEECH_SYNTHESIS_SPEAK = "/SpeechSynthesisSpeak";
const string TOKEN_SPEECH_DETECTION_GET_LANGUAGES = "SpeechDetectionGetLanguages:";
const string TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK = "SpeechDetectionGetLanguagesChunk:";
const string TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_FIRST = "SpeechDetectionGetLanguagesChunkFirst:";
const string TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_LAST = "SpeechDetectionGetLanguagesChunkLast:";
const string TOKEN_SPEECH_DETECTION_GET_RESULT = "SpeechDetectionGetResult:";
const string TOKEN_SPEECH_DETECTION_INIT = "SpeechDetectionInit:";
const string TOKEN_SPEECH_DETECTION_ON_END = "SpeechSynthesisOnEnd:";
const string TOKEN_SPEECH_SYNTHESIS_CANCEL = "SpeechSynthesisCancel:";
const string TOKEN_SPEECH_SYNTHESIS_CREATE_SPEECH_SYNTHESIS_UTTERANCE = "SpeechSynthesisCreateSpeechSynthesisUtterance:";
const string TOKEN_SPEECH_SYNTHESIS_GET_VOICES = "SpeechSynthesisGetVoices:";
const string TOKEN_SPEECH_SYNTHESIS_IDLE = "SpeechSynthesisIdle:";
const string TOKEN_SPEECH_SYNTHESIS_SET_PITCH = "SpeechSynthesisSetPitch:";
const string TOKEN_SPEECH_SYNTHESIS_SET_RATE = "SpeechSynthesisSetRate:";
const string TOKEN_SPEECH_SYNTHESIS_SET_TEXT = "SpeechSynthesisSetText:";
const string TOKEN_SPEECH_SYNTHESIS_SPEAK = "SpeechSynthesisSpeak:";
/// <summary>
/// Reference to form
/// </summary>
private IForm _mForm = null;
private bool _mClosing = false;
private HttpListener _mHttpListener = null;
private Thread _mThread = null;
private bool _mWaitForExit = true;
private string _mWebGLSpeechDetectionPluginLanguages = null; //start as null
private List<string> _mWebGLSpeechDetectionPluginResults = new List<string>();
private List<string> _mWebGLSpeechDetectionPluginOnEnd = new List<string>();
private List<string> _mPendingJavaScript = new List<string>();
private StringBuilder _mStringBuilder = new StringBuilder();
private List<int> _mWebGLSpeechSynthesisPluginUtterances = new List<int>();
private List<string> _mWebGLSpeechSynthesisPluginVoices = new List<string>();
private StringBuilder _mGetLanguagesChunks = new StringBuilder();
public Server(IForm form)
{
_mForm = form;
}
private void AppendStatus(string msg, params object[] args)
{
if (_mClosing)
{
return;
}
string text = string.Format(msg, args) + Environment.NewLine;
_mForm.AppendStatusText(text);
}
private void CloseApp()
{
if (_mClosing)
{
return;
}
_mForm.CloseForm();
}
public void CloseChrome()
{
DisconnectChrome();
RunJavaScript("window.close()");
}
public void DetectedChrome()
{
if (!_mClosing)
{
_mForm.SetChromeConnectedText("Chrome: [Connected]");
}
}
private void DetectedUnity()
{
if (_mClosing)
{
return;
}
_mForm.SetUnityConnectedText("Unity: [Connected]");
}
private void DisconnectChrome()
{
if (!_mClosing)
{
_mForm.SetChromeConnectedText("Chrome: [Disonnected]");
}
}
private static string GetAppConfig()
{
string path = Path.Combine(GetAppDataFolder(), "app.config");
return path;
}
private static JObject GetAppConfigJson()
{
SetupAppDataFolder();
string path = GetAppConfig();
JObject json = null;
try
{
if (File.Exists(path))
{
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
using (JsonTextReader jr = new JsonTextReader(sr))
{
json = (JObject)JToken.ReadFrom(jr);
}
}
}
}
}
catch (Exception)
{
}
if (null == json)
{
json = new JObject();
}
return json;
}
private static string GetAppDataFolder()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), KEY_CHROME_SPEECH_PROXY);
return path;
}
private string GetPendingJavaScript()
{
while (_mPendingJavaScript.Count > 0)
{
_mStringBuilder.AppendLine(_mPendingJavaScript[0]);
_mPendingJavaScript.RemoveAt(0);
}
string result = _mStringBuilder.ToString();
if (_mStringBuilder.Length > 0)
{
_mStringBuilder.Remove(0, _mStringBuilder.Length);
}
return result;
}
public static int GetProxyPort()
{
int port = 5000;
JObject json = GetAppConfigJson();
if (json[KEY_PROXY_PORT] != null &&
json[KEY_PROXY_PORT].Type == JTokenType.Integer)
{
port = (int)json[KEY_PROXY_PORT];
Console.WriteLine("Use port: {0}", port);
}
else
{
SetProxyPort(port);
}
return port;
}
/// <summary>
/// Handle requests with messages from the proxy
/// </summary>
/// <param name="request"></param>
private void HandleProxyData(string request)
{
if (string.IsNullOrEmpty(request))
{
return;
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_IDLE))
{
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_FIRST))
{
if (_mGetLanguagesChunks.Length > 0)
{
_mGetLanguagesChunks.Remove(0, _mGetLanguagesChunks.Length);
}
string chunk = request.Substring(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_FIRST.Length);
if (!string.IsNullOrEmpty(chunk))
{
_mGetLanguagesChunks.Append(chunk);
}
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_LAST))
{
string chunk = request.Substring(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK_LAST.Length);
if (!string.IsNullOrEmpty(chunk))
{
_mGetLanguagesChunks.Append(chunk);
string encoded = _mGetLanguagesChunks.ToString();
string decoded = HttpUtility.UrlDecode(encoded);
_mWebGLSpeechDetectionPluginLanguages = decoded;
}
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK))
{
string chunk = request.Substring(TOKEN_SPEECH_DETECTION_GET_LANGUAGES_CHUNK.Length);
if (!string.IsNullOrEmpty(chunk))
{
_mGetLanguagesChunks.Append(chunk);
}
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_GET_LANGUAGES))
{
string jsonData = request.Substring(TOKEN_SPEECH_DETECTION_GET_LANGUAGES.Length);
if (!string.IsNullOrEmpty(jsonData))
{
string decoded = HttpUtility.UrlDecode(jsonData);
_mWebGLSpeechDetectionPluginLanguages = decoded;
}
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_GET_RESULT))
{
string message = request.Substring(TOKEN_SPEECH_DETECTION_GET_RESULT.Length);
string decoded = HttpUtility.UrlDecode(message);
_mWebGLSpeechDetectionPluginResults.Add(decoded);
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_INIT))
{
_mWebGLSpeechDetectionPluginResults.Clear(); //clear previous results
_mWebGLSpeechDetectionPluginOnEnd.Clear(); //clear previous results
RunJavaScript("console.log(\"Init Complete\")");
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_CANCEL))
{
}
else if (request.StartsWith(TOKEN_SPEECH_DETECTION_ON_END))
{
string message = request.Substring(TOKEN_SPEECH_DETECTION_ON_END.Length);
string decoded = HttpUtility.UrlDecode(message);
_mWebGLSpeechDetectionPluginOnEnd.Add(decoded);
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_CREATE_SPEECH_SYNTHESIS_UTTERANCE))
{
string message = request.Substring(TOKEN_SPEECH_SYNTHESIS_CREATE_SPEECH_SYNTHESIS_UTTERANCE.Length);
int index;
if (int.TryParse(message, out index))
{
_mWebGLSpeechSynthesisPluginUtterances.Add(index);
}
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_GET_VOICES))
{
string jsonData = request.Substring(TOKEN_SPEECH_SYNTHESIS_GET_VOICES.Length);
if (!string.IsNullOrEmpty(jsonData))
{
string decoded = HttpUtility.UrlDecode(jsonData);
_mWebGLSpeechSynthesisPluginVoices.Add(decoded);
}
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_SET_PITCH))
{
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_SET_RATE))
{
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_SET_TEXT))
{
}
else if (request.StartsWith(TOKEN_SPEECH_SYNTHESIS_SPEAK))
{
}
}
public bool IsClosing()
{
return _mClosing;
}
public static bool IsMacOS()
{
return Environment.OSVersion.VersionString.ToUpper().StartsWith("UNIX");
}
public void OpenChrome()
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
string uri = string.Format("http://localhost:{0}", GetProxyPort());
Console.WriteLine("Listening: {0}", uri);
if (IsMacOS())
{
string args = string.Format("-c \"{0} {1}\"", APP_CHROME_MAC, uri);
process.StartInfo = new System.Diagnostics.ProcessStartInfo(APP_BASH_MAC,
args);
process.Start();
Console.WriteLine("{0} {1}", APP_BASH_MAC, args);
}
else // Windows
{
if (File.Exists(APP_CHROME_WIN_64))
{
string args = string.Format("/c start \"\" \"{0}\" {1}", APP_CHROME_WIN_64, uri);
process.StartInfo = new System.Diagnostics.ProcessStartInfo(APP_CMD,
args);
process.Start();
}
else if (File.Exists(APP_CHROME_WIN_32))
{
string args = string.Format("/c start \"\" \"{0}\" {1}", APP_CHROME_WIN_32, uri);
process.StartInfo = new System.Diagnostics.ProcessStartInfo(APP_CMD,
args);
process.Start();
}
else
{
Console.Error.WriteLine("Chrome could not be found! Please install!");
}
}
}
private void RestartWorker()
{
SetStatus("Stopping proxy...");
Thread.Sleep(1000);
_mForm.DisplayUIStopProxy();
StopProxy();
Thread.Sleep(3000);
SetPortText();
SetStatus("Starting proxy...");
Thread.Sleep(1000);
_mForm.DisplayUIStartProxy();
StartProxy();
}
private void RunJavaScript(string js)
{
_mPendingJavaScript.Add(js);
}
private static void SaveAppConfigJson(JObject json)
{
string path = GetAppConfig();
try
{
using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
if (json != null)
{
string contents = json.ToString();
sw.Write(contents);
}
sw.Flush();
}
}
}
catch (Exception)
{
Console.Error.WriteLine("Failed to save app config!");
}
}
public static void SetAppName(string appName)
{
SetupAppDataFolder();
JObject json = GetAppConfigJson();
json[KEY_APP_NAME] = appName;
SaveAppConfigJson(json);
}
public void SetClosing()
{
_mClosing = true;
}
public static void SetInstallDirectory(string installDir)
{
SetupAppDataFolder();
JObject json = GetAppConfigJson();
json[KEY_INSTALL_DIRECTORY] = installDir;
SaveAppConfigJson(json);
}
private void SetPortText()
{
string text = Server.GetProxyPort().ToString();
_mForm.SetPortText(text);
}
public static void SetProxyPort(int port)
{
Console.WriteLine("Set port: {0}", port);
SetupAppDataFolder();
JObject json = GetAppConfigJson();
json[KEY_PROXY_PORT] = port;
SaveAppConfigJson(json);
}
private void SetStatus(string msg, params object[] args)
{
if (!_mClosing)
{
_mForm.SetStatusText("Status:");
}
AppendStatus(Environment.NewLine);
AppendStatus(msg, args);
AppendStatus(Environment.NewLine);
}
private static void SetupAppDataFolder()
{
string path = GetAppDataFolder();
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (Exception)
{
}
}
public void StartProxy()
{
SetStatus("Starting Proxy...");
try
{
_mWaitForExit = true;
int port = GetProxyPort();
string uri = string.Format("http://localhost:{0}", port);
Console.WriteLine("Listening: {0}", uri);
_mHttpListener = new HttpListener();
_mHttpListener.Prefixes.Add(string.Format("http://*:{0}/", port));
_mHttpListener.Start();
ThreadStart ts = new ThreadStart(WorkerThread);
_mThread = new Thread(ts);
_mThread.Start();
AppendStatus("Proxy Started!");
}
catch (Exception ex)
{
AppendStatus("Failed to start listener: {0}", ex);
}
}
public void StopProxy()
{
SetStatus("Stopping Proxy...");
_mWaitForExit = false;
try
{
_mHttpListener.Abort();
}
catch (Exception)
{
}
try
{
_mHttpListener.Stop();
}
catch (Exception)
{
}
if (!_mClosing)
{
_mForm.SetChromeConnectedText("Chrome: [Not Connected]");
_mForm.SetUnityConnectedText("Unity: [Not Connected]");
}
AppendStatus("Proxy Stopped!");
}
private void WorkerThread()
{
bool closeApp = false;
// keep listening and send a response
while (_mWaitForExit)
{
if (null != _mHttpListener)
{
HttpListenerContext context = null;
try
{
context = _mHttpListener.GetContext();
string response = "";
if (string.IsNullOrEmpty(context.Request.Url.LocalPath))
{
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_ROOT))
{
_mWebGLSpeechDetectionPluginResults.Clear(); //clear previous results
_mWebGLSpeechDetectionPluginOnEnd.Clear(); //clear previous results
DetectedChrome();
byte[] buffer = null;
try
{
#if USE_COMPRESSION
using (FileStream fs = File.Open("proxy.zip", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var inStream = new ZipInputStream(fs))
{
ZipEntry htmlFile = inStream.GetNextEntry();
if (htmlFile != null)
{
long size = htmlFile.Size;
buffer = new byte[size];
inStream.Read(buffer, 0, buffer.Length);
}
}
}
#else
using (FileStream fs = File.Open("proxy.html", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
string html = sr.ReadToEnd();
buffer = Encoding.UTF8.GetBytes(html);
}
}
#endif
string content = Encoding.UTF8.GetString(buffer);
response = content.Replace("__PROXY_PORT__", GetProxyPort().ToString());
}
catch (Exception)
{
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_CROSS_DOMAIN_POLICY))
{
response = "<cross-domain-policy>" + Environment.NewLine;
response += "<allow-access-from domain=\"*\"/>" + Environment.NewLine;
response += "</cross-domain-policy>" + Environment.NewLine;
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_PROXY_DATA))
{
try
{
DetectedChrome();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string encodedString = parameters["message"];
if (!string.IsNullOrEmpty(encodedString))
{
byte[] data = Convert.FromBase64String(encodedString);
string request = Encoding.UTF8.GetString(data);
HandleProxyData(request);
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
response = GetPendingJavaScript();
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_CLOSE_BROWSER_TAB))
{
DetectedUnity();
CloseChrome();
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_CLOSE_PROXY))
{
closeApp = true; //close app after response is sent
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_OPEN_BROWSER_TAB))
{
DetectedUnity();
_mPendingJavaScript.Clear();
OpenChrome();
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SET_PROXY_PORT))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string strPort = parameters["port"];
int port;
if (int.TryParse(strPort, out port))
{
SetProxyPort(port);
ThreadStart ts = new ThreadStart(RestartWorker);
Thread thread = new Thread(ts);
thread.Start();
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_GET_RESULT))
{
DetectedUnity();
if (_mWebGLSpeechDetectionPluginResults.Count > 0)
{
response = _mWebGLSpeechDetectionPluginResults[0];
_mWebGLSpeechDetectionPluginResults.RemoveAt(0);
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_INIT))
{
_mWebGLSpeechDetectionPluginResults.Clear(); //clear previous results
DetectedUnity();
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_START_RECOGNITION))
{
DetectedUnity();
RunJavaScript("WebGLSpeechDetectionPlugin.Start()");
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_STOP_RECOGNITION))
{
DetectedUnity();
RunJavaScript("WebGLSpeechDetectionPlugin.Stop()");
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_ABORT))
{
_mWebGLSpeechDetectionPluginResults.Clear(); //clear previous results
DetectedUnity();
RunJavaScript("WebGLSpeechDetectionPlugin.Abort()");
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_GET_LANGUAGES))
{
DetectedUnity();
if (null == _mWebGLSpeechDetectionPluginLanguages)
{
RunJavaScript("WebGLSpeechDetectionPlugin.GetLanguages()");
}
else
{
response = _mWebGLSpeechDetectionPluginLanguages;
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_DETECTION_SET_LANGUAGE))
{
_mWebGLSpeechDetectionPluginResults.Clear(); //clear previous results
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string lang = parameters["lang"];
if (null != lang)
{
RunJavaScript(string.Format("WebGLSpeechDetectionPlugin.SetLanguage(\"{0}\")", lang));
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_CANCEL))
{
DetectedUnity();
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.Cancel()"));
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_CONNECT))
{
DetectedUnity();
_mWebGLSpeechSynthesisPluginUtterances.Clear();
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_CREATE_SPEECH_SYNTHESIS_UTTERANCE))
{
DetectedUnity();
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.CreateSpeechSynthesisUtterance()"));
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_GET_VOICES))
{
DetectedUnity();
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.GetVoices()"));
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_PROXY_ON_END))
{
DetectedUnity();
if (_mWebGLSpeechDetectionPluginOnEnd.Count > 0)
{
response = _mWebGLSpeechDetectionPluginOnEnd[0];
_mWebGLSpeechDetectionPluginOnEnd.RemoveAt(0);
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_PROXY_UTTERANCE))
{
DetectedUnity();
if (_mWebGLSpeechSynthesisPluginUtterances.Count > 0)
{
response = _mWebGLSpeechSynthesisPluginUtterances[0].ToString();
_mWebGLSpeechSynthesisPluginUtterances.RemoveAt(0);
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_PROXY_VOICES))
{
DetectedUnity();
if (_mWebGLSpeechSynthesisPluginVoices.Count > 0)
{
response = _mWebGLSpeechSynthesisPluginVoices[0];
_mWebGLSpeechSynthesisPluginVoices.RemoveAt(0);
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SET_PITCH))
{
DetectedUnity();
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtterancePitch(0, 0)"));
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
string strPitch = parameters["pitch"];
float pitch;
if (int.TryParse(utterance, out index) &&
float.TryParse(strPitch, out pitch))
{
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtterancePitch({0}, {1})", index, pitch));
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SET_RATE))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
string strRate = parameters["rate"];
float rate;
if (int.TryParse(utterance, out index) &&
float.TryParse(strRate, out rate))
{
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtteranceRate({0}, {1})", index, rate));
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SET_TEXT))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
if (int.TryParse(utterance, out index))
{
string encoded = parameters["text"];
string text;
if (string.IsNullOrEmpty(encoded))
{
text = string.Empty;
}
else
{
byte[] decodedBytes = Convert.FromBase64String(encoded);
text = UTF8Encoding.UTF8.GetString(decodedBytes);
}
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtteranceText({0}, \"{1}\")", index, text));
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SET_VOICE))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
if (int.TryParse(utterance, out index))
{
string encoded = parameters["voice"];
string voice;
if (string.IsNullOrEmpty(encoded))
{
voice = string.Empty;
}
else
{
byte[] decodedBytes = Convert.FromBase64String(encoded);
voice = UTF8Encoding.UTF8.GetString(decodedBytes);
}
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtteranceVoice({0}, \"{1}\")", index, voice));
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SET_VOLUME))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
if (int.TryParse(utterance, out index))
{
string strVolume = parameters["volume"];
float volume;
if (float.TryParse(strVolume, out volume))
{
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.SetUtteranceVolume({0}, {1})", index, volume));
}
}
}
else if (context.Request.Url.LocalPath.EndsWith(PATH_SPEECH_SYNTHESIS_SPEAK))
{
DetectedUnity();
System.Collections.Specialized.NameValueCollection parameters = HttpUtility.ParseQueryString(context.Request.Url.Query);
string utterance = parameters["utterance"];
int index;
if (int.TryParse(utterance, out index))
{
RunJavaScript(string.Format("WebGLSpeechSynthesisPlugin.Speak({0})", index));
}
}
byte[] bytes = UTF8Encoding.UTF8.GetBytes(response);
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.AddHeader("ContentType", "utf8");
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.OutputStream.Flush();
}
catch (Exception ex)
{
Console.Error.WriteLine("WorkerThread: HTTPListener exception={0}", ex);
}
finally
{
try
{
// close the connection
if (null != context)
{
context.Response.Close();
}
if (closeApp)
{
CloseApp();
}
}
catch (Exception)
{
}
}
}
Thread.Sleep(0);
}
AppendStatus("Worker Exited!");
}
}
}