2
0

Folder.cs 56 KB

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