CollectionManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using MediaBrowser.Common.Events;
  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 MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Extensions;
  16. namespace Emby.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. private readonly IProviderManager _providerManager;
  25. public event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
  26. public event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
  27. public event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
  28. public CollectionManager(ILibraryManager libraryManager, IFileSystem fileSystem, ILibraryMonitor iLibraryMonitor, ILogger logger, IProviderManager providerManager)
  29. {
  30. _libraryManager = libraryManager;
  31. _fileSystem = fileSystem;
  32. _iLibraryMonitor = iLibraryMonitor;
  33. _logger = logger;
  34. _providerManager = providerManager;
  35. }
  36. public Folder GetCollectionsFolder(string userId)
  37. {
  38. return _libraryManager.RootFolder.Children.OfType<ManualCollectionsFolder>()
  39. .FirstOrDefault() ?? _libraryManager.GetUserRootFolder().Children.OfType<ManualCollectionsFolder>()
  40. .FirstOrDefault();
  41. }
  42. public IEnumerable<BoxSet> GetCollections(User user)
  43. {
  44. var folder = GetCollectionsFolder(user.Id.ToString("N"));
  45. return folder == null ?
  46. new List<BoxSet>() :
  47. folder.GetChildren(user, true).OfType<BoxSet>();
  48. }
  49. public async Task<BoxSet> CreateCollection(CollectionCreationOptions options)
  50. {
  51. var name = options.Name;
  52. // Need to use the [boxset] suffix
  53. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  54. // This could cause it to get re-resolved as a plain folder
  55. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  56. var parentFolder = GetParentFolder(options.ParentId);
  57. if (parentFolder == null)
  58. {
  59. throw new ArgumentException();
  60. }
  61. var path = Path.Combine(parentFolder.Path, folderName);
  62. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  63. try
  64. {
  65. _fileSystem.CreateDirectory(path);
  66. var collection = new BoxSet
  67. {
  68. Name = name,
  69. Path = path,
  70. IsLocked = options.IsLocked,
  71. ProviderIds = options.ProviderIds,
  72. Shares = options.UserIds.Select(i => new Share
  73. {
  74. UserId = i,
  75. CanEdit = true
  76. }).ToList()
  77. };
  78. await parentFolder.AddChild(collection, CancellationToken.None).ConfigureAwait(false);
  79. if (options.ItemIdList.Length > 0)
  80. {
  81. await AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(_fileSystem)
  82. {
  83. // The initial adding of items is going to create a local metadata file
  84. // This will cause internet metadata to be skipped as a result
  85. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  86. });
  87. }
  88. else
  89. {
  90. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High);
  91. }
  92. EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs
  93. {
  94. Collection = collection,
  95. Options = options
  96. }, _logger);
  97. return collection;
  98. }
  99. finally
  100. {
  101. // Refresh handled internally
  102. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  103. }
  104. }
  105. private Folder GetParentFolder(Guid? parentId)
  106. {
  107. if (parentId.HasValue)
  108. {
  109. if (parentId.Value == Guid.Empty)
  110. {
  111. throw new ArgumentNullException("parentId");
  112. }
  113. var folder = _libraryManager.GetItemById(parentId.Value) as Folder;
  114. // Find an actual physical folder
  115. if (folder is CollectionFolder)
  116. {
  117. var child = _libraryManager.RootFolder.Children.OfType<Folder>()
  118. .FirstOrDefault(i => folder.PhysicalLocations.Contains(i.Path, StringComparer.OrdinalIgnoreCase));
  119. if (child != null)
  120. {
  121. return child;
  122. }
  123. }
  124. }
  125. return GetCollectionsFolder(string.Empty);
  126. }
  127. public Task AddToCollection(Guid collectionId, string[] ids)
  128. {
  129. return AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(_fileSystem));
  130. }
  131. private async Task AddToCollection(Guid collectionId, string[] ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  132. {
  133. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  134. if (collection == null)
  135. {
  136. throw new ArgumentException("No collection exists with the supplied Id");
  137. }
  138. var list = new List<LinkedChild>();
  139. var itemList = new List<BaseItem>();
  140. var currentLinkedChildrenIds = collection.GetLinkedChildren().Select(i => i.Id).ToList();
  141. foreach (var itemId in ids)
  142. {
  143. var guidId = new Guid(itemId);
  144. var item = _libraryManager.GetItemById(guidId);
  145. if (string.IsNullOrWhiteSpace(item.Path))
  146. {
  147. continue;
  148. }
  149. if (item == null)
  150. {
  151. throw new ArgumentException("No item exists with the supplied Id");
  152. }
  153. itemList.Add(item);
  154. if (!currentLinkedChildrenIds.Contains(guidId))
  155. {
  156. list.Add(LinkedChild.Create(item));
  157. }
  158. }
  159. if (list.Count > 0)
  160. {
  161. var newList = collection.LinkedChildren.ToList();
  162. newList.AddRange(list);
  163. collection.LinkedChildren = newList.ToArray(newList.Count);
  164. collection.UpdateRatingToContent();
  165. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  166. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  167. if (fireEvent)
  168. {
  169. EventHelper.FireEventIfNotNull(ItemsAddedToCollection, this, new CollectionModifiedEventArgs
  170. {
  171. Collection = collection,
  172. ItemsChanged = itemList
  173. }, _logger);
  174. }
  175. }
  176. }
  177. public async Task RemoveFromCollection(Guid collectionId, string[] itemIds)
  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. foreach (var itemId in itemIds)
  187. {
  188. var guidId = new Guid(itemId);
  189. var childItem = _libraryManager.GetItemById(guidId);
  190. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  191. if (child == null)
  192. {
  193. throw new ArgumentException("No collection title exists with the supplied Id");
  194. }
  195. list.Add(child);
  196. if (childItem != null)
  197. {
  198. itemList.Add(childItem);
  199. }
  200. }
  201. if (list.Count > 0)
  202. {
  203. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  204. }
  205. collection.UpdateRatingToContent();
  206. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  207. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High);
  208. EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
  209. {
  210. Collection = collection,
  211. ItemsChanged = itemList
  212. }, _logger);
  213. }
  214. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  215. {
  216. var results = new Dictionary<Guid, BaseItem>();
  217. var allBoxsets = GetCollections(user).ToList();
  218. foreach (var item in items)
  219. {
  220. var grouping = item as ISupportsBoxSetGrouping;
  221. if (grouping == null)
  222. {
  223. results[item.Id] = item;
  224. }
  225. else
  226. {
  227. var itemId = item.Id;
  228. var currentBoxSets = allBoxsets
  229. .Where(i => i.GetLinkedChildren().Any(j => j.Id == itemId))
  230. .ToList();
  231. if (currentBoxSets.Count > 0)
  232. {
  233. foreach (var boxset in currentBoxSets)
  234. {
  235. results[boxset.Id] = boxset;
  236. }
  237. }
  238. else
  239. {
  240. results[item.Id] = item;
  241. }
  242. }
  243. }
  244. return results.Values;
  245. }
  246. }
  247. }