CollectionManager.cs 14 KB

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