You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jellyfin/Emby.Server.Implementations/Session/WebSocketController.cs

93 lines
2.6 KiB

using System;
11 years ago
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
{
public class WebSocketController : ISessionController, IDisposable
{
11 years ago
public SessionInfo Session { get; private set; }
11 years ago
public IReadOnlyList<IWebSocketConnection> Sockets { get; private set; }
11 years ago
private readonly ILogger _logger;
11 years ago
11 years ago
private readonly ISessionManager _sessionManager;
11 years ago
public WebSocketController(SessionInfo session, ILogger logger, ISessionManager sessionManager)
{
11 years ago
Session = session;
_logger = logger;
11 years ago
_sessionManager = sessionManager;
11 years ago
Sockets = new List<IWebSocketConnection>();
}
private bool HasOpenSockets => GetActiveSockets().Any();
10 years ago
public bool SupportsMediaControl => HasOpenSockets;
10 years ago
public bool IsSessionActive => HasOpenSockets;
11 years ago
private IEnumerable<IWebSocketConnection> GetActiveSockets()
11 years ago
{
return Sockets
11 years ago
.OrderByDescending(i => i.LastActivityDate)
.Where(i => i.State == WebSocketState.Open);
}
11 years ago
public void AddWebSocket(IWebSocketConnection connection)
{
var sockets = Sockets.ToList();
sockets.Add(connection);
Sockets = sockets;
connection.Closed += connection_Closed;
}
void connection_Closed(object sender, EventArgs e)
{
var connection = (IWebSocketConnection)sender;
var sockets = Sockets.ToList();
sockets.Remove(connection);
10 years ago
Sockets = sockets;
_sessionManager.CloseIfNeeded(Session);
11 years ago
}
public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
{
var socket = GetActiveSockets()
.FirstOrDefault();
if (socket == null)
{
return Task.CompletedTask;
}
return socket.SendAsync(new WebSocketMessage<T>
{
Data = data,
MessageType = name,
MessageId = messageId
}, cancellationToken);
}
public void Dispose()
{
foreach (var socket in Sockets.ToList())
{
socket.Closed -= connection_Closed;
}
}
}
}