DeviceManager.cs 8.4 KB

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