Folder.cs 55 KB

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