CollectionFolder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.Json;
  8. using System.Text.Json.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Common.Json;
  12. using MediaBrowser.Controller.IO;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Serialization;
  18. using Microsoft.Extensions.Logging;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Specialized Folder class that points to a subset of the physical folders in the system.
  23. /// It is created from the user-specific folders within the system root.
  24. /// </summary>
  25. public class CollectionFolder : Folder, ICollectionFolder
  26. {
  27. private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  28. private static readonly Dictionary<string, LibraryOptions> _libraryOptions = new Dictionary<string, LibraryOptions>();
  29. private bool _requiresRefresh;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="CollectionFolder"/> class.
  32. /// </summary>
  33. public CollectionFolder()
  34. {
  35. PhysicalLocationsList = Array.Empty<string>();
  36. PhysicalFolderIds = Array.Empty<Guid>();
  37. }
  38. public static IXmlSerializer XmlSerializer { get; set; }
  39. public static IServerApplicationHost ApplicationHost { get; set; }
  40. [JsonIgnore]
  41. public override bool SupportsPlayedStatus => false;
  42. [JsonIgnore]
  43. public override bool SupportsInheritedParentImages => false;
  44. public string CollectionType { get; set; }
  45. /// <summary>
  46. /// Gets the item's children.
  47. /// </summary>
  48. /// <remarks>
  49. /// Our children are actually just references to the ones in the physical root...
  50. /// </remarks>
  51. /// <value>The actual children.</value>
  52. [JsonIgnore]
  53. public override IEnumerable<BaseItem> Children => GetActualChildren();
  54. public override bool CanDelete()
  55. {
  56. return false;
  57. }
  58. public LibraryOptions GetLibraryOptions()
  59. {
  60. return GetLibraryOptions(Path);
  61. }
  62. private static LibraryOptions LoadLibraryOptions(string path)
  63. {
  64. try
  65. {
  66. var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
  67. if (result == null)
  68. {
  69. return new LibraryOptions();
  70. }
  71. foreach (var mediaPath in result.PathInfos)
  72. {
  73. if (!string.IsNullOrEmpty(mediaPath.Path))
  74. {
  75. mediaPath.Path = ApplicationHost.ExpandVirtualPath(mediaPath.Path);
  76. }
  77. }
  78. return result;
  79. }
  80. catch (FileNotFoundException)
  81. {
  82. return new LibraryOptions();
  83. }
  84. catch (IOException)
  85. {
  86. return new LibraryOptions();
  87. }
  88. catch (Exception ex)
  89. {
  90. Logger.LogError(ex, "Error loading library options");
  91. return new LibraryOptions();
  92. }
  93. }
  94. private static string GetLibraryOptionsPath(string path)
  95. {
  96. return System.IO.Path.Combine(path, "options.xml");
  97. }
  98. public void UpdateLibraryOptions(LibraryOptions options)
  99. {
  100. SaveLibraryOptions(Path, options);
  101. }
  102. public static LibraryOptions GetLibraryOptions(string path)
  103. {
  104. lock (_libraryOptions)
  105. {
  106. if (!_libraryOptions.TryGetValue(path, out var options))
  107. {
  108. options = LoadLibraryOptions(path);
  109. _libraryOptions[path] = options;
  110. }
  111. return options;
  112. }
  113. }
  114. public static void SaveLibraryOptions(string path, LibraryOptions options)
  115. {
  116. lock (_libraryOptions)
  117. {
  118. _libraryOptions[path] = options;
  119. var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions);
  120. foreach (var mediaPath in clone.PathInfos)
  121. {
  122. if (!string.IsNullOrEmpty(mediaPath.Path))
  123. {
  124. mediaPath.Path = ApplicationHost.ReverseVirtualPath(mediaPath.Path);
  125. }
  126. }
  127. XmlSerializer.SerializeToFile(clone, GetLibraryOptionsPath(path));
  128. }
  129. }
  130. public static void OnCollectionFolderChange()
  131. {
  132. lock (_libraryOptions)
  133. {
  134. _libraryOptions.Clear();
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the display preferences id.
  139. /// </summary>
  140. /// <remarks>
  141. /// Allow different display preferences for each collection folder.
  142. /// </remarks>
  143. /// <value>The display prefs id.</value>
  144. [JsonIgnore]
  145. public override Guid DisplayPreferencesId => Id;
  146. [JsonIgnore]
  147. public override string[] PhysicalLocations => PhysicalLocationsList;
  148. public string[] PhysicalLocationsList { get; set; }
  149. public Guid[] PhysicalFolderIds { get; set; }
  150. public override bool IsSaveLocalMetadataEnabled()
  151. {
  152. return true;
  153. }
  154. protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  155. {
  156. return CreateResolveArgs(directoryService, true).FileSystemChildren;
  157. }
  158. public override bool RequiresRefresh()
  159. {
  160. var changed = base.RequiresRefresh() || _requiresRefresh;
  161. if (!changed)
  162. {
  163. var locations = PhysicalLocations;
  164. var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations;
  165. if (!locations.SequenceEqual(newLocations))
  166. {
  167. changed = true;
  168. }
  169. }
  170. if (!changed)
  171. {
  172. var folderIds = PhysicalFolderIds;
  173. var newFolderIds = GetPhysicalFolders(false).Select(i => i.Id).ToList();
  174. if (!folderIds.SequenceEqual(newFolderIds))
  175. {
  176. changed = true;
  177. }
  178. }
  179. return changed;
  180. }
  181. public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
  182. {
  183. var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh;
  184. _requiresRefresh = false;
  185. return changed;
  186. }
  187. public override double? GetRefreshProgress()
  188. {
  189. var folders = GetPhysicalFolders(true).ToList();
  190. double totalProgresses = 0;
  191. var foldersWithProgress = 0;
  192. foreach (var folder in folders)
  193. {
  194. var progress = ProviderManager.GetRefreshProgress(folder.Id);
  195. if (progress.HasValue)
  196. {
  197. totalProgresses += progress.Value;
  198. foldersWithProgress++;
  199. }
  200. }
  201. if (foldersWithProgress == 0)
  202. {
  203. return null;
  204. }
  205. return totalProgresses / foldersWithProgress;
  206. }
  207. protected override bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  208. {
  209. return RefreshLinkedChildrenInternal(true);
  210. }
  211. private bool RefreshLinkedChildrenInternal(bool setFolders)
  212. {
  213. var physicalFolders = GetPhysicalFolders(false)
  214. .ToList();
  215. var linkedChildren = physicalFolders
  216. .SelectMany(c => c.LinkedChildren)
  217. .ToList();
  218. var changed = !linkedChildren.SequenceEqual(LinkedChildren, new LinkedChildComparer(FileSystem));
  219. LinkedChildren = linkedChildren.ToArray();
  220. var folderIds = PhysicalFolderIds;
  221. var newFolderIds = physicalFolders.Select(i => i.Id).ToArray();
  222. if (!folderIds.SequenceEqual(newFolderIds))
  223. {
  224. changed = true;
  225. if (setFolders)
  226. {
  227. PhysicalFolderIds = newFolderIds;
  228. }
  229. }
  230. return changed;
  231. }
  232. private ItemResolveArgs CreateResolveArgs(IDirectoryService directoryService, bool setPhysicalLocations)
  233. {
  234. var path = ContainingFolderPath;
  235. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
  236. {
  237. FileInfo = FileSystem.GetDirectoryInfo(path),
  238. Parent = GetParent() as Folder,
  239. CollectionType = CollectionType
  240. };
  241. // Gather child folder and files
  242. if (args.IsDirectory)
  243. {
  244. var flattenFolderDepth = 0;
  245. var files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, FileSystem, ApplicationHost, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: true);
  246. args.FileSystemChildren = files;
  247. }
  248. _requiresRefresh = _requiresRefresh || !args.PhysicalLocations.SequenceEqual(PhysicalLocations);
  249. if (setPhysicalLocations)
  250. {
  251. PhysicalLocationsList = args.PhysicalLocations;
  252. }
  253. return args;
  254. }
  255. /// <summary>
  256. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  257. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
  258. /// </summary>
  259. /// <param name="progress">The progress.</param>
  260. /// <param name="cancellationToken">The cancellation token.</param>
  261. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  262. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  263. /// <param name="refreshOptions">The refresh options.</param>
  264. /// <param name="directoryService">The directory service.</param>
  265. /// <returns>Task.</returns>
  266. protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  267. {
  268. return Task.CompletedTask;
  269. }
  270. public IEnumerable<BaseItem> GetActualChildren()
  271. {
  272. return GetPhysicalFolders(true).SelectMany(c => c.Children);
  273. }
  274. public IEnumerable<Folder> GetPhysicalFolders()
  275. {
  276. return GetPhysicalFolders(true);
  277. }
  278. private IEnumerable<Folder> GetPhysicalFolders(bool enableCache)
  279. {
  280. if (enableCache)
  281. {
  282. return PhysicalFolderIds.Select(i => LibraryManager.GetItemById(i)).OfType<Folder>();
  283. }
  284. var rootChildren = LibraryManager.RootFolder.Children
  285. .OfType<Folder>()
  286. .ToList();
  287. return PhysicalLocations
  288. .Where(i => !FileSystem.AreEqual(i, Path))
  289. .SelectMany(i => GetPhysicalParents(i, rootChildren))
  290. .GroupBy(x => x.Id)
  291. .Select(x => x.First());
  292. }
  293. private IEnumerable<Folder> GetPhysicalParents(string path, List<Folder> rootChildren)
  294. {
  295. var result = rootChildren
  296. .Where(i => FileSystem.AreEqual(i.Path, path))
  297. .ToList();
  298. if (result.Count == 0)
  299. {
  300. if (LibraryManager.FindByPath(path, true) is Folder folder)
  301. {
  302. result.Add(folder);
  303. }
  304. }
  305. return result;
  306. }
  307. [JsonIgnore]
  308. public override bool SupportsPeople => false;
  309. }
  310. }