Fix code issues

pull/2733/head
gion 5 years ago
parent 8a6ec2fb71
commit 5c8cbd4087

@ -22,17 +22,17 @@ namespace Emby.Server.Implementations.Session
/// <summary> /// <summary>
/// The timeout in seconds after which a WebSocket is considered to be lost. /// The timeout in seconds after which a WebSocket is considered to be lost.
/// </summary> /// </summary>
public readonly int WebSocketLostTimeout = 60; public const int WebSocketLostTimeout = 60;
/// <summary> /// <summary>
/// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets. /// The keep-alive interval factor; controls how often the watcher will check on the status of the WebSockets.
/// </summary> /// </summary>
public readonly double IntervalFactor = 0.2; public const float IntervalFactor = 0.2f;
/// <summary> /// <summary>
/// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent. /// The ForceKeepAlive factor; controls when a ForceKeepAlive is sent.
/// </summary> /// </summary>
public readonly double ForceKeepAliveFactor = 0.75; public const float ForceKeepAliveFactor = 0.75f;
/// <summary> /// <summary>
/// The _session manager /// The _session manager
@ -213,7 +213,7 @@ namespace Emby.Server.Implementations.Session
{ {
_keepAliveCancellationToken = new CancellationTokenSource(); _keepAliveCancellationToken = new CancellationTokenSource();
// Start KeepAlive watcher // Start KeepAlive watcher
var task = RepeatAsyncCallbackEvery( _ = RepeatAsyncCallbackEvery(
KeepAliveSockets, KeepAliveSockets,
TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor), TimeSpan.FromSeconds(WebSocketLostTimeout * IntervalFactor),
_keepAliveCancellationToken.Token); _keepAliveCancellationToken.Token);
@ -241,6 +241,7 @@ namespace Emby.Server.Implementations.Session
{ {
webSocket.Closed -= OnWebSocketClosed; webSocket.Closed -= OnWebSocketClosed;
} }
_webSockets.Clear(); _webSockets.Clear();
} }
} }
@ -250,8 +251,8 @@ namespace Emby.Server.Implementations.Session
/// </summary> /// </summary>
private async Task KeepAliveSockets() private async Task KeepAliveSockets()
{ {
IEnumerable<IWebSocketConnection> inactive; List<IWebSocketConnection> inactive;
IEnumerable<IWebSocketConnection> lost; List<IWebSocketConnection> lost;
lock (_webSocketsLock) lock (_webSocketsLock)
{ {
@ -261,8 +262,8 @@ namespace Emby.Server.Implementations.Session
{ {
var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds; var elapsed = (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds;
return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout); return (elapsed > WebSocketLostTimeout * ForceKeepAliveFactor) && (elapsed < WebSocketLostTimeout);
}); }).ToList();
lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout); lost = _webSockets.Where(i => (DateTime.UtcNow - i.LastKeepAliveDate).TotalSeconds >= WebSocketLostTimeout).ToList();
} }
if (inactive.Any()) if (inactive.Any())
@ -279,7 +280,7 @@ namespace Emby.Server.Implementations.Session
catch (WebSocketException exception) catch (WebSocketException exception)
{ {
_logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket."); _logger.LogInformation(exception, "Error sending ForceKeepAlive message to WebSocket.");
lost = lost.Append(webSocket); lost.Add(webSocket);
} }
} }
@ -288,7 +289,7 @@ namespace Emby.Server.Implementations.Session
if (lost.Any()) if (lost.Any())
{ {
_logger.LogInformation("Lost {0} WebSockets.", lost.Count()); _logger.LogInformation("Lost {0} WebSockets.", lost.Count());
foreach (var webSocket in lost.ToList()) foreach (var webSocket in lost)
{ {
// TODO: handle session relative to the lost webSocket // TODO: handle session relative to the lost webSocket
RemoveWebSocket(webSocket); RemoveWebSocket(webSocket);

@ -144,7 +144,7 @@ namespace Emby.Server.Implementations.SyncPlay
session => session.Session session => session.Session
).ToArray(); ).ToArray();
default: default:
return new SessionInfo[] { }; return Array.Empty<SessionInfo>();
} }
} }
@ -541,7 +541,7 @@ namespace Emby.Server.Implementations.SyncPlay
PlayingItemName = _group.PlayingItem.Name, PlayingItemName = _group.PlayingItem.Name,
PlayingItemId = _group.PlayingItem.Id.ToString(), PlayingItemId = _group.PlayingItem.Id.ToString(),
PositionTicks = _group.PositionTicks, PositionTicks = _group.PositionTicks,
Participants = _group.Participants.Values.Select(session => session.Session.UserName).Distinct().ToArray() Participants = _group.Participants.Values.Select(session => session.Session.UserName).Distinct().ToList().AsReadOnly()
}; };
} }
} }

