Folder.cs 44 KB

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