progress on remote control

This commit is contained in:
Luke Pulverenti 2013-05-10 08:18:07 -04:00
parent 35a7986b3f
commit 44f33fdb55
16 changed files with 335 additions and 73 deletions

View File

@ -1,9 +1,13 @@
using MediaBrowser.Controller.Dto; using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Session; using MediaBrowser.Model.Session;
using ServiceStack.ServiceHost; using ServiceStack.ServiceHost;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
namespace MediaBrowser.Api namespace MediaBrowser.Api
{ {
@ -14,11 +18,39 @@ namespace MediaBrowser.Api
[Api(("Gets a list of sessions"))] [Api(("Gets a list of sessions"))]
public class GetSessions : IReturn<List<SessionInfoDto>> public class GetSessions : IReturn<List<SessionInfoDto>>
{ {
[ApiMember(Name = "SupportsRemoteControl", Description = "Optional. Filter by sessions that can be remote controlled.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
public bool? SupportsRemoteControl { get; set; }
}
[Route("/Sessions/{Id}/Viewing", "POST")]
[Api(("Instructs a session to browse to an item or view"))]
public class BrowseTo : IReturnVoid
{
[ApiMember(Name = "Id", Description = "Session Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public Guid Id { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether this instance is recent. /// Artist, Genre, Studio, Person, or any kind of BaseItem
/// </summary> /// </summary>
/// <value><c>true</c> if this instance is recent; otherwise, <c>false</c>.</value> /// <value>The type of the item.</value>
public bool IsRecent { get; set; } [ApiMember(Name = "ItemType", Description = "Only required if the item is an Artist, Genre, Studio, or Person.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string ItemType { get; set; }
/// <summary>
/// Artist name, genre name, item Id, etc
/// </summary>
/// <value>The item identifier.</value>
[ApiMember(Name = "ItemIdentifier", Description = "The Id of the item, unless it is an Artist, Genre, Studio, or Person, in which case it should be the name.", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
public string ItemIdentifier { get; set; }
/// <summary>
/// Gets or sets the context (Movies, Music, TvShows, etc)
/// Applicable to genres, studios and persons only because the context of items and artists can be inferred.
/// This is optional to supply and clients are free to ignore it.
/// </summary>
/// <value>The context.</value>
[ApiMember(Name = "Context", Description = "The navigation context for the client (movies, music, tvshows, games etc). This is optional to supply and clients are free to ignore it.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string Context { get; set; }
} }
/// <summary> /// <summary>
@ -47,9 +79,31 @@ namespace MediaBrowser.Api
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
public object Get(GetSessions request) public object Get(GetSessions request)
{ {
var result = request.IsRecent ? _sessionManager.RecentConnections : _sessionManager.AllConnections; var result = _sessionManager.Sessions.Where(i => i.IsActive);
if (request.SupportsRemoteControl.HasValue)
{
result = result.Where(i => i.IsActive == request.SupportsRemoteControl.Value);
}
return ToOptimizedResult(result.Select(SessionInfoDtoBuilder.GetSessionInfoDto).ToList()); return ToOptimizedResult(result.Select(SessionInfoDtoBuilder.GetSessionInfoDto).ToList());
} }
public void Post(BrowseTo request)
{
var session = _sessionManager.Sessions.FirstOrDefault(i => i.Id == request.Id);
if (session == null)
{
throw new ResourceNotFoundException(string.Format("Session {0} not found.", request.Id));
}
session.WebSocket.SendAsync(new WebSocketMessage<BrowseTo>
{
MessageType = "Browse",
Data = request
}, CancellationToken.None);
}
} }
} }

View File

@ -262,6 +262,9 @@ namespace MediaBrowser.Api.UserLibrary
/// <value>The position ticks.</value> /// <value>The position ticks.</value>
[ApiMember(Name = "PositionTicks", Description = "Optional. The current position, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")] [ApiMember(Name = "PositionTicks", Description = "Optional. The current position, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
public long? PositionTicks { get; set; } public long? PositionTicks { get; set; }
[ApiMember(Name = "IsPaused", Description = "Indicates if the player is paused.", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "POST")]
public bool IsPaused { get; set; }
} }
/// <summary> /// <summary>
@ -715,7 +718,7 @@ namespace MediaBrowser.Api.UserLibrary
if (auth != null) if (auth != null)
{ {
var task = _sessionManager.OnPlaybackProgress(user, item, request.PositionTicks, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty); var task = _sessionManager.OnPlaybackProgress(user, item, request.PositionTicks, request.IsPaused, auth["Client"], auth["DeviceId"], auth["Device"] ?? string.Empty);
Task.WaitAll(task); Task.WaitAll(task);
} }

View File

@ -1,5 +1,4 @@
using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Session; using MediaBrowser.Model.Session;
namespace MediaBrowser.Controller.Dto namespace MediaBrowser.Controller.Dto
@ -23,7 +22,12 @@ namespace MediaBrowser.Controller.Dto
DeviceName = session.DeviceName, DeviceName = session.DeviceName,
Id = session.Id, Id = session.Id,
LastActivityDate = session.LastActivityDate, LastActivityDate = session.LastActivityDate,
NowPlayingPositionTicks = session.NowPlayingPositionTicks NowPlayingPositionTicks = session.NowPlayingPositionTicks,
SupportsRemoteControl = session.SupportsRemoteControl,
IsPaused = session.IsPaused,
NowViewingContext = session.NowViewingContext,
NowViewingItemIdentifier = session.NowViewingItemIdentifier,
NowViewingItemType = session.NowViewingItemType
}; };
if (session.NowPlayingItem != null) if (session.NowPlayingItem != null)
@ -36,9 +40,6 @@ namespace MediaBrowser.Controller.Dto
dto.UserId = session.UserId.Value.ToString("N"); dto.UserId = session.UserId.Value.ToString("N");
} }
dto.SupportsRemoteControl = session.WebSocket != null &&
session.WebSocket.State == WebSocketState.Open;
return dto; return dto;
} }
} }

