jellyfin/Emby.Server.Implementations/Session/SessionManager.cs

1892 lines
64 KiB
C#
Raw Normal View History

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Extensions;
2014-05-18 12:58:42 -07:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Authentication;
2014-10-11 13:38:13 -07:00
using MediaBrowser.Controller.Devices;
2014-04-06 10:53:23 -07:00
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
2014-04-06 10:53:23 -07:00
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
2014-07-07 18:41:03 -07:00
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Session;
2014-10-13 13:14:53 -07:00
using MediaBrowser.Model.Devices;
2015-03-29 09:45:16 -07:00
using MediaBrowser.Model.Dto;
2013-10-02 10:23:10 -07:00
using MediaBrowser.Model.Entities;
2014-08-10 15:13:17 -07:00
using MediaBrowser.Model.Events;
2014-02-20 22:35:56 -07:00
using MediaBrowser.Model.Library;
using MediaBrowser.Model.Querying;
2014-05-18 12:58:42 -07:00
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
2016-11-03 16:35:19 -07:00
namespace Emby.Server.Implementations.Session
{
2013-05-10 05:18:07 -07:00
/// <summary>
/// Class SessionManager
/// </summary>
2018-09-12 10:26:21 -07:00
public class SessionManager : ISessionManager, IDisposable
{
2013-05-10 05:18:07 -07:00
/// <summary>
/// The _user data repository
/// </summary>
private readonly IUserDataManager _userDataManager;
/// <summary>
/// The _logger
/// </summary>
private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
private readonly IMusicManager _musicManager;
2014-04-06 10:53:23 -07:00
private readonly IDtoService _dtoService;
private readonly IImageProcessor _imageProcessor;
private readonly IMediaSourceManager _mediaSourceManager;
2014-05-18 12:58:42 -07:00
private readonly IHttpClient _httpClient;
private readonly IJsonSerializer _jsonSerializer;
private readonly IServerApplicationHost _appHost;
2014-07-07 18:41:03 -07:00
private readonly IAuthenticationRepository _authRepo;
2014-10-11 13:38:13 -07:00
private readonly IDeviceManager _deviceManager;
2014-07-07 18:41:03 -07:00
/// <summary>
/// The _active connections
/// </summary>
2013-10-07 20:06:12 -07:00
private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections =
new ConcurrentDictionary<string, SessionInfo>(StringComparer.OrdinalIgnoreCase);
2014-08-10 15:13:17 -07:00
public event EventHandler<GenericEventArgs<AuthenticationRequest>> AuthenticationFailed;
2018-09-12 10:26:21 -07:00
public event EventHandler<GenericEventArgs<AuthenticationResult>> AuthenticationSucceeded;
2014-10-11 13:38:13 -07:00
/// <summary>
/// Occurs when [playback start].
/// </summary>
public event EventHandler<PlaybackProgressEventArgs> PlaybackStart;
/// <summary>
/// Occurs when [playback progress].
/// </summary>
public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
/// <summary>
/// Occurs when [playback stopped].
/// </summary>
2013-12-30 10:18:18 -07:00
public event EventHandler<PlaybackStopEventArgs> PlaybackStopped;
2014-04-06 10:53:23 -07:00
public event EventHandler<SessionEventArgs> SessionStarted;
2014-05-13 17:46:45 -07:00
public event EventHandler<SessionEventArgs> CapabilitiesChanged;
2014-04-06 10:53:23 -07:00
public event EventHandler<SessionEventArgs> SessionEnded;
2014-05-13 17:46:45 -07:00
public event EventHandler<SessionEventArgs> SessionActivity;
2014-04-06 10:53:23 -07:00
public SessionManager(
IUserDataManager userDataManager,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager,
IUserManager userManager,
IMusicManager musicManager,
IDtoService dtoService,
IImageProcessor imageProcessor,
IJsonSerializer jsonSerializer,
IServerApplicationHost appHost,
IHttpClient httpClient,
IAuthenticationRepository authRepo,
IDeviceManager deviceManager,
2019-02-05 01:49:46 -07:00
IMediaSourceManager mediaSourceManager)
{
_userDataManager = userDataManager;
_logger = loggerFactory.CreateLogger(nameof(SessionManager));
_libraryManager = libraryManager;
_userManager = userManager;
2014-04-02 14:55:19 -07:00
_musicManager = musicManager;
2014-04-06 10:53:23 -07:00
_dtoService = dtoService;
_imageProcessor = imageProcessor;
2014-05-18 12:58:42 -07:00
_jsonSerializer = jsonSerializer;
_appHost = appHost;
_httpClient = httpClient;
2014-07-07 18:41:03 -07:00
_authRepo = authRepo;
2014-10-11 13:38:13 -07:00
_deviceManager = deviceManager;
_mediaSourceManager = mediaSourceManager;
2014-10-13 13:14:53 -07:00
_deviceManager.DeviceOptionsUpdated += _deviceManager_DeviceOptionsUpdated;
}
2018-09-12 10:26:21 -07:00
private void _deviceManager_DeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
2014-10-13 13:14:53 -07:00
{
foreach (var session in Sessions)
{
2018-09-12 10:26:21 -07:00
if (string.Equals(session.DeviceId, e.Argument.Item1))
2014-10-13 13:14:53 -07:00
{
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName))
{
session.HasCustomDeviceName = true;
session.DeviceName = e.Argument.Item2.CustomName;
}
else
{
session.HasCustomDeviceName = false;
}
2014-10-13 13:14:53 -07:00
}
}
}
2018-09-12 10:26:21 -07:00
private bool _disposed;
public void Dispose()
{
_disposed = true;
_deviceManager.DeviceOptionsUpdated -= _deviceManager_DeviceOptionsUpdated;
}
public void CheckDisposed()
{
2018-09-12 10:26:21 -07:00
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Gets all connections.
/// </summary>
/// <value>All connections.</value>
public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList();
2014-04-06 10:53:23 -07:00
private void OnSessionStarted(SessionInfo info)
{
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrEmpty(info.DeviceId))
2014-06-03 20:34:36 -07:00
{
var capabilities = GetSavedCapabilities(info.DeviceId);
if (capabilities != null)
{
ReportCapabilities(info, capabilities, false);
}
}
2014-04-06 10:53:23 -07:00
2018-09-12 10:26:21 -07:00
EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
2014-04-06 10:53:23 -07:00
{
2018-09-12 10:26:21 -07:00
SessionInfo = info
2014-04-06 10:53:23 -07:00
2018-09-12 10:26:21 -07:00
}, _logger);
}
private void OnSessionEnded(SessionInfo info)
{
2014-04-06 10:53:23 -07:00
EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
{
SessionInfo = info
}, _logger);
2018-09-12 10:26:21 -07:00
info.Dispose();
}
2014-04-06 10:53:23 -07:00
2018-09-12 10:26:21 -07:00
public void UpdateDeviceName(string sessionId, string deviceName)
{
var session = GetSession(sessionId);
2014-05-29 07:19:12 -07:00
2018-09-12 10:26:21 -07:00
var key = GetSessionKey(session.Client, session.DeviceId);
2017-04-17 11:40:42 -07:00
2018-09-12 10:26:21 -07:00
if (session != null)
{
session.DeviceName = deviceName;
}
2014-04-06 10:53:23 -07:00
}
/// <summary>
/// Logs the user activity.
/// </summary>
2015-03-14 18:42:09 -07:00
/// <param name="appName">Type of the client.</param>
/// <param name="appVersion">The app version.</param>
/// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
2019-01-13 13:37:13 -07:00
/// <exception cref="ArgumentNullException">user</exception>
/// <exception cref="UnauthorizedAccessException"></exception>
2018-09-12 10:26:21 -07:00
public SessionInfo LogSessionActivity(string appName,
2014-07-07 18:41:03 -07:00
string appVersion,
string deviceId,
string deviceName,
string remoteEndPoint,
User user)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2015-03-14 18:42:09 -07:00
if (string.IsNullOrEmpty(appName))
{
throw new ArgumentNullException(nameof(appName));
}
if (string.IsNullOrEmpty(appVersion))
{
throw new ArgumentNullException(nameof(appVersion));
}
if (string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
}
var activityDate = DateTime.UtcNow;
2018-09-12 10:26:21 -07:00
var session = GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
2015-03-21 09:10:02 -07:00
var lastActivityDate = session.LastActivityDate;
session.LastActivityDate = activityDate;
2015-03-21 09:10:02 -07:00
if (user != null)
{
2015-03-21 09:10:02 -07:00
var userLastActivityDate = user.LastActivityDate ?? DateTime.MinValue;
user.LastActivityDate = activityDate;
if ((activityDate - userLastActivityDate).TotalSeconds > 60)
2015-03-21 09:10:02 -07:00
{
try
{
_userManager.UpdateUser(user);
2015-03-21 09:10:02 -07:00
}
catch (Exception ex)
{
_logger.LogError("Error updating user", ex);
2015-03-21 09:10:02 -07:00
}
}
}
2015-03-21 09:10:02 -07:00
if ((activityDate - lastActivityDate).TotalSeconds > 10)
{
SessionActivity?.Invoke(this, new SessionEventArgs
2015-03-21 09:10:02 -07:00
{
SessionInfo = session
});
2015-03-21 09:10:02 -07:00
}
return session;
}
2018-09-12 10:26:21 -07:00
public void CloseIfNeeded(SessionInfo session)
2014-03-09 19:33:32 -07:00
{
2018-09-12 10:26:21 -07:00
if (!session.SessionControllers.Any(i => i.IsSessionActive))
2014-03-09 19:33:32 -07:00
{
2018-09-12 10:26:21 -07:00
var key = GetSessionKey(session.Client, session.DeviceId);
2014-03-09 19:33:32 -07:00
_activeConnections.TryRemove(key, out var removed);
2014-03-09 19:33:32 -07:00
2018-09-12 10:26:21 -07:00
OnSessionEnded(session);
2014-03-09 19:33:32 -07:00
}
2018-09-12 10:26:21 -07:00
}
public void ReportSessionEnded(string sessionId)
{
CheckDisposed();
var session = GetSession(sessionId, false);
if (session != null)
2014-03-09 19:33:32 -07:00
{
2018-09-12 10:26:21 -07:00
var key = GetSessionKey(session.Client, session.DeviceId);
_activeConnections.TryRemove(key, out var removed);
2018-09-12 10:26:21 -07:00
OnSessionEnded(session);
2014-03-09 19:33:32 -07:00
}
}
2018-09-12 10:26:21 -07:00
private Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId)
2015-03-29 09:45:16 -07:00
{
2016-09-18 13:38:38 -07:00
return _mediaSourceManager.GetMediaSource(item, mediaSourceId, liveStreamId, false, CancellationToken.None);
2015-03-29 09:45:16 -07:00
}
/// <summary>
/// Updates the now playing item id.
/// </summary>
2017-04-17 12:01:16 -07:00
private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bool updateLastCheckInTime)
{
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(info.MediaSourceId))
{
2018-09-12 10:26:21 -07:00
info.MediaSourceId = info.ItemId.ToString("N");
}
2014-04-15 19:17:48 -07:00
2018-09-12 10:26:21 -07:00
if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
{
2015-03-29 09:45:16 -07:00
var current = session.NowPlayingItem;
2015-01-16 21:29:53 -07:00
2018-09-12 10:26:21 -07:00
if (current == null || !info.ItemId.Equals(current.Id))
2015-01-16 21:29:53 -07:00
{
2015-03-29 09:45:16 -07:00
var runtimeTicks = libraryItem.RunTimeTicks;
2015-03-16 21:08:09 -07:00
2015-04-02 09:24:59 -07:00
MediaSourceInfo mediaSource = null;
var hasMediaSources = libraryItem as IHasMediaSources;
if (hasMediaSources != null)
2015-03-29 09:45:16 -07:00
{
2018-09-12 10:26:21 -07:00
mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
2015-04-02 09:24:59 -07:00
if (mediaSource != null)
{
runtimeTicks = mediaSource.RunTimeTicks;
}
2015-03-29 09:45:16 -07:00
}
2014-05-10 10:28:03 -07:00
2017-06-09 12:26:54 -07:00
info.Item = GetItemInfo(libraryItem, mediaSource);
2015-03-29 09:45:16 -07:00
info.Item.RunTimeTicks = runtimeTicks;
2014-05-10 10:28:03 -07:00
}
else
{
info.Item = current;
}
}
2014-04-15 19:17:48 -07:00
session.NowPlayingItem = info.Item;
session.LastActivityDate = DateTime.UtcNow;
2017-04-17 12:01:16 -07:00
if (updateLastCheckInTime)
{
session.LastPlaybackCheckIn = DateTime.UtcNow;
}
2014-04-15 19:17:48 -07:00
2014-04-22 10:25:54 -07:00
session.PlayState.IsPaused = info.IsPaused;
session.PlayState.PositionTicks = info.PositionTicks;
session.PlayState.MediaSourceId = info.MediaSourceId;
2014-04-15 19:17:48 -07:00
session.PlayState.CanSeek = info.CanSeek;
session.PlayState.IsMuted = info.IsMuted;
session.PlayState.VolumeLevel = info.VolumeLevel;
session.PlayState.AudioStreamIndex = info.AudioStreamIndex;
session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex;
2014-04-17 22:03:01 -07:00
session.PlayState.PlayMethod = info.PlayMethod;
2015-07-30 07:34:46 -07:00
session.PlayState.RepeatMode = info.RepeatMode;
2018-09-12 10:26:21 -07:00
session.PlaylistItemId = info.PlaylistItemId;
var nowPlayingQueue = info.NowPlayingQueue;
if (nowPlayingQueue != null)
{
session.NowPlayingQueue = nowPlayingQueue;
}
}
/// <summary>
/// Removes the now playing item id.
/// </summary>
/// <param name="session">The session.</param>
2019-01-13 13:37:13 -07:00
/// <exception cref="ArgumentNullException">item</exception>
2014-04-15 19:17:48 -07:00
private void RemoveNowPlayingItem(SessionInfo session)
{
2014-04-15 19:17:48 -07:00
session.NowPlayingItem = null;
session.PlayState = new PlayerStateInfo();
if (!string.IsNullOrEmpty(session.DeviceId))
{
ClearTranscodingInfo(session.DeviceId);
}
}
private static string GetSessionKey(string appName, string deviceId)
2014-03-09 19:33:32 -07:00
{
2015-03-14 18:42:09 -07:00
return appName + deviceId;
2014-03-09 19:33:32 -07:00
}
/// <summary>
/// Gets the connection.
/// </summary>
2015-03-14 18:42:09 -07:00
/// <param name="appName">Type of the client.</param>
/// <param name="appVersion">The app version.</param>
/// <param name="deviceId">The device id.</param>
/// <param name="deviceName">Name of the device.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
2015-03-09 12:40:03 -07:00
/// <param name="user">The user.</param>
/// <returns>SessionInfo.</returns>
2018-09-12 10:26:21 -07:00
private SessionInfo GetSessionInfo(string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
if (string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
}
2015-03-14 18:42:09 -07:00
var key = GetSessionKey(appName, deviceId);
2018-09-12 10:26:21 -07:00
CheckDisposed();
2014-03-09 19:33:32 -07:00
2019-01-13 13:37:13 -07:00
var sessionInfo = _activeConnections.GetOrAdd(key, k =>
{
2018-09-12 10:26:21 -07:00
return CreateSession(k, appName, appVersion, deviceId, deviceName, remoteEndPoint, user);
});
2014-08-10 15:13:17 -07:00
2018-09-12 10:26:21 -07:00
sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
sessionInfo.UserName = user == null ? null : user.Name;
sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
sessionInfo.RemoteEndPoint = remoteEndPoint;
sessionInfo.Client = appName;
2014-04-06 10:53:23 -07:00
2018-09-12 10:26:21 -07:00
if (!sessionInfo.HasCustomDeviceName || string.IsNullOrEmpty(sessionInfo.DeviceName))
{
sessionInfo.DeviceName = deviceName;
}
2014-10-11 13:38:13 -07:00
2018-09-12 10:26:21 -07:00
sessionInfo.ApplicationVersion = appVersion;
2014-03-09 19:33:32 -07:00
2018-09-12 10:26:21 -07:00
if (user == null)
{
sessionInfo.AdditionalUsers = new SessionUserInfo[] { };
}
2014-10-13 13:14:53 -07:00
2018-09-12 10:26:21 -07:00
return sessionInfo;
}
2015-03-29 09:45:16 -07:00
2018-09-12 10:26:21 -07:00
private SessionInfo CreateSession(string key, string appName, string appVersion, string deviceId, string deviceName, string remoteEndPoint, User user)
{
var sessionInfo = new SessionInfo(this, _logger)
{
Client = appName,
DeviceId = deviceId,
ApplicationVersion = appVersion,
Id = key.GetMD5().ToString("N"),
ServerId = _appHost.SystemId
};
2014-10-13 13:14:53 -07:00
2018-09-12 10:26:21 -07:00
var username = user == null ? null : user.Name;
2014-03-09 19:33:32 -07:00
2018-09-12 10:26:21 -07:00
sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
sessionInfo.UserName = username;
sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
sessionInfo.RemoteEndPoint = remoteEndPoint;
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(deviceName))
{
deviceName = "Network Device";
}
2014-03-09 19:33:32 -07:00
2018-09-12 10:26:21 -07:00
var deviceOptions = _deviceManager.GetDeviceOptions(deviceId);
if (string.IsNullOrEmpty(deviceOptions.CustomName))
{
sessionInfo.DeviceName = deviceName;
2014-03-09 19:33:32 -07:00
}
2018-09-12 10:26:21 -07:00
else
{
2018-09-12 10:26:21 -07:00
sessionInfo.DeviceName = deviceOptions.CustomName;
sessionInfo.HasCustomDeviceName = true;
}
2018-09-12 10:26:21 -07:00
OnSessionStarted(sessionInfo);
return sessionInfo;
}
private List<User> GetUsers(SessionInfo session)
{
var users = new List<User>();
2018-09-12 10:26:21 -07:00
if (!session.UserId.Equals(Guid.Empty))
{
2018-09-12 10:26:21 -07:00
var user = _userManager.GetUserById(session.UserId);
if (user == null)
{
throw new InvalidOperationException("User not found");
}
users.Add(user);
2018-09-12 10:26:21 -07:00
users.AddRange(session.AdditionalUsers
2014-09-14 08:10:51 -07:00
.Select(i => _userManager.GetUserById(i.UserId))
2018-09-12 10:26:21 -07:00
.Where(i => i != null));
}
return users;
}
2019-02-05 01:49:46 -07:00
private Timer _idleTimer;
2014-10-22 21:26:01 -07:00
private void StartIdleCheckTimer()
{
if (_idleTimer == null)
{
2019-02-05 01:49:46 -07:00
_idleTimer = new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
2014-10-22 21:26:01 -07:00
}
}
private void StopIdleCheckTimer()
{
if (_idleTimer != null)
{
_idleTimer.Dispose();
_idleTimer = null;
}
}
private async void CheckForIdlePlayback(object state)
{
var playingSessions = Sessions.Where(i => i.NowPlayingItem != null)
.ToList();
if (playingSessions.Count > 0)
{
var idle = playingSessions
.Where(i => (DateTime.UtcNow - i.LastPlaybackCheckIn).TotalMinutes > 5)
.ToList();
foreach (var session in idle)
{
_logger.LogDebug("Session {0} has gone idle while playing", session.Id);
2014-10-22 21:26:01 -07:00
try
{
await OnPlaybackStopped(new PlaybackStopInfo
{
Item = session.NowPlayingItem,
2018-09-12 10:26:21 -07:00
ItemId = session.NowPlayingItem == null ? Guid.Empty : session.NowPlayingItem.Id,
2014-10-22 21:26:01 -07:00
SessionId = session.Id,
2016-03-27 14:11:27 -07:00
MediaSourceId = session.PlayState == null ? null : session.PlayState.MediaSourceId,
2015-02-01 12:01:21 -07:00
PositionTicks = session.PlayState == null ? null : session.PlayState.PositionTicks
2014-10-22 21:26:01 -07:00
});
}
catch (Exception ex)
{
_logger.LogDebug("Error calling OnPlaybackStopped", ex);
2014-10-22 21:26:01 -07:00
}
}
playingSessions = Sessions.Where(i => i.NowPlayingItem != null)
.ToList();
}
if (playingSessions.Count == 0)
{
StopIdleCheckTimer();
}
}
2018-09-12 10:26:21 -07:00
private BaseItem GetNowPlayingItem(SessionInfo session, Guid itemId)
2016-11-11 21:02:22 -07:00
{
var item = session.FullNowPlayingItem;
2018-09-12 10:26:21 -07:00
if (item != null && item.Id.Equals(itemId))
2016-11-11 21:02:22 -07:00
{
return item;
}
item = _libraryManager.GetItemById(itemId);
session.FullNowPlayingItem = item;
return item;
}
/// <summary>
/// Used to report that playback has started for an item
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
2019-01-13 13:37:13 -07:00
/// <exception cref="ArgumentNullException">info</exception>
2014-04-15 19:17:48 -07:00
public async Task OnPlaybackStart(PlaybackStartInfo info)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
2014-04-15 19:17:48 -07:00
var session = GetSession(info.SessionId);
2018-09-12 10:26:21 -07:00
var libraryItem = info.ItemId.Equals(Guid.Empty)
2014-04-15 19:17:48 -07:00
? null
2016-11-11 21:02:22 -07:00
: GetNowPlayingItem(session, info.ItemId);
2017-04-17 12:01:16 -07:00
await UpdateNowPlayingItem(session, info, libraryItem, true).ConfigureAwait(false);
2014-06-05 21:56:47 -07:00
if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode)
{
ClearTranscodingInfo(session.DeviceId);
}
2019-02-05 01:49:46 -07:00
session.StartAutomaticProgress(info);
var users = GetUsers(session);
2013-05-17 11:05:49 -07:00
2014-04-15 19:17:48 -07:00
if (libraryItem != null)
2013-05-22 10:58:49 -07:00
{
2014-04-15 19:17:48 -07:00
foreach (var user in users)
{
2018-09-12 10:26:21 -07:00
OnPlaybackStart(user, libraryItem);
2014-04-15 19:17:48 -07:00
}
2013-05-22 10:58:49 -07:00
}
// Nothing to save here
// Fire events to inform plugins
EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
{
2014-04-15 19:17:48 -07:00
Item = libraryItem,
Users = users,
2014-04-25 19:55:07 -07:00
MediaSourceId = info.MediaSourceId,
2014-04-26 20:42:05 -07:00
MediaInfo = info.Item,
DeviceName = session.DeviceName,
2014-05-31 07:30:59 -07:00
ClientName = session.Client,
2018-09-12 10:26:21 -07:00
DeviceId = session.DeviceId,
Session = session
2013-12-30 10:18:18 -07:00
}, _logger);
2014-10-22 21:26:01 -07:00
StartIdleCheckTimer();
}
/// <summary>
/// Called when [playback start].
/// </summary>
/// <param name="user">The user object.</param>
/// <param name="item">The item.</param>
2018-09-12 10:26:21 -07:00
private void OnPlaybackStart(User user, BaseItem item)
{
2018-09-12 10:26:21 -07:00
var data = _userDataManager.GetUserData(user, item);
data.PlayCount++;
data.LastPlayedDate = DateTime.UtcNow;
if (item.SupportsPlayedStatus)
{
if (!(item is Video))
{
data.Played = true;
}
}
2016-10-10 23:46:59 -07:00
else
{
data.Played = false;
}
2018-09-12 10:26:21 -07:00
_userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None);
}
2017-04-17 12:01:16 -07:00
public Task OnPlaybackProgress(PlaybackProgressInfo info)
{
return OnPlaybackProgress(info, false);
}
/// <summary>
/// Used to report playback progress for an item
/// </summary>
2017-04-17 12:01:16 -07:00
public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
2014-04-15 19:17:48 -07:00
var session = GetSession(info.SessionId);
2018-09-12 10:26:21 -07:00
var libraryItem = info.ItemId.Equals(Guid.Empty)
2014-04-15 19:17:48 -07:00
? null
2016-11-11 21:02:22 -07:00
: GetNowPlayingItem(session, info.ItemId);
2014-04-06 10:53:23 -07:00
2017-04-17 12:01:16 -07:00
await UpdateNowPlayingItem(session, info, libraryItem, !isAutomated).ConfigureAwait(false);
var users = GetUsers(session);
2018-09-12 10:26:21 -07:00
// only update saved user data on actual check-ins, not automated ones
if (libraryItem != null && !isAutomated)
{
2014-04-15 19:17:48 -07:00
foreach (var user in users)
{
OnPlaybackProgress(user, libraryItem, info);
2014-04-15 19:17:48 -07:00
}
}
PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
{
2014-04-15 19:17:48 -07:00
Item = libraryItem,
Users = users,
2014-04-15 19:17:48 -07:00
PlaybackPositionTicks = session.PlayState.PositionTicks,
2014-04-25 19:55:07 -07:00
MediaSourceId = session.PlayState.MediaSourceId,
2014-04-26 20:42:05 -07:00
MediaInfo = info.Item,
DeviceName = session.DeviceName,
2014-05-31 07:30:59 -07:00
ClientName = session.Client,
2016-03-21 20:31:35 -07:00
DeviceId = session.DeviceId,
IsPaused = info.IsPaused,
2017-04-25 11:23:20 -07:00
PlaySessionId = info.PlaySessionId,
2018-09-12 10:26:21 -07:00
IsAutomated = isAutomated,
Session = session
});
2014-10-22 21:26:01 -07:00
2017-04-17 13:33:07 -07:00
if (!isAutomated)
{
2019-02-05 01:49:46 -07:00
session.StartAutomaticProgress(info);
2017-04-17 13:33:07 -07:00
}
2014-10-22 21:26:01 -07:00
StartIdleCheckTimer();
}
private void OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info)
{
2018-09-12 10:26:21 -07:00
var data = _userDataManager.GetUserData(user, item);
var positionTicks = info.PositionTicks;
2018-09-12 10:26:21 -07:00
var changed = false;
if (positionTicks.HasValue)
{
_userDataManager.UpdatePlayState(item, data, positionTicks.Value);
2018-09-12 10:26:21 -07:00
changed = true;
}
2018-09-12 10:26:21 -07:00
var tracksChanged = UpdatePlaybackSettings(user, info, data);
if (!tracksChanged)
{
changed = true;
}
2018-09-12 10:26:21 -07:00
if (changed)
{
_userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.None);
}
2018-09-12 10:26:21 -07:00
}
private static bool UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data)
{
2018-09-12 10:26:21 -07:00
var changed = false;
if (user.Configuration.RememberAudioSelections)
{
2018-09-12 10:26:21 -07:00
if (data.AudioStreamIndex != info.AudioStreamIndex)
{
data.AudioStreamIndex = info.AudioStreamIndex;
changed = true;
}
}
else
{
2018-09-12 10:26:21 -07:00
if (data.AudioStreamIndex.HasValue)
{
data.AudioStreamIndex = null;
changed = true;
}
}
if (user.Configuration.RememberSubtitleSelections)
{
2018-09-12 10:26:21 -07:00
if (data.SubtitleStreamIndex != info.SubtitleStreamIndex)
{
data.SubtitleStreamIndex = info.SubtitleStreamIndex;
changed = true;
}
}
else
{
2018-09-12 10:26:21 -07:00
if (data.SubtitleStreamIndex.HasValue)
{
data.SubtitleStreamIndex = null;
changed = true;
}
}
2018-09-12 10:26:21 -07:00
return changed;
}
/// <summary>
/// Used to report that playback has ended for an item
/// </summary>
/// <param name="info">The info.</param>
/// <returns>Task.</returns>
2019-01-13 13:37:13 -07:00
/// <exception cref="ArgumentNullException">info</exception>
/// <exception cref="ArgumentOutOfRangeException">positionTicks</exception>
2014-04-15 19:17:48 -07:00
public async Task OnPlaybackStopped(PlaybackStopInfo info)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0)
{
throw new ArgumentOutOfRangeException(nameof(info), "The PlaybackStopInfo's PositionTicks was negative.");
}
2014-04-15 19:17:48 -07:00
var session = GetSession(info.SessionId);
2017-04-17 11:40:42 -07:00
session.StopAutomaticProgress();
2018-09-12 10:26:21 -07:00
var libraryItem = info.ItemId.Equals(Guid.Empty)
2014-04-15 19:17:48 -07:00
? null
2016-11-11 21:02:22 -07:00
: GetNowPlayingItem(session, info.ItemId);
2014-04-15 19:17:48 -07:00
// Normalize
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(info.MediaSourceId))
2014-04-15 19:17:48 -07:00
{
2018-09-12 10:26:21 -07:00
info.MediaSourceId = info.ItemId.ToString("N");
2014-04-15 19:17:48 -07:00
}
2018-09-12 10:26:21 -07:00
if (!info.ItemId.Equals(Guid.Empty) && info.Item == null && libraryItem != null)
{
var current = session.NowPlayingItem;
2018-09-12 10:26:21 -07:00
if (current == null || !info.ItemId.Equals(current.Id))
{
2015-04-02 09:24:59 -07:00
MediaSourceInfo mediaSource = null;
var hasMediaSources = libraryItem as IHasMediaSources;
if (hasMediaSources != null)
{
2018-09-12 10:26:21 -07:00
mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
2015-04-02 09:24:59 -07:00
}
2015-03-29 09:45:16 -07:00
2017-06-09 12:26:54 -07:00
info.Item = GetItemInfo(libraryItem, mediaSource);
}
else
{
info.Item = current;
}
}
2016-11-30 22:46:32 -07:00
if (info.Item != null)
{
var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
_logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
2016-11-30 22:46:32 -07:00
session.Client,
session.ApplicationVersion,
info.Item.Name,
msString);
}
2018-09-12 10:26:21 -07:00
if (info.NowPlayingQueue != null)
{
session.NowPlayingQueue = info.NowPlayingQueue;
}
session.PlaylistItemId = info.PlaylistItemId;
2014-04-15 19:17:48 -07:00
RemoveNowPlayingItem(session);
var users = GetUsers(session);
var playedToCompletion = false;
2014-04-15 19:17:48 -07:00
if (libraryItem != null)
{
2014-04-15 19:17:48 -07:00
foreach (var user in users)
{
2018-09-12 10:26:21 -07:00
playedToCompletion = OnPlaybackStopped(user, libraryItem, info.PositionTicks, info.Failed);
2014-04-15 19:17:48 -07:00
}
}
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrEmpty(info.LiveStreamId))
2015-03-29 11:16:40 -07:00
{
try
{
2016-09-29 05:55:49 -07:00
await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false);
2015-03-29 11:16:40 -07:00
}
catch (Exception ex)
{
_logger.LogError("Error closing live stream", ex);
2015-03-29 11:16:40 -07:00
}
}
EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
{
2014-04-15 19:17:48 -07:00
Item = libraryItem,
Users = users,
PlaybackPositionTicks = info.PositionTicks,
PlayedToCompletion = playedToCompletion,
2014-04-25 19:55:07 -07:00
MediaSourceId = info.MediaSourceId,
2014-04-26 20:42:05 -07:00
MediaInfo = info.Item,
DeviceName = session.DeviceName,
2014-05-31 07:30:59 -07:00
ClientName = session.Client,
2018-09-12 10:26:21 -07:00
DeviceId = session.DeviceId,
Session = session
}, _logger);
}
2018-09-12 10:26:21 -07:00
private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed)
{
2016-03-06 21:56:45 -07:00
bool playedToCompletion = false;
2016-03-06 21:56:45 -07:00
if (!playbackFailed)
{
2018-09-12 10:26:21 -07:00
var data = _userDataManager.GetUserData(user, item);
2016-05-07 10:47:41 -07:00
2016-03-06 21:56:45 -07:00
if (positionTicks.HasValue)
{
playedToCompletion = _userDataManager.UpdatePlayState(item, data, positionTicks.Value);
2016-03-06 21:56:45 -07:00
}
2016-11-30 22:46:32 -07:00
else
2016-03-06 21:56:45 -07:00
{
// If the client isn't able to report this, then we'll just have to make an assumption
data.PlayCount++;
2016-10-10 23:46:59 -07:00
data.Played = item.SupportsPlayedStatus;
2016-03-06 21:56:45 -07:00
data.PlaybackPositionTicks = 0;
playedToCompletion = true;
}
2018-09-12 10:26:21 -07:00
_userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None);
2016-03-06 21:56:45 -07:00
}
2013-12-30 10:18:18 -07:00
return playedToCompletion;
}
2014-03-29 11:20:42 -07:00
/// <summary>
/// Gets the session.
/// </summary>
/// <param name="sessionId">The session identifier.</param>
/// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
/// <returns>SessionInfo.</returns>
/// <exception cref="ResourceNotFoundException"></exception>
private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
{
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
if (session == null && throwOnMissing)
{
throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
}
return session;
}
2015-03-01 22:16:29 -07:00
private SessionInfo GetSessionToRemoteControl(string sessionId)
{
// Accept either device id or session id
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
if (session == null)
{
throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
}
return session;
}
2014-04-15 19:17:48 -07:00
public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2014-05-08 13:09:53 -07:00
var generalCommand = new GeneralCommand
{
Name = GeneralCommandType.DisplayMessage.ToString()
};
2014-05-08 13:09:53 -07:00
generalCommand.Arguments["Header"] = command.Header;
generalCommand.Arguments["Text"] = command.Text;
2014-03-29 11:20:42 -07:00
2014-05-08 13:09:53 -07:00
if (command.TimeoutMs.HasValue)
{
generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
}
return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
}
2014-04-15 19:17:48 -07:00
public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2015-03-01 22:16:29 -07:00
var session = GetSessionToRemoteControl(sessionId);
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrEmpty(controllingSessionId))
2017-02-20 00:04:03 -07:00
{
var controllingSession = GetSession(controllingSessionId);
AssertCanControl(session, controllingSession);
}
2014-03-29 11:20:42 -07:00
2018-09-12 10:26:21 -07:00
return SendMessageToSession(session, "GeneralCommand", command, cancellationToken);
}
private static async Task SendMessageToSession<T>(SessionInfo session, string name, T data, CancellationToken cancellationToken)
2018-09-12 10:26:21 -07:00
{
var controllers = session.SessionControllers.ToArray();
var messageId = Guid.NewGuid().ToString("N");
foreach (var controller in controllers)
{
await controller.SendMessage(name, messageId, data, controllers, cancellationToken).ConfigureAwait(false);
}
}
2016-06-18 23:18:29 -07:00
public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2015-03-01 22:16:29 -07:00
var session = GetSessionToRemoteControl(sessionId);
2018-09-12 10:26:21 -07:00
var user = !session.UserId.Equals(Guid.Empty) ? _userManager.GetUserById(session.UserId) : null;
2014-03-29 11:20:42 -07:00
List<BaseItem> items;
if (command.PlayCommand == PlayCommand.PlayInstantMix)
{
items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user))
.ToList();
command.PlayCommand = PlayCommand.PlayNow;
}
else
{
2016-06-18 23:18:29 -07:00
var list = new List<BaseItem>();
foreach (var itemId in command.ItemIds)
{
2017-05-25 23:48:54 -07:00
var subItems = TranslateItemForPlayback(itemId, user);
2016-06-18 23:18:29 -07:00
list.AddRange(subItems);
}
2016-11-30 22:46:32 -07:00
2017-11-09 13:58:09 -07:00
items = list;
}
2014-02-20 22:35:56 -07:00
2014-03-29 11:20:42 -07:00
if (command.PlayCommand == PlayCommand.PlayShuffle)
{
2014-03-29 11:20:42 -07:00
items = items.OrderBy(i => Guid.NewGuid()).ToList();
command.PlayCommand = PlayCommand.PlayNow;
}
2018-12-28 08:48:26 -07:00
command.ItemIds = items.Select(i => i.Id).ToArray();
2014-03-29 11:20:42 -07:00
if (user != null)
{
2014-02-20 22:35:56 -07:00
if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full))
{
throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name));
}
}
2016-02-26 07:50:58 -07:00
if (user != null && command.ItemIds.Length == 1 && user.Configuration.EnableNextEpisodeAutoPlay)
{
var episode = _libraryManager.GetItemById(command.ItemIds[0]) as Episode;
if (episode != null)
{
var series = episode.Series;
if (series != null)
{
2017-05-21 00:25:49 -07:00
var episodes = series.GetEpisodes(user, new DtoOptions(false)
{
EnableImages = false
})
2016-08-17 22:56:10 -07:00
.Where(i => !i.IsVirtualItem)
2016-02-26 07:50:58 -07:00
.SkipWhile(i => i.Id != episode.Id)
.ToList();
if (episodes.Count > 0)
{
2018-12-28 08:48:26 -07:00
command.ItemIds = episodes.Select(i => i.Id).ToArray();
2016-02-26 07:50:58 -07:00
}
}
}
}
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrEmpty(controllingSessionId))
{
2017-02-20 00:04:03 -07:00
var controllingSession = GetSession(controllingSessionId);
AssertCanControl(session, controllingSession);
2018-09-12 10:26:21 -07:00
if (!controllingSession.UserId.Equals(Guid.Empty))
2017-02-20 00:04:03 -07:00
{
2018-09-12 10:26:21 -07:00
command.ControllingUserId = controllingSession.UserId;
2017-02-20 00:04:03 -07:00
}
}
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, "Play", command, cancellationToken).ConfigureAwait(false);
}
2018-09-12 10:26:21 -07:00
private IList<BaseItem> TranslateItemForPlayback(Guid id, User user)
2014-03-29 11:20:42 -07:00
{
2015-07-05 11:34:52 -07:00
var item = _libraryManager.GetItemById(id);
if (item == null)
{
_logger.LogError("A non-existant item Id {0} was passed into TranslateItemForPlayback", id);
2015-07-05 11:34:52 -07:00
return new List<BaseItem>();
}
2014-03-29 11:20:42 -07:00
var byName = item as IItemByName;
if (byName != null)
{
2018-09-12 10:26:21 -07:00
return byName.GetTaggedItems(new InternalItemsQuery(user)
2016-05-07 10:47:41 -07:00
{
IsFolder = false,
2017-05-21 00:25:49 -07:00
Recursive = true,
DtoOptions = new DtoOptions(false)
{
2017-05-24 12:12:55 -07:00
EnableImages = false,
2017-08-19 12:43:35 -07:00
Fields = new ItemFields[]
2017-05-24 12:12:55 -07:00
{
ItemFields.SortName
}
2017-11-09 13:58:09 -07:00
},
2018-09-12 10:26:21 -07:00
IsVirtualItem = false,
OrderBy = new ValueTuple<string, SortOrder>[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) }
2016-05-07 10:47:41 -07:00
});
}
2015-03-09 12:40:03 -07:00
2014-03-29 11:20:42 -07:00
if (item.IsFolder)
{
var folder = (Folder)item;
2018-09-12 10:26:21 -07:00
return folder.GetItemList(new InternalItemsQuery(user)
2016-05-07 10:47:41 -07:00
{
Recursive = true,
2017-05-21 00:25:49 -07:00
IsFolder = false,
DtoOptions = new DtoOptions(false)
{
2017-05-24 12:12:55 -07:00
EnableImages = false,
2017-08-19 12:43:35 -07:00
Fields = new ItemFields[]
2017-05-24 12:12:55 -07:00
{
ItemFields.SortName
}
2017-11-09 13:58:09 -07:00
},
2018-09-12 10:26:21 -07:00
IsVirtualItem = false,
OrderBy = new ValueTuple<string, SortOrder>[] { new ValueTuple<string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) }
2016-05-07 10:47:41 -07:00
2017-05-25 23:48:54 -07:00
});
2014-03-29 11:20:42 -07:00
}
2016-06-18 23:18:29 -07:00
return new List<BaseItem> { item };
2014-03-29 11:20:42 -07:00
}
2018-09-12 10:26:21 -07:00
private IEnumerable<BaseItem> TranslateItemForInstantMix(Guid id, User user)
{
var item = _libraryManager.GetItemById(id);
2015-07-05 11:34:52 -07:00
if (item == null)
{
_logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
2015-07-05 11:34:52 -07:00
return new List<BaseItem>();
}
2017-05-21 00:25:49 -07:00
return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false });
}
2014-04-15 19:17:48 -07:00
public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, CancellationToken cancellationToken)
{
2014-04-13 10:27:13 -07:00
var generalCommand = new GeneralCommand
{
Name = GeneralCommandType.DisplayContent.ToString()
};
2014-04-13 10:27:13 -07:00
generalCommand.Arguments["ItemId"] = command.ItemId;
generalCommand.Arguments["ItemName"] = command.ItemName;
generalCommand.Arguments["ItemType"] = command.ItemType;
2014-03-29 11:20:42 -07:00
2014-04-13 10:27:13 -07:00
return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
}
2014-04-15 19:17:48 -07:00
public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2015-03-01 22:16:29 -07:00
var session = GetSessionToRemoteControl(sessionId);
2018-09-12 10:26:21 -07:00
if (!string.IsNullOrEmpty(controllingSessionId))
{
2017-02-20 00:04:03 -07:00
var controllingSession = GetSession(controllingSessionId);
AssertCanControl(session, controllingSession);
2018-09-12 10:26:21 -07:00
if (!controllingSession.UserId.Equals(Guid.Empty))
2017-02-20 00:04:03 -07:00
{
2018-09-12 10:26:21 -07:00
command.ControllingUserId = controllingSession.UserId.ToString("N");
2017-02-20 00:04:03 -07:00
}
}
2018-09-12 10:26:21 -07:00
return SendMessageToSession(session, "Playstate", command, cancellationToken);
2013-10-02 18:22:50 -07:00
}
2014-03-16 09:15:10 -07:00
private void AssertCanControl(SessionInfo session, SessionInfo controllingSession)
{
if (session == null)
{
throw new ArgumentNullException(nameof(session));
2014-03-16 09:15:10 -07:00
}
if (controllingSession == null)
{
throw new ArgumentNullException(nameof(controllingSession));
2014-03-16 09:15:10 -07:00
}
}
/// <summary>
/// Sends the restart required message.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2016-06-19 09:53:43 -07:00
public async Task SendRestartRequiredNotification(CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var sessions = Sessions.ToList();
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, "RestartRequired", string.Empty, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Error in SendRestartRequiredNotification.", ex);
}
2018-09-12 10:26:21 -07:00
}, cancellationToken)).ToArray();
2016-06-19 09:53:43 -07:00
await Task.WhenAll(tasks).ConfigureAwait(false);
}
/// <summary>
/// Sends the server shutdown notification.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendServerShutdownNotification(CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var sessions = Sessions.ToList();
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, "ServerShuttingDown", string.Empty, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Error in SendServerShutdownNotification.", ex);
}
2018-09-12 10:26:21 -07:00
}, cancellationToken)).ToArray();
return Task.WhenAll(tasks);
}
/// <summary>
/// Sends the server restart notification.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendServerRestartNotification(CancellationToken cancellationToken)
2013-10-02 18:22:50 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
_logger.LogDebug("Beginning SendServerRestartNotification");
2014-06-04 09:15:44 -07:00
2018-09-12 10:26:21 -07:00
var sessions = Sessions.ToList();
2013-10-02 18:22:50 -07:00
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, "ServerRestarting", string.Empty, cancellationToken).ConfigureAwait(false);
2013-10-02 18:22:50 -07:00
}
catch (Exception ex)
{
_logger.LogError("Error in SendServerRestartNotification.", ex);
2013-10-02 18:22:50 -07:00
}
2018-09-12 10:26:21 -07:00
}, cancellationToken)).ToArray();
return Task.WhenAll(tasks);
}
/// <summary>
/// Adds the additional user.
/// </summary>
/// <param name="sessionId">The session identifier.</param>
/// <param name="userId">The user identifier.</param>
2019-01-13 13:37:13 -07:00
/// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
/// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
2018-09-12 10:26:21 -07:00
public void AddAdditionalUser(string sessionId, Guid userId)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var session = GetSession(sessionId);
2018-09-12 10:26:21 -07:00
if (session.UserId.Equals(userId))
{
throw new ArgumentException("The requested user is already the primary user of the session.");
}
2018-09-12 10:26:21 -07:00
if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId)))
{
var user = _userManager.GetUserById(userId);
2017-08-19 12:43:35 -07:00
var list = session.AdditionalUsers.ToList();
list.Add(new SessionUserInfo
{
2015-05-29 16:51:33 -07:00
UserId = userId,
UserName = user.Name
});
2017-08-19 12:43:35 -07:00
2018-12-28 08:48:26 -07:00
session.AdditionalUsers = list.ToArray();
}
}
/// <summary>
/// Removes the additional user.
/// </summary>
/// <param name="sessionId">The session identifier.</param>
/// <param name="userId">The user identifier.</param>
2019-01-13 13:37:13 -07:00
/// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</exception>
/// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exception>
2018-09-12 10:26:21 -07:00
public void RemoveAdditionalUser(string sessionId, Guid userId)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var session = GetSession(sessionId);
2018-09-12 10:26:21 -07:00
if (session.UserId.Equals(userId))
{
throw new ArgumentException("The requested user is already the primary user of the session.");
}
2018-09-12 10:26:21 -07:00
var user = session.AdditionalUsers.FirstOrDefault(i => i.UserId.Equals(userId));
if (user != null)
{
2017-08-19 12:43:35 -07:00
var list = session.AdditionalUsers.ToList();
list.Remove(user);
2018-12-28 08:48:26 -07:00
session.AdditionalUsers = list.ToArray();
}
}
2014-01-11 16:07:56 -07:00
/// <summary>
/// Authenticates the new session.
/// </summary>
2014-08-10 15:13:17 -07:00
/// <param name="request">The request.</param>
2014-01-11 16:07:56 -07:00
/// <returns>Task{SessionInfo}.</returns>
2016-02-20 23:25:25 -07:00
public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request)
{
return AuthenticateNewSessionInternal(request, true);
}
public Task<AuthenticationResult> CreateNewSession(AuthenticationRequest request)
{
return AuthenticateNewSessionInternal(request, false);
}
private async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enforcePassword)
2014-01-11 16:07:56 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2016-09-14 14:34:19 -07:00
User user = null;
2018-09-12 10:26:21 -07:00
if (!request.UserId.Equals(Guid.Empty))
2016-09-14 14:34:19 -07:00
{
user = _userManager.Users
2018-09-12 10:26:21 -07:00
.FirstOrDefault(i => i.Id == request.UserId);
2016-09-14 14:34:19 -07:00
}
if (user == null)
{
user = _userManager.Users
.FirstOrDefault(i => string.Equals(request.Username, i.Name, StringComparison.OrdinalIgnoreCase));
}
2014-10-15 20:26:39 -07:00
if (user != null)
2014-12-29 13:18:48 -07:00
{
2018-09-12 10:26:21 -07:00
// TODO: Move this to userManager?
if (!string.IsNullOrEmpty(request.DeviceId))
2014-12-29 13:18:48 -07:00
{
2018-09-12 10:26:21 -07:00
if (!_deviceManager.CanAccessDevice(user, request.DeviceId))
{
throw new SecurityException("User is not allowed access from this device.");
}
2014-12-29 13:18:48 -07:00
}
}
2016-02-20 23:25:25 -07:00
if (enforcePassword)
2014-01-11 16:07:56 -07:00
{
2018-09-12 10:26:21 -07:00
var result = await _userManager.AuthenticateUser(request.Username, request.Password, request.PasswordSha1, request.RemoteEndPoint, true).ConfigureAwait(false);
2016-02-20 23:25:25 -07:00
2017-04-06 13:07:25 -07:00
if (result == null)
2016-02-20 23:25:25 -07:00
{
AuthenticationFailed?.Invoke(this, new GenericEventArgs<AuthenticationRequest>(request));
2014-08-10 15:13:17 -07:00
2016-02-20 23:25:25 -07:00
throw new SecurityException("Invalid user or password entered.");
}
2017-04-06 13:07:25 -07:00
user = result;
2014-01-11 16:07:56 -07:00
}
2018-09-12 10:26:21 -07:00
var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName);
2014-07-07 18:41:03 -07:00
2018-09-12 10:26:21 -07:00
var session = LogSessionActivity(request.App,
2014-08-10 15:13:17 -07:00
request.AppVersion,
request.DeviceId,
request.DeviceName,
request.RemoteEndPoint,
2018-09-12 10:26:21 -07:00
user);
2014-10-11 13:38:13 -07:00
2018-09-12 10:26:21 -07:00
var returnResult = new AuthenticationResult
2014-07-02 11:34:08 -07:00
{
2014-08-15 09:35:41 -07:00
User = _userManager.GetUserDto(user, request.RemoteEndPoint),
2018-09-12 10:26:21 -07:00
SessionInfo = session,
2014-07-27 15:01:29 -07:00
AccessToken = token,
2014-09-06 10:46:09 -07:00
ServerId = _appHost.SystemId
2014-07-02 11:34:08 -07:00
};
2016-05-07 10:47:41 -07:00
AuthenticationSucceeded?.Invoke(this, new GenericEventArgs<AuthenticationResult>(returnResult));
2018-09-12 10:26:21 -07:00
return returnResult;
}
2016-05-07 10:47:41 -07:00
2018-09-12 10:26:21 -07:00
private string GetAuthorizationToken(User user, string deviceId, string app, string appVersion, string deviceName)
2014-07-07 18:41:03 -07:00
{
var existing = _authRepo.Get(new AuthenticationInfoQuery
{
DeviceId = deviceId,
2018-09-12 10:26:21 -07:00
UserId = user.Id,
2014-07-07 18:41:03 -07:00
Limit = 1
2018-09-12 10:26:21 -07:00
}).Items.FirstOrDefault();
var allExistingForDevice = _authRepo.Get(new AuthenticationInfoQuery
{
DeviceId = deviceId
}).Items;
foreach (var auth in allExistingForDevice)
{
if (existing == null || !string.Equals(auth.AccessToken, existing.AccessToken, StringComparison.Ordinal))
{
try
{
Logout(auth);
}
catch
{
}
}
}
if (existing != null)
2014-07-07 18:41:03 -07:00
{
_logger.LogInformation("Reissuing access token: " + existing.AccessToken);
2018-09-12 10:26:21 -07:00
return existing.AccessToken;
2014-07-07 18:41:03 -07:00
}
2018-09-12 10:26:21 -07:00
var now = DateTime.UtcNow;
2014-07-07 18:41:03 -07:00
var newToken = new AuthenticationInfo
{
AppName = app,
2015-03-28 11:55:00 -07:00
AppVersion = appVersion,
2018-09-12 10:26:21 -07:00
DateCreated = now,
DateLastActivity = now,
2014-07-07 18:41:03 -07:00
DeviceId = deviceId,
DeviceName = deviceName,
2018-09-12 10:26:21 -07:00
UserId = user.Id,
AccessToken = Guid.NewGuid().ToString("N"),
UserName = user.Name
2014-07-07 18:41:03 -07:00
};
_logger.LogInformation("Creating new access token for user {0}", user.Id);
2018-09-12 10:26:21 -07:00
_authRepo.Create(newToken);
2014-07-07 18:41:03 -07:00
return newToken.AccessToken;
}
public void Logout(string accessToken)
2014-07-07 18:41:03 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
if (string.IsNullOrEmpty(accessToken))
2014-07-07 18:41:03 -07:00
{
throw new ArgumentNullException(nameof(accessToken));
2014-07-07 18:41:03 -07:00
}
var existing = _authRepo.Get(new AuthenticationInfoQuery
{
Limit = 1,
AccessToken = accessToken
}).Items.FirstOrDefault();
if (existing != null)
{
2018-09-12 10:26:21 -07:00
Logout(existing);
}
}
2014-07-07 18:41:03 -07:00
2018-09-12 10:26:21 -07:00
public void Logout(AuthenticationInfo existing)
{
CheckDisposed();
2014-07-07 18:41:03 -07:00
_logger.LogInformation("Logging out access token {0}", existing.AccessToken);
2018-09-12 10:26:21 -07:00
_authRepo.Delete(existing);
2014-07-07 18:41:03 -07:00
2018-09-12 10:26:21 -07:00
var sessions = Sessions
.Where(i => string.Equals(i.DeviceId, existing.DeviceId, StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var session in sessions)
{
try
2014-07-07 18:41:03 -07:00
{
2018-09-12 10:26:21 -07:00
ReportSessionEnded(session.Id);
}
catch (Exception ex)
{
_logger.LogError("Error reporting session ended", ex);
2014-07-07 18:41:03 -07:00
}
}
}
2018-09-12 10:26:21 -07:00
public void RevokeUserTokens(Guid userId, string currentAccessToken)
2014-07-07 18:41:03 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2014-07-07 18:41:03 -07:00
var existing = _authRepo.Get(new AuthenticationInfoQuery
{
UserId = userId
});
foreach (var info in existing.Items)
{
if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase))
{
2018-09-12 10:26:21 -07:00
Logout(info);
}
2014-07-07 18:41:03 -07:00
}
}
2014-07-11 19:31:08 -07:00
public void RevokeToken(string token)
2014-07-11 19:31:08 -07:00
{
Logout(token);
2014-07-11 19:31:08 -07:00
}
2014-07-07 18:41:03 -07:00
2014-03-20 20:31:40 -07:00
/// <summary>
/// Reports the capabilities.
/// </summary>
/// <param name="sessionId">The session identifier.</param>
/// <param name="capabilities">The capabilities.</param>
2014-10-11 13:38:13 -07:00
public void ReportCapabilities(string sessionId, ClientCapabilities capabilities)
2014-03-20 20:31:40 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
2014-03-20 20:31:40 -07:00
var session = GetSession(sessionId);
2014-06-03 20:34:36 -07:00
ReportCapabilities(session, capabilities, true);
}
2017-10-13 12:18:05 -07:00
private void ReportCapabilities(SessionInfo session,
2014-10-11 13:38:13 -07:00
ClientCapabilities capabilities,
2014-06-03 20:34:36 -07:00
bool saveCapabilities)
{
2015-02-19 12:21:03 -07:00
session.Capabilities = capabilities;
2014-05-13 17:46:45 -07:00
2018-09-12 10:26:21 -07:00
if (saveCapabilities)
2014-05-13 17:46:45 -07:00
{
CapabilitiesChanged?.Invoke(this, new SessionEventArgs
2018-09-12 10:26:21 -07:00
{
SessionInfo = session
});
2014-06-03 20:34:36 -07:00
2015-01-25 12:13:04 -07:00
try
{
2017-10-13 12:18:05 -07:00
SaveCapabilities(session.DeviceId, capabilities);
2015-01-25 12:13:04 -07:00
}
catch (Exception ex)
{
_logger.LogError("Error saving device capabilities", ex);
2015-01-25 12:13:04 -07:00
}
2014-06-03 20:34:36 -07:00
}
}
2014-10-11 13:38:13 -07:00
private ClientCapabilities GetSavedCapabilities(string deviceId)
2014-06-03 20:34:36 -07:00
{
2014-10-11 13:38:13 -07:00
return _deviceManager.GetCapabilities(deviceId);
2014-06-03 20:34:36 -07:00
}
2017-10-13 12:18:05 -07:00
private void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
2014-06-03 20:34:36 -07:00
{
2017-10-13 12:18:05 -07:00
_deviceManager.SaveCapabilities(deviceId, capabilities);
2014-03-20 20:31:40 -07:00
}
2014-04-06 10:53:23 -07:00
2017-06-09 12:26:54 -07:00
private DtoOptions _itemInfoDtoOptions;
2014-04-06 10:53:23 -07:00
/// <summary>
/// Converts a BaseItem to a BaseItemInfo
/// </summary>
2017-06-09 12:26:54 -07:00
private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource)
2014-04-06 10:53:23 -07:00
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
2014-04-06 10:53:23 -07:00
}
2017-06-09 12:26:54 -07:00
var dtoOptions = _itemInfoDtoOptions;
2014-04-06 10:53:23 -07:00
2017-06-09 12:26:54 -07:00
if (_itemInfoDtoOptions == null)
2014-04-06 10:53:23 -07:00
{
2017-06-09 12:26:54 -07:00
dtoOptions = new DtoOptions
2014-04-06 10:53:23 -07:00
{
2017-06-09 12:26:54 -07:00
AddProgramRecordingInfo = false
};
2017-08-19 12:43:35 -07:00
var fields = dtoOptions.Fields.ToList();
fields.Remove(ItemFields.BasicSyncInfo);
fields.Remove(ItemFields.CanDelete);
fields.Remove(ItemFields.CanDownload);
fields.Remove(ItemFields.ChildCount);
fields.Remove(ItemFields.CustomRating);
fields.Remove(ItemFields.DateLastMediaAdded);
fields.Remove(ItemFields.DateLastRefreshed);
fields.Remove(ItemFields.DateLastSaved);
fields.Remove(ItemFields.DisplayPreferencesId);
fields.Remove(ItemFields.Etag);
fields.Remove(ItemFields.InheritedParentalRatingValue);
fields.Remove(ItemFields.ItemCounts);
fields.Remove(ItemFields.MediaSourceCount);
fields.Remove(ItemFields.MediaStreams);
fields.Remove(ItemFields.MediaSources);
fields.Remove(ItemFields.People);
fields.Remove(ItemFields.PlayAccess);
fields.Remove(ItemFields.People);
fields.Remove(ItemFields.ProductionLocations);
fields.Remove(ItemFields.RecursiveItemCount);
fields.Remove(ItemFields.RemoteTrailers);
fields.Remove(ItemFields.SeasonUserData);
fields.Remove(ItemFields.Settings);
fields.Remove(ItemFields.SortName);
fields.Remove(ItemFields.Tags);
2018-09-12 10:26:21 -07:00
fields.Remove(ItemFields.ExtraIds);
2017-08-19 12:43:35 -07:00
2018-12-28 08:48:26 -07:00
dtoOptions.Fields = fields.ToArray();
2017-06-09 12:26:54 -07:00
_itemInfoDtoOptions = dtoOptions;
}
var info = _dtoService.GetBaseItemDto(item, dtoOptions);
2014-05-07 22:04:39 -07:00
2015-03-29 09:45:16 -07:00
if (mediaSource != null)
2014-05-07 22:04:39 -07:00
{
2017-08-19 12:43:35 -07:00
info.MediaStreams = mediaSource.MediaStreams.ToArray();
2014-05-07 22:04:39 -07:00
}
2014-04-06 10:53:23 -07:00
return info;
}
2014-05-08 13:09:53 -07:00
private string GetImageCacheTag(BaseItem item, ImageType type)
2014-04-06 10:53:23 -07:00
{
try
{
return _imageProcessor.GetImageCacheTag(item, type);
}
catch (Exception ex)
{
_logger.LogError("Error getting {0} image info", ex, type);
2014-04-06 10:53:23 -07:00
return null;
}
}
2014-04-30 20:24:55 -07:00
public void ReportNowViewingItem(string sessionId, string itemId)
2014-04-15 19:17:48 -07:00
{
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(itemId))
2016-05-30 09:08:46 -07:00
{
throw new ArgumentNullException(nameof(itemId));
2016-05-30 09:08:46 -07:00
}
2016-11-11 21:02:22 -07:00
//var item = _libraryManager.GetItemById(new Guid(itemId));
2014-04-15 19:17:48 -07:00
2016-11-11 21:02:22 -07:00
//var info = GetItemInfo(item, null, null);
2014-04-15 19:17:48 -07:00
2016-11-11 21:02:22 -07:00
//ReportNowViewingItem(sessionId, info);
2014-04-15 19:17:48 -07:00
}
2017-06-09 12:26:54 -07:00
public void ReportNowViewingItem(string sessionId, BaseItemDto item)
2014-04-15 19:17:48 -07:00
{
2016-11-11 21:02:22 -07:00
//var session = GetSession(sessionId);
2014-04-15 19:17:48 -07:00
2016-11-11 21:02:22 -07:00
//session.NowViewingItem = item;
2014-04-15 19:17:48 -07:00
}
public void ReportTranscodingInfo(string deviceId, TranscodingInfo info)
{
var session = Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId));
if (session != null)
{
session.TranscodingInfo = info;
}
}
public void ClearTranscodingInfo(string deviceId)
{
ReportTranscodingInfo(deviceId, null);
}
2014-06-25 08:12:39 -07:00
public SessionInfo GetSession(string deviceId, string client, string version)
{
return Sessions.FirstOrDefault(i => string.Equals(i.DeviceId, deviceId) &&
string.Equals(i.Client, client));
}
2018-09-12 10:26:21 -07:00
public SessionInfo GetSessionByAuthenticationToken(AuthenticationInfo info, string deviceId, string remoteEndpoint, string appVersion)
2015-03-09 12:40:03 -07:00
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
2015-03-09 12:40:03 -07:00
}
2018-09-12 10:26:21 -07:00
var user = info.UserId.Equals(Guid.Empty)
2015-03-09 12:40:03 -07:00
? null
: _userManager.GetUserById(info.UserId);
2018-09-12 10:26:21 -07:00
appVersion = string.IsNullOrEmpty(appVersion)
2015-03-14 18:42:09 -07:00
? info.AppVersion
2015-03-09 12:40:03 -07:00
: appVersion;
2015-03-12 18:55:22 -07:00
var deviceName = info.DeviceName;
2015-03-14 18:42:09 -07:00
var appName = info.AppName;
2015-03-12 18:55:22 -07:00
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(deviceId))
2015-03-12 18:55:22 -07:00
{
deviceId = info.DeviceId;
}
2015-03-28 11:55:00 -07:00
// Prevent argument exception
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(appVersion))
2015-03-28 11:55:00 -07:00
{
appVersion = "1";
}
2015-03-21 09:10:02 -07:00
return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user);
2015-03-09 12:40:03 -07:00
}
2018-09-12 10:26:21 -07:00
public SessionInfo GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpoint)
2015-03-08 12:48:30 -07:00
{
var result = _authRepo.Get(new AuthenticationInfoQuery
{
AccessToken = token
});
2015-03-16 09:47:14 -07:00
var info = result.Items.FirstOrDefault();
2015-03-08 12:48:30 -07:00
2015-03-09 12:40:03 -07:00
if (info == null)
{
2018-09-12 10:26:21 -07:00
return null;
2015-03-09 12:40:03 -07:00
}
2015-03-12 18:55:22 -07:00
return GetSessionByAuthenticationToken(info, deviceId, remoteEndpoint, null);
2015-03-08 12:48:30 -07:00
}
public Task SendMessageToAdminSessions<T>(string name, T data, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var adminUserIds = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToList();
2016-08-20 11:43:13 -07:00
return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken);
}
2018-09-12 10:26:21 -07:00
public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, Func<T> dataFn, CancellationToken cancellationToken)
{
CheckDisposed();
var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
if (sessions.Count == 0)
{
return Task.CompletedTask;
}
var data = dataFn();
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Error sending message", ex);
2018-09-12 10:26:21 -07:00
}
}, cancellationToken)).ToArray();
return Task.WhenAll(tasks);
}
public Task SendMessageToUserSessions<T>(List<Guid> userIds, string name, T data, CancellationToken cancellationToken)
{
CheckDisposed();
var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList();
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Error sending message", ex);
2018-09-12 10:26:21 -07:00
}
}, cancellationToken)).ToArray();
return Task.WhenAll(tasks);
}
public Task SendMessageToUserDeviceSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)).ToList();
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Error sending message", ex);
2015-01-27 21:04:26 -07:00
}
2018-09-12 10:26:21 -07:00
}, cancellationToken)).ToArray();
2015-01-27 21:04:26 -07:00
return Task.WhenAll(tasks);
}
2018-09-12 10:26:21 -07:00
public Task SendMessageToUserDeviceAndAdminSessions<T>(string deviceId, string name, T data, CancellationToken cancellationToken)
2015-01-27 21:04:26 -07:00
{
2018-09-12 10:26:21 -07:00
CheckDisposed();
var sessions = Sessions
.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) || IsAdminSession(i))
.ToList();
2015-01-27 21:04:26 -07:00
var tasks = sessions.Select(session => Task.Run(async () =>
{
try
{
2018-09-12 10:26:21 -07:00
await SendMessageToSession(session, name, data, cancellationToken).ConfigureAwait(false);
2015-01-27 21:04:26 -07:00
}
catch (Exception ex)
{
_logger.LogError("Error sending message", ex);
}
2018-09-12 10:26:21 -07:00
}, cancellationToken)).ToArray();
return Task.WhenAll(tasks);
}
2018-09-12 10:26:21 -07:00
private bool IsAdminSession(SessionInfo s)
{
var user = _userManager.GetUserById(s.UserId);
return user != null && user.Policy.IsAdministrator;
}
}
2018-12-15 08:30:38 -07:00
}