Folder.cs 50 KB

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