View File

@ -3,7 +3,6 @@ using MediaBrowser.Controller.Library;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Model.Session;
namespace MediaBrowser.Controller.Session namespace MediaBrowser.Controller.Session
{ {
@ -28,16 +27,10 @@ namespace MediaBrowser.Controller.Session
event EventHandler<PlaybackProgressEventArgs> PlaybackStopped; event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
/// <summary> /// <summary>
/// Gets all connections. /// Gets the sessions.
/// </summary> /// </summary>
/// <value>All connections.</value> /// <value>The sessions.</value>
IEnumerable<SessionInfo> AllConnections { get; } IEnumerable<SessionInfo> Sessions { get; }
/// <summary>
/// Gets the active connections.
/// </summary>
/// <value>The active connections.</value>
IEnumerable<SessionInfo> RecentConnections { get; }
/// <summary> /// <summary>
/// Logs the user activity. /// Logs the user activity.
@ -67,12 +60,13 @@ namespace MediaBrowser.Controller.Session
/// <param name="user">The user.</param> /// <param name="user">The user.</param>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <param name="positionTicks">The position ticks.</param> /// <param name="positionTicks">The position ticks.</param>
/// <param name="isPaused">if set to <c>true</c> [is paused].</param>
/// <param name="clientType">Type of the client.</param> /// <param name="clientType">Type of the client.</param>
/// <param name="deviceId">The device id.</param> /// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param> /// <param name="deviceName">Name of the device.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentNullException"></exception>
Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName); Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, bool isPaused, string clientType, string deviceId, string deviceName);
/// <summary> /// <summary>
/// Used to report that playback has ended for an item /// Used to report that playback has ended for an item

View File

