Folder.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Model.Dto;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Querying;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.Serialization;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Controller.Channels;
  16. using MediaBrowser.Controller.Entities.TV;
  17. using MediaBrowser.Model.Channels;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Class Folder
  22. /// </summary>
  23. public class Folder : BaseItem, IHasThemeMedia
  24. {
  25. public static IUserManager UserManager { get; set; }
  26. public static IUserViewManager UserViewManager { get; set; }
  27. public List<Guid> ThemeSongIds { get; set; }
  28. public List<Guid> ThemeVideoIds { get; set; }
  29. [IgnoreDataMember]
  30. public DateTime? DateLastMediaAdded { get; set; }
  31. public Folder()
  32. {
  33. LinkedChildren = new List<LinkedChild>();
  34. ThemeSongIds = new List<Guid>();
  35. ThemeVideoIds = new List<Guid>();
  36. }
  37. [IgnoreDataMember]
  38. public virtual bool IsPreSorted
  39. {
  40. get { return false; }
  41. }
  42. /// <summary>
  43. /// Gets a value indicating whether this instance is folder.
  44. /// </summary>
  45. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  46. [IgnoreDataMember]
  47. public override bool IsFolder
  48. {
  49. get
  50. {
  51. return true;
  52. }
  53. }
  54. [IgnoreDataMember]
  55. public virtual bool SupportsCumulativeRunTimeTicks
  56. {
  57. get
  58. {
  59. return false;
  60. }
  61. }
  62. [IgnoreDataMember]
  63. public virtual bool SupportsDateLastMediaAdded
  64. {
  65. get
  66. {
  67. return false;
  68. }
  69. }
  70. public override bool RequiresRefresh()
  71. {
  72. var baseResult = base.RequiresRefresh();
  73. if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
  74. {
  75. baseResult = true;
  76. }
  77. return baseResult;
  78. }
  79. [IgnoreDataMember]
  80. public override string FileNameWithoutExtension
  81. {
  82. get
  83. {
  84. if (LocationType == LocationType.FileSystem)
  85. {
  86. return System.IO.Path.GetFileName(Path);
  87. }
  88. return null;
  89. }
  90. }
  91. protected override bool IsAllowTagFilterEnforced()
  92. {
  93. if (this is ICollectionFolder)
  94. {
  95. return false;
  96. }
  97. if (this is UserView)
  98. {
  99. return false;
  100. }
  101. return true;
  102. }
  103. /// <summary>
  104. /// Gets or sets a value indicating whether this instance is physical root.
  105. /// </summary>
  106. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  107. public bool IsPhysicalRoot { get; set; }
  108. /// <summary>
  109. /// Gets or sets a value indicating whether this instance is root.
  110. /// </summary>
  111. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  112. public bool IsRoot { get; set; }
  113. public virtual List<LinkedChild> LinkedChildren { get; set; }
  114. [IgnoreDataMember]
  115. protected virtual bool SupportsShortcutChildren
  116. {
  117. get { return false; }
  118. }
  119. /// <summary>
  120. /// Adds the child.
  121. /// </summary>
  122. /// <param name="item">The item.</param>
  123. /// <param name="cancellationToken">The cancellation token.</param>
  124. /// <returns>Task.</returns>
  125. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  126. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  127. {
  128. item.SetParent(this);
  129. if (item.Id == Guid.Empty)
  130. {
  131. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  132. }
  133. if (ActualChildren.Any(i => i.Id == item.Id))
  134. {
  135. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  136. }
  137. if (item.DateCreated == DateTime.MinValue)
  138. {
  139. item.DateCreated = DateTime.UtcNow;
  140. }
  141. if (item.DateModified == DateTime.MinValue)
  142. {
  143. item.DateModified = DateTime.UtcNow;
  144. }
  145. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  146. }
  147. /// <summary>
  148. /// Removes the child.
  149. /// </summary>
  150. /// <param name="item">The item.</param>
  151. public void RemoveChild(BaseItem item)
  152. {
  153. item.SetParent(null);
  154. }
  155. #region Indexing
  156. /// <summary>
  157. /// Returns the valid set of index by options for this folder type.
  158. /// Override or extend to modify.
  159. /// </summary>
  160. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  161. protected virtual IEnumerable<string> GetIndexByOptions()
  162. {
  163. return new List<string> {
  164. {"None"},
  165. {"Performer"},
  166. {"Genre"},
  167. {"Director"},
  168. {"Year"},
  169. {"Studio"}
  170. };
  171. }
  172. /// <summary>
  173. /// Get the list of indexy by choices for this folder (localized).
  174. /// </summary>
  175. /// <value>The index by option strings.</value>
  176. [IgnoreDataMember]
  177. public IEnumerable<string> IndexByOptionStrings
  178. {
  179. get { return GetIndexByOptions(); }
  180. }
  181. #endregion
  182. /// <summary>
  183. /// Gets the actual children.
  184. /// </summary>
  185. /// <value>The actual children.</value>
  186. [IgnoreDataMember]
  187. protected virtual IEnumerable<BaseItem> ActualChildren
  188. {
  189. get
  190. {
  191. return LoadChildren();
  192. }
  193. }
  194. /// <summary>
  195. /// thread-safe access to the actual children of this folder - without regard to user
  196. /// </summary>
  197. /// <value>The children.</value>
  198. [IgnoreDataMember]
  199. public IEnumerable<BaseItem> Children
  200. {
  201. get { return ActualChildren.ToList(); }
  202. }
  203. /// <summary>
  204. /// thread-safe access to all recursive children of this folder - without regard to user
  205. /// </summary>
  206. /// <value>The recursive children.</value>
  207. [IgnoreDataMember]
  208. public IEnumerable<BaseItem> RecursiveChildren
  209. {
  210. get { return GetRecursiveChildren(); }
  211. }
  212. public override bool IsVisible(User user)
  213. {
  214. if (this is ICollectionFolder && !(this is BasePluginFolder))
  215. {
  216. if (user.Policy.BlockedMediaFolders != null)
  217. {
  218. if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  219. // Backwards compatibility
  220. user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  221. {
  222. return false;
  223. }
  224. }
  225. else
  226. {
  227. if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  228. {
  229. return false;
  230. }
  231. }
  232. }
  233. return base.IsVisible(user);
  234. }
  235. /// <summary>
  236. /// Loads our children. Validation will occur externally.
  237. /// We want this sychronous.
  238. /// </summary>
  239. protected virtual IEnumerable<BaseItem> LoadChildren()
  240. {
  241. //just load our children from the repo - the library will be validated and maintained in other processes
  242. return GetCachedChildren();
  243. }
  244. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  245. {
  246. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)));
  247. }
  248. /// <summary>
  249. /// Validates that the children of the folder still exist
  250. /// </summary>
  251. /// <param name="progress">The progress.</param>
  252. /// <param name="cancellationToken">The cancellation token.</param>
  253. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  254. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  255. /// <returns>Task.</returns>
  256. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  257. {
  258. return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  259. }
  260. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  261. {
  262. var dictionary = new Dictionary<Guid, BaseItem>();
  263. foreach (var child in ActualChildren)
  264. {
  265. var id = child.Id;
  266. if (dictionary.ContainsKey(id))
  267. {
  268. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  269. Path ?? Name,
  270. child.Path ?? child.Name);
  271. }
  272. else
  273. {
  274. dictionary[id] = child;
  275. }
  276. }
  277. return dictionary;
  278. }
  279. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  280. {
  281. return current.IsValidFromResolver(newItem);
  282. }
  283. /// <summary>
  284. /// Validates the children internal.
  285. /// </summary>
  286. /// <param name="progress">The progress.</param>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  289. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  290. /// <param name="refreshOptions">The refresh options.</param>
  291. /// <param name="directoryService">The directory service.</param>
  292. /// <returns>Task.</returns>
  293. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  294. {
  295. var locationType = LocationType;
  296. cancellationToken.ThrowIfCancellationRequested();
  297. var validChildren = new List<BaseItem>();
  298. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  299. {
  300. IEnumerable<BaseItem> nonCachedChildren;
  301. try
  302. {
  303. nonCachedChildren = GetNonCachedChildren(directoryService);
  304. }
  305. catch (IOException ex)
  306. {
  307. nonCachedChildren = new BaseItem[] { };
  308. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  309. }
  310. if (nonCachedChildren == null) return; //nothing to validate
  311. progress.Report(5);
  312. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  313. var currentChildren = GetActualChildrenDictionary();
  314. //create a list for our validated children
  315. var newItems = new List<BaseItem>();
  316. cancellationToken.ThrowIfCancellationRequested();
  317. foreach (var child in nonCachedChildren)
  318. {
  319. BaseItem currentChild;
  320. if (currentChildren.TryGetValue(child.Id, out currentChild) && IsValidFromResolver(currentChild, child))
  321. {
  322. await UpdateIsOffline(currentChild, false).ConfigureAwait(false);
  323. validChildren.Add(currentChild);
  324. continue;
  325. }
  326. // Brand new item - needs to be added
  327. child.SetParent(this);
  328. newItems.Add(child);
  329. validChildren.Add(child);
  330. }
  331. // If any items were added or removed....
  332. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  333. {
  334. // That's all the new and changed ones - now see if there are any that are missing
  335. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  336. var actualRemovals = new List<BaseItem>();
  337. foreach (var item in itemsRemoved)
  338. {
  339. var itemLocationType = item.LocationType;
  340. if (itemLocationType == LocationType.Virtual ||
  341. itemLocationType == LocationType.Remote)
  342. {
  343. }
  344. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  345. {
  346. await UpdateIsOffline(item, true).ConfigureAwait(false);
  347. }
  348. else
  349. {
  350. actualRemovals.Add(item);
  351. }
  352. }
  353. if (actualRemovals.Count > 0)
  354. {
  355. foreach (var item in actualRemovals)
  356. {
  357. Logger.Debug("Removed item: " + item.Path);
  358. item.SetParent(null);
  359. item.IsOffline = false;
  360. await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false);
  361. LibraryManager.ReportItemRemoved(item);
  362. }
  363. }
  364. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  365. }
  366. }
  367. progress.Report(10);
  368. cancellationToken.ThrowIfCancellationRequested();
  369. if (recursive)
  370. {
  371. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  372. }
  373. progress.Report(20);
  374. if (refreshChildMetadata)
  375. {
  376. var container = this as IMetadataContainer;
  377. var innerProgress = new ActionableProgress<double>();
  378. innerProgress.RegisterAction(p => progress.Report(.80 * p + 20));
  379. if (container != null)
  380. {
  381. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  382. }
  383. else
  384. {
  385. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  386. }
  387. }
  388. progress.Report(100);
  389. }
  390. private Task UpdateIsOffline(BaseItem item, bool newValue)
  391. {
  392. if (item.IsOffline != newValue)
  393. {
  394. item.IsOffline = newValue;
  395. return item.UpdateToRepository(ItemUpdateType.None, CancellationToken.None);
  396. }
  397. return Task.FromResult(true);
  398. }
  399. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  400. {
  401. var children = ActualChildren.ToList();
  402. var percentages = new Dictionary<Guid, double>(children.Count);
  403. var numComplete = 0;
  404. var count = children.Count;
  405. foreach (var child in children)
  406. {
  407. cancellationToken.ThrowIfCancellationRequested();
  408. if (child.IsFolder)
  409. {
  410. var innerProgress = new ActionableProgress<double>();
  411. // Avoid implicitly captured closure
  412. var currentChild = child;
  413. innerProgress.RegisterAction(p =>
  414. {
  415. lock (percentages)
  416. {
  417. percentages[currentChild.Id] = p / 100;
  418. var innerPercent = percentages.Values.Sum();
  419. innerPercent /= count;
  420. innerPercent *= 100;
  421. progress.Report(innerPercent);
  422. }
  423. });
  424. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  425. .ConfigureAwait(false);
  426. }
  427. else
  428. {
  429. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  430. .ConfigureAwait(false);
  431. }
  432. numComplete++;
  433. double percent = numComplete;
  434. percent /= count;
  435. percent *= 100;
  436. progress.Report(percent);
  437. }
  438. progress.Report(100);
  439. }
  440. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  441. {
  442. var container = child as IMetadataContainer;
  443. if (container != null)
  444. {
  445. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  446. }
  447. else
  448. {
  449. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  450. if (recursive)
  451. {
  452. var folder = child as Folder;
  453. if (folder != null)
  454. {
  455. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  456. }
  457. }
  458. }
  459. progress.Report(100);
  460. }
  461. /// <summary>
  462. /// Refreshes the children.
  463. /// </summary>
  464. /// <param name="children">The children.</param>
  465. /// <param name="directoryService">The directory service.</param>
  466. /// <param name="progress">The progress.</param>
  467. /// <param name="cancellationToken">The cancellation token.</param>
  468. /// <returns>Task.</returns>
  469. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  470. {
  471. var list = children;
  472. var childCount = list.Count;
  473. var percentages = new Dictionary<Guid, double>(list.Count);
  474. foreach (var item in list)
  475. {
  476. cancellationToken.ThrowIfCancellationRequested();
  477. var child = item;
  478. var innerProgress = new ActionableProgress<double>();
  479. innerProgress.RegisterAction(p =>
  480. {
  481. lock (percentages)
  482. {
  483. percentages[child.Id] = p / 100;
  484. var percent = percentages.Values.Sum();
  485. percent /= childCount;
  486. progress.Report(10 * percent + 10);
  487. }
  488. });
  489. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  490. .ConfigureAwait(false);
  491. }
  492. }
  493. /// <summary>
  494. /// Determines whether the specified path is offline.
  495. /// </summary>
  496. /// <param name="path">The path.</param>
  497. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  498. public static bool IsPathOffline(string path)
  499. {
  500. if (FileSystem.FileExists(path))
  501. {
  502. return false;
  503. }
  504. var originalPath = path;
  505. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  506. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  507. {
  508. if (FileSystem.DirectoryExists(path))
  509. {
  510. return false;
  511. }
  512. path = System.IO.Path.GetDirectoryName(path);
  513. }
  514. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  515. {
  516. return true;
  517. }
  518. return false;
  519. }
  520. /// <summary>
  521. /// Determines whether the specified folders contains path.
  522. /// </summary>
  523. /// <param name="folders">The folders.</param>
  524. /// <param name="path">The path.</param>
  525. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  526. private static bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  527. {
  528. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  529. }
  530. private static bool ContainsPath(string parent, string path)
  531. {
  532. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  533. }
  534. /// <summary>
  535. /// Get the children of this folder from the actual file system
  536. /// </summary>
  537. /// <returns>IEnumerable{BaseItem}.</returns>
  538. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  539. {
  540. var collectionType = LibraryManager.GetContentType(this);
  541. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  542. }
  543. /// <summary>
  544. /// Get our children from the repo - stubbed for now
  545. /// </summary>
  546. /// <returns>IEnumerable{BaseItem}.</returns>
  547. protected IEnumerable<BaseItem> GetCachedChildren()
  548. {
  549. return ItemRepository.GetItemList(new InternalItemsQuery
  550. {
  551. ParentId = Id,
  552. GroupByPresentationUniqueKey = false
  553. });
  554. }
  555. public virtual int GetChildCount(User user)
  556. {
  557. if (LinkedChildren.Count > 0)
  558. {
  559. if (!(this is ICollectionFolder))
  560. {
  561. return GetChildren(user, true).Count();
  562. }
  563. }
  564. var result = GetItems(new InternalItemsQuery(user)
  565. {
  566. Recursive = false,
  567. Limit = 0,
  568. ParentId = Id
  569. }).Result;
  570. return result.TotalRecordCount;
  571. }
  572. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  573. {
  574. var user = query.User;
  575. if (!query.ForceDirect && RequiresPostFiltering(query))
  576. {
  577. IEnumerable<BaseItem> items;
  578. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  579. if (query.User == null)
  580. {
  581. items = GetRecursiveChildren(filter);
  582. }
  583. else
  584. {
  585. items = GetRecursiveChildren(user, query);
  586. }
  587. return PostFilterAndSort(items, query);
  588. }
  589. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  590. {
  591. query.ParentId = query.ParentId ?? Id;
  592. }
  593. return LibraryManager.GetItemsResult(query);
  594. }
  595. private bool RequiresPostFiltering(InternalItemsQuery query)
  596. {
  597. if (LinkedChildren.Count > 0)
  598. {
  599. if (!(this is ICollectionFolder))
  600. {
  601. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  602. return true;
  603. }
  604. }
  605. if (query.SortBy != null && query.SortBy.Length > 0)
  606. {
  607. if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase))
  608. {
  609. Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder");
  610. return true;
  611. }
  612. if (query.SortBy.Contains(ItemSortBy.Budget, StringComparer.OrdinalIgnoreCase))
  613. {
  614. Logger.Debug("Query requires post-filtering due to ItemSortBy.Budget");
  615. return true;
  616. }
  617. if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase))
  618. {
  619. Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem");
  620. return true;
  621. }
  622. if (query.SortBy.Contains(ItemSortBy.Metascore, StringComparer.OrdinalIgnoreCase))
  623. {
  624. Logger.Debug("Query requires post-filtering due to ItemSortBy.Metascore");
  625. return true;
  626. }
  627. if (query.SortBy.Contains(ItemSortBy.Players, StringComparer.OrdinalIgnoreCase))
  628. {
  629. Logger.Debug("Query requires post-filtering due to ItemSortBy.Players");
  630. return true;
  631. }
  632. if (query.SortBy.Contains(ItemSortBy.Revenue, StringComparer.OrdinalIgnoreCase))
  633. {
  634. Logger.Debug("Query requires post-filtering due to ItemSortBy.Revenue");
  635. return true;
  636. }
  637. if (query.SortBy.Contains(ItemSortBy.VideoBitRate, StringComparer.OrdinalIgnoreCase))
  638. {
  639. Logger.Debug("Query requires post-filtering due to ItemSortBy.VideoBitRate");
  640. return true;
  641. }
  642. }
  643. if (query.ItemIds.Length > 0)
  644. {
  645. Logger.Debug("Query requires post-filtering due to ItemIds");
  646. return true;
  647. }
  648. if (query.IsInBoxSet.HasValue)
  649. {
  650. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  651. return true;
  652. }
  653. // Filter by Video3DFormat
  654. if (query.Is3D.HasValue)
  655. {
  656. Logger.Debug("Query requires post-filtering due to Is3D");
  657. return true;
  658. }
  659. if (query.HasOfficialRating.HasValue)
  660. {
  661. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  662. return true;
  663. }
  664. if (query.IsPlaceHolder.HasValue)
  665. {
  666. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  667. return true;
  668. }
  669. if (query.HasSpecialFeature.HasValue)
  670. {
  671. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  672. return true;
  673. }
  674. if (query.HasSubtitles.HasValue)
  675. {
  676. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  677. return true;
  678. }
  679. if (query.HasTrailer.HasValue)
  680. {
  681. Logger.Debug("Query requires post-filtering due to HasTrailer");
  682. return true;
  683. }
  684. if (query.HasThemeSong.HasValue)
  685. {
  686. Logger.Debug("Query requires post-filtering due to HasThemeSong");
  687. return true;
  688. }
  689. if (query.HasThemeVideo.HasValue)
  690. {
  691. Logger.Debug("Query requires post-filtering due to HasThemeVideo");
  692. return true;
  693. }
  694. // Filter by VideoType
  695. if (query.VideoTypes.Length > 0)
  696. {
  697. Logger.Debug("Query requires post-filtering due to VideoTypes");
  698. return true;
  699. }
  700. // Apply person filter
  701. if (query.ItemIdsFromPersonFilters != null)
  702. {
  703. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  704. return true;
  705. }
  706. if (query.MinPlayers.HasValue)
  707. {
  708. Logger.Debug("Query requires post-filtering due to MinPlayers");
  709. return true;
  710. }
  711. if (query.MaxPlayers.HasValue)
  712. {
  713. Logger.Debug("Query requires post-filtering due to MaxPlayers");
  714. return true;
  715. }
  716. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  717. {
  718. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  719. return true;
  720. }
  721. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  722. {
  723. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  724. return true;
  725. }
  726. if (query.AirDays.Length > 0)
  727. {
  728. Logger.Debug("Query requires post-filtering due to AirDays");
  729. return true;
  730. }
  731. if (query.SeriesStatuses.Length > 0)
  732. {
  733. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  734. return true;
  735. }
  736. if (query.AiredDuringSeason.HasValue)
  737. {
  738. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  739. return true;
  740. }
  741. if (!string.IsNullOrWhiteSpace(query.AlbumArtistStartsWithOrGreater))
  742. {
  743. Logger.Debug("Query requires post-filtering due to AlbumArtistStartsWithOrGreater");
  744. return true;
  745. }
  746. if (query.IsPlayed.HasValue)
  747. {
  748. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  749. {
  750. Logger.Debug("Query requires post-filtering due to IsPlayed");
  751. return true;
  752. }
  753. }
  754. return false;
  755. }
  756. public Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  757. {
  758. if (query.ItemIds.Length > 0)
  759. {
  760. var specificItems = query.ItemIds.Select(LibraryManager.GetItemById).Where(i => i != null).ToList();
  761. return Task.FromResult(PostFilterAndSort(specificItems, query));
  762. }
  763. return GetItemsInternal(query);
  764. }
  765. protected virtual async Task<QueryResult<BaseItem>> GetItemsInternal(InternalItemsQuery query)
  766. {
  767. if (SourceType == SourceType.Channel)
  768. {
  769. try
  770. {
  771. // Don't blow up here because it could cause parent screens with other content to fail
  772. return await ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  773. {
  774. ChannelId = ChannelId,
  775. FolderId = Id.ToString("N"),
  776. Limit = query.Limit,
  777. StartIndex = query.StartIndex,
  778. UserId = query.User.Id.ToString("N"),
  779. SortBy = query.SortBy,
  780. SortOrder = query.SortOrder
  781. }, new Progress<double>(), CancellationToken.None);
  782. }
  783. catch
  784. {
  785. // Already logged at lower levels
  786. return new QueryResult<BaseItem>();
  787. }
  788. }
  789. if (query.Recursive)
  790. {
  791. return QueryRecursive(query);
  792. }
  793. var user = query.User;
  794. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  795. IEnumerable<BaseItem> items;
  796. if (query.User == null)
  797. {
  798. items = query.Recursive
  799. ? GetRecursiveChildren(filter)
  800. : Children.Where(filter);
  801. }
  802. else
  803. {
  804. items = query.Recursive
  805. ? GetRecursiveChildren(user, query)
  806. : GetChildren(user, true).Where(filter);
  807. }
  808. return PostFilterAndSort(items, query);
  809. }
  810. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  811. {
  812. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager);
  813. }
  814. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  815. {
  816. if (user == null)
  817. {
  818. throw new ArgumentNullException();
  819. }
  820. //the true root should return our users root folder children
  821. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  822. var result = new Dictionary<Guid, BaseItem>();
  823. AddChildren(user, includeLinkedChildren, result, false, null);
  824. return result.Values;
  825. }
  826. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  827. {
  828. return Children;
  829. }
  830. /// <summary>
  831. /// Adds the children to list.
  832. /// </summary>
  833. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  834. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  835. {
  836. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  837. {
  838. if (child.IsVisible(user))
  839. {
  840. if (query == null || UserViewBuilder.FilterItem(child, query))
  841. {
  842. result[child.Id] = child;
  843. }
  844. if (recursive && child.IsFolder)
  845. {
  846. var folder = (Folder)child;
  847. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  848. }
  849. }
  850. }
  851. if (includeLinkedChildren)
  852. {
  853. foreach (var child in GetLinkedChildren(user))
  854. {
  855. if (child.IsVisible(user))
  856. {
  857. if (query == null || UserViewBuilder.FilterItem(child, query))
  858. {
  859. result[child.Id] = child;
  860. }
  861. }
  862. }
  863. }
  864. }
  865. /// <summary>
  866. /// Gets allowed recursive children of an item
  867. /// </summary>
  868. /// <param name="user">The user.</param>
  869. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  870. /// <returns>IEnumerable{BaseItem}.</returns>
  871. /// <exception cref="System.ArgumentNullException"></exception>
  872. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  873. {
  874. return GetRecursiveChildren(user, null);
  875. }
  876. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  877. {
  878. if (user == null)
  879. {
  880. throw new ArgumentNullException("user");
  881. }
  882. var result = new Dictionary<Guid, BaseItem>();
  883. AddChildren(user, true, result, true, query);
  884. return result.Values;
  885. }
  886. /// <summary>
  887. /// Gets the recursive children.
  888. /// </summary>
  889. /// <returns>IList{BaseItem}.</returns>
  890. public IList<BaseItem> GetRecursiveChildren()
  891. {
  892. return GetRecursiveChildren(i => true);
  893. }
  894. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  895. {
  896. var result = new Dictionary<Guid, BaseItem>();
  897. AddChildrenToList(result, true, true, filter);
  898. return result.Values.ToList();
  899. }
  900. /// <summary>
  901. /// Adds the children to list.
  902. /// </summary>
  903. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  904. {
  905. foreach (var child in Children)
  906. {
  907. if (filter == null || filter(child))
  908. {
  909. result[child.Id] = child;
  910. }
  911. if (recursive && child.IsFolder)
  912. {
  913. var folder = (Folder)child;
  914. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  915. folder.AddChildrenToList(result, false, true, filter);
  916. }
  917. }
  918. if (includeLinkedChildren)
  919. {
  920. foreach (var child in GetLinkedChildren())
  921. {
  922. if (filter == null || filter(child))
  923. {
  924. result[child.Id] = child;
  925. }
  926. }
  927. }
  928. }
  929. /// <summary>
  930. /// Gets the linked children.
  931. /// </summary>
  932. /// <returns>IEnumerable{BaseItem}.</returns>
  933. public IEnumerable<BaseItem> GetLinkedChildren()
  934. {
  935. return LinkedChildren
  936. .Select(GetLinkedChild)
  937. .Where(i => i != null);
  938. }
  939. protected virtual bool FilterLinkedChildrenPerUser
  940. {
  941. get
  942. {
  943. return false;
  944. }
  945. }
  946. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  947. {
  948. if (!FilterLinkedChildrenPerUser || user == null)
  949. {
  950. return GetLinkedChildren();
  951. }
  952. var locations = user.RootFolder
  953. .Children
  954. .OfType<CollectionFolder>()
  955. .Where(i => i.IsVisible(user))
  956. .SelectMany(i => i.PhysicalLocations)
  957. .ToList();
  958. return LinkedChildren
  959. .Select(i =>
  960. {
  961. var requiresPostFilter = true;
  962. if (!string.IsNullOrWhiteSpace(i.Path))
  963. {
  964. requiresPostFilter = false;
  965. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  966. {
  967. return null;
  968. }
  969. }
  970. var child = GetLinkedChild(i);
  971. if (requiresPostFilter && child != null)
  972. {
  973. if (string.IsNullOrWhiteSpace(child.Path))
  974. {
  975. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  976. return child;
  977. }
  978. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  979. {
  980. return null;
  981. }
  982. }
  983. return child;
  984. })
  985. .Where(i => i != null);
  986. }
  987. /// <summary>
  988. /// Gets the linked children.
  989. /// </summary>
  990. /// <returns>IEnumerable{BaseItem}.</returns>
  991. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  992. {
  993. return LinkedChildren
  994. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  995. .Where(i => i.Item2 != null);
  996. }
  997. [IgnoreDataMember]
  998. protected override bool SupportsOwnedItems
  999. {
  1000. get
  1001. {
  1002. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1003. }
  1004. }
  1005. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1006. {
  1007. var changesFound = false;
  1008. if (LocationType == LocationType.FileSystem)
  1009. {
  1010. if (RefreshLinkedChildren(fileSystemChildren))
  1011. {
  1012. changesFound = true;
  1013. }
  1014. }
  1015. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1016. return baseHasChanges || changesFound;
  1017. }
  1018. /// <summary>
  1019. /// Refreshes the linked children.
  1020. /// </summary>
  1021. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1022. private bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1023. {
  1024. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1025. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1026. List<LinkedChild> newShortcutLinks;
  1027. if (SupportsShortcutChildren)
  1028. {
  1029. newShortcutLinks = fileSystemChildren
  1030. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1031. .Select(i =>
  1032. {
  1033. try
  1034. {
  1035. Logger.Debug("Found shortcut at {0}", i.FullName);
  1036. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1037. if (!string.IsNullOrEmpty(resolvedPath))
  1038. {
  1039. return new LinkedChild
  1040. {
  1041. Path = resolvedPath,
  1042. Type = LinkedChildType.Shortcut
  1043. };
  1044. }
  1045. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1046. return null;
  1047. }
  1048. catch (IOException ex)
  1049. {
  1050. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1051. return null;
  1052. }
  1053. })
  1054. .Where(i => i != null)
  1055. .ToList();
  1056. }
  1057. else { newShortcutLinks = new List<LinkedChild>(); }
  1058. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1059. {
  1060. Logger.Info("Shortcut links have changed for {0}", Path);
  1061. newShortcutLinks.AddRange(currentManualLinks);
  1062. LinkedChildren = newShortcutLinks;
  1063. return true;
  1064. }
  1065. foreach (var child in LinkedChildren)
  1066. {
  1067. // Reset the cached value
  1068. child.ItemId = null;
  1069. }
  1070. return false;
  1071. }
  1072. /// <summary>
  1073. /// Folders need to validate and refresh
  1074. /// </summary>
  1075. /// <returns>Task.</returns>
  1076. public override async Task ChangedExternally()
  1077. {
  1078. var progress = new Progress<double>();
  1079. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1080. await base.ChangedExternally().ConfigureAwait(false);
  1081. }
  1082. /// <summary>
  1083. /// Marks the played.
  1084. /// </summary>
  1085. /// <param name="user">The user.</param>
  1086. /// <param name="datePlayed">The date played.</param>
  1087. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1088. /// <returns>Task.</returns>
  1089. public override async Task MarkPlayed(User user,
  1090. DateTime? datePlayed,
  1091. bool resetPosition)
  1092. {
  1093. var query = new InternalItemsQuery
  1094. {
  1095. User = user,
  1096. Recursive = true,
  1097. IsFolder = false,
  1098. EnableTotalRecordCount = false
  1099. };
  1100. if (!user.Configuration.DisplayMissingEpisodes || !user.Configuration.DisplayUnairedEpisodes)
  1101. {
  1102. query.ExcludeLocationTypes = new[] { LocationType.Virtual };
  1103. }
  1104. var itemsResult = await GetItems(query).ConfigureAwait(false);
  1105. // Sweep through recursively and update status
  1106. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1107. await Task.WhenAll(tasks).ConfigureAwait(false);
  1108. }
  1109. /// <summary>
  1110. /// Marks the unplayed.
  1111. /// </summary>
  1112. /// <param name="user">The user.</param>
  1113. /// <returns>Task.</returns>
  1114. public override async Task MarkUnplayed(User user)
  1115. {
  1116. var itemsResult = await GetItems(new InternalItemsQuery
  1117. {
  1118. User = user,
  1119. Recursive = true,
  1120. IsFolder = false,
  1121. EnableTotalRecordCount = false
  1122. }).ConfigureAwait(false);
  1123. // Sweep through recursively and update status
  1124. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1125. await Task.WhenAll(tasks).ConfigureAwait(false);
  1126. }
  1127. public override bool IsPlayed(User user)
  1128. {
  1129. var itemsResult = GetItems(new InternalItemsQuery(user)
  1130. {
  1131. Recursive = true,
  1132. IsFolder = false,
  1133. ExcludeLocationTypes = new[] { LocationType.Virtual },
  1134. EnableTotalRecordCount = false
  1135. }).Result;
  1136. return itemsResult.Items
  1137. .All(i => i.IsPlayed(user));
  1138. }
  1139. public override bool IsUnplayed(User user)
  1140. {
  1141. return !IsPlayed(user);
  1142. }
  1143. [IgnoreDataMember]
  1144. public virtual bool SupportsUserDataFromChildren
  1145. {
  1146. get
  1147. {
  1148. // These are just far too slow.
  1149. if (this is ICollectionFolder)
  1150. {
  1151. return false;
  1152. }
  1153. if (this is UserView)
  1154. {
  1155. return false;
  1156. }
  1157. if (this is UserRootFolder)
  1158. {
  1159. return false;
  1160. }
  1161. if (this is Channel)
  1162. {
  1163. return false;
  1164. }
  1165. if (SourceType != SourceType.Library)
  1166. {
  1167. return false;
  1168. }
  1169. return true;
  1170. }
  1171. }
  1172. public override async Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1173. {
  1174. if (!SupportsUserDataFromChildren)
  1175. {
  1176. return;
  1177. }
  1178. var unplayedQueryResult = await GetItems(new InternalItemsQuery(user)
  1179. {
  1180. Recursive = true,
  1181. IsFolder = false,
  1182. IsVirtualItem = false,
  1183. EnableTotalRecordCount = true,
  1184. Limit = 0,
  1185. IsPlayed = false
  1186. }).ConfigureAwait(false);
  1187. var allItemsQueryResult = await GetItems(new InternalItemsQuery(user)
  1188. {
  1189. Recursive = true,
  1190. IsFolder = false,
  1191. IsVirtualItem = false,
  1192. EnableTotalRecordCount = true,
  1193. Limit = 0
  1194. }).ConfigureAwait(false);
  1195. if (itemDto != null)
  1196. {
  1197. itemDto.RecursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1198. }
  1199. double recursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1200. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1201. if (recursiveItemCount > 0)
  1202. {
  1203. var unplayedPercentage = (unplayedCount / recursiveItemCount) * 100;
  1204. dto.PlayedPercentage = 100 - unplayedPercentage;
  1205. dto.Played = dto.PlayedPercentage.Value >= 100;
  1206. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1207. }
  1208. }
  1209. }
  1210. }