Folder.cs 46 KB

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