CollectionManager.cs 11 KB

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