CollectionFolder.cs 12 KB

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