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