using System; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using Webserver.SSE; // Implemented following HTML spec // https://html.spec.whatwg.org/multipage/server-sent-events.html namespace Webserver.UrlHandlers { public class SseHandler : AbsHandler { private readonly Dictionary events = new CaseInsensitiveStringDictionary (); private ThreadManager.ThreadInfo queueThead; private readonly AutoResetEvent evSendRequest = new AutoResetEvent (false); private bool shutdown; public SseHandler (string _moduleName = null) : base (_moduleName) { Type[] ctorTypes = { typeof (SseHandler) }; object[] ctorParams = { this }; foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) { if (t.IsAbstract || !t.IsSubclassOf (typeof (AbsEvent))) { continue; } ConstructorInfo ctor = t.GetConstructor (ctorTypes); if (ctor == null) { continue; } AbsEvent apiInstance = (AbsEvent)ctor.Invoke (ctorParams); AddEvent (apiInstance.Name, apiInstance); } } public override void SetBasePathAndParent (Web _parent, string _relativePath) { base.SetBasePathAndParent (_parent, _relativePath); queueThead = ThreadManager.StartThread ("SSE-Processing_" + urlBasePath, QueueProcessThread, ThreadPriority.BelowNormal, _useRealThread: true); } public override void Shutdown () { base.Shutdown (); shutdown = true; SignalSendQueue (); } public void AddEvent (string _eventName, AbsEvent _eventInstance) { events.Add (_eventName, _eventInstance); WebPermissions.Instance.AddKnownModule ("webevent." + _eventName, _eventInstance.DefaultPermissionLevel ()); } public override void HandleRequest (RequestContext _context) { string eventName = _context.RequestPath.Remove (0, urlBasePath.Length); if (!events.TryGetValue (eventName, out AbsEvent eventInstance)) { Log.Warning ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): No handler found for event \"{eventName}\""); _context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } if (!IsAuthorizedForEvent (eventName, _context.PermissionLevel)) { _context.Response.StatusCode = (int)HttpStatusCode.Forbidden; if (_context.Connection != null) { //Log.Out ($"{nameof(SseHandler)}: user '{user.SteamID}' not allowed to access '{eventName}'"); } return; } try { eventInstance.AddListener (_context.Response); // Keep the request open _context.Response.SendChunked = true; _context.Response.AddHeader ("Content-Type", "text/event-stream"); _context.Response.OutputStream.Flush (); } catch (Exception e) { Log.Error ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): Handler {eventInstance.Name} threw an exception:"); Log.Exception (e); _context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } } private bool IsAuthorizedForEvent (string _eventName, int _permissionLevel) { return WebPermissions.Instance.ModuleAllowedWithLevel ("webevent." + _eventName, _permissionLevel); } private void QueueProcessThread (ThreadManager.ThreadInfo _threadInfo) { while (!shutdown && !_threadInfo.TerminationRequested ()) { evSendRequest.WaitOne (500); foreach ((string eventName, AbsEvent eventHandler) in events) { try { eventHandler.ProcessSendQueue (); } catch (Exception e) { Log.Error ($"[Web] [SSE] '{eventName}': Error processing send queue"); Log.Exception (e); } } } } public void SignalSendQueue () { evSendRequest.Set (); } } }