Folder.cs 56 KB

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