@ -1,5 +1,6 @@
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Net;
using System; using System;
namespace MediaBrowser.Controller.Session namespace MediaBrowser.Controller.Session
@ -39,6 +40,24 @@ namespace MediaBrowser.Controller.Session
/// <value>The name of the device.</value> /// <value>The name of the device.</value>
public string DeviceName { get; set; } public string DeviceName { get; set; }
/// <summary>
/// Gets or sets the now viewing context.
/// </summary>
/// <value>The now viewing context.</value>
public string NowViewingContext { get; set; }
/// <summary>
/// Gets or sets the type of the now viewing item.
/// </summary>
/// <value>The type of the now viewing item.</value>
public string NowViewingItemType { get; set; }
/// <summary>
/// Gets or sets the now viewing item identifier.
/// </summary>
/// <value>The now viewing item identifier.</value>
public string NowViewingItemIdentifier { get; set; }
/// <summary> /// <summary>
/// Gets or sets the now playing item. /// Gets or sets the now playing item.
/// </summary> /// </summary>
@ -51,6 +70,12 @@ namespace MediaBrowser.Controller.Session
/// <value>The now playing position ticks.</value> /// <value>The now playing position ticks.</value>
public long? NowPlayingPositionTicks { get; set; } public long? NowPlayingPositionTicks { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is paused.
/// </summary>
/// <value><c>true</c> if this instance is paused; otherwise, <c>false</c>.</value>
public bool? IsPaused { get; set; }
/// <summary> /// <summary>
/// Gets or sets the device id. /// Gets or sets the device id.
/// </summary> /// </summary>
@ -62,5 +87,34 @@ namespace MediaBrowser.Controller.Session
/// </summary> /// </summary>
/// <value>The web socket.</value> /// <value>The web socket.</value>
public IWebSocketConnection WebSocket { get; set; } public IWebSocketConnection WebSocket { get; set; }
/// <summary>
/// Gets a value indicating whether this instance is active.
/// </summary>
/// <value><c>true</c> if this instance is active; otherwise, <c>false</c>.</value>
public bool IsActive
{
get
{
if (WebSocket != null)
{
return WebSocket.State == WebSocketState.Open;
}
return (DateTime.UtcNow - LastActivityDate).TotalMinutes <= 5;
}
}
/// <summary>
/// Gets a value indicating whether [supports remote control].
/// </summary>
/// <value><c>true</c> if [supports remote control]; otherwise, <c>false</c>.</value>
public bool SupportsRemoteControl
{
get
{
return WebSocket != null && WebSocket.State == WebSocketState.Open;
}
}
} }
} }

View File

@ -29,12 +29,36 @@ namespace MediaBrowser.Model.Session
/// <value>The last activity date.</value> /// <value>The last activity date.</value>
public DateTime LastActivityDate { get; set; } public DateTime LastActivityDate { get; set; }
/// <summary>
/// Gets or sets the now viewing context.
/// </summary>
/// <value>The now viewing context.</value>
public string NowViewingContext { get; set; }
/// <summary>
/// Gets or sets the type of the now viewing item.
/// </summary>
/// <value>The type of the now viewing item.</value>
public string NowViewingItemType { get; set; }
/// <summary>
/// Gets or sets the now viewing item identifier.
/// </summary>
/// <value>The now viewing item identifier.</value>
public string NowViewingItemIdentifier { get; set; }
/// <summary> /// <summary>
/// Gets or sets the name of the device. /// Gets or sets the name of the device.
/// </summary> /// </summary>
/// <value>The name of the device.</value> /// <value>The name of the device.</value>
public string DeviceName { get; set; } public string DeviceName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is paused.
/// </summary>
/// <value><c>true</c> if this instance is paused; otherwise, <c>false</c>.</value>
public bool? IsPaused { get; set; }
/// <summary> /// <summary>
/// Gets or sets the now playing item. /// Gets or sets the now playing item.
/// </summary> /// </summary>

View File

@ -207,7 +207,9 @@
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="swagger-ui\css\hightlight.default.css" /> <Content Include="swagger-ui\css\hightlight.default.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="swagger-ui\css\screen.css"> <Content Include="swagger-ui\css\screen.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content> </Content>

View File

@ -100,7 +100,13 @@ namespace MediaBrowser.Server.Implementations.ServerManager
using (var memoryStream = new MemoryStream(bytes)) using (var memoryStream = new MemoryStream(bytes))
{ {
info = (WebSocketMessageInfo)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessageInfo)); var stub = (WebSocketMessage<object>)_jsonSerializer.DeserializeFromStream(memoryStream, typeof(WebSocketMessage<object>));
info = new WebSocketMessageInfo
{
MessageType = stub.MessageType,
Data = stub.Data == null ? null : stub.Data.ToString()
};
} }
info.Connection = this; info.Connection = this;

View File

