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