DeviceManager.cs 16 KB

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