DeviceManager.cs 16 KB

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