CollectionManager.cs 9.2 KB

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