Folder.cs 49 KB

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