DeviceManager.cs 9.5 KB

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