DeviceManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 Jellyfin.Data.Enums;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Devices;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Plugins;
  16. using MediaBrowser.Controller.Security;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Devices;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.Events;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Net;
  24. using MediaBrowser.Model.Querying;
  25. using MediaBrowser.Model.Serialization;
  26. using MediaBrowser.Model.Session;
  27. using MediaBrowser.Model.Users;
  28. using Microsoft.Extensions.Logging;
  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 ILibraryManager _libraryManager;
  39. private readonly ILocalizationManager _localizationManager;
  40. private readonly IAuthenticationRepository _authRepo;
  41. private readonly Dictionary<string, ClientCapabilities> _capabilitiesCache;
  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(
  47. IAuthenticationRepository authRepo,
  48. IJsonSerializer json,
  49. ILibraryManager libraryManager,
  50. ILocalizationManager localizationManager,
  51. IUserManager userManager,
  52. IFileSystem fileSystem,
  53. ILibraryMonitor libraryMonitor,
  54. IServerConfigurationManager config)
  55. {
  56. _json = json;
  57. _userManager = userManager;
  58. _fileSystem = fileSystem;
  59. _libraryMonitor = libraryMonitor;
  60. _config = config;
  61. _libraryManager = libraryManager;
  62. _localizationManager = localizationManager;
  63. _authRepo = authRepo;
  64. _capabilitiesCache = new Dictionary<string, ClientCapabilities>(StringComparer.OrdinalIgnoreCase);
  65. }
  66. public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
  67. {
  68. var path = Path.Combine(GetDevicePath(deviceId), "capabilities.json");
  69. Directory.CreateDirectory(Path.GetDirectoryName(path));
  70. lock (_capabilitiesSyncLock)
  71. {
  72. _capabilitiesCache[deviceId] = capabilities;
  73. _json.SerializeToFile(capabilities, path);
  74. }
  75. }
  76. public void UpdateDeviceOptions(string deviceId, DeviceOptions options)
  77. {
  78. _authRepo.UpdateDeviceOptions(deviceId, options);
  79. if (DeviceOptionsUpdated != null)
  80. {
  81. DeviceOptionsUpdated(this, new GenericEventArgs<Tuple<string, DeviceOptions>>()
  82. {
  83. Argument = new Tuple<string, DeviceOptions>(deviceId, options)
  84. });
  85. }
  86. }
  87. public DeviceOptions GetDeviceOptions(string deviceId)
  88. {
  89. return _authRepo.GetDeviceOptions(deviceId);
  90. }
  91. public ClientCapabilities GetCapabilities(string id)
  92. {
  93. lock (_capabilitiesSyncLock)
  94. {
  95. if (_capabilitiesCache.TryGetValue(id, out var result))
  96. {
  97. return result;
  98. }
  99. var path = Path.Combine(GetDevicePath(id), "capabilities.json");
  100. try
  101. {
  102. return _json.DeserializeFromFile<ClientCapabilities>(path) ?? new ClientCapabilities();
  103. }
  104. catch
  105. {
  106. }
  107. }
  108. return new ClientCapabilities();
  109. }
  110. public DeviceInfo GetDevice(string id)
  111. {
  112. return GetDevice(id, true);
  113. }
  114. private DeviceInfo GetDevice(string id, bool includeCapabilities)
  115. {
  116. var session = _authRepo.Get(new AuthenticationInfoQuery
  117. {
  118. DeviceId = id
  119. }).Items.FirstOrDefault();
  120. var device = session == null ? null : ToDeviceInfo(session);
  121. return device;
  122. }
  123. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  124. {
  125. IEnumerable<AuthenticationInfo> sessions = _authRepo.Get(new AuthenticationInfoQuery
  126. {
  127. //UserId = query.UserId
  128. HasUser = true
  129. }).Items;
  130. // TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
  131. if (query.SupportsSync.HasValue)
  132. {
  133. var val = query.SupportsSync.Value;
  134. sessions = sessions.Where(i => GetCapabilities(i.DeviceId).SupportsSync == val);
  135. }
  136. if (!query.UserId.Equals(Guid.Empty))
  137. {
  138. var user = _userManager.GetUserById(query.UserId);
  139. sessions = sessions.Where(i => CanAccessDevice(user, i.DeviceId));
  140. }
  141. var array = sessions.Select(ToDeviceInfo).ToArray();
  142. return new QueryResult<DeviceInfo>(array);
  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?.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", CultureInfo.InvariantCulture));
  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. Directory.CreateDirectory(Path.GetDirectoryName(path));
  197. await EnsureLibraryFolder(uploadPathInfo.Item2, uploadPathInfo.Item3).ConfigureAwait(false);
  198. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  199. try
  200. {
  201. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.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. CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
  214. {
  215. Argument = new CameraImageUploadInfo
  216. {
  217. Device = device,
  218. FileInfo = file
  219. }
  220. });
  221. }
  222. }
  223. private void AddCameraUpload(string deviceId, LocalFileInfo file)
  224. {
  225. var path = Path.Combine(GetDevicePath(deviceId), "camerauploads.json");
  226. Directory.CreateDirectory(Path.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. Directory.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 => Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
  300. public bool CanAccessDevice(Jellyfin.Data.Entities.User user, string deviceId)
  301. {
  302. if (user == null)
  303. {
  304. throw new ArgumentException("user not found");
  305. }
  306. if (string.IsNullOrEmpty(deviceId))
  307. {
  308. throw new ArgumentNullException(nameof(deviceId));
  309. }
  310. if (user.HasPermission(PermissionKind.EnableAllDevices)
  311. || user.HasPermission(PermissionKind.IsAdministrator))
  312. {
  313. return true;
  314. }
  315. if (!user.GetPreference(PreferenceKind.EnabledDevices).Contains(deviceId, StringComparer.OrdinalIgnoreCase))
  316. {
  317. var capabilities = GetCapabilities(deviceId);
  318. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  319. {
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. }
  326. public class DeviceManagerEntryPoint : IServerEntryPoint
  327. {
  328. private readonly DeviceManager _deviceManager;
  329. private readonly IServerConfigurationManager _config;
  330. private ILogger _logger;
  331. public DeviceManagerEntryPoint(
  332. IDeviceManager deviceManager,
  333. IServerConfigurationManager config,
  334. ILogger<DeviceManagerEntryPoint> logger)
  335. {
  336. _deviceManager = (DeviceManager)deviceManager;
  337. _config = config;
  338. _logger = logger;
  339. }
  340. public async Task RunAsync()
  341. {
  342. if (!_config.Configuration.CameraUploadUpgraded && _config.Configuration.IsStartupWizardCompleted)
  343. {
  344. var path = _deviceManager.GetUploadsPath();
  345. if (Directory.Exists(path))
  346. {
  347. try
  348. {
  349. await _deviceManager.EnsureLibraryFolder(path, null).ConfigureAwait(false);
  350. }
  351. catch (Exception ex)
  352. {
  353. _logger.LogError(ex, "Error creating camera uploads library");
  354. }
  355. _config.Configuration.CameraUploadUpgraded = true;
  356. _config.SaveConfiguration();
  357. }
  358. }
  359. }
  360. #region IDisposable Support
  361. private bool disposedValue = false; // To detect redundant calls
  362. protected virtual void Dispose(bool disposing)
  363. {
  364. if (!disposedValue)
  365. {
  366. if (disposing)
  367. {
  368. // TODO: dispose managed state (managed objects).
  369. }
  370. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  371. // TODO: set large fields to null.
  372. disposedValue = true;
  373. }
  374. }
  375. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  376. // ~DeviceManagerEntryPoint() {
  377. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  378. // Dispose(false);
  379. // }
  380. // This code added to correctly implement the disposable pattern.
  381. public void Dispose()
  382. {
  383. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  384. Dispose(true);
  385. // TODO: uncomment the following line if the finalizer is overridden above.
  386. // GC.SuppressFinalize(this);
  387. }
  388. #endregion
  389. }
  390. public class DevicesConfigStore : IConfigurationFactory
  391. {
  392. public IEnumerable<ConfigurationStore> GetConfigurations()
  393. {
  394. return new ConfigurationStore[]
  395. {
  396. new ConfigurationStore
  397. {
  398. Key = "devices",
  399. ConfigurationType = typeof(DevicesOptions)
  400. }
  401. };
  402. }
  403. }
  404. public static class UploadConfigExtension
  405. {
  406. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  407. {
  408. return config.GetConfiguration<DevicesOptions>("devices");
  409. }
  410. }
  411. }