2
0

Folder.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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) && query.ParentId == Guid.Empty)
  538. {
  539. query.Parent = this;
  540. }
  541. if (RequiresPostFiltering2(query))
  542. {
  543. return QueryWithPostFiltering2(query);
  544. }
  545. return LibraryManager.GetItemsResult(query);
  546. }
  547. private QueryResult<BaseItem> QueryWithPostFiltering2(InternalItemsQuery query)
  548. {
  549. var startIndex = query.StartIndex;
  550. var limit = query.Limit;
  551. query.StartIndex = null;
  552. query.Limit = null;
  553. var itemsList = LibraryManager.GetItemList(query);
  554. var user = query.User;
  555. if (user != null)
  556. {
  557. // needed for boxsets
  558. itemsList = itemsList.Where(i => i.IsVisibleStandalone(query.User)).ToList();
  559. }
  560. BaseItem[] returnItems;
  561. int totalCount = 0;
  562. if (query.EnableTotalRecordCount)
  563. {
  564. var itemsArray = itemsList.ToArray();
  565. totalCount = itemsArray.Length;
  566. returnItems = itemsArray;
  567. }
  568. else
  569. {
  570. returnItems = itemsList.ToArray();
  571. }
  572. if (limit.HasValue)
  573. {
  574. returnItems = returnItems.Skip(startIndex ?? 0).Take(limit.Value).ToArray();
  575. }
  576. else if (startIndex.HasValue)
  577. {
  578. returnItems = returnItems.Skip(startIndex.Value).ToArray();
  579. }
  580. return new QueryResult<BaseItem>
  581. {
  582. TotalRecordCount = totalCount,
  583. Items = returnItems.ToArray()
  584. };
  585. }
  586. private bool RequiresPostFiltering2(InternalItemsQuery query)
  587. {
  588. if (query.IncludeItemTypes.Length == 1 && string.Equals(query.IncludeItemTypes[0], typeof(BoxSet).Name, StringComparison.OrdinalIgnoreCase))
  589. {
  590. Logger.LogDebug("Query requires post-filtering due to BoxSet query");
  591. return true;
  592. }
  593. return false;
  594. }
  595. private bool RequiresPostFiltering(InternalItemsQuery query)
  596. {
  597. if (LinkedChildren.Length > 0)
  598. {
  599. if (!(this is ICollectionFolder))
  600. {
  601. Logger.LogDebug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  602. return true;
  603. }
  604. }
  605. // Filter by Video3DFormat
  606. if (query.Is3D.HasValue)
  607. {
  608. Logger.LogDebug("Query requires post-filtering due to Is3D");
  609. return true;
  610. }
  611. if (query.HasOfficialRating.HasValue)
  612. {
  613. Logger.LogDebug("Query requires post-filtering due to HasOfficialRating");
  614. return true;
  615. }
  616. if (query.IsPlaceHolder.HasValue)
  617. {
  618. Logger.LogDebug("Query requires post-filtering due to IsPlaceHolder");
  619. return true;
  620. }
  621. if (query.HasSpecialFeature.HasValue)
  622. {
  623. Logger.LogDebug("Query requires post-filtering due to HasSpecialFeature");
  624. return true;
  625. }
  626. if (query.HasSubtitles.HasValue)
  627. {
  628. Logger.LogDebug("Query requires post-filtering due to HasSubtitles");
  629. return true;
  630. }
  631. if (query.HasTrailer.HasValue)
  632. {
  633. Logger.LogDebug("Query requires post-filtering due to HasTrailer");
  634. return true;
  635. }
  636. // Filter by VideoType
  637. if (query.VideoTypes.Length > 0)
  638. {
  639. Logger.LogDebug("Query requires post-filtering due to VideoTypes");
  640. return true;
  641. }
  642. if (CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  643. {
  644. Logger.LogDebug("Query requires post-filtering due to CollapseBoxSetItems");
  645. return true;
  646. }
  647. if (!string.IsNullOrEmpty(query.AdjacentTo))
  648. {
  649. Logger.LogDebug("Query requires post-filtering due to AdjacentTo");
  650. return true;
  651. }
  652. if (query.SeriesStatuses.Length > 0)
  653. {
  654. Logger.LogDebug("Query requires post-filtering due to SeriesStatuses");
  655. return true;
  656. }
  657. if (query.AiredDuringSeason.HasValue)
  658. {
  659. Logger.LogDebug("Query requires post-filtering due to AiredDuringSeason");
  660. return true;
  661. }
  662. if (query.IsPlayed.HasValue)
  663. {
  664. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  665. {
  666. Logger.LogDebug("Query requires post-filtering due to IsPlayed");
  667. return true;
  668. }
  669. }
  670. return false;
  671. }
  672. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  673. {
  674. if (query.ItemIds.Length > 0)
  675. {
  676. var result = LibraryManager.GetItemsResult(query);
  677. if (query.OrderBy.Length == 0)
  678. {
  679. var ids = query.ItemIds.ToList();
  680. // Try to preserve order
  681. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id)).ToArray();
  682. }
  683. return result;
  684. }
  685. return GetItemsInternal(query);
  686. }
  687. public BaseItem[] GetItemList(InternalItemsQuery query)
  688. {
  689. query.EnableTotalRecordCount = false;
  690. if (query.ItemIds.Length > 0)
  691. {
  692. var result = LibraryManager.GetItemList(query);
  693. if (query.OrderBy.Length == 0)
  694. {
  695. var ids = query.ItemIds.ToList();
  696. // Try to preserve order
  697. return result.OrderBy(i => ids.IndexOf(i.Id)).ToArray();
  698. }
  699. return result.ToArray();
  700. }
  701. return GetItemsInternal(query).Items;
  702. }
  703. protected virtual QueryResult<BaseItem> GetItemsInternal(InternalItemsQuery query)
  704. {
  705. if (SourceType == SourceType.Channel)
  706. {
  707. try
  708. {
  709. query.Parent = this;
  710. query.ChannelIds = new Guid[] { ChannelId };
  711. // Don't blow up here because it could cause parent screens with other content to fail
  712. return ChannelManager.GetChannelItemsInternal(query, new SimpleProgress<double>(), CancellationToken.None).Result;
  713. }
  714. catch
  715. {
  716. // Already logged at lower levels
  717. return new QueryResult<BaseItem>();
  718. }
  719. }
  720. if (query.Recursive)
  721. {
  722. return QueryRecursive(query);
  723. }
  724. var user = query.User;
  725. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  726. IEnumerable<BaseItem> items;
  727. if (query.User == null)
  728. {
  729. items = Children.Where(filter);
  730. }
  731. else
  732. {
  733. items = GetChildren(user, true).Where(filter);
  734. }
  735. return PostFilterAndSort(items, query, true);
  736. }
  737. public static ICollectionManager CollectionManager { get; set; }
  738. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool enableSorting)
  739. {
  740. var user = query.User;
  741. // Check recursive - don't substitute in plain folder views
  742. if (user != null)
  743. {
  744. items = CollapseBoxSetItemsIfNeeded(items, query, this, user, ConfigurationManager, CollectionManager);
  745. }
  746. if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater))
  747. {
  748. items = items.Where(i => string.Compare(query.NameStartsWithOrGreater, i.SortName, StringComparison.CurrentCultureIgnoreCase) < 1);
  749. }
  750. if (!string.IsNullOrEmpty(query.NameStartsWith))
  751. {
  752. items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.OrdinalIgnoreCase));
  753. }
  754. if (!string.IsNullOrEmpty(query.NameLessThan))
  755. {
  756. items = items.Where(i => string.Compare(query.NameLessThan, i.SortName, StringComparison.CurrentCultureIgnoreCase) == 1);
  757. }
  758. // This must be the last filter
  759. if (!string.IsNullOrEmpty(query.AdjacentTo))
  760. {
  761. items = UserViewBuilder.FilterForAdjacency(items.ToList(), query.AdjacentTo);
  762. }
  763. return UserViewBuilder.SortAndPage(items, null, query, LibraryManager, enableSorting);
  764. }
  765. private static IEnumerable<BaseItem> CollapseBoxSetItemsIfNeeded(IEnumerable<BaseItem> items,
  766. InternalItemsQuery query,
  767. BaseItem queryParent,
  768. User user,
  769. IServerConfigurationManager configurationManager, ICollectionManager collectionManager)
  770. {
  771. if (items == null)
  772. {
  773. throw new ArgumentNullException(nameof(items));
  774. }
  775. if (CollapseBoxSetItems(query, queryParent, user, configurationManager))
  776. {
  777. items = collectionManager.CollapseItemsWithinBoxSets(items, user);
  778. }
  779. return items;
  780. }
  781. private static bool CollapseBoxSetItems(InternalItemsQuery query,
  782. BaseItem queryParent,
  783. User user,
  784. IServerConfigurationManager configurationManager)
  785. {
  786. // Could end up stuck in a loop like this
  787. if (queryParent is BoxSet)
  788. {
  789. return false;
  790. }
  791. if (queryParent is Series)
  792. {
  793. return false;
  794. }
  795. if (queryParent is Season)
  796. {
  797. return false;
  798. }
  799. if (queryParent is MusicAlbum)
  800. {
  801. return false;
  802. }
  803. if (queryParent is MusicArtist)
  804. {
  805. return false;
  806. }
  807. var param = query.CollapseBoxSetItems;
  808. if (!param.HasValue)
  809. {
  810. if (user != null && !configurationManager.Configuration.EnableGroupingIntoCollections)
  811. {
  812. return false;
  813. }
  814. if (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains("Movie", StringComparer.OrdinalIgnoreCase))
  815. {
  816. param = true;
  817. }
  818. }
  819. return param.HasValue && param.Value && AllowBoxSetCollapsing(query);
  820. }
  821. private static bool AllowBoxSetCollapsing(InternalItemsQuery request)
  822. {
  823. if (request.IsFavorite.HasValue)
  824. {
  825. return false;
  826. }
  827. if (request.IsFavoriteOrLiked.HasValue)
  828. {
  829. return false;
  830. }
  831. if (request.IsLiked.HasValue)
  832. {
  833. return false;
  834. }
  835. if (request.IsPlayed.HasValue)
  836. {
  837. return false;
  838. }
  839. if (request.IsResumable.HasValue)
  840. {
  841. return false;
  842. }
  843. if (request.IsFolder.HasValue)
  844. {
  845. return false;
  846. }
  847. if (request.Genres.Length > 0)
  848. {
  849. return false;
  850. }
  851. if (request.GenreIds.Length > 0)
  852. {
  853. return false;
  854. }
  855. if (request.HasImdbId.HasValue)
  856. {
  857. return false;
  858. }
  859. if (request.HasOfficialRating.HasValue)
  860. {
  861. return false;
  862. }
  863. if (request.HasOverview.HasValue)
  864. {
  865. return false;
  866. }
  867. if (request.HasParentalRating.HasValue)
  868. {
  869. return false;
  870. }
  871. if (request.HasSpecialFeature.HasValue)
  872. {
  873. return false;
  874. }
  875. if (request.HasSubtitles.HasValue)
  876. {
  877. return false;
  878. }
  879. if (request.HasThemeSong.HasValue)
  880. {
  881. return false;
  882. }
  883. if (request.HasThemeVideo.HasValue)
  884. {
  885. return false;
  886. }
  887. if (request.HasTmdbId.HasValue)
  888. {
  889. return false;
  890. }
  891. if (request.HasTrailer.HasValue)
  892. {
  893. return false;
  894. }
  895. if (request.ImageTypes.Length > 0)
  896. {
  897. return false;
  898. }
  899. if (request.Is3D.HasValue)
  900. {
  901. return false;
  902. }
  903. if (request.IsHD.HasValue)
  904. {
  905. return false;
  906. }
  907. if (request.IsLocked.HasValue)
  908. {
  909. return false;
  910. }
  911. if (request.IsPlaceHolder.HasValue)
  912. {
  913. return false;
  914. }
  915. if (request.IsPlayed.HasValue)
  916. {
  917. return false;
  918. }
  919. if (!string.IsNullOrWhiteSpace(request.Person))
  920. {
  921. return false;
  922. }
  923. if (request.PersonIds.Length > 0)
  924. {
  925. return false;
  926. }
  927. if (request.ItemIds.Length > 0)
  928. {
  929. return false;
  930. }
  931. if (request.StudioIds.Length > 0)
  932. {
  933. return false;
  934. }
  935. if (request.GenreIds.Length > 0)
  936. {
  937. return false;
  938. }
  939. if (request.VideoTypes.Length > 0)
  940. {
  941. return false;
  942. }
  943. if (request.Years.Length > 0)
  944. {
  945. return false;
  946. }
  947. if (request.Tags.Length > 0)
  948. {
  949. return false;
  950. }
  951. if (request.OfficialRatings.Length > 0)
  952. {
  953. return false;
  954. }
  955. if (request.MinPlayers.HasValue)
  956. {
  957. return false;
  958. }
  959. if (request.MaxPlayers.HasValue)
  960. {
  961. return false;
  962. }
  963. if (request.MinCommunityRating.HasValue)
  964. {
  965. return false;
  966. }
  967. if (request.MinCriticRating.HasValue)
  968. {
  969. return false;
  970. }
  971. if (request.MinIndexNumber.HasValue)
  972. {
  973. return false;
  974. }
  975. return true;
  976. }
  977. public List<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  978. {
  979. return GetChildren(user, includeLinkedChildren, null);
  980. }
  981. public virtual List<BaseItem> GetChildren(User user, bool includeLinkedChildren, InternalItemsQuery query)
  982. {
  983. if (user == null)
  984. {
  985. throw new ArgumentNullException(nameof(user));
  986. }
  987. //the true root should return our users root folder children
  988. if (IsPhysicalRoot) return LibraryManager.GetUserRootFolder().GetChildren(user, includeLinkedChildren);
  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. [IgnoreDataMember]
  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. [IgnoreDataMember]
  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. }