/
HandyScriptServer.cs
175 lines (151 loc) · 6.16 KB
/
HandyScriptServer.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
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
namespace ScriptPlayer.Shared.TheHandy
{
public class HandyScriptServer
{
public int ServeScriptPort { get; set; } = 80;
public string LocalIp { get; set; }
public string ScriptHostUrl => $"http://{LocalIp}:{ServeScriptPort}/script/";
public bool HttpServerRunning => _serveScriptThread != null && _serveScriptThread.IsAlive;
public string LoadedScript { get; set; }
private HttpListener _server;
private Thread _serveScriptThread; // thread running the http server hosting the script
private HandyController _controller;
private bool IsScriptLoaded => !string.IsNullOrWhiteSpace(LoadedScript);
public event EventHandler ScriptDownloadFinished;
public HandyScriptServer(HandyController handyController)
{
_controller = handyController;
LocalIp = GetLocalIp();
}
private string GetLocalIp()
{
// TODO: this isn't great but hopefully works for a lot of people?
var host = Dns.GetHostEntry(Dns.GetHostName());
string foundIp = null;
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
foundIp = ip.ToString();
if (foundIp.StartsWith("192"))
return foundIp;
}
}
// return the last found ipv4 address if there is none starting with 192
if (!string.IsNullOrWhiteSpace(foundIp))
return foundIp;
return "failed to find ip";
}
public void Start()
{
if (_serveScriptThread == null || !_serveScriptThread.IsAlive)
{
_serveScriptThread = new Thread(ServeScript);
_serveScriptThread.Start();
}
}
public void Exit()
{
if (_serveScriptThread.IsAlive)
{
try
{
_server.Close();
_serveScriptThread.Abort();
}
catch (Exception) { }
}
}
// host current loaded script on {local-ip}:{ServeScriptPort}/script/
// handy needs to be in the same network for this to work also needs administrator
// aswell as no firewall blocking access / windows firewall is blocking by default ...
private void ServeScript()
{
string prefix = $"http://+:{ServeScriptPort}/script/";
_server = new HttpListener();
_server.Prefixes.Add(prefix);
try
{
_server.Start();
}
catch (HttpListenerException)
{
try
{
// Launch a command prompt as admin and add prefix to URL-ACL for future use
string args = $"/C netsh http add urlacl url=\"{prefix}\" user=\"{Environment.UserName}\"";
ProcessStartInfo info = new ProcessStartInfo("cmd", args)
{
UseShellExecute = true,
Verb = "runas",
WindowStyle = ProcessWindowStyle.Hidden
};
Process.Start(info);
_server = new HttpListener();
_server.Prefixes.Add(prefix);
_server.Start();
}
catch (HttpListenerException ex)
{
// Still can't start?
MessageBox.Show($"Error hosting script: \"{ex.Message}\" (Try as Administrator)", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
Debug.WriteLine("hosting scripts @ " + ScriptHostUrl);
while (true)
{
Debug.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerResponse response;
try
{
HttpListenerContext context = _server.GetContext();
_controller?.OnOsdRequest("Script Download started", TimeSpan.FromSeconds(3), "ScriptServer");
HttpListenerRequest request = context.Request;
response = context.Response;
}
catch (Exception) { break; }
try
{
// Construct a response.
byte[] buffer;
if (IsScriptLoaded)
{
string responseString = LoadedScript;
buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentType = "text/csv";
}
else
{
buffer = Encoding.UTF8.GetBytes("No script loaded.\nLoad a script and refresh to download.\nThe handy will fetch the script the same way.");
response.ContentType = "text/plain";
}
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
_controller?.OnOsdRequest("Script Download finished", TimeSpan.FromSeconds(3), "ScriptServer");
OnScriptDownloadFinished();
}
catch (Exception)
{
_controller?.OnOsdRequest("Script download failed! Handy disconnected during download.", TimeSpan.FromSeconds(3), "ScriptServer");
}
}
_server.Stop();
}
protected virtual void OnScriptDownloadFinished()
{
ScriptDownloadFinished?.Invoke(this, EventArgs.Empty);
}
}
}