CollectionManager.cs 13 KB

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