Folder.cs 49 KB

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