CollectionManager.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Collections;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Providers;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MoreLinq;
  14. namespace MediaBrowser.Server.Implementations.Collections
  15. {
  16. public class CollectionManager : ICollectionManager
  17. {
  18. private readonly ILibraryManager _libraryManager;
  19. private readonly IFileSystem _fileSystem;
  20. private readonly ILibraryMonitor _iLibraryMonitor;
  21. public CollectionManager(ILibraryManager libraryManager, IFileSystem fileSystem, ILibraryMonitor iLibraryMonitor)
  22. {
  23. _libraryManager = libraryManager;
  24. _fileSystem = fileSystem;
  25. _iLibraryMonitor = iLibraryMonitor;
  26. }
  27. public async Task<BoxSet> CreateCollection(CollectionCreationOptions options)
  28. {
  29. var name = options.Name;
  30. // Need to use the [boxset] suffix
  31. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  32. // This could cause it to get re-resolved as a plain folder
  33. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  34. var parentFolder = GetParentFolder(options.ParentId);
  35. if (parentFolder == null)
  36. {
  37. throw new ArgumentException();
  38. }
  39. var path = Path.Combine(parentFolder.Path, folderName);
  40. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  41. try
  42. {
  43. Directory.CreateDirectory(path);
  44. var collection = new BoxSet
  45. {
  46. Name = name,
  47. Parent = parentFolder,
  48. DisplayMediaType = "Collection",
  49. Path = path,
  50. IsLocked = options.IsLocked,
  51. ProviderIds = options.ProviderIds
  52. };
  53. await parentFolder.AddChild(collection, CancellationToken.None).ConfigureAwait(false);
  54. await collection.RefreshMetadata(new MetadataRefreshOptions(), CancellationToken.None)
  55. .ConfigureAwait(false);
  56. if (options.ItemIdList.Count > 0)
  57. {
  58. await AddToCollection(collection.Id, options.ItemIdList);
  59. }
  60. return collection;
  61. }
  62. finally
  63. {
  64. // Refresh handled internally
  65. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  66. }
  67. }
  68. private Folder GetParentFolder(Guid? parentId)
  69. {
  70. if (parentId.HasValue)
  71. {
  72. if (parentId.Value == Guid.Empty)
  73. {
  74. throw new ArgumentNullException("parentId");
  75. }
  76. var folder = _libraryManager.GetItemById(parentId.Value) as Folder;
  77. // Find an actual physical folder
  78. if (folder is CollectionFolder)
  79. {
  80. var child = _libraryManager.RootFolder.Children.OfType<Folder>()
  81. .FirstOrDefault(i => folder.PhysicalLocations.Contains(i.Path, StringComparer.OrdinalIgnoreCase));
  82. if (child != null)
  83. {
  84. return child;
  85. }
  86. }
  87. }
  88. return _libraryManager.RootFolder.Children.OfType<ManualCollectionsFolder>().FirstOrDefault() ??
  89. _libraryManager.RootFolder.GetHiddenChildren().OfType<ManualCollectionsFolder>().FirstOrDefault();
  90. }
  91. public async Task AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  92. {
  93. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  94. if (collection == null)
  95. {
  96. throw new ArgumentException("No collection exists with the supplied Id");
  97. }
  98. var list = new List<LinkedChild>();
  99. var currentLinkedChildren = collection.GetLinkedChildren().ToList();
  100. foreach (var itemId in ids)
  101. {
  102. var item = _libraryManager.GetItemById(itemId);
  103. if (item == null)
  104. {
  105. throw new ArgumentException("No item exists with the supplied Id");
  106. }
  107. if (currentLinkedChildren.Any(i => i.Id == itemId))
  108. {
  109. throw new ArgumentException("Item already exists in collection");
  110. }
  111. list.Add(new LinkedChild
  112. {
  113. ItemName = item.Name,
  114. ItemYear = item.ProductionYear,
  115. ItemType = item.GetType().Name,
  116. Type = LinkedChildType.Manual
  117. });
  118. var supportsGrouping = item as ISupportsBoxSetGrouping;
  119. if (supportsGrouping != null)
  120. {
  121. var boxsetIdList = supportsGrouping.BoxSetIdList.ToList();
  122. if (!boxsetIdList.Contains(collectionId))
  123. {
  124. boxsetIdList.Add(collectionId);
  125. }
  126. supportsGrouping.BoxSetIdList = boxsetIdList;
  127. }
  128. }
  129. collection.LinkedChildren.AddRange(list);
  130. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  131. await collection.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  132. }
  133. public async Task RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  134. {
  135. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  136. if (collection == null)
  137. {
  138. throw new ArgumentException("No collection exists with the supplied Id");
  139. }
  140. var list = new List<LinkedChild>();
  141. foreach (var itemId in itemIds)
  142. {
  143. var child = collection.LinkedChildren.FirstOrDefault(i => i.ItemId.HasValue && i.ItemId.Value == itemId);
  144. if (child == null)
  145. {
  146. throw new ArgumentException("No collection title exists with the supplied Id");
  147. }
  148. list.Add(child);
  149. var childItem = _libraryManager.GetItemById(itemId);
  150. var supportsGrouping = childItem as ISupportsBoxSetGrouping;
  151. if (supportsGrouping != null)
  152. {
  153. var boxsetIdList = supportsGrouping.BoxSetIdList.ToList();
  154. boxsetIdList.Remove(collectionId);
  155. supportsGrouping.BoxSetIdList = boxsetIdList;
  156. }
  157. }
  158. var shortcutFiles = Directory
  159. .EnumerateFiles(collection.Path, "*", SearchOption.TopDirectoryOnly)
  160. .Where(i => _fileSystem.IsShortcut(i))
  161. .ToList();
  162. var shortcutFilesToDelete = list.Where(child => !string.IsNullOrWhiteSpace(child.Path) && child.Type == LinkedChildType.Shortcut)
  163. .Select(child => shortcutFiles.FirstOrDefault(i => string.Equals(child.Path, _fileSystem.ResolveShortcut(i), StringComparison.OrdinalIgnoreCase)))
  164. .Where(i => !string.IsNullOrWhiteSpace(i))
  165. .ToList();
  166. foreach (var file in shortcutFilesToDelete)
  167. {
  168. _iLibraryMonitor.ReportFileSystemChangeBeginning(file);
  169. }
  170. try
  171. {
  172. foreach (var file in shortcutFilesToDelete)
  173. {
  174. File.Delete(file);
  175. }
  176. foreach (var child in list)
  177. {
  178. collection.LinkedChildren.Remove(child);
  179. }
  180. }
  181. finally
  182. {
  183. foreach (var file in shortcutFilesToDelete)
  184. {
  185. _iLibraryMonitor.ReportFileSystemChangeComplete(file, false);
  186. }
  187. }
  188. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  189. await collection.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  190. }
  191. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  192. {
  193. var itemsToCollapse = new List<ISupportsBoxSetGrouping>();
  194. var boxsets = new List<BaseItem>();
  195. var list = items.ToList();
  196. foreach (var item in list.OfType<ISupportsBoxSetGrouping>())
  197. {
  198. var currentBoxSets = item.BoxSetIdList
  199. .Select(i => _libraryManager.GetItemById(i))
  200. .Where(i => i != null && i.IsVisible(user))
  201. .ToList();
  202. if (currentBoxSets.Count > 0)
  203. {
  204. itemsToCollapse.Add(item);
  205. boxsets.AddRange(currentBoxSets);
  206. }
  207. }
  208. return list
  209. .Except(itemsToCollapse.Cast<BaseItem>())
  210. .Concat(boxsets)
  211. .DistinctBy(i => i.Id);
  212. }
  213. }
  214. }