DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 MediaBrowser.Model.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. if (query.SupportsSync.HasValue)
  127. {
  128. var val = query.SupportsSync.Value;
  129. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val).ToArray();
  130. }
  131. if (!query.UserId.Equals(Guid.Empty))
  132. {
  133. var user = _userManager.GetUserById(query.UserId);
  134. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId)).ToArray();
  135. }
  136. var array = sessions.Select(ToDeviceInfo).ToArray();
  137. return new QueryResult<DeviceInfo>
  138. {
  139. Items = array,
  140. TotalRecordCount = array.Length
  141. };
  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 == null ? null : 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"));
  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. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  196. await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
  197. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  198. try
  199. {
  200. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.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. EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
  213. {
  214. Argument = new CameraImageUploadInfo
  215. {
  216. Device = device,
  217. FileInfo = file
  218. }
  219. }, _logger);
  220. }
  221. }
  222. private void AddCameraUpload(string deviceId, LocalFileInfo file)
  223. {
  224. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  225. _fileSystem.CreateDirectory(_fileSystem.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. _fileSystem.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
  299. {
  300. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); }
  301. }
  302. public bool CanAccessDevice(User user, string deviceId)
  303. {
  304. if (user == null)
  305. {
  306. throw new ArgumentException("user not found");
  307. }
  308. if (string.IsNullOrEmpty(deviceId))
  309. {
  310. throw new ArgumentNullException("deviceId");
  311. }
  312. if (!CanAccessDevice(user.Policy, deviceId))
  313. {
  314. var capabilities = GetCapabilities(deviceId);
  315. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  316. {
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. private bool CanAccessDevice(UserPolicy policy, string id)
  323. {
  324. if (policy.EnableAllDevices)
  325. {
  326. return true;
  327. }
  328. if (policy.IsAdministrator)
  329. {
  330. return true;
  331. }
  332. return policy.EnabledDevices.Contains(id, StringComparer.OrdinalIgnoreCase);
  333. }
  334. }
  335. public class DeviceManagerEntryPoint : IServerEntryPoint
  336. {
  337. private readonly DeviceManager _deviceManager;
  338. private readonly IServerConfigurationManager _config;
  339. private readonly IFileSystem _fileSystem;
  340. private ILogger _logger;
  341. public DeviceManagerEntryPoint(IDeviceManager deviceManager, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger)
  342. {
  343. _deviceManager = (DeviceManager)deviceManager;
  344. _config = config;
  345. _fileSystem = fileSystem;
  346. _logger = logger;
  347. }
  348. public async void Run()
  349. {
  350. if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
  351. {
  352. var path = _deviceManager.GetUploadsPath();
  353. if (_fileSystem.DirectoryExists(path))
  354. {
  355. try
  356. {
  357. await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
  358. }
  359. catch (Exception ex)
  360. {
  361. _logger.ErrorException("Error creating camera uploads library", ex);
  362. }
  363. _config.Configuration.CameraUploadUpgraded = true;
  364. _config.SaveConfiguration();
  365. }
  366. }
  367. }
  368. #region IDisposable Support
  369. private bool disposedValue = false; // To detect redundant calls
  370. protected virtual void Dispose(bool disposing)
  371. {
  372. if (!disposedValue)
  373. {
  374. if (disposing)
  375. {
  376. // TODO: dispose managed state (managed objects).
  377. }
  378. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  379. // TODO: set large fields to null.
  380. disposedValue = true;
  381. }
  382. }
  383. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  384. // ~DeviceManagerEntryPoint() {
  385. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  386. // Dispose(false);
  387. // }
  388. // This code added to correctly implement the disposable pattern.
  389. public void Dispose()
  390. {
  391. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  392. Dispose(true);
  393. // TODO: uncomment the following line if the finalizer is overridden above.
  394. // GC.SuppressFinalize(this);
  395. }
  396. #endregion
  397. }
  398. public class DevicesConfigStore : IConfigurationFactory
  399. {
  400. public IEnumerable<ConfigurationStore> GetConfigurations()
  401. {
  402. return new ConfigurationStore[]
  403. {
  404. new ConfigurationStore
  405. {
  406. Key = "devices",
  407. ConfigurationType = typeof(DevicesOptions)
  408. }
  409. };
  410. }
  411. }
  412. public static class UploadConfigExtension
  413. {
  414. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  415. {
  416. return config.GetConfiguration<DevicesOptions>("devices");
  417. }
  418. }
  419. }