CollectionManager.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. Path = path,
  61. IsLocked = options.IsLocked,
  62. ProviderIds = options.ProviderIds,
  63. Shares = options.UserIds.Select(i => new Share
  64. {
  65. UserId = i.ToString("N")
  66. }).ToList()
  67. };
  68. await parentFolder.AddChild(collection, CancellationToken.None).ConfigureAwait(false);
  69. await collection.RefreshMetadata(new MetadataRefreshOptions(new DirectoryService()), CancellationToken.None)
  70. .ConfigureAwait(false);
  71. if (options.ItemIdList.Count > 0)
  72. {
  73. await AddToCollection(collection.Id, options.ItemIdList, false);
  74. }
  75. EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs
  76. {
  77. Collection = collection,
  78. Options = options
  79. }, _logger);
  80. return collection;
  81. }
  82. finally
  83. {
  84. // Refresh handled internally
  85. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  86. }
  87. }
  88. private Folder GetParentFolder(Guid? parentId)
  89. {
  90. if (parentId.HasValue)
  91. {
  92. if (parentId.Value == Guid.Empty)
  93. {
  94. throw new ArgumentNullException("parentId");
  95. }
  96. var folder = _libraryManager.GetItemById(parentId.Value) as Folder;
  97. // Find an actual physical folder
  98. if (folder is CollectionFolder)
  99. {
  100. var child = _libraryManager.RootFolder.Children.OfType<Folder>()
  101. .FirstOrDefault(i => folder.PhysicalLocations.Contains(i.Path, StringComparer.OrdinalIgnoreCase));
  102. if (child != null)
  103. {
  104. return child;
  105. }
  106. }
  107. }
  108. return GetCollectionsFolder(string.Empty);
  109. }
  110. public Task AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  111. {
  112. return AddToCollection(collectionId, ids, true);
  113. }
  114. private async Task AddToCollection(Guid collectionId, IEnumerable<Guid> ids, bool fireEvent)
  115. {
  116. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  117. if (collection == null)
  118. {
  119. throw new ArgumentException("No collection exists with the supplied Id");
  120. }
  121. var list = new List<LinkedChild>();
  122. var itemList = new List<BaseItem>();
  123. var currentLinkedChildren = collection.GetLinkedChildren().ToList();
  124. foreach (var itemId in ids)
  125. {
  126. var item = _libraryManager.GetItemById(itemId);
  127. if (item == null)
  128. {
  129. throw new ArgumentException("No item exists with the supplied Id");
  130. }
  131. itemList.Add(item);
  132. if (currentLinkedChildren.Any(i => i.Id == itemId))
  133. {
  134. throw new ArgumentException("Item already exists in collection");
  135. }
  136. list.Add(LinkedChild.Create(item));
  137. }
  138. collection.LinkedChildren.AddRange(list);
  139. collection.UpdateRatingToContent();
  140. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  141. await collection.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  142. if (fireEvent)
  143. {
  144. EventHelper.FireEventIfNotNull(ItemsAddedToCollection, this, new CollectionModifiedEventArgs
  145. {
  146. Collection = collection,
  147. ItemsChanged = itemList
  148. }, _logger);
  149. }
  150. }
  151. public async Task RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  152. {
  153. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  154. if (collection == null)
  155. {
  156. throw new ArgumentException("No collection exists with the supplied Id");
  157. }
  158. var list = new List<LinkedChild>();
  159. var itemList = new List<BaseItem>();
  160. foreach (var itemId in itemIds)
  161. {
  162. var child = collection.LinkedChildren.FirstOrDefault(i => i.ItemId.HasValue && i.ItemId.Value == itemId);
  163. if (child == null)
  164. {
  165. throw new ArgumentException("No collection title exists with the supplied Id");
  166. }
  167. list.Add(child);
  168. var childItem = _libraryManager.GetItemById(itemId);
  169. if (childItem != null)
  170. {
  171. itemList.Add(childItem);
  172. }
  173. }
  174. var shortcutFiles = Directory
  175. .EnumerateFiles(collection.Path, "*", SearchOption.TopDirectoryOnly)
  176. .Where(i => _fileSystem.IsShortcut(i))
  177. .ToList();
  178. var shortcutFilesToDelete = list.Where(child => !string.IsNullOrWhiteSpace(child.Path) && child.Type == LinkedChildType.Shortcut)
  179. .Select(child => shortcutFiles.FirstOrDefault(i => string.Equals(child.Path, _fileSystem.ResolveShortcut(i), StringComparison.OrdinalIgnoreCase)))
  180. .Where(i => !string.IsNullOrWhiteSpace(i))
  181. .ToList();
  182. foreach (var file in shortcutFilesToDelete)
  183. {
  184. _iLibraryMonitor.ReportFileSystemChangeBeginning(file);
  185. }
  186. try
  187. {
  188. foreach (var file in shortcutFilesToDelete)
  189. {
  190. _fileSystem.DeleteFile(file);
  191. }
  192. foreach (var child in list)
  193. {
  194. collection.LinkedChildren.Remove(child);
  195. }
  196. }
  197. finally
  198. {
  199. foreach (var file in shortcutFilesToDelete)
  200. {
  201. _iLibraryMonitor.ReportFileSystemChangeComplete(file, false);
  202. }
  203. }
  204. collection.UpdateRatingToContent();
  205. await collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  206. await collection.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  207. EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
  208. {
  209. Collection = collection,
  210. ItemsChanged = itemList
  211. }, _logger);
  212. }
  213. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  214. {
  215. var results = new Dictionary<Guid, BaseItem>();
  216. var allBoxsets = new List<BoxSet>();
  217. foreach (var item in items)
  218. {
  219. var grouping = item as ISupportsBoxSetGrouping;
  220. if (grouping == null)
  221. {
  222. results[item.Id] = item;
  223. }
  224. else
  225. {
  226. var itemId = item.Id;
  227. var currentBoxSets = allBoxsets
  228. .Where(i => i.GetLinkedChildren().Any(j => j.Id == itemId))
  229. .ToList();
  230. if (currentBoxSets.Count > 0)
  231. {
  232. foreach (var boxset in currentBoxSets)
  233. {
  234. results[boxset.Id] = boxset;
  235. }
  236. }
  237. else
  238. {
  239. results[item.Id] = item;
  240. }
  241. }
  242. }
  243. return results.Values;
  244. }
  245. }
  246. }