Folder.cs 56 KB

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