CollectionFolder.cs 12 KB

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