@ -47,8 +47,8 @@ namespace Emby.Server.Implementations.SyncPlay
/// <summary> /// <summary>
/// The groups. /// The groups.
/// </summary> /// </summary>
private readonly Dictionary<string, ISyncPlayController> _groups = private readonly Dictionary<Guid, ISyncPlayController> _groups =
new Dictionary<string, ISyncPlayController>(StringComparer.OrdinalIgnoreCase); new Dictionary<Guid, ISyncPlayController>();
/// <summary> /// <summary>
/// Lock used for accesing any group. /// Lock used for accesing any group.
@ -113,14 +113,22 @@ namespace Emby.Server.Implementations.SyncPlay
private void OnSessionManagerSessionEnded(object sender, SessionEventArgs e) private void OnSessionManagerSessionEnded(object sender, SessionEventArgs e)
{ {
var session = e.SessionInfo; var session = e.SessionInfo;
if (!IsSessionInGroup(session)) return; if (!IsSessionInGroup(session))
{
return;
}
LeaveGroup(session, CancellationToken.None); LeaveGroup(session, CancellationToken.None);
} }
private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e) private void OnSessionManagerPlaybackStopped(object sender, PlaybackStopEventArgs e)
{ {
var session = e.Session; var session = e.Session;
if (!IsSessionInGroup(session)) return; if (!IsSessionInGroup(session))
{
return;
}
LeaveGroup(session, CancellationToken.None); LeaveGroup(session, CancellationToken.None);
} }
@ -193,14 +201,14 @@ namespace Emby.Server.Implementations.SyncPlay
} }
var group = new SyncPlayController(_sessionManager, this); var group = new SyncPlayController(_sessionManager, this);
_groups[group.GetGroupId().ToString()] = group; _groups[group.GetGroupId()] = group;
group.InitGroup(session, cancellationToken); group.InitGroup(session, cancellationToken);
} }
} }
/// <inheritdoc /> /// <inheritdoc />
public void JoinGroup(SessionInfo session, string groupId, JoinGroupRequest request, CancellationToken cancellationToken) public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken)
{ {
var user = _userManager.GetUserById(session.UserId); var user = _userManager.GetUserById(session.UserId);
@ -248,7 +256,11 @@ namespace Emby.Server.Implementations.SyncPlay
if (IsSessionInGroup(session)) if (IsSessionInGroup(session))
{ {
if (GetSessionGroup(session).Equals(groupId)) return; if (GetSessionGroup(session).Equals(groupId))
{
return;
}
LeaveGroup(session, cancellationToken); LeaveGroup(session, cancellationToken);
} }
@ -282,7 +294,7 @@ namespace Emby.Server.Implementations.SyncPlay
if (group.IsGroupEmpty()) if (group.IsGroupEmpty())
{ {
_logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GetGroupId()); _logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GetGroupId());
_groups.Remove(group.GetGroupId().ToString(), out _); _groups.Remove(group.GetGroupId(), out _);
} }
} }
} }

@ -171,31 +171,35 @@ namespace MediaBrowser.Api.SyncPlay
public void Post(SyncPlayJoinGroup request) public void Post(SyncPlayJoinGroup request)
{ {
var currentSession = GetSession(_sessionContext); var currentSession = GetSession(_sessionContext);
var joinRequest = new JoinGroupRequest()
Guid groupId;
Guid playingItemId = Guid.Empty;
var valid = Guid.TryParse(request.GroupId, out groupId);
if (!valid)
{ {
GroupId = Guid.Parse(request.GroupId) Logger.LogError("JoinGroup: {0} is not a valid format for GroupId. Ignoring request.", request.GroupId);
}; return;
}
// Both null and empty strings mean that client isn't playing anything // Both null and empty strings mean that client isn't playing anything
if (!String.IsNullOrEmpty(request.PlayingItemId)) if (!String.IsNullOrEmpty(request.PlayingItemId))
{ {
try valid = Guid.TryParse(request.PlayingItemId, out playingItemId);
{ if (!valid)
joinRequest.PlayingItemId = Guid.Parse(request.PlayingItemId);
}
catch (ArgumentNullException)
{
// Should never happen, but just in case
Logger.LogError("JoinGroup: null value for PlayingItemId. Ignoring request.");
return;
}
catch (FormatException)
{ {
Logger.LogError("JoinGroup: {0} is not a valid format for PlayingItemId. Ignoring request.", request.PlayingItemId); Logger.LogError("JoinGroup: {0} is not a valid format for PlayingItemId. Ignoring request.", request.PlayingItemId);
return; return;
} }
} }
_syncPlayManager.JoinGroup(currentSession, request.GroupId, joinRequest, CancellationToken.None);
var joinRequest = new JoinGroupRequest()
{
GroupId = groupId,
PlayingItemId = playingItemId
};
_syncPlayManager.JoinGroup(currentSession, groupId, joinRequest, CancellationToken.None);
} }
/// <summary> /// <summary>
@ -217,21 +221,16 @@ namespace MediaBrowser.Api.SyncPlay
{ {
var currentSession = GetSession(_sessionContext); var currentSession = GetSession(_sessionContext);
var filterItemId = Guid.Empty; var filterItemId = Guid.Empty;
if (!String.IsNullOrEmpty(request.FilterItemId)) if (!String.IsNullOrEmpty(request.FilterItemId))
{ {
try var valid = Guid.TryParse(request.FilterItemId, out filterItemId);
{ if (!valid)
filterItemId = Guid.Parse(request.FilterItemId);
}
catch (ArgumentNullException)
{
Logger.LogWarning("ListGroups: null value for FilterItemId. Ignoring filter.");
}
catch (FormatException)
{ {
Logger.LogWarning("ListGroups: {0} is not a valid format for FilterItemId. Ignoring filter.", request.FilterItemId); Logger.LogWarning("ListGroups: {0} is not a valid format for FilterItemId. Ignoring filter.", request.FilterItemId);
} }
} }
return _syncPlayManager.ListGroups(currentSession, filterItemId); return _syncPlayManager.ListGroups(currentSession, filterItemId);
} }

