CollectionManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. parentFolder.AddChild(collection, CancellationToken.None);
  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, IEnumerable<string> ids)
  128. {
  129. return AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(_fileSystem));
  130. }
  131. public Task AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  132. {
  133. return AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(_fileSystem));
  134. }
  135. private async Task AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  136. {
  137. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  138. if (collection == null)
  139. {
  140. throw new ArgumentException("No collection exists with the supplied Id");
  141. }
  142. var list = new List<LinkedChild>();
  143. var itemList = new List<BaseItem>();
  144. var currentLinkedChildrenIds = collection.GetLinkedChildren().Select(i => i.Id).ToList();
  145. foreach (var id in ids)
  146. {
  147. var guidId = new Guid(id);
  148. var item = _libraryManager.GetItemById(guidId);
  149. if (string.IsNullOrWhiteSpace(item.Path))
  150. {
  151. continue;
  152. }
  153. if (item == null)
  154. {
  155. throw new ArgumentException("No item exists with the supplied Id");
  156. }
  157. itemList.Add(item);
  158. if (!currentLinkedChildrenIds.Contains(guidId))
  159. {
  160. list.Add(LinkedChild.Create(item));
  161. }
  162. }
  163. if (list.Count > 0)
  164. {
  165. var newList = collection.LinkedChildren.ToList();
  166. newList.AddRange(list);
  167. collection.LinkedChildren = newList.ToArray(newList.Count);
  168. collection.UpdateRatingToContent();
  169. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  170. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  171. if (fireEvent)
  172. {
  173. EventHelper.FireEventIfNotNull(ItemsAddedToCollection, this, new CollectionModifiedEventArgs
  174. {
  175. Collection = collection,
  176. ItemsChanged = itemList
  177. }, _logger);
  178. }
  179. }
  180. }
  181. public Task RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds)
  182. {
  183. return RemoveFromCollection(collectionId, itemIds.Select(i => new Guid(i)));
  184. }
  185. public async Task RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  186. {
  187. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  188. if (collection == null)
  189. {
  190. throw new ArgumentException("No collection exists with the supplied Id");
  191. }
  192. var list = new List<LinkedChild>();
  193. var itemList = new List<BaseItem>();
  194. foreach (var guidId in itemIds)
  195. {
  196. var childItem = _libraryManager.GetItemById(guidId);
  197. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  198. if (child == null)
  199. {
  200. throw new ArgumentException("No collection title exists with the supplied Id");
  201. }
  202. list.Add(child);
  203. if (childItem != null)
  204. {
  205. itemList.Add(childItem);
  206. }
  207. }
  208. if (list.Count > 0)
  209. {
  210. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  211. }
  212. collection.UpdateRatingToContent();
  213. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  214. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(_fileSystem), RefreshPriority.High);
  215. EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
  216. {
  217. Collection = collection,
  218. ItemsChanged = itemList
  219. }, _logger);
  220. }
  221. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  222. {
  223. var results = new Dictionary<Guid, BaseItem>();
  224. var allBoxsets = GetCollections(user).ToList();
  225. foreach (var item in items)
  226. {
  227. var grouping = item as ISupportsBoxSetGrouping;
  228. if (grouping == null)
  229. {
  230. results[item.Id] = item;
  231. }
  232. else
  233. {
  234. var itemId = item.Id;
  235. var currentBoxSets = allBoxsets
  236. .Where(i => i.GetLinkedChildren().Any(j => j.Id == itemId))
  237. .ToList();
  238. if (currentBoxSets.Count > 0)
  239. {
  240. foreach (var boxset in currentBoxSets)
  241. {
  242. results[boxset.Id] = boxset;
  243. }
  244. }
  245. else
  246. {
  247. results[item.Id] = item;
  248. }
  249. }
  250. }
  251. return results.Values;
  252. }
  253. }
  254. }