Folder.cs 43 KB

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