Folder.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. return _children ?? (_children = LoadChildrenInternal());
  247. }
  248. }
  249. /// <summary>
  250. /// thread-safe access to the actual children of this folder - without regard to user
  251. /// </summary>
  252. /// <value>The children.</value>
  253. [IgnoreDataMember]
  254. public IEnumerable<BaseItem> Children
  255. {
  256. get { return ActualChildren; }
  257. }
  258. /// <summary>
  259. /// thread-safe access to all recursive children of this folder - without regard to user
  260. /// </summary>
  261. /// <value>The recursive children.</value>
  262. [IgnoreDataMember]
  263. public IEnumerable<BaseItem> RecursiveChildren
  264. {
  265. get { return GetRecursiveChildren(); }
  266. }
  267. public override bool IsVisible(User user)
  268. {
  269. if (this is ICollectionFolder && !(this is BasePluginFolder))
  270. {
  271. if (user.Policy.BlockedMediaFolders != null)
  272. {
  273. if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  274. // Backwards compatibility
  275. user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  276. {
  277. return false;
  278. }
  279. }
  280. else
  281. {
  282. if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  283. {
  284. return false;
  285. }
  286. }
  287. }
  288. return base.IsVisible(user);
  289. }
  290. private List<BaseItem> LoadChildrenInternal()
  291. {
  292. return LoadChildren().ToList();
  293. }
  294. /// <summary>
  295. /// Loads our children. Validation will occur externally.
  296. /// We want this sychronous.
  297. /// </summary>
  298. protected virtual IEnumerable<BaseItem> LoadChildren()
  299. {
  300. //just load our children from the repo - the library will be validated and maintained in other processes
  301. return GetCachedChildren();
  302. }
  303. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  304. {
  305. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService()));
  306. }
  307. /// <summary>
  308. /// Validates that the children of the folder still exist
  309. /// </summary>
  310. /// <param name="progress">The progress.</param>
  311. /// <param name="cancellationToken">The cancellation token.</param>
  312. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  313. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  314. /// <returns>Task.</returns>
  315. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  316. {
  317. return ValidateChildrenWithCancellationSupport(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  318. }
  319. private Task ValidateChildrenWithCancellationSupport(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  320. {
  321. return ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
  322. }
  323. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  324. {
  325. var dictionary = new Dictionary<Guid, BaseItem>();
  326. foreach (var child in ActualChildren)
  327. {
  328. var id = child.Id;
  329. if (dictionary.ContainsKey(id))
  330. {
  331. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  332. Path ?? Name,
  333. child.Path ?? child.Name);
  334. }
  335. else
  336. {
  337. dictionary[id] = child;
  338. }
  339. }
  340. return dictionary;
  341. }
  342. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  343. {
  344. return current.IsValidFromResolver(newItem);
  345. }
  346. /// <summary>
  347. /// Validates the children internal.
  348. /// </summary>
  349. /// <param name="progress">The progress.</param>
  350. /// <param name="cancellationToken">The cancellation token.</param>
  351. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  352. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  353. /// <param name="refreshOptions">The refresh options.</param>
  354. /// <param name="directoryService">The directory service.</param>
  355. /// <returns>Task.</returns>
  356. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  357. {
  358. var locationType = LocationType;
  359. cancellationToken.ThrowIfCancellationRequested();
  360. var validChildren = new List<BaseItem>();
  361. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  362. {
  363. IEnumerable<BaseItem> nonCachedChildren;
  364. try
  365. {
  366. nonCachedChildren = GetNonCachedChildren(directoryService);
  367. }
  368. catch (IOException ex)
  369. {
  370. nonCachedChildren = new BaseItem[] { };
  371. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  372. }
  373. if (nonCachedChildren == null) return; //nothing to validate
  374. progress.Report(5);
  375. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  376. var currentChildren = GetActualChildrenDictionary();
  377. //create a list for our validated children
  378. var newItems = new List<BaseItem>();
  379. cancellationToken.ThrowIfCancellationRequested();
  380. foreach (var child in nonCachedChildren)
  381. {
  382. BaseItem currentChild;
  383. if (currentChildren.TryGetValue(child.Id, out currentChild))
  384. {
  385. if (IsValidFromResolver(currentChild, child))
  386. {
  387. var currentChildLocationType = currentChild.LocationType;
  388. if (currentChildLocationType != LocationType.Remote &&
  389. currentChildLocationType != LocationType.Virtual)
  390. {
  391. currentChild.DateModified = child.DateModified;
  392. }
  393. currentChild.IsOffline = false;
  394. validChildren.Add(currentChild);
  395. }
  396. else
  397. {
  398. newItems.Add(child);
  399. validChildren.Add(child);
  400. }
  401. }
  402. else
  403. {
  404. // Brand new item - needs to be added
  405. newItems.Add(child);
  406. validChildren.Add(child);
  407. }
  408. }
  409. // If any items were added or removed....
  410. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  411. {
  412. // That's all the new and changed ones - now see if there are any that are missing
  413. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  414. var actualRemovals = new List<BaseItem>();
  415. foreach (var item in itemsRemoved)
  416. {
  417. if (item.LocationType == LocationType.Virtual ||
  418. item.LocationType == LocationType.Remote)
  419. {
  420. // Don't remove these because there's no way to accurately validate them.
  421. validChildren.Add(item);
  422. }
  423. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  424. {
  425. item.IsOffline = true;
  426. validChildren.Add(item);
  427. }
  428. else
  429. {
  430. item.IsOffline = false;
  431. actualRemovals.Add(item);
  432. }
  433. }
  434. if (actualRemovals.Count > 0)
  435. {
  436. RemoveChildrenInternal(actualRemovals);
  437. foreach (var item in actualRemovals)
  438. {
  439. LibraryManager.ReportItemRemoved(item);
  440. }
  441. }
  442. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  443. AddChildrenInternal(newItems);
  444. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  445. }
  446. }
  447. progress.Report(10);
  448. cancellationToken.ThrowIfCancellationRequested();
  449. if (recursive)
  450. {
  451. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  452. }
  453. progress.Report(20);
  454. if (refreshChildMetadata)
  455. {
  456. var container = this as IMetadataContainer;
  457. var innerProgress = new ActionableProgress<double>();
  458. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  459. if (container != null)
  460. {
  461. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  462. }
  463. else
  464. {
  465. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  466. }
  467. }
  468. progress.Report(100);
  469. }
  470. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  471. {
  472. var children = ActualChildren.ToList();
  473. var percentages = new Dictionary<Guid, double>(children.Count);
  474. var tasks = new List<Task>();
  475. foreach (var child in children)
  476. {
  477. if (tasks.Count >= 2)
  478. {
  479. await Task.WhenAll(tasks).ConfigureAwait(false);
  480. tasks.Clear();
  481. }
  482. cancellationToken.ThrowIfCancellationRequested();
  483. var innerProgress = new ActionableProgress<double>();
  484. // Avoid implicitly captured closure
  485. var currentChild = child;
  486. innerProgress.RegisterAction(p =>
  487. {
  488. lock (percentages)
  489. {
  490. percentages[currentChild.Id] = p / 100;
  491. var percent = percentages.Values.Sum();
  492. percent /= children.Count;
  493. percent *= 100;
  494. progress.Report(percent);
  495. }
  496. });
  497. if (child.IsFolder)
  498. {
  499. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  500. .ConfigureAwait(false);
  501. }
  502. else
  503. {
  504. // Avoid implicitly captured closure
  505. var taskChild = child;
  506. tasks.Add(Task.Run(async () => await RefreshChildMetadata(taskChild, refreshOptions, false, innerProgress, cancellationToken).ConfigureAwait(false), cancellationToken));
  507. }
  508. }
  509. await Task.WhenAll(tasks).ConfigureAwait(false);
  510. progress.Report(100);
  511. }
  512. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  513. {
  514. var container = child as IMetadataContainer;
  515. if (container != null)
  516. {
  517. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  518. }
  519. else
  520. {
  521. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  522. if (recursive)
  523. {
  524. var folder = child as Folder;
  525. if (folder != null)
  526. {
  527. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  528. }
  529. }
  530. }
  531. progress.Report(100);
  532. }
  533. /// <summary>
  534. /// Refreshes the children.
  535. /// </summary>
  536. /// <param name="children">The children.</param>
  537. /// <param name="directoryService">The directory service.</param>
  538. /// <param name="progress">The progress.</param>
  539. /// <param name="cancellationToken">The cancellation token.</param>
  540. /// <returns>Task.</returns>
  541. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  542. {
  543. var list = children;
  544. var childCount = list.Count;
  545. var percentages = new Dictionary<Guid, double>(list.Count);
  546. foreach (var item in list)
  547. {
  548. cancellationToken.ThrowIfCancellationRequested();
  549. var child = item;
  550. var innerProgress = new ActionableProgress<double>();
  551. innerProgress.RegisterAction(p =>
  552. {
  553. lock (percentages)
  554. {
  555. percentages[child.Id] = p / 100;
  556. var percent = percentages.Values.Sum();
  557. percent /= childCount;
  558. progress.Report((10 * percent) + 10);
  559. }
  560. });
  561. await child.ValidateChildrenWithCancellationSupport(innerProgress, cancellationToken, true, false, null, directoryService)
  562. .ConfigureAwait(false);
  563. }
  564. }
  565. /// <summary>
  566. /// Determines whether the specified path is offline.
  567. /// </summary>
  568. /// <param name="path">The path.</param>
  569. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  570. private bool IsPathOffline(string path)
  571. {
  572. if (File.Exists(path))
  573. {
  574. return false;
  575. }
  576. var originalPath = path;
  577. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  578. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  579. {
  580. if (Directory.Exists(path))
  581. {
  582. return false;
  583. }
  584. path = System.IO.Path.GetDirectoryName(path);
  585. }
  586. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  587. {
  588. return true;
  589. }
  590. return ContainsPath(LibraryManager.GetVirtualFolders(), originalPath);
  591. }
  592. /// <summary>
  593. /// Determines whether the specified folders contains path.
  594. /// </summary>
  595. /// <param name="folders">The folders.</param>
  596. /// <param name="path">The path.</param>
  597. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  598. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  599. {
  600. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  601. }
  602. private bool ContainsPath(string parent, string path)
  603. {
  604. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  605. }
  606. /// <summary>
  607. /// Get the children of this folder from the actual file system
  608. /// </summary>
  609. /// <returns>IEnumerable{BaseItem}.</returns>
  610. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  611. {
  612. var collectionType = LibraryManager.GetContentType(this);
  613. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  614. }
  615. /// <summary>
  616. /// Get our children from the repo - stubbed for now
  617. /// </summary>
  618. /// <returns>IEnumerable{BaseItem}.</returns>
  619. protected IEnumerable<BaseItem> GetCachedChildren()
  620. {
  621. var childrenItems = ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null);
  622. //var children = ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null).ToList();
  623. //if (children.Count != childrenItems.Count)
  624. //{
  625. // var b = this;
  626. //}
  627. return childrenItems;
  628. }
  629. /// <summary>
  630. /// Retrieves the child.
  631. /// </summary>
  632. /// <param name="child">The child.</param>
  633. /// <returns>BaseItem.</returns>
  634. private BaseItem RetrieveChild(Guid child)
  635. {
  636. var item = LibraryManager.GetItemById(child);
  637. if (item != null)
  638. {
  639. if (item is IByReferenceItem)
  640. {
  641. return LibraryManager.GetOrAddByReferenceItem(item);
  642. }
  643. item.Parent = this;
  644. }
  645. return item;
  646. }
  647. private BaseItem RetrieveChild(BaseItem child)
  648. {
  649. if (child.Id == Guid.Empty)
  650. {
  651. Logger.Error("Item found with empty Id: " + (child.Path ?? child.Name));
  652. return null;
  653. }
  654. var item = LibraryManager.GetMemoryItemById(child.Id);
  655. if (item != null)
  656. {
  657. if (item is IByReferenceItem)
  658. {
  659. return LibraryManager.GetOrAddByReferenceItem(item);
  660. }
  661. item.Parent = this;
  662. }
  663. else
  664. {
  665. child.Parent = this;
  666. LibraryManager.RegisterItem(child);
  667. item = child;
  668. }
  669. return item;
  670. }
  671. public virtual Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  672. {
  673. var user = query.User;
  674. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  675. var items = query.Recursive
  676. ? GetRecursiveChildren(user, filter)
  677. : GetChildren(user, true).Where(filter);
  678. var result = PostFilterAndSort(items, query);
  679. return Task.FromResult(result);
  680. }
  681. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  682. {
  683. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager);
  684. }
  685. /// <summary>
  686. /// Gets allowed children of an item
  687. /// </summary>
  688. /// <param name="user">The user.</param>
  689. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  690. /// <returns>IEnumerable{BaseItem}.</returns>
  691. /// <exception cref="System.ArgumentNullException"></exception>
  692. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  693. {
  694. return GetChildren(user, includeLinkedChildren, false);
  695. }
  696. internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
  697. {
  698. if (user == null)
  699. {
  700. throw new ArgumentNullException();
  701. }
  702. //the true root should return our users root folder children
  703. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  704. var result = new Dictionary<Guid, BaseItem>();
  705. AddChildren(user, includeLinkedChildren, result, includeHidden, false, null);
  706. return result.Values;
  707. }
  708. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  709. {
  710. return Children;
  711. }
  712. /// <summary>
  713. /// Adds the children to list.
  714. /// </summary>
  715. /// <param name="user">The user.</param>
  716. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  717. /// <param name="result">The result.</param>
  718. /// <param name="includeHidden">if set to <c>true</c> [include hidden].</param>
  719. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  720. /// <param name="filter">The filter.</param>
  721. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  722. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool includeHidden, bool recursive, Func<BaseItem, bool> filter)
  723. {
  724. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  725. {
  726. if (child.IsVisible(user))
  727. {
  728. if (includeHidden || !child.IsHiddenFromUser(user))
  729. {
  730. if (filter == null || filter(child))
  731. {
  732. result[child.Id] = child;
  733. }
  734. }
  735. if (recursive && child.IsFolder)
  736. {
  737. var folder = (Folder)child;
  738. folder.AddChildren(user, includeLinkedChildren, result, includeHidden, true, filter);
  739. }
  740. }
  741. }
  742. if (includeLinkedChildren)
  743. {
  744. foreach (var child in GetLinkedChildren(user))
  745. {
  746. if (child.IsVisible(user))
  747. {
  748. if (filter == null || filter(child))
  749. {
  750. result[child.Id] = child;
  751. }
  752. }
  753. }
  754. }
  755. }
  756. /// <summary>
  757. /// Gets allowed recursive children of an item
  758. /// </summary>
  759. /// <param name="user">The user.</param>
  760. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  761. /// <returns>IEnumerable{BaseItem}.</returns>
  762. /// <exception cref="System.ArgumentNullException"></exception>
  763. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  764. {
  765. return GetRecursiveChildren(user, i => true);
  766. }
  767. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
  768. {
  769. if (user == null)
  770. {
  771. throw new ArgumentNullException("user");
  772. }
  773. var result = new Dictionary<Guid, BaseItem>();
  774. AddChildren(user, true, result, false, true, filter);
  775. return result.Values;
  776. }
  777. /// <summary>
  778. /// Gets the recursive children.
  779. /// </summary>
  780. /// <returns>IList{BaseItem}.</returns>
  781. public IList<BaseItem> GetRecursiveChildren()
  782. {
  783. return GetRecursiveChildren(null);
  784. }
  785. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  786. {
  787. var list = new List<BaseItem>();
  788. AddChildrenToList(list, true, filter);
  789. return list;
  790. }
  791. /// <summary>
  792. /// Adds the children to list.
  793. /// </summary>
  794. /// <param name="list">The list.</param>
  795. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  796. /// <param name="filter">The filter.</param>
  797. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  798. {
  799. foreach (var child in Children)
  800. {
  801. if (filter == null || filter(child))
  802. {
  803. list.Add(child);
  804. }
  805. if (recursive && child.IsFolder)
  806. {
  807. var folder = (Folder)child;
  808. folder.AddChildrenToList(list, true, filter);
  809. }
  810. }
  811. }
  812. /// <summary>
  813. /// Gets the linked children.
  814. /// </summary>
  815. /// <returns>IEnumerable{BaseItem}.</returns>
  816. public IEnumerable<BaseItem> GetLinkedChildren()
  817. {
  818. return LinkedChildren
  819. .Select(GetLinkedChild)
  820. .Where(i => i != null);
  821. }
  822. protected virtual bool FilterLinkedChildrenPerUser
  823. {
  824. get
  825. {
  826. return false;
  827. }
  828. }
  829. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  830. {
  831. if (!FilterLinkedChildrenPerUser || user == null)
  832. {
  833. return GetLinkedChildren();
  834. }
  835. var locations = user.RootFolder
  836. .GetChildren(user, true)
  837. .OfType<CollectionFolder>()
  838. .SelectMany(i => i.PhysicalLocations)
  839. .ToList();
  840. return LinkedChildren
  841. .Select(i =>
  842. {
  843. var requiresPostFilter = true;
  844. if (!string.IsNullOrWhiteSpace(i.Path))
  845. {
  846. requiresPostFilter = false;
  847. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  848. {
  849. return null;
  850. }
  851. }
  852. var child = GetLinkedChild(i);
  853. if (requiresPostFilter && child != null)
  854. {
  855. if (string.IsNullOrWhiteSpace(child.Path))
  856. {
  857. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  858. return child;
  859. }
  860. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  861. {
  862. return null;
  863. }
  864. }
  865. return child;
  866. })
  867. .Where(i => i != null);
  868. }
  869. /// <summary>
  870. /// Gets the linked children.
  871. /// </summary>
  872. /// <returns>IEnumerable{BaseItem}.</returns>
  873. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  874. {
  875. return LinkedChildren
  876. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  877. .Where(i => i.Item2 != null);
  878. }
  879. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  880. {
  881. var changesFound = false;
  882. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  883. {
  884. if (RefreshLinkedChildren(fileSystemChildren))
  885. {
  886. changesFound = true;
  887. }
  888. }
  889. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  890. return baseHasChanges || changesFound;
  891. }
  892. /// <summary>
  893. /// Refreshes the linked children.
  894. /// </summary>
  895. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  896. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  897. {
  898. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  899. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  900. var newShortcutLinks = fileSystemChildren
  901. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  902. .Select(i =>
  903. {
  904. try
  905. {
  906. Logger.Debug("Found shortcut at {0}", i.FullName);
  907. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  908. if (!string.IsNullOrEmpty(resolvedPath))
  909. {
  910. return new LinkedChild
  911. {
  912. Path = resolvedPath,
  913. Type = LinkedChildType.Shortcut
  914. };
  915. }
  916. Logger.Error("Error resolving shortcut {0}", i.FullName);
  917. return null;
  918. }
  919. catch (IOException ex)
  920. {
  921. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  922. return null;
  923. }
  924. })
  925. .Where(i => i != null)
  926. .ToList();
  927. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  928. {
  929. Logger.Info("Shortcut links have changed for {0}", Path);
  930. newShortcutLinks.AddRange(currentManualLinks);
  931. LinkedChildren = newShortcutLinks;
  932. return true;
  933. }
  934. foreach (var child in LinkedChildren)
  935. {
  936. // Reset the cached value
  937. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  938. {
  939. child.ItemId = null;
  940. }
  941. }
  942. return false;
  943. }
  944. /// <summary>
  945. /// Folders need to validate and refresh
  946. /// </summary>
  947. /// <returns>Task.</returns>
  948. public override async Task ChangedExternally()
  949. {
  950. var progress = new Progress<double>();
  951. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  952. await base.ChangedExternally().ConfigureAwait(false);
  953. }
  954. /// <summary>
  955. /// Marks the played.
  956. /// </summary>
  957. /// <param name="user">The user.</param>
  958. /// <param name="datePlayed">The date played.</param>
  959. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  960. /// <returns>Task.</returns>
  961. public override async Task MarkPlayed(User user,
  962. DateTime? datePlayed,
  963. bool resetPosition)
  964. {
  965. // Sweep through recursively and update status
  966. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  967. .Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  968. await Task.WhenAll(tasks).ConfigureAwait(false);
  969. }
  970. /// <summary>
  971. /// Marks the unplayed.
  972. /// </summary>
  973. /// <param name="user">The user.</param>
  974. /// <returns>Task.</returns>
  975. public override async Task MarkUnplayed(User user)
  976. {
  977. // Sweep through recursively and update status
  978. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  979. .Select(c => c.MarkUnplayed(user));
  980. await Task.WhenAll(tasks).ConfigureAwait(false);
  981. }
  982. /// <summary>
  983. /// Finds an item by path, recursively
  984. /// </summary>
  985. /// <param name="path">The path.</param>
  986. /// <returns>BaseItem.</returns>
  987. /// <exception cref="System.ArgumentNullException"></exception>
  988. public BaseItem FindByPath(string path)
  989. {
  990. if (string.IsNullOrEmpty(path))
  991. {
  992. throw new ArgumentNullException();
  993. }
  994. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  995. {
  996. return this;
  997. }
  998. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  999. {
  1000. return this;
  1001. }
  1002. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1003. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1004. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1005. .FirstOrDefault();
  1006. }
  1007. public override bool IsPlayed(User user)
  1008. {
  1009. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1010. .All(i => i.IsPlayed(user));
  1011. }
  1012. public override bool IsUnplayed(User user)
  1013. {
  1014. return !IsPlayed(user);
  1015. }
  1016. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1017. {
  1018. var recursiveItemCount = 0;
  1019. var unplayed = 0;
  1020. double totalPercentPlayed = 0;
  1021. IEnumerable<BaseItem> children;
  1022. var folder = this;
  1023. var season = folder as Season;
  1024. if (season != null)
  1025. {
  1026. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1027. }
  1028. else
  1029. {
  1030. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1031. }
  1032. // Loop through each recursive child
  1033. foreach (var child in children)
  1034. {
  1035. recursiveItemCount++;
  1036. var isUnplayed = true;
  1037. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1038. // Incrememt totalPercentPlayed
  1039. if (itemUserData != null)
  1040. {
  1041. if (itemUserData.Played)
  1042. {
  1043. totalPercentPlayed += 100;
  1044. isUnplayed = false;
  1045. }
  1046. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1047. {
  1048. double itemPercent = itemUserData.PlaybackPositionTicks;
  1049. itemPercent /= child.RunTimeTicks.Value;
  1050. totalPercentPlayed += itemPercent;
  1051. }
  1052. }
  1053. if (isUnplayed)
  1054. {
  1055. unplayed++;
  1056. }
  1057. }
  1058. dto.UnplayedItemCount = unplayed;
  1059. if (recursiveItemCount > 0)
  1060. {
  1061. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1062. dto.Played = dto.PlayedPercentage.Value >= 100;
  1063. }
  1064. }
  1065. }
  1066. }