@ -1,14 +1,12 @@
using MediaBrowser.Common.Events; using MediaBrowser.Common.Events;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging; using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Session;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@ -18,10 +16,19 @@ using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Session namespace MediaBrowser.Server.Implementations.Session
{ {
/// <summary>
/// Class SessionManager
/// </summary>
public class SessionManager : ISessionManager public class SessionManager : ISessionManager
{ {
/// <summary>
/// The _user data repository
/// </summary>
private readonly IUserDataRepository _userDataRepository; private readonly IUserDataRepository _userDataRepository;
/// <summary>
/// The _user repository
/// </summary>
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
/// <summary> /// <summary>
@ -54,6 +61,13 @@ namespace MediaBrowser.Server.Implementations.Session
/// </summary> /// </summary>
public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped; public event EventHandler<PlaybackProgressEventArgs> PlaybackStopped;
/// <summary>
/// Initializes a new instance of the <see cref="SessionManager"/> class.
/// </summary>
/// <param name="userDataRepository">The user data repository.</param>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="logger">The logger.</param>
/// <param name="userRepository">The user repository.</param>
public SessionManager(IUserDataRepository userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository) public SessionManager(IUserDataRepository userDataRepository, IServerConfigurationManager configurationManager, ILogger logger, IUserRepository userRepository)
{ {
_userDataRepository = userDataRepository; _userDataRepository = userDataRepository;
@ -66,20 +80,14 @@ namespace MediaBrowser.Server.Implementations.Session
/// Gets all connections. /// Gets all connections.
/// </summary> /// </summary>
/// <value>All connections.</value> /// <value>All connections.</value>
public IEnumerable<SessionInfo> AllConnections public IEnumerable<SessionInfo> Sessions
{ {
get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate); } get { return _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList(); }
} }
/// <summary> /// <summary>
/// Gets the active connections. /// The _true task result
/// </summary> /// </summary>
/// <value>The active connections.</value>
public IEnumerable<SessionInfo> RecentConnections
{
get { return AllConnections.Where(c => (DateTime.UtcNow - c.LastActivityDate).TotalMinutes <= 5); }
}
private readonly Task _trueTaskResult = Task.FromResult(true); private readonly Task _trueTaskResult = Task.FromResult(true);
/// <summary> /// <summary>
@ -124,11 +132,13 @@ namespace MediaBrowser.Server.Implementations.Session
/// <param name="deviceId">The device id.</param> /// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param> /// <param name="deviceName">Name of the device.</param>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <param name="isPaused">if set to <c>true</c> [is paused].</param>
/// <param name="currentPositionTicks">The current position ticks.</param> /// <param name="currentPositionTicks">The current position ticks.</param>
private void UpdateNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item, long? currentPositionTicks = null) private void UpdateNowPlayingItemId(User user, string clientType, string deviceId, string deviceName, BaseItem item, bool isPaused, long? currentPositionTicks = null)
{ {
var conn = GetConnection(clientType, deviceId, deviceName, user); var conn = GetConnection(clientType, deviceId, deviceName, user);
conn.IsPaused = isPaused;
conn.NowPlayingPositionTicks = currentPositionTicks; conn.NowPlayingPositionTicks = currentPositionTicks;
conn.NowPlayingItem = item; conn.NowPlayingItem = item;
conn.LastActivityDate = DateTime.UtcNow; conn.LastActivityDate = DateTime.UtcNow;
@ -150,6 +160,7 @@ namespace MediaBrowser.Server.Implementations.Session
{ {
conn.NowPlayingItem = null; conn.NowPlayingItem = null;
conn.NowPlayingPositionTicks = null; conn.NowPlayingPositionTicks = null;
conn.IsPaused = null;
} }
} }
@ -187,7 +198,8 @@ namespace MediaBrowser.Server.Implementations.Session
/// <param name="clientType">Type of the client.</param> /// <param name="clientType">Type of the client.</param>
/// <param name="deviceId">The device id.</param> /// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param> /// <param name="deviceName">Name of the device.</param>
/// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentNullException">
/// </exception>
public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName) public void OnPlaybackStart(User user, BaseItem item, string clientType, string deviceId, string deviceName)
{ {
if (user == null) if (user == null)
@ -199,7 +211,7 @@ namespace MediaBrowser.Server.Implementations.Session
throw new ArgumentNullException(); throw new ArgumentNullException();
} }
UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item); UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, false);
// Nothing to save here // Nothing to save here
// Fire events to inform plugins // Fire events to inform plugins
@ -216,12 +228,14 @@ namespace MediaBrowser.Server.Implementations.Session
/// <param name="user">The user.</param> /// <param name="user">The user.</param>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <param name="positionTicks">The position ticks.</param> /// <param name="positionTicks">The position ticks.</param>
/// <param name="isPaused">if set to <c>true</c> [is paused].</param>
/// <param name="clientType">Type of the client.</param> /// <param name="clientType">Type of the client.</param>
/// <param name="deviceId">The device id.</param> /// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param> /// <param name="deviceName">Name of the device.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentNullException">
public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName) /// </exception>
public async Task OnPlaybackProgress(User user, BaseItem item, long? positionTicks, bool isPaused, string clientType, string deviceId, string deviceName)
{ {
if (user == null) if (user == null)
{ {
@ -232,7 +246,7 @@ namespace MediaBrowser.Server.Implementations.Session
throw new ArgumentNullException(); throw new ArgumentNullException();
} }
UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, positionTicks); UpdateNowPlayingItemId(user, clientType, deviceId, deviceName, item, isPaused, positionTicks);
var key = item.GetUserDataKey(); var key = item.GetUserDataKey();
@ -262,7 +276,8 @@ namespace MediaBrowser.Server.Implementations.Session
/// <param name="deviceId">The device id.</param> /// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param> /// <param name="deviceName">Name of the device.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.ArgumentNullException">
/// </exception>
public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName) public async Task OnPlaybackStopped(User user, BaseItem item, long? positionTicks, string clientType, string deviceId, string deviceName)
{ {
if (user == null) if (user == null)
@ -355,20 +370,5 @@ namespace MediaBrowser.Server.Implementations.Session
data.LastPlayedDate = DateTime.UtcNow; data.LastPlayedDate = DateTime.UtcNow;
} }
} }
/// <summary>
/// Identifies the web socket.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="webSocket">The web socket.</param>
public void IdentifyWebSocket(Guid sessionId, IWebSocketConnection webSocket)
{
var session = AllConnections.FirstOrDefault(i => i.Id == sessionId);
if (session != null)
{
session.WebSocket = webSocket;
}
}
} }
} }

