Folder.cs 56 KB

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