Folder.cs 56 KB

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