DeviceManager.cs 9.3 KB

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