DeviceManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Devices;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Controller.Security;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Devices;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Events;
  20. using MediaBrowser.Model.Globalization;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.Querying;
  23. using MediaBrowser.Model.Serialization;
  24. using MediaBrowser.Model.Session;
  25. using MediaBrowser.Model.Users;
  26. using Microsoft.Extensions.Logging;
  27. namespace Emby.Server.Implementations.Devices
  28. {
  29. public class DeviceManager : IDeviceManager
  30. {
  31. private readonly IJsonSerializer _json;
  32. private readonly IUserManager _userManager;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly IServerConfigurationManager _config;
  35. private readonly ILibraryManager _libraryManager;
  36. private readonly ILocalizationManager _localizationManager;
  37. private readonly IAuthenticationRepository _authRepo;
  38. private readonly Dictionary<string, ClientCapabilities> _capabilitiesCache;
  39. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
  40. private readonly object _capabilitiesSyncLock = new object();
  41. public DeviceManager(
  42. IAuthenticationRepository authRepo,
  43. IJsonSerializer json,
  44. ILibraryManager libraryManager,
  45. ILocalizationManager localizationManager,
  46. IUserManager userManager,
  47. IFileSystem fileSystem,
  48. IServerConfigurationManager config)
  49. {
  50. _json = json;
  51. _userManager = userManager;
  52. _fileSystem = fileSystem;
  53. _config = config;
  54. _libraryManager = libraryManager;
  55. _localizationManager = localizationManager;
  56. _authRepo = authRepo;
  57. _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
  58. }
  59. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  60. {
  61. var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
  62. Directory.CreateDirectory(Path.GetDirectoryName(path));
  63. lock (_capabilitiesSyncLock)
  64. {
  65. _capabilitiesCache[deviceId] = capabilities;
  66. _json.SerializeToFile(capabilities, path);
  67. }
  68. }
  69. public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
  70. {
  71. _authRepo.UpdateDeviceOptions(deviceId, options);
  72. if (DeviceOptionsUpdated != null)
  73. {
  74. DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
  75. {
  76. Argument = new Tuple<string, DeviceOptions>(deviceId, options)
  77. });
  78. }
  79. }
  80. public DeviceOptions GetDeviceOptions(string deviceId)
  81. {
  82. return _authRepo.GetDeviceOptions(deviceId);
  83. }
  84. public ClientCapabilities GetCapabilities(string id)
  85. {
  86. lock (_capabilitiesSyncLock)
  87. {
  88. if (_capabilitiesCache.TryGetValue(id, out var result))
  89. {
  90. return result;
  91. }
  92. var path = Path.Combine(GetDevicePath(id), "capabilities.json");
  93. try
  94. {
  95. return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
  96. }
  97. catch
  98. {
  99. }
  100. }
  101. return new ClientCapabilities();
  102. }
  103. public DeviceInfo GetDevice(string id)
  104. {
  105. return GetDevice(id, true);
  106. }
  107. private DeviceInfo GetDevice(string id, bool includeCapabilities)
  108. {
  109. var session = _authRepo.Get(new AuthenticationInfoQuery
  110. {
  111. DeviceId = id
  112. }).Items.FirstOrDefault();
  113. var device = session == null ? null : ToDeviceInfo(session);
  114. return device;
  115. }
  116. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  117. {
  118. IEnumerable<AuthenticationInfo> sessions = _authRepo.Get(new AuthenticationInfoQuery
  119. {
  120. //UserId = query.UserId
  121. HasUser = true
  122. }).Items;
  123. // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
  124. if (query.SupportsSync.HasValue)
  125. {
  126. var val = query.SupportsSync.Value;
  127. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val);
  128. }
  129. if (!query.UserId.Equals(Guid.Empty))
  130. {
  131. var user = _userManager.GetUserById(query.UserId);
  132. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  133. }
  134. var array = sessions.Select(ToDeviceInfo).ToArray();
  135. return new QueryResult<DeviceInfo>(array);
  136. }
  137. private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
  138. {
  139. var caps = GetCapabilities(authInfo.DeviceId);
  140. return new DeviceInfo
  141. {
  142. AppName = authInfo.AppName,
  143. AppVersion = authInfo.AppVersion,
  144. Id = authInfo.DeviceId,
  145. LastUserId = authInfo.UserId,
  146. LastUserName = authInfo.UserName,
  147. Name = authInfo.DeviceName,
  148. DateLastActivity = authInfo.DateLastActivity,
  149. IconUrl = caps?.IconUrl
  150. };
  151. }
  152. private string GetDevicesPath()
  153. {
  154. return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
  155. }
  156. private string GetDevicePath(string id)
  157. {
  158. return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture));
  159. }
  160. internal Task EnsureLibraryFolder(string path, string name)
  161. {
  162. var existingFolders = _libraryManager
  163. .RootFolder
  164. .Children
  165. .OfType<Folder>()
  166. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
  167. .ToList();
  168. if (existingFolders.Count > 0)
  169. {
  170. return Task.CompletedTask;
  171. }
  172. Directory.CreateDirectory(path);
  173. var libraryOptions = new LibraryOptions
  174. {
  175. PathInfos = new[] { new MediaPathInfo { Path = path } },
  176. EnablePhotos = true,
  177. EnableRealtimeMonitor = false,
  178. SaveLocalMetadata = true
  179. };
  180. if (string.IsNullOrWhiteSpace(name))
  181. {
  182. name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
  183. }
  184. return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
  185. }
  186. public bool CanAccessDevice(User user, string deviceId)
  187. {
  188. if (user == null)
  189. {
  190. throw new ArgumentException("user not found");
  191. }
  192. if (string.IsNullOrEmpty(deviceId))
  193. {
  194. throw new ArgumentNullException(nameof(deviceId));
  195. }
  196. if (!CanAccessDevice(user.Policy, deviceId))
  197. {
  198. var capabilities = GetCapabilities(deviceId);
  199. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  200. {
  201. return false;
  202. }
  203. }
  204. return true;
  205. }
  206. private static bool CanAccessDevice(UserPolicy policy, string id)
  207. {
  208. if (policy.EnableAllDevices)
  209. {
  210. return true;
  211. }
  212. if (policy.IsAdministrator)
  213. {
  214. return true;
  215. }
  216. return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
  217. }
  218. }
  219. public class DeviceManagerEntryPoint : IServerEntryPoint
  220. {
  221. private readonly DeviceManager _deviceManager;
  222. private readonly IServerConfigurationManager _config;
  223. private ILogger _logger;
  224. public DeviceManagerEntryPoint(
  225. IDeviceManager deviceManager,
  226. IServerConfigurationManager config,
  227. ILogger<DeviceManagerEntryPoint> logger)
  228. {
  229. _deviceManager = (DeviceManager)deviceManager;
  230. _config = config;
  231. _logger = logger;
  232. }
  233. public Task RunAsync()
  234. {
  235. return Task.CompletedTask;
  236. }
  237. #region IDisposable Support
  238. private bool disposedValue = false; // To detect redundant calls
  239. protected virtual void Dispose(bool disposing)
  240. {
  241. if (!disposedValue)
  242. {
  243. if (disposing)
  244. {
  245. // TODO: dispose managed state (managed objects).
  246. }
  247. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  248. // TODO: set large fields to null.
  249. disposedValue = true;
  250. }
  251. }
  252. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  253. // ~DeviceManagerEntryPoint() {
  254. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  255. // Dispose(false);
  256. // }
  257. // This code added to correctly implement the disposable pattern.
  258. public void Dispose()
  259. {
  260. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  261. Dispose(true);
  262. // TODO: uncomment the following line if the finalizer is overridden above.
  263. // GC.SuppressFinalize(this);
  264. }
  265. #endregion
  266. }
  267. public class DevicesConfigStore : IConfigurationFactory
  268. {
  269. public IEnumerable<ConfigurationStore> GetConfigurations()
  270. {
  271. return new ConfigurationStore[]
  272. {
  273. new ConfigurationStore
  274. {
  275. Key = "devices",
  276. ConfigurationType = typeof(DevicesOptions)
  277. }
  278. };
  279. }
  280. }
  281. public static class UploadConfigExtension
  282. {
  283. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  284. {
  285. return config.GetConfiguration<DevicesOptions>("devices");
  286. }
  287. }
  288. }