Folder.cs 44 KB

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