CollectionFolder.cs 12 KB

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