CollectionFolder.cs 12 KB

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