Folder.cs 54 KB

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