Folder.cs 44 KB

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