2
0

CollectionFolder.cs 12 KB

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