Folder.cs 44 KB

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