Folder.cs 54 KB

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