DeviceManager.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Events;
  3. using MediaBrowser.Common.IO;
  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.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. namespace MediaBrowser.Server.Implementations.Devices
  19. {
  20. public class DeviceManager : IDeviceManager
  21. {
  22. private readonly IDeviceRepository _repo;
  23. private readonly IUserManager _userManager;
  24. private readonly IFileSystem _fileSystem;
  25. private readonly ILibraryMonitor _libraryMonitor;
  26. private readonly IConfigurationManager _config;
  27. private readonly ILogger _logger;
  28. public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
  29. /// <summary>
  30. /// Occurs when [device options updated].
  31. /// </summary>
  32. public event EventHandler<GenericEventArgs<DeviceInfo>> DeviceOptionsUpdated;
  33. public DeviceManager(IDeviceRepository repo, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IConfigurationManager config, ILogger logger)
  34. {
  35. _repo = repo;
  36. _userManager = userManager;
  37. _fileSystem = fileSystem;
  38. _libraryMonitor = libraryMonitor;
  39. _config = config;
  40. _logger = logger;
  41. }
  42. public async Task<DeviceInfo> RegisterDevice(string reportedId, string name, string appName, string appVersion, string usedByUserId)
  43. {
  44. var device = GetDevice(reportedId) ?? new DeviceInfo
  45. {
  46. Id = reportedId
  47. };
  48. device.ReportedName = name;
  49. device.AppName = appName;
  50. device.AppVersion = appVersion;
  51. if (!string.IsNullOrWhiteSpace(usedByUserId))
  52. {
  53. var user = _userManager.GetUserById(usedByUserId);
  54. device.LastUserId = user.Id.ToString("N");
  55. device.LastUserName = user.Name;
  56. }
  57. device.DateLastModified = DateTime.UtcNow;
  58. await _repo.SaveDevice(device).ConfigureAwait(false);
  59. return device;
  60. }
  61. public Task SaveCapabilities(string reportedId, ClientCapabilities capabilities)
  62. {
  63. return _repo.SaveCapabilities(reportedId, capabilities);
  64. }
  65. public ClientCapabilities GetCapabilities(string reportedId)
  66. {
  67. return _repo.GetCapabilities(reportedId);
  68. }
  69. public DeviceInfo GetDevice(string id)
  70. {
  71. return _repo.GetDevice(id);
  72. }
  73. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  74. {
  75. IEnumerable<DeviceInfo> devices = _repo.GetDevices().OrderByDescending(i => i.DateLastModified);
  76. if (query.SupportsContentUploading.HasValue)
  77. {
  78. var val = query.SupportsContentUploading.Value;
  79. devices = devices.Where(i => GetCapabilities(i.Id).SupportsContentUploading == val);
  80. }
  81. if (query.SupportsSync.HasValue)
  82. {
  83. var val = query.SupportsSync.Value;
  84. devices = devices.Where(i => GetCapabilities(i.Id).SupportsSync == val);
  85. }
  86. if (query.SupportsPersistentIdentifier.HasValue)
  87. {
  88. var val = query.SupportsPersistentIdentifier.Value;
  89. devices = devices.Where(i =>
  90. {
  91. var caps = GetCapabilities(i.Id);
  92. var deviceVal = caps.SupportsPersistentIdentifier;
  93. return deviceVal == val;
  94. });
  95. }
  96. if (!string.IsNullOrWhiteSpace(query.UserId))
  97. {
  98. devices = devices.Where(i => CanAccessDevice(query.UserId, i.Id));
  99. }
  100. var array = devices.ToArray();
  101. return new QueryResult<DeviceInfo>
  102. {
  103. Items = array,
  104. TotalRecordCount = array.Length
  105. };
  106. }
  107. public Task DeleteDevice(string id)
  108. {
  109. return _repo.DeleteDevice(id);
  110. }
  111. public ContentUploadHistory GetCameraUploadHistory(string deviceId)
  112. {
  113. return _repo.GetCameraUploadHistory(deviceId);
  114. }
  115. public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
  116. {
  117. var device = GetDevice(deviceId);
  118. var path = GetUploadPath(device);
  119. if (!string.IsNullOrWhiteSpace(file.Album))
  120. {
  121. path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
  122. }
  123. Directory.CreateDirectory(path);
  124. path = Path.Combine(path, file.Name);
  125. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  126. try
  127. {
  128. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  129. {
  130. await stream.CopyToAsync(fs).ConfigureAwait(false);
  131. }
  132. _repo.AddCameraUpload(deviceId, file);
  133. }
  134. finally
  135. {
  136. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  137. }
  138. if (CameraImageUploaded != null)
  139. {
  140. EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
  141. {
  142. Argument = new CameraImageUploadInfo
  143. {
  144. Device = device,
  145. FileInfo = file
  146. }
  147. }, _logger);
  148. }
  149. }
  150. private string GetUploadPath(string deviceId)
  151. {
  152. return GetUploadPath(GetDevice(deviceId));
  153. }
  154. private string GetUploadPath(DeviceInfo device)
  155. {
  156. if (!string.IsNullOrWhiteSpace(device.CameraUploadPath))
  157. {
  158. return device.CameraUploadPath;
  159. }
  160. var config = _config.GetUploadOptions();
  161. if (!string.IsNullOrWhiteSpace(config.CameraUploadPath))
  162. {
  163. return config.CameraUploadPath;
  164. }
  165. var path = Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads");
  166. if (config.EnableCameraUploadSubfolders)
  167. {
  168. path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
  169. }
  170. return path;
  171. }
  172. public async Task UpdateDeviceInfo(string id, DeviceOptions options)
  173. {
  174. var device = GetDevice(id);
  175. device.CustomName = options.CustomName;
  176. device.CameraUploadPath = options.CameraUploadPath;
  177. await _repo.SaveDevice(device).ConfigureAwait(false);
  178. EventHelper.FireEventIfNotNull(DeviceOptionsUpdated, this, new GenericEventArgs<DeviceInfo>(device), _logger);
  179. }
  180. public bool CanAccessDevice(string userId, string deviceId)
  181. {
  182. if (string.IsNullOrWhiteSpace(userId))
  183. {
  184. throw new ArgumentNullException("userId");
  185. }
  186. if (string.IsNullOrWhiteSpace(deviceId))
  187. {
  188. throw new ArgumentNullException("deviceId");
  189. }
  190. var user = _userManager.GetUserById(userId);
  191. if (user == null)
  192. {
  193. throw new ArgumentException("user not found");
  194. }
  195. if (!CanAccessDevice(user.Policy, deviceId))
  196. {
  197. var capabilities = GetCapabilities(deviceId);
  198. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  199. {
  200. return false;
  201. }
  202. }
  203. return true;
  204. }
  205. private bool CanAccessDevice(UserPolicy policy, string id)
  206. {
  207. if (policy.EnableAllDevices)
  208. {
  209. return true;
  210. }
  211. return ListHelper.ContainsIgnoreCase(policy.EnabledDevices, id);
  212. }
  213. }
  214. public class DevicesConfigStore : IConfigurationFactory
  215. {
  216. public IEnumerable<ConfigurationStore> GetConfigurations()
  217. {
  218. return new List<ConfigurationStore>
  219. {
  220. new ConfigurationStore
  221. {
  222. Key = "devices",
  223. ConfigurationType = typeof(DevicesOptions)
  224. }
  225. };
  226. }
  227. }
  228. public static class UploadConfigExtension
  229. {
  230. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  231. {
  232. return config.GetConfiguration<DevicesOptions>("devices");
  233. }
  234. }
  235. }