Folder.cs 55 KB

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