Folder.cs 49 KB

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