Folder.cs 45 KB

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