DeviceManager.cs 9.0 KB

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