Folder.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  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.Runtime.Serialization;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Controller.Channels;
  16. using MediaBrowser.Controller.Entities.Audio;
  17. using MediaBrowser.Controller.Entities.TV;
  18. using MediaBrowser.Model.Channels;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class Folder
  23. /// </summary>
  24. public class Folder : BaseItem
  25. {
  26. public static IUserManager UserManager { get; set; }
  27. public static IUserViewManager UserViewManager { get; set; }
  28. /// <summary>
  29. /// Gets or sets a value indicating whether this instance is root.
  30. /// </summary>
  31. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  32. public bool IsRoot { get; set; }
  33. public virtual List<LinkedChild> LinkedChildren { get; set; }
  34. [IgnoreDataMember]
  35. public DateTime? DateLastMediaAdded { get; set; }
  36. public Folder()
  37. {
  38. LinkedChildren = new List<LinkedChild>();
  39. }
  40. [IgnoreDataMember]
  41. public override bool SupportsThemeMedia
  42. {
  43. get { return true; }
  44. }
  45. [IgnoreDataMember]
  46. public virtual bool IsPreSorted
  47. {
  48. get { return false; }
  49. }
  50. [IgnoreDataMember]
  51. public virtual bool IsPhysicalRoot
  52. {
  53. get { return false; }
  54. }
  55. [IgnoreDataMember]
  56. public override bool SupportsPlayedStatus
  57. {
  58. get
  59. {
  60. return true;
  61. }
  62. }
  63. /// <summary>
  64. /// Gets a value indicating whether this instance is folder.
  65. /// </summary>
  66. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  67. [IgnoreDataMember]
  68. public override bool IsFolder
  69. {
  70. get
  71. {
  72. return true;
  73. }
  74. }
  75. [IgnoreDataMember]
  76. public virtual bool SupportsCumulativeRunTimeTicks
  77. {
  78. get
  79. {
  80. return false;
  81. }
  82. }
  83. [IgnoreDataMember]
  84. public virtual bool SupportsDateLastMediaAdded
  85. {
  86. get
  87. {
  88. return false;
  89. }
  90. }
  91. public override bool RequiresRefresh()
  92. {
  93. var baseResult = base.RequiresRefresh();
  94. if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue)
  95. {
  96. baseResult = true;
  97. }
  98. return baseResult;
  99. }
  100. [IgnoreDataMember]
  101. public override string FileNameWithoutExtension
  102. {
  103. get
  104. {
  105. if (LocationType == LocationType.FileSystem)
  106. {
  107. return System.IO.Path.GetFileName(Path);
  108. }
  109. return null;
  110. }
  111. }
  112. protected override bool IsAllowTagFilterEnforced()
  113. {
  114. if (this is ICollectionFolder)
  115. {
  116. return false;
  117. }
  118. if (this is UserView)
  119. {
  120. return false;
  121. }
  122. return true;
  123. }
  124. [IgnoreDataMember]
  125. protected virtual bool SupportsShortcutChildren
  126. {
  127. get { return false; }
  128. }
  129. /// <summary>
  130. /// Adds the child.
  131. /// </summary>
  132. /// <param name="item">The item.</param>
  133. /// <param name="cancellationToken">The cancellation token.</param>
  134. /// <returns>Task.</returns>
  135. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  136. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  137. {
  138. item.SetParent(this);
  139. if (item.Id == Guid.Empty)
  140. {
  141. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  142. }
  143. if (ActualChildren.Any(i => i.Id == item.Id))
  144. {
  145. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  146. }
  147. if (item.DateCreated == DateTime.MinValue)
  148. {
  149. item.DateCreated = DateTime.UtcNow;
  150. }
  151. if (item.DateModified == DateTime.MinValue)
  152. {
  153. item.DateModified = DateTime.UtcNow;
  154. }
  155. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  156. }
  157. /// <summary>
  158. /// Removes the child.
  159. /// </summary>
  160. /// <param name="item">The item.</param>
  161. public void RemoveChild(BaseItem item)
  162. {
  163. item.SetParent(null);
  164. }
  165. /// <summary>
  166. /// Returns the valid set of index by options for this folder type.
  167. /// Override or extend to modify.
  168. /// </summary>
  169. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  170. protected virtual IEnumerable<string> GetIndexByOptions()
  171. {
  172. return new List<string> {
  173. {"None"},
  174. {"Performer"},
  175. {"Genre"},
  176. {"Director"},
  177. {"Year"},
  178. {"Studio"}
  179. };
  180. }
  181. /// <summary>
  182. /// Get the list of indexy by choices for this folder (localized).
  183. /// </summary>
  184. /// <value>The index by option strings.</value>
  185. [IgnoreDataMember]
  186. public IEnumerable<string> IndexByOptionStrings
  187. {
  188. get { return GetIndexByOptions(); }
  189. }
  190. /// <summary>
  191. /// Gets the actual children.
  192. /// </summary>
  193. /// <value>The actual children.</value>
  194. [IgnoreDataMember]
  195. protected virtual IEnumerable<BaseItem> ActualChildren
  196. {
  197. get
  198. {
  199. return LoadChildren();
  200. }
  201. }
  202. /// <summary>
  203. /// thread-safe access to the actual children of this folder - without regard to user
  204. /// </summary>
  205. /// <value>The children.</value>
  206. [IgnoreDataMember]
  207. public IEnumerable<BaseItem> Children
  208. {
  209. get { return ActualChildren.ToList(); }
  210. }
  211. /// <summary>
  212. /// thread-safe access to all recursive children of this folder - without regard to user
  213. /// </summary>
  214. /// <value>The recursive children.</value>
  215. [IgnoreDataMember]
  216. public IEnumerable<BaseItem> RecursiveChildren
  217. {
  218. get { return GetRecursiveChildren(); }
  219. }
  220. public override bool IsVisible(User user)
  221. {
  222. if (this is ICollectionFolder && !(this is BasePluginFolder))
  223. {
  224. if (user.Policy.BlockedMediaFolders != null)
  225. {
  226. if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  227. // Backwards compatibility
  228. user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  229. {
  230. return false;
  231. }
  232. }
  233. else
  234. {
  235. if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  236. {
  237. return false;
  238. }
  239. }
  240. }
  241. return base.IsVisible(user);
  242. }
  243. /// <summary>
  244. /// Loads our children. Validation will occur externally.
  245. /// We want this sychronous.
  246. /// </summary>
  247. protected virtual IEnumerable<BaseItem> LoadChildren()
  248. {
  249. //Logger.Debug("Loading children from {0} {1} {2}", GetType().Name, Id, Path);
  250. //just load our children from the repo - the library will be validated and maintained in other processes
  251. return GetCachedChildren();
  252. }
  253. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  254. {
  255. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)));
  256. }
  257. /// <summary>
  258. /// Validates that the children of the folder still exist
  259. /// </summary>
  260. /// <param name="progress">The progress.</param>
  261. /// <param name="cancellationToken">The cancellation token.</param>
  262. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  263. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  264. /// <returns>Task.</returns>
  265. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  266. {
  267. return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  268. }
  269. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  270. {
  271. var dictionary = new Dictionary<Guid, BaseItem>();
  272. foreach (var child in ActualChildren)
  273. {
  274. var id = child.Id;
  275. if (dictionary.ContainsKey(id))
  276. {
  277. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  278. Path ?? Name,
  279. child.Path ?? child.Name);
  280. }
  281. else
  282. {
  283. dictionary[id] = child;
  284. }
  285. }
  286. return dictionary;
  287. }
  288. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  289. {
  290. return current.IsValidFromResolver(newItem);
  291. }
  292. /// <summary>
  293. /// Validates the children internal.
  294. /// </summary>
  295. /// <param name="progress">The progress.</param>
  296. /// <param name="cancellationToken">The cancellation token.</param>
  297. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  298. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  299. /// <param name="refreshOptions">The refresh options.</param>
  300. /// <param name="directoryService">The directory service.</param>
  301. /// <returns>Task.</returns>
  302. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  303. {
  304. var locationType = LocationType;
  305. cancellationToken.ThrowIfCancellationRequested();
  306. var validChildren = new List<BaseItem>();
  307. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  308. {
  309. IEnumerable<BaseItem> nonCachedChildren;
  310. try
  311. {
  312. nonCachedChildren = GetNonCachedChildren(directoryService);
  313. }
  314. catch (IOException ex)
  315. {
  316. nonCachedChildren = new BaseItem[] { };
  317. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  318. }
  319. if (nonCachedChildren == null) return; //nothing to validate
  320. progress.Report(5);
  321. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  322. var currentChildren = GetActualChildrenDictionary();
  323. //create a list for our validated children
  324. var newItems = new List<BaseItem>();
  325. cancellationToken.ThrowIfCancellationRequested();
  326. foreach (var child in nonCachedChildren)
  327. {
  328. BaseItem currentChild;
  329. if (currentChildren.TryGetValue(child.Id, out currentChild) && IsValidFromResolver(currentChild, child))
  330. {
  331. await currentChild.UpdateIsOffline(false).ConfigureAwait(false);
  332. validChildren.Add(currentChild);
  333. continue;
  334. }
  335. // Brand new item - needs to be added
  336. child.SetParent(this);
  337. newItems.Add(child);
  338. validChildren.Add(child);
  339. }
  340. // If any items were added or removed....
  341. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  342. {
  343. // That's all the new and changed ones - now see if there are any that are missing
  344. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  345. var actualRemovals = new List<BaseItem>();
  346. foreach (var item in itemsRemoved)
  347. {
  348. var itemLocationType = item.LocationType;
  349. if (itemLocationType == LocationType.Virtual ||
  350. itemLocationType == LocationType.Remote)
  351. {
  352. }
  353. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  354. {
  355. await item.UpdateIsOffline(true).ConfigureAwait(false);
  356. }
  357. else
  358. {
  359. actualRemovals.Add(item);
  360. }
  361. }
  362. if (actualRemovals.Count > 0)
  363. {
  364. foreach (var item in actualRemovals)
  365. {
  366. Logger.Debug("Removed item: " + item.Path);
  367. item.SetParent(null);
  368. item.IsOffline = false;
  369. await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false);
  370. LibraryManager.ReportItemRemoved(item);
  371. }
  372. }
  373. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  374. }
  375. }
  376. progress.Report(10);
  377. cancellationToken.ThrowIfCancellationRequested();
  378. if (recursive)
  379. {
  380. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  381. }
  382. progress.Report(20);
  383. if (refreshChildMetadata)
  384. {
  385. var container = this as IMetadataContainer;
  386. var innerProgress = new ActionableProgress<double>();
  387. innerProgress.RegisterAction(p => progress.Report(.80 * p + 20));
  388. if (container != null)
  389. {
  390. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  391. }
  392. else
  393. {
  394. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  395. }
  396. }
  397. progress.Report(100);
  398. }
  399. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  400. {
  401. var children = ActualChildren.ToList();
  402. var percentages = new Dictionary<Guid, double>(children.Count);
  403. var numComplete = 0;
  404. var count = children.Count;
  405. foreach (var child in children)
  406. {
  407. cancellationToken.ThrowIfCancellationRequested();
  408. if (child.IsFolder)
  409. {
  410. var innerProgress = new ActionableProgress<double>();
  411. // Avoid implicitly captured closure
  412. var currentChild = child;
  413. innerProgress.RegisterAction(p =>
  414. {
  415. lock (percentages)
  416. {
  417. percentages[currentChild.Id] = p / 100;
  418. var innerPercent = percentages.Values.Sum();
  419. innerPercent /= count;
  420. innerPercent *= 100;
  421. progress.Report(innerPercent);
  422. }
  423. });
  424. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  425. .ConfigureAwait(false);
  426. }
  427. else
  428. {
  429. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  430. .ConfigureAwait(false);
  431. }
  432. numComplete++;
  433. double percent = numComplete;
  434. percent /= count;
  435. percent *= 100;
  436. progress.Report(percent);
  437. }
  438. progress.Report(100);
  439. }
  440. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  441. {
  442. var container = child as IMetadataContainer;
  443. if (container != null)
  444. {
  445. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  446. }
  447. else
  448. {
  449. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  450. if (recursive)
  451. {
  452. var folder = child as Folder;
  453. if (folder != null)
  454. {
  455. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  456. }
  457. }
  458. }
  459. progress.Report(100);
  460. }
  461. /// <summary>
  462. /// Refreshes the children.
  463. /// </summary>
  464. /// <param name="children">The children.</param>
  465. /// <param name="directoryService">The directory service.</param>
  466. /// <param name="progress">The progress.</param>
  467. /// <param name="cancellationToken">The cancellation token.</param>
  468. /// <returns>Task.</returns>
  469. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  470. {
  471. var list = children;
  472. var childCount = list.Count;
  473. var percentages = new Dictionary<Guid, double>(list.Count);
  474. foreach (var item in list)
  475. {
  476. cancellationToken.ThrowIfCancellationRequested();
  477. var child = item;
  478. var innerProgress = new ActionableProgress<double>();
  479. innerProgress.RegisterAction(p =>
  480. {
  481. lock (percentages)
  482. {
  483. percentages[child.Id] = p / 100;
  484. var percent = percentages.Values.Sum();
  485. percent /= childCount;
  486. progress.Report(10 * percent + 10);
  487. }
  488. });
  489. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  490. .ConfigureAwait(false);
  491. }
  492. }
  493. /// <summary>
  494. /// Determines whether the specified path is offline.
  495. /// </summary>
  496. /// <param name="path">The path.</param>
  497. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  498. public static bool IsPathOffline(string path)
  499. {
  500. if (FileSystem.FileExists(path))
  501. {
  502. return false;
  503. }
  504. var originalPath = path;
  505. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  506. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  507. {
  508. if (FileSystem.DirectoryExists(path))
  509. {
  510. return false;
  511. }
  512. path = System.IO.Path.GetDirectoryName(path);
  513. }
  514. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  515. {
  516. return true;
  517. }
  518. return false;
  519. }
  520. /// <summary>
  521. /// Determines whether the specified folders contains path.
  522. /// </summary>
  523. /// <param name="folders">The folders.</param>
  524. /// <param name="path">The path.</param>
  525. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  526. private static bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  527. {
  528. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  529. }
  530. private static bool ContainsPath(string parent, string path)
  531. {
  532. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  533. }
  534. /// <summary>
  535. /// Get the children of this folder from the actual file system
  536. /// </summary>
  537. /// <returns>IEnumerable{BaseItem}.</returns>
  538. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  539. {
  540. var collectionType = LibraryManager.GetContentType(this);
  541. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  542. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, libraryOptions, collectionType);
  543. }
  544. /// <summary>
  545. /// Get our children from the repo - stubbed for now
  546. /// </summary>
  547. /// <returns>IEnumerable{BaseItem}.</returns>
  548. protected IEnumerable<BaseItem> GetCachedChildren()
  549. {
  550. return ItemRepository.GetItemList(new InternalItemsQuery
  551. {
  552. ParentId = Id,
  553. GroupByPresentationUniqueKey = false
  554. });
  555. }
  556. public virtual int GetChildCount(User user)
  557. {
  558. if (LinkedChildren.Count > 0)
  559. {
  560. if (!(this is ICollectionFolder))
  561. {
  562. return GetChildren(user, true).Count();
  563. }
  564. }
  565. var result = GetItems(new InternalItemsQuery(user)
  566. {
  567. Recursive = false,
  568. Limit = 0,
  569. ParentId = Id
  570. }).Result;
  571. return result.TotalRecordCount;
  572. }
  573. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  574. {
  575. var user = query.User;
  576. if (!query.ForceDirect && RequiresPostFiltering(query))
  577. {
  578. IEnumerable<BaseItem> items;
  579. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  580. if (query.User == null)
  581. {
  582. items = GetRecursiveChildren(filter);
  583. }
  584. else
  585. {
  586. items = GetRecursiveChildren(user, query);
  587. }
  588. return PostFilterAndSort(items, query, true, true);
  589. }
  590. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  591. {
  592. query.ParentId = query.ParentId ?? Id;
  593. }
  594. return LibraryManager.GetItemsResult(query);
  595. }
  596. private bool RequiresPostFiltering(InternalItemsQuery query)
  597. {
  598. if (LinkedChildren.Count > 0)
  599. {
  600. if (!(this is ICollectionFolder))
  601. {
  602. Logger.Debug("Query requires post-filtering due to LinkedChildren. Type: " + GetType().Name);
  603. return true;
  604. }
  605. }
  606. if (query.SortBy != null && query.SortBy.Length > 0)
  607. {
  608. if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase))
  609. {
  610. Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder");
  611. return true;
  612. }
  613. if (query.SortBy.Contains(ItemSortBy.Budget, StringComparer.OrdinalIgnoreCase))
  614. {
  615. Logger.Debug("Query requires post-filtering due to ItemSortBy.Budget");
  616. return true;
  617. }
  618. if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase))
  619. {
  620. Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem");
  621. return true;
  622. }
  623. if (query.SortBy.Contains(ItemSortBy.Metascore, StringComparer.OrdinalIgnoreCase))
  624. {
  625. Logger.Debug("Query requires post-filtering due to ItemSortBy.Metascore");
  626. return true;
  627. }
  628. if (query.SortBy.Contains(ItemSortBy.Players, StringComparer.OrdinalIgnoreCase))
  629. {
  630. Logger.Debug("Query requires post-filtering due to ItemSortBy.Players");
  631. return true;
  632. }
  633. if (query.SortBy.Contains(ItemSortBy.Revenue, StringComparer.OrdinalIgnoreCase))
  634. {
  635. Logger.Debug("Query requires post-filtering due to ItemSortBy.Revenue");
  636. return true;
  637. }
  638. if (query.SortBy.Contains(ItemSortBy.VideoBitRate, StringComparer.OrdinalIgnoreCase))
  639. {
  640. Logger.Debug("Query requires post-filtering due to ItemSortBy.VideoBitRate");
  641. return true;
  642. }
  643. }
  644. if (query.ItemIds.Length > 0)
  645. {
  646. Logger.Debug("Query requires post-filtering due to ItemIds");
  647. return true;
  648. }
  649. if (query.IsInBoxSet.HasValue)
  650. {
  651. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  652. return true;
  653. }
  654. // Filter by Video3DFormat
  655. if (query.Is3D.HasValue)
  656. {
  657. Logger.Debug("Query requires post-filtering due to Is3D");
  658. return true;
  659. }
  660. if (query.HasOfficialRating.HasValue)
  661. {
  662. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  663. return true;
  664. }
  665. if (query.IsPlaceHolder.HasValue)
  666. {
  667. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  668. return true;
  669. }
  670. if (query.HasSpecialFeature.HasValue)
  671. {
  672. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  673. return true;
  674. }
  675. if (query.HasSubtitles.HasValue)
  676. {
  677. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  678. return true;
  679. }
  680. if (query.HasTrailer.HasValue)
  681. {
  682. Logger.Debug("Query requires post-filtering due to HasTrailer");
  683. return true;
  684. }
  685. // Filter by VideoType
  686. if (query.VideoTypes.Length > 0)
  687. {
  688. Logger.Debug("Query requires post-filtering due to VideoTypes");
  689. return true;
  690. }
  691. // Apply person filter
  692. if (query.ItemIdsFromPersonFilters != null)
  693. {
  694. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  695. return true;
  696. }
  697. if (query.MinPlayers.HasValue)
  698. {
  699. Logger.Debug("Query requires post-filtering due to MinPlayers");
  700. return true;
  701. }
  702. if (query.MaxPlayers.HasValue)
  703. {
  704. Logger.Debug("Query requires post-filtering due to MaxPlayers");
  705. return true;
  706. }
  707. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User, ConfigurationManager))
  708. {
  709. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  710. return true;
  711. }
  712. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  713. {
  714. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  715. return true;
  716. }
  717. if (query.AirDays.Length > 0)
  718. {
  719. Logger.Debug("Query requires post-filtering due to AirDays");
  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 (!string.IsNullOrWhiteSpace(query.AlbumArtistStartsWithOrGreater))
  733. {
  734. Logger.Debug("Query requires post-filtering due to AlbumArtistStartsWithOrGreater");
  735. return true;
  736. }
  737. if (query.IsPlayed.HasValue)
  738. {
  739. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes.Contains(typeof(Series).Name))
  740. {
  741. Logger.Debug("Query requires post-filtering due to IsPlayed");
  742. return true;
  743. }
  744. }
  745. return false;
  746. }
  747. public Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  748. {
  749. if (query.ItemIds.Length > 0)
  750. {
  751. var result = LibraryManager.GetItemsResult(query);
  752. if (query.SortBy.Length == 0)
  753. {
  754. var ids = query.ItemIds.ToList();
  755. // Try to preserve order
  756. result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
  757. }
  758. return Task.FromResult(result);
  759. }
  760. return GetItemsInternal(query);
  761. }
  762. protected virtual async Task<QueryResult<BaseItem>> GetItemsInternal(InternalItemsQuery query)
  763. {
  764. if (SourceType == SourceType.Channel)
  765. {
  766. try
  767. {
  768. // Don't blow up here because it could cause parent screens with other content to fail
  769. return await ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  770. {
  771. ChannelId = ChannelId,
  772. FolderId = Id.ToString("N"),
  773. Limit = query.Limit,
  774. StartIndex = query.StartIndex,
  775. UserId = query.User.Id.ToString("N"),
  776. SortBy = query.SortBy,
  777. SortOrder = query.SortOrder
  778. }, new Progress<double>(), CancellationToken.None);
  779. }
  780. catch
  781. {
  782. // Already logged at lower levels
  783. return new QueryResult<BaseItem>();
  784. }
  785. }
  786. if (query.Recursive)
  787. {
  788. return QueryRecursive(query);
  789. }
  790. var user = query.User;
  791. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  792. IEnumerable<BaseItem> items;
  793. if (query.User == null)
  794. {
  795. items = query.Recursive
  796. ? GetRecursiveChildren(filter)
  797. : Children.Where(filter);
  798. }
  799. else
  800. {
  801. items = query.Recursive
  802. ? GetRecursiveChildren(user, query)
  803. : GetChildren(user, true).Where(filter);
  804. }
  805. return PostFilterAndSort(items, query, true, true);
  806. }
  807. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query, bool collapseBoxSetItems, bool enableSorting)
  808. {
  809. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager, ConfigurationManager, collapseBoxSetItems, enableSorting);
  810. }
  811. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  812. {
  813. if (user == null)
  814. {
  815. throw new ArgumentNullException();
  816. }
  817. //the true root should return our users root folder children
  818. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  819. var result = new Dictionary<Guid, BaseItem>();
  820. AddChildren(user, includeLinkedChildren, result, false, null);
  821. return result.Values;
  822. }
  823. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  824. {
  825. return Children;
  826. }
  827. /// <summary>
  828. /// Adds the children to list.
  829. /// </summary>
  830. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  831. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, InternalItemsQuery query)
  832. {
  833. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  834. {
  835. if (child.IsVisible(user))
  836. {
  837. if (query == null || UserViewBuilder.FilterItem(child, query))
  838. {
  839. result[child.Id] = child;
  840. }
  841. if (recursive && child.IsFolder)
  842. {
  843. var folder = (Folder)child;
  844. folder.AddChildren(user, includeLinkedChildren, result, true, query);
  845. }
  846. }
  847. }
  848. if (includeLinkedChildren)
  849. {
  850. foreach (var child in GetLinkedChildren(user))
  851. {
  852. if (child.IsVisible(user))
  853. {
  854. if (query == null || UserViewBuilder.FilterItem(child, query))
  855. {
  856. result[child.Id] = child;
  857. }
  858. }
  859. }
  860. }
  861. }
  862. /// <summary>
  863. /// Gets allowed recursive children of an item
  864. /// </summary>
  865. /// <param name="user">The user.</param>
  866. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  867. /// <returns>IEnumerable{BaseItem}.</returns>
  868. /// <exception cref="System.ArgumentNullException"></exception>
  869. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  870. {
  871. return GetRecursiveChildren(user, null);
  872. }
  873. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, InternalItemsQuery query)
  874. {
  875. if (user == null)
  876. {
  877. throw new ArgumentNullException("user");
  878. }
  879. var result = new Dictionary<Guid, BaseItem>();
  880. AddChildren(user, true, result, true, query);
  881. return result.Values;
  882. }
  883. /// <summary>
  884. /// Gets the recursive children.
  885. /// </summary>
  886. /// <returns>IList{BaseItem}.</returns>
  887. public IList<BaseItem> GetRecursiveChildren()
  888. {
  889. return GetRecursiveChildren(true);
  890. }
  891. public IList<BaseItem> GetRecursiveChildren(bool includeLinkedChildren)
  892. {
  893. return GetRecursiveChildren(i => true, includeLinkedChildren);
  894. }
  895. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  896. {
  897. return GetRecursiveChildren(filter, true);
  898. }
  899. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter, bool includeLinkedChildren)
  900. {
  901. var result = new Dictionary<Guid, BaseItem>();
  902. AddChildrenToList(result, includeLinkedChildren, true, filter);
  903. return result.Values.ToList();
  904. }
  905. /// <summary>
  906. /// Adds the children to list.
  907. /// </summary>
  908. private void AddChildrenToList(Dictionary<Guid, BaseItem> result, bool includeLinkedChildren, bool recursive, Func<BaseItem, bool> filter)
  909. {
  910. foreach (var child in Children)
  911. {
  912. if (filter == null || filter(child))
  913. {
  914. result[child.Id] = child;
  915. }
  916. if (recursive && child.IsFolder)
  917. {
  918. var folder = (Folder)child;
  919. // We can only support includeLinkedChildren for the first folder, or we might end up stuck in a loop of linked items
  920. folder.AddChildrenToList(result, false, true, filter);
  921. }
  922. }
  923. if (includeLinkedChildren)
  924. {
  925. foreach (var child in GetLinkedChildren())
  926. {
  927. if (filter == null || filter(child))
  928. {
  929. result[child.Id] = child;
  930. }
  931. }
  932. }
  933. }
  934. /// <summary>
  935. /// Gets the linked children.
  936. /// </summary>
  937. /// <returns>IEnumerable{BaseItem}.</returns>
  938. public IEnumerable<BaseItem> GetLinkedChildren()
  939. {
  940. return LinkedChildren
  941. .Select(GetLinkedChild)
  942. .Where(i => i != null);
  943. }
  944. protected virtual bool FilterLinkedChildrenPerUser
  945. {
  946. get
  947. {
  948. return false;
  949. }
  950. }
  951. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  952. {
  953. if (!FilterLinkedChildrenPerUser || user == null)
  954. {
  955. return GetLinkedChildren();
  956. }
  957. var locations = user.RootFolder
  958. .Children
  959. .OfType<CollectionFolder>()
  960. .Where(i => i.IsVisible(user))
  961. .SelectMany(i => i.PhysicalLocations)
  962. .ToList();
  963. return LinkedChildren
  964. .Select(i =>
  965. {
  966. var child = GetLinkedChild(i);
  967. if (child != null)
  968. {
  969. var childLocationType = child.LocationType;
  970. if (childLocationType == LocationType.Remote || childLocationType == LocationType.Virtual)
  971. {
  972. if (!child.IsVisibleStandalone(user))
  973. {
  974. return null;
  975. }
  976. }
  977. else if (childLocationType == LocationType.FileSystem && !locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  978. {
  979. return null;
  980. }
  981. }
  982. return child;
  983. })
  984. .Where(i => i != null);
  985. }
  986. /// <summary>
  987. /// Gets the linked children.
  988. /// </summary>
  989. /// <returns>IEnumerable{BaseItem}.</returns>
  990. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  991. {
  992. return LinkedChildren
  993. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  994. .Where(i => i.Item2 != null);
  995. }
  996. [IgnoreDataMember]
  997. protected override bool SupportsOwnedItems
  998. {
  999. get
  1000. {
  1001. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1002. }
  1003. }
  1004. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1005. {
  1006. var changesFound = false;
  1007. if (LocationType == LocationType.FileSystem)
  1008. {
  1009. if (RefreshLinkedChildren(fileSystemChildren))
  1010. {
  1011. changesFound = true;
  1012. }
  1013. }
  1014. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1015. return baseHasChanges || changesFound;
  1016. }
  1017. /// <summary>
  1018. /// Refreshes the linked children.
  1019. /// </summary>
  1020. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1021. private bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1022. {
  1023. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1024. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1025. List<LinkedChild> newShortcutLinks;
  1026. if (SupportsShortcutChildren)
  1027. {
  1028. newShortcutLinks = fileSystemChildren
  1029. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1030. .Select(i =>
  1031. {
  1032. try
  1033. {
  1034. Logger.Debug("Found shortcut at {0}", i.FullName);
  1035. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1036. if (!string.IsNullOrEmpty(resolvedPath))
  1037. {
  1038. return new LinkedChild
  1039. {
  1040. Path = resolvedPath,
  1041. Type = LinkedChildType.Shortcut
  1042. };
  1043. }
  1044. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1045. return null;
  1046. }
  1047. catch (IOException ex)
  1048. {
  1049. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1050. return null;
  1051. }
  1052. })
  1053. .Where(i => i != null)
  1054. .ToList();
  1055. }
  1056. else { newShortcutLinks = new List<LinkedChild>(); }
  1057. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1058. {
  1059. Logger.Info("Shortcut links have changed for {0}", Path);
  1060. newShortcutLinks.AddRange(currentManualLinks);
  1061. LinkedChildren = newShortcutLinks;
  1062. return true;
  1063. }
  1064. foreach (var child in LinkedChildren)
  1065. {
  1066. // Reset the cached value
  1067. child.ItemId = null;
  1068. }
  1069. return false;
  1070. }
  1071. /// <summary>
  1072. /// Folders need to validate and refresh
  1073. /// </summary>
  1074. /// <returns>Task.</returns>
  1075. public override async Task ChangedExternally()
  1076. {
  1077. var progress = new Progress<double>();
  1078. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1079. await base.ChangedExternally().ConfigureAwait(false);
  1080. }
  1081. /// <summary>
  1082. /// Marks the played.
  1083. /// </summary>
  1084. /// <param name="user">The user.</param>
  1085. /// <param name="datePlayed">The date played.</param>
  1086. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1087. /// <returns>Task.</returns>
  1088. public override async Task MarkPlayed(User user,
  1089. DateTime? datePlayed,
  1090. bool resetPosition)
  1091. {
  1092. var query = new InternalItemsQuery
  1093. {
  1094. User = user,
  1095. Recursive = true,
  1096. IsFolder = false,
  1097. EnableTotalRecordCount = false
  1098. };
  1099. if (!user.Configuration.DisplayMissingEpisodes || !user.Configuration.DisplayUnairedEpisodes)
  1100. {
  1101. query.ExcludeLocationTypes = new[] { LocationType.Virtual };
  1102. }
  1103. var itemsResult = await GetItems(query).ConfigureAwait(false);
  1104. // Sweep through recursively and update status
  1105. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1106. await Task.WhenAll(tasks).ConfigureAwait(false);
  1107. }
  1108. /// <summary>
  1109. /// Marks the unplayed.
  1110. /// </summary>
  1111. /// <param name="user">The user.</param>
  1112. /// <returns>Task.</returns>
  1113. public override async Task MarkUnplayed(User user)
  1114. {
  1115. var itemsResult = await GetItems(new InternalItemsQuery
  1116. {
  1117. User = user,
  1118. Recursive = true,
  1119. IsFolder = false,
  1120. EnableTotalRecordCount = false
  1121. }).ConfigureAwait(false);
  1122. // Sweep through recursively and update status
  1123. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1124. await Task.WhenAll(tasks).ConfigureAwait(false);
  1125. }
  1126. public override bool IsPlayed(User user)
  1127. {
  1128. var itemsResult = GetItems(new InternalItemsQuery(user)
  1129. {
  1130. Recursive = true,
  1131. IsFolder = false,
  1132. ExcludeLocationTypes = new[] { LocationType.Virtual },
  1133. EnableTotalRecordCount = false
  1134. }).Result;
  1135. return itemsResult.Items
  1136. .All(i => i.IsPlayed(user));
  1137. }
  1138. public override bool IsUnplayed(User user)
  1139. {
  1140. return !IsPlayed(user);
  1141. }
  1142. [IgnoreDataMember]
  1143. public virtual bool SupportsUserDataFromChildren
  1144. {
  1145. get
  1146. {
  1147. // These are just far too slow.
  1148. if (this is ICollectionFolder)
  1149. {
  1150. return false;
  1151. }
  1152. if (this is UserView)
  1153. {
  1154. return false;
  1155. }
  1156. if (this is UserRootFolder)
  1157. {
  1158. return false;
  1159. }
  1160. if (this is Channel)
  1161. {
  1162. return false;
  1163. }
  1164. if (SourceType != SourceType.Library)
  1165. {
  1166. return false;
  1167. }
  1168. return true;
  1169. }
  1170. }
  1171. public override async Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1172. {
  1173. if (!SupportsUserDataFromChildren)
  1174. {
  1175. return;
  1176. }
  1177. var unplayedQueryResult = await GetItems(new InternalItemsQuery(user)
  1178. {
  1179. Recursive = true,
  1180. IsFolder = false,
  1181. IsVirtualItem = false,
  1182. EnableTotalRecordCount = true,
  1183. Limit = 0,
  1184. IsPlayed = false
  1185. }).ConfigureAwait(false);
  1186. var allItemsQueryResult = await GetItems(new InternalItemsQuery(user)
  1187. {
  1188. Recursive = true,
  1189. IsFolder = false,
  1190. IsVirtualItem = false,
  1191. EnableTotalRecordCount = true,
  1192. Limit = 0
  1193. }).ConfigureAwait(false);
  1194. if (itemDto != null)
  1195. {
  1196. itemDto.RecursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1197. }
  1198. var recursiveItemCount = allItemsQueryResult.TotalRecordCount;
  1199. double unplayedCount = unplayedQueryResult.TotalRecordCount;
  1200. if (recursiveItemCount > 0)
  1201. {
  1202. var unplayedPercentage = (unplayedCount / recursiveItemCount) * 100;
  1203. dto.PlayedPercentage = 100 - unplayedPercentage;
  1204. dto.Played = dto.PlayedPercentage.Value >= 100;
  1205. dto.UnplayedItemCount = unplayedQueryResult.TotalRecordCount;
  1206. }
  1207. if (itemDto != null)
  1208. {
  1209. if (this is Season || this is MusicAlbum)
  1210. {
  1211. itemDto.ChildCount = recursiveItemCount;
  1212. }
  1213. }
  1214. }
  1215. }
  1216. }