2
0

Folder.cs 45 KB

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