Folder.cs 44 KB

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