CollectionManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Data.Entities;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Controller.Collections;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.Movies;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Plugins;
  16. using MediaBrowser.Controller.Providers;
  17. using MediaBrowser.Model.Configuration;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Globalization;
  20. using MediaBrowser.Model.IO;
  21. using Microsoft.Extensions.Logging;
  22. namespace Emby.Server.Implementations.Collections
  23. {
  24. /// <summary>
  25. /// The collection manager.
  26. /// </summary>
  27. public class CollectionManager : ICollectionManager
  28. {
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly ILibraryMonitor _iLibraryMonitor;
  32. private readonly ILogger<CollectionManager> _logger;
  33. private readonly IProviderManager _providerManager;
  34. private readonly ILocalizationManager _localizationManager;
  35. private readonly IApplicationPaths _appPaths;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="CollectionManager"/> class.
  38. /// </summary>
  39. /// <param name="libraryManager">The library manager.</param>
  40. /// <param name="appPaths">The application paths.</param>
  41. /// <param name="localizationManager">The localization manager.</param>
  42. /// <param name="fileSystem">The filesystem.</param>
  43. /// <param name="iLibraryMonitor">The library monitor.</param>
  44. /// <param name="loggerFactory">The logger factory.</param>
  45. /// <param name="providerManager">The provider manager.</param>
  46. public CollectionManager(
  47. ILibraryManager libraryManager,
  48. IApplicationPaths appPaths,
  49. ILocalizationManager localizationManager,
  50. IFileSystem fileSystem,
  51. ILibraryMonitor iLibraryMonitor,
  52. ILoggerFactory loggerFactory,
  53. IProviderManager providerManager)
  54. {
  55. _libraryManager = libraryManager;
  56. _fileSystem = fileSystem;
  57. _iLibraryMonitor = iLibraryMonitor;
  58. _logger = loggerFactory.CreateLogger<CollectionManager>();
  59. _providerManager = providerManager;
  60. _localizationManager = localizationManager;
  61. _appPaths = appPaths;
  62. }
  63. /// <inheritdoc />
  64. public event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
  65. /// <inheritdoc />
  66. public event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
  67. /// <inheritdoc />
  68. public event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
  69. private IEnumerable<Folder> FindFolders(string path)
  70. {
  71. return _libraryManager
  72. .RootFolder
  73. .Children
  74. .OfType<Folder>()
  75. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path));
  76. }
  77. internal async Task<Folder> EnsureLibraryFolder(string path, bool createIfNeeded)
  78. {
  79. var existingFolders = FindFolders(path)
  80. .ToList();
  81. if (existingFolders.Count > 0)
  82. {
  83. return existingFolders[0];
  84. }
  85. if (!createIfNeeded)
  86. {
  87. return null;
  88. }
  89. Directory.CreateDirectory(path);
  90. var libraryOptions = new LibraryOptions
  91. {
  92. PathInfos = new[] { new MediaPathInfo { Path = path } },
  93. EnableRealtimeMonitor = false,
  94. SaveLocalMetadata = true
  95. };
  96. var name = _localizationManager.GetLocalizedString("Collections");
  97. await _libraryManager.AddVirtualFolder(name, CollectionType.BoxSets, libraryOptions, true).ConfigureAwait(false);
  98. return FindFolders(path).First();
  99. }
  100. internal string GetCollectionsFolderPath()
  101. {
  102. return Path.Combine(_appPaths.DataPath, "collections");
  103. }
  104. private Task<Folder> GetCollectionsFolder(bool createIfNeeded)
  105. {
  106. return EnsureLibraryFolder(GetCollectionsFolderPath(), createIfNeeded);
  107. }
  108. private IEnumerable<BoxSet> GetCollections(User user)
  109. {
  110. var folder = GetCollectionsFolder(false).Result;
  111. return folder == null
  112. ? Enumerable.Empty<BoxSet>()
  113. : folder.GetChildren(user, true).OfType<BoxSet>();
  114. }
  115. /// <inheritdoc />
  116. public BoxSet CreateCollection(CollectionCreationOptions options)
  117. {
  118. var name = options.Name;
  119. // Need to use the [boxset] suffix
  120. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  121. // This could cause it to get re-resolved as a plain folder
  122. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  123. var parentFolder = GetCollectionsFolder(true).GetAwaiter().GetResult();
  124. if (parentFolder == null)
  125. {
  126. throw new ArgumentException();
  127. }
  128. var path = Path.Combine(parentFolder.Path, folderName);
  129. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  130. try
  131. {
  132. Directory.CreateDirectory(path);
  133. var collection = new BoxSet
  134. {
  135. Name = name,
  136. Path = path,
  137. IsLocked = options.IsLocked,
  138. ProviderIds = options.ProviderIds,
  139. DateCreated = DateTime.UtcNow
  140. };
  141. parentFolder.AddChild(collection, CancellationToken.None);
  142. if (options.ItemIdList.Length > 0)
  143. {
  144. AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  145. {
  146. // The initial adding of items is going to create a local metadata file
  147. // This will cause internet metadata to be skipped as a result
  148. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  149. });
  150. }
  151. else
  152. {
  153. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  154. }
  155. CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
  156. {
  157. Collection = collection,
  158. Options = options
  159. });
  160. return collection;
  161. }
  162. finally
  163. {
  164. // Refresh handled internally
  165. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  166. }
  167. }
  168. /// <inheritdoc />
  169. public void AddToCollection(Guid collectionId, IEnumerable<string> ids)
  170. {
  171. AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  172. }
  173. /// <inheritdoc />
  174. public void AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  175. {
  176. AddToCollection(collectionId, ids.Select(i => i.ToString("N", CultureInfo.InvariantCulture)), true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  177. }
  178. private void AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  179. {
  180. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  181. if (collection == null)
  182. {
  183. throw new ArgumentException("No collection exists with the supplied Id");
  184. }
  185. var list = new List<LinkedChild>();
  186. var itemList = new List<BaseItem>();
  187. var linkedChildrenList = collection.GetLinkedChildren();
  188. var currentLinkedChildrenIds = linkedChildrenList.Select(i => i.Id).ToList();
  189. foreach (var id in ids)
  190. {
  191. var guidId = new Guid(id);
  192. var item = _libraryManager.GetItemById(guidId);
  193. if (item == null)
  194. {
  195. throw new ArgumentException("No item exists with the supplied Id");
  196. }
  197. if (!currentLinkedChildrenIds.Contains(guidId))
  198. {
  199. itemList.Add(item);
  200. list.Add(LinkedChild.Create(item));
  201. linkedChildrenList.Add(item);
  202. }
  203. }
  204. if (list.Count > 0)
  205. {
  206. var newList = collection.LinkedChildren.ToList();
  207. newList.AddRange(list);
  208. collection.LinkedChildren = newList.ToArray();
  209. collection.UpdateRatingToItems(linkedChildrenList);
  210. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  211. refreshOptions.ForceSave = true;
  212. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  213. if (fireEvent)
  214. {
  215. ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
  216. {
  217. Collection = collection,
  218. ItemsChanged = itemList
  219. });
  220. }
  221. }
  222. }
  223. /// <inheritdoc />
  224. public void RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds)
  225. {
  226. RemoveFromCollection(collectionId, itemIds.Select(i => new Guid(i)));
  227. }
  228. /// <inheritdoc />
  229. public void RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  230. {
  231. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  232. if (collection == null)
  233. {
  234. throw new ArgumentException("No collection exists with the supplied Id");
  235. }
  236. var list = new List<LinkedChild>();
  237. var itemList = new List<BaseItem>();
  238. foreach (var guidId in itemIds)
  239. {
  240. var childItem = _libraryManager.GetItemById(guidId);
  241. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  242. if (child == null)
  243. {
  244. _logger.LogWarning("No collection title exists with the supplied Id");
  245. continue;
  246. }
  247. list.Add(child);
  248. if (childItem != null)
  249. {
  250. itemList.Add(childItem);
  251. }
  252. }
  253. if (list.Count > 0)
  254. {
  255. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  256. }
  257. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  258. _providerManager.QueueRefresh(
  259. collection.Id,
  260. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  261. {
  262. ForceSave = true
  263. },
  264. RefreshPriority.High);
  265. ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
  266. {
  267. Collection = collection,
  268. ItemsChanged = itemList
  269. });
  270. }
  271. /// <inheritdoc />
  272. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  273. {
  274. var results = new Dictionary<Guid, BaseItem>();
  275. var allBoxsets = GetCollections(user).ToList();
  276. foreach (var item in items)
  277. {
  278. if (!(item is ISupportsBoxSetGrouping))
  279. {
  280. results[item.Id] = item;
  281. }
  282. else
  283. {
  284. var itemId = item.Id;
  285. var currentBoxSets = allBoxsets
  286. .Where(i => i.ContainsLinkedChildByItemId(itemId))
  287. .ToList();
  288. if (currentBoxSets.Count > 0)
  289. {
  290. foreach (var boxset in currentBoxSets)
  291. {
  292. results[boxset.Id] = boxset;
  293. }
  294. }
  295. else
  296. {
  297. results[item.Id] = item;
  298. }
  299. }
  300. }
  301. return results.Values;
  302. }
  303. }
  304. }