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 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. var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
  82. if (result == null)
  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. {
  119. lock (_libraryOptions)
  120. {
  121. if (!_libraryOptions.TryGetValue(path, out var options))
  122. {
  123. options = LoadLibraryOptions(path);
  124. _libraryOptions[path] = options;
  125. }
  126. return options;
  127. }
  128. }
  129. public static void SaveLibraryOptions(string path, LibraryOptions options)
  130. {
  131. lock (_libraryOptions)
  132. {
  133. _libraryOptions[path] = options;
  134. var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions);
  135. foreach (var mediaPath in clone.PathInfos)
  136. {
  137. if (!string.IsNullOrEmpty(mediaPath.Path))
  138. {
  139. mediaPath.Path = ApplicationHost.ReverseVirtualPath(mediaPath.Path);
  140. }
  141. }
  142. XmlSerializer.SerializeToFile(clone, GetLibraryOptionsPath(path));
  143. }
  144. }
  145. public static void OnCollectionFolderChange()
  146. {
  147. lock (_libraryOptions)
  148. {
  149. _libraryOptions.Clear();
  150. }
  151. }
  152. public override bool IsSaveLocalMetadataEnabled()
  153. {
  154. return true;
  155. }
  156. protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  157. {
  158. return CreateResolveArgs(directoryService, true).FileSystemChildren;
  159. }
  160. public override bool RequiresRefresh()
  161. {
  162. var changed = base.RequiresRefresh() || _requiresRefresh;
  163. if (!changed)
  164. {
  165. var locations = PhysicalLocations;
  166. var newLocations = CreateResolveArgs(new DirectoryService(FileSystem), false).PhysicalLocations;
  167. if (!locations.SequenceEqual(newLocations))
  168. {
  169. changed = true;
  170. }
  171. }
  172. if (!changed)
  173. {
  174. var folderIds = PhysicalFolderIds;
  175. var newFolderIds = GetPhysicalFolders(false).Select(i => i.Id).ToList();
  176. if (!folderIds.SequenceEqual(newFolderIds))
  177. {
  178. changed = true;
  179. }
  180. }
  181. return changed;
  182. }
  183. public override bool BeforeMetadataRefresh(bool replaceAllMetadata)
  184. {
  185. var changed = base.BeforeMetadataRefresh(replaceAllMetadata) || _requiresRefresh;
  186. _requiresRefresh = false;
  187. return changed;
  188. }
  189. public override double? GetRefreshProgress()
  190. {
  191. var folders = GetPhysicalFolders(true).ToList();
  192. double totalProgresses = 0;
  193. var foldersWithProgress = 0;
  194. foreach (var folder in folders)
  195. {
  196. var progress = ProviderManager.GetRefreshProgress(folder.Id);
  197. if (progress.HasValue)
  198. {
  199. totalProgresses += progress.Value;
  200. foldersWithProgress++;
  201. }
  202. }
  203. if (foldersWithProgress == 0)
  204. {
  205. return null;
  206. }
  207. return totalProgresses / foldersWithProgress;
  208. }
  209. protected override bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  210. {
  211. return RefreshLinkedChildrenInternal(true);
  212. }
  213. private bool RefreshLinkedChildrenInternal(bool setFolders)
  214. {
  215. var physicalFolders = GetPhysicalFolders(false)
  216. .ToList();
  217. var linkedChildren = physicalFolders
  218. .SelectMany(c => c.LinkedChildren)
  219. .ToList();
  220. var changed = !linkedChildren.SequenceEqual(LinkedChildren, new LinkedChildComparer(FileSystem));
  221. LinkedChildren = linkedChildren.ToArray();
  222. var folderIds = PhysicalFolderIds;
  223. var newFolderIds = physicalFolders.Select(i => i.Id).ToArray();
  224. if (!folderIds.SequenceEqual(newFolderIds))
  225. {
  226. changed = true;
  227. if (setFolders)
  228. {
  229. PhysicalFolderIds = newFolderIds;
  230. }
  231. }
  232. return changed;
  233. }
  234. private ItemResolveArgs CreateResolveArgs(IDirectoryService directoryService, bool setPhysicalLocations)
  235. {
  236. var path = ContainingFolderPath;
  237. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
  238. {
  239. FileInfo = FileSystem.GetDirectoryInfo(path),
  240. Parent = GetParent() as Folder,
  241. CollectionType = CollectionType
  242. };
  243. // Gather child folder and files
  244. if (args.IsDirectory)
  245. {
  246. var flattenFolderDepth = 0;
  247. var files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, FileSystem, ApplicationHost, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: true);
  248. args.FileSystemChildren = files;
  249. }
  250. _requiresRefresh = _requiresRefresh || !args.PhysicalLocations.SequenceEqual(PhysicalLocations);
  251. if (setPhysicalLocations)
  252. {
  253. PhysicalLocationsList = args.PhysicalLocations;
  254. }
  255. return args;
  256. }
  257. /// <summary>
  258. /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
  259. /// ***Currently does not contain logic to maintain items that are unavailable in the file system***.
  260. /// </summary>
  261. /// <param name="progress">The progress.</param>
  262. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  263. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  264. /// <param name="refreshOptions">The refresh options.</param>
  265. /// <param name="directoryService">The directory service.</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. /// <returns>Task.</returns>
  268. protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
  269. {
  270. return Task.CompletedTask;
  271. }
  272. public IEnumerable<BaseItem> GetActualChildren()
  273. {
  274. return GetPhysicalFolders(true).SelectMany(c => c.Children);
  275. }
  276. public IEnumerable<Folder> GetPhysicalFolders()
  277. {
  278. return GetPhysicalFolders(true);
  279. }
  280. private IEnumerable<Folder> GetPhysicalFolders(bool enableCache)
  281. {
  282. if (enableCache)
  283. {
  284. return PhysicalFolderIds.Select(i => LibraryManager.GetItemById(i)).OfType<Folder>();
  285. }
  286. var rootChildren = LibraryManager.RootFolder.Children
  287. .OfType<Folder>()
  288. .ToList();
  289. return PhysicalLocations
  290. .Where(i => !FileSystem.AreEqual(i, Path))
  291. .SelectMany(i => GetPhysicalParents(i, rootChildren))
  292. .GroupBy(x => x.Id)
  293. .Select(x => x.First());
  294. }
  295. private IEnumerable<Folder> GetPhysicalParents(string path, List<Folder> rootChildren)
  296. {
  297. var result = rootChildren
  298. .Where(i => FileSystem.AreEqual(i.Path, path))
  299. .ToList();
  300. if (result.Count == 0)
  301. {
  302. if (LibraryManager.FindByPath(path, true) is Folder folder)
  303. {
  304. result.Add(folder);
  305. }
  306. }
  307. return result;
  308. }
  309. }
  310. }