1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Net;
|
---|
4 | using System.Reflection;
|
---|
5 | using System.Threading;
|
---|
6 | using Webserver.Permissions;
|
---|
7 | using Webserver.SSE;
|
---|
8 |
|
---|
9 | // Implemented following HTML spec
|
---|
10 | // https://html.spec.whatwg.org/multipage/server-sent-events.html
|
---|
11 |
|
---|
12 | namespace Webserver.UrlHandlers {
|
---|
13 | public class SseHandler : AbsHandler {
|
---|
14 | private readonly Dictionary<string, AbsEvent> events = new CaseInsensitiveStringDictionary<AbsEvent> ();
|
---|
15 |
|
---|
16 | private ThreadManager.ThreadInfo queueThead;
|
---|
17 | private readonly AutoResetEvent evSendRequest = new AutoResetEvent (false);
|
---|
18 | private bool shutdown;
|
---|
19 |
|
---|
20 | private static readonly Type[] ctorTypes = { typeof (SseHandler) };
|
---|
21 | private static readonly object[] ctorParams = new object[1];
|
---|
22 |
|
---|
23 | public SseHandler (string _moduleName = null) : base (_moduleName) {
|
---|
24 | ctorParams[0] = this;
|
---|
25 |
|
---|
26 | ReflectionHelpers.FindTypesImplementingBase (typeof (AbsEvent), apiFoundCallback);
|
---|
27 | }
|
---|
28 |
|
---|
29 | private void apiFoundCallback (Type _type) {
|
---|
30 | ConstructorInfo ctor = _type.GetConstructor (ctorTypes);
|
---|
31 | if (ctor == null) {
|
---|
32 | return;
|
---|
33 | }
|
---|
34 |
|
---|
35 | AbsEvent apiInstance = (AbsEvent)ctor.Invoke (ctorParams);
|
---|
36 | AddEvent (apiInstance.Name, apiInstance);
|
---|
37 | }
|
---|
38 |
|
---|
39 | public override void SetBasePathAndParent (Web _parent, string _relativePath) {
|
---|
40 | base.SetBasePathAndParent (_parent, _relativePath);
|
---|
41 |
|
---|
42 | queueThead = ThreadManager.StartThread ($"SSE-Processing_{urlBasePath}", QueueProcessThread, ThreadPriority.BelowNormal,
|
---|
43 | _useRealThread: true);
|
---|
44 | }
|
---|
45 |
|
---|
46 | public override void Shutdown () {
|
---|
47 | base.Shutdown ();
|
---|
48 | shutdown = true;
|
---|
49 | SignalSendQueue ();
|
---|
50 | }
|
---|
51 |
|
---|
52 | // ReSharper disable once MemberCanBePrivate.Global
|
---|
53 | public void AddEvent (string _eventName, AbsEvent _eventInstance) {
|
---|
54 | events.Add (_eventName, _eventInstance);
|
---|
55 | AdminWebModules.Instance.AddKnownModule ($"webevent.{_eventName}", _eventInstance.DefaultPermissionLevel ());
|
---|
56 | }
|
---|
57 |
|
---|
58 | public override void HandleRequest (RequestContext _context) {
|
---|
59 | string eventName = _context.RequestPath.Remove (0, urlBasePath.Length);
|
---|
60 |
|
---|
61 | if (!events.TryGetValue (eventName, out AbsEvent eventInstance)) {
|
---|
62 | Log.Warning ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): No handler found for event \"{eventName}\"");
|
---|
63 | _context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
---|
64 | return;
|
---|
65 | }
|
---|
66 |
|
---|
67 | if (!IsAuthorizedForEvent (eventName, _context.PermissionLevel)) {
|
---|
68 | _context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
---|
69 | if (_context.Connection != null) {
|
---|
70 | //Log.Out ($"{nameof(SseHandler)}: user '{user.SteamID}' not allowed to access '{eventName}'");
|
---|
71 | }
|
---|
72 |
|
---|
73 | return;
|
---|
74 | }
|
---|
75 |
|
---|
76 | try {
|
---|
77 | eventInstance.AddListener (_context.Response);
|
---|
78 |
|
---|
79 | // Keep the request open
|
---|
80 | _context.Response.SendChunked = true;
|
---|
81 |
|
---|
82 | _context.Response.AddHeader ("Content-Type", "text/event-stream");
|
---|
83 | _context.Response.OutputStream.Flush ();
|
---|
84 | } catch (Exception e) {
|
---|
85 | Log.Error ($"[Web] [SSE] In {nameof (SseHandler)}.HandleRequest(): Handler {eventInstance.Name} threw an exception:");
|
---|
86 | Log.Exception (e);
|
---|
87 | _context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
---|
88 | }
|
---|
89 | }
|
---|
90 |
|
---|
91 | private bool IsAuthorizedForEvent (string _eventName, int _permissionLevel) {
|
---|
92 | return AdminWebModules.Instance.ModuleAllowedWithLevel ($"webevent.{_eventName}", _permissionLevel);
|
---|
93 | }
|
---|
94 |
|
---|
95 | private void QueueProcessThread (ThreadManager.ThreadInfo _threadInfo) {
|
---|
96 | while (!shutdown && !_threadInfo.TerminationRequested ()) {
|
---|
97 | evSendRequest.WaitOne (500);
|
---|
98 |
|
---|
99 | foreach ((string eventName, AbsEvent eventHandler) in events) {
|
---|
100 | try {
|
---|
101 | eventHandler.ProcessSendQueue ();
|
---|
102 | } catch (Exception e) {
|
---|
103 | Log.Error ($"[Web] [SSE] '{eventName}': Error processing send queue");
|
---|
104 | Log.Exception (e);
|
---|
105 | }
|
---|
106 | }
|
---|
107 | }
|
---|
108 | }
|
---|
109 |
|
---|
110 | public void SignalSendQueue () {
|
---|
111 | evSendRequest.Set ();
|
---|
112 | }
|
---|
113 | }
|
---|
114 | }
|
---|