CollectionManager.cs 14 KB

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