Folder.cs 55 KB

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