Pusher.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 pushes, called on client connection.
  13. /// </summary>
  14. /// <returns>New pushes</returns>
  15. IEnumerable<BaseObject> Poll(Guid session);
  16. }
  17. public class PollHandler<TPush> : IPollHandler
  18. where TPush : BaseObject
  19. {
  20. public delegate IEnumerable<TPush> PollEvent(Guid session);
  21. public event PollEvent? OnPoll;
  22. public Type Type => typeof(TPush);
  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<TPush>();
  29. }
  30. /// <summary>
  31. /// Classes that implement this interface implement the manner by which the server actually gets messages pushed to the client.
  32. /// The implementation will manage the transport layer.
  33. /// </summary>
  34. /// <remarks>
  35. /// If one wishes to implement <see cref="IPusher"/>, it is likely one should also register it with <see cref="PushManager.AddPusher(IPusher)"/>;
  36. /// this way, when the server wishes to push a message, it will go through this pusher (as well as any other registered ones).
  37. /// </remarks>
  38. public interface IPusher
  39. {
  40. void PushToAll<TPush>(TPush push) where TPush : BaseObject;
  41. void PushToSession<TPush>(Guid session, TPush push) where TPush : BaseObject;
  42. void PushToSession(Guid session, Type TPush, BaseObject push);
  43. IEnumerable<Guid> GetUserSessions(Guid user);
  44. IEnumerable<Guid> GetSessions(Platform platform);
  45. public void Push<TPush>(TPush push)
  46. where TPush : BaseObject
  47. {
  48. PushToAll(push);
  49. }
  50. public void Push(Guid session, Type TPush, BaseObject push)
  51. {
  52. PushToSession(session, TPush, push);
  53. }
  54. public void Push<TPush>(Guid session, TPush push)
  55. where TPush : BaseObject
  56. {
  57. PushToSession(session, push);
  58. }
  59. public void PushUser<TPush>(Guid user, TPush push)
  60. where TPush : BaseObject
  61. {
  62. foreach (var session in GetUserSessions(user))
  63. {
  64. PushToSession(session, push);
  65. }
  66. }
  67. public void Push<TPush>(Platform platform, TPush push)
  68. where TPush : BaseObject
  69. {
  70. foreach (var session in GetSessions(platform))
  71. {
  72. PushToSession(session, push);
  73. }
  74. }
  75. }
  76. }