This repository was archived by the owner on Dec 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathHttpServer.cs
More file actions
326 lines (289 loc) · 11.5 KB
/
Copy pathHttpServer.cs
File metadata and controls
326 lines (289 loc) · 11.5 KB
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
using GitHub.Logging;
using GitHub.Unity;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
namespace TestWebServer
{
public class HttpServer
{
private static readonly IDictionary<string, string> mimeTypeMappings =
new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
{ ".gif", "image/gif" },
{ ".html", "text/html" },
{ ".jpg", "image/jpeg" },
{ ".png", "image/png" },
{ ".txt", "text/plain" },
{ ".md5", "text/plain" },
{ ".zip", "application/zip" },
{ ".json", "application/json" },
};
private readonly HttpListener listener;
private readonly string rootDirectory;
private bool abort;
private static ILogging Logger = LogHelper.GetLogger<HttpServer>();
private ManualResetEvent delay = new ManualResetEvent(false);
/// <summary>
/// Construct server with given port.
/// </summary>
/// <param name="path">Directory path to serve.</param>
/// <param name="port">Port of the server.</param>
public HttpServer(string path = null, int port = 0)
{
if (String.IsNullOrEmpty(path) || !Directory.Exists(path))
{
path = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "files");
}
rootDirectory = path;
if (port == 0)
{
//get an empty port
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
}
Port = port;
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:" + port + "/");
}
/// <summary>
/// Stop server and dispose all functions.
/// </summary>
public void Stop()
{
listener.Stop();
}
public void Start()
{
try
{
Logger.Info($"Starting http server on port {Port} serving from {rootDirectory}");
listener.Start();
while (true)
{
try
{
abort = false;
Logger.Info($"Waiting for a request...");
var context = listener.GetContext();
var thread = new Thread(p => Process((HttpListenerContext)p));
thread.Start(context);
}
catch (Exception)
{
break;
}
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
public void Abort()
{
abort = true;
delay.Set();
}
private void Process(HttpListenerContext context)
{
Logger.Info("Handling request {0}", context.Request.Url.AbsolutePath);
if (context.Request.Url.AbsolutePath == "/api/usage/unity")
{
var streamReader = new StreamReader(context.Request.InputStream);
string body = null;
using (streamReader)
{
body = streamReader.ReadToEnd();
}
var parsedJson = JsonConvert.DeserializeObject(body);
var formattedJson = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
Logger.Info(formattedJson);
var json = new { result = "Cool unity usage" }.ToJson();
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentLength64 = json.Length;
string mime;
context.Response.ContentType = mimeTypeMappings.TryGetValue(".json", out mime)
? mime
: "application/octet-stream";
Utils.Copy(new MemoryStream(Encoding.UTF8.GetBytes(json)), context.Response.OutputStream, json.Length);
context.Response.OutputStream.Flush();
context.Response.Close();
return;
}
var filename = context.Request.Url.AbsolutePath;
filename = filename.TrimStart('/');
filename = filename.Replace('/', Path.DirectorySeparatorChar);
filename = Path.Combine(rootDirectory, filename);
if (!File.Exists(filename))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
Logger.Info($"Path not found - Returning 404");
context.Response.Close();
return;
}
try
{
string mime;
context.Response.ContentType = mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime)
? mime
: "application/octet-stream";
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));
using (var input = new FileStream(filename, FileMode.Open))
{
var length = input.Length;
var range = context.Request.Headers["Range"];
if (range == null)
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
}
else
{
var parts = range.Split('-');
var start = long.Parse(parts[0].Substring("bytes=".Length));
var endRange = parts[1];
long end = 0;
if (!string.IsNullOrEmpty(endRange))
{
end = long.Parse(endRange);
}
else
{
end = length - 1;
}
length = end - start + 1;
if (input.CanSeek && (input.Length > start) && (end <= input.Length))
{
context.Response.StatusCode = (int)HttpStatusCode.PartialContent;
context.Response.Headers.Add("Content-Range", $"{start}-{end}/{input.Length}");
input.Seek(start, SeekOrigin.Current);
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
}
}
if (context.Response.StatusCode != (int)HttpStatusCode.RequestedRangeNotSatisfiable)
{
context.Response.ContentLength64 = length;
Logger.Info($"Writing {length} bytes");
delay.Reset();
Utils.Copy(input, context.Response.OutputStream, length,
progress: (total, __) =>
{
if (Delay > 0)
delay.WaitOne(Delay);
if (abort)
Logger.Info($"aborting after {total} bytes");
return !abort;
},
progressUpdateRate: 0
);
context.Response.OutputStream.Flush();
}
}
}
catch (Exception ex)
{
LogHelper.GetLogger<HttpServer>().Error(ex);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
finally
{
try
{
context.Response.Close();
}
catch { }
}
}
public int Delay { get; set; }
public int Port { get; }
}
static class Utils
{
public static bool Copy(Stream source, Stream destination, long totalSize = 0, int chunkSize = 8192,
Func<long, long, bool> progress = null, int progressUpdateRate = 100)
{
var buffer = new byte[chunkSize];
var bytesRead = 0;
long totalRead = 0;
var averageSpeed = -1f;
var lastSpeed = 0f;
var smoothing = 0.005f;
long readLastSecond = 0;
long timeToFinish = 0;
Stopwatch watch = null;
var success = true;
var trackProgress = (totalSize > 0) && (progress != null);
if (trackProgress)
{
watch = new Stopwatch();
}
do
{
if (trackProgress)
{
watch.Start();
}
bytesRead = source.Read(buffer, 0,
totalRead + chunkSize > totalSize ? (int)(totalSize - totalRead) : chunkSize);
if (trackProgress)
{
watch.Stop();
}
totalRead += bytesRead;
if (bytesRead > 0)
{
destination.Write(buffer, 0, bytesRead);
if (trackProgress)
{
readLastSecond += bytesRead;
if ((watch.ElapsedMilliseconds >= progressUpdateRate) || (totalRead == totalSize) ||
(bytesRead == 0))
{
watch.Reset();
if (bytesRead == 0) // we've reached the end
{
totalSize = totalRead;
}
lastSpeed = readLastSecond;
readLastSecond = 0;
averageSpeed = averageSpeed < 0f
? lastSpeed
: smoothing * lastSpeed + (1f - smoothing) * averageSpeed;
timeToFinish = Math.Max(1L,
(long)((totalSize - totalRead) / (averageSpeed / progressUpdateRate)));
success = progress(totalRead, timeToFinish);
if (!success)
{
break;
}
}
}
else // we still need to call the callback if it's there, so we can abort if needed
{
success = progress?.Invoke(totalRead, timeToFinish) ?? true;
if (!success)
{
break;
}
}
}
} while ((bytesRead > 0) && ((totalSize == 0) || (totalSize > totalRead)));
if (totalRead > 0)
{
destination.Flush();
}
return success;
}
}
}