using System;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
{
///
/// Class SessionWebSocketListener
///
public sealed class SessionWebSocketListener : IWebSocketListener, IDisposable
{
///
/// The _session manager
///
private readonly ISessionManager _sessionManager;
///
/// The _logger
///
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IHttpServer _httpServer;
///
/// Initializes a new instance of the class.
///
/// The logger.
/// The session manager.
/// The logger factory.
/// The HTTP server.
public SessionWebSocketListener(
ILogger logger,
ISessionManager sessionManager,
ILoggerFactory loggerFactory,
IHttpServer httpServer)
{
_logger = logger;
_sessionManager = sessionManager;
_loggerFactory = loggerFactory;
_httpServer = httpServer;
httpServer.WebSocketConnected += OnServerManagerWebSocketConnected;
}
private void OnServerManagerWebSocketConnected(object sender, GenericEventArgs e)
{
var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint.ToString());
if (session != null)
{
EnsureController(session, e.Argument);
}
else
{
_logger.LogWarning("Unable to determine session based on query string: {0}", e.Argument.QueryString);
}
}
private SessionInfo GetSession(IQueryCollection queryString, string remoteEndpoint)
{
if (queryString == null)
{
return null;
}
var token = queryString["api_key"];
if (string.IsNullOrWhiteSpace(token))
{
return null;
}
var deviceId = queryString["deviceId"];
return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint);
}
///
public void Dispose()
{
_httpServer.WebSocketConnected -= OnServerManagerWebSocketConnected;
}
///
/// Processes the message.
///
/// The message.
/// Task.
public Task ProcessMessageAsync(WebSocketMessageInfo message)
=> Task.CompletedTask;
private void EnsureController(SessionInfo session, IWebSocketConnection connection)
{
var controllerInfo = session.EnsureController(
s => new WebSocketController(_loggerFactory.CreateLogger(), s, _sessionManager));
var controller = (WebSocketController)controllerInfo.Item1;
controller.AddWebSocket(connection);
}
}
}