View File

@ -1,5 +1,9 @@
using MediaBrowser.Common.Net; using System.Globalization;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session; using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -21,13 +25,27 @@ namespace MediaBrowser.Server.Implementations.Session
/// </summary> /// </summary>
private readonly ISessionManager _sessionManager; private readonly ISessionManager _sessionManager;
/// <summary>
/// The _logger
/// </summary>
private readonly ILogger _logger;
private readonly IUserManager _userManager;
private readonly ILibraryManager _libraryManager;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class. /// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
/// </summary> /// </summary>
/// <param name="sessionManager">The session manager.</param> /// <param name="sessionManager">The session manager.</param>
public SessionWebSocketListener(ISessionManager sessionManager) /// <param name="logger">The logger.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="userManager">The user manager.</param>
public SessionWebSocketListener(ISessionManager sessionManager, ILogger logger, ILibraryManager libraryManager, IUserManager userManager)
{ {
_sessionManager = sessionManager; _sessionManager = sessionManager;
_logger = logger;
_libraryManager = libraryManager;
_userManager = userManager;
} }
/// <summary> /// <summary>
@ -44,11 +62,87 @@ namespace MediaBrowser.Server.Implementations.Session
var client = vals[0]; var client = vals[0];
var deviceId = vals[1]; var deviceId = vals[1];
var session = _sessionManager.AllConnections.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) && string.Equals(i.Client, client)); var session = _sessionManager.Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) && string.Equals(i.Client, client));
if (session != null) if (session != null)
{ {
((SessionManager)_sessionManager).IdentifyWebSocket(session.Id, message.Connection); session.WebSocket = message.Connection;
}
}
else if (string.Equals(message.MessageType, "Context", StringComparison.OrdinalIgnoreCase))
{
var session = _sessionManager.Sessions.FirstOrDefault(i => i.WebSocket == message.Connection);
if (session != null)
{
var vals = message.Data.Split('|');
session.NowViewingItemType = vals[0];
session.NowViewingItemIdentifier = vals[1];
session.NowViewingContext = vals.Length > 2 ? vals[2] : null;
}
}
else if (string.Equals(message.MessageType, "PlaybackStart", StringComparison.OrdinalIgnoreCase))
{
var session = _sessionManager.Sessions.FirstOrDefault(i => i.WebSocket == message.Connection);
if (session != null && session.UserId.HasValue)
{
var item = DtoBuilder.GetItemByClientId(message.Data, _userManager, _libraryManager);
_sessionManager.OnPlaybackStart(_userManager.GetUserById(session.UserId.Value), item, session.Client, session.DeviceId, session.DeviceName);
}
}
else if (string.Equals(message.MessageType, "PlaybackProgress", StringComparison.OrdinalIgnoreCase))
{
var session = _sessionManager.Sessions.FirstOrDefault(i => i.WebSocket == message.Connection);
if (session != null && session.UserId.HasValue)
{
var vals = message.Data.Split('|');
var item = DtoBuilder.GetItemByClientId(vals[0], _userManager, _libraryManager);
long? positionTicks = null;
if (vals.Length > 1)
{
long pos;
if (long.TryParse(vals[1], out pos))
{
positionTicks = pos;
}
}
var isPaused = vals.Length > 2 && string.Equals(vals[2], "true", StringComparison.OrdinalIgnoreCase);
_sessionManager.OnPlaybackProgress(_userManager.GetUserById(session.UserId.Value), item, positionTicks, isPaused, session.Client, session.DeviceId, session.DeviceName);
}
}
else if (string.Equals(message.MessageType, "PlaybackStopped", StringComparison.OrdinalIgnoreCase))
{
var session = _sessionManager.Sessions.FirstOrDefault(i => i.WebSocket == message.Connection);
if (session != null && session.UserId.HasValue)
{
var vals = message.Data.Split('|');
var item = DtoBuilder.GetItemByClientId(vals[0], _userManager, _libraryManager);
long? positionTicks = null;
if (vals.Length > 1)
{
long pos;
if (long.TryParse(vals[1], out pos))
{
positionTicks = pos;
}
}
_sessionManager.OnPlaybackStopped(_userManager.GetUserById(session.UserId.Value), item, positionTicks, session.Client, session.DeviceId, session.DeviceName);
} }
} }

