Folder.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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))
  405. {
  406. if (IsValidFromResolver(currentChild, child))
  407. {
  408. var currentChildLocationType = currentChild.LocationType;
  409. if (currentChildLocationType != LocationType.Remote &&
  410. currentChildLocationType != LocationType.Virtual)
  411. {
  412. currentChild.DateModified = child.DateModified;
  413. }
  414. await UpdateIsOffline(currentChild, false).ConfigureAwait(false);
  415. validChildren.Add(currentChild);
  416. }
  417. else
  418. {
  419. child.SetParent(this);
  420. newItems.Add(child);
  421. validChildren.Add(child);
  422. }
  423. }
  424. else
  425. {
  426. // Brand new item - needs to be added
  427. child.SetParent(this);
  428. newItems.Add(child);
  429. validChildren.Add(child);
  430. }
  431. }
  432. // If any items were added or removed....
  433. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  434. {
  435. // That's all the new and changed ones - now see if there are any that are missing
  436. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  437. var actualRemovals = new List<BaseItem>();
  438. foreach (var item in itemsRemoved)
  439. {
  440. if (item.LocationType == LocationType.Virtual ||
  441. item.LocationType == LocationType.Remote)
  442. {
  443. // Don't remove these because there's no way to accurately validate them.
  444. validChildren.Add(item);
  445. }
  446. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  447. {
  448. await UpdateIsOffline(item, true).ConfigureAwait(false);
  449. validChildren.Add(item);
  450. }
  451. else
  452. {
  453. actualRemovals.Add(item);
  454. }
  455. }
  456. if (actualRemovals.Count > 0)
  457. {
  458. RemoveChildrenInternal(actualRemovals);
  459. foreach (var item in actualRemovals)
  460. {
  461. item.SetParent(null);
  462. item.IsOffline = false;
  463. await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false);
  464. LibraryManager.ReportItemRemoved(item);
  465. }
  466. }
  467. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  468. AddChildrenInternal(newItems);
  469. if (!EnableNewFolderQuerying())
  470. {
  471. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  472. }
  473. }
  474. }
  475. progress.Report(10);
  476. cancellationToken.ThrowIfCancellationRequested();
  477. if (recursive)
  478. {
  479. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  480. }
  481. progress.Report(20);
  482. if (refreshChildMetadata)
  483. {
  484. var container = this as IMetadataContainer;
  485. var innerProgress = new ActionableProgress<double>();
  486. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  487. if (container != null)
  488. {
  489. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  490. }
  491. else
  492. {
  493. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  494. }
  495. }
  496. progress.Report(100);
  497. }
  498. private Task UpdateIsOffline(BaseItem item, bool newValue)
  499. {
  500. if (item.IsOffline != newValue)
  501. {
  502. item.IsOffline = newValue;
  503. return item.UpdateToRepository(ItemUpdateType.None, CancellationToken.None);
  504. }
  505. return Task.FromResult(true);
  506. }
  507. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  508. {
  509. var children = ActualChildren.ToList();
  510. var percentages = new Dictionary<Guid, double>(children.Count);
  511. var numComplete = 0;
  512. var count = children.Count;
  513. foreach (var child in children)
  514. {
  515. cancellationToken.ThrowIfCancellationRequested();
  516. if (child.IsFolder)
  517. {
  518. var innerProgress = new ActionableProgress<double>();
  519. // Avoid implicitly captured closure
  520. var currentChild = child;
  521. innerProgress.RegisterAction(p =>
  522. {
  523. lock (percentages)
  524. {
  525. percentages[currentChild.Id] = p / 100;
  526. var innerPercent = percentages.Values.Sum();
  527. innerPercent /= count;
  528. innerPercent *= 100;
  529. progress.Report(innerPercent);
  530. }
  531. });
  532. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  533. .ConfigureAwait(false);
  534. }
  535. else
  536. {
  537. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  538. .ConfigureAwait(false);
  539. }
  540. numComplete++;
  541. double percent = numComplete;
  542. percent /= count;
  543. percent *= 100;
  544. progress.Report(percent);
  545. }
  546. progress.Report(100);
  547. }
  548. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  549. {
  550. var container = child as IMetadataContainer;
  551. if (container != null)
  552. {
  553. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  554. }
  555. else
  556. {
  557. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  558. if (recursive)
  559. {
  560. var folder = child as Folder;
  561. if (folder != null)
  562. {
  563. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  564. }
  565. }
  566. }
  567. progress.Report(100);
  568. }
  569. /// <summary>
  570. /// Refreshes the children.
  571. /// </summary>
  572. /// <param name="children">The children.</param>
  573. /// <param name="directoryService">The directory service.</param>
  574. /// <param name="progress">The progress.</param>
  575. /// <param name="cancellationToken">The cancellation token.</param>
  576. /// <returns>Task.</returns>
  577. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  578. {
  579. var list = children;
  580. var childCount = list.Count;
  581. var percentages = new Dictionary<Guid, double>(list.Count);
  582. foreach (var item in list)
  583. {
  584. cancellationToken.ThrowIfCancellationRequested();
  585. var child = item;
  586. var innerProgress = new ActionableProgress<double>();
  587. innerProgress.RegisterAction(p =>
  588. {
  589. lock (percentages)
  590. {
  591. percentages[child.Id] = p / 100;
  592. var percent = percentages.Values.Sum();
  593. percent /= childCount;
  594. progress.Report((10 * percent) + 10);
  595. }
  596. });
  597. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  598. .ConfigureAwait(false);
  599. }
  600. }
  601. /// <summary>
  602. /// Determines whether the specified path is offline.
  603. /// </summary>
  604. /// <param name="path">The path.</param>
  605. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  606. public static bool IsPathOffline(string path)
  607. {
  608. if (FileSystem.FileExists(path))
  609. {
  610. return false;
  611. }
  612. var originalPath = path;
  613. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  614. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  615. {
  616. if (FileSystem.DirectoryExists(path))
  617. {
  618. return false;
  619. }
  620. path = System.IO.Path.GetDirectoryName(path);
  621. }
  622. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  623. {
  624. return true;
  625. }
  626. return ContainsPath(LibraryManager.GetVirtualFolders(), originalPath);
  627. }
  628. /// <summary>
  629. /// Determines whether the specified folders contains path.
  630. /// </summary>
  631. /// <param name="folders">The folders.</param>
  632. /// <param name="path">The path.</param>
  633. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  634. private static bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  635. {
  636. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  637. }
  638. private static bool ContainsPath(string parent, string path)
  639. {
  640. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  641. }
  642. /// <summary>
  643. /// Get the children of this folder from the actual file system
  644. /// </summary>
  645. /// <returns>IEnumerable{BaseItem}.</returns>
  646. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  647. {
  648. var collectionType = LibraryManager.GetContentType(this);
  649. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  650. }
  651. /// <summary>
  652. /// Get our children from the repo - stubbed for now
  653. /// </summary>
  654. /// <returns>IEnumerable{BaseItem}.</returns>
  655. protected IEnumerable<BaseItem> GetCachedChildren()
  656. {
  657. if (EnableNewFolderQuerying())
  658. {
  659. return ItemRepository.GetItemList(new InternalItemsQuery
  660. {
  661. ParentId = Id
  662. }).Select(RetrieveChild).Where(i => i != null);
  663. }
  664. return ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null);
  665. }
  666. private BaseItem RetrieveChild(BaseItem child)
  667. {
  668. if (child == null || child.Id == Guid.Empty)
  669. {
  670. Logger.Error("Item found with empty Id: " + (child.Path ?? child.Name));
  671. return null;
  672. }
  673. var item = LibraryManager.GetMemoryItemById(child.Id);
  674. if (item != null)
  675. {
  676. if (item is IByReferenceItem)
  677. {
  678. return LibraryManager.GetOrAddByReferenceItem(item);
  679. }
  680. item.SetParent(this);
  681. }
  682. else
  683. {
  684. child.SetParent(this);
  685. LibraryManager.RegisterItem(child);
  686. item = child;
  687. }
  688. return item;
  689. }
  690. public virtual Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  691. {
  692. var user = query.User;
  693. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  694. IEnumerable<BaseItem> items;
  695. if (query.User == null)
  696. {
  697. items = query.Recursive
  698. ? GetRecursiveChildren(filter)
  699. : Children.Where(filter);
  700. }
  701. else
  702. {
  703. items = query.Recursive
  704. ? GetRecursiveChildren(user, filter)
  705. : GetChildren(user, true).Where(filter);
  706. }
  707. var result = PostFilterAndSort(items, query);
  708. return Task.FromResult(result);
  709. }
  710. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  711. {
  712. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager);
  713. }
  714. /// <summary>
  715. /// Gets allowed children of an item
  716. /// </summary>
  717. /// <param name="user">The user.</param>
  718. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  719. /// <returns>IEnumerable{BaseItem}.</returns>
  720. /// <exception cref="System.ArgumentNullException"></exception>
  721. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  722. {
  723. return GetChildren(user, includeLinkedChildren, false);
  724. }
  725. internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
  726. {
  727. if (user == null)
  728. {
  729. throw new ArgumentNullException();
  730. }
  731. //the true root should return our users root folder children
  732. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  733. var result = new Dictionary<Guid, BaseItem>();
  734. AddChildren(user, includeLinkedChildren, result, includeHidden, false, null);
  735. return result.Values;
  736. }
  737. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  738. {
  739. return Children;
  740. }
  741. /// <summary>
  742. /// Adds the children to list.
  743. /// </summary>
  744. /// <param name="user">The user.</param>
  745. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  746. /// <param name="result">The result.</param>
  747. /// <param name="includeHidden">if set to <c>true</c> [include hidden].</param>
  748. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  749. /// <param name="filter">The filter.</param>
  750. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  751. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool includeHidden, bool recursive, Func<BaseItem, bool> filter)
  752. {
  753. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  754. {
  755. if (child.IsVisible(user))
  756. {
  757. if (includeHidden || !child.IsHiddenFromUser(user))
  758. {
  759. if (filter == null || filter(child))
  760. {
  761. result[child.Id] = child;
  762. }
  763. }
  764. if (recursive && child.IsFolder)
  765. {
  766. var folder = (Folder)child;
  767. folder.AddChildren(user, includeLinkedChildren, result, includeHidden, true, filter);
  768. }
  769. }
  770. }
  771. if (includeLinkedChildren)
  772. {
  773. foreach (var child in GetLinkedChildren(user))
  774. {
  775. if (child.IsVisible(user))
  776. {
  777. if (filter == null || filter(child))
  778. {
  779. result[child.Id] = child;
  780. }
  781. }
  782. }
  783. }
  784. }
  785. /// <summary>
  786. /// Gets allowed recursive children of an item
  787. /// </summary>
  788. /// <param name="user">The user.</param>
  789. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  790. /// <returns>IEnumerable{BaseItem}.</returns>
  791. /// <exception cref="System.ArgumentNullException"></exception>
  792. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  793. {
  794. return GetRecursiveChildren(user, i => true);
  795. }
  796. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
  797. {
  798. if (user == null)
  799. {
  800. throw new ArgumentNullException("user");
  801. }
  802. var result = new Dictionary<Guid, BaseItem>();
  803. AddChildren(user, true, result, false, true, filter);
  804. return result.Values;
  805. }
  806. /// <summary>
  807. /// Gets the recursive children.
  808. /// </summary>
  809. /// <returns>IList{BaseItem}.</returns>
  810. public IList<BaseItem> GetRecursiveChildren()
  811. {
  812. return GetRecursiveChildren(i => true);
  813. }
  814. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  815. {
  816. var list = new List<BaseItem>();
  817. AddChildrenToList(list, true, filter);
  818. return list;
  819. }
  820. /// <summary>
  821. /// Adds the children to list.
  822. /// </summary>
  823. /// <param name="list">The list.</param>
  824. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  825. /// <param name="filter">The filter.</param>
  826. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  827. {
  828. foreach (var child in Children)
  829. {
  830. if (filter == null || filter(child))
  831. {
  832. list.Add(child);
  833. }
  834. if (recursive && child.IsFolder)
  835. {
  836. var folder = (Folder)child;
  837. folder.AddChildrenToList(list, true, filter);
  838. }
  839. }
  840. }
  841. /// <summary>
  842. /// Gets the linked children.
  843. /// </summary>
  844. /// <returns>IEnumerable{BaseItem}.</returns>
  845. public IEnumerable<BaseItem> GetLinkedChildren()
  846. {
  847. return LinkedChildren
  848. .Select(GetLinkedChild)
  849. .Where(i => i != null);
  850. }
  851. protected virtual bool FilterLinkedChildrenPerUser
  852. {
  853. get
  854. {
  855. return false;
  856. }
  857. }
  858. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  859. {
  860. if (!FilterLinkedChildrenPerUser || user == null)
  861. {
  862. return GetLinkedChildren();
  863. }
  864. var locations = user.RootFolder
  865. .Children
  866. .OfType<CollectionFolder>()
  867. .Where(i => i.IsVisible(user))
  868. .SelectMany(i => i.PhysicalLocations)
  869. .ToList();
  870. return LinkedChildren
  871. .Select(i =>
  872. {
  873. var requiresPostFilter = true;
  874. if (!string.IsNullOrWhiteSpace(i.Path))
  875. {
  876. requiresPostFilter = false;
  877. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  878. {
  879. return null;
  880. }
  881. }
  882. var child = GetLinkedChild(i);
  883. if (requiresPostFilter && child != null)
  884. {
  885. if (string.IsNullOrWhiteSpace(child.Path))
  886. {
  887. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  888. return child;
  889. }
  890. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  891. {
  892. return null;
  893. }
  894. }
  895. return child;
  896. })
  897. .Where(i => i != null);
  898. }
  899. /// <summary>
  900. /// Gets the linked children.
  901. /// </summary>
  902. /// <returns>IEnumerable{BaseItem}.</returns>
  903. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  904. {
  905. return LinkedChildren
  906. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  907. .Where(i => i.Item2 != null);
  908. }
  909. [IgnoreDataMember]
  910. protected override bool SupportsOwnedItems
  911. {
  912. get
  913. {
  914. return base.SupportsOwnedItems || SupportsShortcutChildren;
  915. }
  916. }
  917. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  918. {
  919. var changesFound = false;
  920. if (LocationType == LocationType.FileSystem)
  921. {
  922. if (RefreshLinkedChildren(fileSystemChildren))
  923. {
  924. changesFound = true;
  925. }
  926. }
  927. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  928. return baseHasChanges || changesFound;
  929. }
  930. /// <summary>
  931. /// Refreshes the linked children.
  932. /// </summary>
  933. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  934. private bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  935. {
  936. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  937. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  938. List<LinkedChild> newShortcutLinks;
  939. if (SupportsShortcutChildren)
  940. {
  941. newShortcutLinks = fileSystemChildren
  942. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  943. .Select(i =>
  944. {
  945. try
  946. {
  947. Logger.Debug("Found shortcut at {0}", i.FullName);
  948. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  949. if (!string.IsNullOrEmpty(resolvedPath))
  950. {
  951. return new LinkedChild
  952. {
  953. Path = resolvedPath,
  954. Type = LinkedChildType.Shortcut
  955. };
  956. }
  957. Logger.Error("Error resolving shortcut {0}", i.FullName);
  958. return null;
  959. }
  960. catch (IOException ex)
  961. {
  962. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  963. return null;
  964. }
  965. })
  966. .Where(i => i != null)
  967. .ToList();
  968. }
  969. else { newShortcutLinks = new List<LinkedChild>(); }
  970. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  971. {
  972. Logger.Info("Shortcut links have changed for {0}", Path);
  973. newShortcutLinks.AddRange(currentManualLinks);
  974. LinkedChildren = newShortcutLinks;
  975. return true;
  976. }
  977. foreach (var child in LinkedChildren)
  978. {
  979. // Reset the cached value
  980. child.ItemId = null;
  981. }
  982. return false;
  983. }
  984. /// <summary>
  985. /// Folders need to validate and refresh
  986. /// </summary>
  987. /// <returns>Task.</returns>
  988. public override async Task ChangedExternally()
  989. {
  990. var progress = new Progress<double>();
  991. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  992. await base.ChangedExternally().ConfigureAwait(false);
  993. }
  994. /// <summary>
  995. /// Marks the played.
  996. /// </summary>
  997. /// <param name="user">The user.</param>
  998. /// <param name="datePlayed">The date played.</param>
  999. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1000. /// <returns>Task.</returns>
  1001. public override async Task MarkPlayed(User user,
  1002. DateTime? datePlayed,
  1003. bool resetPosition)
  1004. {
  1005. var itemsResult = await GetItems(new InternalItemsQuery
  1006. {
  1007. User = user,
  1008. Recursive = true,
  1009. IsFolder = false
  1010. }).ConfigureAwait(false);
  1011. // Sweep through recursively and update status
  1012. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1013. await Task.WhenAll(tasks).ConfigureAwait(false);
  1014. }
  1015. /// <summary>
  1016. /// Marks the unplayed.
  1017. /// </summary>
  1018. /// <param name="user">The user.</param>
  1019. /// <returns>Task.</returns>
  1020. public override async Task MarkUnplayed(User user)
  1021. {
  1022. var itemsResult = await GetItems(new InternalItemsQuery
  1023. {
  1024. User = user,
  1025. Recursive = true,
  1026. IsFolder = false
  1027. }).ConfigureAwait(false);
  1028. // Sweep through recursively and update status
  1029. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1030. await Task.WhenAll(tasks).ConfigureAwait(false);
  1031. }
  1032. /// <summary>
  1033. /// Finds an item by path, recursively
  1034. /// </summary>
  1035. /// <param name="path">The path.</param>
  1036. /// <returns>BaseItem.</returns>
  1037. /// <exception cref="System.ArgumentNullException"></exception>
  1038. public BaseItem FindByPath(string path)
  1039. {
  1040. if (string.IsNullOrEmpty(path))
  1041. {
  1042. throw new ArgumentNullException();
  1043. }
  1044. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  1045. {
  1046. return this;
  1047. }
  1048. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1049. {
  1050. return this;
  1051. }
  1052. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1053. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1054. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1055. .FirstOrDefault();
  1056. }
  1057. public override bool IsPlayed(User user)
  1058. {
  1059. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1060. .All(i => i.IsPlayed(user));
  1061. }
  1062. public override bool IsUnplayed(User user)
  1063. {
  1064. return !IsPlayed(user);
  1065. }
  1066. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1067. {
  1068. var recursiveItemCount = 0;
  1069. var unplayed = 0;
  1070. double totalPercentPlayed = 0;
  1071. IEnumerable<BaseItem> children;
  1072. var folder = this;
  1073. var season = folder as Season;
  1074. if (season != null)
  1075. {
  1076. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1077. }
  1078. else
  1079. {
  1080. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1081. }
  1082. // Loop through each recursive child
  1083. foreach (var child in children)
  1084. {
  1085. recursiveItemCount++;
  1086. var isUnplayed = true;
  1087. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1088. // Incrememt totalPercentPlayed
  1089. if (itemUserData != null)
  1090. {
  1091. if (itemUserData.Played)
  1092. {
  1093. totalPercentPlayed += 100;
  1094. isUnplayed = false;
  1095. }
  1096. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1097. {
  1098. double itemPercent = itemUserData.PlaybackPositionTicks;
  1099. itemPercent /= child.RunTimeTicks.Value;
  1100. totalPercentPlayed += itemPercent;
  1101. }
  1102. }
  1103. if (isUnplayed)
  1104. {
  1105. unplayed++;
  1106. }
  1107. }
  1108. dto.UnplayedItemCount = unplayed;
  1109. if (recursiveItemCount > 0)
  1110. {
  1111. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1112. dto.Played = dto.PlayedPercentage.Value >= 100;
  1113. }
  1114. }
  1115. }
  1116. }