CollectionManager.cs 11 KB

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