CollectionManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 existingFolders = FindFolders(path)
  77. .ToList();
  78. if (existingFolders.Count > 0)
  79. {
  80. return existingFolders[0];
  81. }
  82. if (!createIfNeeded)
  83. {
  84. return null;
  85. }
  86. Directory.CreateDirectory(path);
  87. var libraryOptions = new LibraryOptions
  88. {
  89. PathInfos = new[] { new MediaPathInfo { Path = path } },
  90. EnableRealtimeMonitor = false,
  91. SaveLocalMetadata = true
  92. };
  93. var name = _localizationManager.GetLocalizedString("Collections");
  94. await _libraryManager.AddVirtualFolder(name, CollectionTypeOptions.BoxSets, libraryOptions, true).ConfigureAwait(false);
  95. return FindFolders(path).First();
  96. }
  97. internal string GetCollectionsFolderPath()
  98. {
  99. return Path.Combine(_appPaths.DataPath, "collections");
  100. }
  101. private Task<Folder> GetCollectionsFolder(bool createIfNeeded)
  102. {
  103. return EnsureLibraryFolder(GetCollectionsFolderPath(), createIfNeeded);
  104. }
  105. private IEnumerable<BoxSet> GetCollections(User user)
  106. {
  107. var folder = GetCollectionsFolder(false).GetAwaiter().GetResult();
  108. return folder == null
  109. ? Enumerable.Empty<BoxSet>()
  110. : folder.GetChildren(user, true).OfType<BoxSet>();
  111. }
  112. /// <inheritdoc />
  113. public async Task<BoxSet> CreateCollectionAsync(CollectionCreationOptions options)
  114. {
  115. var name = options.Name;
  116. // Need to use the [boxset] suffix
  117. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  118. // This could cause it to get re-resolved as a plain folder
  119. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  120. var parentFolder = await GetCollectionsFolder(true).ConfigureAwait(false);
  121. if (parentFolder == null)
  122. {
  123. throw new ArgumentException();
  124. }
  125. var path = Path.Combine(parentFolder.Path, folderName);
  126. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  127. try
  128. {
  129. Directory.CreateDirectory(path);
  130. var collection = new BoxSet
  131. {
  132. Name = name,
  133. Path = path,
  134. IsLocked = options.IsLocked,
  135. ProviderIds = options.ProviderIds,
  136. DateCreated = DateTime.UtcNow
  137. };
  138. parentFolder.AddChild(collection, CancellationToken.None);
  139. if (options.ItemIdList.Count > 0)
  140. {
  141. await AddToCollectionAsync(
  142. collection.Id,
  143. options.ItemIdList.Select(x => new Guid(x)),
  144. false,
  145. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  146. {
  147. // The initial adding of items is going to create a local metadata file
  148. // This will cause internet metadata to be skipped as a result
  149. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  150. }).ConfigureAwait(false);
  151. }
  152. else
  153. {
  154. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  155. }
  156. CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
  157. {
  158. Collection = collection,
  159. Options = options
  160. });
  161. return collection;
  162. }
  163. finally
  164. {
  165. // Refresh handled internally
  166. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  167. }
  168. }
  169. /// <inheritdoc />
  170. public Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> ids)
  171. => AddToCollectionAsync(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  172. private async Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  173. {
  174. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  175. if (collection == null)
  176. {
  177. throw new ArgumentException("No collection exists with the supplied Id");
  178. }
  179. var list = new List<LinkedChild>();
  180. var itemList = new List<BaseItem>();
  181. var linkedChildrenList = collection.GetLinkedChildren();
  182. var currentLinkedChildrenIds = linkedChildrenList.Select(i => i.Id).ToList();
  183. foreach (var id in ids)
  184. {
  185. var item = _libraryManager.GetItemById(id);
  186. if (item == null)
  187. {
  188. throw new ArgumentException("No item exists with the supplied Id");
  189. }
  190. if (!currentLinkedChildrenIds.Contains(id))
  191. {
  192. itemList.Add(item);
  193. list.Add(LinkedChild.Create(item));
  194. linkedChildrenList.Add(item);
  195. }
  196. }
  197. if (list.Count > 0)
  198. {
  199. var newList = collection.LinkedChildren.ToList();
  200. newList.AddRange(list);
  201. collection.LinkedChildren = newList.ToArray();
  202. collection.UpdateRatingToItems(linkedChildrenList);
  203. await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  204. refreshOptions.ForceSave = true;
  205. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  206. if (fireEvent)
  207. {
  208. ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList));
  209. }
  210. }
  211. }
  212. /// <inheritdoc />
  213. public async Task RemoveFromCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds)
  214. {
  215. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  216. if (collection == null)
  217. {
  218. throw new ArgumentException("No collection exists with the supplied Id");
  219. }
  220. var list = new List<LinkedChild>();
  221. var itemList = new List<BaseItem>();
  222. foreach (var guidId in itemIds)
  223. {
  224. var childItem = _libraryManager.GetItemById(guidId);
  225. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  226. if (child == null)
  227. {
  228. _logger.LogWarning("No collection title exists with the supplied Id");
  229. continue;
  230. }
  231. list.Add(child);
  232. if (childItem != null)
  233. {
  234. itemList.Add(childItem);
  235. }
  236. }
  237. if (list.Count > 0)
  238. {
  239. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  240. }
  241. await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  242. _providerManager.QueueRefresh(
  243. collection.Id,
  244. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  245. {
  246. ForceSave = true
  247. },
  248. RefreshPriority.High);
  249. ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs(collection, itemList));
  250. }
  251. /// <inheritdoc />
  252. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  253. {
  254. var results = new Dictionary<Guid, BaseItem>();
  255. var allBoxSets = GetCollections(user).ToList();
  256. foreach (var item in items)
  257. {
  258. if (item is not ISupportsBoxSetGrouping)
  259. {
  260. results[item.Id] = item;
  261. }
  262. else
  263. {
  264. var itemId = item.Id;
  265. var itemIsInBoxSet = false;
  266. foreach (var boxSet in allBoxSets)
  267. {
  268. if (!boxSet.ContainsLinkedChildByItemId(itemId))
  269. {
  270. continue;
  271. }
  272. itemIsInBoxSet = true;
  273. results.TryAdd(boxSet.Id, boxSet);
  274. }
  275. // skip any item that is in a box set
  276. if (itemIsInBoxSet)
  277. {
  278. continue;
  279. }
  280. var alreadyInResults = false;
  281. // this is kind of a performance hack because only Video has alternate versions that should be in a box set?
  282. if (item is Video video)
  283. {
  284. foreach (var childId in video.GetLocalAlternateVersionIds())
  285. {
  286. if (!results.ContainsKey(childId))
  287. {
  288. continue;
  289. }
  290. alreadyInResults = true;
  291. break;
  292. }
  293. }
  294. if (!alreadyInResults)
  295. {
  296. results[itemId] = item;
  297. }
  298. }
  299. }
  300. return results.Values;
  301. }
  302. }
  303. }