DeviceManager.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Jellyfin.Data.Entities;
  6. using Jellyfin.Data.Entities.Security;
  7. using Jellyfin.Data.Enums;
  8. using Jellyfin.Data.Events;
  9. using MediaBrowser.Controller.Devices;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Model.Devices;
  12. using MediaBrowser.Model.Querying;
  13. using MediaBrowser.Model.Session;
  14. using Microsoft.EntityFrameworkCore;
  15. namespace Jellyfin.Server.Implementations.Devices
  16. {
  17. /// <summary>
  18. /// Manages the creation, updating, and retrieval of devices.
  19. /// </summary>
  20. public class DeviceManager : IDeviceManager
  21. {
  22. private readonly JellyfinDbProvider _dbProvider;
  23. private readonly IUserManager _userManager;
  24. private readonly ConcurrentDictionary<string, ClientCapabilities> _capabilitiesMap = new ();
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="DeviceManager"/> class.
  27. /// </summary>
  28. /// <param name="dbProvider">The database provider.</param>
  29. /// <param name="userManager">The user manager.</param>
  30. public DeviceManager(JellyfinDbProvider dbProvider, IUserManager userManager)
  31. {
  32. _dbProvider = dbProvider;
  33. _userManager = userManager;
  34. }
  35. /// <inheritdoc />
  36. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>>? DeviceOptionsUpdated;
  37. /// <inheritdoc />
  38. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  39. {
  40. _capabilitiesMap[deviceId] = capabilities;
  41. }
  42. /// <inheritdoc />
  43. public async Task UpdateDeviceOptions(string deviceId, DeviceOptions options)
  44. {
  45. await using var dbContext = _dbProvider.CreateContext();
  46. await dbContext.Database
  47. .ExecuteSqlRawAsync($"UPDATE [DeviceOptions] SET [CustomName] = ${options.CustomName}")
  48. .ConfigureAwait(false);
  49. DeviceOptionsUpdated?.Invoke(this, new GenericEventArgs<Tuple<string, DeviceOptions>>(new Tuple<string, DeviceOptions>(deviceId, options)));
  50. }
  51. /// <inheritdoc />
  52. public async Task<DeviceOptions?> GetDeviceOptions(string deviceId)
  53. {
  54. await using var dbContext = _dbProvider.CreateContext();
  55. return await dbContext.DeviceOptions
  56. .AsQueryable()
  57. .FirstOrDefaultAsync(d => d.DeviceId == deviceId)
  58. .ConfigureAwait(false);
  59. }
  60. /// <inheritdoc />
  61. public ClientCapabilities GetCapabilities(string deviceId)
  62. {
  63. return _capabilitiesMap.TryGetValue(deviceId, out ClientCapabilities? result)
  64. ? result
  65. : new ClientCapabilities();
  66. }
  67. /// <inheritdoc />
  68. public async Task<DeviceInfo?> GetDevice(string id)
  69. {
  70. await using var dbContext = _dbProvider.CreateContext();
  71. var device = await dbContext.Devices
  72. .AsQueryable()
  73. .Where(d => d.DeviceId == id)
  74. .OrderByDescending(d => d.DateLastActivity)
  75. .Include(d => d.User)
  76. .FirstOrDefaultAsync()
  77. .ConfigureAwait(false);
  78. var deviceInfo = device == null ? null : ToDeviceInfo(device);
  79. return deviceInfo;
  80. }
  81. /// <inheritdoc />
  82. public async Task<QueryResult<DeviceInfo>> GetDevicesForUser(Guid? userId, bool? supportsSync)
  83. {
  84. await using var dbContext = _dbProvider.CreateContext();
  85. var sessions = dbContext.Devices
  86. .AsQueryable()
  87. .OrderBy(d => d.DeviceId)
  88. .ThenByDescending(d => d.DateLastActivity)
  89. .AsAsyncEnumerable();
  90. if (supportsSync.HasValue)
  91. {
  92. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == supportsSync.Value);
  93. }
  94. if (userId.HasValue)
  95. {
  96. var user = _userManager.GetUserById(userId.Value);
  97. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  98. }
  99. var array = await sessions.Select(ToDeviceInfo).ToArrayAsync().ConfigureAwait(false);
  100. return new QueryResult<DeviceInfo>(array);
  101. }
  102. /// <inheritdoc />
  103. public bool CanAccessDevice(User user, string deviceId)
  104. {
  105. if (user == null)
  106. {
  107. throw new ArgumentException("user not found");
  108. }
  109. if (string.IsNullOrEmpty(deviceId))
  110. {
  111. throw new ArgumentNullException(nameof(deviceId));
  112. }
  113. if (user.HasPermission(PermissionKind.EnableAllDevices) || user.HasPermission(PermissionKind.IsAdministrator))
  114. {
  115. return true;
  116. }
  117. return user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparer.OrdinalIgnoreCase)
  118. || !GetCapabilities(deviceId).SupportsPersistentIdentifier;
  119. }
  120. private DeviceInfo ToDeviceInfo(Device authInfo)
  121. {
  122. var caps = GetCapabilities(authInfo.DeviceId);
  123. return new DeviceInfo
  124. {
  125. AppName = authInfo.AppName,
  126. AppVersion = authInfo.AppVersion,
  127. Id = authInfo.DeviceId,
  128. LastUserId = authInfo.UserId,
  129. LastUserName = authInfo.User.Username,
  130. Name = authInfo.DeviceName,
  131. DateLastActivity = authInfo.DateLastActivity,
  132. IconUrl = caps.IconUrl
  133. };
  134. }
  135. }
  136. }