DeviceManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. using CommonIO;
  21. using MediaBrowser.Controller.Configuration;
  22. using MediaBrowser.Controller.Plugins;
  23. using MediaBrowser.Model.Entities;
  24. namespace MediaBrowser.Server.Implementations.Devices
  25. {
  26. public class DeviceManager : IDeviceManager
  27. {
  28. private readonly IDeviceRepository _repo;
  29. private readonly IUserManager _userManager;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly ILibraryMonitor _libraryMonitor;
  32. private readonly IServerConfigurationManager _config;
  33. private readonly ILogger _logger;
  34. private readonly INetworkManager _network;
  35. public event EventHandler<GenericEventArgs<CameraImageUploadInfo>> CameraImageUploaded;
  36. /// <summary>
  37. /// Occurs when [device options updated].
  38. /// </summary>
  39. public event EventHandler<GenericEventArgs<DeviceInfo>> DeviceOptionsUpdated;
  40. public DeviceManager(IDeviceRepository repo, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network)
  41. {
  42. _repo = repo;
  43. _userManager = userManager;
  44. _fileSystem = fileSystem;
  45. _libraryMonitor = libraryMonitor;
  46. _config = config;
  47. _logger = logger;
  48. _network = network;
  49. }
  50. public async Task<DeviceInfo> RegisterDevice(string reportedId, string name, string appName, string appVersion, string usedByUserId)
  51. {
  52. var device = GetDevice(reportedId) ?? new DeviceInfo
  53. {
  54. Id = reportedId
  55. };
  56. device.ReportedName = name;
  57. device.AppName = appName;
  58. device.AppVersion = appVersion;
  59. if (!string.IsNullOrWhiteSpace(usedByUserId))
  60. {
  61. var user = _userManager.GetUserById(usedByUserId);
  62. device.LastUserId = user.Id.ToString("N");
  63. device.LastUserName = user.Name;
  64. }
  65. device.DateLastModified = DateTime.UtcNow;
  66. await _repo.SaveDevice(device).ConfigureAwait(false);
  67. return device;
  68. }
  69. public Task SaveCapabilities(string reportedId, ClientCapabilities capabilities)
  70. {
  71. return _repo.SaveCapabilities(reportedId, capabilities);
  72. }
  73. public ClientCapabilities GetCapabilities(string reportedId)
  74. {
  75. return _repo.GetCapabilities(reportedId);
  76. }
  77. public DeviceInfo GetDevice(string id)
  78. {
  79. return _repo.GetDevice(id);
  80. }
  81. public QueryResult<DeviceInfo> GetDevices(DeviceQuery query)
  82. {
  83. IEnumerable<DeviceInfo> devices = _repo.GetDevices().OrderByDescending(i => i.DateLastModified);
  84. if (query.SupportsContentUploading.HasValue)
  85. {
  86. var val = query.SupportsContentUploading.Value;
  87. devices = devices.Where(i => GetCapabilities(i.Id).SupportsContentUploading == val);
  88. }
  89. if (query.SupportsSync.HasValue)
  90. {
  91. var val = query.SupportsSync.Value;
  92. devices = devices.Where(i => GetCapabilities(i.Id).SupportsSync == val);
  93. }
  94. if (query.SupportsPersistentIdentifier.HasValue)
  95. {
  96. var val = query.SupportsPersistentIdentifier.Value;
  97. devices = devices.Where(i =>
  98. {
  99. var caps = GetCapabilities(i.Id);
  100. var deviceVal = caps.SupportsPersistentIdentifier;
  101. return deviceVal == val;
  102. });
  103. }
  104. if (!string.IsNullOrWhiteSpace(query.UserId))
  105. {
  106. devices = devices.Where(i => CanAccessDevice(query.UserId, i.Id));
  107. }
  108. var array = devices.ToArray();
  109. return new QueryResult<DeviceInfo>
  110. {
  111. Items = array,
  112. TotalRecordCount = array.Length
  113. };
  114. }
  115. public Task DeleteDevice(string id)
  116. {
  117. return _repo.DeleteDevice(id);
  118. }
  119. public ContentUploadHistory GetCameraUploadHistory(string deviceId)
  120. {
  121. return _repo.GetCameraUploadHistory(deviceId);
  122. }
  123. public async Task AcceptCameraUpload(string deviceId, Stream stream, LocalFileInfo file)
  124. {
  125. var device = GetDevice(deviceId);
  126. var path = GetUploadPath(device);
  127. if (!string.IsNullOrWhiteSpace(file.Album))
  128. {
  129. path = Path.Combine(path, _fileSystem.GetValidFilename(file.Album));
  130. }
  131. path = Path.Combine(path, file.Name);
  132. path = Path.ChangeExtension(path, MimeTypes.ToExtension(file.MimeType) ?? "jpg");
  133. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  134. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  135. try
  136. {
  137. using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
  138. {
  139. await stream.CopyToAsync(fs).ConfigureAwait(false);
  140. }
  141. _repo.AddCameraUpload(deviceId, file);
  142. }
  143. finally
  144. {
  145. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  146. }
  147. if (CameraImageUploaded != null)
  148. {
  149. EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
  150. {
  151. Argument = new CameraImageUploadInfo
  152. {
  153. Device = device,
  154. FileInfo = file
  155. }
  156. }, _logger);
  157. }
  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 = DefaultCameraUploadsPath;
  171. if (config.EnableCameraUploadSubfolders)
  172. {
  173. path = Path.Combine(path, _fileSystem.GetValidFilename(device.Name));
  174. }
  175. EnsureMediaLibrarySetup();
  176. return path;
  177. }
  178. private string DefaultCameraUploadsPath
  179. {
  180. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); }
  181. }
  182. internal void EnsureMediaLibrarySetup()
  183. {
  184. //EnsureMediaLibrarySetup(DefaultCameraUploadsPath, false);
  185. }
  186. private void EnsureMediaLibrarySetup(string libraryPath, bool force)
  187. {
  188. var requiresSetup = false;
  189. var path = Path.Combine(_config.ApplicationPaths.DefaultUserViewsPath, "Camera Uploads");
  190. var collectionMarkerFile = Path.Combine(path, CollectionType.Photos + ".collection");
  191. if (!_fileSystem.FileExists(collectionMarkerFile))
  192. {
  193. requiresSetup = true;
  194. }
  195. var shortcutFile = Path.Combine(path, "camerauploads.mblink");
  196. try
  197. {
  198. if (!string.Equals(_fileSystem.ReadAllText(shortcutFile), libraryPath))
  199. {
  200. requiresSetup = true;
  201. }
  202. }
  203. catch
  204. {
  205. requiresSetup = true;
  206. }
  207. if (requiresSetup)
  208. {
  209. if (!force)
  210. {
  211. var extensions = new[] { ".jpg", ".png" };
  212. var hasPhotos = _fileSystem.GetFiles(libraryPath, true).Any(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase));
  213. // Nothing to do
  214. if (!hasPhotos)
  215. {
  216. return;
  217. }
  218. }
  219. }
  220. if (requiresSetup)
  221. {
  222. Directory.CreateDirectory(path);
  223. using (File.Create(collectionMarkerFile))
  224. {
  225. }
  226. _fileSystem.CreateShortcut(shortcutFile, libraryPath);
  227. }
  228. }
  229. public async Task UpdateDeviceInfo(string id, DeviceOptions options)
  230. {
  231. var device = GetDevice(id);
  232. device.CustomName = options.CustomName;
  233. device.CameraUploadPath = options.CameraUploadPath;
  234. await _repo.SaveDevice(device).ConfigureAwait(false);
  235. EventHelper.FireEventIfNotNull(DeviceOptionsUpdated, this, new GenericEventArgs<DeviceInfo>(device), _logger);
  236. }
  237. public bool CanAccessDevice(string userId, string deviceId)
  238. {
  239. if (string.IsNullOrWhiteSpace(userId))
  240. {
  241. throw new ArgumentNullException("userId");
  242. }
  243. if (string.IsNullOrWhiteSpace(deviceId))
  244. {
  245. throw new ArgumentNullException("deviceId");
  246. }
  247. var user = _userManager.GetUserById(userId);
  248. if (user == null)
  249. {
  250. throw new ArgumentException("user not found");
  251. }
  252. if (!CanAccessDevice(user.Policy, deviceId))
  253. {
  254. var capabilities = GetCapabilities(deviceId);
  255. if (capabilities != null && capabilities.SupportsPersistentIdentifier)
  256. {
  257. return false;
  258. }
  259. }
  260. return true;
  261. }
  262. private bool CanAccessDevice(UserPolicy policy, string id)
  263. {
  264. if (policy.EnableAllDevices)
  265. {
  266. return true;
  267. }
  268. if (policy.IsAdministrator)
  269. {
  270. return true;
  271. }
  272. return ListHelper.ContainsIgnoreCase(policy.EnabledDevices, id);
  273. }
  274. }
  275. public class DeviceManagerEntryPoint : IServerEntryPoint
  276. {
  277. private readonly IDeviceManager _deviceManager;
  278. public DeviceManagerEntryPoint(IDeviceManager deviceManager)
  279. {
  280. _deviceManager = deviceManager;
  281. }
  282. public void Run()
  283. {
  284. ((DeviceManager)_deviceManager).EnsureMediaLibrarySetup();
  285. }
  286. public void Dispose()
  287. {
  288. }
  289. }
  290. public class DevicesConfigStore : IConfigurationFactory
  291. {
  292. public IEnumerable<ConfigurationStore> GetConfigurations()
  293. {
  294. return new List<ConfigurationStore>
  295. {
  296. new ConfigurationStore
  297. {
  298. Key = "devices",
  299. ConfigurationType = typeof(DevicesOptions)
  300. }
  301. };
  302. }
  303. }
  304. public static class UploadConfigExtension
  305. {
  306. public static DevicesOptions GetUploadOptions(this IConfigurationManager config)
  307. {
  308. return config.GetConfiguration<DevicesOptions>("devices");
  309. }
  310. }
  311. }