Folder.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  295. {
  296. return false;
  297. }
  298. }
  299. return base.IsVisible(user);
  300. }
  301. private List<BaseItem> LoadChildrenInternal()
  302. {
  303. return LoadChildren().ToList();
  304. }
  305. /// <summary>
  306. /// Loads our children. Validation will occur externally.
  307. /// We want this sychronous.
  308. /// </summary>
  309. protected virtual IEnumerable<BaseItem> LoadChildren()
  310. {
  311. //just load our children from the repo - the library will be validated and maintained in other processes
  312. return GetCachedChildren();
  313. }
  314. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  315. {
  316. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService()));
  317. }
  318. /// <summary>
  319. /// Validates that the children of the folder still exist
  320. /// </summary>
  321. /// <param name="progress">The progress.</param>
  322. /// <param name="cancellationToken">The cancellation token.</param>
  323. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  324. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  325. /// <returns>Task.</returns>
  326. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  327. {
  328. return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  329. }
  330. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  331. {
  332. var dictionary = new Dictionary<Guid, BaseItem>();
  333. foreach (var child in ActualChildren)
  334. {
  335. var id = child.Id;
  336. if (dictionary.ContainsKey(id))
  337. {
  338. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  339. Path ?? Name,
  340. child.Path ?? child.Name);
  341. }
  342. else
  343. {
  344. dictionary[id] = child;
  345. }
  346. }
  347. return dictionary;
  348. }
  349. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  350. {
  351. return current.IsValidFromResolver(newItem);
  352. }
  353. /// <summary>
  354. /// Validates the children internal.
  355. /// </summary>
  356. /// <param name="progress">The progress.</param>
  357. /// <param name="cancellationToken">The cancellation token.</param>
  358. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  359. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  360. /// <param name="refreshOptions">The refresh options.</param>
  361. /// <param name="directoryService">The directory service.</param>
  362. /// <returns>Task.</returns>
  363. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  364. {
  365. var locationType = LocationType;
  366. cancellationToken.ThrowIfCancellationRequested();
  367. var validChildren = new List<BaseItem>();
  368. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  369. {
  370. IEnumerable<BaseItem> nonCachedChildren;
  371. try
  372. {
  373. nonCachedChildren = GetNonCachedChildren(directoryService);
  374. }
  375. catch (IOException ex)
  376. {
  377. nonCachedChildren = new BaseItem[] { };
  378. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  379. }
  380. if (nonCachedChildren == null) return; //nothing to validate
  381. progress.Report(5);
  382. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  383. var currentChildren = GetActualChildrenDictionary();
  384. //create a list for our validated children
  385. var newItems = new List<BaseItem>();
  386. cancellationToken.ThrowIfCancellationRequested();
  387. foreach (var child in nonCachedChildren)
  388. {
  389. BaseItem currentChild;
  390. if (currentChildren.TryGetValue(child.Id, out currentChild))
  391. {
  392. if (IsValidFromResolver(currentChild, child))
  393. {
  394. var currentChildLocationType = currentChild.LocationType;
  395. if (currentChildLocationType != LocationType.Remote &&
  396. currentChildLocationType != LocationType.Virtual)
  397. {
  398. currentChild.DateModified = child.DateModified;
  399. }
  400. currentChild.IsOffline = false;
  401. validChildren.Add(currentChild);
  402. }
  403. else
  404. {
  405. newItems.Add(child);
  406. validChildren.Add(child);
  407. }
  408. }
  409. else
  410. {
  411. // Brand new item - needs to be added
  412. newItems.Add(child);
  413. validChildren.Add(child);
  414. }
  415. }
  416. // If any items were added or removed....
  417. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  418. {
  419. // That's all the new and changed ones - now see if there are any that are missing
  420. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  421. var actualRemovals = new List<BaseItem>();
  422. foreach (var item in itemsRemoved)
  423. {
  424. if (item.LocationType == LocationType.Virtual ||
  425. item.LocationType == LocationType.Remote)
  426. {
  427. // Don't remove these because there's no way to accurately validate them.
  428. validChildren.Add(item);
  429. }
  430. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  431. {
  432. item.IsOffline = true;
  433. validChildren.Add(item);
  434. }
  435. else
  436. {
  437. item.IsOffline = false;
  438. actualRemovals.Add(item);
  439. }
  440. }
  441. if (actualRemovals.Count > 0)
  442. {
  443. RemoveChildrenInternal(actualRemovals);
  444. foreach (var item in actualRemovals)
  445. {
  446. LibraryManager.ReportItemRemoved(item);
  447. }
  448. }
  449. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  450. AddChildrenInternal(newItems);
  451. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  452. }
  453. }
  454. progress.Report(10);
  455. cancellationToken.ThrowIfCancellationRequested();
  456. if (recursive)
  457. {
  458. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  459. }
  460. progress.Report(20);
  461. if (refreshChildMetadata)
  462. {
  463. var container = this as IMetadataContainer;
  464. var innerProgress = new ActionableProgress<double>();
  465. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  466. if (container != null)
  467. {
  468. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  469. }
  470. else
  471. {
  472. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  473. }
  474. }
  475. progress.Report(100);
  476. }
  477. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  478. {
  479. var children = ActualChildren.ToList();
  480. var percentages = new Dictionary<Guid, double>(children.Count);
  481. var numComplete = 0;
  482. var count = children.Count;
  483. foreach (var child in children)
  484. {
  485. cancellationToken.ThrowIfCancellationRequested();
  486. if (child.IsFolder)
  487. {
  488. var innerProgress = new ActionableProgress<double>();
  489. // Avoid implicitly captured closure
  490. var currentChild = child;
  491. innerProgress.RegisterAction(p =>
  492. {
  493. lock (percentages)
  494. {
  495. percentages[currentChild.Id] = p / 100;
  496. var innerPercent = percentages.Values.Sum();
  497. innerPercent /= count;
  498. innerPercent *= 100;
  499. progress.Report(innerPercent);
  500. }
  501. });
  502. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  503. .ConfigureAwait(false);
  504. }
  505. else
  506. {
  507. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  508. .ConfigureAwait(false);
  509. }
  510. numComplete++;
  511. double percent = numComplete;
  512. percent /= count;
  513. percent *= 100;
  514. progress.Report(percent);
  515. }
  516. progress.Report(100);
  517. }
  518. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  519. {
  520. var container = child as IMetadataContainer;
  521. if (container != null)
  522. {
  523. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  524. }
  525. else
  526. {
  527. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  528. if (recursive)
  529. {
  530. var folder = child as Folder;
  531. if (folder != null)
  532. {
  533. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  534. }
  535. }
  536. }
  537. progress.Report(100);
  538. }
  539. /// <summary>
  540. /// Refreshes the children.
  541. /// </summary>
  542. /// <param name="children">The children.</param>
  543. /// <param name="directoryService">The directory service.</param>
  544. /// <param name="progress">The progress.</param>
  545. /// <param name="cancellationToken">The cancellation token.</param>
  546. /// <returns>Task.</returns>
  547. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  548. {
  549. var list = children;
  550. var childCount = list.Count;
  551. var percentages = new Dictionary<Guid, double>(list.Count);
  552. foreach (var item in list)
  553. {
  554. cancellationToken.ThrowIfCancellationRequested();
  555. var child = item;
  556. var innerProgress = new ActionableProgress<double>();
  557. innerProgress.RegisterAction(p =>
  558. {
  559. lock (percentages)
  560. {
  561. percentages[child.Id] = p / 100;
  562. var percent = percentages.Values.Sum();
  563. percent /= childCount;
  564. progress.Report((10 * percent) + 10);
  565. }
  566. });
  567. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  568. .ConfigureAwait(false);
  569. }
  570. }
  571. /// <summary>
  572. /// Determines whether the specified path is offline.
  573. /// </summary>
  574. /// <param name="path">The path.</param>
  575. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  576. private bool IsPathOffline(string path)
  577. {
  578. if (File.Exists(path))
  579. {
  580. return false;
  581. }
  582. var originalPath = path;
  583. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  584. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  585. {
  586. if (Directory.Exists(path))
  587. {
  588. return false;
  589. }
  590. path = System.IO.Path.GetDirectoryName(path);
  591. }
  592. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  593. {
  594. return true;
  595. }
  596. return ContainsPath(LibraryManager.GetVirtualFolders(), originalPath);
  597. }
  598. /// <summary>
  599. /// Determines whether the specified folders contains path.
  600. /// </summary>
  601. /// <param name="folders">The folders.</param>
  602. /// <param name="path">The path.</param>
  603. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  604. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  605. {
  606. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  607. }
  608. private bool ContainsPath(string parent, string path)
  609. {
  610. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  611. }
  612. /// <summary>
  613. /// Get the children of this folder from the actual file system
  614. /// </summary>
  615. /// <returns>IEnumerable{BaseItem}.</returns>
  616. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  617. {
  618. var collectionType = LibraryManager.GetContentType(this);
  619. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  620. }
  621. /// <summary>
  622. /// Get our children from the repo - stubbed for now
  623. /// </summary>
  624. /// <returns>IEnumerable{BaseItem}.</returns>
  625. protected IEnumerable<BaseItem> GetCachedChildren()
  626. {
  627. var childrenItems = ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null);
  628. //var children = ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null).ToList();
  629. //if (children.Count != childrenItems.Count)
  630. //{
  631. // var b = this;
  632. //}
  633. return childrenItems;
  634. }
  635. private BaseItem RetrieveChild(BaseItem child)
  636. {
  637. if (child.Id == Guid.Empty)
  638. {
  639. Logger.Error("Item found with empty Id: " + (child.Path ?? child.Name));
  640. return null;
  641. }
  642. var item = LibraryManager.GetMemoryItemById(child.Id);
  643. if (item != null)
  644. {
  645. if (item is IByReferenceItem)
  646. {
  647. return LibraryManager.GetOrAddByReferenceItem(item);
  648. }
  649. item.Parent = this;
  650. }
  651. else
  652. {
  653. child.Parent = this;
  654. LibraryManager.RegisterItem(child);
  655. item = child;
  656. }
  657. return item;
  658. }
  659. public virtual Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  660. {
  661. var user = query.User;
  662. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  663. IEnumerable<BaseItem> items;
  664. if (query.User == null)
  665. {
  666. items = query.Recursive
  667. ? GetRecursiveChildren(filter)
  668. : Children.Where(filter);
  669. }
  670. else
  671. {
  672. items = query.Recursive
  673. ? GetRecursiveChildren(user, filter)
  674. : GetChildren(user, true).Where(filter);
  675. }
  676. var result = PostFilterAndSort(items, query);
  677. return Task.FromResult(result);
  678. }
  679. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  680. {
  681. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager);
  682. }
  683. /// <summary>
  684. /// Gets allowed children of an item
  685. /// </summary>
  686. /// <param name="user">The user.</param>
  687. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  688. /// <returns>IEnumerable{BaseItem}.</returns>
  689. /// <exception cref="System.ArgumentNullException"></exception>
  690. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  691. {
  692. return GetChildren(user, includeLinkedChildren, false);
  693. }
  694. internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
  695. {
  696. if (user == null)
  697. {
  698. throw new ArgumentNullException();
  699. }
  700. //the true root should return our users root folder children
  701. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  702. var result = new Dictionary<Guid, BaseItem>();
  703. AddChildren(user, includeLinkedChildren, result, includeHidden, false, null);
  704. return result.Values;
  705. }
  706. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  707. {
  708. return Children;
  709. }
  710. /// <summary>
  711. /// Adds the children to list.
  712. /// </summary>
  713. /// <param name="user">The user.</param>
  714. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  715. /// <param name="result">The result.</param>
  716. /// <param name="includeHidden">if set to <c>true</c> [include hidden].</param>
  717. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  718. /// <param name="filter">The filter.</param>
  719. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  720. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool includeHidden, bool recursive, Func<BaseItem, bool> filter)
  721. {
  722. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  723. {
  724. if (child.IsVisible(user))
  725. {
  726. if (includeHidden || !child.IsHiddenFromUser(user))
  727. {
  728. if (filter == null || filter(child))
  729. {
  730. result[child.Id] = child;
  731. }
  732. }
  733. if (recursive && child.IsFolder)
  734. {
  735. var folder = (Folder)child;
  736. folder.AddChildren(user, includeLinkedChildren, result, includeHidden, true, filter);
  737. }
  738. }
  739. }
  740. if (includeLinkedChildren)
  741. {
  742. foreach (var child in GetLinkedChildren(user))
  743. {
  744. if (child.IsVisible(user))
  745. {
  746. if (filter == null || filter(child))
  747. {
  748. result[child.Id] = child;
  749. }
  750. }
  751. }
  752. }
  753. }
  754. /// <summary>
  755. /// Gets allowed recursive children of an item
  756. /// </summary>
  757. /// <param name="user">The user.</param>
  758. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  759. /// <returns>IEnumerable{BaseItem}.</returns>
  760. /// <exception cref="System.ArgumentNullException"></exception>
  761. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  762. {
  763. return GetRecursiveChildren(user, i => true);
  764. }
  765. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
  766. {
  767. if (user == null)
  768. {
  769. throw new ArgumentNullException("user");
  770. }
  771. var result = new Dictionary<Guid, BaseItem>();
  772. AddChildren(user, true, result, false, true, filter);
  773. return result.Values;
  774. }
  775. /// <summary>
  776. /// Gets the recursive children.
  777. /// </summary>
  778. /// <returns>IList{BaseItem}.</returns>
  779. public IList<BaseItem> GetRecursiveChildren()
  780. {
  781. return GetRecursiveChildren(i => true);
  782. }
  783. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  784. {
  785. var list = new List<BaseItem>();
  786. AddChildrenToList(list, true, filter);
  787. return list;
  788. }
  789. /// <summary>
  790. /// Adds the children to list.
  791. /// </summary>
  792. /// <param name="list">The list.</param>
  793. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  794. /// <param name="filter">The filter.</param>
  795. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  796. {
  797. foreach (var child in Children)
  798. {
  799. if (filter == null || filter(child))
  800. {
  801. list.Add(child);
  802. }
  803. if (recursive && child.IsFolder)
  804. {
  805. var folder = (Folder)child;
  806. folder.AddChildrenToList(list, true, filter);
  807. }
  808. }
  809. }
  810. /// <summary>
  811. /// Gets the linked children.
  812. /// </summary>
  813. /// <returns>IEnumerable{BaseItem}.</returns>
  814. public IEnumerable<BaseItem> GetLinkedChildren()
  815. {
  816. return LinkedChildren
  817. .Select(GetLinkedChild)
  818. .Where(i => i != null);
  819. }
  820. protected virtual bool FilterLinkedChildrenPerUser
  821. {
  822. get
  823. {
  824. return false;
  825. }
  826. }
  827. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  828. {
  829. if (!FilterLinkedChildrenPerUser || user == null)
  830. {
  831. return GetLinkedChildren();
  832. }
  833. var locations = user.RootFolder
  834. .Children
  835. .OfType<CollectionFolder>()
  836. .Where(i => i.IsVisible(user))
  837. .SelectMany(i => i.PhysicalLocations)
  838. .ToList();
  839. return LinkedChildren
  840. .Select(i =>
  841. {
  842. var requiresPostFilter = true;
  843. if (!string.IsNullOrWhiteSpace(i.Path))
  844. {
  845. requiresPostFilter = false;
  846. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  847. {
  848. return null;
  849. }
  850. }
  851. var child = GetLinkedChild(i);
  852. if (requiresPostFilter && child != null)
  853. {
  854. if (string.IsNullOrWhiteSpace(child.Path))
  855. {
  856. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  857. return child;
  858. }
  859. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  860. {
  861. return null;
  862. }
  863. }
  864. return child;
  865. })
  866. .Where(i => i != null);
  867. }
  868. /// <summary>
  869. /// Gets the linked children.
  870. /// </summary>
  871. /// <returns>IEnumerable{BaseItem}.</returns>
  872. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  873. {
  874. return LinkedChildren
  875. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  876. .Where(i => i.Item2 != null);
  877. }
  878. [IgnoreDataMember]
  879. protected override bool SupportsOwnedItems
  880. {
  881. get
  882. {
  883. return base.SupportsOwnedItems || SupportsShortcutChildren;
  884. }
  885. }
  886. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  887. {
  888. var changesFound = false;
  889. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  890. {
  891. if (RefreshLinkedChildren(fileSystemChildren))
  892. {
  893. changesFound = true;
  894. }
  895. }
  896. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  897. return baseHasChanges || changesFound;
  898. }
  899. /// <summary>
  900. /// Refreshes the linked children.
  901. /// </summary>
  902. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  903. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  904. {
  905. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  906. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  907. var newShortcutLinks = fileSystemChildren
  908. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  909. .Select(i =>
  910. {
  911. try
  912. {
  913. Logger.Debug("Found shortcut at {0}", i.FullName);
  914. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  915. if (!string.IsNullOrEmpty(resolvedPath))
  916. {
  917. return new LinkedChild
  918. {
  919. Path = resolvedPath,
  920. Type = LinkedChildType.Shortcut
  921. };
  922. }
  923. Logger.Error("Error resolving shortcut {0}", i.FullName);
  924. return null;
  925. }
  926. catch (IOException ex)
  927. {
  928. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  929. return null;
  930. }
  931. })
  932. .Where(i => i != null)
  933. .ToList();
  934. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  935. {
  936. Logger.Info("Shortcut links have changed for {0}", Path);
  937. newShortcutLinks.AddRange(currentManualLinks);
  938. LinkedChildren = newShortcutLinks;
  939. return true;
  940. }
  941. foreach (var child in LinkedChildren)
  942. {
  943. // Reset the cached value
  944. child.ItemId = null;
  945. }
  946. return false;
  947. }
  948. /// <summary>
  949. /// Folders need to validate and refresh
  950. /// </summary>
  951. /// <returns>Task.</returns>
  952. public override async Task ChangedExternally()
  953. {
  954. var progress = new Progress<double>();
  955. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  956. await base.ChangedExternally().ConfigureAwait(false);
  957. }
  958. /// <summary>
  959. /// Marks the played.
  960. /// </summary>
  961. /// <param name="user">The user.</param>
  962. /// <param name="datePlayed">The date played.</param>
  963. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  964. /// <returns>Task.</returns>
  965. public override async Task MarkPlayed(User user,
  966. DateTime? datePlayed,
  967. bool resetPosition)
  968. {
  969. // Sweep through recursively and update status
  970. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  971. .Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  972. await Task.WhenAll(tasks).ConfigureAwait(false);
  973. }
  974. /// <summary>
  975. /// Marks the unplayed.
  976. /// </summary>
  977. /// <param name="user">The user.</param>
  978. /// <returns>Task.</returns>
  979. public override async Task MarkUnplayed(User user)
  980. {
  981. // Sweep through recursively and update status
  982. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  983. .Select(c => c.MarkUnplayed(user));
  984. await Task.WhenAll(tasks).ConfigureAwait(false);
  985. }
  986. /// <summary>
  987. /// Finds an item by path, recursively
  988. /// </summary>
  989. /// <param name="path">The path.</param>
  990. /// <returns>BaseItem.</returns>
  991. /// <exception cref="System.ArgumentNullException"></exception>
  992. public BaseItem FindByPath(string path)
  993. {
  994. if (string.IsNullOrEmpty(path))
  995. {
  996. throw new ArgumentNullException();
  997. }
  998. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  999. {
  1000. return this;
  1001. }
  1002. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1003. {
  1004. return this;
  1005. }
  1006. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1007. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1008. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1009. .FirstOrDefault();
  1010. }
  1011. public override bool IsPlayed(User user)
  1012. {
  1013. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1014. .All(i => i.IsPlayed(user));
  1015. }
  1016. public override bool IsUnplayed(User user)
  1017. {
  1018. return !IsPlayed(user);
  1019. }
  1020. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1021. {
  1022. var recursiveItemCount = 0;
  1023. var unplayed = 0;
  1024. double totalPercentPlayed = 0;
  1025. IEnumerable<BaseItem> children;
  1026. var folder = this;
  1027. var season = folder as Season;
  1028. if (season != null)
  1029. {
  1030. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1031. }
  1032. else
  1033. {
  1034. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1035. }
  1036. // Loop through each recursive child
  1037. foreach (var child in children)
  1038. {
  1039. recursiveItemCount++;
  1040. var isUnplayed = true;
  1041. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1042. // Incrememt totalPercentPlayed
  1043. if (itemUserData != null)
  1044. {
  1045. if (itemUserData.Played)
  1046. {
  1047. totalPercentPlayed += 100;
  1048. isUnplayed = false;
  1049. }
  1050. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1051. {
  1052. double itemPercent = itemUserData.PlaybackPositionTicks;
  1053. itemPercent /= child.RunTimeTicks.Value;
  1054. totalPercentPlayed += itemPercent;
  1055. }
  1056. }
  1057. if (isUnplayed)
  1058. {
  1059. unplayed++;
  1060. }
  1061. }
  1062. dto.UnplayedItemCount = unplayed;
  1063. if (recursiveItemCount > 0)
  1064. {
  1065. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1066. dto.Played = dto.PlayedPercentage.Value >= 100;
  1067. }
  1068. }
  1069. }
  1070. }