@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.Net
/// Gets or sets the date of last Keeplive received. /// Gets or sets the date of last Keeplive received.
/// </summary> /// </summary>
/// <value>The date of last Keeplive received.</value> /// <value>The date of last Keeplive received.</value>
public DateTime LastKeepAliveDate { get; set; } DateTime LastKeepAliveDate { get; set; }
/// <summary> /// <summary>
/// Gets or sets the URL. /// Gets or sets the URL.

@ -69,7 +69,11 @@ namespace MediaBrowser.Controller.SyncPlay
/// <param name="session">The session.</param> /// <param name="session">The session.</param>
public void AddSession(SessionInfo session) public void AddSession(SessionInfo session)
{ {
if (ContainsSession(session.Id.ToString())) return; if (ContainsSession(session.Id.ToString()))
{
return;
}
var member = new GroupMember(); var member = new GroupMember();
member.Session = session; member.Session = session;
member.Ping = DefaulPing; member.Ping = DefaulPing;
@ -84,9 +88,12 @@ namespace MediaBrowser.Controller.SyncPlay
public void RemoveSession(SessionInfo session) public void RemoveSession(SessionInfo session)
{ {
if (!ContainsSession(session.Id.ToString())) return; if (!ContainsSession(session.Id.ToString()))
GroupMember member; {
Participants.Remove(session.Id.ToString(), out member); return;
}
Participants.Remove(session.Id.ToString(), out _);
} }
/// <summary> /// <summary>
@ -96,7 +103,11 @@ namespace MediaBrowser.Controller.SyncPlay
/// <param name="ping">The ping.</param> /// <param name="ping">The ping.</param>
public void UpdatePing(SessionInfo session, long ping) public void UpdatePing(SessionInfo session, long ping)
{ {
if (!ContainsSession(session.Id.ToString())) return; if (!ContainsSession(session.Id.ToString()))
{
return;
}
Participants[session.Id.ToString()].Ping = ping; Participants[session.Id.ToString()].Ping = ping;
} }
@ -121,7 +132,11 @@ namespace MediaBrowser.Controller.SyncPlay
/// <param name="isBuffering">The state.</param> /// <param name="isBuffering">The state.</param>
public void SetBuffering(SessionInfo session, bool isBuffering) public void SetBuffering(SessionInfo session, bool isBuffering)
{ {
if (!ContainsSession(session.Id.ToString())) return; if (!ContainsSession(session.Id.ToString()))
{
return;
}
Participants[session.Id.ToString()].IsBuffering = isBuffering; Participants[session.Id.ToString()].IsBuffering = isBuffering;
} }
@ -133,7 +148,10 @@ namespace MediaBrowser.Controller.SyncPlay
{ {
foreach (var session in Participants.Values) foreach (var session in Participants.Values)
{ {
if (session.IsBuffering) return true; if (session.IsBuffering)
{
return true;
}
} }
return false; return false;
} }

@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.SyncPlay
/// <param name="groupId">The group id.</param> /// <param name="groupId">The group id.</param>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
void JoinGroup(SessionInfo session, string groupId, JoinGroupRequest request, CancellationToken cancellationToken); void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken);
/// <summary> /// <summary>
/// Removes the session from a group. /// Removes the session from a group.

@ -1,3 +1,5 @@
using System.Collections.Generic;
namespace MediaBrowser.Model.SyncPlay namespace MediaBrowser.Model.SyncPlay
{ {
/// <summary> /// <summary>
@ -33,6 +35,6 @@ namespace MediaBrowser.Model.SyncPlay
/// Gets or sets the participants. /// Gets or sets the participants.
/// </summary> /// </summary>
/// <value>The participants.</value> /// <value>The participants.</value>
public string[] Participants { get; set; } public IReadOnlyList<string> Participants { get; set; }
} }
} }

Loading…
Cancel
Save