DeviceManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 Jellyfin.Data.Queries;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Controller.Devices;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Devices;
  14. using MediaBrowser.Model.Querying;
  15. using MediaBrowser.Model.Session;
  16. using Microsoft.EntityFrameworkCore;
  17. namespace Jellyfin.Server.Implementations.Devices
  18. {
  19. /// <summary>
  20. /// Manages the creation, updating, and retrieval of devices.
  21. /// </summary>
  22. public class DeviceManager : IDeviceManager
  23. {
  24. private readonly JellyfinDbProvider _dbProvider;
  25. private readonly IUserManager _userManager;
  26. private readonly ConcurrentDictionary<string, ClientCapabilities> _capabilitiesMap = new();
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="DeviceManager"/> class.
  29. /// </summary>
  30. /// <param name="dbProvider">The database provider.</param>
  31. /// <param name="userManager">The user manager.</param>
  32. public DeviceManager(JellyfinDbProvider dbProvider, IUserManager userManager)
  33. {
  34. _dbProvider = dbProvider;
  35. _userManager = userManager;
  36. }
  37. /// <inheritdoc />
  38. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>>? DeviceOptionsUpdated;
  39. /// <inheritdoc />
  40. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  41. {
  42. _capabilitiesMap[deviceId] = capabilities;
  43. }
  44. /// <inheritdoc />
  45. public async Task UpdateDeviceOptions(string deviceId, string deviceName)
  46. {
  47. await using var dbContext = _dbProvider.CreateContext();
  48. var deviceOptions = await dbContext.DeviceOptions.AsQueryable().FirstOrDefaultAsync(dev => dev.DeviceId == deviceId).ConfigureAwait(false);
  49. if (deviceOptions == null)
  50. {
  51. deviceOptions = new DeviceOptions(deviceId);
  52. dbContext.DeviceOptions.Add(deviceOptions);
  53. }
  54. deviceOptions.CustomName = deviceName;
  55. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  56. DeviceOptionsUpdated?.Invoke(this, new GenericEventArgs<Tuple<string, DeviceOptions>>(new Tuple<string, DeviceOptions>(deviceId, deviceOptions)));
  57. }
  58. /// <inheritdoc />
  59. public async Task<Device> CreateDevice(Device device)
  60. {
  61. await using var dbContext = _dbProvider.CreateContext();
  62. dbContext.Devices.Add(device);
  63. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  64. return device;
  65. }
  66. /// <inheritdoc />
  67. public async Task<DeviceOptions> GetDeviceOptions(string deviceId)
  68. {
  69. await using var dbContext = _dbProvider.CreateContext();
  70. var deviceOptions = await dbContext.DeviceOptions
  71. .AsQueryable()
  72. .FirstOrDefaultAsync(d => d.DeviceId == deviceId)
  73. .ConfigureAwait(false);
  74. return deviceOptions ?? new DeviceOptions(deviceId);
  75. }
  76. /// <inheritdoc />
  77. public ClientCapabilities GetCapabilities(string deviceId)
  78. {
  79. return _capabilitiesMap.TryGetValue(deviceId, out ClientCapabilities? result)
  80. ? result
  81. : new ClientCapabilities();
  82. }
  83. /// <inheritdoc />
  84. public async Task<DeviceInfo?> GetDevice(string id)
  85. {
  86. await using var dbContext = _dbProvider.CreateContext();
  87. var device = await dbContext.Devices
  88. .AsQueryable()
  89. .Where(d => d.DeviceId == id)
  90. .OrderByDescending(d => d.DateLastActivity)
  91. .Include(d => d.User)
  92. .FirstOrDefaultAsync()
  93. .ConfigureAwait(false);
  94. var deviceInfo = device == null ? null : ToDeviceInfo(device);
  95. return deviceInfo;
  96. }
  97. /// <inheritdoc />
  98. public async Task<QueryResult<Device>> GetDevices(DeviceQuery query)
  99. {
  100. await using var dbContext = _dbProvider.CreateContext();
  101. var devices = dbContext.Devices.AsQueryable();
  102. if (query.UserId.HasValue)
  103. {
  104. devices = devices.Where(device => device.UserId.Equals(query.UserId.Value));
  105. }
  106. if (query.DeviceId != null)
  107. {
  108. devices = devices.Where(device => device.DeviceId == query.DeviceId);
  109. }
  110. if (query.AccessToken != null)
  111. {
  112. devices = devices.Where(device => device.AccessToken == query.AccessToken);
  113. }
  114. var count = await devices.CountAsync().ConfigureAwait(false);
  115. if (query.Skip.HasValue)
  116. {
  117. devices = devices.Skip(query.Skip.Value);
  118. }
  119. if (query.Limit.HasValue)
  120. {
  121. devices = devices.Take(query.Limit.Value);
  122. }
  123. return new QueryResult<Device>(
  124. query.Skip,
  125. count,
  126. await devices.ToListAsync().ConfigureAwait(false));
  127. }
  128. /// <inheritdoc />
  129. public async Task<QueryResult<DeviceInfo>> GetDeviceInfos(DeviceQuery query)
  130. {
  131. var devices = await GetDevices(query).ConfigureAwait(false);
  132. return new QueryResult<DeviceInfo>(
  133. devices.StartIndex,
  134. devices.TotalRecordCount,
  135. devices.Items.Select(device => ToDeviceInfo(device)).ToList());
  136. }
  137. /// <inheritdoc />
  138. public async Task<QueryResult<DeviceInfo>> GetDevicesForUser(Guid? userId, bool? supportsSync)
  139. {
  140. await using var dbContext = _dbProvider.CreateContext();
  141. var sessions = dbContext.Devices
  142. .Include(d => d.User)
  143. .AsQueryable()
  144. .OrderByDescending(d => d.DateLastActivity)
  145. .ThenBy(d => d.DeviceId)
  146. .AsAsyncEnumerable();
  147. if (supportsSync.HasValue)
  148. {
  149. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == supportsSync.Value);
  150. }
  151. if (userId.HasValue)
  152. {
  153. var user = _userManager.GetUserById(userId.Value);
  154. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  155. }
  156. var array = await sessions.Select(device => ToDeviceInfo(device)).ToArrayAsync().ConfigureAwait(false);
  157. return new QueryResult<DeviceInfo>(array);
  158. }
  159. /// <inheritdoc />
  160. public async Task DeleteDevice(Device device)
  161. {
  162. await using var dbContext = _dbProvider.CreateContext();
  163. dbContext.Devices.Remove(device);
  164. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  165. }
  166. /// <inheritdoc />
  167. public bool CanAccessDevice(User user, string deviceId)
  168. {
  169. if (user == null)
  170. {
  171. throw new ArgumentNullException(nameof(user));
  172. }
  173. if (string.IsNullOrEmpty(deviceId))
  174. {
  175. throw new ArgumentNullException(nameof(deviceId));
  176. }
  177. if (user.HasPermission(PermissionKind.EnableAllDevices) || user.HasPermission(PermissionKind.IsAdministrator))
  178. {
  179. return true;
  180. }
  181. return user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparison.OrdinalIgnoreCase)
  182. || !GetCapabilities(deviceId).SupportsPersistentIdentifier;
  183. }
  184. private DeviceInfo ToDeviceInfo(Device authInfo)
  185. {
  186. var caps = GetCapabilities(authInfo.DeviceId);
  187. return new DeviceInfo
  188. {
  189. AppName = authInfo.AppName,
  190. AppVersion = authInfo.AppVersion,
  191. Id = authInfo.DeviceId,
  192. LastUserId = authInfo.UserId,
  193. LastUserName = authInfo.User.Username,
  194. Name = authInfo.DeviceName,
  195. DateLastActivity = authInfo.DateLastActivity,
  196. IconUrl = caps.IconUrl
  197. };
  198. }
  199. }
  200. }