DeviceManager.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 == 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. {
  125. Items = await devices.ToListAsync().ConfigureAwait(false),
  126. StartIndex = query.Skip ?? 0,
  127. TotalRecordCount = count
  128. };
  129. }
  130. /// <inheritdoc />
  131. public async Task<QueryResult<DeviceInfo>> GetDeviceInfos(DeviceQuery query)
  132. {
  133. var devices = await GetDevices(query).ConfigureAwait(false);
  134. return new QueryResult<DeviceInfo>
  135. {
  136. Items = devices.Items.Select(device => ToDeviceInfo(device)).ToList(),
  137. StartIndex = devices.StartIndex,
  138. TotalRecordCount = devices.TotalRecordCount
  139. };
  140. }
  141. /// <inheritdoc />
  142. public async Task<QueryResult<DeviceInfo>> GetDevicesForUser(Guid? userId, bool? supportsSync)
  143. {
  144. await using var dbContext = _dbProvider.CreateContext();
  145. var sessions = dbContext.Devices
  146. .Include(d => d.User)
  147. .AsQueryable()
  148. .OrderBy(d => d.DeviceId)
  149. .ThenByDescending(d => d.DateLastActivity)
  150. .AsAsyncEnumerable();
  151. if (supportsSync.HasValue)
  152. {
  153. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == supportsSync.Value);
  154. }
  155. if (userId.HasValue)
  156. {
  157. var user = _userManager.GetUserById(userId.Value);
  158. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  159. }
  160. var array = await sessions.Select(device => ToDeviceInfo(device)).ToArrayAsync().ConfigureAwait(false);
  161. return new QueryResult<DeviceInfo>(array);
  162. }
  163. /// <inheritdoc />
  164. public async Task DeleteDevice(Device device)
  165. {
  166. await using var dbContext = _dbProvider.CreateContext();
  167. dbContext.Devices.Remove(device);
  168. await dbContext.SaveChangesAsync().ConfigureAwait(false);
  169. }
  170. /// <inheritdoc />
  171. public bool CanAccessDevice(User user, string deviceId)
  172. {
  173. if (user == null)
  174. {
  175. throw new ArgumentNullException(nameof(user));
  176. }
  177. if (string.IsNullOrEmpty(deviceId))
  178. {
  179. throw new ArgumentNullException(nameof(deviceId));
  180. }
  181. if (user.HasPermission(PermissionKind.EnableAllDevices) || user.HasPermission(PermissionKind.IsAdministrator))
  182. {
  183. return true;
  184. }
  185. return user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparison.OrdinalIgnoreCase)
  186. || !GetCapabilities(deviceId).SupportsPersistentIdentifier;
  187. }
  188. private DeviceInfo ToDeviceInfo(Device authInfo)
  189. {
  190. var caps = GetCapabilities(authInfo.DeviceId);
  191. return new DeviceInfo
  192. {
  193. AppName = authInfo.AppName,
  194. AppVersion = authInfo.AppVersion,
  195. Id = authInfo.DeviceId,
  196. LastUserId = authInfo.UserId,
  197. LastUserName = authInfo.User.Username,
  198. Name = authInfo.DeviceName,
  199. DateLastActivity = authInfo.DateLastActivity,
  200. IconUrl = caps.IconUrl
  201. };
  202. }
  203. }
  204. }