CollectionFolder.cs 12 KB

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