Folder.cs 48 KB

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