View File

@ -206,7 +206,7 @@ namespace MediaBrowser.WebDashboard.Api
ILibraryManager libraryManager, ILibraryManager libraryManager,
ISessionManager connectionManager) ISessionManager connectionManager)
{ {
var connections = connectionManager.RecentConnections.ToArray(); var connections = connectionManager.Sessions.Where(i => i.IsActive).ToArray();
var dtoBuilder = new UserDtoBuilder(logger); var dtoBuilder = new UserDtoBuilder(logger);

View File

@ -2379,6 +2379,16 @@ MediaBrowser.ApiClient = function ($, navigator, JSON, WebSocket, setTimeout) {
throw new Error("null itemId"); throw new Error("null itemId");
} }
if (self.isWebSocketOpen()) {
var deferred = $.Deferred();
self.sendWebSocketMessage("PlaybackStart", itemId);
deferred.resolveWith(null, []);
return deferred.promise();
}
var url = self.getUrl("Users/" + userId + "/PlayingItems/" + itemId); var url = self.getUrl("Users/" + userId + "/PlayingItems/" + itemId);
return self.ajax({ return self.ajax({
@ -2392,7 +2402,7 @@ MediaBrowser.ApiClient = function ($, navigator, JSON, WebSocket, setTimeout) {
* @param {String} userId * @param {String} userId
* @param {String} itemId * @param {String} itemId
*/ */
self.reportPlaybackProgress = function (userId, itemId, positionTicks) { self.reportPlaybackProgress = function (userId, itemId, positionTicks, isPaused) {
if (!userId) { if (!userId) {
throw new Error("null userId"); throw new Error("null userId");
@ -2402,6 +2412,16 @@ MediaBrowser.ApiClient = function ($, navigator, JSON, WebSocket, setTimeout) {
throw new Error("null itemId"); throw new Error("null itemId");
} }
if (self.isWebSocketOpen()) {
var deferred = $.Deferred();
self.sendWebSocketMessage("PlaybackProgress", itemId + "|" + (positionTicks == null ? "" : positionTicks) + "|" + (isPaused == null ? "" : isPaused));
deferred.resolveWith(null, []);
return deferred.promise();
}
var params = { var params = {
}; };
@ -2433,6 +2453,16 @@ MediaBrowser.ApiClient = function ($, navigator, JSON, WebSocket, setTimeout) {
throw new Error("null itemId"); throw new Error("null itemId");
} }
if (self.isWebSocketOpen()) {
var deferred = $.Deferred();
self.sendWebSocketMessage("PlaybackStopped", itemId + "|" + (positionTicks == null ? "" : positionTicks));
deferred.resolveWith(null, []);
return deferred.promise();
}
var params = { var params = {
}; };

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="MediaBrowser.ApiClient.Javascript" version="3.0.101" targetFramework="net45" /> <package id="MediaBrowser.ApiClient.Javascript" version="3.0.104" targetFramework="net45" />
<package id="ServiceStack.Common" version="3.9.44" targetFramework="net45" /> <package id="ServiceStack.Common" version="3.9.44" targetFramework="net45" />
<package id="ServiceStack.Text" version="3.9.44" targetFramework="net45" /> <package id="ServiceStack.Text" version="3.9.44" targetFramework="net45" />
</packages> </packages>

View File

@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"> <package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata> <metadata>
<id>MediaBrowser.Common.Internal</id> <id>MediaBrowser.Common.Internal</id>
<version>3.0.97</version> <version>3.0.98</version>
<title>MediaBrowser.Common.Internal</title> <title>MediaBrowser.Common.Internal</title>
<authors>Luke</authors> <authors>Luke</authors>
<owners>ebr,Luke,scottisafool</owners> <owners>ebr,Luke,scottisafool</owners>
@ -12,9 +12,9 @@
<description>Contains common components shared by Media Browser Theatre and Media Browser Server. Not intended for plugin developer consumption.</description> <description>Contains common components shared by Media Browser Theatre and Media Browser Server. Not intended for plugin developer consumption.</description>
<copyright>Copyright © Media Browser 2013</copyright> <copyright>Copyright © Media Browser 2013</copyright>
<dependencies> <dependencies>
<dependency id="MediaBrowser.Common" version="3.0.97" /> <dependency id="MediaBrowser.Common" version="3.0.98" />
<dependency id="NLog" version="2.0.1.2" /> <dependency id="NLog" version="2.0.1.2" />
<dependency id="ServiceStack.Text" version="3.9.97" /> <dependency id="ServiceStack.Text" version="3.9.98" />
<dependency id="SimpleInjector" version="2.2.1" /> <dependency id="SimpleInjector" version="2.2.1" />
</dependencies> </dependencies>
</metadata> </metadata>

View File

@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata> <metadata>
<id>MediaBrowser.Common</id> <id>MediaBrowser.Common</id>
<version>3.0.97</version> <version>3.0.98</version>
<title>MediaBrowser.Common</title> <title>MediaBrowser.Common</title>
<authors>Media Browser Team</authors> <authors>Media Browser Team</authors>
<owners>ebr,Luke,scottisafool</owners> <owners>ebr,Luke,scottisafool</owners>

View File

@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> <package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata> <metadata>
<id>MediaBrowser.Server.Core</id> <id>MediaBrowser.Server.Core</id>
<version>3.0.97</version> <version>3.0.98</version>
<title>Media Browser.Server.Core</title> <title>Media Browser.Server.Core</title>
<authors>Media Browser Team</authors> <authors>Media Browser Team</authors>
<owners>ebr,Luke,scottisafool</owners> <owners>ebr,Luke,scottisafool</owners>
@ -12,7 +12,7 @@
<description>Contains core components required to build plugins for Media Browser Server.</description> <description>Contains core components required to build plugins for Media Browser Server.</description>
<copyright>Copyright © Media Browser 2013</copyright> <copyright>Copyright © Media Browser 2013</copyright>
<dependencies> <dependencies>
<dependency id="MediaBrowser.Common" version="3.0.97" /> <dependency id="MediaBrowser.Common" version="3.0.98" />
</dependencies> </dependencies>
</metadata> </metadata>
<files> <files>