DeviceManager.cs 11 KB

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