mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-04-16 07:12:18 +01:00
move classes to portable
This commit is contained in:
186
Emby.Server.Implementations/Session/HttpSessionController.cs
Normal file
186
Emby.Server.Implementations/Session/HttpSessionController.cs
Normal file
@@ -0,0 +1,186 @@
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.Session;
|
||||
using MediaBrowser.Model.System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
public class HttpSessionController : ISessionController, IDisposable
|
||||
{
|
||||
private readonly IHttpClient _httpClient;
|
||||
private readonly IJsonSerializer _json;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
public SessionInfo Session { get; private set; }
|
||||
|
||||
private readonly string _postUrl;
|
||||
|
||||
public HttpSessionController(IHttpClient httpClient,
|
||||
IJsonSerializer json,
|
||||
SessionInfo session,
|
||||
string postUrl, ISessionManager sessionManager)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_json = json;
|
||||
Session = session;
|
||||
_postUrl = postUrl;
|
||||
_sessionManager = sessionManager;
|
||||
}
|
||||
|
||||
public void OnActivity()
|
||||
{
|
||||
}
|
||||
|
||||
private string PostUrl
|
||||
{
|
||||
get
|
||||
{
|
||||
return string.Format("http://{0}{1}", Session.RemoteEndPoint, _postUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSessionActive
|
||||
{
|
||||
get
|
||||
{
|
||||
return (DateTime.UtcNow - Session.LastActivityDate).TotalMinutes <= 10;
|
||||
}
|
||||
}
|
||||
|
||||
public bool SupportsMediaControl
|
||||
{
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
private Task SendMessage(string name, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage(name, new Dictionary<string, string>(), cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SendMessage(string name,
|
||||
Dictionary<string, string> args,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var url = PostUrl + "/" + name + ToQueryString(args);
|
||||
|
||||
await _httpClient.Post(new HttpRequestOptions
|
||||
{
|
||||
Url = url,
|
||||
CancellationToken = cancellationToken,
|
||||
BufferContent = false
|
||||
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SendPlaybackStartNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SendPlaybackStoppedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
|
||||
{
|
||||
var dict = new Dictionary<string, string>();
|
||||
|
||||
dict["ItemIds"] = string.Join(",", command.ItemIds);
|
||||
|
||||
if (command.StartPositionTicks.HasValue)
|
||||
{
|
||||
dict["StartPositionTicks"] = command.StartPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return SendMessage(command.PlayCommand.ToString(), dict, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
|
||||
{
|
||||
var args = new Dictionary<string, string>();
|
||||
|
||||
if (command.Command == PlaystateCommand.Seek)
|
||||
{
|
||||
if (!command.SeekPositionTicks.HasValue)
|
||||
{
|
||||
throw new ArgumentException("SeekPositionTicks cannot be null");
|
||||
}
|
||||
|
||||
args["SeekPositionTicks"] = command.SeekPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return SendMessage(command.Command.ToString(), args, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SendRestartRequiredNotification(SystemInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage("RestartRequired", cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendUserDataChangeInfo(UserDataChangeInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task SendServerShutdownNotification(CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage("ServerShuttingDown", cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendServerRestartNotification(CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage("ServerRestarting", cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage(command.Name, command.Arguments, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendMessage<T>(string name, T data, CancellationToken cancellationToken)
|
||||
{
|
||||
// Not supported or needed right now
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
private string ToQueryString(Dictionary<string, string> nvc)
|
||||
{
|
||||
var array = (from item in nvc
|
||||
select string.Format("{0}={1}", WebUtility.UrlEncode(item.Key), WebUtility.UrlEncode(item.Value)))
|
||||
.ToArray();
|
||||
|
||||
var args = string.Join("&", array);
|
||||
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
return args;
|
||||
}
|
||||
|
||||
return "?" + args;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
1933
Emby.Server.Implementations/Session/SessionManager.cs
Normal file
1933
Emby.Server.Implementations/Session/SessionManager.cs
Normal file
File diff suppressed because it is too large
Load Diff
485
Emby.Server.Implementations/Session/SessionWebSocketListener.cs
Normal file
485
Emby.Server.Implementations/Session/SessionWebSocketListener.cs
Normal file
@@ -0,0 +1,485 @@
|
||||
using MediaBrowser.Controller.Net;
|
||||
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;
|
||||
using MediaBrowser.Model.Services;
|
||||
|
||||
namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
/// <summary>
|
||||
/// Class SessionWebSocketListener
|
||||
/// </summary>
|
||||
public class SessionWebSocketListener : IWebSocketListener, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The _true task result
|
||||
/// </summary>
|
||||
private readonly Task _trueTaskResult = Task.FromResult(true);
|
||||
|
||||
/// <summary>
|
||||
/// The _session manager
|
||||
/// </summary>
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
/// <summary>
|
||||
/// The _logger
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The _dto service
|
||||
/// </summary>
|
||||
private readonly IJsonSerializer _json;
|
||||
|
||||
private readonly IHttpServer _httpServer;
|
||||
private readonly IServerManager _serverManager;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SessionWebSocketListener" /> class.
|
||||
/// </summary>
|
||||
/// <param name="sessionManager">The session manager.</param>
|
||||
/// <param name="logManager">The log manager.</param>
|
||||
/// <param name="json">The json.</param>
|
||||
/// <param name="httpServer">The HTTP server.</param>
|
||||
/// <param name="serverManager">The server manager.</param>
|
||||
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;
|
||||
}
|
||||
|
||||
async void _serverManager_WebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
|
||||
{
|
||||
var session = await GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint).ConfigureAwait(false);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
async void _httpServer_WebSocketConnecting(object sender, WebSocketConnectingEventArgs e)
|
||||
{
|
||||
//var token = e.QueryString["api_key"];
|
||||
//if (!string.IsNullOrWhiteSpace(token))
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// var session = await GetSession(e.QueryString, e.Endpoint).ConfigureAwait(false);
|
||||
|
||||
// if (session == null)
|
||||
// {
|
||||
// e.AllowConnection = false;
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// _logger.ErrorException("Error getting session info", ex);
|
||||
// }
|
||||
//}
|
||||
}
|
||||
|
||||
private Task<SessionInfo> GetSession(QueryParamCollection queryString, string remoteEndpoint)
|
||||
{
|
||||
if (queryString == null)
|
||||
{
|
||||
throw new ArgumentNullException("queryString");
|
||||
}
|
||||
|
||||
var token = queryString["api_key"];
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return Task.FromResult<SessionInfo>(null);
|
||||
}
|
||||
var deviceId = queryString["deviceId"];
|
||||
return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_httpServer.WebSocketConnecting -= _httpServer_WebSocketConnecting;
|
||||
_serverManager.WebSocketConnected -= _serverManager_WebSocketConnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the message.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task ProcessMessage(WebSocketMessageInfo message)
|
||||
{
|
||||
if (string.Equals(message.MessageType, "Identity", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ProcessIdentityMessage(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "Context", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ProcessContextMessage(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "PlaybackStart", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
OnPlaybackStart(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "PlaybackProgress", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
OnPlaybackProgress(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "PlaybackStopped", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
OnPlaybackStopped(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "ReportPlaybackStart", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ReportPlaybackStart(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "ReportPlaybackProgress", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ReportPlaybackProgress(message);
|
||||
}
|
||||
else if (string.Equals(message.MessageType, "ReportPlaybackStopped", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ReportPlaybackStopped(message);
|
||||
}
|
||||
|
||||
return _trueTaskResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the identity message.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private async void ProcessIdentityMessage(WebSocketMessageInfo message)
|
||||
{
|
||||
_logger.Debug("Received Identity message: " + message.Data);
|
||||
|
||||
var vals = message.Data.Split('|');
|
||||
|
||||
if (vals.Length < 3)
|
||||
{
|
||||
_logger.Error("Client sent invalid identity message.");
|
||||
return;
|
||||
}
|
||||
|
||||
var client = vals[0];
|
||||
var deviceId = vals[1];
|
||||
var version = vals[2];
|
||||
var deviceName = vals.Length > 3 ? vals[3] : string.Empty;
|
||||
|
||||
var session = _sessionManager.GetSession(deviceId, client, version);
|
||||
|
||||
if (session == null && !string.IsNullOrEmpty(deviceName))
|
||||
{
|
||||
_logger.Debug("Logging session activity");
|
||||
|
||||
session = await _sessionManager.LogSessionActivity(client, version, deviceId, deviceName, message.Connection.RemoteEndPoint, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (session != null)
|
||||
{
|
||||
var controller = session.SessionController as WebSocketController;
|
||||
|
||||
if (controller == null)
|
||||
{
|
||||
controller = new WebSocketController(session, _logger, _sessionManager);
|
||||
}
|
||||
|
||||
controller.AddWebSocket(message.Connection);
|
||||
|
||||
session.SessionController = controller;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Warn("Unable to determine session based on identity message: {0}", message.Data);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the context message.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private void ProcessContextMessage(WebSocketMessageInfo message)
|
||||
{
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null)
|
||||
{
|
||||
var vals = message.Data.Split('|');
|
||||
|
||||
var itemId = vals[1];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(itemId))
|
||||
{
|
||||
_sessionManager.ReportNowViewingItem(session.Id, itemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the session from message.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <returns>SessionInfo.</returns>
|
||||
private SessionInfo GetSessionFromMessage(WebSocketMessageInfo message)
|
||||
{
|
||||
var result = _sessionManager.Sessions.FirstOrDefault(i =>
|
||||
{
|
||||
var controller = i.SessionController as WebSocketController;
|
||||
|
||||
if (controller != null)
|
||||
{
|
||||
if (controller.Sockets.Any(s => s.Id == message.Connection.Id))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
});
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
_logger.Error("Unable to find session based on web socket message");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
|
||||
|
||||
/// <summary>
|
||||
/// Reports the playback start.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private void OnPlaybackStart(WebSocketMessageInfo message)
|
||||
{
|
||||
_logger.Debug("Received PlaybackStart message");
|
||||
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var vals = message.Data.Split('|');
|
||||
|
||||
var itemId = vals[0];
|
||||
|
||||
var queueableMediaTypes = string.Empty;
|
||||
var canSeek = true;
|
||||
|
||||
if (vals.Length > 1)
|
||||
{
|
||||
canSeek = string.Equals(vals[1], "true", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
if (vals.Length > 2)
|
||||
{
|
||||
queueableMediaTypes = vals[2];
|
||||
}
|
||||
|
||||
var info = new PlaybackStartInfo
|
||||
{
|
||||
CanSeek = canSeek,
|
||||
ItemId = itemId,
|
||||
SessionId = session.Id,
|
||||
QueueableMediaTypes = queueableMediaTypes.Split(',').ToList()
|
||||
};
|
||||
|
||||
if (vals.Length > 3)
|
||||
{
|
||||
info.MediaSourceId = vals[3];
|
||||
}
|
||||
|
||||
if (vals.Length > 4 && !string.IsNullOrWhiteSpace(vals[4]))
|
||||
{
|
||||
info.AudioStreamIndex = int.Parse(vals[4], _usCulture);
|
||||
}
|
||||
|
||||
if (vals.Length > 5 && !string.IsNullOrWhiteSpace(vals[5]))
|
||||
{
|
||||
info.SubtitleStreamIndex = int.Parse(vals[5], _usCulture);
|
||||
}
|
||||
|
||||
_sessionManager.OnPlaybackStart(info);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReportPlaybackStart(WebSocketMessageInfo message)
|
||||
{
|
||||
_logger.Debug("Received ReportPlaybackStart message");
|
||||
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var info = _json.DeserializeFromString<PlaybackStartInfo>(message.Data);
|
||||
|
||||
info.SessionId = session.Id;
|
||||
|
||||
_sessionManager.OnPlaybackStart(info);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReportPlaybackProgress(WebSocketMessageInfo message)
|
||||
{
|
||||
//_logger.Debug("Received ReportPlaybackProgress message");
|
||||
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var info = _json.DeserializeFromString<PlaybackProgressInfo>(message.Data);
|
||||
|
||||
info.SessionId = session.Id;
|
||||
|
||||
_sessionManager.OnPlaybackProgress(info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the playback progress.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private void OnPlaybackProgress(WebSocketMessageInfo message)
|
||||
{
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var vals = message.Data.Split('|');
|
||||
|
||||
var itemId = vals[0];
|
||||
|
||||
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);
|
||||
var isMuted = vals.Length > 3 && string.Equals(vals[3], "true", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var info = new PlaybackProgressInfo
|
||||
{
|
||||
ItemId = itemId,
|
||||
PositionTicks = positionTicks,
|
||||
IsMuted = isMuted,
|
||||
IsPaused = isPaused,
|
||||
SessionId = session.Id
|
||||
};
|
||||
|
||||
if (vals.Length > 4)
|
||||
{
|
||||
info.MediaSourceId = vals[4];
|
||||
}
|
||||
|
||||
if (vals.Length > 5 && !string.IsNullOrWhiteSpace(vals[5]))
|
||||
{
|
||||
info.VolumeLevel = int.Parse(vals[5], _usCulture);
|
||||
}
|
||||
|
||||
if (vals.Length > 5 && !string.IsNullOrWhiteSpace(vals[6]))
|
||||
{
|
||||
info.AudioStreamIndex = int.Parse(vals[6], _usCulture);
|
||||
}
|
||||
|
||||
if (vals.Length > 7 && !string.IsNullOrWhiteSpace(vals[7]))
|
||||
{
|
||||
info.SubtitleStreamIndex = int.Parse(vals[7], _usCulture);
|
||||
}
|
||||
|
||||
_sessionManager.OnPlaybackProgress(info);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReportPlaybackStopped(WebSocketMessageInfo message)
|
||||
{
|
||||
_logger.Debug("Received ReportPlaybackStopped message");
|
||||
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var info = _json.DeserializeFromString<PlaybackStopInfo>(message.Data);
|
||||
|
||||
info.SessionId = session.Id;
|
||||
|
||||
_sessionManager.OnPlaybackStopped(info);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the playback stopped.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private void OnPlaybackStopped(WebSocketMessageInfo message)
|
||||
{
|
||||
_logger.Debug("Received PlaybackStopped message");
|
||||
|
||||
var session = GetSessionFromMessage(message);
|
||||
|
||||
if (session != null && session.UserId.HasValue)
|
||||
{
|
||||
var vals = message.Data.Split('|');
|
||||
|
||||
var itemId = vals[0];
|
||||
|
||||
long? positionTicks = null;
|
||||
|
||||
if (vals.Length > 1)
|
||||
{
|
||||
long pos;
|
||||
|
||||
if (long.TryParse(vals[1], out pos))
|
||||
{
|
||||
positionTicks = pos;
|
||||
}
|
||||
}
|
||||
|
||||
var info = new PlaybackStopInfo
|
||||
{
|
||||
ItemId = itemId,
|
||||
PositionTicks = positionTicks,
|
||||
SessionId = session.Id
|
||||
};
|
||||
|
||||
if (vals.Length > 2)
|
||||
{
|
||||
info.MediaSourceId = vals[2];
|
||||
}
|
||||
|
||||
_sessionManager.OnPlaybackStopped(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
288
Emby.Server.Implementations/Session/WebSocketController.cs
Normal file
288
Emby.Server.Implementations/Session/WebSocketController.cs
Normal file
@@ -0,0 +1,288 @@
|
||||
using MediaBrowser.Controller.Net;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Model.Session;
|
||||
using MediaBrowser.Model.System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
public class WebSocketController : ISessionController, IDisposable
|
||||
{
|
||||
public SessionInfo Session { get; private set; }
|
||||
public IReadOnlyList<IWebSocketConnection> Sockets { get; private set; }
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
public WebSocketController(SessionInfo session, ILogger logger, ISessionManager sessionManager)
|
||||
{
|
||||
Session = session;
|
||||
_logger = logger;
|
||||
_sessionManager = sessionManager;
|
||||
Sockets = new List<IWebSocketConnection>();
|
||||
}
|
||||
|
||||
private bool HasOpenSockets
|
||||
{
|
||||
get { return GetActiveSockets().Any(); }
|
||||
}
|
||||
|
||||
public bool SupportsMediaControl
|
||||
{
|
||||
get { return HasOpenSockets; }
|
||||
}
|
||||
|
||||
private bool _isActive;
|
||||
private DateTime _lastActivityDate;
|
||||
public bool IsSessionActive
|
||||
{
|
||||
get
|
||||
{
|
||||
if (HasOpenSockets)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
//return false;
|
||||
return _isActive && (DateTime.UtcNow - _lastActivityDate).TotalMinutes <= 10;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnActivity()
|
||||
{
|
||||
_isActive = true;
|
||||
_lastActivityDate = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
private IEnumerable<IWebSocketConnection> GetActiveSockets()
|
||||
{
|
||||
return Sockets
|
||||
.OrderByDescending(i => i.LastActivityDate)
|
||||
.Where(i => i.State == WebSocketState.Open);
|
||||
}
|
||||
|
||||
public void AddWebSocket(IWebSocketConnection connection)
|
||||
{
|
||||
var sockets = Sockets.ToList();
|
||||
sockets.Add(connection);
|
||||
|
||||
Sockets = sockets;
|
||||
|
||||
connection.Closed += connection_Closed;
|
||||
}
|
||||
|
||||
void connection_Closed(object sender, EventArgs e)
|
||||
{
|
||||
if (!GetActiveSockets().Any())
|
||||
{
|
||||
_isActive = false;
|
||||
|
||||
try
|
||||
{
|
||||
_sessionManager.ReportSessionEnded(Session.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error reporting session ended.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IWebSocketConnection GetActiveSocket()
|
||||
{
|
||||
var socket = GetActiveSockets()
|
||||
.FirstOrDefault();
|
||||
|
||||
if (socket == null)
|
||||
{
|
||||
throw new InvalidOperationException("The requested session does not have an open web socket.");
|
||||
}
|
||||
|
||||
return socket;
|
||||
}
|
||||
|
||||
public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessageInternal(new WebSocketMessage<PlayRequest>
|
||||
{
|
||||
MessageType = "Play",
|
||||
Data = command
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessageInternal(new WebSocketMessage<PlaystateRequest>
|
||||
{
|
||||
MessageType = "Playstate",
|
||||
Data = command
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<LibraryUpdateInfo>
|
||||
{
|
||||
MessageType = "LibraryChanged",
|
||||
Data = info
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the restart required message.
|
||||
/// </summary>
|
||||
/// <param name="info">The information.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SendRestartRequiredNotification(SystemInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<SystemInfo>
|
||||
{
|
||||
MessageType = "RestartRequired",
|
||||
Data = info
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Sends the user data change info.
|
||||
/// </summary>
|
||||
/// <param name="info">The info.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SendUserDataChangeInfo(UserDataChangeInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<UserDataChangeInfo>
|
||||
{
|
||||
MessageType = "UserDataChanged",
|
||||
Data = info
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the server shutdown notification.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SendServerShutdownNotification(CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<string>
|
||||
{
|
||||
MessageType = "ServerShuttingDown",
|
||||
Data = string.Empty
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends the server restart notification.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public Task SendServerRestartNotification(CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<string>
|
||||
{
|
||||
MessageType = "ServerRestarting",
|
||||
Data = string.Empty
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessageInternal(new WebSocketMessage<GeneralCommand>
|
||||
{
|
||||
MessageType = "GeneralCommand",
|
||||
Data = command
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<SessionInfoDto>
|
||||
{
|
||||
MessageType = "SessionEnded",
|
||||
Data = sessionInfo
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendPlaybackStartNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<SessionInfoDto>
|
||||
{
|
||||
MessageType = "PlaybackStart",
|
||||
Data = sessionInfo
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendPlaybackStoppedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<SessionInfoDto>
|
||||
{
|
||||
MessageType = "PlaybackStopped",
|
||||
Data = sessionInfo
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendMessage<T>(string name, T data, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<T>
|
||||
{
|
||||
Data = data,
|
||||
MessageType = name
|
||||
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
private Task SendMessageInternal<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
|
||||
{
|
||||
var socket = GetActiveSocket();
|
||||
|
||||
return socket.SendAsync(message, cancellationToken);
|
||||
}
|
||||
|
||||
private Task SendMessagesInternal<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
|
||||
{
|
||||
var tasks = GetActiveSockets().Select(i => Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await i.SendAsync(message, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error sending web socket message", ex);
|
||||
}
|
||||
|
||||
}, cancellationToken));
|
||||
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var socket in Sockets.ToList())
|
||||
{
|
||||
socket.Closed -= connection_Closed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user