using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Net; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using Tesses.WebServer; namespace Ooui { public class UI : Server { public bool Verbose {get;set;}=true; private async Task HandleAsync(ServerContext ctx) { string upgrade; if(ctx.RequestHeaders.TryGetFirst("Upgrade",out upgrade) && upgrade == "websocket") { ProcessWebSocketRequest (ctx, CancellationToken.None); } else { ProcessRequest(ctx,CancellationToken.None); } await Task.FromResult(0); } public override async Task GetAsync(ServerContext ctx) { await HandleAsync(ctx); } public override async Task OptionsAsync(ServerContext ctx) { await HandleAsync(ctx); } public override async Task PostAsync(ServerContext ctx) { await HandleAsync(ctx); } public override async Task OtherAsync(ServerContext ctx) { await HandleAsync(ctx); } public const int MaxFps = 30; static readonly ManualResetEvent started = new ManualResetEvent (false); //static CancellationTokenSource serverCts; static readonly Dictionary publishedPaths = new Dictionary (); static readonly byte[] clientJsBytes; static readonly string clientJsEtag; public static byte[] ClientJsBytes => clientJsBytes; public static string ClientJsEtag => clientJsEtag; public static string HeadHtml { get; set; } = @""; public static string BodyHeaderHtml { get; set; } = @""; public static string BodyFooterHtml { get; set; } = @""; 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")) { if (s == null) throw new Exception ("Missing Client.js"); using (var r = new StreamReader (s)) { clientJsBytes = Encoding.UTF8.GetBytes (r.ReadToEnd ()); } } clientJsEtag = "\"" + Utilities.GetShaHash (clientJsBytes) + "\""; } class PublishedPath { public string Path { get; } public Regex RegexPath { get; } public RequestHandler Handler { get; } public PublishedPath (string path, RequestHandler handler) { Path = path; RegexPath = new Regex ("^" + path + "$"); Handler = handler; } } void Publish (string path, RequestHandler handler) { //Console.WriteLine ($"PUBLISH {path} {handler}"); lock (publishedPaths) publishedPaths[path] = new PublishedPath (path, handler); } public void Publish (string path, Func elementCtor, bool disposeElementWhenDone = true) { Publish (path, new ElementHandler (elementCtor, disposeElementWhenDone)); } public void Publish (string path, Func elementCtor, bool disposeElementWhenDone = true) { Publish (path, new ElementHandler (_ => elementCtor (), disposeElementWhenDone)); } public void Publish (string path, Element element, bool disposeElementWhenDone = true) { Publish (path, () => element, disposeElementWhenDone); } public void PublishFile (string filePath) { var path = "/" + System.IO.Path.GetFileName (filePath); PublishFile (path, filePath); } public void PublishFile (string path, string filePath, string contentType = null) { var data = System.IO.File.ReadAllBytes (filePath); if (contentType == null) { contentType = GuessContentType (path, filePath); } var etag = "\"" + Utilities.GetShaHash (data) + "\""; Publish (path, new DataHandler (data, etag, contentType)); } public void PublishFile (string path, byte[] data, string contentType) { var etag = "\"" + Utilities.GetShaHash (data) + "\""; Publish (path, new DataHandler (data, etag, contentType)); } public void PublishFile (string path, byte[] data, string etag, string contentType) { Publish (path, new DataHandler (data, etag, contentType)); } public bool TryGetFileContentAtPath (string path, out FileContent file) { PublishedPath pp; lock (publishedPaths) { if (!publishedPaths.TryGetValue (path, out pp)) { file = null; return false; } } if (pp.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; } } public void PublishJson (string path, Func ctor) { Publish (path, new JsonHandler (_ => ctor ())); } public void PublishJson (string path, Func ctor) { Publish (path, new JsonHandler (ctor)); } public void PublishJson (string path, object value) { var data = JsonHandler.GetData (value); var etag = "\"" + Utilities.GetShaHash (data) + "\""; Publish (path, new DataHandler (data, etag, JsonHandler.ContentType)); } public void PublishCustomResponse (string path, Action responder) { Publish (path, new CustomHandler (responder)); } static string GuessContentType (string path, string filePath) { return null; } // public static void WaitUntilStarted () => started.WaitOne (); void ProcessRequest (ServerContext listenerContext, CancellationToken token) { var path = listenerContext.UrlPath; if(this.Verbose) Console.WriteLine ($"{listenerContext.Method} {path}"); if (path == "/ooui.js") { string inm=""; listenerContext.RequestHeaders.TryGetFirst ("If-None-Match",out inm); if ( string.IsNullOrEmpty (inm) || inm != clientJsEtag) { listenerContext.StatusCode = 200; listenerContext.ResponseHeaders.Add ("Cache-Control", "public, max-age=60"); listenerContext.ResponseHeaders.Add ("Etag", clientJsEtag); listenerContext.SendBytes(clientJsBytes,"appllication/json"); } else { listenerContext.StatusCode=304; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close(); } } else { var found = false; PublishedPath pp; var variables = new Dictionary (); lock (publishedPaths) found = publishedPaths.TryGetValue (path, out pp); if (!found) { // Try regex List pps; lock (publishedPaths) pps = publishedPaths.Values.ToList(); foreach (var p in pps) { var m = p.RegexPath.Match (path); if (m.Success) { pp = p; found = true; for (var ig = 1; ig < m.Groups.Count; ig++) { variables[p.RegexPath.GroupNameFromNumber(ig)] = m.Groups[ig].Value; } break; } } } if (found) { try { var context = UIContext.ForListenerContext (listenerContext, variables); pp.Handler.Respond (listenerContext, context, token); } catch (Exception ex) { Error ("Handler failed to respond", ex); try { listenerContext.StatusCode = 500; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close (); } catch { // Ignore ending the response errors } } } else { listenerContext.StatusCode = 500; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close (); } } } abstract class RequestHandler { public abstract void Respond (ServerContext listenerContext, UIContext context, CancellationToken token); } class ElementHandler : RequestHandler { readonly Func ctor; public bool DisposeElementWhenDone { get; } public ElementHandler (Func ctor, bool disposeElementWhenDone) { this.ctor = ctor; DisposeElementWhenDone = disposeElementWhenDone; } public Element GetElement (UIContext context) => ctor (context); public override void Respond (ServerContext listenerContext, UIContext context, CancellationToken token) { var path = listenerContext.UrlPath; listenerContext.StatusCode = 200; listenerContext.SendText(RenderTemplate (path)); } } public static string RenderTemplate (string webSocketPath, string title = "", string initialHtml = "") { using (var w = new System.IO.StringWriter ()) { RenderTemplate (w, webSocketPath, title, initialHtml); return w.ToString (); } } static string EscapeHtml (string text) { return text.Replace ("&", "&").Replace ("<", "<"); } public static void RenderTemplate (TextWriter writer, string webSocketPath, string title, string initialHtml) { writer.Write (@" "); writer.Write (EscapeHtml (title)); writer.Write (@" "); writer.WriteLine (HeadHtml); writer.WriteLine (@" "); writer.WriteLine (BodyHeaderHtml); writer.WriteLine (@"
"); writer.WriteLine (initialHtml); writer.Write (@"
"); writer.WriteLine (BodyFooterHtml); writer.WriteLine (@" "); } class DataHandler : RequestHandler { readonly byte[] data; readonly string etag; readonly string contentType; public byte[] Data => data; public string Etag => etag; public string ContentType => contentType; public DataHandler (byte[] data, string etag, string contentType = null) { this.data = data; this.etag = etag; this.contentType = contentType; } public override void Respond (ServerContext listenerContext, UIContext context, CancellationToken token) { var url = listenerContext.UrlPath; string inm=""; if (listenerContext.RequestHeaders.TryGetFirst("If-None-Match",out inm) && !string.IsNullOrEmpty (inm) && inm == etag) { listenerContext.StatusCode = 304; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close(); } else { string content_type = "application/octet-stream"; listenerContext.StatusCode = 200; listenerContext.ResponseHeaders.Add ("Etag", etag); if (!string.IsNullOrEmpty (contentType)) content_type= contentType; listenerContext.SendBytes(data,content_type); } } } class JsonHandler : RequestHandler { public const string ContentType = "application/json; charset=utf-8"; readonly Func ctor; public JsonHandler (Func ctor) { this.ctor = ctor; } public static byte[] GetData (object obj) { var r = Ooui.JsonConvert.SerializeObject (obj); var e = new UTF8Encoding (false); return e.GetBytes (r); } public override void Respond (ServerContext listenerContext, UIContext context, CancellationToken token) { var data = GetData (ctor (context)); listenerContext.StatusCode = 200; listenerContext.SendBytes(data,ContentType); } } class CustomHandler : RequestHandler { readonly Action responder; public CustomHandler (Action responder) { this.responder = responder; } public override void Respond (ServerContext listenerContext, UIContext context, CancellationToken token) { responder (listenerContext, token); } } void ProcessWebSocketRequest (ServerContext listenerContext, CancellationToken serverToken) { // // Find the element // var path = listenerContext.UrlPath; PublishedPath pp; var found = false; var variables = new Dictionary (); lock (publishedPaths) found = publishedPaths.TryGetValue (path, out pp); if (!found) { List pps; lock (publishedPaths) pps = publishedPaths.Values.ToList (); foreach (var p in pps) { var m = p.RegexPath.Match (path); if (m.Success) { pp = p; found = true; for (var ig = 1; ig < m.Groups.Count; ig++) { variables[p.RegexPath.GroupNameFromNumber (ig)] = m.Groups[ig].Value; } break; } } } var elementHandler = pp?.Handler as ElementHandler; if (!found || elementHandler == null) { listenerContext.StatusCode = 404; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close(); return; } Element element = null; bool disposeElementWhenDone = true; try { var context = UIContext.ForListenerContext (listenerContext, variables); context.QueryParams = listenerContext.QueryParams; element = elementHandler.GetElement (context); disposeElementWhenDone = elementHandler.DisposeElementWhenDone; if (element == null) throw new Exception ("Handler returned a null element"); } catch (Exception ex) { listenerContext.StatusCode = 500; listenerContext.WriteHeaders(); listenerContext.NetworkStream.Close(); Error ("Failed to create element", ex); return; } // // Connect the web socket // //listenerContext.RequestHeaders.Add("Sec-WebSocket-Protocol","ooui"); // // Set the element's dimensions // var query = listenerContext.QueryParams; if (!query.TryGetFirst ("w", out var wValue) || string.IsNullOrEmpty (wValue)) { wValue = "640"; } if (!query.TryGetFirst ("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; // // Create a new session and let it handle everything from here // try { var session = new WebSocketSession (element, disposeElementWhenDone, w, h, Error, serverToken); listenerContext.StartWebSocketConnection(session.Opened, session.Arrived, session.Closed); } catch (Exception ex) { Error ("Web socket failed", ex); } } void Error (string message, Exception ex) { if(!Verbose) return; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine ("{0}: {1}", message, ex); Console.ResetColor (); } static readonly Dictionary styles = new Dictionary (); static readonly StyleSelectors rules = new StyleSelectors (); public static StyleSelectors Styles => rules; public class StyleSelectors { public Style this[string selector] { get { var key = selector ?? ""; lock (styles) { if (!styles.TryGetValue (key, out Style r)) { 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); } } } } public class UIContext { public Dictionary> QueryParams {get;set;}=new Dictionary>(); readonly Dictionary variables = new Dictionary (); public string RequestUrl { get; } public string this[string key] => variables.TryGetValue (key, out var v) ? v : ""; public UIContext (string requestUrl) { RequestUrl = requestUrl ?? throw new ArgumentNullException (nameof (requestUrl)); } public static UIContext ForListenerContext (ServerContext listenerContext, Dictionary variables) { var c = new UIContext (listenerContext.UrlPath); foreach (var kv in variables) { c.variables.Add (kv.Key, kv.Value); } return c; } public static UIContext ForWebAssemblySession (string sessionId, string elementPath) { throw new NotSupportedException("Not supported on this fork"); } } }