DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Extensions;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Devices;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Plugins;
  14. using MediaBrowser.Controller.Security;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Devices;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Events;
  19. using MediaBrowser.Model.Globalization;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Net;
  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 ILibraryMonitor _libraryMonitor;
  35. private readonly IServerConfigurationManager _config;
  36. private readonly ILibraryManager _libraryManager;
  37. private readonly ILocalizationManager _localizationManager;
  38. private readonly IAuthenticationRepository _authRepo;
  39. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
  40. public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
  41. private readonly object _cameraUploadSyncLock = new object();
  42. private readonly object _capabilitiesSyncLock = new object();
  43. public DeviceManager(
  44. IAuthenticationRepository authRepo,
  45. IJsonSerializer json,
  46. ILibraryManager libraryManager,
  47. ILocalizationManager localizationManager,
  48. IUserManager userManager,
  49. IFileSystem fileSystem,
  50. ILibraryMonitor libraryMonitor,
  51. IServerConfigurationManager config)
  52. {
  53. _json = json;
  54. _userManager = userManager;
  55. _fileSystem = fileSystem;
  56. _libraryMonitor = libraryMonitor;
  57. _config = config;
  58. _libraryManager = libraryManager;
  59. _localizationManager = localizationManager;
  60. _authRepo = authRepo;
  61. }
  62. private Dictionary<string, ClientCapabilities> _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
  63. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  64. {
  65. var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
  66. Directory.CreateDirectory(Path.GetDirectoryName(path));
  67. lock (_capabilitiesSyncLock)
  68. {
  69. _capabilitiesCache[deviceId] = capabilities;
  70. _json.SerializeToFile(capabilities, path);
  71. }
  72. }
  73. public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
  74. {
  75. _authRepo.UpdateDeviceOptions(deviceId, options);
  76. if (DeviceOptionsUpdated != null)
  77. {
  78. DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
  79. {
  80. Argument = new Tuple<string, DeviceOptions>(deviceId, options)
  81. });
  82. }
  83. }
  84. public DeviceOptions GetDeviceOptions(string deviceId)
  85. {
  86. return _authRepo.GetDeviceOptions(deviceId);
  87. }
  88. public ClientCapabilities GetCapabilities(string id)
  89. {
  90. lock (_capabilitiesSyncLock)
  91. {
  92. if (_capabilitiesCache.TryGetValue(id, out var result))
  93. {
  94. return result;
  95. }
  96. var path = Path.Combine(GetDevicePath(id), "capabilities.json");
  97. try
  98. {
  99. return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
  100. }
  101. catch
  102. {
  103. }
  104. }
  105. return new ClientCapabilities();
  106. }
  107. public DeviceInfo GetDevice(string id)
  108. {
  109. return GetDevice(id, true);
  110. }
  111. private DeviceInfo GetDevice(string id, bool includeCapabilities)
  112. {
  113. var session = _authRepo.Get(new AuthenticationInfoQuery
  114. {
  115. DeviceId = id
  116. }).Items.FirstOrDefault();
  117. var device = session == null ? null : ToDeviceInfo(session);
  118. return device;
  119. }
  120. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  121. {
  122. var sessions = _authRepo.Get(new AuthenticationInfoQuery
  123. {
  124. //UserId = query.UserId
  125. HasUser = true
  126. }).Items;
  127. // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
  128. if (query.SupportsSync.HasValue)
  129. {
  130. var val = query.SupportsSync.Value;
  131. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val).ToArray();
  132. }
  133. if (!query.UserId.Equals(Guid.Empty))
  134. {
  135. var user = _userManager.GetUserById(query.UserId);
  136. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)).ToArray();
  137. }
  138. var array = sessions.Select(ToDeviceInfo).ToArray();
  139. return new QueryResult<DeviceInfo>
  140. {
  141. Items = array,
  142. TotalRecordCount = array.Length
  143. };
  144. }
  145. private DeviceInfo ToDeviceInfo(AuthenticationInfo authInfo)
  146. {
  147. var caps = GetCapabilities(authInfo.DeviceId);
  148. return new DeviceInfo
  149. {
  150. AppName = authInfo.AppName,
  151. AppVersion = authInfo.AppVersion,
  152. Id = authInfo.DeviceId,
  153. LastUserId = authInfo.UserId,
  154. LastUserName = authInfo.UserName,
  155. Name = authInfo.DeviceName,
  156. DateLastActivity = authInfo.DateLastActivity,
  157. IconUrl = caps == null ? null : caps.IconUrl
  158. };
  159. }
  160. private string GetDevicesPath()
  161. {
  162. return Path.Combine(_config.ApplicationPaths.DataPath, "devices");
  163. }
  164. private string GetDevicePath(string id)
  165. {
  166. return Path.Combine(GetDevicesPath(), id.GetMD5().ToString("N", CultureInfo.InvariantCulture));
  167. }
  168. public ContentUploadHistory GetCameraUploadHistory(string deviceId)
  169. {
  170. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  171. lock (_cameraUploadSyncLock)
  172. {
  173. try
  174. {
  175. return _json.DeserializeFromFile<ContentUploadHistory>(path);
  176. }
  177. catch (IOException)
  178. {
  179. return new ContentUploadHistory
  180. {
  181. DeviceId = deviceId
  182. };
  183. }
  184. }
  185. }
  186. public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
  187. {
  188. var device = GetDevice(deviceId, false);
  189. var uploadPathInfo = GetUploadPath(device);
  190. var path = uploadPathInfo.Item1;
  191. if (!string.IsNullOrWhiteSpace(file.Album))
  192. {
  193. path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
  194. }
  195. path = Path.Combine(path, file.Name);
  196. path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
  197. Directory.CreateDirectory(Path.GetDirectoryName(path));
  198. await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
  199. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  200. try
  201. {
  202. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  203. {
  204. await stream.CopyToAsync(fs).ConfigureAwait(false);
  205. }
  206. AddCameraUpload(deviceId, file);
  207. }
  208. finally
  209. {
  210. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  211. }
  212. if (CameraImageUploaded != null)
  213. {
  214. CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
  215. {
  216. Argument = new CameraImageUploadInfo
  217. {
  218. Device = device,
  219. FileInfo = file
  220. }
  221. });
  222. }
  223. }
  224. private void AddCameraUpload(string deviceId, LocalFileInfo file)
  225. {
  226. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  227. Directory.CreateDirectory(Path.GetDirectoryName(path));
  228. lock (_cameraUploadSyncLock)
  229. {
  230. ContentUploadHistory history;
  231. try
  232. {
  233. history = _json.DeserializeFromFile<ContentUploadHistory>(path);
  234. }
  235. catch (IOException)
  236. {
  237. history = new ContentUploadHistory
  238. {
  239. DeviceId = deviceId
  240. };
  241. }
  242. history.DeviceId = deviceId;
  243. var list = history.FilesUploaded.ToList();
  244. list.Add(file);
  245. history.FilesUploaded = list.ToArray();
  246. _json.SerializeToFile(history, path);
  247. }
  248. }
  249. internal Task EnsureLibraryFolder(string path, string name)
  250. {
  251. var existingFolders = _libraryManager
  252. .RootFolder
  253. .Children
  254. .OfType<Folder>()
  255. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path))
  256. .ToList();
  257. if (existingFolders.Count > 0)
  258. {
  259. return Task.CompletedTask;
  260. }
  261. Directory.CreateDirectory(path);
  262. var libraryOptions = new LibraryOptions
  263. {
  264. PathInfos = new[] { new MediaPathInfo { Path = path } },
  265. EnablePhotos = true,
  266. EnableRealtimeMonitor = false,
  267. SaveLocalMetadata = true
  268. };
  269. if (string.IsNullOrWhiteSpace(name))
  270. {
  271. name = _localizationManager.GetLocalizedString("HeaderCameraUploads");
  272. }
  273. return _libraryManager.AddVirtualFolder(name, CollectionType.HomeVideos, libraryOptions, true);
  274. }
  275. private Tuple<string, string, string> GetUploadPath(DeviceInfo device)
  276. {
  277. var config = _config.GetUploadOptions();
  278. var path = config.CameraUploadPath;
  279. if (string.IsNullOrWhiteSpace(path))
  280. {
  281. path = DefaultCameraUploadsPath;
  282. }
  283. var topLibraryPath = path;
  284. if (config.EnableCameraUploadSubfolders)
  285. {
  286. path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
  287. }
  288. return new Tuple<string, string, string>(path, topLibraryPath, null);
  289. }
  290. internal string GetUploadsPath()
  291. {
  292. var config = _config.GetUploadOptions();
  293. var path = config.CameraUploadPath;
  294. if (string.IsNullOrWhiteSpace(path))
  295. {
  296. path = DefaultCameraUploadsPath;
  297. }
  298. return path;
  299. }
  300. private string DefaultCameraUploadsPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
  301. public bool CanAccessDevice(User user, string deviceId)
  302. {
  303. if (user == null)
  304. {
  305. throw new ArgumentException("user not found");
  306. }
  307. if (string.IsNullOrEmpty(deviceId))
  308. {
  309. throw new ArgumentNullException(nameof(deviceId));
  310. }
  311. if (!CanAccessDevice(user.Policy, deviceId))
  312. {
  313. var capabilities = GetCapabilities(deviceId);
  314. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  315. {
  316. return false;
  317. }
  318. }
  319. return true;
  320. }
  321. private static bool CanAccessDevice(UserPolicy policy, string id)
  322. {
  323. if (policy.EnableAllDevices)
  324. {
  325. return true;
  326. }
  327. if (policy.IsAdministrator)
  328. {
  329. return true;
  330. }
  331. return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
  332. }
  333. }
  334. public class DeviceManagerEntryPoint : IServerEntryPoint
  335. {
  336. private readonly DeviceManager _deviceManager;
  337. private readonly IServerConfigurationManager _config;
  338. private ILogger _logger;
  339. public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, ILogger 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. }