2
0

Folder.cs 56 KB

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