2
0

DeviceManager.cs 11 KB

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