From 55c47e50fc261849c277cb65654d91a8c5a8e308 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 8 Mar 2015 15:06:15 -0400 Subject: exclude httplistener from project --- .../Session/SessionWebSocketListener.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index 36a7fcbd8a..d1bb4b837c 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,5 +1,4 @@ -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; -- cgit v1.2.3 From ccb2dda358a54810d940c0c7ddceb255a82ae947 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 8 Mar 2015 15:48:30 -0400 Subject: connect to socket with access token --- MediaBrowser.Controller/Net/IHttpServer.cs | 5 ++ MediaBrowser.Controller/Net/IServerManager.cs | 7 ++- .../Net/IWebSocketConnection.cs | 14 ++++- .../Net/WebSocketConnectEventArgs.cs | 42 ++++++++++++++ MediaBrowser.Controller/Session/ISessionManager.cs | 7 +++ .../HttpServer/HttpListenerHost.cs | 14 ++++- .../HttpServer/IHttpListener.cs | 8 ++- .../HttpServer/Security/SessionContext.cs | 4 ++ .../SocketSharp/WebSocketSharpListener.cs | 51 +++++++++++++---- .../ServerManager/ServerManager.cs | 16 +++++- .../ServerManager/WebSocketConnection.cs | 15 ++++- .../Session/SessionManager.cs | 20 +++++++ .../Session/SessionWebSocketListener.cs | 65 +++++++++++++++++++++- 13 files changed, 247 insertions(+), 21 deletions(-) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Controller/Net/IHttpServer.cs b/MediaBrowser.Controller/Net/IHttpServer.cs index 315b48b837..37142af194 100644 --- a/MediaBrowser.Controller/Net/IHttpServer.cs +++ b/MediaBrowser.Controller/Net/IHttpServer.cs @@ -44,6 +44,11 @@ namespace MediaBrowser.Controller.Net /// event EventHandler WebSocketConnected; + /// + /// Occurs when [web socket connecting]. + /// + event EventHandler WebSocketConnecting; + /// /// Inits this instance. /// diff --git a/MediaBrowser.Controller/Net/IServerManager.cs b/MediaBrowser.Controller/Net/IServerManager.cs index d90a0f8ed6..5191a62e31 100644 --- a/MediaBrowser.Controller/Net/IServerManager.cs +++ b/MediaBrowser.Controller/Net/IServerManager.cs @@ -1,4 +1,4 @@ -using MediaBrowser.Common.Net; +using MediaBrowser.Model.Events; using System; using System.Collections.Generic; using System.Threading; @@ -58,5 +58,10 @@ namespace MediaBrowser.Controller.Net /// /// The web socket connections. IEnumerable WebSocketConnections { get; } + + /// + /// Occurs when [web socket connected]. + /// + event EventHandler> WebSocketConnected; } } \ No newline at end of file diff --git a/MediaBrowser.Controller/Net/IWebSocketConnection.cs b/MediaBrowser.Controller/Net/IWebSocketConnection.cs index 37fd6708d9..e21df3c395 100644 --- a/MediaBrowser.Controller/Net/IWebSocketConnection.cs +++ b/MediaBrowser.Controller/Net/IWebSocketConnection.cs @@ -1,5 +1,6 @@ using MediaBrowser.Model.Net; using System; +using System.Collections.Specialized; using System.Threading; using System.Threading.Tasks; @@ -11,7 +12,7 @@ namespace MediaBrowser.Controller.Net /// Occurs when [closed]. /// event EventHandler Closed; - + /// /// Gets the id. /// @@ -24,6 +25,17 @@ namespace MediaBrowser.Controller.Net /// The last activity date. DateTime LastActivityDate { get; } + /// + /// Gets or sets the URL. + /// + /// The URL. + string Url { get; set; } + /// + /// Gets or sets the query string. + /// + /// The query string. + NameValueCollection QueryString { get; set; } + /// /// Gets or sets the receive action. /// diff --git a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs b/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs index 394fcd92ff..ffeaf286e2 100644 --- a/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs +++ b/MediaBrowser.Controller/Net/WebSocketConnectEventArgs.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Specialized; namespace MediaBrowser.Controller.Net { @@ -7,6 +8,16 @@ namespace MediaBrowser.Controller.Net /// public class WebSocketConnectEventArgs : EventArgs { + /// + /// Gets or sets the URL. + /// + /// The URL. + public string Url { get; set; } + /// + /// Gets or sets the query string. + /// + /// The query string. + public NameValueCollection QueryString { get; set; } /// /// Gets or sets the web socket. /// @@ -18,4 +29,35 @@ namespace MediaBrowser.Controller.Net /// The endpoint. public string Endpoint { get; set; } } + + public class WebSocketConnectingEventArgs : EventArgs + { + /// + /// Gets or sets the URL. + /// + /// The URL. + public string Url { get; set; } + /// + /// Gets or sets the endpoint. + /// + /// The endpoint. + public string Endpoint { get; set; } + /// + /// Gets or sets the query string. + /// + /// The query string. + public NameValueCollection QueryString { get; set; } + /// + /// Gets or sets a value indicating whether [allow connection]. + /// + /// true if [allow connection]; otherwise, false. + public bool AllowConnection { get; set; } + + public WebSocketConnectingEventArgs() + { + QueryString = new NameValueCollection(); + AllowConnection = true; + } + } + } diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 4082f56008..b51b590cf7 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -278,6 +278,13 @@ namespace MediaBrowser.Controller.Session /// SessionInfo. SessionInfo GetSession(string deviceId, string client, string version); + /// + /// Gets the session by authentication token. + /// + /// The token. + /// SessionInfo. + SessionInfo GetSessionByAuthenticationToken(string token); + /// /// Logouts the specified access token. /// diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 4727e6035b..f910542063 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -35,6 +35,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer private readonly ContainerAdapter _containerAdapter; public event EventHandler WebSocketConnected; + public event EventHandler WebSocketConnecting; private readonly List _localEndpoints = new List(); @@ -196,7 +197,8 @@ namespace MediaBrowser.Server.Implementations.HttpServer _listener = GetListener(); - _listener.WebSocketHandler = WebSocketHandler; + _listener.WebSocketConnected = OnWebSocketConnected; + _listener.WebSocketConnecting = OnWebSocketConnecting; _listener.ErrorHandler = ErrorHandler; _listener.RequestHandler = RequestHandler; @@ -208,7 +210,15 @@ namespace MediaBrowser.Server.Implementations.HttpServer return new WebSocketSharpListener(_logger, OnRequestReceived, CertificatePath); } - private void WebSocketHandler(WebSocketConnectEventArgs args) + private void OnWebSocketConnecting(WebSocketConnectingEventArgs args) + { + if (WebSocketConnecting != null) + { + WebSocketConnecting(this, args); + } + } + + private void OnWebSocketConnected(WebSocketConnectEventArgs args) { if (WebSocketConnected != null) { diff --git a/MediaBrowser.Server.Implementations/HttpServer/IHttpListener.cs b/MediaBrowser.Server.Implementations/HttpServer/IHttpListener.cs index e77600e938..dc315601f2 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/IHttpListener.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/IHttpListener.cs @@ -24,8 +24,14 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// Gets or sets the web socket handler. /// /// The web socket handler. - Action WebSocketHandler { get; set; } + Action WebSocketConnected { get; set; } + /// + /// Gets or sets the web socket connecting. + /// + /// The web socket connecting. + Action WebSocketConnecting { get; set; } + /// /// Starts this instance. /// diff --git a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs index 9d1ddb7fc4..954db3a9d8 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -23,6 +23,10 @@ namespace MediaBrowser.Server.Implementations.HttpServer.Security { var authorization = _authContext.GetAuthorizationInfo(requestContext); + if (!string.IsNullOrWhiteSpace(authorization.Token)) + { + return _sessionManager.GetSessionByAuthenticationToken(authorization.Token); + } return _sessionManager.GetSession(authorization.DeviceId, authorization.Client, authorization.Version); } diff --git a/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs b/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs index 0c5c9e9bf1..a223cf68d0 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/SocketSharp/WebSocketSharpListener.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Net; +using System.Collections.Specialized; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.Logging; using MediaBrowser.Server.Implementations.Logging; using ServiceStack; @@ -18,9 +19,9 @@ namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp private readonly ILogger _logger; private readonly Action _endpointListener; - private readonly string _certificatePath ; + private readonly string _certificatePath; - public WebSocketSharpListener(ILogger logger, Action endpointListener, + public WebSocketSharpListener(ILogger logger, Action endpointListener, string certificatePath) { _logger = logger; @@ -32,7 +33,9 @@ namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp public Func RequestHandler { get; set; } - public Action WebSocketHandler { get; set; } + public Action WebSocketConnecting { get; set; } + + public Action WebSocketConnected { get; set; } public void Start(IEnumerable urlPrefixes) { @@ -115,15 +118,43 @@ namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp { try { - var webSocketContext = ctx.AcceptWebSocket(null); + var endpoint = ctx.Request.RemoteEndPoint.ToString(); + var url = ctx.Request.RawUrl; + var queryString = new NameValueCollection(ctx.Request.QueryString); + + var connectingArgs = new WebSocketConnectingEventArgs + { + Url = url, + QueryString = queryString, + Endpoint = endpoint + }; + + if (WebSocketConnecting != null) + { + WebSocketConnecting(connectingArgs); + } - if (WebSocketHandler != null) + if (connectingArgs.AllowConnection) { - WebSocketHandler(new WebSocketConnectEventArgs + _logger.Debug("Web socket connection allowed"); + + var webSocketContext = ctx.AcceptWebSocket(null); + + if (WebSocketConnected != null) { - WebSocket = new SharpWebSocket(webSocketContext.WebSocket, _logger), - Endpoint = ctx.Request.RemoteEndPoint.ToString() - }); + WebSocketConnected(new WebSocketConnectEventArgs + { + Url = url, + QueryString = queryString, + WebSocket = new SharpWebSocket(webSocketContext.WebSocket, _logger), + Endpoint = endpoint + }); + } + } + else + { + _logger.Warn("Web socket connection not allowed"); + ctx.Response.Close(); } } catch (Exception ex) diff --git a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs b/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs index dcfb9c4490..6428d10a97 100644 --- a/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs +++ b/MediaBrowser.Server.Implementations/ServerManager/ServerManager.cs @@ -1,11 +1,14 @@ -using MediaBrowser.Controller; +using MediaBrowser.Common.Events; +using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Events; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; +using System.Collections.Specialized; using System.Linq; using System.Net.Sockets; using System.Threading; @@ -44,6 +47,8 @@ namespace MediaBrowser.Server.Implementations.ServerManager get { return _webSocketConnections; } } + public event EventHandler> WebSocketConnected; + /// /// The _logger /// @@ -140,10 +145,17 @@ namespace MediaBrowser.Server.Implementations.ServerManager { var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger) { - OnReceive = ProcessWebSocketMessageReceived + OnReceive = ProcessWebSocketMessageReceived, + Url = e.Url, + QueryString = new NameValueCollection(e.QueryString) }; _webSocketConnections.Add(connection); + + if (WebSocketConnected != null) + { + EventHelper.FireEventIfNotNull(WebSocketConnected, this, new GenericEventArgs (connection), _logger); + } } /// diff --git a/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs b/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs index 08e4c2ec2e..738e82bd02 100644 --- a/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs +++ b/MediaBrowser.Server.Implementations/ServerManager/WebSocketConnection.cs @@ -1,10 +1,10 @@ -using System.Text; -using MediaBrowser.Common.Events; +using MediaBrowser.Common.Events; using MediaBrowser.Controller.Net; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Serialization; using System; +using System.Collections.Specialized; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -66,6 +66,17 @@ namespace MediaBrowser.Server.Implementations.ServerManager /// The id. public Guid Id { get; private set; } + /// + /// Gets or sets the URL. + /// + /// The URL. + public string Url { get; set; } + /// + /// Gets or sets the query string. + /// + /// The query string. + public NameValueCollection QueryString { get; set; } + /// /// Initializes a new instance of the class. /// diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 8eef8536ab..a09f585fd4 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -1640,6 +1640,26 @@ namespace MediaBrowser.Server.Implementations.Session string.Equals(i.Client, client)); } + public SessionInfo GetSessionByAuthenticationToken(string token) + { + var result = _authRepo.Get(new AuthenticationInfoQuery + { + AccessToken = token + }); + + if (result.Items.Length == 0) + { + return null; + } + + var info = result.Items[0]; + + // TODO: Make Token part of SessionInfo and get result that way + // This can't be done until all apps are updated to new authentication. + return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, info.DeviceId) && + string.Equals(i.Client, info.AppName)); + } + public Task SendMessageToUserSessions(string userId, string name, T data, CancellationToken cancellationToken) { diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index d1bb4b837c..b581f9144e 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,9 +1,12 @@ using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Events; using MediaBrowser.Model.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; @@ -13,7 +16,7 @@ namespace MediaBrowser.Server.Implementations.Session /// /// Class SessionWebSocketListener /// - public class SessionWebSocketListener : IWebSocketListener + public class SessionWebSocketListener : IWebSocketListener, IDisposable { /// /// The _true task result @@ -35,17 +38,75 @@ namespace MediaBrowser.Server.Implementations.Session /// private readonly IJsonSerializer _json; + private readonly IHttpServer _httpServer; + private readonly IServerManager _serverManager; + + /// /// Initializes a new instance of the class. /// /// The session manager. /// The log manager. /// The json. - public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json) + /// The HTTP server. + /// The server manager. + public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json, IHttpServer httpServer, IServerManager serverManager) { _sessionManager = sessionManager; _logger = logManager.GetLogger(GetType().Name); _json = json; + _httpServer = httpServer; + _serverManager = serverManager; + httpServer.WebSocketConnecting += _httpServer_WebSocketConnecting; + serverManager.WebSocketConnected += _serverManager_WebSocketConnected; + } + + void _serverManager_WebSocketConnected(object sender, GenericEventArgs e) + { + var session = GetSession(e.Argument.QueryString); + + if (session != null) + { + var controller = session.SessionController as WebSocketController; + + if (controller == null) + { + controller = new WebSocketController(session, _logger, _sessionManager); + } + + controller.AddWebSocket(e.Argument); + + session.SessionController = controller; + } + else + { + _logger.Warn("Unable to determine session based on url: {0}", e.Argument.Url); + } + } + + void _httpServer_WebSocketConnecting(object sender, WebSocketConnectingEventArgs e) + { + if (e.QueryString.AllKeys.Contains("api_key", StringComparer.OrdinalIgnoreCase)) + { + var session = GetSession(e.QueryString); + + if (session == null) + { + e.AllowConnection = false; + } + } + } + + private SessionInfo GetSession(NameValueCollection queryString) + { + var token = queryString["api_key"]; + return _sessionManager.GetSessionByAuthenticationToken(token); + } + + public void Dispose() + { + _httpServer.WebSocketConnecting -= _httpServer_WebSocketConnecting; + _serverManager.WebSocketConnected -= _serverManager_WebSocketConnected; } /// -- cgit v1.2.3 From 1b46fb62c48c86e5f9aed9426a90702e2d392bb6 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 9 Mar 2015 15:40:03 -0400 Subject: fix session not found errors --- MediaBrowser.Api/BaseApiService.cs | 7 +- MediaBrowser.Api/LiveTv/LiveTvService.cs | 2 +- MediaBrowser.Api/Session/SessionsService.cs | 18 ++--- MediaBrowser.Api/UserLibrary/PlaystateService.cs | 10 +-- MediaBrowser.Controller/Net/ISessionContext.cs | 11 +-- MediaBrowser.Controller/Session/ISessionManager.cs | 13 +++- .../HttpServer/Security/SessionContext.cs | 30 +++++--- .../Session/SessionManager.cs | 89 +++++++++++++--------- .../Session/SessionWebSocketListener.cs | 13 ++-- 9 files changed, 118 insertions(+), 75 deletions(-) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs index dff433c9dc..91e1c7d9a1 100644 --- a/MediaBrowser.Api/BaseApiService.cs +++ b/MediaBrowser.Api/BaseApiService.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Dto; +using System.Threading.Tasks; +using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; @@ -88,9 +89,9 @@ namespace MediaBrowser.Api /// Gets the session. /// /// SessionInfo. - protected SessionInfo GetSession() + protected async Task GetSession() { - var session = SessionContext.GetSession(Request); + var session = await SessionContext.GetSession(Request).ConfigureAwait(false); if (session == null) { diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index fe21b9ada1..f3fd8f42a6 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -315,7 +315,7 @@ namespace MediaBrowser.Api.LiveTv private void AssertUserCanManageLiveTv() { - var user = SessionContext.GetUser(Request); + var user = SessionContext.GetUser(Request).Result; if (user == null) { diff --git a/MediaBrowser.Api/Session/SessionsService.cs b/MediaBrowser.Api/Session/SessionsService.cs index 319b3d28c6..52ecb95ec6 100644 --- a/MediaBrowser.Api/Session/SessionsService.cs +++ b/MediaBrowser.Api/Session/SessionsService.cs @@ -418,7 +418,7 @@ namespace MediaBrowser.Api.Session SeekPositionTicks = request.SeekPositionTicks }; - var task = _sessionManager.SendPlaystateCommand(GetSession().Id, request.Id, command, CancellationToken.None); + var task = _sessionManager.SendPlaystateCommand(GetSession().Result.Id, request.Id, command, CancellationToken.None); Task.WaitAll(task); } @@ -436,7 +436,7 @@ namespace MediaBrowser.Api.Session ItemType = request.ItemType }; - var task = _sessionManager.SendBrowseCommand(GetSession().Id, request.Id, command, CancellationToken.None); + var task = _sessionManager.SendBrowseCommand(GetSession().Result.Id, request.Id, command, CancellationToken.None); Task.WaitAll(task); } @@ -455,7 +455,7 @@ namespace MediaBrowser.Api.Session name = commandType.ToString(); } - var currentSession = GetSession(); + var currentSession = GetSession().Result; var command = new GeneralCommand { @@ -481,7 +481,7 @@ namespace MediaBrowser.Api.Session Text = request.Text }; - var task = _sessionManager.SendMessageCommand(GetSession().Id, request.Id, command, CancellationToken.None); + var task = _sessionManager.SendMessageCommand(GetSession().Result.Id, request.Id, command, CancellationToken.None); Task.WaitAll(task); } @@ -500,14 +500,14 @@ namespace MediaBrowser.Api.Session StartPositionTicks = request.StartPositionTicks }; - var task = _sessionManager.SendPlayCommand(GetSession().Id, request.Id, command, CancellationToken.None); + var task = _sessionManager.SendPlayCommand(GetSession().Result.Id, request.Id, command, CancellationToken.None); Task.WaitAll(task); } public void Post(SendGeneralCommand request) { - var currentSession = GetSession(); + var currentSession = GetSession().Result; var command = new GeneralCommand { @@ -522,7 +522,7 @@ namespace MediaBrowser.Api.Session public void Post(SendFullGeneralCommand request) { - var currentSession = GetSession(); + var currentSession = GetSession().Result; request.ControllingUserId = currentSession.UserId.HasValue ? currentSession.UserId.Value.ToString("N") : null; @@ -545,7 +545,7 @@ namespace MediaBrowser.Api.Session { if (string.IsNullOrWhiteSpace(request.Id)) { - request.Id = GetSession().Id; + request.Id = GetSession().Result.Id; } _sessionManager.ReportCapabilities(request.Id, new ClientCapabilities { @@ -569,7 +569,7 @@ namespace MediaBrowser.Api.Session { if (string.IsNullOrWhiteSpace(request.Id)) { - request.Id = GetSession().Id; + request.Id = GetSession().Result.Id; } _sessionManager.ReportCapabilities(request.Id, request); } diff --git a/MediaBrowser.Api/UserLibrary/PlaystateService.cs b/MediaBrowser.Api/UserLibrary/PlaystateService.cs index fae83e3692..55e1681e0d 100644 --- a/MediaBrowser.Api/UserLibrary/PlaystateService.cs +++ b/MediaBrowser.Api/UserLibrary/PlaystateService.cs @@ -231,7 +231,7 @@ namespace MediaBrowser.Api.UserLibrary datePlayed = DateTime.ParseExact(request.DatePlayed, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); } - var session = GetSession(); + var session = await GetSession().ConfigureAwait(false); var dto = await UpdatePlayedStatus(user, request.Id, true, datePlayed).ConfigureAwait(false); @@ -266,7 +266,7 @@ namespace MediaBrowser.Api.UserLibrary public void Post(ReportPlaybackStart request) { - request.SessionId = GetSession().Id; + request.SessionId = GetSession().Result.Id; var task = _sessionManager.OnPlaybackStart(request); @@ -294,7 +294,7 @@ namespace MediaBrowser.Api.UserLibrary public void Post(ReportPlaybackProgress request) { - request.SessionId = GetSession().Id; + request.SessionId = GetSession().Result.Id; var task = _sessionManager.OnPlaybackProgress(request); @@ -317,7 +317,7 @@ namespace MediaBrowser.Api.UserLibrary public void Post(ReportPlaybackStopped request) { - request.SessionId = GetSession().Id; + request.SessionId = GetSession().Result.Id; var task = _sessionManager.OnPlaybackStopped(request); @@ -339,7 +339,7 @@ namespace MediaBrowser.Api.UserLibrary { var user = _userManager.GetUserById(request.UserId); - var session = GetSession(); + var session = await GetSession().ConfigureAwait(false); var dto = await UpdatePlayedStatus(user, request.Id, false, null).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/Net/ISessionContext.cs b/MediaBrowser.Controller/Net/ISessionContext.cs index be8d28acc6..167e178671 100644 --- a/MediaBrowser.Controller/Net/ISessionContext.cs +++ b/MediaBrowser.Controller/Net/ISessionContext.cs @@ -1,14 +1,15 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Session; +using System.Threading.Tasks; namespace MediaBrowser.Controller.Net { public interface ISessionContext { - SessionInfo GetSession(object requestContext); - User GetUser(object requestContext); - - SessionInfo GetSession(IServiceRequest requestContext); - User GetUser(IServiceRequest requestContext); + Task GetSession(object requestContext); + Task GetUser(object requestContext); + + Task GetSession(IServiceRequest requestContext); + Task GetUser(IServiceRequest requestContext); } } diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index b51b590cf7..234a823460 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -1,5 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Security; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Events; using MediaBrowser.Model.Session; @@ -282,8 +283,18 @@ namespace MediaBrowser.Controller.Session /// Gets the session by authentication token. /// /// The token. + /// The remote endpoint. /// SessionInfo. - SessionInfo GetSessionByAuthenticationToken(string token); + Task GetSessionByAuthenticationToken(string token, string remoteEndpoint); + + /// + /// Gets the session by authentication token. + /// + /// The information. + /// The remote endpoint. + /// The application version. + /// Task<SessionInfo>. + Task GetSessionByAuthenticationToken(AuthenticationInfo info, string remoteEndpoint, string appVersion); /// /// Logouts the specified access token. diff --git a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs index 954db3a9d8..0557f7528d 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -1,8 +1,10 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; +using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; using ServiceStack.Web; +using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.HttpServer.Security { @@ -19,31 +21,41 @@ namespace MediaBrowser.Server.Implementations.HttpServer.Security _sessionManager = sessionManager; } - public SessionInfo GetSession(IServiceRequest requestContext) + public Task GetSession(IServiceRequest requestContext) { var authorization = _authContext.GetAuthorizationInfo(requestContext); if (!string.IsNullOrWhiteSpace(authorization.Token)) { - return _sessionManager.GetSessionByAuthenticationToken(authorization.Token); + var auth = GetTokenInfo(requestContext); + return _sessionManager.GetSessionByAuthenticationToken(auth, requestContext.RemoteIp, authorization.Version); } - return _sessionManager.GetSession(authorization.DeviceId, authorization.Client, authorization.Version); + + var session = _sessionManager.GetSession(authorization.DeviceId, authorization.Client, authorization.Version); + return Task.FromResult(session); } - public User GetUser(IServiceRequest requestContext) + private AuthenticationInfo GetTokenInfo(IServiceRequest request) { - var session = GetSession(requestContext); - - return session == null || !session.UserId.HasValue ? null : _userManager.GetUserById(session.UserId.Value); + object info; + request.Items.TryGetValue("OriginalAuthenticationInfo", out info); + return info as AuthenticationInfo; } - public SessionInfo GetSession(object requestContext) + public Task GetSession(object requestContext) { var req = new ServiceStackServiceRequest((IRequest)requestContext); return GetSession(req); } - public User GetUser(object requestContext) + public async Task GetUser(IServiceRequest requestContext) + { + var session = await GetSession(requestContext).ConfigureAwait(false); + + return session == null || !session.UserId.HasValue ? null : _userManager.GetUserById(session.UserId.Value); + } + + public Task GetUser(object requestContext) { var req = new ServiceStackServiceRequest((IRequest)requestContext); return GetUser(req); diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index a09f585fd4..2e28862e9e 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -237,10 +237,7 @@ namespace MediaBrowser.Server.Implementations.Session var activityDate = DateTime.UtcNow; - var userId = user == null ? (Guid?)null : user.Id; - var username = user == null ? null : user.Name; - - var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, userId, username).ConfigureAwait(false); + var session = await GetSessionInfo(clientType, appVersion, deviceId, deviceName, remoteEndPoint, user).ConfigureAwait(false); session.LastActivityDate = activityDate; @@ -281,7 +278,7 @@ namespace MediaBrowser.Server.Implementations.Session if (session != null) { - var key = GetSessionKey(session.Client, session.ApplicationVersion, session.DeviceId); + var key = GetSessionKey(session.Client, session.DeviceId); SessionInfo removed; @@ -365,7 +362,7 @@ namespace MediaBrowser.Server.Implementations.Session } } - private string GetSessionKey(string clientType, string appVersion, string deviceId) + private string GetSessionKey(string clientType, string deviceId) { return clientType + deviceId; } @@ -378,29 +375,31 @@ namespace MediaBrowser.Server.Implementations.Session /// The device id. /// Name of the device. /// The remote end point. - /// The user identifier. - /// The username. + /// The user. /// SessionInfo. - private async Task GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, Guid? userId, string username) + private async Task GetSessionInfo(string clientType, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user) { - var key = GetSessionKey(clientType, appVersion, deviceId); + var key = GetSessionKey(clientType, deviceId); await _sessionLock.WaitAsync(CancellationToken.None).ConfigureAwait(false); + var userId = user == null ? (Guid?)null : user.Id; + var username = user == null ? null : user.Name; + try { - SessionInfo connection; + SessionInfo sessionInfo; DeviceInfo device = null; - if (!_activeConnections.TryGetValue(key, out connection)) + if (!_activeConnections.TryGetValue(key, out sessionInfo)) { - var sessionInfo = new SessionInfo - { - Client = clientType, - DeviceId = deviceId, - ApplicationVersion = appVersion, - Id = key.GetMD5().ToString("N") - }; + sessionInfo = new SessionInfo + { + Client = clientType, + DeviceId = deviceId, + ApplicationVersion = appVersion, + Id = key.GetMD5().ToString("N") + }; sessionInfo.DeviceName = deviceName; sessionInfo.UserId = userId; @@ -410,7 +409,6 @@ namespace MediaBrowser.Server.Implementations.Session OnSessionStarted(sessionInfo); _activeConnections.TryAdd(key, sessionInfo); - connection = sessionInfo; if (!string.IsNullOrEmpty(deviceId)) { @@ -426,24 +424,25 @@ namespace MediaBrowser.Server.Implementations.Session deviceName = device.CustomName; } - connection.DeviceName = deviceName; - connection.UserId = userId; - connection.UserName = username; - connection.RemoteEndPoint = remoteEndPoint; + sessionInfo.DeviceName = deviceName; + sessionInfo.UserId = userId; + sessionInfo.UserName = username; + sessionInfo.RemoteEndPoint = remoteEndPoint; + sessionInfo.ApplicationVersion = appVersion; if (!userId.HasValue) { - connection.AdditionalUsers.Clear(); + sessionInfo.AdditionalUsers.Clear(); } - if (connection.SessionController == null) + if (sessionInfo.SessionController == null) { - connection.SessionController = _sessionFactories - .Select(i => i.GetSessionController(connection)) + sessionInfo.SessionController = _sessionFactories + .Select(i => i.GetSessionController(sessionInfo)) .FirstOrDefault(i => i != null); } - return connection; + return sessionInfo; } finally { @@ -920,7 +919,7 @@ namespace MediaBrowser.Server.Implementations.Session return FilterToSingleMediaType(items) .OrderBy(i => i.SortName); } - + if (item.IsFolder) { var folder = (Folder)item; @@ -1640,7 +1639,25 @@ namespace MediaBrowser.Server.Implementations.Session string.Equals(i.Client, client)); } - public SessionInfo GetSessionByAuthenticationToken(string token) + public Task GetSessionByAuthenticationToken(AuthenticationInfo info, string remoteEndpoint, string appVersion) + { + if (info == null) + { + throw new ArgumentNullException("info"); + } + + var user = string.IsNullOrWhiteSpace(info.UserId) + ? null + : _userManager.GetUserById(info.UserId); + + appVersion = string.IsNullOrWhiteSpace(appVersion) + ? "1" + : appVersion; + + return GetSessionInfo(info.AppName, appVersion, info.DeviceId, info.DeviceName, remoteEndpoint, user); + } + + public Task GetSessionByAuthenticationToken(string token, string remoteEndpoint) { var result = _authRepo.Get(new AuthenticationInfoQuery { @@ -1654,10 +1671,12 @@ namespace MediaBrowser.Server.Implementations.Session var info = result.Items[0]; - // TODO: Make Token part of SessionInfo and get result that way - // This can't be done until all apps are updated to new authentication. - return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, info.DeviceId) && - string.Equals(i.Client, info.AppName)); + if (info == null) + { + return null; + } + + return GetSessionByAuthenticationToken(info, remoteEndpoint, null); } public Task SendMessageToUserSessions(string userId, string name, T data, diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index b581f9144e..72ec16f85d 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -1,5 +1,4 @@ using MediaBrowser.Controller.Net; -using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Session; using MediaBrowser.Model.Events; using MediaBrowser.Model.Logging; @@ -61,9 +60,9 @@ namespace MediaBrowser.Server.Implementations.Session serverManager.WebSocketConnected += _serverManager_WebSocketConnected; } - void _serverManager_WebSocketConnected(object sender, GenericEventArgs e) + async void _serverManager_WebSocketConnected(object sender, GenericEventArgs e) { - var session = GetSession(e.Argument.QueryString); + var session = await GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint).ConfigureAwait(false); if (session != null) { @@ -84,11 +83,11 @@ namespace MediaBrowser.Server.Implementations.Session } } - void _httpServer_WebSocketConnecting(object sender, WebSocketConnectingEventArgs e) + async void _httpServer_WebSocketConnecting(object sender, WebSocketConnectingEventArgs e) { if (e.QueryString.AllKeys.Contains("api_key", StringComparer.OrdinalIgnoreCase)) { - var session = GetSession(e.QueryString); + var session = await GetSession(e.QueryString, e.Endpoint).ConfigureAwait(false); if (session == null) { @@ -97,10 +96,10 @@ namespace MediaBrowser.Server.Implementations.Session } } - private SessionInfo GetSession(NameValueCollection queryString) + private Task GetSession(NameValueCollection queryString, string remoteEndpoint) { var token = queryString["api_key"]; - return _sessionManager.GetSessionByAuthenticationToken(token); + return _sessionManager.GetSessionByAuthenticationToken(token, remoteEndpoint); } public void Dispose() -- cgit v1.2.3 From a11c4d0b0872096dadcedc321d600c5e4d31db90 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 9 Mar 2015 21:47:52 -0400 Subject: fix null reference in web socket connection --- .../Session/SessionWebSocketListener.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index 72ec16f85d..7cbff9768d 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -99,6 +99,10 @@ namespace MediaBrowser.Server.Implementations.Session private Task GetSession(NameValueCollection queryString, string remoteEndpoint) { var token = queryString["api_key"]; + if (string.IsNullOrWhiteSpace(token)) + { + return Task.FromResult(null); + } return _sessionManager.GetSessionByAuthenticationToken(token, remoteEndpoint); } -- cgit v1.2.3 From 0ec38a9d40a015af87b19cf345e0dfb1e433b45d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 12 Mar 2015 21:55:22 -0400 Subject: adjust audio direct play checks --- MediaBrowser.Controller/Session/ISessionManager.cs | 6 +- MediaBrowser.Model/Dlna/StreamBuilder.cs | 119 ++++++++++++--------- MediaBrowser.Providers/Manager/ProviderUtils.cs | 2 +- .../MediaInfo/FFProbeAudioInfo.cs | 13 ++- .../HttpServer/Security/SessionContext.cs | 2 +- .../Session/SessionManager.cs | 24 ++++- .../Session/SessionWebSocketListener.cs | 3 +- 7 files changed, 109 insertions(+), 60 deletions(-) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Controller/Session/ISessionManager.cs b/MediaBrowser.Controller/Session/ISessionManager.cs index 234a823460..bddc035e08 100644 --- a/MediaBrowser.Controller/Session/ISessionManager.cs +++ b/MediaBrowser.Controller/Session/ISessionManager.cs @@ -283,18 +283,20 @@ namespace MediaBrowser.Controller.Session /// Gets the session by authentication token. /// /// The token. + /// The device identifier. /// The remote endpoint. /// SessionInfo. - Task GetSessionByAuthenticationToken(string token, string remoteEndpoint); + Task GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint); /// /// Gets the session by authentication token. /// /// The information. + /// The device identifier. /// The remote endpoint. /// The application version. /// Task<SessionInfo>. - Task GetSessionByAuthenticationToken(AuthenticationInfo info, string remoteEndpoint, string appVersion); + Task GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion); /// /// Logouts the specified access token. diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 126b218e82..07c7ecd8bc 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -138,72 +138,60 @@ namespace MediaBrowser.Model.Dlna DeviceProfile = options.Profile }; - int? maxBitrateSetting = options.GetMaxBitrate(); - - MediaStream audioStream = item.DefaultAudioStream; + List directPlayMethods = GetAudioDirectPlayMethods(item, options); - // Honor the max bitrate setting - if (IsAudioEligibleForDirectPlay(item, maxBitrateSetting)) + if (directPlayMethods.Count > 0) { - DirectPlayProfile directPlay = null; - foreach (DirectPlayProfile i in options.Profile.DirectPlayProfiles) - { - if (i.Type == playlistItem.MediaType && IsAudioDirectPlaySupported(i, item, audioStream)) - { - directPlay = i; - break; - } - } + MediaStream audioStream = item.DefaultAudioStream; - if (directPlay != null) + string audioCodec = audioStream == null ? null : audioStream.Codec; + + // Make sure audio codec profiles are satisfied + if (!string.IsNullOrEmpty(audioCodec)) { - string audioCodec = audioStream == null ? null : audioStream.Codec; + ConditionProcessor conditionProcessor = new ConditionProcessor(); - // Make sure audio codec profiles are satisfied - if (!string.IsNullOrEmpty(audioCodec)) + List conditions = new List(); + foreach (CodecProfile i in options.Profile.CodecProfiles) { - ConditionProcessor conditionProcessor = new ConditionProcessor(); - - List conditions = new List(); - foreach (CodecProfile i in options.Profile.CodecProfiles) + if (i.Type == CodecType.Audio && i.ContainsCodec(audioCodec)) { - if (i.Type == CodecType.Audio && i.ContainsCodec(audioCodec)) + foreach (ProfileCondition c in i.Conditions) { - foreach (ProfileCondition c in i.Conditions) - { - conditions.Add(c); - } + conditions.Add(c); } } + } - int? audioChannels = audioStream.Channels; - int? audioBitrate = audioStream.BitRate; + int? audioChannels = audioStream.Channels; + int? audioBitrate = audioStream.BitRate; - bool all = true; - foreach (ProfileCondition c in conditions) + bool all = true; + foreach (ProfileCondition c in conditions) + { + if (!conditionProcessor.IsAudioConditionSatisfied(c, audioChannels, audioBitrate)) { - if (!conditionProcessor.IsAudioConditionSatisfied(c, audioChannels, audioBitrate)) - { - all = false; - break; - } + all = false; + break; } + } - if (all) + if (all) + { + if (item.Protocol == MediaProtocol.File && + directPlayMethods.Contains(PlayMethod.DirectPlay) && + _localPlayer.CanAccessFile(item.Path)) { - if (item.Protocol == MediaProtocol.File && _localPlayer.CanAccessFile(item.Path)) - { - playlistItem.PlayMethod = PlayMethod.DirectPlay; - } - else - { - playlistItem.PlayMethod = PlayMethod.DirectStream; - } + playlistItem.PlayMethod = PlayMethod.DirectPlay; + } + else if (directPlayMethods.Contains(PlayMethod.DirectStream)) + { + playlistItem.PlayMethod = PlayMethod.DirectStream; + } - playlistItem.Container = item.Container; + playlistItem.Container = item.Container; - return playlistItem; - } + return playlistItem; } } } @@ -272,6 +260,41 @@ namespace MediaBrowser.Model.Dlna return playlistItem; } + private List GetAudioDirectPlayMethods(MediaSourceInfo item, AudioOptions options) + { + MediaStream audioStream = item.DefaultAudioStream; + + DirectPlayProfile directPlayProfile = null; + foreach (DirectPlayProfile i in options.Profile.DirectPlayProfiles) + { + if (i.Type == DlnaProfileType.Audio && IsAudioDirectPlaySupported(i, item, audioStream)) + { + directPlayProfile = i; + break; + } + } + + List playMethods = new List(); + + if (directPlayProfile != null) + { + // While options takes the network and other factors into account. Only applies to direct stream + if (IsAudioEligibleForDirectPlay(item, options.GetMaxBitrate())) + { + playMethods.Add(PlayMethod.DirectStream); + } + + // The profile describes what the device supports + // If device requirements are satisfied then allow both direct stream and direct play + if (IsAudioEligibleForDirectPlay(item, options.Profile.MaxStaticBitrate)) + { + playMethods.Add(PlayMethod.DirectPlay); + } + } + + return playMethods; + } + private StreamInfo BuildVideoItem(MediaSourceInfo item, VideoOptions options) { StreamInfo playlistItem = new StreamInfo diff --git a/MediaBrowser.Providers/Manager/ProviderUtils.cs b/MediaBrowser.Providers/Manager/ProviderUtils.cs index 155cd208f3..aa92cc2802 100644 --- a/MediaBrowser.Providers/Manager/ProviderUtils.cs +++ b/MediaBrowser.Providers/Manager/ProviderUtils.cs @@ -252,7 +252,7 @@ namespace MediaBrowser.Providers.Manager if (sourceHasAlbumArtist != null && targetHasAlbumArtist != null) { - if (replaceData || targetHasAlbumArtist.AlbumArtists.Count > 0) + if (replaceData || targetHasAlbumArtist.AlbumArtists.Count == 0) { targetHasAlbumArtist.AlbumArtists = sourceHasAlbumArtist.AlbumArtists; } diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs index 39f138c5bc..26d00d5444 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeAudioInfo.cs @@ -210,7 +210,15 @@ namespace MediaBrowser.Providers.MediaInfo } } - var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist") ?? FFProbeHelpers.GetDictionaryValue(tags, "album artist") ?? FFProbeHelpers.GetDictionaryValue(tags, "album_artist"); + var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist"); + if (string.IsNullOrWhiteSpace(albumArtist)) + { + albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist"); + } + if (string.IsNullOrWhiteSpace(albumArtist)) + { + albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist"); + } if (string.IsNullOrWhiteSpace(albumArtist)) { @@ -277,8 +285,7 @@ namespace MediaBrowser.Providers.MediaInfo return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries) .Select(i => i.Trim()) - .Where(i => !string.IsNullOrWhiteSpace(i)) - .FirstOrDefault(); + .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i)); } private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' }; diff --git a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs index 0557f7528d..1bbe9893b8 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/Security/SessionContext.cs @@ -28,7 +28,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer.Security if (!string.IsNullOrWhiteSpace(authorization.Token)) { var auth = GetTokenInfo(requestContext); - return _sessionManager.GetSessionByAuthenticationToken(auth, requestContext.RemoteIp, authorization.Version); + return _sessionManager.GetSessionByAuthenticationToken(auth, authorization.DeviceId, requestContext.RemoteIp, authorization.Version); } var session = _sessionManager.GetSession(authorization.DeviceId, authorization.Client, authorization.Version); diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 2e28862e9e..7c6ab2af64 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -1639,7 +1639,7 @@ namespace MediaBrowser.Server.Implementations.Session string.Equals(i.Client, client)); } - public Task GetSessionByAuthenticationToken(AuthenticationInfo info, string remoteEndpoint, string appVersion) + public Task GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion) { if (info == null) { @@ -1654,10 +1654,26 @@ namespace MediaBrowser.Server.Implementations.Session ? "1" : appVersion; - return GetSessionInfo(info.AppName, appVersion, info.DeviceId, info.DeviceName, remoteEndpoint, user); + var deviceName = info.DeviceName; + + if (!string.IsNullOrWhiteSpace(deviceId)) + { + // Replace the info from the token with more recent info + var device = _deviceManager.GetDevice(deviceId); + if (device != null) + { + deviceName = device.Name; + } + } + else + { + deviceId = info.DeviceId; + } + + return GetSessionInfo(info.AppName, appVersion, deviceId, deviceName, remoteEndpoint, user); } - public Task GetSessionByAuthenticationToken(string token, string remoteEndpoint) + public Task GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint) { var result = _authRepo.Get(new AuthenticationInfoQuery { @@ -1676,7 +1692,7 @@ namespace MediaBrowser.Server.Implementations.Session return null; } - return GetSessionByAuthenticationToken(info, remoteEndpoint, null); + return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null); } public Task SendMessageToUserSessions(string userId, string name, T data, diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index 7cbff9768d..dda4c2b90f 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -103,7 +103,8 @@ namespace MediaBrowser.Server.Implementations.Session { return Task.FromResult(null); } - return _sessionManager.GetSessionByAuthenticationToken(token, remoteEndpoint); + var deviceId = queryString["deviceId"]; + return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint); } public void Dispose() -- cgit v1.2.3 From f988539e13e9f0a4bc206d2b6803520a35b7228e Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 16 Mar 2015 12:47:14 -0400 Subject: update session listener --- MediaBrowser.Api/Playback/MediaInfoService.cs | 35 +++++++++++++++------- .../Session/SessionManager.cs | 9 ++---- .../Session/SessionWebSocketListener.cs | 8 ++++- 3 files changed, 33 insertions(+), 19 deletions(-) (limited to 'MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs') diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index dfb5086b9b..5adb76cc58 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -1,7 +1,10 @@ using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Dlna; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.MediaInfo; using ServiceStack; +using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -38,24 +41,34 @@ namespace MediaBrowser.Api.Playback _mediaSourceManager = mediaSourceManager; } - public async Task Get(GetPlaybackInfo request) + public Task Get(GetPlaybackInfo request) { - var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(request.Id, request.UserId, true, CancellationToken.None).ConfigureAwait(false); + return GetPlaybackInfo(request.Id, request.UserId); + } - return ToOptimizedResult(new LiveMediaInfoResult - { - MediaSources = mediaSources.ToList() - }); + public Task Get(GetLiveMediaInfo request) + { + return GetPlaybackInfo(request.Id, request.UserId); } - public async Task Get(GetLiveMediaInfo request) + private async Task GetPlaybackInfo(string id, string userId) { - var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(request.Id, request.UserId, true, CancellationToken.None).ConfigureAwait(false); + IEnumerable mediaSources; + var result = new LiveMediaInfoResult(); - return ToOptimizedResult(new LiveMediaInfoResult + try { - MediaSources = mediaSources.ToList() - }); + mediaSources = await _mediaSourceManager.GetPlayackMediaSources(id, userId, true, CancellationToken.None).ConfigureAwait(false); + } + catch (PlaybackException ex) + { + mediaSources = new List(); + result.ErrorCode = ex.ErrorCode; + } + + result.MediaSources = mediaSources.ToList(); + + return ToOptimizedResult(result); } } } diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 76e97ff485..8a21ed6bdd 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -1687,16 +1687,11 @@ namespace MediaBrowser.Server.Implementations.Session AccessToken = token }); - if (result.Items.Length == 0) - { - return null; - } - - var info = result.Items[0]; + var info = result.Items.FirstOrDefault(); if (info == null) { - return null; + return Task.FromResult(null); } return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null); diff --git a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs index dda4c2b90f..b8cab0c199 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionWebSocketListener.cs @@ -85,7 +85,8 @@ namespace MediaBrowser.Server.Implementations.Session async void _httpServer_WebSocketConnecting(object sender, WebSocketConnectingEventArgs e) { - if (e.QueryString.AllKeys.Contains("api_key", StringComparer.OrdinalIgnoreCase)) + var token = e.QueryString["api_key"]; + if (!string.IsNullOrWhiteSpace(token)) { var session = await GetSession(e.QueryString, e.Endpoint).ConfigureAwait(false); @@ -98,6 +99,11 @@ namespace MediaBrowser.Server.Implementations.Session private Task GetSession(NameValueCollection queryString, string remoteEndpoint) { + if (queryString == null) + { + throw new ArgumentNullException("queryString"); + } + var token = queryString["api_key"]; if (string.IsNullOrWhiteSpace(token)) { -- cgit v1.2.3