Folder.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Localization;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Entities;
  8. using MoreLinq;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Runtime.Serialization;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Controller.Entities
  18. {
  19. /// <summary>
  20. /// Class Folder
  21. /// </summary>
  22. public class Folder : BaseItem, IHasThemeMedia
  23. {
  24. public static IUserManager UserManager { get; set; }
  25. public List<Guid> ThemeSongIds { get; set; }
  26. public List<Guid> ThemeVideoIds { get; set; }
  27. public Folder()
  28. {
  29. LinkedChildren = new List<LinkedChild>();
  30. ThemeSongIds = new List<Guid>();
  31. ThemeVideoIds = new List<Guid>();
  32. }
  33. /// <summary>
  34. /// Gets a value indicating whether this instance is folder.
  35. /// </summary>
  36. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  37. [IgnoreDataMember]
  38. public override bool IsFolder
  39. {
  40. get
  41. {
  42. return true;
  43. }
  44. }
  45. /// <summary>
  46. /// Gets or sets a value indicating whether this instance is physical root.
  47. /// </summary>
  48. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  49. public bool IsPhysicalRoot { get; set; }
  50. /// <summary>
  51. /// Gets or sets a value indicating whether this instance is root.
  52. /// </summary>
  53. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  54. public bool IsRoot { get; set; }
  55. /// <summary>
  56. /// Gets a value indicating whether this instance is virtual folder.
  57. /// </summary>
  58. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  59. [IgnoreDataMember]
  60. public virtual bool IsVirtualFolder
  61. {
  62. get
  63. {
  64. return false;
  65. }
  66. }
  67. public virtual List<LinkedChild> LinkedChildren { get; set; }
  68. protected virtual bool SupportsShortcutChildren
  69. {
  70. get { return true; }
  71. }
  72. /// <summary>
  73. /// Adds the child.
  74. /// </summary>
  75. /// <param name="item">The item.</param>
  76. /// <param name="cancellationToken">The cancellation token.</param>
  77. /// <returns>Task.</returns>
  78. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  79. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  80. {
  81. item.Parent = this;
  82. if (item.Id == Guid.Empty)
  83. {
  84. item.Id = item.Path.GetMBId(item.GetType());
  85. }
  86. if (ActualChildren.Any(i => i.Id == item.Id))
  87. {
  88. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  89. }
  90. if (item.DateCreated == DateTime.MinValue)
  91. {
  92. item.DateCreated = DateTime.UtcNow;
  93. }
  94. if (item.DateModified == DateTime.MinValue)
  95. {
  96. item.DateModified = DateTime.UtcNow;
  97. }
  98. AddChildInternal(item);
  99. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  100. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  101. }
  102. protected void AddChildrenInternal(IEnumerable<BaseItem> children)
  103. {
  104. lock (_childrenSyncLock)
  105. {
  106. var newChildren = ActualChildren.ToList();
  107. newChildren.AddRange(children);
  108. _children = newChildren;
  109. }
  110. }
  111. protected void AddChildInternal(BaseItem child)
  112. {
  113. lock (_childrenSyncLock)
  114. {
  115. var newChildren = ActualChildren.ToList();
  116. newChildren.Add(child);
  117. _children = newChildren;
  118. }
  119. }
  120. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  121. {
  122. var ids = children.Select(i => i.Id).ToList();
  123. lock (_childrenSyncLock)
  124. {
  125. _children = ActualChildren.Where(i => !ids.Contains(i.Id)).ToList();
  126. }
  127. }
  128. protected void ClearChildrenInternal()
  129. {
  130. lock (_childrenSyncLock)
  131. {
  132. _children = new List<BaseItem>();
  133. }
  134. }
  135. /// <summary>
  136. /// Never want folders to be blocked by "BlockNotRated"
  137. /// </summary>
  138. [IgnoreDataMember]
  139. public override string OfficialRatingForComparison
  140. {
  141. get
  142. {
  143. if (this is Series)
  144. {
  145. return base.OfficialRatingForComparison;
  146. }
  147. return !string.IsNullOrEmpty(base.OfficialRatingForComparison) ? base.OfficialRatingForComparison : "None";
  148. }
  149. }
  150. /// <summary>
  151. /// Removes the child.
  152. /// </summary>
  153. /// <param name="item">The item.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task.</returns>
  156. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  157. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  158. {
  159. RemoveChildrenInternal(new[] { item });
  160. item.Parent = null;
  161. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  162. }
  163. /// <summary>
  164. /// Clears the children.
  165. /// </summary>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task.</returns>
  168. public Task ClearChildren(CancellationToken cancellationToken)
  169. {
  170. var items = ActualChildren.ToList();
  171. ClearChildrenInternal();
  172. foreach (var item in items)
  173. {
  174. LibraryManager.ReportItemRemoved(item);
  175. }
  176. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  177. }
  178. #region Indexing
  179. /// <summary>
  180. /// Returns the valid set of index by options for this folder type.
  181. /// Override or extend to modify.
  182. /// </summary>
  183. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  184. protected virtual IEnumerable<string> GetIndexByOptions()
  185. {
  186. return new List<string> {
  187. {LocalizedStrings.Instance.GetString("NoneDispPref")},
  188. {LocalizedStrings.Instance.GetString("PerformerDispPref")},
  189. {LocalizedStrings.Instance.GetString("GenreDispPref")},
  190. {LocalizedStrings.Instance.GetString("DirectorDispPref")},
  191. {LocalizedStrings.Instance.GetString("YearDispPref")},
  192. {LocalizedStrings.Instance.GetString("StudioDispPref")}
  193. };
  194. }
  195. /// <summary>
  196. /// Get the list of indexy by choices for this folder (localized).
  197. /// </summary>
  198. /// <value>The index by option strings.</value>
  199. [IgnoreDataMember]
  200. public IEnumerable<string> IndexByOptionStrings
  201. {
  202. get { return GetIndexByOptions(); }
  203. }
  204. #endregion
  205. /// <summary>
  206. /// The children
  207. /// </summary>
  208. private IReadOnlyList<BaseItem> _children;
  209. /// <summary>
  210. /// The _children sync lock
  211. /// </summary>
  212. private readonly object _childrenSyncLock = new object();
  213. /// <summary>
  214. /// Gets or sets the actual children.
  215. /// </summary>
  216. /// <value>The actual children.</value>
  217. protected virtual IEnumerable<BaseItem> ActualChildren
  218. {
  219. get
  220. {
  221. return _children ?? (_children = LoadChildrenInternal());
  222. }
  223. }
  224. /// <summary>
  225. /// thread-safe access to the actual children of this folder - without regard to user
  226. /// </summary>
  227. /// <value>The children.</value>
  228. [IgnoreDataMember]
  229. public IEnumerable<BaseItem> Children
  230. {
  231. get { return ActualChildren.Where(i => !i.IsHidden); }
  232. }
  233. /// <summary>
  234. /// thread-safe access to all recursive children of this folder - without regard to user
  235. /// </summary>
  236. /// <value>The recursive children.</value>
  237. [IgnoreDataMember]
  238. public IEnumerable<BaseItem> RecursiveChildren
  239. {
  240. get { return GetRecursiveChildren(); }
  241. }
  242. public override bool IsVisible(User user)
  243. {
  244. if (this is ICollectionFolder)
  245. {
  246. if (user.Configuration.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  247. // Backwards compatibility
  248. user.Configuration.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  249. {
  250. return false;
  251. }
  252. }
  253. return base.IsVisible(user);
  254. }
  255. private List<BaseItem> LoadChildrenInternal()
  256. {
  257. return LoadChildren().ToList();
  258. }
  259. /// <summary>
  260. /// Loads our children. Validation will occur externally.
  261. /// We want this sychronous.
  262. /// </summary>
  263. protected virtual IEnumerable<BaseItem> LoadChildren()
  264. {
  265. //just load our children from the repo - the library will be validated and maintained in other processes
  266. return GetCachedChildren();
  267. }
  268. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  269. {
  270. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions());
  271. }
  272. /// <summary>
  273. /// Validates that the children of the folder still exist
  274. /// </summary>
  275. /// <param name="progress">The progress.</param>
  276. /// <param name="cancellationToken">The cancellation token.</param>
  277. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  278. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  279. /// <returns>Task.</returns>
  280. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  281. {
  282. metadataRefreshOptions.DirectoryService = metadataRefreshOptions.DirectoryService ?? new DirectoryService(Logger);
  283. return ValidateChildrenWithCancellationSupport(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  284. }
  285. private Task ValidateChildrenWithCancellationSupport(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  286. {
  287. return ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
  288. }
  289. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  290. {
  291. var dictionary = new Dictionary<Guid, BaseItem>();
  292. foreach (var child in ActualChildren)
  293. {
  294. var id = child.Id;
  295. if (dictionary.ContainsKey(id))
  296. {
  297. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  298. Path ?? Name,
  299. child.Path ?? child.Name);
  300. }
  301. else
  302. {
  303. dictionary[id] = child;
  304. }
  305. }
  306. return dictionary;
  307. }
  308. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  309. {
  310. var currentAsVideo = current as Video;
  311. if (currentAsVideo != null)
  312. {
  313. var newAsVideo = newItem as Video;
  314. if (newAsVideo != null)
  315. {
  316. if (currentAsVideo.IsPlaceHolder != newAsVideo.IsPlaceHolder)
  317. {
  318. return false;
  319. }
  320. if (currentAsVideo.IsMultiPart != newAsVideo.IsMultiPart)
  321. {
  322. return false;
  323. }
  324. if (currentAsVideo.HasLocalAlternateVersions != newAsVideo.HasLocalAlternateVersions)
  325. {
  326. return false;
  327. }
  328. }
  329. }
  330. else
  331. {
  332. var currentAsPlaceHolder = current as ISupportsPlaceHolders;
  333. if (currentAsPlaceHolder != null)
  334. {
  335. var newHasPlaceHolder = newItem as ISupportsPlaceHolders;
  336. if (newHasPlaceHolder != null)
  337. {
  338. if (currentAsPlaceHolder.IsPlaceHolder != newHasPlaceHolder.IsPlaceHolder)
  339. {
  340. return false;
  341. }
  342. }
  343. }
  344. }
  345. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  346. }
  347. /// <summary>
  348. /// Validates the children internal.
  349. /// </summary>
  350. /// <param name="progress">The progress.</param>
  351. /// <param name="cancellationToken">The cancellation token.</param>
  352. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  353. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  354. /// <param name="refreshOptions">The refresh options.</param>
  355. /// <param name="directoryService">The directory service.</param>
  356. /// <returns>Task.</returns>
  357. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  358. {
  359. var locationType = LocationType;
  360. cancellationToken.ThrowIfCancellationRequested();
  361. var validChildren = new List<BaseItem>();
  362. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  363. {
  364. IEnumerable<BaseItem> nonCachedChildren;
  365. try
  366. {
  367. nonCachedChildren = GetNonCachedChildren(directoryService);
  368. }
  369. catch (IOException ex)
  370. {
  371. nonCachedChildren = new BaseItem[] { };
  372. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  373. }
  374. if (nonCachedChildren == null) return; //nothing to validate
  375. progress.Report(5);
  376. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  377. var currentChildren = GetActualChildrenDictionary();
  378. //create a list for our validated children
  379. var newItems = new List<BaseItem>();
  380. cancellationToken.ThrowIfCancellationRequested();
  381. foreach (var child in nonCachedChildren)
  382. {
  383. BaseItem currentChild;
  384. if (currentChildren.TryGetValue(child.Id, out currentChild))
  385. {
  386. if (IsValidFromResolver(currentChild, child))
  387. {
  388. var currentChildLocationType = currentChild.LocationType;
  389. if (currentChildLocationType != LocationType.Remote &&
  390. currentChildLocationType != LocationType.Virtual)
  391. {
  392. currentChild.DateModified = child.DateModified;
  393. }
  394. currentChild.IsOffline = false;
  395. validChildren.Add(currentChild);
  396. }
  397. else
  398. {
  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 >= 3)
  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.GetDefaultVirtualFolders(), originalPath))
  587. {
  588. return true;
  589. }
  590. return UserManager.Users.Any(user => ContainsPath(LibraryManager.GetVirtualFolders(user), 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. return LibraryManager.ResolvePaths<BaseItem>(GetFileSystemChildren(directoryService), directoryService, this);
  613. }
  614. /// <summary>
  615. /// Get our children from the repo - stubbed for now
  616. /// </summary>
  617. /// <returns>IEnumerable{BaseItem}.</returns>
  618. protected IEnumerable<BaseItem> GetCachedChildren()
  619. {
  620. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  621. }
  622. /// <summary>
  623. /// Retrieves the child.
  624. /// </summary>
  625. /// <param name="child">The child.</param>
  626. /// <returns>BaseItem.</returns>
  627. private BaseItem RetrieveChild(Guid child)
  628. {
  629. var item = LibraryManager.GetItemById(child);
  630. if (item != null)
  631. {
  632. if (item is IByReferenceItem)
  633. {
  634. return LibraryManager.GetOrAddByReferenceItem(item);
  635. }
  636. item.Parent = this;
  637. }
  638. return item;
  639. }
  640. /// <summary>
  641. /// Gets allowed children of an item
  642. /// </summary>
  643. /// <param name="user">The user.</param>
  644. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  645. /// <returns>IEnumerable{BaseItem}.</returns>
  646. /// <exception cref="System.ArgumentNullException"></exception>
  647. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  648. {
  649. if (user == null)
  650. {
  651. throw new ArgumentNullException();
  652. }
  653. //the true root should return our users root folder children
  654. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  655. var list = new List<BaseItem>();
  656. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, false, null);
  657. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  658. }
  659. /// <summary>
  660. /// Adds the children to list.
  661. /// </summary>
  662. /// <param name="user">The user.</param>
  663. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  664. /// <param name="list">The list.</param>
  665. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  666. /// <param name="filter">The filter.</param>
  667. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  668. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  669. {
  670. var hasLinkedChildren = false;
  671. foreach (var child in Children)
  672. {
  673. if (child.IsVisible(user))
  674. {
  675. if (filter == null || filter(child))
  676. {
  677. list.Add(child);
  678. }
  679. if (recursive && child.IsFolder)
  680. {
  681. var folder = (Folder)child;
  682. if (folder.AddChildrenToList(user, includeLinkedChildren, list, true, filter))
  683. {
  684. hasLinkedChildren = true;
  685. }
  686. }
  687. }
  688. }
  689. if (includeLinkedChildren)
  690. {
  691. foreach (var child in GetLinkedChildren())
  692. {
  693. if (filter != null && !filter(child))
  694. {
  695. continue;
  696. }
  697. if (child.IsVisible(user))
  698. {
  699. hasLinkedChildren = true;
  700. list.Add(child);
  701. }
  702. }
  703. }
  704. return hasLinkedChildren;
  705. }
  706. /// <summary>
  707. /// Gets allowed recursive children of an item
  708. /// </summary>
  709. /// <param name="user">The user.</param>
  710. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  711. /// <returns>IEnumerable{BaseItem}.</returns>
  712. /// <exception cref="System.ArgumentNullException"></exception>
  713. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  714. {
  715. return GetRecursiveChildren(user, null, includeLinkedChildren);
  716. }
  717. /// <summary>
  718. /// Gets the recursive children.
  719. /// </summary>
  720. /// <param name="user">The user.</param>
  721. /// <param name="filter">The filter.</param>
  722. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  723. /// <returns>IList{BaseItem}.</returns>
  724. /// <exception cref="System.ArgumentNullException"></exception>
  725. public IList<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter, bool includeLinkedChildren = true)
  726. {
  727. if (user == null)
  728. {
  729. throw new ArgumentNullException("user");
  730. }
  731. var list = new List<BaseItem>();
  732. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, true, filter);
  733. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  734. }
  735. /// <summary>
  736. /// Gets the recursive children.
  737. /// </summary>
  738. /// <returns>IList{BaseItem}.</returns>
  739. public IList<BaseItem> GetRecursiveChildren()
  740. {
  741. return GetRecursiveChildren(i => true);
  742. }
  743. /// <summary>
  744. /// Gets the recursive children.
  745. /// </summary>
  746. /// <param name="filter">The filter.</param>
  747. /// <returns>IEnumerable{BaseItem}.</returns>
  748. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  749. {
  750. var list = new List<BaseItem>();
  751. AddChildrenToList(list, true, filter);
  752. return list;
  753. }
  754. /// <summary>
  755. /// Adds the children to list.
  756. /// </summary>
  757. /// <param name="list">The list.</param>
  758. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  759. /// <param name="filter">The filter.</param>
  760. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  761. {
  762. foreach (var child in Children)
  763. {
  764. if (filter == null || filter(child))
  765. {
  766. list.Add(child);
  767. }
  768. if (recursive && child.IsFolder)
  769. {
  770. var folder = (Folder)child;
  771. folder.AddChildrenToList(list, true, filter);
  772. }
  773. }
  774. }
  775. /// <summary>
  776. /// Gets the linked children.
  777. /// </summary>
  778. /// <returns>IEnumerable{BaseItem}.</returns>
  779. public IEnumerable<BaseItem> GetLinkedChildren()
  780. {
  781. return LinkedChildren
  782. .Select(GetLinkedChild)
  783. .Where(i => i != null);
  784. }
  785. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  786. {
  787. var changesFound = false;
  788. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  789. {
  790. if (RefreshLinkedChildren(fileSystemChildren))
  791. {
  792. changesFound = true;
  793. }
  794. }
  795. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  796. return baseHasChanges || changesFound;
  797. }
  798. /// <summary>
  799. /// Refreshes the linked children.
  800. /// </summary>
  801. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  802. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  803. {
  804. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  805. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  806. var newShortcutLinks = fileSystemChildren
  807. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  808. .Select(i =>
  809. {
  810. try
  811. {
  812. Logger.Debug("Found shortcut at {0}", i.FullName);
  813. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  814. if (!string.IsNullOrEmpty(resolvedPath))
  815. {
  816. return new LinkedChild
  817. {
  818. Path = resolvedPath,
  819. Type = LinkedChildType.Shortcut
  820. };
  821. }
  822. Logger.Error("Error resolving shortcut {0}", i.FullName);
  823. return null;
  824. }
  825. catch (IOException ex)
  826. {
  827. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  828. return null;
  829. }
  830. })
  831. .Where(i => i != null)
  832. .ToList();
  833. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  834. {
  835. Logger.Info("Shortcut links have changed for {0}", Path);
  836. newShortcutLinks.AddRange(currentManualLinks);
  837. LinkedChildren = newShortcutLinks;
  838. return true;
  839. }
  840. foreach (var child in LinkedChildren)
  841. {
  842. // Reset the cached value
  843. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  844. {
  845. child.ItemId = null;
  846. }
  847. }
  848. return false;
  849. }
  850. /// <summary>
  851. /// Folders need to validate and refresh
  852. /// </summary>
  853. /// <returns>Task.</returns>
  854. public override async Task ChangedExternally()
  855. {
  856. var progress = new Progress<double>();
  857. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  858. await base.ChangedExternally().ConfigureAwait(false);
  859. }
  860. /// <summary>
  861. /// Marks the played.
  862. /// </summary>
  863. /// <param name="user">The user.</param>
  864. /// <param name="datePlayed">The date played.</param>
  865. /// <param name="userManager">The user manager.</param>
  866. /// <returns>Task.</returns>
  867. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  868. {
  869. // Sweep through recursively and update status
  870. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  871. await Task.WhenAll(tasks).ConfigureAwait(false);
  872. }
  873. /// <summary>
  874. /// Marks the unplayed.
  875. /// </summary>
  876. /// <param name="user">The user.</param>
  877. /// <param name="userManager">The user manager.</param>
  878. /// <returns>Task.</returns>
  879. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  880. {
  881. // Sweep through recursively and update status
  882. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkUnplayed(user, userManager));
  883. await Task.WhenAll(tasks).ConfigureAwait(false);
  884. }
  885. /// <summary>
  886. /// Finds an item by path, recursively
  887. /// </summary>
  888. /// <param name="path">The path.</param>
  889. /// <returns>BaseItem.</returns>
  890. /// <exception cref="System.ArgumentNullException"></exception>
  891. public BaseItem FindByPath(string path)
  892. {
  893. if (string.IsNullOrEmpty(path))
  894. {
  895. throw new ArgumentNullException();
  896. }
  897. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  898. {
  899. return this;
  900. }
  901. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  902. {
  903. return this;
  904. }
  905. return RecursiveChildren.FirstOrDefault(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  906. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  907. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase));
  908. }
  909. public override bool IsPlayed(User user)
  910. {
  911. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  912. .All(i => i.IsPlayed(user));
  913. }
  914. public override bool IsUnplayed(User user)
  915. {
  916. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  917. .All(i => i.IsUnplayed(user));
  918. }
  919. public IEnumerable<BaseItem> GetHiddenChildren()
  920. {
  921. return ActualChildren.Where(i => i.IsHidden);
  922. }
  923. }
  924. }