Folder.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. .GetChildren(user, true)
  835. .OfType<CollectionFolder>()
  836. .SelectMany(i => i.PhysicalLocations)
  837. .ToList();
  838. return LinkedChildren
  839. .Select(i =>
  840. {
  841. var requiresPostFilter = true;
  842. if (!string.IsNullOrWhiteSpace(i.Path))
  843. {
  844. requiresPostFilter = false;
  845. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  846. {
  847. return null;
  848. }
  849. }
  850. var child = GetLinkedChild(i);
  851. if (requiresPostFilter && child != null)
  852. {
  853. if (string.IsNullOrWhiteSpace(child.Path))
  854. {
  855. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  856. return child;
  857. }
  858. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  859. {
  860. return null;
  861. }
  862. }
  863. return child;
  864. })
  865. .Where(i => i != null);
  866. }
  867. /// <summary>
  868. /// Gets the linked children.
  869. /// </summary>
  870. /// <returns>IEnumerable{BaseItem}.</returns>
  871. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  872. {
  873. return LinkedChildren
  874. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  875. .Where(i => i.Item2 != null);
  876. }
  877. [IgnoreDataMember]
  878. protected override bool SupportsOwnedItems
  879. {
  880. get
  881. {
  882. return base.SupportsOwnedItems || SupportsShortcutChildren;
  883. }
  884. }
  885. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  886. {
  887. var changesFound = false;
  888. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  889. {
  890. if (RefreshLinkedChildren(fileSystemChildren))
  891. {
  892. changesFound = true;
  893. }
  894. }
  895. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  896. return baseHasChanges || changesFound;
  897. }
  898. /// <summary>
  899. /// Refreshes the linked children.
  900. /// </summary>
  901. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  902. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  903. {
  904. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  905. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  906. var newShortcutLinks = fileSystemChildren
  907. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  908. .Select(i =>
  909. {
  910. try
  911. {
  912. Logger.Debug("Found shortcut at {0}", i.FullName);
  913. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  914. if (!string.IsNullOrEmpty(resolvedPath))
  915. {
  916. return new LinkedChild
  917. {
  918. Path = resolvedPath,
  919. Type = LinkedChildType.Shortcut
  920. };
  921. }
  922. Logger.Error("Error resolving shortcut {0}", i.FullName);
  923. return null;
  924. }
  925. catch (IOException ex)
  926. {
  927. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  928. return null;
  929. }
  930. })
  931. .Where(i => i != null)
  932. .ToList();
  933. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  934. {
  935. Logger.Info("Shortcut links have changed for {0}", Path);
  936. newShortcutLinks.AddRange(currentManualLinks);
  937. LinkedChildren = newShortcutLinks;
  938. return true;
  939. }
  940. foreach (var child in LinkedChildren)
  941. {
  942. // Reset the cached value
  943. child.ItemId = null;
  944. }
  945. return false;
  946. }
  947. /// <summary>
  948. /// Folders need to validate and refresh
  949. /// </summary>
  950. /// <returns>Task.</returns>
  951. public override async Task ChangedExternally()
  952. {
  953. var progress = new Progress<double>();
  954. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  955. await base.ChangedExternally().ConfigureAwait(false);
  956. }
  957. /// <summary>
  958. /// Marks the played.
  959. /// </summary>
  960. /// <param name="user">The user.</param>
  961. /// <param name="datePlayed">The date played.</param>
  962. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  963. /// <returns>Task.</returns>
  964. public override async Task MarkPlayed(User user,
  965. DateTime? datePlayed,
  966. bool resetPosition)
  967. {
  968. // Sweep through recursively and update status
  969. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  970. .Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  971. await Task.WhenAll(tasks).ConfigureAwait(false);
  972. }
  973. /// <summary>
  974. /// Marks the unplayed.
  975. /// </summary>
  976. /// <param name="user">The user.</param>
  977. /// <returns>Task.</returns>
  978. public override async Task MarkUnplayed(User user)
  979. {
  980. // Sweep through recursively and update status
  981. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  982. .Select(c => c.MarkUnplayed(user));
  983. await Task.WhenAll(tasks).ConfigureAwait(false);
  984. }
  985. /// <summary>
  986. /// Finds an item by path, recursively
  987. /// </summary>
  988. /// <param name="path">The path.</param>
  989. /// <returns>BaseItem.</returns>
  990. /// <exception cref="System.ArgumentNullException"></exception>
  991. public BaseItem FindByPath(string path)
  992. {
  993. if (string.IsNullOrEmpty(path))
  994. {
  995. throw new ArgumentNullException();
  996. }
  997. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  998. {
  999. return this;
  1000. }
  1001. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1002. {
  1003. return this;
  1004. }
  1005. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1006. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1007. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1008. .FirstOrDefault();
  1009. }
  1010. public override bool IsPlayed(User user)
  1011. {
  1012. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1013. .All(i => i.IsPlayed(user));
  1014. }
  1015. public override bool IsUnplayed(User user)
  1016. {
  1017. return !IsPlayed(user);
  1018. }
  1019. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1020. {
  1021. var recursiveItemCount = 0;
  1022. var unplayed = 0;
  1023. double totalPercentPlayed = 0;
  1024. IEnumerable<BaseItem> children;
  1025. var folder = this;
  1026. var season = folder as Season;
  1027. if (season != null)
  1028. {
  1029. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1030. }
  1031. else
  1032. {
  1033. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1034. }
  1035. // Loop through each recursive child
  1036. foreach (var child in children)
  1037. {
  1038. recursiveItemCount++;
  1039. var isUnplayed = true;
  1040. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1041. // Incrememt totalPercentPlayed
  1042. if (itemUserData != null)
  1043. {
  1044. if (itemUserData.Played)
  1045. {
  1046. totalPercentPlayed += 100;
  1047. isUnplayed = false;
  1048. }
  1049. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1050. {
  1051. double itemPercent = itemUserData.PlaybackPositionTicks;
  1052. itemPercent /= child.RunTimeTicks.Value;
  1053. totalPercentPlayed += itemPercent;
  1054. }
  1055. }
  1056. if (isUnplayed)
  1057. {
  1058. unplayed++;
  1059. }
  1060. }
  1061. dto.UnplayedItemCount = unplayed;
  1062. if (recursiveItemCount > 0)
  1063. {
  1064. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1065. dto.Played = dto.PlayedPercentage.Value >= 100;
  1066. }
  1067. }
  1068. }
  1069. }