CollectionFolder.cs 13 KB

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