using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.Session
{
///
/// Class SessionWebSocketListener
///
public class SessionWebSocketListener : IWebSocketListener, IDisposable
{
///
/// The _session manager
///
private readonly ISessionManager _sessionManager;
///
/// The _logger
///
private readonly ILogger _logger;
///
/// The _dto service
///
private readonly IJsonSerializer _json;
private readonly IHttpServer _httpServer;
///
/// Initializes a new instance of the class.
///
/// The session manager.
/// The logger factory.
/// The json.
/// The HTTP server.
public SessionWebSocketListener(ISessionManager sessionManager, ILoggerFactory loggerFactory, IJsonSerializer json, IHttpServer httpServer)
{
_sessionManager = sessionManager;
_logger = loggerFactory.CreateLogger(GetType().Name);
_json = json;
_httpServer = httpServer;
httpServer.WebSocketConnected += _serverManager_WebSocketConnected;
}
void _serverManager_WebSocketConnected(object sender, GenericEventArgs e)
{
var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint);
if (session != null)
{
EnsureController(session, e.Argument);
}
else
{
_logger.LogWarning("Unable to determine session based on url: {0}", e.Argument.Url);
}
}
private SessionInfo GetSession(QueryParamCollection queryString, string remoteEndpoint)
{
if (queryString == null)
{
throw new ArgumentNullException(nameof(queryString));
}
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 -= _serverManager_WebSocketConnected;
}
///
/// Processes the message.
///
/// The message.
/// Task.
public Task ProcessMessage(WebSocketMessageInfo message)
{
return Task.CompletedTask;
}
private void EnsureController(SessionInfo session, IWebSocketConnection connection)
{
var controllerInfo = session.EnsureController(s => new WebSocketController(s, _logger, _sessionManager));
var controller = (WebSocketController)controllerInfo.Item1;
controller.AddWebSocket(connection);
}
}
}