Folder.cs 45 KB

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