DeviceManager.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Data.Entities;
  7. using Jellyfin.Data.Entities.Security;
  8. using Jellyfin.Data.Enums;
  9. using Jellyfin.Data.Events;
  10. using Jellyfin.Data.Queries;
  11. using Jellyfin.Extensions;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Controller.Devices;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Model.Devices;
  16. using MediaBrowser.Model.Querying;
  17. using MediaBrowser.Model.Session;
  18. using Microsoft.EntityFrameworkCore;
  19. namespace Jellyfin.Server.Implementations.Devices
  20. {
  21. /// <summary>
  22. /// Manages the creation, updating, and retrieval of devices.
  23. /// </summary>
  24. public class DeviceManager : IDeviceManager
  25. {
  26. private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
  27. private readonly IUserManager _userManager;
  28. private readonly ConcurrentDictionary<string, ClientCapabilities> _capabilitiesMap = new();
  29. private readonly ConcurrentDictionary<int, Device> _devices;
  30. private readonly ConcurrentDictionary<string, DeviceOptions> _deviceOptions;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="DeviceManager"/> class.
  33. /// </summary>
  34. /// <param name="dbProvider">The database provider.</param>
  35. /// <param name="userManager">The user manager.</param>
  36. public DeviceManager(IDbContextFactory<JellyfinDbContext> dbProvider, IUserManager userManager)
  37. {
  38. _dbProvider = dbProvider;
  39. _userManager = userManager;
  40. _devices = new ConcurrentDictionary<int, Device>();
  41. _deviceOptions = new ConcurrentDictionary<string, DeviceOptions>();
  42. using var dbContext = _dbProvider.CreateDbContext();
  43. foreach (var device in dbContext.Devices
  44. .OrderBy(d => d.Id)
  45. .AsEnumerable())
  46. {
  47. _devices.TryAdd(device.Id, device);
  48. }
  49. foreach (var deviceOption in dbContext.DeviceOptions
  50. .OrderBy(d => d.Id)
  51. .AsEnumerable())
  52. {
  53. _deviceOptions.TryAdd(deviceOption.DeviceId, deviceOption);
  54. }
  55. }
  56. /// <inheritdoc />
  57. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>>? DeviceOptionsUpdated;
  58. /// <inheritdoc />
  59. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  60. {
  61. _capabilitiesMap[deviceId] = capabilities;
  62. }
  63. /// <inheritdoc />
  64. public async Task UpdateDeviceOptions(string deviceId, string deviceName)
  65. {
  66. DeviceOptions? deviceOptions;
  67. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  68. await using (dbContext.ConfigureAwait(false))
  69. {
  70. deviceOptions = await dbContext.DeviceOptions.FirstOrDefaultAsync(dev => dev.DeviceId == deviceId).ConfigureAwait(false);
  71. if (deviceOptions is null)
  72. {
  73. deviceOptions = new DeviceOptions(deviceId);
  74. dbContext.DeviceOptions.Add(deviceOptions);
  75. }
  76. deviceOptions.CustomName = deviceName;
  77. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  78. }
  79. _deviceOptions[deviceId] = deviceOptions;
  80. DeviceOptionsUpdated?.Invoke(this, new GenericEventArgs<Tuple<string, DeviceOptions>>(new Tuple<string, DeviceOptions>(deviceId, deviceOptions)));
  81. }
  82. /// <inheritdoc />
  83. public async Task<Device> CreateDevice(Device device)
  84. {
  85. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  86. await using (dbContext.ConfigureAwait(false))
  87. {
  88. dbContext.Devices.Add(device);
  89. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  90. _devices.TryAdd(device.Id, device);
  91. }
  92. return device;
  93. }
  94. /// <inheritdoc />
  95. public DeviceOptions GetDeviceOptions(string deviceId)
  96. {
  97. _deviceOptions.TryGetValue(deviceId, out var deviceOptions);
  98. return deviceOptions ?? new DeviceOptions(deviceId);
  99. }
  100. /// <inheritdoc />
  101. public ClientCapabilities GetCapabilities(string deviceId)
  102. {
  103. return _capabilitiesMap.TryGetValue(deviceId, out ClientCapabilities? result)
  104. ? result
  105. : new ClientCapabilities();
  106. }
  107. /// <inheritdoc />
  108. public DeviceInfo? GetDevice(string id)
  109. {
  110. var device = _devices.Values.Where(d => d.DeviceId == id).OrderByDescending(d => d.DateLastActivity).FirstOrDefault();
  111. _deviceOptions.TryGetValue(id, out var deviceOption);
  112. var deviceInfo = device is null ? null : ToDeviceInfo(device, deviceOption);
  113. return deviceInfo;
  114. }
  115. /// <inheritdoc />
  116. public QueryResult<Device> GetDevices(DeviceQuery query)
  117. {
  118. IEnumerable<Device> devices = _devices.Values
  119. .Where(device => !query.UserId.HasValue || device.UserId.Equals(query.UserId.Value))
  120. .Where(device => query.DeviceId == null || device.DeviceId == query.DeviceId)
  121. .Where(device => query.AccessToken == null || device.AccessToken == query.AccessToken)
  122. .OrderBy(d => d.Id)
  123. .ToList();
  124. var count = devices.Count();
  125. if (query.Skip.HasValue)
  126. {
  127. devices = devices.Skip(query.Skip.Value);
  128. }
  129. if (query.Limit.HasValue)
  130. {
  131. devices = devices.Take(query.Limit.Value);
  132. }
  133. return new QueryResult<Device>(query.Skip, count, devices.ToList());
  134. }
  135. /// <inheritdoc />
  136. public QueryResult<DeviceInfo> GetDeviceInfos(DeviceQuery query)
  137. {
  138. var devices = GetDevices(query);
  139. return new QueryResult<DeviceInfo>(
  140. devices.StartIndex,
  141. devices.TotalRecordCount,
  142. devices.Items.Select(device => ToDeviceInfo(device)).ToList());
  143. }
  144. /// <inheritdoc />
  145. public QueryResult<DeviceInfo> GetDevicesForUser(Guid? userId)
  146. {
  147. IEnumerable<Device> devices = _devices.Values
  148. .OrderByDescending(d => d.DateLastActivity)
  149. .ThenBy(d => d.DeviceId);
  150. if (!userId.IsNullOrEmpty())
  151. {
  152. var user = _userManager.GetUserById(userId.Value);
  153. if (user is null)
  154. {
  155. throw new ResourceNotFoundException();
  156. }
  157. devices = devices.Where(i => CanAccessDevice(user, i.DeviceId));
  158. }
  159. var array = devices.Select(device =>
  160. {
  161. _deviceOptions.TryGetValue(device.DeviceId, out var option);
  162. return ToDeviceInfo(device, option);
  163. }).ToArray();
  164. return new QueryResult<DeviceInfo>(array);
  165. }
  166. /// <inheritdoc />
  167. public async Task DeleteDevice(Device device)
  168. {
  169. _devices.TryRemove(device.Id, out _);
  170. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  171. await using (dbContext.ConfigureAwait(false))
  172. {
  173. dbContext.Devices.Remove(device);
  174. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  175. }
  176. }
  177. /// <inheritdoc />
  178. public async Task UpdateDevice(Device device)
  179. {
  180. var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false);
  181. await using (dbContext.ConfigureAwait(false))
  182. {
  183. dbContext.Devices.Update(device);
  184. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  185. }
  186. _devices[device.Id] = device;
  187. }
  188. /// <inheritdoc />
  189. public bool CanAccessDevice(User user, string deviceId)
  190. {
  191. ArgumentNullException.ThrowIfNull(user);
  192. ArgumentException.ThrowIfNullOrEmpty(deviceId);
  193. if (user.HasPermission(PermissionKind.EnableAllDevices) || user.HasPermission(PermissionKind.IsAdministrator))
  194. {
  195. return true;
  196. }
  197. return user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparison.OrdinalIgnoreCase)
  198. || !GetCapabilities(deviceId).SupportsPersistentIdentifier;
  199. }
  200. private DeviceInfo ToDeviceInfo(Device authInfo, DeviceOptions? options = null)
  201. {
  202. var caps = GetCapabilities(authInfo.DeviceId);
  203. var user = _userManager.GetUserById(authInfo.UserId);
  204. if (user is null)
  205. {
  206. throw new ResourceNotFoundException("User with UserId " + authInfo.UserId + " not found");
  207. }
  208. return new DeviceInfo
  209. {
  210. AppName = authInfo.AppName,
  211. AppVersion = authInfo.AppVersion,
  212. Id = authInfo.DeviceId,
  213. LastUserId = authInfo.UserId,
  214. LastUserName = user.Username,
  215. Name = authInfo.DeviceName,
  216. DateLastActivity = authInfo.DateLastActivity,
  217. IconUrl = caps.IconUrl,
  218. CustomName = options?.CustomName,
  219. };
  220. }
  221. }
  222. }