Folder.cs 45 KB

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