CollectionManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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, CollectionTypeOptions.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).GetAwaiter().GetResult();
  111. return folder == null
  112. ? Enumerable.Empty<BoxSet>()
  113. : folder.GetChildren(user, true).OfType<BoxSet>();
  114. }
  115. /// <inheritdoc />
  116. public async Task<BoxSet> CreateCollectionAsync(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 = await GetCollectionsFolder(true).ConfigureAwait(false);
  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. await AddToCollectionAsync(
  145. collection.Id,
  146. options.ItemIdList.Select(x => new Guid(x)),
  147. false,
  148. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  149. {
  150. // The initial adding of items is going to create a local metadata file
  151. // This will cause internet metadata to be skipped as a result
  152. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  153. }).ConfigureAwait(false);
  154. }
  155. else
  156. {
  157. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  158. }
  159. CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
  160. {
  161. Collection = collection,
  162. Options = options
  163. });
  164. return collection;
  165. }
  166. finally
  167. {
  168. // Refresh handled internally
  169. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  170. }
  171. }
  172. /// <inheritdoc />
  173. public Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> ids)
  174. => AddToCollectionAsync(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_fileSystem)));
  175. private async Task AddToCollectionAsync(Guid collectionId, IEnumerable<Guid> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  176. {
  177. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  178. if (collection == null)
  179. {
  180. throw new ArgumentException("No collection exists with the supplied Id");
  181. }
  182. var list = new List<LinkedChild>();
  183. var itemList = new List<BaseItem>();
  184. var linkedChildrenList = collection.GetLinkedChildren();
  185. var currentLinkedChildrenIds = linkedChildrenList.Select(i => i.Id).ToList();
  186. foreach (var id in ids)
  187. {
  188. var item = _libraryManager.GetItemById(id);
  189. if (item == null)
  190. {
  191. throw new ArgumentException("No item exists with the supplied Id");
  192. }
  193. if (!currentLinkedChildrenIds.Contains(id))
  194. {
  195. itemList.Add(item);
  196. list.Add(LinkedChild.Create(item));
  197. linkedChildrenList.Add(item);
  198. }
  199. }
  200. if (list.Count > 0)
  201. {
  202. var newList = collection.LinkedChildren.ToList();
  203. newList.AddRange(list);
  204. collection.LinkedChildren = newList.ToArray();
  205. collection.UpdateRatingToItems(linkedChildrenList);
  206. await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  207. refreshOptions.ForceSave = true;
  208. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  209. if (fireEvent)
  210. {
  211. ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
  212. {
  213. Collection = collection,
  214. ItemsChanged = itemList
  215. });
  216. }
  217. }
  218. }
  219. /// <inheritdoc />
  220. public async Task RemoveFromCollectionAsync(Guid collectionId, IEnumerable<Guid> itemIds)
  221. {
  222. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  223. if (collection == null)
  224. {
  225. throw new ArgumentException("No collection exists with the supplied Id");
  226. }
  227. var list = new List<LinkedChild>();
  228. var itemList = new List<BaseItem>();
  229. foreach (var guidId in itemIds)
  230. {
  231. var childItem = _libraryManager.GetItemById(guidId);
  232. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  233. if (child == null)
  234. {
  235. _logger.LogWarning("No collection title exists with the supplied Id");
  236. continue;
  237. }
  238. list.Add(child);
  239. if (childItem != null)
  240. {
  241. itemList.Add(childItem);
  242. }
  243. }
  244. if (list.Count > 0)
  245. {
  246. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  247. }
  248. await collection.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  249. _providerManager.QueueRefresh(
  250. collection.Id,
  251. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  252. {
  253. ForceSave = true
  254. },
  255. RefreshPriority.High);
  256. ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
  257. {
  258. Collection = collection,
  259. ItemsChanged = itemList
  260. });
  261. }
  262. /// <inheritdoc />
  263. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  264. {
  265. var results = new Dictionary<Guid, BaseItem>();
  266. var allBoxSets = GetCollections(user).ToList();
  267. foreach (var item in items)
  268. {
  269. if (item is not ISupportsBoxSetGrouping)
  270. {
  271. results[item.Id] = item;
  272. }
  273. else
  274. {
  275. var itemId = item.Id;
  276. var itemIsInBoxSet = false;
  277. foreach (var boxSet in allBoxSets)
  278. {
  279. if (!boxSet.ContainsLinkedChildByItemId(itemId))
  280. {
  281. continue;
  282. }
  283. itemIsInBoxSet = true;
  284. results.TryAdd(boxSet.Id, boxSet);
  285. }
  286. // skip any item that is in a box set
  287. if (itemIsInBoxSet)
  288. {
  289. continue;
  290. }
  291. var alreadyInResults = false;
  292. // this is kind of a performance hack because only Video has alternate versions that should be in a box set?
  293. if (item is Video video)
  294. {
  295. foreach (var childId in video.GetLocalAlternateVersionIds())
  296. {
  297. if (!results.ContainsKey(childId))
  298. {
  299. continue;
  300. }
  301. alreadyInResults = true;
  302. break;
  303. }
  304. }
  305. if (!alreadyInResults)
  306. {
  307. results[itemId] = item;
  308. }
  309. }
  310. }
  311. return results.Values;
  312. }
  313. }
  314. }