Folder.cs 48 KB

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