mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-06-03 14:28:46 +01:00
Update to 3.5.2 and .net core 2.1
This commit is contained in:
131
Emby.Server.Implementations/Session/FirebaseSessionController.cs
Normal file
131
Emby.Server.Implementations/Session/FirebaseSessionController.cs
Normal file
@@ -0,0 +1,131 @@
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Text;
|
||||
using MediaBrowser.Common;
|
||||
|
||||
namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
public class FirebaseSessionController : ISessionController
|
||||
{
|
||||
private readonly IHttpClient _httpClient;
|
||||
private readonly IJsonSerializer _json;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
|
||||
public SessionInfo Session { get; private set; }
|
||||
|
||||
private readonly string _token;
|
||||
|
||||
private IApplicationHost _appHost;
|
||||
private string _senderId;
|
||||
private string _applicationId;
|
||||
|
||||
public FirebaseSessionController(IHttpClient httpClient,
|
||||
IApplicationHost appHost,
|
||||
IJsonSerializer json,
|
||||
SessionInfo session,
|
||||
string token, ISessionManager sessionManager)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_json = json;
|
||||
_appHost = appHost;
|
||||
Session = session;
|
||||
_token = token;
|
||||
_sessionManager = sessionManager;
|
||||
|
||||
_applicationId = _appHost.GetValue("firebase_applicationid");
|
||||
_senderId = _appHost.GetValue("firebase_senderid");
|
||||
}
|
||||
|
||||
public static bool IsSupported(IApplicationHost appHost)
|
||||
{
|
||||
return !string.IsNullOrEmpty(appHost.GetValue("firebase_applicationid")) && !string.IsNullOrEmpty(appHost.GetValue("firebase_senderid"));
|
||||
}
|
||||
|
||||
public bool IsSessionActive
|
||||
{
|
||||
get
|
||||
{
|
||||
return (DateTime.UtcNow - Session.LastActivityDate).TotalDays <= 3;
|
||||
}
|
||||
}
|
||||
|
||||
public bool SupportsMediaControl
|
||||
{
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public async Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!IsSessionActive)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(_senderId) || string.IsNullOrEmpty(_applicationId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var controller in allControllers)
|
||||
{
|
||||
// Don't send if there's an active web socket connection
|
||||
if ((controller is WebSocketController) && controller.IsSessionActive)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var msg = new WebSocketMessage<T>
|
||||
{
|
||||
Data = data,
|
||||
MessageType = name,
|
||||
MessageId = messageId,
|
||||
ServerId = _appHost.SystemId
|
||||
};
|
||||
|
||||
var req = new FirebaseBody<T>
|
||||
{
|
||||
to = _token,
|
||||
data = msg
|
||||
};
|
||||
|
||||
var byteArray = Encoding.UTF8.GetBytes(_json.SerializeToString(req));
|
||||
|
||||
var enableLogging = false;
|
||||
|
||||
#if DEBUG
|
||||
enableLogging = true;
|
||||
#endif
|
||||
|
||||
var options = new HttpRequestOptions
|
||||
{
|
||||
Url = "https://fcm.googleapis.com/fcm/send",
|
||||
RequestContentType = "application/json",
|
||||
RequestContentBytes = byteArray,
|
||||
CancellationToken = cancellationToken,
|
||||
LogRequest = enableLogging,
|
||||
LogResponse = enableLogging,
|
||||
LogErrors = enableLogging
|
||||
};
|
||||
|
||||
options.RequestHeaders["Authorization"] = string.Format("key={0}", _applicationId);
|
||||
options.RequestHeaders["Sender"] = string.Format("id={0}", _senderId);
|
||||
|
||||
using (var response = await _httpClient.Post(options).ConfigureAwait(false))
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class FirebaseBody<T>
|
||||
{
|
||||
public string to { get; set; }
|
||||
public WebSocketMessage<T> data { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -36,10 +36,6 @@ namespace Emby.Server.Implementations.Session
|
||||
_sessionManager = sessionManager;
|
||||
}
|
||||
|
||||
public void OnActivity()
|
||||
{
|
||||
}
|
||||
|
||||
private string PostUrl
|
||||
{
|
||||
get
|
||||
@@ -52,7 +48,7 @@ namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
get
|
||||
{
|
||||
return (DateTime.UtcNow - Session.LastActivityDate).TotalMinutes <= 10;
|
||||
return (DateTime.UtcNow - Session.LastActivityDate).TotalMinutes <= 5;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,49 +57,29 @@ namespace Emby.Server.Implementations.Session
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
private Task SendMessage(string name, CancellationToken cancellationToken)
|
||||
private Task SendMessage(string name, string messageId, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage(name, new Dictionary<string, string>(), cancellationToken);
|
||||
return SendMessage(name, messageId, new Dictionary<string, string>(), cancellationToken);
|
||||
}
|
||||
|
||||
private async Task SendMessage(string name,
|
||||
Dictionary<string, string> args,
|
||||
CancellationToken cancellationToken)
|
||||
private Task SendMessage(string name, string messageId, Dictionary<string, string> args, CancellationToken cancellationToken)
|
||||
{
|
||||
args["messageId"] = messageId;
|
||||
var url = PostUrl + "/" + name + ToQueryString(args);
|
||||
|
||||
using ((await _httpClient.Post(new HttpRequestOptions
|
||||
return SendRequest(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)
|
||||
private Task SendPlayCommand(PlayRequest command, string messageId, CancellationToken cancellationToken)
|
||||
{
|
||||
var dict = new Dictionary<string, string>();
|
||||
|
||||
dict["ItemIds"] = string.Join(",", command.ItemIds);
|
||||
dict["ItemIds"] = string.Join(",", command.ItemIds.Select(i => i.ToString("N")).ToArray());
|
||||
|
||||
if (command.StartPositionTicks.HasValue)
|
||||
{
|
||||
@@ -121,15 +97,15 @@ namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
dict["StartIndex"] = command.StartIndex.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(command.MediaSourceId))
|
||||
if (!string.IsNullOrEmpty(command.MediaSourceId))
|
||||
{
|
||||
dict["MediaSourceId"] = command.MediaSourceId;
|
||||
}
|
||||
|
||||
return SendMessage(command.PlayCommand.ToString(), dict, cancellationToken);
|
||||
return SendMessage(command.PlayCommand.ToString(), messageId, dict, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
|
||||
private Task SendPlaystateCommand(PlaystateRequest command, string messageId, CancellationToken cancellationToken)
|
||||
{
|
||||
var args = new Dictionary<string, string>();
|
||||
|
||||
@@ -143,60 +119,74 @@ namespace Emby.Server.Implementations.Session
|
||||
args["SeekPositionTicks"] = command.SeekPositionTicks.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return SendMessage(command.Command.ToString(), args, cancellationToken);
|
||||
return SendMessage(command.Command.ToString(), messageId, args, cancellationToken);
|
||||
}
|
||||
|
||||
public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
|
||||
private string[] _supportedMessages = new string[] { };
|
||||
public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessage("LibraryChanged", info, cancellationToken);
|
||||
if (!IsSessionActive)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (string.Equals(name, "Play", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return SendPlayCommand(data as PlayRequest, messageId, cancellationToken);
|
||||
}
|
||||
if (string.Equals(name, "PlayState", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return SendPlaystateCommand(data as PlaystateRequest, messageId, cancellationToken);
|
||||
}
|
||||
if (string.Equals(name, "GeneralCommand", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var command = data as GeneralCommand;
|
||||
return SendMessage(command.Name, messageId, command.Arguments, cancellationToken);
|
||||
}
|
||||
|
||||
if (!_supportedMessages.Contains(name, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var url = PostUrl + "/" + name;
|
||||
|
||||
url += "?messageId=" + messageId;
|
||||
|
||||
var options = new HttpRequestOptions
|
||||
{
|
||||
Url = url,
|
||||
CancellationToken = cancellationToken,
|
||||
BufferContent = false
|
||||
};
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
if (typeof(T) == typeof(string))
|
||||
{
|
||||
var str = data as String;
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
{
|
||||
options.RequestContent = str;
|
||||
options.RequestContentType = "application/json";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
options.RequestContent = _json.SerializeToString(data);
|
||||
options.RequestContentType = "application/json";
|
||||
}
|
||||
}
|
||||
|
||||
return SendRequest(options);
|
||||
}
|
||||
|
||||
public Task SendRestartRequiredNotification(CancellationToken cancellationToken)
|
||||
private async Task SendRequest(HttpRequestOptions options)
|
||||
{
|
||||
return SendMessage("RestartRequired", cancellationToken);
|
||||
}
|
||||
using (var response = await _httpClient.Post(options).ConfigureAwait(false))
|
||||
{
|
||||
|
||||
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)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
//var url = PostUrl + "/" + name;
|
||||
|
||||
//var options = new HttpRequestOptions
|
||||
//{
|
||||
// Url = url,
|
||||
// CancellationToken = cancellationToken,
|
||||
// BufferContent = false
|
||||
//};
|
||||
|
||||
//options.RequestContent = _json.SerializeToString(data);
|
||||
//options.RequestContentType = "application/json";
|
||||
|
||||
//return _httpClient.Post(new HttpRequestOptions
|
||||
//{
|
||||
// Url = url,
|
||||
// CancellationToken = cancellationToken,
|
||||
// BufferContent = false
|
||||
//});
|
||||
}
|
||||
}
|
||||
|
||||
private string ToQueryString(Dictionary<string, string> nvc)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,11 +18,6 @@ namespace Emby.Server.Implementations.Session
|
||||
/// </summary>
|
||||
public class SessionWebSocketListener : IWebSocketListener, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The _true task result
|
||||
/// </summary>
|
||||
private readonly Task _trueTaskResult = Task.FromResult(true);
|
||||
|
||||
/// <summary>
|
||||
/// The _session manager
|
||||
/// </summary>
|
||||
@@ -39,7 +34,6 @@ namespace Emby.Server.Implementations.Session
|
||||
private readonly IJsonSerializer _json;
|
||||
|
||||
private readonly IHttpServer _httpServer;
|
||||
private readonly IServerManager _serverManager;
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -50,32 +44,22 @@ namespace Emby.Server.Implementations.Session
|
||||
/// <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)
|
||||
public SessionWebSocketListener(ISessionManager sessionManager, ILogManager logManager, IJsonSerializer json, IHttpServer httpServer)
|
||||
{
|
||||
_sessionManager = sessionManager;
|
||||
_logger = logManager.GetLogger(GetType().Name);
|
||||
_json = json;
|
||||
_httpServer = httpServer;
|
||||
_serverManager = serverManager;
|
||||
serverManager.WebSocketConnected += _serverManager_WebSocketConnected;
|
||||
httpServer.WebSocketConnected += _serverManager_WebSocketConnected;
|
||||
}
|
||||
|
||||
async void _serverManager_WebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
|
||||
void _serverManager_WebSocketConnected(object sender, GenericEventArgs<IWebSocketConnection> e)
|
||||
{
|
||||
var session = await GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint).ConfigureAwait(false);
|
||||
var session = GetSession(e.Argument.QueryString, e.Argument.RemoteEndPoint);
|
||||
|
||||
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;
|
||||
EnsureController(session, e.Argument);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -83,7 +67,7 @@ namespace Emby.Server.Implementations.Session
|
||||
}
|
||||
}
|
||||
|
||||
private Task<SessionInfo> GetSession(QueryParamCollection queryString, string remoteEndpoint)
|
||||
private SessionInfo GetSession(QueryParamCollection queryString, string remoteEndpoint)
|
||||
{
|
||||
if (queryString == null)
|
||||
{
|
||||
@@ -93,7 +77,7 @@ namespace Emby.Server.Implementations.Session
|
||||
var token = queryString["api_key"];
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return Task.FromResult<SessionInfo>(null);
|
||||
return null;
|
||||
}
|
||||
var deviceId = queryString["deviceId"];
|
||||
return _sessionManager.GetSessionByAuthenticationToken(token, deviceId, remoteEndpoint);
|
||||
@@ -101,8 +85,7 @@ namespace Emby.Server.Implementations.Session
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_serverManager.WebSocketConnected -= _serverManager_WebSocketConnected;
|
||||
GC.SuppressFinalize(this);
|
||||
_httpServer.WebSocketConnected -= _serverManager_WebSocketConnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -112,350 +95,15 @@ namespace Emby.Server.Implementations.Session
|
||||
/// <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;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the identity message.
|
||||
/// </summary>
|
||||
/// <param name="message">The message.</param>
|
||||
private async void ProcessIdentityMessage(WebSocketMessageInfo message)
|
||||
private void EnsureController(SessionInfo session, IWebSocketConnection connection)
|
||||
{
|
||||
_logger.Debug("Received Identity message: " + message.Data);
|
||||
var controllerInfo = session.EnsureController<WebSocketController>(s => new WebSocketController(s, _logger, _sessionManager));
|
||||
|
||||
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 canSeek = true;
|
||||
|
||||
if (vals.Length > 1)
|
||||
{
|
||||
canSeek = string.Equals(vals[1], "true", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
if (vals.Length > 2)
|
||||
{
|
||||
// vals[2] used to be QueueableMediaTypes
|
||||
}
|
||||
|
||||
var info = new PlaybackStartInfo
|
||||
{
|
||||
CanSeek = canSeek,
|
||||
ItemId = itemId,
|
||||
SessionId = session.Id
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
var controller = (WebSocketController)controllerInfo.Item1;
|
||||
controller.AddWebSocket(connection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Net.WebSockets;
|
||||
|
||||
namespace Emby.Server.Implementations.Session
|
||||
{
|
||||
@@ -40,28 +41,14 @@ namespace Emby.Server.Implementations.Session
|
||||
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;
|
||||
return HasOpenSockets;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnActivity()
|
||||
{
|
||||
_isActive = true;
|
||||
_lastActivityDate = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
private IEnumerable<IWebSocketConnection> GetActiveSockets()
|
||||
{
|
||||
return Sockets
|
||||
@@ -81,209 +68,40 @@ namespace Emby.Server.Implementations.Session
|
||||
|
||||
void connection_Closed(object sender, EventArgs e)
|
||||
{
|
||||
if (!GetActiveSockets().Any())
|
||||
{
|
||||
_isActive = false;
|
||||
var connection = (IWebSocketConnection)sender;
|
||||
var sockets = Sockets.ToList();
|
||||
sockets.Remove(connection);
|
||||
|
||||
try
|
||||
{
|
||||
_sessionManager.ReportSessionEnded(Session.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error reporting session ended.", ex);
|
||||
}
|
||||
}
|
||||
Sockets = sockets;
|
||||
|
||||
_sessionManager.CloseIfNeeded(Session);
|
||||
}
|
||||
|
||||
private IWebSocketConnection GetActiveSocket()
|
||||
public Task SendMessage<T>(string name, string messageId, T data, ISessionController[] allControllers, CancellationToken cancellationToken)
|
||||
{
|
||||
var socket = GetActiveSockets()
|
||||
.FirstOrDefault();
|
||||
|
||||
if (socket == null)
|
||||
{
|
||||
throw new InvalidOperationException("The requested session does not have an open web socket.");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
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(CancellationToken cancellationToken)
|
||||
{
|
||||
return SendMessagesInternal(new WebSocketMessage<string>
|
||||
{
|
||||
MessageType = "RestartRequired",
|
||||
Data = string.Empty
|
||||
|
||||
}, 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>
|
||||
return socket.SendAsync(new WebSocketMessage<T>
|
||||
{
|
||||
Data = data,
|
||||
MessageType = name
|
||||
MessageType = name,
|
||||
MessageId = messageId
|
||||
|
||||
}, 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;
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user