DeviceManager.cs 11 KB

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