DeviceManager.cs 13 KB

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