DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Devices;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Plugins;
  16. using MediaBrowser.Controller.Security;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Devices;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Net;
  24. using MediaBrowser.Model.Querying;
  25. using MediaBrowser.Model.Serialization;
  26. using MediaBrowser.Model.Session;
  27. using MediaBrowser.Model.Users;
  28. using Microsoft.Extensions.Logging;
  29. namespace Emby.Server.Implementations.Devices
  30. {
  31. public class DeviceManager : IDeviceManager
  32. {
  33. private readonly IJsonSerializer _json;
  34. private readonly IUserManager _userManager;
  35. private readonly IFileSystem _fileSystem;
  36. private readonly ILibraryMonitor _libraryMonitor;
  37. private readonly IServerConfigurationManager _config;
  38. private readonly ILibraryManager _libraryManager;
  39. private readonly ILocalizationManager _localizationManager;
  40. private readonly IAuthenticationRepository _authRepo;
  41. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
  42. public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
  43. private readonly object _cameraUploadSyncLock = new object();
  44. private readonly object _capabilitiesSyncLock = new object();
  45. public DeviceManager(
  46. IAuthenticationRepository authRepo,
  47. IJsonSerializer json,
  48. ILibraryManager libraryManager,
  49. ILocalizationManager localizationManager,
  50. IUserManager userManager,
  51. IFileSystem fileSystem,
  52. ILibraryMonitor libraryMonitor,
  53. IServerConfigurationManager config)
  54. {
  55. _json = json;
  56. _userManager = userManager;
  57. _fileSystem = fileSystem;
  58. _libraryMonitor = libraryMonitor;
  59. _config = config;
  60. _libraryManager = libraryManager;
  61. _localizationManager = localizationManager;
  62. _authRepo = authRepo;
  63. }
  64. private Dictionary<string, ClientCapabilities> _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
  65. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  66. {
  67. var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
  68. Directory.CreateDirectory(Path.GetDirectoryName(path));
  69. lock (_capabilitiesSyncLock)
  70. {
  71. _capabilitiesCache[deviceId] = capabilities;
  72. _json.SerializeToFile(capabilities, path);
  73. }
  74. }
  75. public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
  76. {
  77. _authRepo.UpdateDeviceOptions(deviceId, options);
  78. if (DeviceOptionsUpdated != null)
  79. {
  80. DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
  81. {
  82. Argument = new Tuple<string, DeviceOptions>(deviceId, options)
  83. });
  84. }
  85. }
  86. public DeviceOptions GetDeviceOptions(string deviceId)
  87. {
  88. return _authRepo.GetDeviceOptions(deviceId);
  89. }
  90. public ClientCapabilities GetCapabilities(string id)
  91. {
  92. lock (_capabilitiesSyncLock)
  93. {
  94. if (_capabilitiesCache.TryGetValue(id, out var result))
  95. {
  96. return result;
  97. }
  98. var path = Path.Combine(GetDevicePath(id), "capabilities.json");
  99. try
  100. {
  101. return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
  102. }
  103. catch
  104. {
  105. }
  106. }
  107. return new ClientCapabilities();
  108. }
  109. public DeviceInfo GetDevice(string id)
  110. {
  111. return GetDevice(id, true);
  112. }
  113. private DeviceInfo GetDevice(string id, bool includeCapabilities)
  114. {
  115. var session = _authRepo.Get(new AuthenticationInfoQuery
  116. {
  117. DeviceId = id
  118. }).Items.FirstOrDefault();
  119. var device = session == null ? null : ToDeviceInfo(session);
  120. return device;
  121. }
  122. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  123. {
  124. IEnumerable<AuthenticationInfo> sessions = _authRepo.Get(new AuthenticationInfoQuery
  125. {
  126. //UserId = query.UserId
  127. HasUser = true
  128. }).Items;
  129. // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
  130. if (query.SupportsSync.HasValue)
  131. {
  132. var val = query.SupportsSync.Value;
  133. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val);
  134. }
  135. if (!query.UserId.Equals(Guid.Empty))
  136. {
  137. var user = _userManager.GetUserById(query.UserId);
  138. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  139. }
  140. var array = sessions.Select(ToDeviceInfo).ToArray();
  141. return new QueryResult<DeviceInfo>(array);
  142. }
  143. private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
  144. {
  145. var caps = GetCapabilities(authInfo.DeviceId);
  146. return new DeviceInfo
  147. {
  148. AppName = authInfo.AppName,
  149. AppVersion = authInfo.AppVersion,
  150. Id = authInfo.DeviceId,
  151. LastUserId = authInfo.UserId,
  152. LastUserName = authInfo.UserName,
  153. Name = authInfo.DeviceName,
  154. DateLastActivity = authInfo.DateLastActivity,
  155. IconUrl = caps?.IconUrl
  156. };
  157. }
  158. private string GetDevicesPath()
  159. {
  160. return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
  161. }
  162. private string GetDevicePath(string id)
  163. {
  164. return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture));
  165. }
  166. public ContentUploadHistory GetCameraUploadHistory(string deviceId)
  167. {
  168. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  169. lock (_cameraUploadSyncLock)
  170. {
  171. try
  172. {
  173. return _json.DeserializeFromFile<ContentUploadHistory>(path);
  174. }
  175. catch (IOException)
  176. {
  177. return new ContentUploadHistory
  178. {
  179. DeviceId = deviceId
  180. };
  181. }
  182. }
  183. }
  184. public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
  185. {
  186. var device = GetDevice(deviceId, false);
  187. var uploadPathInfo = GetUploadPath(device);
  188. var path = uploadPathInfo.Item1;
  189. if (!string.IsNullOrWhiteSpace(file.Album))
  190. {
  191. path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
  192. }
  193. path = Path.Combine(path, file.Name);
  194. path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
  195. Directory.CreateDirectory(Path.GetDirectoryName(path));
  196. await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
  197. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  198. try
  199. {
  200. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  201. {
  202. await stream.CopyToAsync(fs).ConfigureAwait(false);
  203. }
  204. AddCameraUpload(deviceId, file);
  205. }
  206. finally
  207. {
  208. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  209. }
  210. if (CameraImageUploaded != null)
  211. {
  212. CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
  213. {
  214. Argument = new CameraImageUploadInfo
  215. {
  216. Device = device,
  217. FileInfo = file
  218. }
  219. });
  220. }
  221. }
  222. private void AddCameraUpload(string deviceId, LocalFileInfo file)
  223. {
  224. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  225. Directory.CreateDirectory(Path.GetDirectoryName(path));
  226. lock (_cameraUploadSyncLock)
  227. {
  228. ContentUploadHistory history;
  229. try
  230. {
  231. history = _json.DeserializeFromFile<ContentUploadHistory>(path);
  232. }
  233. catch (IOException)
  234. {
  235. history = new ContentUploadHistory
  236. {
  237. DeviceId = deviceId
  238. };
  239. }
  240. history.DeviceId = deviceId;
  241. var list = history.FilesUploaded.ToList();
  242. list.Add(file);
  243. history.FilesUploaded = list.ToArray();
  244. _json.SerializeToFile(history, path);
  245. }
  246. }
  247. internal Task EnsureLibraryFolder(string path, string name)
  248. {
  249. var existingFolders = _libraryManager
  250. .RootFolder
  251. .Children
  252. .OfType<Folder>()
  253. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
  254. .ToList();
  255. if (existingFolders.Count > 0)
  256. {
  257. return Task.CompletedTask;
  258. }
  259. Directory.CreateDirectory(path);
  260. var libraryOptions = new LibraryOptions
  261. {
  262. PathInfos = new[] { new MediaPathInfo { Path = path } },
  263. EnablePhotos = true,
  264. EnableRealtimeMonitor = false,
  265. SaveLocalMetadata = true
  266. };
  267. if (string.IsNullOrWhiteSpace(name))
  268. {
  269. name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
  270. }
  271. return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
  272. }
  273. private Tuple<string, string, string> GetUploadPath(DeviceInfo device)
  274. {
  275. var config = _config.GetUploadOptions();
  276. var path = config.CameraUploadPath;
  277. if (string.IsNullOrWhiteSpace(path))
  278. {
  279. path = DefaultCameraUploadsPath;
  280. }
  281. var topLibraryPath = path;
  282. if (config.EnableCameraUploadSubfolders)
  283. {
  284. path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
  285. }
  286. return new Tuple<string, string, string>(path, topLibraryPath, null);
  287. }
  288. internal string GetUploadsPath()
  289. {
  290. var config = _config.GetUploadOptions();
  291. var path = config.CameraUploadPath;
  292. if (string.IsNullOrWhiteSpace(path))
  293. {
  294. path = DefaultCameraUploadsPath;
  295. }
  296. return path;
  297. }
  298. private string DefaultCameraUploadsPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
  299. public bool CanAccessDevice(User user, string deviceId)
  300. {
  301. if (user == null)
  302. {
  303. throw new ArgumentException("user not found");
  304. }
  305. if (string.IsNullOrEmpty(deviceId))
  306. {
  307. throw new ArgumentNullException(nameof(deviceId));
  308. }
  309. if (!CanAccessDevice(user.Policy, deviceId))
  310. {
  311. var capabilities = GetCapabilities(deviceId);
  312. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  313. {
  314. return false;
  315. }
  316. }
  317. return true;
  318. }
  319. private static bool CanAccessDevice(UserPolicy policy, string id)
  320. {
  321. if (policy.EnableAllDevices)
  322. {
  323. return true;
  324. }
  325. if (policy.IsAdministrator)
  326. {
  327. return true;
  328. }
  329. return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
  330. }
  331. }
  332. public class DeviceManagerEntryPoint : IServerEntryPoint
  333. {
  334. private readonly DeviceManager _deviceManager;
  335. private readonly IServerConfigurationManager _config;
  336. private ILogger _logger;
  337. public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, ILogger logger)
  338. {
  339. _deviceManager = (DeviceManager)deviceManager;
  340. _config = config;
  341. _logger = logger;
  342. }
  343. public async Task RunAsync()
  344. {
  345. if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
  346. {
  347. var path = _deviceManager.GetUploadsPath();
  348. if (Directory.Exists(path))
  349. {
  350. try
  351. {
  352. await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
  353. }
  354. catch (Exception ex)
  355. {
  356. _logger.LogError(ex, "Error creating camera uploads library");
  357. }
  358. _config.Configuration.CameraUploadUpgraded = true;
  359. _config.SaveConfiguration();
  360. }
  361. }
  362. }
  363. #region IDisposable Support
  364. private bool disposedValue = false; // To detect redundant calls
  365. protected virtual void Dispose(bool disposing)
  366. {
  367. if (!disposedValue)
  368. {
  369. if (disposing)
  370. {
  371. // TODO: dispose managed state (managed objects).
  372. }
  373. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  374. // TODO: set large fields to null.
  375. disposedValue = true;
  376. }
  377. }
  378. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  379. // ~DeviceManagerEntryPoint() {
  380. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  381. // Dispose(false);
  382. // }
  383. // This code added to correctly implement the disposable pattern.
  384. public void Dispose()
  385. {
  386. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  387. Dispose(true);
  388. // TODO: uncomment the following line if the finalizer is overridden above.
  389. // GC.SuppressFinalize(this);
  390. }
  391. #endregion
  392. }
  393. public class DevicesConfigStore : IConfigurationFactory
  394. {
  395. public IEnumerable<ConfigurationStore> GetConfigurations()
  396. {
  397. return new ConfigurationStore[]
  398. {
  399. new ConfigurationStore
  400. {
  401. Key = "devices",
  402. ConfigurationType = typeof(DevicesOptions)
  403. }
  404. };
  405. }
  406. }
  407. public static class UploadConfigExtension
  408. {
  409. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  410. {
  411. return config.GetConfiguration<DevicesOptions>("devices");
  412. }
  413. }
  414. }