DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Devices;
  6. using MediaBrowser.Model.Events;
  7. using MediaBrowser.Model.Extensions;
  8. using Microsoft.Extensions.Logging;
  9. using MediaBrowser.Model.Net;
  10. using MediaBrowser.Model.Querying;
  11. using MediaBrowser.Model.Session;
  12. using MediaBrowser.Model.Users;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading.Tasks;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Controller.Entities;
  21. using MediaBrowser.Model.Entities;
  22. using MediaBrowser.Model.Configuration;
  23. using MediaBrowser.Controller.Plugins;
  24. using MediaBrowser.Model.Globalization;
  25. using MediaBrowser.Controller.Security;
  26. using MediaBrowser.Model.Serialization;
  27. using MediaBrowser.Common.Extensions;
  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 ILogger _logger;
  38. private readonly INetworkManager _network;
  39. private readonly ILibraryManager _libraryManager;
  40. private readonly ILocalizationManager _localizationManager;
  41. private readonly IAuthenticationRepository _authRepo;
  42. public event EventHandler<GenericEventArgs<Tuple<string, DeviceOptions>>> DeviceOptionsUpdated;
  43. public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
  44. private readonly object _cameraUploadSyncLock = new object();
  45. private readonly object _capabilitiesSyncLock = new object();
  46. public DeviceManager(IAuthenticationRepository authRepo, IJsonSerializer json, ILibraryManager libraryManager, ILocalizationManager localizationManager, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network)
  47. {
  48. _json = json;
  49. _userManager = userManager;
  50. _fileSystem = fileSystem;
  51. _libraryMonitor = libraryMonitor;
  52. _config = config;
  53. _logger = logger;
  54. _network = network;
  55. _libraryManager = libraryManager;
  56. _localizationManager = localizationManager;
  57. _authRepo = authRepo;
  58. }
  59. private Dictionary<string, ClientCapabilities> _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
  60. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  61. {
  62. var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
  63. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
  64. lock (_capabilitiesSyncLock)
  65. {
  66. _capabilitiesCache[deviceId] = capabilities;
  67. _json.SerializeToFile(capabilities, path);
  68. }
  69. }
  70. public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
  71. {
  72. _authRepo.UpdateDeviceOptions(deviceId, options);
  73. if (DeviceOptionsUpdated != null)
  74. {
  75. DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
  76. {
  77. Argument = new Tuple<string, DeviceOptions>(deviceId, options)
  78. });
  79. }
  80. }
  81. public DeviceOptions GetDeviceOptions(string deviceId)
  82. {
  83. return _authRepo.GetDeviceOptions(deviceId);
  84. }
  85. public ClientCapabilities GetCapabilities(string id)
  86. {
  87. lock (_capabilitiesSyncLock)
  88. {
  89. ClientCapabilities result;
  90. if (_capabilitiesCache.TryGetValue(id, out result))
  91. {
  92. return result;
  93. }
  94. var path = Path.Combine(GetDevicePath(id), "capabilities.json");
  95. try
  96. {
  97. return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
  98. }
  99. catch
  100. {
  101. }
  102. }
  103. return new ClientCapabilities();
  104. }
  105. public DeviceInfo GetDevice(string id)
  106. {
  107. return GetDevice(id, true);
  108. }
  109. private DeviceInfo GetDevice(string id, bool includeCapabilities)
  110. {
  111. var session = _authRepo.Get(new AuthenticationInfoQuery
  112. {
  113. DeviceId = id
  114. }).Items.FirstOrDefault();
  115. var device = session == null ? null : ToDeviceInfo(session);
  116. return device;
  117. }
  118. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  119. {
  120. var sessions = _authRepo.Get(new AuthenticationInfoQuery
  121. {
  122. //UserId = query.UserId
  123. HasUser = true
  124. }).Items;
  125. // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
  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. CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
  213. {
  214. Argument = new CameraImageUploadInfo
  215. {
  216. Device = device,
  217. FileInfo = file
  218. }
  219. });
  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.LogError(ex, "Error creating camera uploads library");
  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. }