Folder.cs 56 KB

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