CollectionManager.cs 13 KB

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