DeviceManager.cs 16 KB

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