WebSocketController.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using MediaBrowser.Controller.Net;
  2. using MediaBrowser.Controller.Session;
  3. using MediaBrowser.Model.Entities;
  4. using Microsoft.Extensions.Logging;
  5. using MediaBrowser.Model.Net;
  6. using MediaBrowser.Model.Session;
  7. using MediaBrowser.Model.System;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Net.WebSockets;
  14. namespace Emby.Server.Implementations.Session
  15. {
  16. public class WebSocketController : ISessionController, IDisposable
  17. {
  18. public SessionInfo Session { get; private set; }
  19. public IReadOnlyList<IWebSocketConnection> Sockets { get; private set; }
  20. private readonly ILogger _logger;
  21. private readonly ISessionManager _sessionManager;
  22. public WebSocketController(SessionInfo session, ILogger logger, ISessionManager sessionManager)
  23. {
  24. Session = session;
  25. _logger = logger;
  26. _sessionManager = sessionManager;
  27. Sockets = new List<IWebSocketConnection>();
  28. }
  29. private bool HasOpenSockets => GetActiveSockets().Any();
  30. public bool SupportsMediaControl => HasOpenSockets;
  31. public bool IsSessionActive => HasOpenSockets;
  32. private IEnumerable<IWebSocketConnection> GetActiveSockets()
  33. {
  34. return Sockets
  35. .OrderByDescending(i => i.LastActivityDate)
  36. .Where(i => i.State == WebSocketState.Open);
  37. }
  38. public void AddWebSocket(IWebSocketConnection connection)
  39. {
  40. var sockets = Sockets.ToList();
  41. sockets.Add(connection);
  42. Sockets = sockets;
  43. connection.Closed += connection_Closed;
  44. }
  45. void connection_Closed(object sender, EventArgs e)
  46. {
  47. var connection = (IWebSocketConnection)sender;
  48. var sockets = Sockets.ToList();
  49. sockets.Remove(connection);
  50. Sockets = sockets;
  51. _sessionManager.CloseIfNeeded(Session);
  52. }
  53. public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
  54. {
  55. var socket = GetActiveSockets()
  56. .FirstOrDefault();
  57. if (socket == null)
  58. {
  59. return Task.CompletedTask;
  60. }
  61. return socket.SendAsync(new WebSocketMessage<T>
  62. {
  63. Data = data,
  64. MessageType = name,
  65. MessageId = messageId
  66. }, cancellationToken);
  67. }
  68. public void Dispose()
  69. {
  70. foreach (var socket in Sockets.ToList())
  71. {
  72. socket.Closed -= connection_Closed;
  73. }
  74. }
  75. }
  76. }