Folder.cs 55 KB

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