DeviceManager.cs 9.2 KB

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