CollectionFolder.cs 12 KB

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