DeviceManager.cs 9.2 KB

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