Notifier.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using InABox.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. namespace InABox.Core
  7. {
  8. public interface IPollHandler
  9. {
  10. Type Type { get; }
  11. /// <summary>
  12. /// Polls for notifications, called on client connection.
  13. /// </summary>
  14. /// <returns>New notifications</returns>
  15. IEnumerable<BaseObject> Poll(Guid session);
  16. }
  17. public class PollHandler<TNotification> : IPollHandler
  18. where TNotification : BaseObject
  19. {
  20. public delegate IEnumerable<TNotification> PollEvent(Guid session);
  21. public event PollEvent? OnPoll;
  22. public Type Type => typeof(TNotification);
  23. public PollHandler() { }
  24. public PollHandler(PollEvent poll)
  25. {
  26. OnPoll += poll;
  27. }
  28. public IEnumerable<BaseObject> Poll(Guid session) => OnPoll?.Invoke(session) ?? Array.Empty<TNotification>();
  29. }
  30. public abstract class Notifier
  31. {
  32. protected abstract void NotifyAll<TNotification>(TNotification notification) where TNotification : BaseObject;
  33. protected abstract void NotifySession<TNotification>(Guid session, TNotification notification) where TNotification : BaseObject;
  34. protected abstract void NotifySession(Guid session, Type TNotification, BaseObject notification);
  35. protected abstract IEnumerable<Guid> GetUserSessions(Guid user);
  36. protected abstract IEnumerable<Guid> GetSessions(Platform platform);
  37. public void Push<TNotification>(TNotification notification)
  38. where TNotification : BaseObject
  39. {
  40. NotifyAll(notification);
  41. }
  42. public void Push(Guid session, Type TNotification, BaseObject notification)
  43. {
  44. NotifySession(session, TNotification, notification);
  45. }
  46. public void Push<TNotification>(Guid session, TNotification notification)
  47. where TNotification : BaseObject
  48. {
  49. NotifySession(session, notification);
  50. }
  51. public void PushUser<TNotification>(Guid user, TNotification notification)
  52. where TNotification : BaseObject
  53. {
  54. foreach (var session in GetUserSessions(user))
  55. {
  56. NotifySession(session, notification);
  57. }
  58. }
  59. public void Push<TNotification>(Platform platform, TNotification notification)
  60. where TNotification : BaseObject
  61. {
  62. foreach (var session in GetSessions(platform))
  63. {
  64. NotifySession(session, notification);
  65. }
  66. }
  67. }
  68. }