| | 1 | | #nullable disable |
| | 2 | |
|
| | 3 | | #pragma warning disable CS1591 |
| | 4 | |
|
| | 5 | | using System; |
| | 6 | | using System.Collections.Concurrent; |
| | 7 | | using System.Collections.Generic; |
| | 8 | | using System.Globalization; |
| | 9 | | using System.Linq; |
| | 10 | | using System.Threading; |
| | 11 | | using System.Threading.Tasks; |
| | 12 | | using Jellyfin.Data.Entities; |
| | 13 | | using Jellyfin.Data.Entities.Security; |
| | 14 | | using Jellyfin.Data.Enums; |
| | 15 | | using Jellyfin.Data.Events; |
| | 16 | | using Jellyfin.Data.Queries; |
| | 17 | | using Jellyfin.Extensions; |
| | 18 | | using MediaBrowser.Common.Events; |
| | 19 | | using MediaBrowser.Common.Extensions; |
| | 20 | | using MediaBrowser.Controller; |
| | 21 | | using MediaBrowser.Controller.Authentication; |
| | 22 | | using MediaBrowser.Controller.Configuration; |
| | 23 | | using MediaBrowser.Controller.Devices; |
| | 24 | | using MediaBrowser.Controller.Drawing; |
| | 25 | | using MediaBrowser.Controller.Dto; |
| | 26 | | using MediaBrowser.Controller.Entities; |
| | 27 | | using MediaBrowser.Controller.Events; |
| | 28 | | using MediaBrowser.Controller.Events.Authentication; |
| | 29 | | using MediaBrowser.Controller.Events.Session; |
| | 30 | | using MediaBrowser.Controller.Library; |
| | 31 | | using MediaBrowser.Controller.Net; |
| | 32 | | using MediaBrowser.Controller.Session; |
| | 33 | | using MediaBrowser.Model.Dto; |
| | 34 | | using MediaBrowser.Model.Entities; |
| | 35 | | using MediaBrowser.Model.Library; |
| | 36 | | using MediaBrowser.Model.Querying; |
| | 37 | | using MediaBrowser.Model.Session; |
| | 38 | | using MediaBrowser.Model.SyncPlay; |
| | 39 | | using Microsoft.EntityFrameworkCore; |
| | 40 | | using Microsoft.Extensions.Hosting; |
| | 41 | | using Microsoft.Extensions.Logging; |
| | 42 | | using Episode = MediaBrowser.Controller.Entities.TV.Episode; |
| | 43 | |
|
| | 44 | | namespace Emby.Server.Implementations.Session |
| | 45 | | { |
| | 46 | | /// <summary> |
| | 47 | | /// Class SessionManager. |
| | 48 | | /// </summary> |
| | 49 | | public sealed class SessionManager : ISessionManager, IAsyncDisposable |
| | 50 | | { |
| | 51 | | private readonly IUserDataManager _userDataManager; |
| | 52 | | private readonly IServerConfigurationManager _config; |
| | 53 | | private readonly ILogger<SessionManager> _logger; |
| | 54 | | private readonly IEventManager _eventManager; |
| | 55 | | private readonly ILibraryManager _libraryManager; |
| | 56 | | private readonly IUserManager _userManager; |
| | 57 | | private readonly IMusicManager _musicManager; |
| | 58 | | private readonly IDtoService _dtoService; |
| | 59 | | private readonly IImageProcessor _imageProcessor; |
| | 60 | | private readonly IMediaSourceManager _mediaSourceManager; |
| | 61 | | private readonly IServerApplicationHost _appHost; |
| | 62 | | private readonly IDeviceManager _deviceManager; |
| | 63 | | private readonly CancellationTokenRegistration _shutdownCallback; |
| 32 | 64 | | private readonly ConcurrentDictionary<string, SessionInfo> _activeConnections |
| 32 | 65 | | = new(StringComparer.OrdinalIgnoreCase); |
| | 66 | |
|
| | 67 | | private Timer _idleTimer; |
| | 68 | | private Timer _inactiveTimer; |
| | 69 | |
|
| | 70 | | private DtoOptions _itemInfoDtoOptions; |
| | 71 | | private bool _disposed = false; |
| | 72 | |
|
| | 73 | | public SessionManager( |
| | 74 | | ILogger<SessionManager> logger, |
| | 75 | | IEventManager eventManager, |
| | 76 | | IUserDataManager userDataManager, |
| | 77 | | IServerConfigurationManager config, |
| | 78 | | ILibraryManager libraryManager, |
| | 79 | | IUserManager userManager, |
| | 80 | | IMusicManager musicManager, |
| | 81 | | IDtoService dtoService, |
| | 82 | | IImageProcessor imageProcessor, |
| | 83 | | IServerApplicationHost appHost, |
| | 84 | | IDeviceManager deviceManager, |
| | 85 | | IMediaSourceManager mediaSourceManager, |
| | 86 | | IHostApplicationLifetime hostApplicationLifetime) |
| | 87 | | { |
| 32 | 88 | | _logger = logger; |
| 32 | 89 | | _eventManager = eventManager; |
| 32 | 90 | | _userDataManager = userDataManager; |
| 32 | 91 | | _config = config; |
| 32 | 92 | | _libraryManager = libraryManager; |
| 32 | 93 | | _userManager = userManager; |
| 32 | 94 | | _musicManager = musicManager; |
| 32 | 95 | | _dtoService = dtoService; |
| 32 | 96 | | _imageProcessor = imageProcessor; |
| 32 | 97 | | _appHost = appHost; |
| 32 | 98 | | _deviceManager = deviceManager; |
| 32 | 99 | | _mediaSourceManager = mediaSourceManager; |
| 32 | 100 | | _shutdownCallback = hostApplicationLifetime.ApplicationStopping.Register(OnApplicationStopping); |
| | 101 | |
|
| 32 | 102 | | _deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated; |
| 32 | 103 | | } |
| | 104 | |
|
| | 105 | | /// <summary> |
| | 106 | | /// Occurs when playback has started. |
| | 107 | | /// </summary> |
| | 108 | | public event EventHandler<PlaybackProgressEventArgs> PlaybackStart; |
| | 109 | |
|
| | 110 | | /// <summary> |
| | 111 | | /// Occurs when playback has progressed. |
| | 112 | | /// </summary> |
| | 113 | | public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress; |
| | 114 | |
|
| | 115 | | /// <summary> |
| | 116 | | /// Occurs when playback has stopped. |
| | 117 | | /// </summary> |
| | 118 | | public event EventHandler<PlaybackStopEventArgs> PlaybackStopped; |
| | 119 | |
|
| | 120 | | /// <inheritdoc /> |
| | 121 | | public event EventHandler<SessionEventArgs> SessionStarted; |
| | 122 | |
|
| | 123 | | /// <inheritdoc /> |
| | 124 | | public event EventHandler<SessionEventArgs> CapabilitiesChanged; |
| | 125 | |
|
| | 126 | | /// <inheritdoc /> |
| | 127 | | public event EventHandler<SessionEventArgs> SessionEnded; |
| | 128 | |
|
| | 129 | | /// <inheritdoc /> |
| | 130 | | public event EventHandler<SessionEventArgs> SessionActivity; |
| | 131 | |
|
| | 132 | | /// <inheritdoc /> |
| | 133 | | public event EventHandler<SessionEventArgs> SessionControllerConnected; |
| | 134 | |
|
| | 135 | | /// <summary> |
| | 136 | | /// Gets all connections. |
| | 137 | | /// </summary> |
| | 138 | | /// <value>All connections.</value> |
| 39 | 139 | | public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate) |
| | 140 | |
|
| | 141 | | private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e |
| | 142 | | { |
| 0 | 143 | | foreach (var session in Sessions) |
| | 144 | | { |
| 0 | 145 | | if (string.Equals(session.DeviceId, e.Argument.Item1, StringComparison.Ordinal)) |
| | 146 | | { |
| 0 | 147 | | if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName)) |
| | 148 | | { |
| 0 | 149 | | session.HasCustomDeviceName = true; |
| 0 | 150 | | session.DeviceName = e.Argument.Item2.CustomName; |
| | 151 | | } |
| | 152 | | else |
| | 153 | | { |
| 0 | 154 | | session.HasCustomDeviceName = false; |
| | 155 | | } |
| | 156 | | } |
| | 157 | | } |
| 0 | 158 | | } |
| | 159 | |
|
| | 160 | | private void CheckDisposed() |
| | 161 | | { |
| 74 | 162 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| 74 | 163 | | } |
| | 164 | |
|
| | 165 | | private void OnSessionStarted(SessionInfo info) |
| | 166 | | { |
| 16 | 167 | | if (!string.IsNullOrEmpty(info.DeviceId)) |
| | 168 | | { |
| 16 | 169 | | var capabilities = _deviceManager.GetCapabilities(info.DeviceId); |
| | 170 | |
|
| 16 | 171 | | if (capabilities is not null) |
| | 172 | | { |
| 16 | 173 | | ReportCapabilities(info, capabilities, false); |
| | 174 | | } |
| | 175 | | } |
| | 176 | |
|
| 16 | 177 | | _eventManager.Publish(new SessionStartedEventArgs(info)); |
| | 178 | |
|
| 16 | 179 | | EventHelper.QueueEventIfNotNull( |
| 16 | 180 | | SessionStarted, |
| 16 | 181 | | this, |
| 16 | 182 | | new SessionEventArgs |
| 16 | 183 | | { |
| 16 | 184 | | SessionInfo = info |
| 16 | 185 | | }, |
| 16 | 186 | | _logger); |
| 16 | 187 | | } |
| | 188 | |
|
| | 189 | | private async ValueTask OnSessionEnded(SessionInfo info) |
| | 190 | | { |
| | 191 | | EventHelper.QueueEventIfNotNull( |
| | 192 | | SessionEnded, |
| | 193 | | this, |
| | 194 | | new SessionEventArgs |
| | 195 | | { |
| | 196 | | SessionInfo = info |
| | 197 | | }, |
| | 198 | | _logger); |
| | 199 | |
|
| | 200 | | _eventManager.Publish(new SessionEndedEventArgs(info)); |
| | 201 | |
|
| | 202 | | await info.DisposeAsync().ConfigureAwait(false); |
| | 203 | | } |
| | 204 | |
|
| | 205 | | /// <inheritdoc /> |
| | 206 | | public void UpdateDeviceName(string sessionId, string reportedDeviceName) |
| | 207 | | { |
| 0 | 208 | | var session = GetSession(sessionId); |
| 0 | 209 | | if (session is not null) |
| | 210 | | { |
| 0 | 211 | | session.DeviceName = reportedDeviceName; |
| | 212 | | } |
| 0 | 213 | | } |
| | 214 | |
|
| | 215 | | /// <summary> |
| | 216 | | /// Logs the user activity. |
| | 217 | | /// </summary> |
| | 218 | | /// <param name="appName">Type of the client.</param> |
| | 219 | | /// <param name="appVersion">The app version.</param> |
| | 220 | | /// <param name="deviceId">The device id.</param> |
| | 221 | | /// <param name="deviceName">Name of the device.</param> |
| | 222 | | /// <param name="remoteEndPoint">The remote end point.</param> |
| | 223 | | /// <param name="user">The user.</param> |
| | 224 | | /// <returns>SessionInfo.</returns> |
| | 225 | | public async Task<SessionInfo> LogSessionActivity( |
| | 226 | | string appName, |
| | 227 | | string appVersion, |
| | 228 | | string deviceId, |
| | 229 | | string deviceName, |
| | 230 | | string remoteEndPoint, |
| | 231 | | User user) |
| | 232 | | { |
| | 233 | | CheckDisposed(); |
| | 234 | |
|
| | 235 | | ArgumentException.ThrowIfNullOrEmpty(appName); |
| | 236 | | ArgumentException.ThrowIfNullOrEmpty(appVersion); |
| | 237 | | ArgumentException.ThrowIfNullOrEmpty(deviceId); |
| | 238 | |
|
| | 239 | | var activityDate = DateTime.UtcNow; |
| | 240 | | var session = GetSessionInfo(appName, appVersion, deviceId, deviceName, remoteEndPoint, user); |
| | 241 | | var lastActivityDate = session.LastActivityDate; |
| | 242 | | session.LastActivityDate = activityDate; |
| | 243 | |
|
| | 244 | | if (user is not null) |
| | 245 | | { |
| | 246 | | var userLastActivityDate = user.LastActivityDate ?? DateTime.MinValue; |
| | 247 | |
|
| | 248 | | if ((activityDate - userLastActivityDate).TotalSeconds > 60) |
| | 249 | | { |
| | 250 | | try |
| | 251 | | { |
| | 252 | | user.LastActivityDate = activityDate; |
| | 253 | | await _userManager.UpdateUserAsync(user).ConfigureAwait(false); |
| | 254 | | } |
| | 255 | | catch (DbUpdateConcurrencyException e) |
| | 256 | | { |
| | 257 | | _logger.LogDebug(e, "Error updating user's last activity date."); |
| | 258 | | } |
| | 259 | | } |
| | 260 | | } |
| | 261 | |
|
| | 262 | | if ((activityDate - lastActivityDate).TotalSeconds > 10) |
| | 263 | | { |
| | 264 | | SessionActivity?.Invoke( |
| | 265 | | this, |
| | 266 | | new SessionEventArgs |
| | 267 | | { |
| | 268 | | SessionInfo = session |
| | 269 | | }); |
| | 270 | | } |
| | 271 | |
|
| | 272 | | return session; |
| | 273 | | } |
| | 274 | |
|
| | 275 | | /// <inheritdoc /> |
| | 276 | | public void OnSessionControllerConnected(SessionInfo session) |
| | 277 | | { |
| 0 | 278 | | EventHelper.QueueEventIfNotNull( |
| 0 | 279 | | SessionControllerConnected, |
| 0 | 280 | | this, |
| 0 | 281 | | new SessionEventArgs |
| 0 | 282 | | { |
| 0 | 283 | | SessionInfo = session |
| 0 | 284 | | }, |
| 0 | 285 | | _logger); |
| 0 | 286 | | } |
| | 287 | |
|
| | 288 | | /// <inheritdoc /> |
| | 289 | | public async Task CloseIfNeededAsync(SessionInfo session) |
| | 290 | | { |
| | 291 | | if (!session.SessionControllers.Any(i => i.IsSessionActive)) |
| | 292 | | { |
| | 293 | | var key = GetSessionKey(session.Client, session.DeviceId); |
| | 294 | |
|
| | 295 | | _activeConnections.TryRemove(key, out _); |
| | 296 | | if (!string.IsNullOrEmpty(session.PlayState?.LiveStreamId)) |
| | 297 | | { |
| | 298 | | await _mediaSourceManager.CloseLiveStream(session.PlayState.LiveStreamId).ConfigureAwait(false); |
| | 299 | | } |
| | 300 | |
|
| | 301 | | await OnSessionEnded(session).ConfigureAwait(false); |
| | 302 | | } |
| | 303 | | } |
| | 304 | |
|
| | 305 | | /// <inheritdoc /> |
| | 306 | | public async ValueTask ReportSessionEnded(string sessionId) |
| | 307 | | { |
| | 308 | | CheckDisposed(); |
| | 309 | | var session = GetSession(sessionId, false); |
| | 310 | |
|
| | 311 | | if (session is not null) |
| | 312 | | { |
| | 313 | | var key = GetSessionKey(session.Client, session.DeviceId); |
| | 314 | |
|
| | 315 | | _activeConnections.TryRemove(key, out _); |
| | 316 | |
|
| | 317 | | await OnSessionEnded(session).ConfigureAwait(false); |
| | 318 | | } |
| | 319 | | } |
| | 320 | |
|
| | 321 | | private Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId) |
| | 322 | | { |
| 0 | 323 | | return _mediaSourceManager.GetMediaSource(item, mediaSourceId, liveStreamId, false, CancellationToken.None); |
| | 324 | | } |
| | 325 | |
|
| | 326 | | /// <summary> |
| | 327 | | /// Updates the now playing item id. |
| | 328 | | /// </summary> |
| | 329 | | /// <returns>Task.</returns> |
| | 330 | | private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bo |
| | 331 | | { |
| | 332 | | if (string.IsNullOrEmpty(info.MediaSourceId)) |
| | 333 | | { |
| | 334 | | info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture); |
| | 335 | | } |
| | 336 | |
|
| | 337 | | if (!info.ItemId.IsEmpty() && info.Item is null && libraryItem is not null) |
| | 338 | | { |
| | 339 | | var current = session.NowPlayingItem; |
| | 340 | |
|
| | 341 | | if (current is null || !info.ItemId.Equals(current.Id)) |
| | 342 | | { |
| | 343 | | var runtimeTicks = libraryItem.RunTimeTicks; |
| | 344 | |
|
| | 345 | | MediaSourceInfo mediaSource = null; |
| | 346 | | if (libraryItem is IHasMediaSources) |
| | 347 | | { |
| | 348 | | mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).Configure |
| | 349 | |
|
| | 350 | | if (mediaSource is not null) |
| | 351 | | { |
| | 352 | | runtimeTicks = mediaSource.RunTimeTicks; |
| | 353 | | } |
| | 354 | | } |
| | 355 | |
|
| | 356 | | info.Item = GetItemInfo(libraryItem, mediaSource); |
| | 357 | |
|
| | 358 | | info.Item.RunTimeTicks = runtimeTicks; |
| | 359 | | } |
| | 360 | | else |
| | 361 | | { |
| | 362 | | info.Item = current; |
| | 363 | | } |
| | 364 | | } |
| | 365 | |
|
| | 366 | | session.NowPlayingItem = info.Item; |
| | 367 | | session.LastActivityDate = DateTime.UtcNow; |
| | 368 | |
|
| | 369 | | if (updateLastCheckInTime) |
| | 370 | | { |
| | 371 | | session.LastPlaybackCheckIn = DateTime.UtcNow; |
| | 372 | | } |
| | 373 | |
|
| | 374 | | if (info.IsPaused && session.LastPausedDate is null) |
| | 375 | | { |
| | 376 | | session.LastPausedDate = DateTime.UtcNow; |
| | 377 | | } |
| | 378 | | else if (!info.IsPaused) |
| | 379 | | { |
| | 380 | | session.LastPausedDate = null; |
| | 381 | | } |
| | 382 | |
|
| | 383 | | session.PlayState.IsPaused = info.IsPaused; |
| | 384 | | session.PlayState.PositionTicks = info.PositionTicks; |
| | 385 | | session.PlayState.MediaSourceId = info.MediaSourceId; |
| | 386 | | session.PlayState.LiveStreamId = info.LiveStreamId; |
| | 387 | | session.PlayState.CanSeek = info.CanSeek; |
| | 388 | | session.PlayState.IsMuted = info.IsMuted; |
| | 389 | | session.PlayState.VolumeLevel = info.VolumeLevel; |
| | 390 | | session.PlayState.AudioStreamIndex = info.AudioStreamIndex; |
| | 391 | | session.PlayState.SubtitleStreamIndex = info.SubtitleStreamIndex; |
| | 392 | | session.PlayState.PlayMethod = info.PlayMethod; |
| | 393 | | session.PlayState.RepeatMode = info.RepeatMode; |
| | 394 | | session.PlayState.PlaybackOrder = info.PlaybackOrder; |
| | 395 | | session.PlaylistItemId = info.PlaylistItemId; |
| | 396 | |
|
| | 397 | | var nowPlayingQueue = info.NowPlayingQueue; |
| | 398 | |
|
| | 399 | | if (nowPlayingQueue?.Length > 0) |
| | 400 | | { |
| | 401 | | session.NowPlayingQueue = nowPlayingQueue; |
| | 402 | |
|
| | 403 | | var itemIds = Array.ConvertAll(nowPlayingQueue, queue => queue.Id); |
| | 404 | | session.NowPlayingQueueFullItems = _dtoService.GetBaseItemDtos( |
| | 405 | | _libraryManager.GetItemList(new InternalItemsQuery { ItemIds = itemIds }), |
| | 406 | | new DtoOptions(true)); |
| | 407 | | } |
| | 408 | | } |
| | 409 | |
|
| | 410 | | /// <summary> |
| | 411 | | /// Removes the now playing item id. |
| | 412 | | /// </summary> |
| | 413 | | /// <param name="session">The session.</param> |
| | 414 | | private void RemoveNowPlayingItem(SessionInfo session) |
| | 415 | | { |
| 0 | 416 | | session.NowPlayingItem = null; |
| 0 | 417 | | session.PlayState = new PlayerStateInfo(); |
| | 418 | |
|
| 0 | 419 | | if (!string.IsNullOrEmpty(session.DeviceId)) |
| | 420 | | { |
| 0 | 421 | | ClearTranscodingInfo(session.DeviceId); |
| | 422 | | } |
| 0 | 423 | | } |
| | 424 | |
|
| | 425 | | private static string GetSessionKey(string appName, string deviceId) |
| 16 | 426 | | => appName + deviceId; |
| | 427 | |
|
| | 428 | | /// <summary> |
| | 429 | | /// Gets the connection. |
| | 430 | | /// </summary> |
| | 431 | | /// <param name="appName">Type of the client.</param> |
| | 432 | | /// <param name="appVersion">The app version.</param> |
| | 433 | | /// <param name="deviceId">The device id.</param> |
| | 434 | | /// <param name="deviceName">Name of the device.</param> |
| | 435 | | /// <param name="remoteEndPoint">The remote end point.</param> |
| | 436 | | /// <param name="user">The user.</param> |
| | 437 | | /// <returns>SessionInfo.</returns> |
| | 438 | | private SessionInfo GetSessionInfo( |
| | 439 | | string appName, |
| | 440 | | string appVersion, |
| | 441 | | string deviceId, |
| | 442 | | string deviceName, |
| | 443 | | string remoteEndPoint, |
| | 444 | | User user) |
| | 445 | | { |
| 16 | 446 | | CheckDisposed(); |
| | 447 | |
|
| 16 | 448 | | ArgumentException.ThrowIfNullOrEmpty(deviceId); |
| | 449 | |
|
| 16 | 450 | | var key = GetSessionKey(appName, deviceId); |
| | 451 | |
|
| 16 | 452 | | CheckDisposed(); |
| | 453 | |
|
| 16 | 454 | | if (!_activeConnections.TryGetValue(key, out var sessionInfo)) |
| | 455 | | { |
| 16 | 456 | | sessionInfo = CreateSession(key, appName, appVersion, deviceId, deviceName, remoteEndPoint, user); |
| 16 | 457 | | _activeConnections[key] = sessionInfo; |
| | 458 | | } |
| | 459 | |
|
| 16 | 460 | | sessionInfo.UserId = user?.Id ?? Guid.Empty; |
| 16 | 461 | | sessionInfo.UserName = user?.Username; |
| 16 | 462 | | sessionInfo.UserPrimaryImageTag = user?.ProfileImage is null ? null : GetImageCacheTag(user); |
| 16 | 463 | | sessionInfo.RemoteEndPoint = remoteEndPoint; |
| 16 | 464 | | sessionInfo.Client = appName; |
| | 465 | |
|
| 16 | 466 | | if (!sessionInfo.HasCustomDeviceName || string.IsNullOrEmpty(sessionInfo.DeviceName)) |
| | 467 | | { |
| 16 | 468 | | sessionInfo.DeviceName = deviceName; |
| | 469 | | } |
| | 470 | |
|
| 16 | 471 | | sessionInfo.ApplicationVersion = appVersion; |
| | 472 | |
|
| 16 | 473 | | if (user is null) |
| | 474 | | { |
| 0 | 475 | | sessionInfo.AdditionalUsers = Array.Empty<SessionUserInfo>(); |
| | 476 | | } |
| | 477 | |
|
| 16 | 478 | | return sessionInfo; |
| | 479 | | } |
| | 480 | |
|
| | 481 | | private SessionInfo CreateSession( |
| | 482 | | string key, |
| | 483 | | string appName, |
| | 484 | | string appVersion, |
| | 485 | | string deviceId, |
| | 486 | | string deviceName, |
| | 487 | | string remoteEndPoint, |
| | 488 | | User user) |
| | 489 | | { |
| 16 | 490 | | var sessionInfo = new SessionInfo(this, _logger) |
| 16 | 491 | | { |
| 16 | 492 | | Client = appName, |
| 16 | 493 | | DeviceId = deviceId, |
| 16 | 494 | | ApplicationVersion = appVersion, |
| 16 | 495 | | Id = key.GetMD5().ToString("N", CultureInfo.InvariantCulture), |
| 16 | 496 | | ServerId = _appHost.SystemId |
| 16 | 497 | | }; |
| | 498 | |
|
| 16 | 499 | | var username = user?.Username; |
| | 500 | |
|
| 16 | 501 | | sessionInfo.UserId = user?.Id ?? Guid.Empty; |
| 16 | 502 | | sessionInfo.UserName = username; |
| 16 | 503 | | sessionInfo.UserPrimaryImageTag = user?.ProfileImage is null ? null : GetImageCacheTag(user); |
| 16 | 504 | | sessionInfo.RemoteEndPoint = remoteEndPoint; |
| | 505 | |
|
| 16 | 506 | | if (string.IsNullOrEmpty(deviceName)) |
| | 507 | | { |
| 0 | 508 | | deviceName = "Network Device"; |
| | 509 | | } |
| | 510 | |
|
| 16 | 511 | | var deviceOptions = _deviceManager.GetDeviceOptions(deviceId); |
| 16 | 512 | | if (string.IsNullOrEmpty(deviceOptions.CustomName)) |
| | 513 | | { |
| 16 | 514 | | sessionInfo.DeviceName = deviceName; |
| | 515 | | } |
| | 516 | | else |
| | 517 | | { |
| 0 | 518 | | sessionInfo.DeviceName = deviceOptions.CustomName; |
| 0 | 519 | | sessionInfo.HasCustomDeviceName = true; |
| | 520 | | } |
| | 521 | |
|
| 16 | 522 | | OnSessionStarted(sessionInfo); |
| 16 | 523 | | return sessionInfo; |
| | 524 | | } |
| | 525 | |
|
| | 526 | | private List<User> GetUsers(SessionInfo session) |
| | 527 | | { |
| 0 | 528 | | var users = new List<User>(); |
| | 529 | |
|
| 0 | 530 | | if (session.UserId.IsEmpty()) |
| | 531 | | { |
| 0 | 532 | | return users; |
| | 533 | | } |
| | 534 | |
|
| 0 | 535 | | var user = _userManager.GetUserById(session.UserId); |
| | 536 | |
|
| 0 | 537 | | if (user is null) |
| | 538 | | { |
| 0 | 539 | | throw new InvalidOperationException("User not found"); |
| | 540 | | } |
| | 541 | |
|
| 0 | 542 | | users.Add(user); |
| | 543 | |
|
| 0 | 544 | | users.AddRange(session.AdditionalUsers |
| 0 | 545 | | .Select(i => _userManager.GetUserById(i.UserId)) |
| 0 | 546 | | .Where(i => i is not null)); |
| | 547 | |
|
| 0 | 548 | | return users; |
| | 549 | | } |
| | 550 | |
|
| | 551 | | private void StartCheckTimers() |
| | 552 | | { |
| 0 | 553 | | _idleTimer ??= new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); |
| | 554 | |
|
| 0 | 555 | | if (_config.Configuration.InactiveSessionThreshold > 0) |
| | 556 | | { |
| 0 | 557 | | _inactiveTimer ??= new Timer(CheckForInactiveSteams, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes |
| | 558 | | } |
| | 559 | | else |
| | 560 | | { |
| 0 | 561 | | StopInactiveCheckTimer(); |
| | 562 | | } |
| 0 | 563 | | } |
| | 564 | |
|
| | 565 | | private void StopIdleCheckTimer() |
| | 566 | | { |
| 0 | 567 | | if (_idleTimer is not null) |
| | 568 | | { |
| 0 | 569 | | _idleTimer.Dispose(); |
| 0 | 570 | | _idleTimer = null; |
| | 571 | | } |
| 0 | 572 | | } |
| | 573 | |
|
| | 574 | | private void StopInactiveCheckTimer() |
| | 575 | | { |
| 0 | 576 | | if (_inactiveTimer is not null) |
| | 577 | | { |
| 0 | 578 | | _inactiveTimer.Dispose(); |
| 0 | 579 | | _inactiveTimer = null; |
| | 580 | | } |
| 0 | 581 | | } |
| | 582 | |
|
| | 583 | | private async void CheckForIdlePlayback(object state) |
| | 584 | | { |
| | 585 | | var playingSessions = Sessions.Where(i => i.NowPlayingItem is not null) |
| | 586 | | .ToList(); |
| | 587 | |
|
| | 588 | | if (playingSessions.Count > 0) |
| | 589 | | { |
| | 590 | | var idle = playingSessions |
| | 591 | | .Where(i => (DateTime.UtcNow - i.LastPlaybackCheckIn).TotalMinutes > 5) |
| | 592 | | .ToList(); |
| | 593 | |
|
| | 594 | | foreach (var session in idle) |
| | 595 | | { |
| | 596 | | _logger.LogDebug("Session {0} has gone idle while playing", session.Id); |
| | 597 | |
|
| | 598 | | try |
| | 599 | | { |
| | 600 | | await OnPlaybackStopped(new PlaybackStopInfo |
| | 601 | | { |
| | 602 | | Item = session.NowPlayingItem, |
| | 603 | | ItemId = session.NowPlayingItem is null ? Guid.Empty : session.NowPlayingItem.Id, |
| | 604 | | SessionId = session.Id, |
| | 605 | | MediaSourceId = session.PlayState?.MediaSourceId, |
| | 606 | | PositionTicks = session.PlayState?.PositionTicks |
| | 607 | | }).ConfigureAwait(false); |
| | 608 | | } |
| | 609 | | catch (Exception ex) |
| | 610 | | { |
| | 611 | | _logger.LogDebug(ex, "Error calling OnPlaybackStopped"); |
| | 612 | | } |
| | 613 | | } |
| | 614 | | } |
| | 615 | | else |
| | 616 | | { |
| | 617 | | StopIdleCheckTimer(); |
| | 618 | | } |
| | 619 | | } |
| | 620 | |
|
| | 621 | | private async void CheckForInactiveSteams(object state) |
| | 622 | | { |
| | 623 | | var inactiveSessions = Sessions.Where(i => |
| | 624 | | i.NowPlayingItem is not null |
| | 625 | | && i.PlayState.IsPaused |
| | 626 | | && (DateTime.UtcNow - i.LastPausedDate).Value.TotalMinutes > _config.Configuration.InactiveSessionTh |
| | 627 | |
|
| | 628 | | foreach (var session in inactiveSessions) |
| | 629 | | { |
| | 630 | | _logger.LogDebug("Session {Session} has been inactive for {InactiveTime} minutes. Stopping it.", session |
| | 631 | |
|
| | 632 | | try |
| | 633 | | { |
| | 634 | | await SendPlaystateCommand( |
| | 635 | | session.Id, |
| | 636 | | session.Id, |
| | 637 | | new PlaystateRequest() |
| | 638 | | { |
| | 639 | | Command = PlaystateCommand.Stop, |
| | 640 | | ControllingUserId = session.UserId.ToString(), |
| | 641 | | SeekPositionTicks = session.PlayState?.PositionTicks |
| | 642 | | }, |
| | 643 | | CancellationToken.None).ConfigureAwait(true); |
| | 644 | | } |
| | 645 | | catch (Exception ex) |
| | 646 | | { |
| | 647 | | _logger.LogDebug(ex, "Error calling SendPlaystateCommand for stopping inactive session {Session}.", |
| | 648 | | } |
| | 649 | | } |
| | 650 | |
|
| | 651 | | bool playingSessions = Sessions.Any(i => i.NowPlayingItem is not null); |
| | 652 | |
|
| | 653 | | if (!playingSessions) |
| | 654 | | { |
| | 655 | | StopInactiveCheckTimer(); |
| | 656 | | } |
| | 657 | | } |
| | 658 | |
|
| | 659 | | private BaseItem GetNowPlayingItem(SessionInfo session, Guid itemId) |
| | 660 | | { |
| 0 | 661 | | var item = session.FullNowPlayingItem; |
| 0 | 662 | | if (item is not null && item.Id.Equals(itemId)) |
| | 663 | | { |
| 0 | 664 | | return item; |
| | 665 | | } |
| | 666 | |
|
| 0 | 667 | | item = _libraryManager.GetItemById(itemId); |
| | 668 | |
|
| 0 | 669 | | session.FullNowPlayingItem = item; |
| | 670 | |
|
| 0 | 671 | | return item; |
| | 672 | | } |
| | 673 | |
|
| | 674 | | /// <summary> |
| | 675 | | /// Used to report that playback has started for an item. |
| | 676 | | /// </summary> |
| | 677 | | /// <param name="info">The info.</param> |
| | 678 | | /// <returns>Task.</returns> |
| | 679 | | /// <exception cref="ArgumentNullException"><c>info</c> is <c>null</c>.</exception> |
| | 680 | | public async Task OnPlaybackStart(PlaybackStartInfo info) |
| | 681 | | { |
| | 682 | | CheckDisposed(); |
| | 683 | |
|
| | 684 | | ArgumentNullException.ThrowIfNull(info); |
| | 685 | |
|
| | 686 | | var session = GetSession(info.SessionId); |
| | 687 | |
|
| | 688 | | var libraryItem = info.ItemId.IsEmpty() |
| | 689 | | ? null |
| | 690 | | : GetNowPlayingItem(session, info.ItemId); |
| | 691 | |
|
| | 692 | | await UpdateNowPlayingItem(session, info, libraryItem, true).ConfigureAwait(false); |
| | 693 | |
|
| | 694 | | if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode) |
| | 695 | | { |
| | 696 | | ClearTranscodingInfo(session.DeviceId); |
| | 697 | | } |
| | 698 | |
|
| | 699 | | session.StartAutomaticProgress(info); |
| | 700 | |
|
| | 701 | | var users = GetUsers(session); |
| | 702 | |
|
| | 703 | | if (libraryItem is not null) |
| | 704 | | { |
| | 705 | | foreach (var user in users) |
| | 706 | | { |
| | 707 | | OnPlaybackStart(user, libraryItem); |
| | 708 | | } |
| | 709 | | } |
| | 710 | |
|
| | 711 | | var eventArgs = new PlaybackStartEventArgs |
| | 712 | | { |
| | 713 | | Item = libraryItem, |
| | 714 | | Users = users, |
| | 715 | | MediaSourceId = info.MediaSourceId, |
| | 716 | | MediaInfo = info.Item, |
| | 717 | | DeviceName = session.DeviceName, |
| | 718 | | ClientName = session.Client, |
| | 719 | | DeviceId = session.DeviceId, |
| | 720 | | Session = session, |
| | 721 | | PlaybackPositionTicks = info.PositionTicks, |
| | 722 | | PlaySessionId = info.PlaySessionId |
| | 723 | | }; |
| | 724 | |
|
| | 725 | | await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false); |
| | 726 | |
|
| | 727 | | // Nothing to save here |
| | 728 | | // Fire events to inform plugins |
| | 729 | | EventHelper.QueueEventIfNotNull( |
| | 730 | | PlaybackStart, |
| | 731 | | this, |
| | 732 | | eventArgs, |
| | 733 | | _logger); |
| | 734 | |
|
| | 735 | | StartCheckTimers(); |
| | 736 | | } |
| | 737 | |
|
| | 738 | | /// <summary> |
| | 739 | | /// Called when [playback start]. |
| | 740 | | /// </summary> |
| | 741 | | /// <param name="user">The user object.</param> |
| | 742 | | /// <param name="item">The item.</param> |
| | 743 | | private void OnPlaybackStart(User user, BaseItem item) |
| | 744 | | { |
| 0 | 745 | | var data = _userDataManager.GetUserData(user, item); |
| | 746 | |
|
| 0 | 747 | | data.PlayCount++; |
| 0 | 748 | | data.LastPlayedDate = DateTime.UtcNow; |
| | 749 | |
|
| 0 | 750 | | if (item.SupportsPlayedStatus && !item.SupportsPositionTicksResume) |
| | 751 | | { |
| 0 | 752 | | data.Played = true; |
| | 753 | | } |
| | 754 | | else |
| | 755 | | { |
| 0 | 756 | | data.Played = false; |
| | 757 | | } |
| | 758 | |
|
| 0 | 759 | | _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackStart, CancellationToken.None); |
| 0 | 760 | | } |
| | 761 | |
|
| | 762 | | /// <inheritdoc /> |
| | 763 | | public Task OnPlaybackProgress(PlaybackProgressInfo info) |
| | 764 | | { |
| 0 | 765 | | return OnPlaybackProgress(info, false); |
| | 766 | | } |
| | 767 | |
|
| | 768 | | /// <summary> |
| | 769 | | /// Used to report playback progress for an item. |
| | 770 | | /// </summary> |
| | 771 | | /// <param name="info">The playback progress info.</param> |
| | 772 | | /// <param name="isAutomated">Whether this is an automated update.</param> |
| | 773 | | /// <returns>Task.</returns> |
| | 774 | | public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated) |
| | 775 | | { |
| | 776 | | CheckDisposed(); |
| | 777 | |
|
| | 778 | | ArgumentNullException.ThrowIfNull(info); |
| | 779 | |
|
| | 780 | | var session = GetSession(info.SessionId); |
| | 781 | |
|
| | 782 | | var libraryItem = info.ItemId.IsEmpty() |
| | 783 | | ? null |
| | 784 | | : GetNowPlayingItem(session, info.ItemId); |
| | 785 | |
|
| | 786 | | await UpdateNowPlayingItem(session, info, libraryItem, !isAutomated).ConfigureAwait(false); |
| | 787 | |
|
| | 788 | | if (!string.IsNullOrEmpty(session.DeviceId) && info.PlayMethod != PlayMethod.Transcode) |
| | 789 | | { |
| | 790 | | ClearTranscodingInfo(session.DeviceId); |
| | 791 | | } |
| | 792 | |
|
| | 793 | | var users = GetUsers(session); |
| | 794 | |
|
| | 795 | | // only update saved user data on actual check-ins, not automated ones |
| | 796 | | if (libraryItem is not null && !isAutomated) |
| | 797 | | { |
| | 798 | | foreach (var user in users) |
| | 799 | | { |
| | 800 | | OnPlaybackProgress(user, libraryItem, info); |
| | 801 | | } |
| | 802 | | } |
| | 803 | |
|
| | 804 | | var eventArgs = new PlaybackProgressEventArgs |
| | 805 | | { |
| | 806 | | Item = libraryItem, |
| | 807 | | Users = users, |
| | 808 | | PlaybackPositionTicks = session.PlayState.PositionTicks, |
| | 809 | | MediaSourceId = session.PlayState.MediaSourceId, |
| | 810 | | MediaInfo = info.Item, |
| | 811 | | DeviceName = session.DeviceName, |
| | 812 | | ClientName = session.Client, |
| | 813 | | DeviceId = session.DeviceId, |
| | 814 | | IsPaused = info.IsPaused, |
| | 815 | | PlaySessionId = info.PlaySessionId, |
| | 816 | | IsAutomated = isAutomated, |
| | 817 | | Session = session |
| | 818 | | }; |
| | 819 | |
|
| | 820 | | await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false); |
| | 821 | |
|
| | 822 | | PlaybackProgress?.Invoke(this, eventArgs); |
| | 823 | |
|
| | 824 | | if (!isAutomated) |
| | 825 | | { |
| | 826 | | session.StartAutomaticProgress(info); |
| | 827 | | } |
| | 828 | |
|
| | 829 | | StartCheckTimers(); |
| | 830 | | } |
| | 831 | |
|
| | 832 | | private void OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info) |
| | 833 | | { |
| 0 | 834 | | var data = _userDataManager.GetUserData(user, item); |
| | 835 | |
|
| 0 | 836 | | var positionTicks = info.PositionTicks; |
| | 837 | |
|
| 0 | 838 | | var changed = false; |
| | 839 | |
|
| 0 | 840 | | if (positionTicks.HasValue) |
| | 841 | | { |
| 0 | 842 | | _userDataManager.UpdatePlayState(item, data, positionTicks.Value); |
| 0 | 843 | | changed = true; |
| | 844 | | } |
| | 845 | |
|
| 0 | 846 | | var tracksChanged = UpdatePlaybackSettings(user, info, data); |
| 0 | 847 | | if (!tracksChanged) |
| | 848 | | { |
| 0 | 849 | | changed = true; |
| | 850 | | } |
| | 851 | |
|
| 0 | 852 | | if (changed) |
| | 853 | | { |
| 0 | 854 | | _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackProgress, CancellationToken.N |
| | 855 | | } |
| 0 | 856 | | } |
| | 857 | |
|
| | 858 | | private static bool UpdatePlaybackSettings(User user, PlaybackProgressInfo info, UserItemData data) |
| | 859 | | { |
| 0 | 860 | | var changed = false; |
| | 861 | |
|
| 0 | 862 | | if (user.RememberAudioSelections) |
| | 863 | | { |
| 0 | 864 | | if (data.AudioStreamIndex != info.AudioStreamIndex) |
| | 865 | | { |
| 0 | 866 | | data.AudioStreamIndex = info.AudioStreamIndex; |
| 0 | 867 | | changed = true; |
| | 868 | | } |
| | 869 | | } |
| | 870 | | else |
| | 871 | | { |
| 0 | 872 | | if (data.AudioStreamIndex.HasValue) |
| | 873 | | { |
| 0 | 874 | | data.AudioStreamIndex = null; |
| 0 | 875 | | changed = true; |
| | 876 | | } |
| | 877 | | } |
| | 878 | |
|
| 0 | 879 | | if (user.RememberSubtitleSelections) |
| | 880 | | { |
| 0 | 881 | | if (data.SubtitleStreamIndex != info.SubtitleStreamIndex) |
| | 882 | | { |
| 0 | 883 | | data.SubtitleStreamIndex = info.SubtitleStreamIndex; |
| 0 | 884 | | changed = true; |
| | 885 | | } |
| | 886 | | } |
| | 887 | | else |
| | 888 | | { |
| 0 | 889 | | if (data.SubtitleStreamIndex.HasValue) |
| | 890 | | { |
| 0 | 891 | | data.SubtitleStreamIndex = null; |
| 0 | 892 | | changed = true; |
| | 893 | | } |
| | 894 | | } |
| | 895 | |
|
| 0 | 896 | | return changed; |
| | 897 | | } |
| | 898 | |
|
| | 899 | | /// <summary> |
| | 900 | | /// Used to report that playback has ended for an item. |
| | 901 | | /// </summary> |
| | 902 | | /// <param name="info">The info.</param> |
| | 903 | | /// <returns>Task.</returns> |
| | 904 | | /// <exception cref="ArgumentNullException"><c>info</c> is <c>null</c>.</exception> |
| | 905 | | /// <exception cref="ArgumentOutOfRangeException"><c>info.PositionTicks</c> is <c>null</c> or negative.</excepti |
| | 906 | | public async Task OnPlaybackStopped(PlaybackStopInfo info) |
| | 907 | | { |
| | 908 | | CheckDisposed(); |
| | 909 | |
|
| | 910 | | ArgumentNullException.ThrowIfNull(info); |
| | 911 | |
|
| | 912 | | if (info.PositionTicks.HasValue && info.PositionTicks.Value < 0) |
| | 913 | | { |
| | 914 | | throw new ArgumentOutOfRangeException(nameof(info), "The PlaybackStopInfo's PositionTicks was negative." |
| | 915 | | } |
| | 916 | |
|
| | 917 | | var session = GetSession(info.SessionId); |
| | 918 | |
|
| | 919 | | session.StopAutomaticProgress(); |
| | 920 | |
|
| | 921 | | var libraryItem = info.ItemId.IsEmpty() |
| | 922 | | ? null |
| | 923 | | : GetNowPlayingItem(session, info.ItemId); |
| | 924 | |
|
| | 925 | | // Normalize |
| | 926 | | if (string.IsNullOrEmpty(info.MediaSourceId)) |
| | 927 | | { |
| | 928 | | info.MediaSourceId = info.ItemId.ToString("N", CultureInfo.InvariantCulture); |
| | 929 | | } |
| | 930 | |
|
| | 931 | | if (!info.ItemId.IsEmpty() && info.Item is null && libraryItem is not null) |
| | 932 | | { |
| | 933 | | var current = session.NowPlayingItem; |
| | 934 | |
|
| | 935 | | if (current is null || !info.ItemId.Equals(current.Id)) |
| | 936 | | { |
| | 937 | | MediaSourceInfo mediaSource = null; |
| | 938 | |
|
| | 939 | | if (libraryItem is IHasMediaSources) |
| | 940 | | { |
| | 941 | | mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).Configure |
| | 942 | | } |
| | 943 | |
|
| | 944 | | info.Item = GetItemInfo(libraryItem, mediaSource); |
| | 945 | | } |
| | 946 | | else |
| | 947 | | { |
| | 948 | | info.Item = current; |
| | 949 | | } |
| | 950 | | } |
| | 951 | |
|
| | 952 | | if (info.Item is not null) |
| | 953 | | { |
| | 954 | | var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.Inv |
| | 955 | |
|
| | 956 | | _logger.LogInformation( |
| | 957 | | "Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms", |
| | 958 | | session.Client, |
| | 959 | | session.ApplicationVersion, |
| | 960 | | info.Item.Name, |
| | 961 | | msString); |
| | 962 | | } |
| | 963 | |
|
| | 964 | | if (info.NowPlayingQueue is not null) |
| | 965 | | { |
| | 966 | | session.NowPlayingQueue = info.NowPlayingQueue; |
| | 967 | | } |
| | 968 | |
|
| | 969 | | session.PlaylistItemId = info.PlaylistItemId; |
| | 970 | |
|
| | 971 | | RemoveNowPlayingItem(session); |
| | 972 | |
|
| | 973 | | var users = GetUsers(session); |
| | 974 | | var playedToCompletion = false; |
| | 975 | |
|
| | 976 | | if (libraryItem is not null) |
| | 977 | | { |
| | 978 | | foreach (var user in users) |
| | 979 | | { |
| | 980 | | playedToCompletion = OnPlaybackStopped(user, libraryItem, info.PositionTicks, info.Failed); |
| | 981 | | } |
| | 982 | | } |
| | 983 | |
|
| | 984 | | if (!string.IsNullOrEmpty(info.LiveStreamId)) |
| | 985 | | { |
| | 986 | | try |
| | 987 | | { |
| | 988 | | await _mediaSourceManager.CloseLiveStream(info.LiveStreamId).ConfigureAwait(false); |
| | 989 | | } |
| | 990 | | catch (Exception ex) |
| | 991 | | { |
| | 992 | | _logger.LogError(ex, "Error closing live stream"); |
| | 993 | | } |
| | 994 | | } |
| | 995 | |
|
| | 996 | | var eventArgs = new PlaybackStopEventArgs |
| | 997 | | { |
| | 998 | | Item = libraryItem, |
| | 999 | | Users = users, |
| | 1000 | | PlaybackPositionTicks = info.PositionTicks, |
| | 1001 | | PlayedToCompletion = playedToCompletion, |
| | 1002 | | MediaSourceId = info.MediaSourceId, |
| | 1003 | | MediaInfo = info.Item, |
| | 1004 | | DeviceName = session.DeviceName, |
| | 1005 | | ClientName = session.Client, |
| | 1006 | | DeviceId = session.DeviceId, |
| | 1007 | | Session = session, |
| | 1008 | | PlaySessionId = info.PlaySessionId |
| | 1009 | | }; |
| | 1010 | |
|
| | 1011 | | await _eventManager.PublishAsync(eventArgs).ConfigureAwait(false); |
| | 1012 | |
|
| | 1013 | | EventHelper.QueueEventIfNotNull(PlaybackStopped, this, eventArgs, _logger); |
| | 1014 | | } |
| | 1015 | |
|
| | 1016 | | private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed) |
| | 1017 | | { |
| 0 | 1018 | | if (playbackFailed) |
| | 1019 | | { |
| 0 | 1020 | | return false; |
| | 1021 | | } |
| | 1022 | |
|
| 0 | 1023 | | var data = _userDataManager.GetUserData(user, item); |
| | 1024 | | bool playedToCompletion; |
| 0 | 1025 | | if (positionTicks.HasValue) |
| | 1026 | | { |
| 0 | 1027 | | playedToCompletion = _userDataManager.UpdatePlayState(item, data, positionTicks.Value); |
| | 1028 | | } |
| | 1029 | | else |
| | 1030 | | { |
| | 1031 | | // If the client isn't able to report this, then we'll just have to make an assumption |
| 0 | 1032 | | data.PlayCount++; |
| 0 | 1033 | | data.Played = item.SupportsPlayedStatus; |
| 0 | 1034 | | data.PlaybackPositionTicks = 0; |
| 0 | 1035 | | playedToCompletion = true; |
| | 1036 | | } |
| | 1037 | |
|
| 0 | 1038 | | _userDataManager.SaveUserData(user, item, data, UserDataSaveReason.PlaybackFinished, CancellationToken.None) |
| | 1039 | |
|
| 0 | 1040 | | return playedToCompletion; |
| | 1041 | | } |
| | 1042 | |
|
| | 1043 | | /// <summary> |
| | 1044 | | /// Gets the session. |
| | 1045 | | /// </summary> |
| | 1046 | | /// <param name="sessionId">The session identifier.</param> |
| | 1047 | | /// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param> |
| | 1048 | | /// <returns>SessionInfo.</returns> |
| | 1049 | | /// <exception cref="ResourceNotFoundException"> |
| | 1050 | | /// No session with an Id equal to <c>sessionId</c> was found |
| | 1051 | | /// and <c>throwOnMissing</c> is <c>true</c>. |
| | 1052 | | /// </exception> |
| | 1053 | | private SessionInfo GetSession(string sessionId, bool throwOnMissing = true) |
| | 1054 | | { |
| 0 | 1055 | | var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal)); |
| 0 | 1056 | | if (session is null && throwOnMissing) |
| | 1057 | | { |
| 0 | 1058 | | throw new ResourceNotFoundException( |
| 0 | 1059 | | string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); |
| | 1060 | | } |
| | 1061 | |
|
| 0 | 1062 | | return session; |
| | 1063 | | } |
| | 1064 | |
|
| | 1065 | | private SessionInfo GetSessionToRemoteControl(string sessionId) |
| | 1066 | | { |
| | 1067 | | // Accept either device id or session id |
| 0 | 1068 | | var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal)); |
| | 1069 | |
|
| 0 | 1070 | | if (session is null) |
| | 1071 | | { |
| 0 | 1072 | | throw new ResourceNotFoundException( |
| 0 | 1073 | | string.Format(CultureInfo.InvariantCulture, "Session {0} not found.", sessionId)); |
| | 1074 | | } |
| | 1075 | |
|
| 0 | 1076 | | return session; |
| | 1077 | | } |
| | 1078 | |
|
| | 1079 | | /// <inheritdoc /> |
| | 1080 | | public Task SendMessageCommand(string controllingSessionId, string sessionId, MessageCommand command, Cancellati |
| | 1081 | | { |
| 0 | 1082 | | CheckDisposed(); |
| | 1083 | |
|
| 0 | 1084 | | var generalCommand = new GeneralCommand |
| 0 | 1085 | | { |
| 0 | 1086 | | Name = GeneralCommandType.DisplayMessage |
| 0 | 1087 | | }; |
| | 1088 | |
|
| 0 | 1089 | | generalCommand.Arguments["Header"] = command.Header; |
| 0 | 1090 | | generalCommand.Arguments["Text"] = command.Text; |
| | 1091 | |
|
| 0 | 1092 | | if (command.TimeoutMs.HasValue) |
| | 1093 | | { |
| 0 | 1094 | | generalCommand.Arguments["TimeoutMs"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture); |
| | 1095 | | } |
| | 1096 | |
|
| 0 | 1097 | | return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); |
| | 1098 | | } |
| | 1099 | |
|
| | 1100 | | /// <inheritdoc /> |
| | 1101 | | public Task SendGeneralCommand(string controllingSessionId, string sessionId, GeneralCommand command, Cancellati |
| | 1102 | | { |
| 0 | 1103 | | CheckDisposed(); |
| | 1104 | |
|
| 0 | 1105 | | var session = GetSessionToRemoteControl(sessionId); |
| | 1106 | |
|
| 0 | 1107 | | if (!string.IsNullOrEmpty(controllingSessionId)) |
| | 1108 | | { |
| 0 | 1109 | | var controllingSession = GetSession(controllingSessionId); |
| 0 | 1110 | | AssertCanControl(session, controllingSession); |
| | 1111 | | } |
| | 1112 | |
|
| 0 | 1113 | | return SendMessageToSession(session, SessionMessageType.GeneralCommand, command, cancellationToken); |
| | 1114 | | } |
| | 1115 | |
|
| | 1116 | | private static async Task SendMessageToSession<T>(SessionInfo session, SessionMessageType name, T data, Cancella |
| | 1117 | | { |
| | 1118 | | var controllers = session.SessionControllers; |
| | 1119 | | var messageId = Guid.NewGuid(); |
| | 1120 | |
|
| | 1121 | | foreach (var controller in controllers) |
| | 1122 | | { |
| | 1123 | | await controller.SendMessage(name, messageId, data, cancellationToken).ConfigureAwait(false); |
| | 1124 | | } |
| | 1125 | | } |
| | 1126 | |
|
| | 1127 | | private static Task SendMessageToSessions<T>(IEnumerable<SessionInfo> sessions, SessionMessageType name, T data, |
| | 1128 | | { |
| | 1129 | | IEnumerable<Task> GetTasks() |
| | 1130 | | { |
| | 1131 | | var messageId = Guid.NewGuid(); |
| | 1132 | | foreach (var session in sessions) |
| | 1133 | | { |
| | 1134 | | var controllers = session.SessionControllers; |
| | 1135 | | foreach (var controller in controllers) |
| | 1136 | | { |
| | 1137 | | yield return controller.SendMessage(name, messageId, data, cancellationToken); |
| | 1138 | | } |
| | 1139 | | } |
| | 1140 | | } |
| | 1141 | |
|
| 22 | 1142 | | return Task.WhenAll(GetTasks()); |
| | 1143 | | } |
| | 1144 | |
|
| | 1145 | | /// <inheritdoc /> |
| | 1146 | | public async Task SendPlayCommand(string controllingSessionId, string sessionId, PlayRequest command, Cancellati |
| | 1147 | | { |
| | 1148 | | CheckDisposed(); |
| | 1149 | |
|
| | 1150 | | var session = GetSessionToRemoteControl(sessionId); |
| | 1151 | |
|
| | 1152 | | var user = session.UserId.IsEmpty() ? null : _userManager.GetUserById(session.UserId); |
| | 1153 | |
|
| | 1154 | | List<BaseItem> items; |
| | 1155 | |
|
| | 1156 | | if (command.PlayCommand == PlayCommand.PlayInstantMix) |
| | 1157 | | { |
| | 1158 | | items = command.ItemIds.SelectMany(i => TranslateItemForInstantMix(i, user)) |
| | 1159 | | .ToList(); |
| | 1160 | |
|
| | 1161 | | command.PlayCommand = PlayCommand.PlayNow; |
| | 1162 | | } |
| | 1163 | | else |
| | 1164 | | { |
| | 1165 | | var list = new List<BaseItem>(); |
| | 1166 | | foreach (var itemId in command.ItemIds) |
| | 1167 | | { |
| | 1168 | | var subItems = TranslateItemForPlayback(itemId, user); |
| | 1169 | | list.AddRange(subItems); |
| | 1170 | | } |
| | 1171 | |
|
| | 1172 | | items = list; |
| | 1173 | | } |
| | 1174 | |
|
| | 1175 | | if (command.PlayCommand == PlayCommand.PlayShuffle) |
| | 1176 | | { |
| | 1177 | | items.Shuffle(); |
| | 1178 | | command.PlayCommand = PlayCommand.PlayNow; |
| | 1179 | | } |
| | 1180 | |
|
| | 1181 | | command.ItemIds = items.Select(i => i.Id).ToArray(); |
| | 1182 | |
|
| | 1183 | | if (user is not null) |
| | 1184 | | { |
| | 1185 | | if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full)) |
| | 1186 | | { |
| | 1187 | | throw new ArgumentException( |
| | 1188 | | string.Format(CultureInfo.InvariantCulture, "{0} is not allowed to play media.", user.Username)) |
| | 1189 | | } |
| | 1190 | | } |
| | 1191 | |
|
| | 1192 | | if (user is not null |
| | 1193 | | && command.ItemIds.Length == 1 |
| | 1194 | | && user.EnableNextEpisodeAutoPlay |
| | 1195 | | && _libraryManager.GetItemById(command.ItemIds[0]) is Episode episode) |
| | 1196 | | { |
| | 1197 | | var series = episode.Series; |
| | 1198 | | if (series is not null) |
| | 1199 | | { |
| | 1200 | | var episodes = series.GetEpisodes( |
| | 1201 | | user, |
| | 1202 | | new DtoOptions(false) |
| | 1203 | | { |
| | 1204 | | EnableImages = false |
| | 1205 | | }, |
| | 1206 | | user.DisplayMissingEpisodes) |
| | 1207 | | .Where(i => !i.IsVirtualItem) |
| | 1208 | | .SkipWhile(i => !i.Id.Equals(episode.Id)) |
| | 1209 | | .ToList(); |
| | 1210 | |
|
| | 1211 | | if (episodes.Count > 0) |
| | 1212 | | { |
| | 1213 | | command.ItemIds = episodes.Select(i => i.Id).ToArray(); |
| | 1214 | | } |
| | 1215 | | } |
| | 1216 | | } |
| | 1217 | |
|
| | 1218 | | if (!string.IsNullOrEmpty(controllingSessionId)) |
| | 1219 | | { |
| | 1220 | | var controllingSession = GetSession(controllingSessionId); |
| | 1221 | | AssertCanControl(session, controllingSession); |
| | 1222 | | if (!controllingSession.UserId.IsEmpty()) |
| | 1223 | | { |
| | 1224 | | command.ControllingUserId = controllingSession.UserId; |
| | 1225 | | } |
| | 1226 | | } |
| | 1227 | |
|
| | 1228 | | await SendMessageToSession(session, SessionMessageType.Play, command, cancellationToken).ConfigureAwait(fals |
| | 1229 | | } |
| | 1230 | |
|
| | 1231 | | /// <inheritdoc /> |
| | 1232 | | public async Task SendSyncPlayCommand(string sessionId, SendCommand command, CancellationToken cancellationToken |
| | 1233 | | { |
| | 1234 | | CheckDisposed(); |
| | 1235 | | var session = GetSession(sessionId); |
| | 1236 | | await SendMessageToSession(session, SessionMessageType.SyncPlayCommand, command, cancellationToken).Configur |
| | 1237 | | } |
| | 1238 | |
|
| | 1239 | | /// <inheritdoc /> |
| | 1240 | | public async Task SendSyncPlayGroupUpdate<T>(string sessionId, GroupUpdate<T> command, CancellationToken cancell |
| | 1241 | | { |
| | 1242 | | CheckDisposed(); |
| | 1243 | | var session = GetSession(sessionId); |
| | 1244 | | await SendMessageToSession(session, SessionMessageType.SyncPlayGroupUpdate, command, cancellationToken).Conf |
| | 1245 | | } |
| | 1246 | |
|
| | 1247 | | private IEnumerable<BaseItem> TranslateItemForPlayback(Guid id, User user) |
| | 1248 | | { |
| 0 | 1249 | | var item = _libraryManager.GetItemById(id); |
| | 1250 | |
|
| 0 | 1251 | | if (item is null) |
| | 1252 | | { |
| 0 | 1253 | | _logger.LogError("A non-existent item Id {0} was passed into TranslateItemForPlayback", id); |
| 0 | 1254 | | return Array.Empty<BaseItem>(); |
| | 1255 | | } |
| | 1256 | |
|
| 0 | 1257 | | if (item is IItemByName byName) |
| | 1258 | | { |
| 0 | 1259 | | return byName.GetTaggedItems(new InternalItemsQuery(user) |
| 0 | 1260 | | { |
| 0 | 1261 | | IsFolder = false, |
| 0 | 1262 | | Recursive = true, |
| 0 | 1263 | | DtoOptions = new DtoOptions(false) |
| 0 | 1264 | | { |
| 0 | 1265 | | EnableImages = false, |
| 0 | 1266 | | Fields = new[] |
| 0 | 1267 | | { |
| 0 | 1268 | | ItemFields.SortName |
| 0 | 1269 | | } |
| 0 | 1270 | | }, |
| 0 | 1271 | | IsVirtualItem = false, |
| 0 | 1272 | | OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) } |
| 0 | 1273 | | }); |
| | 1274 | | } |
| | 1275 | |
|
| 0 | 1276 | | if (item.IsFolder) |
| | 1277 | | { |
| 0 | 1278 | | var folder = (Folder)item; |
| | 1279 | |
|
| 0 | 1280 | | return folder.GetItemList(new InternalItemsQuery(user) |
| 0 | 1281 | | { |
| 0 | 1282 | | Recursive = true, |
| 0 | 1283 | | IsFolder = false, |
| 0 | 1284 | | DtoOptions = new DtoOptions(false) |
| 0 | 1285 | | { |
| 0 | 1286 | | EnableImages = false, |
| 0 | 1287 | | Fields = new ItemFields[] |
| 0 | 1288 | | { |
| 0 | 1289 | | ItemFields.SortName |
| 0 | 1290 | | } |
| 0 | 1291 | | }, |
| 0 | 1292 | | IsVirtualItem = false, |
| 0 | 1293 | | OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) } |
| 0 | 1294 | | }); |
| | 1295 | | } |
| | 1296 | |
|
| 0 | 1297 | | return new[] { item }; |
| | 1298 | | } |
| | 1299 | |
|
| | 1300 | | private List<BaseItem> TranslateItemForInstantMix(Guid id, User user) |
| | 1301 | | { |
| 0 | 1302 | | var item = _libraryManager.GetItemById(id); |
| | 1303 | |
|
| 0 | 1304 | | if (item is null) |
| | 1305 | | { |
| 0 | 1306 | | _logger.LogError("A non-existent item Id {0} was passed into TranslateItemForInstantMix", id); |
| 0 | 1307 | | return new List<BaseItem>(); |
| | 1308 | | } |
| | 1309 | |
|
| 0 | 1310 | | return _musicManager.GetInstantMixFromItem(item, user, new DtoOptions(false) { EnableImages = false }).ToLis |
| | 1311 | | } |
| | 1312 | |
|
| | 1313 | | /// <inheritdoc /> |
| | 1314 | | public Task SendBrowseCommand(string controllingSessionId, string sessionId, BrowseRequest command, Cancellation |
| | 1315 | | { |
| 0 | 1316 | | var generalCommand = new GeneralCommand |
| 0 | 1317 | | { |
| 0 | 1318 | | Name = GeneralCommandType.DisplayContent, |
| 0 | 1319 | | Arguments = |
| 0 | 1320 | | { |
| 0 | 1321 | | ["ItemId"] = command.ItemId, |
| 0 | 1322 | | ["ItemName"] = command.ItemName, |
| 0 | 1323 | | ["ItemType"] = command.ItemType.ToString() |
| 0 | 1324 | | } |
| 0 | 1325 | | }; |
| | 1326 | |
|
| 0 | 1327 | | return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken); |
| | 1328 | | } |
| | 1329 | |
|
| | 1330 | | /// <inheritdoc /> |
| | 1331 | | public Task SendPlaystateCommand(string controllingSessionId, string sessionId, PlaystateRequest command, Cancel |
| | 1332 | | { |
| 0 | 1333 | | CheckDisposed(); |
| | 1334 | |
|
| 0 | 1335 | | var session = GetSessionToRemoteControl(sessionId); |
| | 1336 | |
|
| 0 | 1337 | | if (!string.IsNullOrEmpty(controllingSessionId)) |
| | 1338 | | { |
| 0 | 1339 | | var controllingSession = GetSession(controllingSessionId); |
| 0 | 1340 | | AssertCanControl(session, controllingSession); |
| 0 | 1341 | | if (!controllingSession.UserId.IsEmpty()) |
| | 1342 | | { |
| 0 | 1343 | | command.ControllingUserId = controllingSession.UserId.ToString("N", CultureInfo.InvariantCulture); |
| | 1344 | | } |
| | 1345 | | } |
| | 1346 | |
|
| 0 | 1347 | | return SendMessageToSession(session, SessionMessageType.Playstate, command, cancellationToken); |
| | 1348 | | } |
| | 1349 | |
|
| | 1350 | | private static void AssertCanControl(SessionInfo session, SessionInfo controllingSession) |
| | 1351 | | { |
| 0 | 1352 | | ArgumentNullException.ThrowIfNull(session); |
| | 1353 | |
|
| 0 | 1354 | | ArgumentNullException.ThrowIfNull(controllingSession); |
| 0 | 1355 | | } |
| | 1356 | |
|
| | 1357 | | /// <summary> |
| | 1358 | | /// Sends the restart required message. |
| | 1359 | | /// </summary> |
| | 1360 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | 1361 | | /// <returns>Task.</returns> |
| | 1362 | | public Task SendRestartRequiredNotification(CancellationToken cancellationToken) |
| | 1363 | | { |
| 0 | 1364 | | CheckDisposed(); |
| | 1365 | |
|
| 0 | 1366 | | return SendMessageToSessions(Sessions, SessionMessageType.RestartRequired, string.Empty, cancellationToken); |
| | 1367 | | } |
| | 1368 | |
|
| | 1369 | | /// <summary> |
| | 1370 | | /// Adds the additional user. |
| | 1371 | | /// </summary> |
| | 1372 | | /// <param name="sessionId">The session identifier.</param> |
| | 1373 | | /// <param name="userId">The user identifier.</param> |
| | 1374 | | /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</ |
| | 1375 | | /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exceptio |
| | 1376 | | public void AddAdditionalUser(string sessionId, Guid userId) |
| | 1377 | | { |
| 0 | 1378 | | CheckDisposed(); |
| | 1379 | |
|
| 0 | 1380 | | var session = GetSession(sessionId); |
| | 1381 | |
|
| 0 | 1382 | | if (session.UserId.Equals(userId)) |
| | 1383 | | { |
| 0 | 1384 | | throw new ArgumentException("The requested user is already the primary user of the session."); |
| | 1385 | | } |
| | 1386 | |
|
| 0 | 1387 | | if (session.AdditionalUsers.All(i => !i.UserId.Equals(userId))) |
| | 1388 | | { |
| 0 | 1389 | | var user = _userManager.GetUserById(userId); |
| 0 | 1390 | | var newUser = new SessionUserInfo |
| 0 | 1391 | | { |
| 0 | 1392 | | UserId = userId, |
| 0 | 1393 | | UserName = user.Username |
| 0 | 1394 | | }; |
| | 1395 | |
|
| 0 | 1396 | | session.AdditionalUsers = [..session.AdditionalUsers, newUser]; |
| | 1397 | | } |
| 0 | 1398 | | } |
| | 1399 | |
|
| | 1400 | | /// <summary> |
| | 1401 | | /// Removes the additional user. |
| | 1402 | | /// </summary> |
| | 1403 | | /// <param name="sessionId">The session identifier.</param> |
| | 1404 | | /// <param name="userId">The user identifier.</param> |
| | 1405 | | /// <exception cref="UnauthorizedAccessException">Cannot modify additional users without authenticating first.</ |
| | 1406 | | /// <exception cref="ArgumentException">The requested user is already the primary user of the session.</exceptio |
| | 1407 | | public void RemoveAdditionalUser(string sessionId, Guid userId) |
| | 1408 | | { |
| 0 | 1409 | | CheckDisposed(); |
| | 1410 | |
|
| 0 | 1411 | | var session = GetSession(sessionId); |
| | 1412 | |
|
| 0 | 1413 | | if (session.UserId.Equals(userId)) |
| | 1414 | | { |
| 0 | 1415 | | throw new ArgumentException("The requested user is already the primary user of the session."); |
| | 1416 | | } |
| | 1417 | |
|
| 0 | 1418 | | var user = session.AdditionalUsers.FirstOrDefault(i => i.UserId.Equals(userId)); |
| | 1419 | |
|
| 0 | 1420 | | if (user is not null) |
| | 1421 | | { |
| 0 | 1422 | | var list = session.AdditionalUsers.ToList(); |
| 0 | 1423 | | list.Remove(user); |
| | 1424 | |
|
| 0 | 1425 | | session.AdditionalUsers = list.ToArray(); |
| | 1426 | | } |
| 0 | 1427 | | } |
| | 1428 | |
|
| | 1429 | | /// <summary> |
| | 1430 | | /// Authenticates the new session. |
| | 1431 | | /// </summary> |
| | 1432 | | /// <param name="request">The authenticationrequest.</param> |
| | 1433 | | /// <returns>The authentication result.</returns> |
| | 1434 | | public Task<AuthenticationResult> AuthenticateNewSession(AuthenticationRequest request) |
| | 1435 | | { |
| 16 | 1436 | | return AuthenticateNewSessionInternal(request, true); |
| | 1437 | | } |
| | 1438 | |
|
| | 1439 | | /// <summary> |
| | 1440 | | /// Directly authenticates the session without enforcing password. |
| | 1441 | | /// </summary> |
| | 1442 | | /// <param name="request">The authentication request.</param> |
| | 1443 | | /// <returns>The authentication result.</returns> |
| | 1444 | | public Task<AuthenticationResult> AuthenticateDirect(AuthenticationRequest request) |
| | 1445 | | { |
| 0 | 1446 | | return AuthenticateNewSessionInternal(request, false); |
| | 1447 | | } |
| | 1448 | |
|
| | 1449 | | internal async Task<AuthenticationResult> AuthenticateNewSessionInternal(AuthenticationRequest request, bool enf |
| | 1450 | | { |
| | 1451 | | CheckDisposed(); |
| | 1452 | |
|
| | 1453 | | ArgumentException.ThrowIfNullOrEmpty(request.App); |
| | 1454 | | ArgumentException.ThrowIfNullOrEmpty(request.DeviceId); |
| | 1455 | | ArgumentException.ThrowIfNullOrEmpty(request.DeviceName); |
| | 1456 | | ArgumentException.ThrowIfNullOrEmpty(request.AppVersion); |
| | 1457 | |
|
| | 1458 | | User user = null; |
| | 1459 | | if (!request.UserId.IsEmpty()) |
| | 1460 | | { |
| | 1461 | | user = _userManager.GetUserById(request.UserId); |
| | 1462 | | } |
| | 1463 | |
|
| | 1464 | | user ??= _userManager.GetUserByName(request.Username); |
| | 1465 | |
|
| | 1466 | | if (enforcePassword) |
| | 1467 | | { |
| | 1468 | | user = await _userManager.AuthenticateUser( |
| | 1469 | | request.Username, |
| | 1470 | | request.Password, |
| | 1471 | | request.RemoteEndPoint, |
| | 1472 | | true).ConfigureAwait(false); |
| | 1473 | | } |
| | 1474 | |
|
| | 1475 | | if (user is null) |
| | 1476 | | { |
| | 1477 | | await _eventManager.PublishAsync(new AuthenticationRequestEventArgs(request)).ConfigureAwait(false); |
| | 1478 | | throw new AuthenticationException("Invalid username or password entered."); |
| | 1479 | | } |
| | 1480 | |
|
| | 1481 | | if (!string.IsNullOrEmpty(request.DeviceId) |
| | 1482 | | && !_deviceManager.CanAccessDevice(user, request.DeviceId)) |
| | 1483 | | { |
| | 1484 | | throw new SecurityException("User is not allowed access from this device."); |
| | 1485 | | } |
| | 1486 | |
|
| | 1487 | | int sessionsCount = Sessions.Count(i => i.UserId.Equals(user.Id)); |
| | 1488 | | int maxActiveSessions = user.MaxActiveSessions; |
| | 1489 | | _logger.LogInformation("Current/Max sessions for user {User}: {Sessions}/{Max}", user.Username, sessionsCoun |
| | 1490 | | if (maxActiveSessions >= 1 && sessionsCount >= maxActiveSessions) |
| | 1491 | | { |
| | 1492 | | throw new SecurityException("User is at their maximum number of sessions."); |
| | 1493 | | } |
| | 1494 | |
|
| | 1495 | | var token = await GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.Dev |
| | 1496 | |
|
| | 1497 | | var session = await LogSessionActivity( |
| | 1498 | | request.App, |
| | 1499 | | request.AppVersion, |
| | 1500 | | request.DeviceId, |
| | 1501 | | request.DeviceName, |
| | 1502 | | request.RemoteEndPoint, |
| | 1503 | | user).ConfigureAwait(false); |
| | 1504 | |
|
| | 1505 | | var returnResult = new AuthenticationResult |
| | 1506 | | { |
| | 1507 | | User = _userManager.GetUserDto(user, request.RemoteEndPoint), |
| | 1508 | | SessionInfo = session, |
| | 1509 | | AccessToken = token, |
| | 1510 | | ServerId = _appHost.SystemId |
| | 1511 | | }; |
| | 1512 | |
|
| | 1513 | | await _eventManager.PublishAsync(new AuthenticationResultEventArgs(returnResult)).ConfigureAwait(false); |
| | 1514 | | return returnResult; |
| | 1515 | | } |
| | 1516 | |
|
| | 1517 | | internal async Task<string> GetAuthorizationToken(User user, string deviceId, string app, string appVersion, str |
| | 1518 | | { |
| | 1519 | | // This should be validated above, but if it isn't don't delete all tokens. |
| | 1520 | | ArgumentException.ThrowIfNullOrEmpty(deviceId); |
| | 1521 | |
|
| | 1522 | | var existing = _deviceManager.GetDevices( |
| | 1523 | | new DeviceQuery |
| | 1524 | | { |
| | 1525 | | DeviceId = deviceId, |
| | 1526 | | UserId = user.Id |
| | 1527 | | }).Items; |
| | 1528 | |
|
| | 1529 | | foreach (var auth in existing) |
| | 1530 | | { |
| | 1531 | | try |
| | 1532 | | { |
| | 1533 | | // Logout any existing sessions for the user on this device |
| | 1534 | | await Logout(auth).ConfigureAwait(false); |
| | 1535 | | } |
| | 1536 | | catch (Exception ex) |
| | 1537 | | { |
| | 1538 | | _logger.LogError(ex, "Error while logging out existing session."); |
| | 1539 | | } |
| | 1540 | | } |
| | 1541 | |
|
| | 1542 | | _logger.LogInformation("Creating new access token for user {0}", user.Id); |
| | 1543 | | var device = await _deviceManager.CreateDevice(new Device(user.Id, app, appVersion, deviceName, deviceId)).C |
| | 1544 | |
|
| | 1545 | | return device.AccessToken; |
| | 1546 | | } |
| | 1547 | |
|
| | 1548 | | /// <inheritdoc /> |
| | 1549 | | public async Task Logout(string accessToken) |
| | 1550 | | { |
| | 1551 | | CheckDisposed(); |
| | 1552 | |
|
| | 1553 | | ArgumentException.ThrowIfNullOrEmpty(accessToken); |
| | 1554 | |
|
| | 1555 | | var existing = _deviceManager.GetDevices( |
| | 1556 | | new DeviceQuery |
| | 1557 | | { |
| | 1558 | | Limit = 1, |
| | 1559 | | AccessToken = accessToken |
| | 1560 | | }).Items; |
| | 1561 | |
|
| | 1562 | | if (existing.Count > 0) |
| | 1563 | | { |
| | 1564 | | await Logout(existing[0]).ConfigureAwait(false); |
| | 1565 | | } |
| | 1566 | | } |
| | 1567 | |
|
| | 1568 | | /// <inheritdoc /> |
| | 1569 | | public async Task Logout(Device device) |
| | 1570 | | { |
| | 1571 | | CheckDisposed(); |
| | 1572 | |
|
| | 1573 | | _logger.LogInformation("Logging out access token {0}", device.AccessToken); |
| | 1574 | |
|
| | 1575 | | await _deviceManager.DeleteDevice(device).ConfigureAwait(false); |
| | 1576 | |
|
| | 1577 | | var sessions = Sessions |
| | 1578 | | .Where(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase)) |
| | 1579 | | .ToList(); |
| | 1580 | |
|
| | 1581 | | foreach (var session in sessions) |
| | 1582 | | { |
| | 1583 | | try |
| | 1584 | | { |
| | 1585 | | await ReportSessionEnded(session.Id).ConfigureAwait(false); |
| | 1586 | | } |
| | 1587 | | catch (Exception ex) |
| | 1588 | | { |
| | 1589 | | _logger.LogError(ex, "Error reporting session ended"); |
| | 1590 | | } |
| | 1591 | | } |
| | 1592 | | } |
| | 1593 | |
|
| | 1594 | | /// <inheritdoc /> |
| | 1595 | | public async Task RevokeUserTokens(Guid userId, string currentAccessToken) |
| | 1596 | | { |
| | 1597 | | CheckDisposed(); |
| | 1598 | |
|
| | 1599 | | var existing = _deviceManager.GetDevices(new DeviceQuery |
| | 1600 | | { |
| | 1601 | | UserId = userId |
| | 1602 | | }); |
| | 1603 | |
|
| | 1604 | | foreach (var info in existing.Items) |
| | 1605 | | { |
| | 1606 | | if (!string.Equals(currentAccessToken, info.AccessToken, StringComparison.OrdinalIgnoreCase)) |
| | 1607 | | { |
| | 1608 | | await Logout(info).ConfigureAwait(false); |
| | 1609 | | } |
| | 1610 | | } |
| | 1611 | | } |
| | 1612 | |
|
| | 1613 | | /// <summary> |
| | 1614 | | /// Reports the capabilities. |
| | 1615 | | /// </summary> |
| | 1616 | | /// <param name="sessionId">The session identifier.</param> |
| | 1617 | | /// <param name="capabilities">The capabilities.</param> |
| | 1618 | | public void ReportCapabilities(string sessionId, ClientCapabilities capabilities) |
| | 1619 | | { |
| 0 | 1620 | | CheckDisposed(); |
| | 1621 | |
|
| 0 | 1622 | | var session = GetSession(sessionId); |
| | 1623 | |
|
| 0 | 1624 | | ReportCapabilities(session, capabilities, true); |
| 0 | 1625 | | } |
| | 1626 | |
|
| | 1627 | | private void ReportCapabilities( |
| | 1628 | | SessionInfo session, |
| | 1629 | | ClientCapabilities capabilities, |
| | 1630 | | bool saveCapabilities) |
| | 1631 | | { |
| 16 | 1632 | | session.Capabilities = capabilities; |
| | 1633 | |
|
| 16 | 1634 | | if (saveCapabilities) |
| | 1635 | | { |
| 0 | 1636 | | CapabilitiesChanged?.Invoke( |
| 0 | 1637 | | this, |
| 0 | 1638 | | new SessionEventArgs |
| 0 | 1639 | | { |
| 0 | 1640 | | SessionInfo = session |
| 0 | 1641 | | }); |
| | 1642 | |
|
| 0 | 1643 | | _deviceManager.SaveCapabilities(session.DeviceId, capabilities); |
| | 1644 | | } |
| 16 | 1645 | | } |
| | 1646 | |
|
| | 1647 | | /// <summary> |
| | 1648 | | /// Converts a BaseItem to a BaseItemInfo. |
| | 1649 | | /// </summary> |
| | 1650 | | private BaseItemDto GetItemInfo(BaseItem item, MediaSourceInfo mediaSource) |
| | 1651 | | { |
| 0 | 1652 | | ArgumentNullException.ThrowIfNull(item); |
| | 1653 | |
|
| 0 | 1654 | | var dtoOptions = _itemInfoDtoOptions; |
| | 1655 | |
|
| 0 | 1656 | | if (_itemInfoDtoOptions is null) |
| | 1657 | | { |
| 0 | 1658 | | dtoOptions = new DtoOptions |
| 0 | 1659 | | { |
| 0 | 1660 | | AddProgramRecordingInfo = false |
| 0 | 1661 | | }; |
| | 1662 | |
|
| 0 | 1663 | | var fields = dtoOptions.Fields.ToList(); |
| | 1664 | |
|
| 0 | 1665 | | fields.Remove(ItemFields.CanDelete); |
| 0 | 1666 | | fields.Remove(ItemFields.CanDownload); |
| 0 | 1667 | | fields.Remove(ItemFields.ChildCount); |
| 0 | 1668 | | fields.Remove(ItemFields.CustomRating); |
| 0 | 1669 | | fields.Remove(ItemFields.DateLastMediaAdded); |
| 0 | 1670 | | fields.Remove(ItemFields.DateLastRefreshed); |
| 0 | 1671 | | fields.Remove(ItemFields.DateLastSaved); |
| 0 | 1672 | | fields.Remove(ItemFields.DisplayPreferencesId); |
| 0 | 1673 | | fields.Remove(ItemFields.Etag); |
| 0 | 1674 | | fields.Remove(ItemFields.InheritedParentalRatingValue); |
| 0 | 1675 | | fields.Remove(ItemFields.ItemCounts); |
| 0 | 1676 | | fields.Remove(ItemFields.MediaSourceCount); |
| 0 | 1677 | | fields.Remove(ItemFields.MediaStreams); |
| 0 | 1678 | | fields.Remove(ItemFields.MediaSources); |
| 0 | 1679 | | fields.Remove(ItemFields.People); |
| 0 | 1680 | | fields.Remove(ItemFields.PlayAccess); |
| 0 | 1681 | | fields.Remove(ItemFields.People); |
| 0 | 1682 | | fields.Remove(ItemFields.ProductionLocations); |
| 0 | 1683 | | fields.Remove(ItemFields.RecursiveItemCount); |
| 0 | 1684 | | fields.Remove(ItemFields.RemoteTrailers); |
| 0 | 1685 | | fields.Remove(ItemFields.SeasonUserData); |
| 0 | 1686 | | fields.Remove(ItemFields.Settings); |
| 0 | 1687 | | fields.Remove(ItemFields.SortName); |
| 0 | 1688 | | fields.Remove(ItemFields.Tags); |
| 0 | 1689 | | fields.Remove(ItemFields.ExtraIds); |
| | 1690 | |
|
| 0 | 1691 | | dtoOptions.Fields = fields.ToArray(); |
| | 1692 | |
|
| 0 | 1693 | | _itemInfoDtoOptions = dtoOptions; |
| | 1694 | | } |
| | 1695 | |
|
| 0 | 1696 | | var info = _dtoService.GetBaseItemDto(item, dtoOptions); |
| | 1697 | |
|
| 0 | 1698 | | if (mediaSource is not null) |
| | 1699 | | { |
| 0 | 1700 | | info.MediaStreams = mediaSource.MediaStreams.ToArray(); |
| | 1701 | | } |
| | 1702 | |
|
| 0 | 1703 | | return info; |
| | 1704 | | } |
| | 1705 | |
|
| | 1706 | | private string GetImageCacheTag(User user) |
| | 1707 | | { |
| | 1708 | | try |
| | 1709 | | { |
| 0 | 1710 | | return _imageProcessor.GetImageCacheTag(user); |
| | 1711 | | } |
| 0 | 1712 | | catch (Exception e) |
| | 1713 | | { |
| 0 | 1714 | | _logger.LogError(e, "Error getting image information for profile image"); |
| 0 | 1715 | | return null; |
| | 1716 | | } |
| 0 | 1717 | | } |
| | 1718 | |
|
| | 1719 | | /// <inheritdoc /> |
| | 1720 | | public void ReportNowViewingItem(string sessionId, string itemId) |
| | 1721 | | { |
| 0 | 1722 | | ArgumentException.ThrowIfNullOrEmpty(itemId); |
| | 1723 | |
|
| 0 | 1724 | | var item = _libraryManager.GetItemById(new Guid(itemId)); |
| 0 | 1725 | | var session = GetSession(sessionId); |
| | 1726 | |
|
| 0 | 1727 | | session.NowViewingItem = GetItemInfo(item, null); |
| 0 | 1728 | | } |
| | 1729 | |
|
| | 1730 | | /// <inheritdoc /> |
| | 1731 | | public void ReportTranscodingInfo(string deviceId, TranscodingInfo info) |
| | 1732 | | { |
| 0 | 1733 | | var session = Sessions.FirstOrDefault(i => |
| 0 | 1734 | | string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)); |
| | 1735 | |
|
| 0 | 1736 | | if (session is not null) |
| | 1737 | | { |
| 0 | 1738 | | session.TranscodingInfo = info; |
| | 1739 | | } |
| 0 | 1740 | | } |
| | 1741 | |
|
| | 1742 | | /// <inheritdoc /> |
| | 1743 | | public void ClearTranscodingInfo(string deviceId) |
| | 1744 | | { |
| 0 | 1745 | | ReportTranscodingInfo(deviceId, null); |
| 0 | 1746 | | } |
| | 1747 | |
|
| | 1748 | | /// <inheritdoc /> |
| | 1749 | | public SessionInfo GetSession(string deviceId, string client, string version) |
| | 1750 | | { |
| 0 | 1751 | | return Sessions.FirstOrDefault(i => |
| 0 | 1752 | | string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase) |
| 0 | 1753 | | && string.Equals(i.Client, client, StringComparison.OrdinalIgnoreCase)); |
| | 1754 | | } |
| | 1755 | |
|
| | 1756 | | /// <inheritdoc /> |
| | 1757 | | public Task<SessionInfo> GetSessionByAuthenticationToken(Device info, string deviceId, string remoteEndpoint, st |
| | 1758 | | { |
| 0 | 1759 | | ArgumentNullException.ThrowIfNull(info); |
| | 1760 | |
|
| 0 | 1761 | | var user = info.UserId.IsEmpty() |
| 0 | 1762 | | ? null |
| 0 | 1763 | | : _userManager.GetUserById(info.UserId); |
| | 1764 | |
|
| 0 | 1765 | | appVersion = string.IsNullOrEmpty(appVersion) |
| 0 | 1766 | | ? info.AppVersion |
| 0 | 1767 | | : appVersion; |
| | 1768 | |
|
| 0 | 1769 | | var deviceName = info.DeviceName; |
| 0 | 1770 | | var appName = info.AppName; |
| | 1771 | |
|
| 0 | 1772 | | if (string.IsNullOrEmpty(deviceId)) |
| | 1773 | | { |
| 0 | 1774 | | deviceId = info.DeviceId; |
| | 1775 | | } |
| | 1776 | |
|
| | 1777 | | // Prevent argument exception |
| 0 | 1778 | | if (string.IsNullOrEmpty(appVersion)) |
| | 1779 | | { |
| 0 | 1780 | | appVersion = "1"; |
| | 1781 | | } |
| | 1782 | |
|
| 0 | 1783 | | return LogSessionActivity(appName, appVersion, deviceId, deviceName, remoteEndpoint, user); |
| | 1784 | | } |
| | 1785 | |
|
| | 1786 | | /// <inheritdoc /> |
| | 1787 | | public async Task<SessionInfo> GetSessionByAuthenticationToken(string token, string deviceId, string remoteEndpo |
| | 1788 | | { |
| | 1789 | | var items = _deviceManager.GetDevices(new DeviceQuery |
| | 1790 | | { |
| | 1791 | | AccessToken = token, |
| | 1792 | | Limit = 1 |
| | 1793 | | }).Items; |
| | 1794 | |
|
| | 1795 | | if (items.Count == 0) |
| | 1796 | | { |
| | 1797 | | return null; |
| | 1798 | | } |
| | 1799 | |
|
| | 1800 | | return await GetSessionByAuthenticationToken(items[0], deviceId, remoteEndpoint, null).ConfigureAwait(false) |
| | 1801 | | } |
| | 1802 | |
|
| | 1803 | | /// <inheritdoc /> |
| | 1804 | | public Task SendMessageToAdminSessions<T>(SessionMessageType name, T data, CancellationToken cancellationToken) |
| | 1805 | | { |
| 0 | 1806 | | CheckDisposed(); |
| | 1807 | |
|
| 0 | 1808 | | var adminUserIds = _userManager.Users |
| 0 | 1809 | | .Where(i => i.HasPermission(PermissionKind.IsAdministrator)) |
| 0 | 1810 | | .Select(i => i.Id) |
| 0 | 1811 | | .ToList(); |
| | 1812 | |
|
| 0 | 1813 | | return SendMessageToUserSessions(adminUserIds, name, data, cancellationToken); |
| | 1814 | | } |
| | 1815 | |
|
| | 1816 | | /// <inheritdoc /> |
| | 1817 | | public Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, Func<T> dataFn, Cancellati |
| | 1818 | | { |
| 0 | 1819 | | CheckDisposed(); |
| | 1820 | |
|
| 0 | 1821 | | var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)).ToList(); |
| | 1822 | |
|
| 0 | 1823 | | if (sessions.Count == 0) |
| | 1824 | | { |
| 0 | 1825 | | return Task.CompletedTask; |
| | 1826 | | } |
| | 1827 | |
|
| 0 | 1828 | | return SendMessageToSessions(sessions, name, dataFn(), cancellationToken); |
| | 1829 | | } |
| | 1830 | |
|
| | 1831 | | /// <inheritdoc /> |
| | 1832 | | public Task SendMessageToUserSessions<T>(List<Guid> userIds, SessionMessageType name, T data, CancellationToken |
| | 1833 | | { |
| 0 | 1834 | | CheckDisposed(); |
| | 1835 | |
|
| 0 | 1836 | | var sessions = Sessions.Where(i => userIds.Any(i.ContainsUser)); |
| 0 | 1837 | | return SendMessageToSessions(sessions, name, data, cancellationToken); |
| | 1838 | | } |
| | 1839 | |
|
| | 1840 | | /// <inheritdoc /> |
| | 1841 | | public Task SendMessageToUserDeviceSessions<T>(string deviceId, SessionMessageType name, T data, CancellationTok |
| | 1842 | | { |
| 0 | 1843 | | CheckDisposed(); |
| | 1844 | |
|
| 0 | 1845 | | var sessions = Sessions.Where(i => string.Equals(i.DeviceId, deviceId, StringComparison.OrdinalIgnoreCase)); |
| | 1846 | |
|
| 0 | 1847 | | return SendMessageToSessions(sessions, name, data, cancellationToken); |
| | 1848 | | } |
| | 1849 | |
|
| | 1850 | | /// <inheritdoc /> |
| | 1851 | | public async ValueTask DisposeAsync() |
| | 1852 | | { |
| | 1853 | | if (_disposed) |
| | 1854 | | { |
| | 1855 | | return; |
| | 1856 | | } |
| | 1857 | |
|
| | 1858 | | foreach (var session in _activeConnections.Values) |
| | 1859 | | { |
| | 1860 | | await session.DisposeAsync().ConfigureAwait(false); |
| | 1861 | | } |
| | 1862 | |
|
| | 1863 | | if (_idleTimer is not null) |
| | 1864 | | { |
| | 1865 | | await _idleTimer.DisposeAsync().ConfigureAwait(false); |
| | 1866 | | _idleTimer = null; |
| | 1867 | | } |
| | 1868 | |
|
| | 1869 | | if (_inactiveTimer is not null) |
| | 1870 | | { |
| | 1871 | | await _inactiveTimer.DisposeAsync().ConfigureAwait(false); |
| | 1872 | | _inactiveTimer = null; |
| | 1873 | | } |
| | 1874 | |
|
| | 1875 | | await _shutdownCallback.DisposeAsync().ConfigureAwait(false); |
| | 1876 | |
|
| | 1877 | | _deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated; |
| | 1878 | | _disposed = true; |
| | 1879 | | } |
| | 1880 | |
|
| | 1881 | | private async void OnApplicationStopping() |
| | 1882 | | { |
| | 1883 | | _logger.LogInformation("Sending shutdown notifications"); |
| | 1884 | | try |
| | 1885 | | { |
| | 1886 | | var messageType = _appHost.ShouldRestart ? SessionMessageType.ServerRestarting : SessionMessageType.Serv |
| | 1887 | |
|
| | 1888 | | await SendMessageToSessions(Sessions, messageType, string.Empty, CancellationToken.None).ConfigureAwait( |
| | 1889 | | } |
| | 1890 | | catch (Exception ex) |
| | 1891 | | { |
| | 1892 | | _logger.LogError(ex, "Error sending server shutdown notifications"); |
| | 1893 | | } |
| | 1894 | |
|
| | 1895 | | // Close open websockets to allow Kestrel to shut down cleanly |
| | 1896 | | foreach (var session in _activeConnections.Values) |
| | 1897 | | { |
| | 1898 | | await session.DisposeAsync().ConfigureAwait(false); |
| | 1899 | | } |
| | 1900 | |
|
| | 1901 | | _activeConnections.Clear(); |
| | 1902 | | } |
| | 1903 | | } |
| | 1904 | | } |