Folder.cs 56 KB

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