2017-06-14 01:37:03 +00:00
|
|
|
using System;
|
2017-06-15 07:40:08 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
2017-06-27 01:48:57 +00:00
|
|
|
using System.Linq;
|
2017-06-15 07:40:08 +00:00
|
|
|
using System.Text;
|
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using System.Net;
|
2018-03-09 20:56:32 +00:00
|
|
|
|
|
|
|
#if !PCL
|
2017-06-15 07:40:08 +00:00
|
|
|
using System.Net.WebSockets;
|
2018-03-09 20:56:32 +00:00
|
|
|
#endif
|
2017-06-14 01:37:03 +00:00
|
|
|
|
|
|
|
namespace Ooui
|
|
|
|
{
|
|
|
|
public static class UI
|
|
|
|
{
|
2018-03-09 20:56:32 +00:00
|
|
|
#if !PCL
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
static readonly ManualResetEvent started = new ManualResetEvent (false);
|
|
|
|
|
2017-12-10 01:02:04 +00:00
|
|
|
[ThreadStatic]
|
|
|
|
static System.Security.Cryptography.SHA256 sha256;
|
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
static CancellationTokenSource serverCts;
|
|
|
|
|
2017-07-06 23:01:21 +00:00
|
|
|
static readonly Dictionary<string, RequestHandler> publishedPaths =
|
|
|
|
new Dictionary<string, RequestHandler> ();
|
2017-06-15 07:40:08 +00:00
|
|
|
|
|
|
|
static readonly byte[] clientJsBytes;
|
2017-12-10 01:02:04 +00:00
|
|
|
static readonly string clientJsEtag;
|
2017-06-15 07:40:08 +00:00
|
|
|
|
2017-11-10 05:00:15 +00:00
|
|
|
public static byte[] ClientJsBytes => clientJsBytes;
|
2017-12-10 01:02:04 +00:00
|
|
|
public static string ClientJsEtag => clientJsEtag;
|
2017-11-10 05:00:15 +00:00
|
|
|
|
2018-02-22 00:32:12 +00:00
|
|
|
public static string HeadHtml { get; set; } = @"<link rel=""stylesheet"" href=""https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"" />";
|
|
|
|
public static string BodyHeaderHtml { get; set; } = @"";
|
|
|
|
public static string BodyFooterHtml { get; set; } = @"";
|
2017-06-19 02:12:37 +00:00
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
static string host = "*";
|
|
|
|
public static string Host {
|
|
|
|
get => host;
|
|
|
|
set {
|
|
|
|
if (!string.IsNullOrWhiteSpace (value) && host != value) {
|
|
|
|
host = value;
|
|
|
|
Restart ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
static int port = 8080;
|
|
|
|
public static int Port {
|
|
|
|
get => port;
|
|
|
|
set {
|
|
|
|
if (port != value) {
|
|
|
|
port = value;
|
|
|
|
Restart ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-12-11 01:51:05 +00:00
|
|
|
static bool serverEnabled = true;
|
|
|
|
public static bool ServerEnabled {
|
|
|
|
get => serverEnabled;
|
|
|
|
set {
|
|
|
|
if (serverEnabled != value) {
|
|
|
|
serverEnabled = value;
|
|
|
|
if (serverEnabled)
|
|
|
|
Restart ();
|
|
|
|
else
|
|
|
|
Stop ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-06-15 07:40:08 +00:00
|
|
|
|
|
|
|
static UI ()
|
|
|
|
{
|
|
|
|
var asm = typeof(UI).Assembly;
|
|
|
|
// System.Console.WriteLine("ASM = {0}", asm);
|
|
|
|
// foreach (var n in asm.GetManifestResourceNames()) {
|
|
|
|
// System.Console.WriteLine(" {0}", n);
|
|
|
|
// }
|
|
|
|
using (var s = asm.GetManifestResourceStream ("Ooui.Client.js")) {
|
2017-07-07 19:51:00 +00:00
|
|
|
if (s == null)
|
|
|
|
throw new Exception ("Missing Client.js");
|
2017-06-15 07:40:08 +00:00
|
|
|
using (var r = new StreamReader (s)) {
|
|
|
|
clientJsBytes = Encoding.UTF8.GetBytes (r.ReadToEnd ());
|
|
|
|
}
|
|
|
|
}
|
2017-12-10 01:02:04 +00:00
|
|
|
clientJsEtag = "\"" + Hash (clientJsBytes) + "\"";
|
|
|
|
}
|
|
|
|
|
2017-12-11 01:51:05 +00:00
|
|
|
public static string Hash (byte[] bytes)
|
2017-12-10 01:02:04 +00:00
|
|
|
{
|
|
|
|
var sha = sha256;
|
|
|
|
if (sha == null) {
|
|
|
|
sha = System.Security.Cryptography.SHA256.Create ();
|
|
|
|
sha256 = sha;
|
|
|
|
}
|
|
|
|
var data = sha.ComputeHash (bytes);
|
|
|
|
StringBuilder sBuilder = new StringBuilder ();
|
|
|
|
for (int i = 0; i < data.Length; i++) {
|
|
|
|
sBuilder.Append (data[i].ToString ("x2"));
|
|
|
|
}
|
|
|
|
return sBuilder.ToString ();
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
static void Publish (string path, RequestHandler handler)
|
2017-06-15 07:40:08 +00:00
|
|
|
{
|
2017-07-08 02:38:04 +00:00
|
|
|
Console.WriteLine ($"PUBLISH {path} {handler}");
|
2017-07-06 23:01:21 +00:00
|
|
|
lock (publishedPaths) publishedPaths[path] = handler;
|
2017-06-15 07:40:08 +00:00
|
|
|
Start ();
|
|
|
|
}
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
public static void Publish (string path, Func<Element> elementCtor)
|
|
|
|
{
|
|
|
|
Publish (path, new ElementHandler (elementCtor));
|
|
|
|
}
|
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
public static void Publish (string path, Element element)
|
|
|
|
{
|
|
|
|
Publish (path, () => element);
|
|
|
|
}
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
public static void PublishFile (string filePath)
|
|
|
|
{
|
|
|
|
var path = "/" + System.IO.Path.GetFileName (filePath);
|
|
|
|
PublishFile (path, filePath);
|
|
|
|
}
|
|
|
|
|
2017-07-08 03:27:03 +00:00
|
|
|
public static void PublishFile (string path, string filePath, string contentType = null)
|
2017-07-08 02:38:04 +00:00
|
|
|
{
|
|
|
|
var data = System.IO.File.ReadAllBytes (filePath);
|
|
|
|
if (contentType == null) {
|
|
|
|
contentType = GuessContentType (path, filePath);
|
|
|
|
}
|
2017-12-11 01:51:05 +00:00
|
|
|
var etag = "\"" + Hash (data) + "\"";
|
|
|
|
Publish (path, new DataHandler (data, etag, contentType));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void PublishFile (string path, byte[] data, string contentType)
|
|
|
|
{
|
|
|
|
var etag = "\"" + Hash (data) + "\"";
|
|
|
|
Publish (path, new DataHandler (data, etag, contentType));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void PublishFile (string path, byte[] data, string etag, string contentType)
|
|
|
|
{
|
|
|
|
Publish (path, new DataHandler (data, etag, contentType));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static bool TryGetFileContentAtPath (string path, out FileContent file)
|
|
|
|
{
|
|
|
|
RequestHandler handler;
|
|
|
|
lock (publishedPaths) {
|
|
|
|
if (!publishedPaths.TryGetValue (path, out handler)) {
|
|
|
|
file = null;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (handler is DataHandler dh) {
|
|
|
|
file = new FileContent {
|
|
|
|
Etag = dh.Etag,
|
|
|
|
Content = dh.Data,
|
|
|
|
ContentType = dh.ContentType,
|
|
|
|
};
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
file = null;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
public class FileContent
|
|
|
|
{
|
|
|
|
public string ContentType { get; set; }
|
|
|
|
public string Etag { get; set; }
|
|
|
|
public byte[] Content { get; set; }
|
2017-07-08 03:27:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static void PublishJson (string path, Func<object> ctor)
|
|
|
|
{
|
|
|
|
Publish (path, new JsonHandler (ctor));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void PublishJson (string path, object value)
|
|
|
|
{
|
|
|
|
var data = JsonHandler.GetData (value);
|
2017-12-11 01:51:05 +00:00
|
|
|
var etag = "\"" + Hash (data) + "\"";
|
|
|
|
Publish (path, new DataHandler (data, etag, JsonHandler.ContentType));
|
2017-07-08 02:38:04 +00:00
|
|
|
}
|
|
|
|
|
2017-08-23 03:26:01 +00:00
|
|
|
public static void PublishCustomResponse (string path, Action<HttpListenerContext, CancellationToken> responder)
|
|
|
|
{
|
|
|
|
Publish (path, new CustomHandler (responder));
|
|
|
|
}
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
static string GuessContentType (string path, string filePath)
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2017-07-06 22:39:44 +00:00
|
|
|
public static void Present (string path, object presenter = null)
|
|
|
|
{
|
2017-07-08 02:38:04 +00:00
|
|
|
WaitUntilStarted ();
|
|
|
|
var url = GetUrl (path);
|
2017-07-06 22:39:44 +00:00
|
|
|
Console.WriteLine ($"PRESENT {url}");
|
2017-07-07 23:58:38 +00:00
|
|
|
Platform.OpenBrowser (url, presenter);
|
|
|
|
}
|
2017-07-06 22:39:44 +00:00
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
public static string GetUrl (string path)
|
|
|
|
{
|
|
|
|
var localhost = host == "*" ? "localhost" : host;
|
|
|
|
var url = $"http://{localhost}:{port}{path}";
|
|
|
|
return url;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void WaitUntilStarted () => started.WaitOne ();
|
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
static void Start ()
|
2017-06-14 01:37:03 +00:00
|
|
|
{
|
2017-12-11 01:51:05 +00:00
|
|
|
if (!serverEnabled) return;
|
2017-06-15 07:40:08 +00:00
|
|
|
if (serverCts != null) return;
|
|
|
|
serverCts = new CancellationTokenSource ();
|
|
|
|
var token = serverCts.Token;
|
|
|
|
var listenerPrefix = $"http://{host}:{port}/";
|
|
|
|
Task.Run (() => RunAsync (listenerPrefix, token), token);
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
static void Stop ()
|
|
|
|
{
|
|
|
|
var scts = serverCts;
|
|
|
|
if (scts == null) return;
|
|
|
|
serverCts = null;
|
2017-07-08 02:38:04 +00:00
|
|
|
started.Reset ();
|
2017-06-15 07:40:08 +00:00
|
|
|
|
|
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
|
|
Console.WriteLine ($"Stopping...");
|
|
|
|
Console.ResetColor ();
|
2017-06-15 07:58:55 +00:00
|
|
|
|
2017-06-15 07:40:08 +00:00
|
|
|
scts.Cancel ();
|
|
|
|
}
|
|
|
|
|
|
|
|
static void Restart ()
|
|
|
|
{
|
|
|
|
if (serverCts == null) return;
|
|
|
|
Stop ();
|
|
|
|
Start ();
|
|
|
|
}
|
|
|
|
|
|
|
|
static async Task RunAsync (string listenerPrefix, CancellationToken token)
|
|
|
|
{
|
|
|
|
HttpListener listener = null;
|
2017-07-08 05:54:43 +00:00
|
|
|
var wait = 5;
|
2017-06-15 07:40:08 +00:00
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
started.Reset ();
|
|
|
|
while (!started.WaitOne(0) && !token.IsCancellationRequested) {
|
2017-06-15 07:40:08 +00:00
|
|
|
try {
|
|
|
|
listener = new HttpListener ();
|
|
|
|
listener.Prefixes.Add (listenerPrefix);
|
|
|
|
listener.Start ();
|
2017-07-08 02:38:04 +00:00
|
|
|
started.Set ();
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
2017-07-08 05:54:43 +00:00
|
|
|
catch (System.Net.Sockets.SocketException ex) {
|
|
|
|
Console.WriteLine ($"{listenerPrefix} error: {ex.Message}. Trying again in {wait} seconds...");
|
2017-06-16 00:23:07 +00:00
|
|
|
await Task.Delay (wait * 1000).ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
2017-07-08 05:54:43 +00:00
|
|
|
catch (System.Net.HttpListenerException ex) {
|
|
|
|
Console.WriteLine ($"{listenerPrefix} error: {ex.Message}. Trying again in {wait} seconds...");
|
|
|
|
await Task.Delay (wait * 1000).ConfigureAwait (false);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
Error ("Error listening", ex);
|
|
|
|
return;
|
|
|
|
}
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
|
|
Console.WriteLine ($"Listening at {listenerPrefix}...");
|
|
|
|
Console.ResetColor ();
|
|
|
|
|
|
|
|
while (!token.IsCancellationRequested) {
|
2017-06-16 00:23:07 +00:00
|
|
|
var listenerContext = await listener.GetContextAsync ().ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
if (listenerContext.Request.IsWebSocketRequest) {
|
|
|
|
ProcessWebSocketRequest (listenerContext, token);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
ProcessRequest (listenerContext, token);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void ProcessRequest (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
|
|
|
|
Console.WriteLine ($"{listenerContext.Request.HttpMethod} {url.LocalPath}");
|
|
|
|
|
|
|
|
var response = listenerContext.Response;
|
|
|
|
|
2017-06-19 02:12:37 +00:00
|
|
|
if (path == "/ooui.js") {
|
2017-12-10 01:02:04 +00:00
|
|
|
var inm = listenerContext.Request.Headers.Get ("If-None-Match");
|
|
|
|
if (string.IsNullOrEmpty (inm) || inm != clientJsEtag) {
|
|
|
|
response.StatusCode = 200;
|
|
|
|
response.ContentLength64 = clientJsBytes.LongLength;
|
|
|
|
response.ContentType = "application/javascript";
|
|
|
|
response.ContentEncoding = Encoding.UTF8;
|
|
|
|
response.AddHeader ("Cache-Control", "public, max-age=60");
|
|
|
|
response.AddHeader ("Etag", clientJsEtag);
|
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (clientJsBytes, 0, clientJsBytes.Length);
|
|
|
|
}
|
|
|
|
response.Close ();
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
response.StatusCode = 304;
|
|
|
|
response.Close ();
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2017-06-16 00:35:20 +00:00
|
|
|
var found = false;
|
2017-07-06 23:01:21 +00:00
|
|
|
RequestHandler handler;
|
|
|
|
lock (publishedPaths) found = publishedPaths.TryGetValue (path, out handler);
|
2017-06-16 00:35:20 +00:00
|
|
|
if (found) {
|
2017-07-06 23:01:21 +00:00
|
|
|
try {
|
|
|
|
handler.Respond (listenerContext, token);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
2017-07-06 23:12:34 +00:00
|
|
|
Error ("Handler failed to respond", ex);
|
2017-07-06 23:01:21 +00:00
|
|
|
try {
|
|
|
|
response.StatusCode = 500;
|
|
|
|
response.Close ();
|
|
|
|
}
|
|
|
|
catch {
|
|
|
|
// Ignore ending the response errors
|
|
|
|
}
|
|
|
|
}
|
2017-06-16 00:35:20 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
response.StatusCode = 404;
|
|
|
|
response.Close ();
|
|
|
|
}
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-06 23:01:21 +00:00
|
|
|
abstract class RequestHandler
|
2017-06-19 02:12:37 +00:00
|
|
|
{
|
2017-07-06 23:01:21 +00:00
|
|
|
public abstract void Respond (HttpListenerContext listenerContext, CancellationToken token);
|
2017-06-19 02:12:37 +00:00
|
|
|
}
|
|
|
|
|
2017-07-06 23:01:21 +00:00
|
|
|
class ElementHandler : RequestHandler
|
2017-06-15 07:40:08 +00:00
|
|
|
{
|
2017-07-06 23:01:21 +00:00
|
|
|
readonly Lazy<Element> element;
|
|
|
|
|
|
|
|
public ElementHandler (Func<Element> ctor)
|
|
|
|
{
|
|
|
|
element = new Lazy<Element> (ctor);
|
|
|
|
}
|
|
|
|
|
|
|
|
public Element GetElement () => element.Value;
|
|
|
|
|
|
|
|
public override void Respond (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
var response = listenerContext.Response;
|
|
|
|
|
|
|
|
response.StatusCode = 200;
|
|
|
|
response.ContentType = "text/html";
|
|
|
|
response.ContentEncoding = Encoding.UTF8;
|
|
|
|
var html = Encoding.UTF8.GetBytes (RenderTemplate (path));
|
|
|
|
response.ContentLength64 = html.LongLength;
|
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (html, 0, html.Length);
|
|
|
|
}
|
|
|
|
response.Close ();
|
|
|
|
}
|
2017-11-10 03:34:37 +00:00
|
|
|
}
|
2017-07-06 23:01:21 +00:00
|
|
|
|
2018-02-02 04:18:16 +00:00
|
|
|
public static string RenderTemplate (string webSocketPath, string title = "", string initialHtml = "")
|
2017-11-10 03:34:37 +00:00
|
|
|
{
|
2018-02-22 00:32:12 +00:00
|
|
|
using (var w = new System.IO.StringWriter ()) {
|
|
|
|
RenderTemplate (w, webSocketPath, title, initialHtml);
|
|
|
|
return w.ToString ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void RenderTemplate (TextWriter writer, string webSocketPath, string title, string initialHtml)
|
|
|
|
{
|
|
|
|
writer.Write (@"<!DOCTYPE html>
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<title>");
|
|
|
|
writer.Write (title.Replace ("&", "&").Replace ("<", "<"));
|
|
|
|
writer.Write (@"</title>
|
|
|
|
<meta name=""viewport"" content=""width=device-width, initial-scale=1"" />
|
|
|
|
");
|
|
|
|
writer.WriteLine (HeadHtml);
|
|
|
|
writer.WriteLine (@" <style>");
|
|
|
|
writer.WriteLine (rules.ToString ());
|
|
|
|
writer.WriteLine (@" </style>
|
|
|
|
</head>
|
|
|
|
<body>");
|
|
|
|
writer.WriteLine (BodyHeaderHtml);
|
|
|
|
writer.WriteLine (@"<div id=""ooui-body"" class=""container-fluid"">");
|
|
|
|
writer.WriteLine (initialHtml);
|
|
|
|
writer.Write (@"</div>
|
|
|
|
|
|
|
|
<script src=""/ooui.js""></script>
|
|
|
|
<script>ooui(""");
|
|
|
|
writer.Write (webSocketPath);
|
|
|
|
writer.WriteLine (@""");</script>");
|
|
|
|
writer.WriteLine (BodyFooterHtml);
|
|
|
|
writer.WriteLine (@"</body>
|
|
|
|
</html>");
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
|
2017-07-08 02:38:04 +00:00
|
|
|
class DataHandler : RequestHandler
|
|
|
|
{
|
|
|
|
readonly byte[] data;
|
2017-12-11 01:51:05 +00:00
|
|
|
readonly string etag;
|
2017-07-08 02:38:04 +00:00
|
|
|
readonly string contentType;
|
|
|
|
|
2017-12-11 01:51:05 +00:00
|
|
|
public byte[] Data => data;
|
|
|
|
public string Etag => etag;
|
|
|
|
public string ContentType => contentType;
|
|
|
|
|
|
|
|
public DataHandler (byte[] data, string etag, string contentType = null)
|
2017-07-08 02:38:04 +00:00
|
|
|
{
|
|
|
|
this.data = data;
|
2017-12-11 01:51:05 +00:00
|
|
|
this.etag = etag;
|
2017-07-08 02:38:04 +00:00
|
|
|
this.contentType = contentType;
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void Respond (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
var response = listenerContext.Response;
|
|
|
|
|
2017-12-11 01:51:05 +00:00
|
|
|
var inm = listenerContext.Request.Headers.Get ("If-None-Match");
|
|
|
|
if (!string.IsNullOrEmpty (inm) && inm == etag) {
|
|
|
|
response.StatusCode = 304;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
response.StatusCode = 200;
|
|
|
|
response.AddHeader ("Etag", etag);
|
|
|
|
if (!string.IsNullOrEmpty (contentType))
|
|
|
|
response.ContentType = contentType;
|
|
|
|
response.ContentLength64 = data.LongLength;
|
2017-07-08 03:27:03 +00:00
|
|
|
|
2017-12-11 01:51:05 +00:00
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (data, 0, data.Length);
|
|
|
|
}
|
2017-07-08 03:27:03 +00:00
|
|
|
}
|
|
|
|
response.Close ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class JsonHandler : RequestHandler
|
|
|
|
{
|
|
|
|
public const string ContentType = "application/json; charset=utf-8";
|
|
|
|
|
|
|
|
readonly Func<object> ctor;
|
|
|
|
|
|
|
|
public JsonHandler (Func<object> ctor)
|
|
|
|
{
|
|
|
|
this.ctor = ctor;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static byte[] GetData (object obj)
|
|
|
|
{
|
|
|
|
var r = Newtonsoft.Json.JsonConvert.SerializeObject (obj);
|
|
|
|
return System.Text.Encoding.UTF8.GetBytes (r);
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void Respond (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
var response = listenerContext.Response;
|
|
|
|
|
|
|
|
var data = GetData (ctor ());
|
|
|
|
|
|
|
|
response.StatusCode = 200;
|
|
|
|
response.ContentType = ContentType;
|
2017-07-08 02:38:04 +00:00
|
|
|
response.ContentLength64 = data.LongLength;
|
|
|
|
|
|
|
|
using (var s = response.OutputStream) {
|
|
|
|
s.Write (data, 0, data.Length);
|
|
|
|
}
|
|
|
|
response.Close ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-23 03:26:01 +00:00
|
|
|
class CustomHandler : RequestHandler
|
|
|
|
{
|
|
|
|
readonly Action<HttpListenerContext, CancellationToken> responder;
|
|
|
|
|
|
|
|
public CustomHandler (Action<HttpListenerContext, CancellationToken> responder)
|
|
|
|
{
|
|
|
|
this.responder = responder;
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void Respond (HttpListenerContext listenerContext, CancellationToken token)
|
|
|
|
{
|
|
|
|
responder (listenerContext, token);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-16 04:21:38 +00:00
|
|
|
static async void ProcessWebSocketRequest (HttpListenerContext listenerContext, CancellationToken serverToken)
|
2017-06-15 07:40:08 +00:00
|
|
|
{
|
|
|
|
//
|
|
|
|
// Find the element
|
|
|
|
//
|
|
|
|
var url = listenerContext.Request.Url;
|
|
|
|
var path = url.LocalPath;
|
|
|
|
|
2017-07-06 23:01:21 +00:00
|
|
|
RequestHandler handler;
|
2017-06-16 00:35:20 +00:00
|
|
|
var found = false;
|
2017-07-06 23:01:21 +00:00
|
|
|
lock (publishedPaths) found = publishedPaths.TryGetValue (path, out handler);
|
|
|
|
var elementHandler = handler as ElementHandler;
|
|
|
|
if (!found || elementHandler == null) {
|
2017-06-15 07:40:08 +00:00
|
|
|
listenerContext.Response.StatusCode = 404;
|
|
|
|
listenerContext.Response.Close ();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
Element element = null;
|
|
|
|
try {
|
2017-07-06 23:01:21 +00:00
|
|
|
element = elementHandler.GetElement ();
|
2017-11-09 07:57:04 +00:00
|
|
|
|
|
|
|
if (element == null)
|
|
|
|
throw new Exception ("Handler returned a null element");
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
listenerContext.Response.StatusCode = 500;
|
|
|
|
listenerContext.Response.Close();
|
|
|
|
Error ("Failed to create element", ex);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
//
|
|
|
|
// Connect the web socket
|
|
|
|
//
|
|
|
|
WebSocketContext webSocketContext = null;
|
|
|
|
WebSocket webSocket = null;
|
|
|
|
try {
|
2017-06-16 00:23:07 +00:00
|
|
|
webSocketContext = await listenerContext.AcceptWebSocketAsync (subProtocol: "ooui").ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
webSocket = webSocketContext.WebSocket;
|
|
|
|
Console.WriteLine ("WEBSOCKET {0}", listenerContext.Request.Url.LocalPath);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
listenerContext.Response.StatusCode = 500;
|
|
|
|
listenerContext.Response.Close();
|
|
|
|
Error ("Failed to accept WebSocket", ex);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-12-09 23:34:48 +00:00
|
|
|
//
|
|
|
|
// Set the element's dimensions
|
|
|
|
//
|
|
|
|
var query =
|
|
|
|
(from part in listenerContext.Request.Url.Query.Split (new[] { '?', '&' })
|
|
|
|
where part.Length > 0
|
|
|
|
let kvs = part.Split ('=')
|
|
|
|
where kvs.Length == 2
|
|
|
|
select kvs).ToDictionary (x => Uri.UnescapeDataString (x[0]), x => Uri.UnescapeDataString (x[1]));
|
|
|
|
if (!query.TryGetValue ("w", out var wValue) || string.IsNullOrEmpty (wValue)) {
|
|
|
|
wValue = "640";
|
|
|
|
}
|
|
|
|
if (!query.TryGetValue ("h", out var hValue) || string.IsNullOrEmpty (hValue)) {
|
|
|
|
hValue = "480";
|
|
|
|
}
|
|
|
|
var icult = System.Globalization.CultureInfo.InvariantCulture;
|
|
|
|
if (!double.TryParse (wValue, System.Globalization.NumberStyles.Any, icult, out var w))
|
|
|
|
w = 640;
|
|
|
|
if (!double.TryParse (hValue, System.Globalization.NumberStyles.Any, icult, out var h))
|
|
|
|
h = 480;
|
|
|
|
|
2017-06-15 09:39:19 +00:00
|
|
|
//
|
2017-06-16 04:21:38 +00:00
|
|
|
// Create a new session and let it handle everything from here
|
2017-06-15 07:40:08 +00:00
|
|
|
//
|
|
|
|
try {
|
2017-12-09 23:34:48 +00:00
|
|
|
var session = new Session (webSocket, element, w, h, serverToken);
|
2017-06-18 08:13:15 +00:00
|
|
|
await session.RunAsync ().ConfigureAwait (false);
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
catch (WebSocketException ex) when (ex.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely) {
|
|
|
|
// The remote party closed the WebSocket connection without completing the close handshake.
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
2017-06-15 09:39:19 +00:00
|
|
|
Error ("Web socket failed", ex);
|
2017-06-15 07:40:08 +00:00
|
|
|
}
|
|
|
|
finally {
|
|
|
|
webSocket?.Dispose ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void Error (string message, Exception ex)
|
2017-06-14 01:37:03 +00:00
|
|
|
{
|
2017-06-15 07:40:08 +00:00
|
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
|
|
Console.WriteLine ("{0}: {1}", message, ex);
|
|
|
|
Console.ResetColor ();
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
2017-06-16 04:21:38 +00:00
|
|
|
|
2017-11-10 05:00:15 +00:00
|
|
|
public class Session
|
2017-06-16 04:21:38 +00:00
|
|
|
{
|
|
|
|
readonly WebSocket webSocket;
|
|
|
|
readonly Element element;
|
2017-06-18 08:13:15 +00:00
|
|
|
readonly Action<Message> handleElementMessageSent;
|
|
|
|
|
|
|
|
readonly CancellationTokenSource sessionCts = new CancellationTokenSource ();
|
|
|
|
readonly CancellationTokenSource linkedCts;
|
|
|
|
readonly CancellationToken token;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
readonly HashSet<string> createdIds;
|
|
|
|
readonly List<Message> queuedMessages = new List<Message> ();
|
|
|
|
|
2017-12-10 06:19:16 +00:00
|
|
|
public const int MaxFps = 30;
|
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
readonly System.Timers.Timer sendThrottle;
|
|
|
|
DateTime lastTransmitTime = DateTime.MinValue;
|
2017-12-10 06:19:16 +00:00
|
|
|
readonly TimeSpan throttleInterval = TimeSpan.FromSeconds (1.0 / MaxFps);
|
2017-11-19 20:19:44 +00:00
|
|
|
readonly double initialWidth;
|
|
|
|
readonly double initialHeight;
|
2017-06-18 08:13:15 +00:00
|
|
|
|
2017-11-19 20:19:44 +00:00
|
|
|
public Session (WebSocket webSocket, Element element, double initialWidth, double initialHeight, CancellationToken serverToken)
|
2017-06-16 04:21:38 +00:00
|
|
|
{
|
|
|
|
this.webSocket = webSocket;
|
|
|
|
this.element = element;
|
2017-11-19 20:19:44 +00:00
|
|
|
this.initialWidth = initialWidth;
|
|
|
|
this.initialHeight = initialHeight;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
//
|
|
|
|
// Create a new session cancellation token that will trigger
|
|
|
|
// automatically if the server shutsdown or the session shutsdown.
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
linkedCts = CancellationTokenSource.CreateLinkedTokenSource (serverToken, sessionCts.Token);
|
|
|
|
token = linkedCts.Token;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
//
|
|
|
|
// Keep a list of all the elements for which we've transmitted the initial state
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
createdIds = new HashSet<string> {
|
2017-06-16 04:21:38 +00:00
|
|
|
"window",
|
|
|
|
"document",
|
|
|
|
"document.body",
|
|
|
|
};
|
|
|
|
|
|
|
|
//
|
|
|
|
// Preparse handlers for the element
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
handleElementMessageSent = QueueMessage;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Create a timer to use as a throttle when sending messages
|
|
|
|
//
|
|
|
|
sendThrottle = new System.Timers.Timer (throttleInterval.TotalMilliseconds);
|
|
|
|
sendThrottle.Elapsed += (s, e) => {
|
2017-06-18 08:17:47 +00:00
|
|
|
// System.Console.WriteLine ("TICK SEND THROTTLE FOR {0}", element);
|
2017-06-18 08:13:15 +00:00
|
|
|
if ((e.SignalTime - lastTransmitTime) >= throttleInterval) {
|
|
|
|
sendThrottle.Enabled = false;
|
|
|
|
lastTransmitTime = e.SignalTime;
|
|
|
|
TransmitQueuedMessages ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
};
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
2017-06-16 04:21:38 +00:00
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
public async Task RunAsync ()
|
|
|
|
{
|
2017-06-16 04:21:38 +00:00
|
|
|
//
|
|
|
|
// Start watching for changes in the element
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
element.MessageSent += handleElementMessageSent;
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
//
|
|
|
|
// Add it to the document body
|
|
|
|
//
|
2017-11-19 20:19:44 +00:00
|
|
|
if (element.WantsFullScreen) {
|
|
|
|
element.Style.Width = initialWidth;
|
|
|
|
element.Style.Height = initialHeight;
|
|
|
|
}
|
2017-06-18 08:13:15 +00:00
|
|
|
QueueMessage (Message.Call ("document.body", "appendChild", element));
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
//
|
2017-06-18 08:13:15 +00:00
|
|
|
// Start the Read Loop
|
2017-06-16 04:21:38 +00:00
|
|
|
//
|
2017-06-18 08:21:00 +00:00
|
|
|
var receiveBuffer = new byte[64*1024];
|
2017-06-16 04:21:38 +00:00
|
|
|
|
|
|
|
while (webSocket.State == WebSocketState.Open && !token.IsCancellationRequested) {
|
|
|
|
var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), token).ConfigureAwait (false);
|
|
|
|
|
|
|
|
if (receiveResult.MessageType == WebSocketMessageType.Close) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.NormalClosure, "", token).ConfigureAwait (false);
|
2017-06-16 04:29:57 +00:00
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
else if (receiveResult.MessageType == WebSocketMessageType.Binary) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", token).ConfigureAwait (false);
|
2017-06-16 04:29:57 +00:00
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
var size = receiveResult.Count;
|
|
|
|
while (!receiveResult.EndOfMessage) {
|
|
|
|
if (size >= receiveBuffer.Length) {
|
|
|
|
await webSocket.CloseAsync (WebSocketCloseStatus.MessageTooBig, "Message too big", token).ConfigureAwait (false);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
receiveResult = await webSocket.ReceiveAsync (new ArraySegment<byte>(receiveBuffer, size, receiveBuffer.Length - size), token).ConfigureAwait (false);
|
|
|
|
size += receiveResult.Count;
|
|
|
|
}
|
|
|
|
var receivedString = Encoding.UTF8.GetString (receiveBuffer, 0, size);
|
|
|
|
|
|
|
|
try {
|
|
|
|
// Console.WriteLine ("RECEIVED: {0}", receivedString);
|
|
|
|
var message = Newtonsoft.Json.JsonConvert.DeserializeObject<Message> (receivedString);
|
|
|
|
element.Receive (message);
|
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
Error ("Failed to process received message", ex);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
finally {
|
2017-06-18 08:13:15 +00:00
|
|
|
element.MessageSent -= handleElementMessageSent;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-10 20:51:35 +00:00
|
|
|
void QueueStateMessagesLocked (EventTarget target)
|
2017-06-18 08:13:15 +00:00
|
|
|
{
|
|
|
|
if (target == null) return;
|
2017-11-16 03:58:48 +00:00
|
|
|
var created = false;
|
2017-06-18 08:13:15 +00:00
|
|
|
foreach (var m in target.StateMessages) {
|
2017-11-16 03:58:48 +00:00
|
|
|
if (m.MessageType == MessageType.Create) {
|
|
|
|
createdIds.Add (m.TargetId);
|
|
|
|
created = true;
|
|
|
|
}
|
|
|
|
if (created) {
|
|
|
|
QueueMessageLocked (m);
|
|
|
|
}
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-10 20:51:35 +00:00
|
|
|
void QueueMessageLocked (Message message)
|
2017-06-18 08:13:15 +00:00
|
|
|
{
|
|
|
|
//
|
|
|
|
// Make sure all the referenced objects have been created
|
|
|
|
//
|
2017-11-16 03:58:48 +00:00
|
|
|
if (!createdIds.Contains (message.TargetId)) {
|
|
|
|
QueueStateMessagesLocked (element.GetElementById (message.TargetId));
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
2017-11-16 03:58:48 +00:00
|
|
|
if (message.Value is EventTarget ve) {
|
|
|
|
if (!createdIds.Contains (ve.Id)) {
|
|
|
|
QueueStateMessagesLocked (ve);
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
2017-11-16 03:58:48 +00:00
|
|
|
}
|
|
|
|
else if (message.Value is Array a) {
|
|
|
|
for (var i = 0; i < a.Length; i++) {
|
|
|
|
// Console.WriteLine ($"A{i} = {a.GetValue(i)}");
|
|
|
|
if (a.GetValue (i) is EventTarget e && !createdIds.Contains (e.Id)) {
|
|
|
|
QueueStateMessagesLocked (e);
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-11-16 03:58:48 +00:00
|
|
|
|
2017-06-18 08:13:15 +00:00
|
|
|
//
|
|
|
|
// Add it to the queue
|
|
|
|
//
|
2017-12-10 01:49:11 +00:00
|
|
|
//Console.WriteLine ($"QM {message.MessageType} {message.TargetId} {message.Key} {message.Value}");
|
2017-11-10 20:51:35 +00:00
|
|
|
queuedMessages.Add (message);
|
|
|
|
}
|
|
|
|
|
|
|
|
void QueueMessage (Message message)
|
|
|
|
{
|
|
|
|
lock (queuedMessages) {
|
|
|
|
QueueMessageLocked (message);
|
|
|
|
}
|
2017-06-18 08:13:15 +00:00
|
|
|
sendThrottle.Enabled = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
async void TransmitQueuedMessages ()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
//
|
|
|
|
// Dequeue as many messages as we can
|
|
|
|
//
|
|
|
|
var messagesToSend = new List<Message> ();
|
2017-12-10 01:49:11 +00:00
|
|
|
System.Runtime.CompilerServices.ConfiguredTaskAwaitable task;
|
2017-06-18 08:13:15 +00:00
|
|
|
lock (queuedMessages) {
|
|
|
|
messagesToSend.AddRange (queuedMessages);
|
|
|
|
queuedMessages.Clear ();
|
|
|
|
|
2017-12-10 01:49:11 +00:00
|
|
|
if (messagesToSend.Count == 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
//
|
|
|
|
// Now actually send this message
|
|
|
|
// Do this while locked to make sure SendAsync is called in the right order
|
|
|
|
//
|
|
|
|
var json = Newtonsoft.Json.JsonConvert.SerializeObject (messagesToSend);
|
|
|
|
var outputBuffer = new ArraySegment<byte> (Encoding.UTF8.GetBytes (json));
|
|
|
|
//Console.WriteLine ("TRANSMIT " + json);
|
|
|
|
task = webSocket.SendAsync (outputBuffer, WebSocketMessageType.Text, true, token).ConfigureAwait (false);
|
|
|
|
}
|
|
|
|
await task;
|
2017-06-18 08:13:15 +00:00
|
|
|
}
|
|
|
|
catch (Exception ex) {
|
|
|
|
Error ("Failed to send queued messages, aborting session", ex);
|
|
|
|
element.MessageSent -= handleElementMessageSent;
|
|
|
|
sessionCts.Cancel ();
|
2017-06-16 04:21:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-06-27 01:48:57 +00:00
|
|
|
|
2018-03-09 20:56:32 +00:00
|
|
|
#endif
|
|
|
|
|
|
|
|
static readonly Dictionary<string, Style> styles =
|
|
|
|
new Dictionary<string, Style> ();
|
|
|
|
static readonly StyleSelectors rules = new StyleSelectors ();
|
|
|
|
|
|
|
|
public static StyleSelectors Styles => rules;
|
|
|
|
|
2017-06-27 01:48:57 +00:00
|
|
|
public class StyleSelectors
|
|
|
|
{
|
|
|
|
public Style this[string selector] {
|
|
|
|
get {
|
|
|
|
var key = selector ?? "";
|
|
|
|
lock (styles) {
|
2017-07-06 23:12:34 +00:00
|
|
|
if (!styles.TryGetValue (key, out Style r)) {
|
2017-06-27 01:48:57 +00:00
|
|
|
r = new Style ();
|
|
|
|
styles.Add (key, r);
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
set {
|
|
|
|
var key = selector ?? "";
|
|
|
|
lock (styles) {
|
|
|
|
if (value == null) {
|
|
|
|
styles.Remove (key);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
styles[key] = value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public void Clear ()
|
|
|
|
{
|
|
|
|
lock (styles) {
|
|
|
|
styles.Clear ();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public override string ToString()
|
|
|
|
{
|
|
|
|
lock (styles) {
|
|
|
|
var q =
|
|
|
|
from s in styles
|
|
|
|
let v = s.Value.ToString ()
|
|
|
|
where v.Length > 0
|
|
|
|
select s.Key + " {" + s.Value.ToString () + "}";
|
|
|
|
return String.Join ("\n", q);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-06-14 01:37:03 +00:00
|
|
|
}
|
|
|
|
}
|