Folder.cs 56 KB

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