CollectionFolder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Json;
  11. using MediaBrowser.Controller.IO;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Serialization;
  17. using Microsoft.Extensions.Logging;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Specialized Folder class that points to a subset of the physical folders in the system.
  22. /// It is created from the user-specific folders within the system root.
  23. /// </summary>
  24. public class CollectionFolder : Folder, ICollectionFolder
  25. {
  26. private static readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  27. public static IXmlSerializer XmlSerializer { get; set; }
  28. public static IServerApplicationHost ApplicationHost { get; set; }
  29. public CollectionFolder()
  30. {
  31. PhysicalLocationsList = Array.Empty<string>();
  32. PhysicalFolderIds = Array.Empty<Guid>();
  33. }
  34. [JsonIgnore]
  35. public override bool SupportsPlayedStatus => false;
  36. [JsonIgnore]
  37. public override bool SupportsInheritedParentImages => false;
  38. public override bool CanDelete()
  39. {
  40. return false;
  41. }
  42. public string CollectionType { get; set; }
  43. private static readonly Dictionary<string, LibraryOptions> LibraryOptions = new Dictionary<string, LibraryOptions>();
  44. public LibraryOptions GetLibraryOptions()
  45. {
  46. return GetLibraryOptions(Path);
  47. }
  48. private static LibraryOptions LoadLibraryOptions(string path)
  49. {
  50. try
  51. {
  52. var result = XmlSerializer.DeserializeFromFile(typeof(LibraryOptions), GetLibraryOptionsPath(path)) as LibraryOptions;
  53. if (result == null)
  54. {
  55. return new LibraryOptions();
  56. }
  57. foreach (var mediaPath in result.PathInfos)
  58. {
  59. if (!string.IsNullOrEmpty(mediaPath.Path))
  60. {
  61. mediaPath.Path = ApplicationHost.ExpandVirtualPath(mediaPath.Path);
  62. }
  63. }
  64. return result;
  65. }
  66. catch (FileNotFoundException)
  67. {
  68. return new LibraryOptions();
  69. }
  70. catch (IOException)
  71. {
  72. return new LibraryOptions();
  73. }
  74. catch (Exception ex)
  75. {
  76. Logger.LogError(ex, "Error loading library options");
  77. return new LibraryOptions();
  78. }
  79. }
  80. private static string GetLibraryOptionsPath(string path)
  81. {
  82. return System.IO.Path.Combine(path, "options.xml");
  83. }
  84. public void UpdateLibraryOptions(LibraryOptions options)
  85. {
  86. SaveLibraryOptions(Path, options);
  87. }
  88. public static LibraryOptions GetLibraryOptions(string path)
  89. {
  90. lock (LibraryOptions)
  91. {
  92. if (!LibraryOptions.TryGetValue(path, out var options))
  93. {
  94. options = LoadLibraryOptions(path);
  95. LibraryOptions[path] = options;
  96. }
  97. return options;
  98. }
  99. }
  100. public static void SaveLibraryOptions(string path, LibraryOptions options)
  101. {
  102. lock (LibraryOptions)
  103. {
  104. LibraryOptions[path] = options;
  105. var clone = JsonSerializer.Deserialize<LibraryOptions>(JsonSerializer.SerializeToUtf8Bytes(options, _jsonOptions), _jsonOptions);
  106. foreach (var mediaPath in clone.PathInfos)
  107. {
  108. if (!string.IsNullOrEmpty(mediaPath.Path))
  109. {
  110. mediaPath.Path = ApplicationHost.ReverseVirtualPath(mediaPath.Path);
  111. }
  112. }
  113. XmlSerializer.SerializeToFile(clone, GetLibraryOptionsPath(path));
  114. }
  115. }
  116. public static void OnCollectionFolderChange()
  117. {
  118. lock (LibraryOptions)
  119. {
  120. LibraryOptions.Clear();
  121. }
  122. }
  123. /// <summary>
  124. /// Allow different display preferences for each collection folder.
  125. /// </summary>
  126. /// <value>The display prefs id.</value>
  127. [JsonIgnore]
  128. public override Guid DisplayPreferencesId => Id;
  129. [JsonIgnore]
  130. public override string[] PhysicalLocations => PhysicalLocationsList;
  131. public override bool IsSaveLocalMetadataEnabled()
  132. {
  133. return true;
  134. }
  135. public string[] PhysicalLocationsList { get; set; }
  136. public Guid[] PhysicalFolderIds { get; set; }
  137. protected override FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  138. {
  139. return CreateResolveArgs(directoryService, true).FileSystemChildren;
  140. }
  141. private bool _requiresRefresh;
  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 replaceAllMetdata)
  166. {
  167. var changed = base.BeforeMetadataRefresh(replaceAllMetdata) || _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, directoryService)
  220. {
  221. FileInfo = FileSystem.GetDirectoryInfo(path),
  222. Path = 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="cancellationToken">The cancellation token.</param>
  246. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  247. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  248. /// <param name="refreshOptions">The refresh options.</param>
  249. /// <param name="directoryService">The directory service.</param>
  250. /// <returns>Task.</returns>
  251. protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  252. {
  253. return Task.CompletedTask;
  254. }
  255. /// <summary>
  256. /// Our children are actually just references to the ones in the physical root...
  257. /// </summary>
  258. /// <value>The actual children.</value>
  259. [JsonIgnore]
  260. public override IEnumerable<BaseItem> Children => GetActualChildren();
  261. public IEnumerable<BaseItem> GetActualChildren()
  262. {
  263. return GetPhysicalFolders(true).SelectMany(c => c.Children);
  264. }
  265. public IEnumerable<Folder> GetPhysicalFolders()
  266. {
  267. return GetPhysicalFolders(true);
  268. }
  269. private IEnumerable<Folder> GetPhysicalFolders(bool enableCache)
  270. {
  271. if (enableCache)
  272. {
  273. return PhysicalFolderIds.Select(i => LibraryManager.GetItemById(i)).OfType<Folder>();
  274. }
  275. var rootChildren = LibraryManager.RootFolder.Children
  276. .OfType<Folder>()
  277. .ToList();
  278. return PhysicalLocations
  279. .Where(i => !FileSystem.AreEqual(i, Path))
  280. .SelectMany(i => GetPhysicalParents(i, rootChildren))
  281. .GroupBy(x => x.Id)
  282. .Select(x => x.First());
  283. }
  284. private IEnumerable<Folder> GetPhysicalParents(string path, List<Folder> rootChildren)
  285. {
  286. var result = rootChildren
  287. .Where(i => FileSystem.AreEqual(i.Path, path))
  288. .ToList();
  289. if (result.Count == 0)
  290. {
  291. var folder = LibraryManager.FindByPath(path, true) as Folder;
  292. if (folder != null)
  293. {
  294. result.Add(folder);
  295. }
  296. }
  297. return result;
  298. }
  299. [JsonIgnore]
  300. public override bool SupportsPeople => false;
  301. }
  302. }