CollectionManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Controller.Collections;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Entities.Movies;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Plugins;
  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. public class CollectionManager : ICollectionManager
  23. {
  24. private readonly ILibraryManager _libraryManager;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ILibraryMonitor _iLibraryMonitor;
  27. private readonly ILogger _logger;
  28. private readonly IProviderManager _providerManager;
  29. private readonly ILocalizationManager _localizationManager;
  30. private IApplicationPaths _appPaths;
  31. public event EventHandler<CollectionCreatedEventArgs> CollectionCreated;
  32. public event EventHandler<CollectionModifiedEventArgs> ItemsAddedToCollection;
  33. public event EventHandler<CollectionModifiedEventArgs> ItemsRemovedFromCollection;
  34. public CollectionManager(
  35. ILibraryManager libraryManager,
  36. IApplicationPaths appPaths,
  37. ILocalizationManager localizationManager,
  38. IFileSystem fileSystem,
  39. ILibraryMonitor iLibraryMonitor,
  40. ILoggerFactory loggerFactory,
  41. IProviderManager providerManager)
  42. {
  43. _libraryManager = libraryManager;
  44. _fileSystem = fileSystem;
  45. _iLibraryMonitor = iLibraryMonitor;
  46. _logger = loggerFactory.CreateLogger(nameof(CollectionManager));
  47. _providerManager = providerManager;
  48. _localizationManager = localizationManager;
  49. _appPaths = appPaths;
  50. }
  51. private IEnumerable<Folder> FindFolders(string path)
  52. {
  53. return _libraryManager
  54. .RootFolder
  55. .Children
  56. .OfType<Folder>()
  57. .Where(i => _fileSystem.AreEqual(path, i.Path) || _fileSystem.ContainsSubPath(i.Path, path));
  58. }
  59. internal async Task<Folder> EnsureLibraryFolder(string path, bool createIfNeeded)
  60. {
  61. var existingFolders = FindFolders(path)
  62. .ToList();
  63. if (existingFolders.Count > 0)
  64. {
  65. return existingFolders[0];
  66. }
  67. if (!createIfNeeded)
  68. {
  69. return null;
  70. }
  71. _fileSystem.CreateDirectory(path);
  72. var libraryOptions = new LibraryOptions
  73. {
  74. PathInfos = new[] { new MediaPathInfo { Path = path } },
  75. EnableRealtimeMonitor = false,
  76. SaveLocalMetadata = true
  77. };
  78. var name = _localizationManager.GetLocalizedString("Collections");
  79. await _libraryManager.AddVirtualFolder(name, CollectionType.BoxSets, libraryOptions, true).ConfigureAwait(false);
  80. return FindFolders(path).First();
  81. }
  82. internal string GetCollectionsFolderPath()
  83. {
  84. return Path.Combine(_appPaths.DataPath, "collections");
  85. }
  86. private Task<Folder> GetCollectionsFolder(bool createIfNeeded)
  87. {
  88. return EnsureLibraryFolder(GetCollectionsFolderPath(), createIfNeeded);
  89. }
  90. private IEnumerable<BoxSet> GetCollections(User user)
  91. {
  92. var folder = GetCollectionsFolder(false).Result;
  93. return folder == null ?
  94. new List<BoxSet>() :
  95. folder.GetChildren(user, true).OfType<BoxSet>();
  96. }
  97. public BoxSet CreateCollection(CollectionCreationOptions options)
  98. {
  99. var name = options.Name;
  100. // Need to use the [boxset] suffix
  101. // If internet metadata is not found, or if xml saving is off there will be no collection.xml
  102. // This could cause it to get re-resolved as a plain folder
  103. var folderName = _fileSystem.GetValidFilename(name) + " [boxset]";
  104. var parentFolder = GetCollectionsFolder(true).Result;
  105. if (parentFolder == null)
  106. {
  107. throw new ArgumentException();
  108. }
  109. var path = Path.Combine(parentFolder.Path, folderName);
  110. _iLibraryMonitor.ReportFileSystemChangeBeginning(path);
  111. try
  112. {
  113. _fileSystem.CreateDirectory(path);
  114. var collection = new BoxSet
  115. {
  116. Name = name,
  117. Path = path,
  118. IsLocked = options.IsLocked,
  119. ProviderIds = options.ProviderIds,
  120. DateCreated = DateTime.UtcNow
  121. };
  122. parentFolder.AddChild(collection, CancellationToken.None);
  123. if (options.ItemIdList.Length > 0)
  124. {
  125. AddToCollection(collection.Id, options.ItemIdList, false, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
  126. {
  127. // The initial adding of items is going to create a local metadata file
  128. // This will cause internet metadata to be skipped as a result
  129. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  130. });
  131. }
  132. else
  133. {
  134. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High);
  135. }
  136. CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
  137. {
  138. Collection = collection,
  139. Options = options
  140. });
  141. return collection;
  142. }
  143. finally
  144. {
  145. // Refresh handled internally
  146. _iLibraryMonitor.ReportFileSystemChangeComplete(path, false);
  147. }
  148. }
  149. public void AddToCollection(Guid collectionId, IEnumerable<string> ids)
  150. {
  151. AddToCollection(collectionId, ids, true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
  152. }
  153. public void AddToCollection(Guid collectionId, IEnumerable<Guid> ids)
  154. {
  155. AddToCollection(collectionId, ids.Select(i => i.ToString("N")), true, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)));
  156. }
  157. private void AddToCollection(Guid collectionId, IEnumerable<string> ids, bool fireEvent, MetadataRefreshOptions refreshOptions)
  158. {
  159. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  160. if (collection == null)
  161. {
  162. throw new ArgumentException("No collection exists with the supplied Id");
  163. }
  164. var list = new List<LinkedChild>();
  165. var itemList = new List<BaseItem>();
  166. var linkedChildrenList = collection.GetLinkedChildren();
  167. var currentLinkedChildrenIds = linkedChildrenList.Select(i => i.Id).ToList();
  168. foreach (var id in ids)
  169. {
  170. var guidId = new Guid(id);
  171. var item = _libraryManager.GetItemById(guidId);
  172. if (item == null)
  173. {
  174. throw new ArgumentException("No item exists with the supplied Id");
  175. }
  176. if (!currentLinkedChildrenIds.Contains(guidId))
  177. {
  178. itemList.Add(item);
  179. list.Add(LinkedChild.Create(item));
  180. linkedChildrenList.Add(item);
  181. }
  182. }
  183. if (list.Count > 0)
  184. {
  185. var newList = collection.LinkedChildren.ToList();
  186. newList.AddRange(list);
  187. collection.LinkedChildren = newList.ToArray();
  188. collection.UpdateRatingToItems(linkedChildrenList);
  189. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  190. refreshOptions.ForceSave = true;
  191. _providerManager.QueueRefresh(collection.Id, refreshOptions, RefreshPriority.High);
  192. if (fireEvent)
  193. {
  194. ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
  195. {
  196. Collection = collection,
  197. ItemsChanged = itemList
  198. });
  199. }
  200. }
  201. }
  202. public void RemoveFromCollection(Guid collectionId, IEnumerable<string> itemIds)
  203. {
  204. RemoveFromCollection(collectionId, itemIds.Select(i => new Guid(i)));
  205. }
  206. public void RemoveFromCollection(Guid collectionId, IEnumerable<Guid> itemIds)
  207. {
  208. var collection = _libraryManager.GetItemById(collectionId) as BoxSet;
  209. if (collection == null)
  210. {
  211. throw new ArgumentException("No collection exists with the supplied Id");
  212. }
  213. var list = new List<LinkedChild>();
  214. var itemList = new List<BaseItem>();
  215. foreach (var guidId in itemIds)
  216. {
  217. var childItem = _libraryManager.GetItemById(guidId);
  218. var child = collection.LinkedChildren.FirstOrDefault(i => (i.ItemId.HasValue && i.ItemId.Value == guidId) || (childItem != null && string.Equals(childItem.Path, i.Path, StringComparison.OrdinalIgnoreCase)));
  219. if (child == null)
  220. {
  221. _logger.LogWarning("No collection title exists with the supplied Id");
  222. continue;
  223. }
  224. list.Add(child);
  225. if (childItem != null)
  226. {
  227. itemList.Add(childItem);
  228. }
  229. }
  230. if (list.Count > 0)
  231. {
  232. collection.LinkedChildren = collection.LinkedChildren.Except(list).ToArray();
  233. }
  234. collection.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  235. _providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
  236. {
  237. ForceSave = true
  238. }, RefreshPriority.High);
  239. ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
  240. {
  241. Collection = collection,
  242. ItemsChanged = itemList
  243. });
  244. }
  245. public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)
  246. {
  247. var results = new Dictionary<Guid, BaseItem>();
  248. var allBoxsets = GetCollections(user).ToList();
  249. foreach (var item in items)
  250. {
  251. var grouping = item as ISupportsBoxSetGrouping;
  252. if (grouping == null)
  253. {
  254. results[item.Id] = item;
  255. }
  256. else
  257. {
  258. var itemId = item.Id;
  259. var currentBoxSets = allBoxsets
  260. .Where(i => i.ContainsLinkedChildByItemId(itemId))
  261. .ToList();
  262. if (currentBoxSets.Count > 0)
  263. {
  264. foreach (var boxset in currentBoxSets)
  265. {
  266. results[boxset.Id] = boxset;
  267. }
  268. }
  269. else
  270. {
  271. results[item.Id] = item;
  272. }
  273. }
  274. }
  275. return results.Values;
  276. }
  277. }
  278. public class CollectionManagerEntryPoint : IServerEntryPoint
  279. {
  280. private readonly CollectionManager _collectionManager;
  281. private readonly IServerConfigurationManager _config;
  282. private readonly IFileSystem _fileSystem;
  283. private ILogger _logger;
  284. public CollectionManagerEntryPoint(ICollectionManager collectionManager, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger)
  285. {
  286. _collectionManager = (CollectionManager)collectionManager;
  287. _config = config;
  288. _fileSystem = fileSystem;
  289. _logger = logger;
  290. }
  291. public async void Run()
  292. {
  293. if (!_config.Configuration.CollectionsUpgraded && _config.Configuration.IsStartupWizardCompleted)
  294. {
  295. var path = _collectionManager.GetCollectionsFolderPath();
  296. if (_fileSystem.DirectoryExists(path))
  297. {
  298. try
  299. {
  300. await _collectionManager.EnsureLibraryFolder(path, true).ConfigureAwait(false);
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.LogError(ex, "Error creating camera uploads library");
  305. }
  306. _config.Configuration.CollectionsUpgraded = true;
  307. _config.SaveConfiguration();
  308. }
  309. }
  310. }
  311. #region IDisposable Support
  312. private bool disposedValue = false; // To detect redundant calls
  313. protected virtual void Dispose(bool disposing)
  314. {
  315. if (!disposedValue)
  316. {
  317. if (disposing)
  318. {
  319. // TODO: dispose managed state (managed objects).
  320. }
  321. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  322. // TODO: set large fields to null.
  323. disposedValue = true;
  324. }
  325. }
  326. // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
  327. // ~CollectionManagerEntryPoint() {
  328. // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  329. // Dispose(false);
  330. // }
  331. // This code added to correctly implement the disposable pattern.
  332. public void Dispose()
  333. {
  334. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  335. Dispose(true);
  336. // TODO: uncomment the following line if the finalizer is overridden above.
  337. // GC.SuppressFinalize(this);
  338. }
  339. #endregion
  340. }
  341. }