DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. var 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).ToArray();
  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)).ToArray();
  139. }
  140. var array = sessions.Select(ToDeviceInfo).ToArray();
  141. return new QueryResult<DeviceInfo>
  142. {
  143. Items = array,
  144. TotalRecordCount = array.Length
  145. };
  146. }
  147. private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
  148. {
  149. var caps = GetCapabilities(authInfo.DeviceId);
  150. return new DeviceInfo
  151. {
  152. AppName = authInfo.AppName,
  153. AppVersion = authInfo.AppVersion,
  154. Id = authInfo.DeviceId,
  155. LastUserId = authInfo.UserId,
  156. LastUserName = authInfo.UserName,
  157. Name = authInfo.DeviceName,
  158. DateLastActivity = authInfo.DateLastActivity,
  159. IconUrl = caps == null ? null : caps.IconUrl
  160. };
  161. }
  162. private string GetDevicesPath()
  163. {
  164. return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
  165. }
  166. private string GetDevicePath(string id)
  167. {
  168. return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture));
  169. }
  170. public ContentUploadHistory GetCameraUploadHistory(string deviceId)
  171. {
  172. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  173. lock (_cameraUploadSyncLock)
  174. {
  175. try
  176. {
  177. return _json.DeserializeFromFile<ContentUploadHistory>(path);
  178. }
  179. catch (IOException)
  180. {
  181. return new ContentUploadHistory
  182. {
  183. DeviceId = deviceId
  184. };
  185. }
  186. }
  187. }
  188. public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
  189. {
  190. var device = GetDevice(deviceId, false);
  191. var uploadPathInfo = GetUploadPath(device);
  192. var path = uploadPathInfo.Item1;
  193. if (!string.IsNullOrWhiteSpace(file.Album))
  194. {
  195. path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
  196. }
  197. path = Path.Combine(path, file.Name);
  198. path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
  199. Directory.CreateDirectory(Path.GetDirectoryName(path));
  200. await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
  201. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  202. try
  203. {
  204. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  205. {
  206. await stream.CopyToAsync(fs).ConfigureAwait(false);
  207. }
  208. AddCameraUpload(deviceId, file);
  209. }
  210. finally
  211. {
  212. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  213. }
  214. if (CameraImageUploaded != null)
  215. {
  216. CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
  217. {
  218. Argument = new CameraImageUploadInfo
  219. {
  220. Device = device,
  221. FileInfo = file
  222. }
  223. });
  224. }
  225. }
  226. private void AddCameraUpload(string deviceId, LocalFileInfo file)
  227. {
  228. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  229. Directory.CreateDirectory(Path.GetDirectoryName(path));
  230. lock (_cameraUploadSyncLock)
  231. {
  232. ContentUploadHistory history;
  233. try
  234. {
  235. history = _json.DeserializeFromFile<ContentUploadHistory>(path);
  236. }
  237. catch (IOException)
  238. {
  239. history = new ContentUploadHistory
  240. {
  241. DeviceId = deviceId
  242. };
  243. }
  244. history.DeviceId = deviceId;
  245. var list = history.FilesUploaded.ToList();
  246. list.Add(file);
  247. history.FilesUploaded = list.ToArray();
  248. _json.SerializeToFile(history, path);
  249. }
  250. }
  251. internal Task EnsureLibraryFolder(string path, string name)
  252. {
  253. var existingFolders = _libraryManager
  254. .RootFolder
  255. .Children
  256. .OfType<Folder>()
  257. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
  258. .ToList();
  259. if (existingFolders.Count > 0)
  260. {
  261. return Task.CompletedTask;
  262. }
  263. Directory.CreateDirectory(path);
  264. var libraryOptions = new LibraryOptions
  265. {
  266. PathInfos = new[] { new MediaPathInfo { Path = path } },
  267. EnablePhotos = true,
  268. EnableRealtimeMonitor = false,
  269. SaveLocalMetadata = true
  270. };
  271. if (string.IsNullOrWhiteSpace(name))
  272. {
  273. name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
  274. }
  275. return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
  276. }
  277. private Tuple<string, string, string> GetUploadPath(DeviceInfo device)
  278. {
  279. var config = _config.GetUploadOptions();
  280. var path = config.CameraUploadPath;
  281. if (string.IsNullOrWhiteSpace(path))
  282. {
  283. path = DefaultCameraUploadsPath;
  284. }
  285. var topLibraryPath = path;
  286. if (config.EnableCameraUploadSubfolders)
  287. {
  288. path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
  289. }
  290. return new Tuple<string, string, string>(path, topLibraryPath, null);
  291. }
  292. internal string GetUploadsPath()
  293. {
  294. var config = _config.GetUploadOptions();
  295. var path = config.CameraUploadPath;
  296. if (string.IsNullOrWhiteSpace(path))
  297. {
  298. path = DefaultCameraUploadsPath;
  299. }
  300. return path;
  301. }
  302. private string DefaultCameraUploadsPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
  303. public bool CanAccessDevice(User user, string deviceId)
  304. {
  305. if (user == null)
  306. {
  307. throw new ArgumentException("user not found");
  308. }
  309. if (string.IsNullOrEmpty(deviceId))
  310. {
  311. throw new ArgumentNullException(nameof(deviceId));
  312. }
  313. if (!CanAccessDevice(user.Policy, deviceId))
  314. {
  315. var capabilities = GetCapabilities(deviceId);
  316. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  317. {
  318. return false;
  319. }
  320. }
  321. return true;
  322. }
  323. private static bool CanAccessDevice(UserPolicy policy, string id)
  324. {
  325. if (policy.EnableAllDevices)
  326. {
  327. return true;
  328. }
  329. if (policy.IsAdministrator)
  330. {
  331. return true;
  332. }
  333. return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
  334. }
  335. }
  336. public class DeviceManagerEntryPoint : IServerEntryPoint
  337. {
  338. private readonly DeviceManager _deviceManager;
  339. private readonly IServerConfigurationManager _config;
  340. private ILogger _logger;
  341. public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, ILogger logger)
  342. {
  343. _deviceManager = (DeviceManager)deviceManager;
  344. _config = config;
  345. _logger = logger;
  346. }
  347. public async Task RunAsync()
  348. {
  349. if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
  350. {
  351. var path = _deviceManager.GetUploadsPath();
  352. if (Directory.Exists(path))
  353. {
  354. try
  355. {
  356. await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
  357. }
  358. catch (Exception ex)
  359. {
  360. _logger.LogError(ex, "Error creating camera uploads library");
  361. }
  362. _config.Configuration.CameraUploadUpgraded = true;
  363. _config.SaveConfiguration();
  364. }
  365. }
  366. }
  367. #region IDisposable Support
  368. private bool disposedValue = false; // To detect redundant calls
  369. protected virtual void Dispose(bool disposing)
  370. {
  371. if (!disposedValue)
  372. {
  373. if (disposing)
  374. {
  375. // TODO: dispose managed state (managed objects).
  376. }
  377. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  378. // TODO: set large fields to null.
  379. disposedValue = true;
  380. }
  381. }
  382. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  383. // ~DeviceManagerEntryPoint() {
  384. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  385. // Dispose(false);
  386. // }
  387. // This code added to correctly implement the disposable pattern.
  388. public void Dispose()
  389. {
  390. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  391. Dispose(true);
  392. // TODO: uncomment the following line if the finalizer is overridden above.
  393. // GC.SuppressFinalize(this);
  394. }
  395. #endregion
  396. }
  397. public class DevicesConfigStore : IConfigurationFactory
  398. {
  399. public IEnumerable<ConfigurationStore> GetConfigurations()
  400. {
  401. return new ConfigurationStore[]
  402. {
  403. new ConfigurationStore
  404. {
  405. Key = "devices",
  406. ConfigurationType = typeof(DevicesOptions)
  407. }
  408. };
  409. }
  410. }
  411. public static class UploadConfigExtension
  412. {
  413. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  414. {
  415. return config.GetConfiguration<DevicesOptions>("devices");
  416. }
  417. }
  418. }