Folder.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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.Common.IO;
  14. using MediaBrowser.Controller.Channels;
  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. ParentId = Id,
  567. GroupByPresentationUniqueKey = false
  568. });
  569. }
  570. public virtual int GetChildCount(User user)
  571. {
  572. if (LinkedChildren.Count > 0)
  573. {
  574. if (!(this is ICollectionFolder))
  575. {
  576. return GetChildren(user, true).Count();
  577. }
  578. }
  579. var result = GetItems(new InternalItemsQuery(user)
  580. {
  581. Recursive = false,
  582. Limit = 0,
  583. ParentId = Id
  584. }).Result;
  585. return result.TotalRecordCount;
  586. }
  587. public virtual int GetRecursiveChildCount(User user)
  588. {
  589. return GetItems(new InternalItemsQuery(user)
  590. {
  591. Recursive = true,
  592. IsFolder = false,
  593. IsVirtualItem = false,
  594. EnableTotalRecordCount = true,
  595. Limit = 0
  596. }).Result.TotalRecordCount;
  597. }
  598. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  599. {
  600. var user = query.User;
  601. if (!query.ForceDirect && RequiresPostFiltering(query))
  602. {
  603. IEnumerable<BaseItem> items;
  604. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  605. if (query.User == null)
  606. {
  607. items = GetRecursiveChildren(filter);
  608. }
  609. else
  610. {
  611. items = GetRecursiveChildren(user, query);
  612. }
  613. return PostFilterAndSort(items, query, true, true);
  614. }
  615. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  616. {
  617. query.ParentId = query.ParentId ?? Id;
  618. }
  619. if (RequiresPostFiltering2(query))
  620. {
  621. return QueryWithPostFiltering2(query);
  622. }
  623. return LibraryManager.GetItemsResult(query);
  624. }
  625. private QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  626. {
  627. var startIndex = query.StartIndex;
  628. var limit = query.Limit;
  629. query.StartIndex = null;
  630. query.Limit = null;
  631. var itemsList = LibraryManager.GetItemList(query);
  632. var user = query.User;
  633. if (user != null)
  634. {
  635. // needed for boxsets
  636. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User));
  637. }
  638. IEnumerable<BaseItem> returnItems;
  639. int totalCount = 0;
  640. if (query.EnableTotalRecordCount)
  641. {
  642. var itemsArray = itemsList.ToArray();
  643. totalCount = itemsArray.Length;
  644. returnItems = itemsArray;
  645. }
  646. else
  647. {
  648. returnItems = itemsList;
  649. }
  650. if (limit.HasValue)
  651. {
  652. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value);
  653. }
  654. else if (startIndex.HasValue)
  655. {
  656. returnItems = returnItems.Skip(startIndex.Value);
  657. }
  658. return new QueryResult<BaseItem>
  659. {
  660. TotalRecordCount = totalCount,
  661. Items = returnItems.ToArray()
  662. };
  663. }
  664. private bool RequiresPostFiltering2(InternalItemsQuery query)
  665. {
  666. if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
  667. {
  668. Logger.Debug("Query requires post-filtering due to BoxSet query");
  669. return true;
  670. }
  671. return false;
  672. }
  673. private bool RequiresPostFiltering(InternalItemsQuery query)
  674. {
  675. if (LinkedChildren.Count > 0)
  676. {
  677. if (!(this is ICollectionFolder))
  678. {
  679. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  680. return true;
  681. }
  682. }
  683. if (query.SortBy != null && query.SortBy.Length > 0)
  684. {
  685. if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase))
  686. {
  687. Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder");
  688. return true;
  689. }
  690. if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase))
  691. {
  692. Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem");
  693. return true;
  694. }
  695. if (query.SortBy.Contains(ItemSortBy.Players, StringComparer.OrdinalIgnoreCase))
  696. {
  697. Logger.Debug("Query requires post-filtering due to ItemSortBy.Players");
  698. return true;
  699. }
  700. if (query.SortBy.Contains(ItemSortBy.VideoBitRate, StringComparer.OrdinalIgnoreCase))
  701. {
  702. Logger.Debug("Query requires post-filtering due to ItemSortBy.VideoBitRate");
  703. return true;
  704. }
  705. }
  706. if (query.IsInBoxSet.HasValue)
  707. {
  708. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  709. return true;
  710. }
  711. // Filter by Video3DFormat
  712. if (query.Is3D.HasValue)
  713. {
  714. Logger.Debug("Query requires post-filtering due to Is3D");
  715. return true;
  716. }
  717. if (query.HasOfficialRating.HasValue)
  718. {
  719. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  720. return true;
  721. }
  722. if (query.IsPlaceHolder.HasValue)
  723. {
  724. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  725. return true;
  726. }
  727. if (query.HasSpecialFeature.HasValue)
  728. {
  729. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  730. return true;
  731. }
  732. if (query.HasSubtitles.HasValue)
  733. {
  734. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  735. return true;
  736. }
  737. if (query.HasTrailer.HasValue)
  738. {
  739. Logger.Debug("Query requires post-filtering due to HasTrailer");
  740. return true;
  741. }
  742. // Filter by VideoType
  743. if (query.VideoTypes.Length > 0)
  744. {
  745. Logger.Debug("Query requires post-filtering due to VideoTypes");
  746. return true;
  747. }
  748. // Apply person filter
  749. if (query.ItemIdsFromPersonFilters != null)
  750. {
  751. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  752. return true;
  753. }
  754. if (query.MinPlayers.HasValue)
  755. {
  756. Logger.Debug("Query requires post-filtering due to MinPlayers");
  757. return true;
  758. }
  759. if (query.MaxPlayers.HasValue)
  760. {
  761. Logger.Debug("Query requires post-filtering due to MaxPlayers");
  762. return true;
  763. }
  764. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  765. {
  766. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  767. return true;
  768. }
  769. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  770. {
  771. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  772. return true;
  773. }
  774. if (query.AirDays.Length > 0)
  775. {
  776. Logger.Debug("Query requires post-filtering due to AirDays");
  777. return true;
  778. }
  779. if (query.SeriesStatuses.Length > 0)
  780. {
  781. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  782. return true;
  783. }
  784. if (query.AiredDuringSeason.HasValue)
  785. {
  786. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  787. return true;
  788. }
  789. if (!string.IsNullOrWhiteSpace(query.AlbumArtistStartsWithOrGreater))
  790. {
  791. Logger.Debug("Query requires post-filtering due to AlbumArtistStartsWithOrGreater");
  792. return true;
  793. }
  794. if (query.IsPlayed.HasValue)
  795. {
  796. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  797. {
  798. Logger.Debug("Query requires post-filtering due to IsPlayed");
  799. return true;
  800. }
  801. }
  802. return false;
  803. }
  804. public Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  805. {
  806. if (query.ItemIds.Length > 0)
  807. {
  808. var result = LibraryManager.GetItemsResult(query);
  809. if (query.SortBy.Length == 0)
  810. {
  811. var ids = query.ItemIds.ToList();
  812. // Try to preserve order
  813. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  814. }
  815. return Task.FromResult(result);
  816. }
  817. return GetItemsInternal(query);
  818. }
  819. protected virtual async Task<QueryResult<BaseItem>> GetItemsInternal(InternalItemsQuery query)
  820. {
  821. if (SourceType == SourceType.Channel)
  822. {
  823. try
  824. {
  825. // Don't blow up here because it could cause parent screens with other content to fail
  826. return await ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  827. {
  828. ChannelId = ChannelId,
  829. FolderId = Id.ToString("N"),
  830. Limit = query.Limit,
  831. StartIndex = query.StartIndex,
  832. UserId = query.User.Id.ToString("N"),
  833. SortBy = query.SortBy,
  834. SortOrder = query.SortOrder
  835. }, new Progress<double>(), CancellationToken.None);
  836. }
  837. catch
  838. {
  839. // Already logged at lower levels
  840. return new QueryResult<BaseItem>();
  841. }
  842. }
  843. if (query.Recursive)
  844. {
  845. return QueryRecursive(query);
  846. }
  847. var user = query.User;
  848. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  849. IEnumerable<BaseItem> items;
  850. if (query.User == null)
  851. {
  852. items = query.Recursive
  853. ? GetRecursiveChildren(filter)
  854. : Children.Where(filter);
  855. }
  856. else
  857. {
  858. items = query.Recursive
  859. ? GetRecursiveChildren(user, query)
  860. : GetChildren(user, true).Where(filter);
  861. }
  862. return PostFilterAndSort(items, query, true, true);
  863. }
  864. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  865. {
  866. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  867. }
  868. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  869. {
  870. if (user == null)
  871. {
  872. throw new ArgumentNullException();
  873. }
  874. //the true root should return our users root folder children
  875. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  876. var result = new Dictionary<Guid, BaseItem>();
  877. AddChildren(user, includeLinkedChildren, result, false, null);
  878. return result.Values;
  879. }
  880. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  881. {
  882. return Children;
  883. }
  884. /// <summary>
  885. /// Adds the children to list.
  886. /// </summary>
  887. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  888. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  889. {
  890. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  891. {
  892. if (child.IsVisible(user))
  893. {
  894. if (query == null || UserViewBuilder.FilterItem(child, query))
  895. {
  896. result[child.Id] = child;
  897. }
  898. if (recursive && child.IsFolder)
  899. {
  900. var folder = (Folder)child;
  901. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  902. }
  903. }
  904. }
  905. if (includeLinkedChildren)
  906. {
  907. foreach (var child in GetLinkedChildren(user))
  908. {
  909. if (child.IsVisible(user))
  910. {
  911. if (query == null || UserViewBuilder.FilterItem(child, query))
  912. {
  913. result[child.Id] = child;
  914. }
  915. }
  916. }
  917. }
  918. }
  919. /// <summary>
  920. /// Gets allowed recursive children of an item
  921. /// </summary>
  922. /// <param name="user">The user.</param>
  923. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  924. /// <returns>IEnumerable{BaseItem}.</returns>
  925. /// <exception cref="System.ArgumentNullException"></exception>
  926. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  927. {
  928. return GetRecursiveChildren(user, null);
  929. }
  930. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  931. {
  932. if (user == null)
  933. {
  934. throw new ArgumentNullException("user");
  935. }
  936. var result = new Dictionary<Guid, BaseItem>();
  937. AddChildren(user, true, result, true, query);
  938. return result.Values;
  939. }
  940. /// <summary>
  941. /// Gets the recursive children.
  942. /// </summary>
  943. /// <returns>IList{BaseItem}.</returns>
  944. public IList<BaseItem> GetRecursiveChildren()
  945. {
  946. return GetRecursiveChildren(true);
  947. }
  948. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  949. {
  950. return GetRecursiveChildren(i => true, includeLinkedChildren);
  951. }
  952. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  953. {
  954. return GetRecursiveChildren(filter, true);
  955. }
  956. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  957. {
  958. var result = new Dictionary<Guid, BaseItem>();
  959. AddChildrenToList(result, includeLinkedChildren, true, filter);
  960. return result.Values.ToList();
  961. }
  962. /// <summary>
  963. /// Adds the children to list.
  964. /// </summary>
  965. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  966. {
  967. foreach (var child in Children)
  968. {
  969. if (filter == null || filter(child))
  970. {
  971. result[child.Id] = child;
  972. }
  973. if (recursive && child.IsFolder)
  974. {
  975. var folder = (Folder)child;
  976. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  977. folder.AddChildrenToList(result, false, true, filter);
  978. }
  979. }
  980. if (includeLinkedChildren)
  981. {
  982. foreach (var child in GetLinkedChildren())
  983. {
  984. if (filter == null || filter(child))
  985. {
  986. result[child.Id] = child;
  987. }
  988. }
  989. }
  990. }
  991. /// <summary>
  992. /// Gets the linked children.
  993. /// </summary>
  994. /// <returns>IEnumerable{BaseItem}.</returns>
  995. public IEnumerable<BaseItem> GetLinkedChildren()
  996. {
  997. return LinkedChildren
  998. .Select(GetLinkedChild)
  999. .Where(i => i != null);
  1000. }
  1001. protected virtual bool FilterLinkedChildrenPerUser
  1002. {
  1003. get
  1004. {
  1005. return false;
  1006. }
  1007. }
  1008. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  1009. {
  1010. if (!FilterLinkedChildrenPerUser || user == null)
  1011. {
  1012. return GetLinkedChildren();
  1013. }
  1014. if (LinkedChildren.Count == 0)
  1015. {
  1016. return new List<BaseItem>();
  1017. }
  1018. var allUserRootChildren = user.RootFolder.Children.OfType<Folder>().ToList();
  1019. var collectionFolderIds = allUserRootChildren
  1020. .OfType<CollectionFolder>()
  1021. .Where(i => i.IsVisible(user))
  1022. .Select(i => i.Id)
  1023. .ToList();
  1024. return LinkedChildren
  1025. .Select(i =>
  1026. {
  1027. var child = GetLinkedChild(i);
  1028. if (child != null)
  1029. {
  1030. var childLocationType = child.LocationType;
  1031. if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
  1032. {
  1033. if (!child.IsVisibleStandalone(user))
  1034. {
  1035. return null;
  1036. }
  1037. }
  1038. else if (childLocationType == LocationType.FileSystem)
  1039. {
  1040. var itemCollectionFolderIds =
  1041. LibraryManager.GetCollectionFolders(child, allUserRootChildren)
  1042. .Select(f => f.Id).ToList();
  1043. if (!itemCollectionFolderIds.Any(collectionFolderIds.Contains))
  1044. {
  1045. return null;
  1046. }
  1047. }
  1048. }
  1049. return child;
  1050. })
  1051. .Where(i => i != null);
  1052. }
  1053. /// <summary>
  1054. /// Gets the linked children.
  1055. /// </summary>
  1056. /// <returns>IEnumerable{BaseItem}.</returns>
  1057. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1058. {
  1059. return LinkedChildren
  1060. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1061. .Where(i => i.Item2 != null);
  1062. }
  1063. [IgnoreDataMember]
  1064. protected override bool SupportsOwnedItems
  1065. {
  1066. get
  1067. {
  1068. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1069. }
  1070. }
  1071. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1072. {
  1073. var changesFound = false;
  1074. if (LocationType == LocationType.FileSystem)
  1075. {
  1076. if (RefreshLinkedChildren(fileSystemChildren))
  1077. {
  1078. changesFound = true;
  1079. }
  1080. }
  1081. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1082. return baseHasChanges || changesFound;
  1083. }
  1084. /// <summary>
  1085. /// Refreshes the linked children.
  1086. /// </summary>
  1087. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1088. protected virtual bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1089. {
  1090. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1091. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1092. List<LinkedChild> newShortcutLinks;
  1093. if (SupportsShortcutChildren)
  1094. {
  1095. newShortcutLinks = fileSystemChildren
  1096. .Where(i => !i.IsDirectory && FileSystem.IsShortcut(i.FullName))
  1097. .Select(i =>
  1098. {
  1099. try
  1100. {
  1101. Logger.Debug("Found shortcut at {0}", i.FullName);
  1102. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1103. if (!string.IsNullOrEmpty(resolvedPath))
  1104. {
  1105. return new LinkedChild
  1106. {
  1107. Path = resolvedPath,
  1108. Type = LinkedChildType.Shortcut
  1109. };
  1110. }
  1111. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1112. return null;
  1113. }
  1114. catch (IOException ex)
  1115. {
  1116. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1117. return null;
  1118. }
  1119. })
  1120. .Where(i => i != null)
  1121. .ToList();
  1122. }
  1123. else { newShortcutLinks = new List<LinkedChild>(); }
  1124. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer(FileSystem)))
  1125. {
  1126. Logger.Info("Shortcut links have changed for {0}", Path);
  1127. newShortcutLinks.AddRange(currentManualLinks);
  1128. LinkedChildren = newShortcutLinks;
  1129. return true;
  1130. }
  1131. foreach (var child in LinkedChildren)
  1132. {
  1133. // Reset the cached value
  1134. child.ItemId = null;
  1135. }
  1136. return false;
  1137. }
  1138. /// <summary>
  1139. /// Folders need to validate and refresh
  1140. /// </summary>
  1141. /// <returns>Task.</returns>
  1142. public override async Task ChangedExternally()
  1143. {
  1144. var progress = new Progress<double>();
  1145. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1146. await base.ChangedExternally().ConfigureAwait(false);
  1147. }
  1148. /// <summary>
  1149. /// Marks the played.
  1150. /// </summary>
  1151. /// <param name="user">The user.</param>
  1152. /// <param name="datePlayed">The date played.</param>
  1153. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1154. /// <returns>Task.</returns>
  1155. public override async Task MarkPlayed(User user,
  1156. DateTime? datePlayed,
  1157. bool resetPosition)
  1158. {
  1159. var query = new InternalItemsQuery
  1160. {
  1161. User = user,
  1162. Recursive = true,
  1163. IsFolder = false,
  1164. EnableTotalRecordCount = false
  1165. };
  1166. if (!user.Configuration.DisplayMissingEpisodes || !user.Configuration.DisplayUnairedEpisodes)
  1167. {
  1168. query.IsVirtualItem = false;
  1169. }
  1170. var itemsResult = await GetItems(query).ConfigureAwait(false);
  1171. // Sweep through recursively and update status
  1172. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1173. await Task.WhenAll(tasks).ConfigureAwait(false);
  1174. }
  1175. /// <summary>
  1176. /// Marks the unplayed.
  1177. /// </summary>
  1178. /// <param name="user">The user.</param>
  1179. /// <returns>Task.</returns>
  1180. public override async Task MarkUnplayed(User user)
  1181. {
  1182. var itemsResult = await GetItems(new InternalItemsQuery
  1183. {
  1184. User = user,
  1185. Recursive = true,
  1186. IsFolder = false,
  1187. EnableTotalRecordCount = false
  1188. }).ConfigureAwait(false);
  1189. // Sweep through recursively and update status
  1190. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1191. await Task.WhenAll(tasks).ConfigureAwait(false);
  1192. }
  1193. public override bool IsPlayed(User user)
  1194. {
  1195. var itemsResult = GetItems(new InternalItemsQuery(user)
  1196. {
  1197. Recursive = true,
  1198. IsFolder = false,
  1199. IsVirtualItem = false,
  1200. EnableTotalRecordCount = false
  1201. }).Result;
  1202. return itemsResult.Items
  1203. .All(i => i.IsPlayed(user));
  1204. }
  1205. public override bool IsUnplayed(User user)
  1206. {
  1207. return !IsPlayed(user);
  1208. }
  1209. [IgnoreDataMember]
  1210. public virtual bool SupportsUserDataFromChildren
  1211. {
  1212. get
  1213. {
  1214. // These are just far too slow.
  1215. if (this is ICollectionFolder)
  1216. {
  1217. return false;
  1218. }
  1219. if (this is UserView)
  1220. {
  1221. return false;
  1222. }
  1223. if (this is UserRootFolder)
  1224. {
  1225. return false;
  1226. }
  1227. if (this is Channel)
  1228. {
  1229. return false;
  1230. }
  1231. if (SourceType != SourceType.Library)
  1232. {
  1233. return false;
  1234. }
  1235. var iItemByName = this as IItemByName;
  1236. if (iItemByName != null)
  1237. {
  1238. var hasDualAccess = this as IHasDualAccess;
  1239. if (hasDualAccess == null || hasDualAccess.IsAccessedByName)
  1240. {
  1241. return false;
  1242. }
  1243. }
  1244. return true;
  1245. }
  1246. }
  1247. public override async Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, List<ItemFields> itemFields)
  1248. {
  1249. if (!SupportsUserDataFromChildren)
  1250. {
  1251. return;
  1252. }
  1253. if (itemDto != null)
  1254. {
  1255. if (itemFields.Contains(ItemFields.RecursiveItemCount))
  1256. {
  1257. itemDto.RecursiveItemCount = GetRecursiveChildCount(user);
  1258. }
  1259. }
  1260. if (SupportsPlayedStatus)
  1261. {
  1262. var unplayedQueryResult = await GetItems(new InternalItemsQuery(user)
  1263. {
  1264. Recursive = true,
  1265. IsFolder = false,
  1266. IsVirtualItem = false,
  1267. EnableTotalRecordCount = true,
  1268. Limit = 0,
  1269. IsPlayed = false
  1270. }).ConfigureAwait(false);
  1271. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1272. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1273. if (itemDto != null && itemDto.RecursiveItemCount.HasValue)
  1274. {
  1275. if (itemDto.RecursiveItemCount.Value > 0)
  1276. {
  1277. var unplayedPercentage = (unplayedCount / itemDto.RecursiveItemCount.Value) * 100;
  1278. dto.PlayedPercentage = 100 - unplayedPercentage;
  1279. dto.Played = dto.PlayedPercentage.Value >= 100;
  1280. }
  1281. }
  1282. else
  1283. {
  1284. dto.Played = (dto.UnplayedItemCount ?? 0) == 0;
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }