CollectionManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Collections;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Entities.Movies;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Plugins;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.Globalization;
  19. using MediaBrowser.Model.IO;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.Collections
  22. {
  23. /// <summary>
  24. /// The collection manager.
  25. /// </summary>
  26. public class CollectionManager : ICollectionManager
  27. {
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly ILibraryMonitor _iLibraryMonitor;
  31. private readonly ILogger _logger;
  32. private readonly IProviderManager _providerManager;
  33. private readonly ILocalizationManager _localizationManager;
  34. private readonly IApplicationPaths _appPaths;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="CollectionManager"/> class.
  37. /// </summary>
  38. /// <param name="libraryManager">The library manager.</param>
  39. /// <param name="appPaths">The application paths.</param>
  40. /// <param name="localizationManager">The localization manager.</param>
  41. /// <param name="fileSystem">The filesystem.</param>
  42. /// <param name="iLibraryMonitor">The library monitor.</param>
  43. /// <param name="loggerFactory">The logger factory.</param>
  44. /// <param name="providerManager">The provider manager.</param>
  45. public CollectionManager(
  46. ILibraryManager libraryManager,
  47. IApplicationPaths appPaths,
  48. ILocalizationManager localizationManager,
  49. IFileSystem fileSystem,
  50. ILibraryMonitor iLibraryMonitor,
  51. ILoggerFactory loggerFactory,
  52. IProviderManager providerManager)
  53. {
  54. _libraryManager = libraryManager;
  55. _fileSystem = fileSystem;
  56. _iLibraryMonitor = iLibraryMonitor;
  57. _logger = loggerFactory.CreateLogger(nameof(CollectionManager));
  58. _providerManager = providerManager;
  59. _localizationManager = localizationManager;
  60. _appPaths = appPaths;
  61. }
  62. /// <inheritdoc />
  63. public event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
  64. /// <inheritdoc />
  65. public event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
  66. /// <inheritdoc />
  67. public event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
  68. private IEnumerable<Folder> FindFolders(string path)
  69. {
  70. return _libraryManager
  71. .RootFolder
  72. .Children
  73. .OfType<Folder>()
  74. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path));
  75. }
  76. internal async Task<Folder> EnsureLibraryFolder(string path, bool createIfNeeded)
  77. {
  78. var existingFolders = FindFolders(path)
  79. .ToList();
  80. if (existingFolders.Count > 0)
  81. {
  82. return existingFolders[0];
  83. }
  84. if (!createIfNeeded)
  85. {
  86. return null;
  87. }
  88. Directory.CreateDirectory(path);
  89. var libraryOptions = new LibraryOptions
  90. {
  91. PathInfos = new[] { new MediaPathInfo { Path = path } },
  92. EnableRealtimeMonitor = false,
  93. SaveLocalMetadata = true
  94. };
  95. var name = _localizationManager.GetLocalizedString("Collections");
  96. await _libraryManager.AddVirtualFolder(name, CollectionType.BoxSets, libraryOptions, true).ConfigureAwait(false);
  97. return FindFolders(path).First();
  98. }
  99. internal string GetCollectionsFolderPath()
  100. {
  101. return Path.Combine(_appPaths.DataPath, "collections");
  102. }
  103. private Task<Folder> GetCollectionsFolder(bool createIfNeeded)
  104. {
  105. return EnsureLibraryFolder(GetCollectionsFolderPath(), createIfNeeded);
  106. }
  107. private IEnumerable<BoxSet> GetCollections(User user)
  108. {
  109. var folder = GetCollectionsFolder(false).Result;
  110. return folder == null
  111. ? Enumerable.Empty<BoxSet>()
  112. : folder.GetChildren(user, true).OfType<BoxSet>();
  113. }
  114. /// <inheritdoc />
  115. public BoxSet CreateCollection(CollectionCreationOptions options)
  116. {
  117. var name = options.Name;
  118. // Need to use the [boxset] suffix
  119. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  120. // This could cause it to get re-resolved as a plain folder
  121. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  122. var parentFolder = GetCollectionsFolder(true).GetAwaiter().GetResult();
  123. if (parentFolder == null)
  124. {
  125. throw new ArgumentException();
  126. }
  127. var path = Path.Combine(parentFolder.Path, folderName);
  128. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  129. try
  130. {
  131. Directory.CreateDirectory(path);
  132. var collection = new BoxSet
  133. {
  134. Name = name,
  135. Path = path,
  136. IsLocked = options.IsLocked,
  137. ProviderIds = options.ProviderIds,
  138. DateCreated = DateTime.UtcNow
  139. };
  140. parentFolder.AddChild(collection, CancellationToken.None);
  141. if (options.ItemIdList.Length > 0)
  142. {
  143. AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  144. {
  145. // The initial adding of items is going to create a local metadata file
  146. // This will cause internet metadata to be skipped as a result
  147. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  148. });
  149. }
  150. else
  151. {
  152. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  153. }
  154. CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
  155. {
  156. Collection = collection,
  157. Options = options
  158. });
  159. return collection;
  160. }
  161. finally
  162. {
  163. // Refresh handled internally
  164. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  165. }
  166. }
  167. /// <inheritdoc />
  168. public void AddToCollection(Guid collectionId, IEnumerable<string> ids)
  169. {
  170. AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  171. }
  172. /// <inheritdoc />
  173. public void AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  174. {
  175. AddToCollection(collectionId, ids.Select(i => i.ToString("N", CultureInfo.InvariantCulture)), true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  176. }
  177. private void AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  178. {
  179. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  180. if (collection == null)
  181. {
  182. throw new ArgumentException("No collection exists with the supplied Id");
  183. }
  184. var list = new List<LinkedChild>();
  185. var itemList = new List<BaseItem>();
  186. var linkedChildrenList = collection.GetLinkedChildren();
  187. var currentLinkedChildrenIds = linkedChildrenList.Select(i => i.Id).ToList();
  188. foreach (var id in ids)
  189. {
  190. var guidId = new Guid(id);
  191. var item = _libraryManager.GetItemById(guidId);
  192. if (item == null)
  193. {
  194. throw new ArgumentException("No item exists with the supplied Id");
  195. }
  196. if (!currentLinkedChildrenIds.Contains(guidId))
  197. {
  198. itemList.Add(item);
  199. list.Add(LinkedChild.Create(item));
  200. linkedChildrenList.Add(item);
  201. }
  202. }
  203. if (list.Count > 0)
  204. {
  205. var newList = collection.LinkedChildren.ToList();
  206. newList.AddRange(list);
  207. collection.LinkedChildren = newList.ToArray();
  208. collection.UpdateRatingToItems(linkedChildrenList);
  209. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  210. refreshOptions.ForceSave = true;
  211. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  212. if (fireEvent)
  213. {
  214. ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
  215. {
  216. Collection = collection,
  217. ItemsChanged = itemList
  218. });
  219. }
  220. }
  221. }
  222. /// <inheritdoc />
  223. public void RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds)
  224. {
  225. RemoveFromCollection(collectionId, itemIds.Select(i => new Guid(i)));
  226. }
  227. /// <inheritdoc />
  228. public void RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  229. {
  230. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  231. if (collection == null)
  232. {
  233. throw new ArgumentException("No collection exists with the supplied Id");
  234. }
  235. var list = new List<LinkedChild>();
  236. var itemList = new List<BaseItem>();
  237. foreach (var guidId in itemIds)
  238. {
  239. var childItem = _libraryManager.GetItemById(guidId);
  240. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  241. if (child == null)
  242. {
  243. _logger.LogWarning("No collection title exists with the supplied Id");
  244. continue;
  245. }
  246. list.Add(child);
  247. if (childItem != null)
  248. {
  249. itemList.Add(childItem);
  250. }
  251. }
  252. if (list.Count > 0)
  253. {
  254. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  255. }
  256. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  257. _providerManager.QueueRefresh(
  258. collection.Id,
  259. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  260. {
  261. ForceSave = true
  262. },
  263. RefreshPriority.High);
  264. ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
  265. {
  266. Collection = collection,
  267. ItemsChanged = itemList
  268. });
  269. }
  270. /// <inheritdoc />
  271. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  272. {
  273. var results = new Dictionary<Guid, BaseItem>();
  274. var allBoxsets = GetCollections(user).ToList();
  275. foreach (var item in items)
  276. {
  277. if (!(item is ISupportsBoxSetGrouping))
  278. {
  279. results[item.Id] = item;
  280. }
  281. else
  282. {
  283. var itemId = item.Id;
  284. var currentBoxSets = allBoxsets
  285. .Where(i => i.ContainsLinkedChildByItemId(itemId))
  286. .ToList();
  287. if (currentBoxSets.Count > 0)
  288. {
  289. foreach (var boxset in currentBoxSets)
  290. {
  291. results[boxset.Id] = boxset;
  292. }
  293. }
  294. else
  295. {
  296. results[item.Id] = item;
  297. }
  298. }
  299. }
  300. return results.Values;
  301. }
  302. }
  303. /// <summary>
  304. /// The collection manager entry point.
  305. /// </summary>
  306. public sealed class CollectionManagerEntryPoint : IServerEntryPoint
  307. {
  308. private readonly CollectionManager _collectionManager;
  309. private readonly IServerConfigurationManager _config;
  310. private readonly ILogger _logger;
  311. /// <summary>
  312. /// Initializes a new instance of the <see cref="CollectionManagerEntryPoint"/> class.
  313. /// </summary>
  314. /// <param name="collectionManager">The collection manager.</param>
  315. /// <param name="config">The server configuration manager.</param>
  316. /// <param name="logger">The logger.</param>
  317. public CollectionManagerEntryPoint(
  318. ICollectionManager collectionManager,
  319. IServerConfigurationManager config,
  320. ILogger<CollectionManagerEntryPoint> logger)
  321. {
  322. _collectionManager = (CollectionManager)collectionManager;
  323. _config = config;
  324. _logger = logger;
  325. }
  326. /// <inheritdoc />
  327. public async Task RunAsync()
  328. {
  329. if (!_config.Configuration.CollectionsUpgraded && _config.Configuration.IsStartupWizardCompleted)
  330. {
  331. var path = _collectionManager.GetCollectionsFolderPath();
  332. if (Directory.Exists(path))
  333. {
  334. try
  335. {
  336. await _collectionManager.EnsureLibraryFolder(path, true).ConfigureAwait(false);
  337. }
  338. catch (Exception ex)
  339. {
  340. _logger.LogError(ex, "Error creating camera uploads library");
  341. }
  342. _config.Configuration.CollectionsUpgraded = true;
  343. _config.SaveConfiguration();
  344. }
  345. }
  346. }
  347. /// <inheritdoc />
  348. public void Dispose()
  349. {
  350. // Nothing to dispose
  351. }
  352. }
  353. }