Folder.cs 45 KB

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