Folder.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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 false; }
  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 ConfigurationManager.Configuration.EnableWindowsShortcuts; }
  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(FileSystem)));
  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. await UpdateIsOffline(currentChild, false).ConfigureAwait(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. await UpdateIsOffline(item, true).ConfigureAwait(false);
  442. validChildren.Add(item);
  443. }
  444. else
  445. {
  446. await UpdateIsOffline(item, false).ConfigureAwait(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 Task UpdateIsOffline(BaseItem item, bool newValue)
  487. {
  488. if (item.IsOffline != newValue)
  489. {
  490. item.IsOffline = newValue;
  491. return item.UpdateToRepository(ItemUpdateType.None, CancellationToken.None);
  492. }
  493. return Task.FromResult(true);
  494. }
  495. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  496. {
  497. var children = ActualChildren.ToList();
  498. var percentages = new Dictionary<Guid, double>(children.Count);
  499. var numComplete = 0;
  500. var count = children.Count;
  501. foreach (var child in children)
  502. {
  503. cancellationToken.ThrowIfCancellationRequested();
  504. if (child.IsFolder)
  505. {
  506. var innerProgress = new ActionableProgress<double>();
  507. // Avoid implicitly captured closure
  508. var currentChild = child;
  509. innerProgress.RegisterAction(p =>
  510. {
  511. lock (percentages)
  512. {
  513. percentages[currentChild.Id] = p / 100;
  514. var innerPercent = percentages.Values.Sum();
  515. innerPercent /= count;
  516. innerPercent *= 100;
  517. progress.Report(innerPercent);
  518. }
  519. });
  520. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  521. .ConfigureAwait(false);
  522. }
  523. else
  524. {
  525. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  526. .ConfigureAwait(false);
  527. }
  528. numComplete++;
  529. double percent = numComplete;
  530. percent /= count;
  531. percent *= 100;
  532. progress.Report(percent);
  533. }
  534. progress.Report(100);
  535. }
  536. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  537. {
  538. var container = child as IMetadataContainer;
  539. if (container != null)
  540. {
  541. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  542. }
  543. else
  544. {
  545. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  546. if (recursive)
  547. {
  548. var folder = child as Folder;
  549. if (folder != null)
  550. {
  551. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  552. }
  553. }
  554. }
  555. progress.Report(100);
  556. }
  557. /// <summary>
  558. /// Refreshes the children.
  559. /// </summary>
  560. /// <param name="children">The children.</param>
  561. /// <param name="directoryService">The directory service.</param>
  562. /// <param name="progress">The progress.</param>
  563. /// <param name="cancellationToken">The cancellation token.</param>
  564. /// <returns>Task.</returns>
  565. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  566. {
  567. var list = children;
  568. var childCount = list.Count;
  569. var percentages = new Dictionary<Guid, double>(list.Count);
  570. foreach (var item in list)
  571. {
  572. cancellationToken.ThrowIfCancellationRequested();
  573. var child = item;
  574. var innerProgress = new ActionableProgress<double>();
  575. innerProgress.RegisterAction(p =>
  576. {
  577. lock (percentages)
  578. {
  579. percentages[child.Id] = p / 100;
  580. var percent = percentages.Values.Sum();
  581. percent /= childCount;
  582. progress.Report((10 * percent) + 10);
  583. }
  584. });
  585. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  586. .ConfigureAwait(false);
  587. }
  588. }
  589. /// <summary>
  590. /// Determines whether the specified path is offline.
  591. /// </summary>
  592. /// <param name="path">The path.</param>
  593. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  594. private bool IsPathOffline(string path)
  595. {
  596. if (FileSystem.FileExists(path))
  597. {
  598. return false;
  599. }
  600. var originalPath = path;
  601. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  602. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  603. {
  604. if (FileSystem.DirectoryExists(path))
  605. {
  606. return false;
  607. }
  608. path = System.IO.Path.GetDirectoryName(path);
  609. }
  610. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  611. {
  612. return true;
  613. }
  614. return ContainsPath(LibraryManager.GetVirtualFolders(), originalPath);
  615. }
  616. /// <summary>
  617. /// Determines whether the specified folders contains path.
  618. /// </summary>
  619. /// <param name="folders">The folders.</param>
  620. /// <param name="path">The path.</param>
  621. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  622. private bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  623. {
  624. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  625. }
  626. private bool ContainsPath(string parent, string path)
  627. {
  628. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  629. }
  630. /// <summary>
  631. /// Get the children of this folder from the actual file system
  632. /// </summary>
  633. /// <returns>IEnumerable{BaseItem}.</returns>
  634. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  635. {
  636. var collectionType = LibraryManager.GetContentType(this);
  637. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  638. }
  639. /// <summary>
  640. /// Get our children from the repo - stubbed for now
  641. /// </summary>
  642. /// <returns>IEnumerable{BaseItem}.</returns>
  643. protected IEnumerable<BaseItem> GetCachedChildren()
  644. {
  645. var childrenItems = ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null);
  646. //var children = ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null).ToList();
  647. //if (children.Count != childrenItems.Count)
  648. //{
  649. // var b = this;
  650. //}
  651. return childrenItems;
  652. }
  653. private BaseItem RetrieveChild(BaseItem child)
  654. {
  655. if (child.Id == Guid.Empty)
  656. {
  657. Logger.Error("Item found with empty Id: " + (child.Path ?? child.Name));
  658. return null;
  659. }
  660. var item = LibraryManager.GetMemoryItemById(child.Id);
  661. if (item != null)
  662. {
  663. if (item is IByReferenceItem)
  664. {
  665. return LibraryManager.GetOrAddByReferenceItem(item);
  666. }
  667. item.SetParent(this);
  668. }
  669. else
  670. {
  671. child.SetParent(this);
  672. LibraryManager.RegisterItem(child);
  673. item = child;
  674. }
  675. return item;
  676. }
  677. public virtual Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  678. {
  679. var user = query.User;
  680. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  681. IEnumerable<BaseItem> items;
  682. if (query.User == null)
  683. {
  684. items = query.Recursive
  685. ? GetRecursiveChildren(filter)
  686. : Children.Where(filter);
  687. }
  688. else
  689. {
  690. items = query.Recursive
  691. ? GetRecursiveChildren(user, filter)
  692. : GetChildren(user, true).Where(filter);
  693. }
  694. var result = PostFilterAndSort(items, query);
  695. return Task.FromResult(result);
  696. }
  697. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  698. {
  699. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager);
  700. }
  701. /// <summary>
  702. /// Gets allowed children of an item
  703. /// </summary>
  704. /// <param name="user">The user.</param>
  705. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  706. /// <returns>IEnumerable{BaseItem}.</returns>
  707. /// <exception cref="System.ArgumentNullException"></exception>
  708. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  709. {
  710. return GetChildren(user, includeLinkedChildren, false);
  711. }
  712. internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
  713. {
  714. if (user == null)
  715. {
  716. throw new ArgumentNullException();
  717. }
  718. //the true root should return our users root folder children
  719. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  720. var result = new Dictionary<Guid, BaseItem>();
  721. AddChildren(user, includeLinkedChildren, result, includeHidden, false, null);
  722. return result.Values;
  723. }
  724. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  725. {
  726. return Children;
  727. }
  728. /// <summary>
  729. /// Adds the children to list.
  730. /// </summary>
  731. /// <param name="user">The user.</param>
  732. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  733. /// <param name="result">The result.</param>
  734. /// <param name="includeHidden">if set to <c>true</c> [include hidden].</param>
  735. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  736. /// <param name="filter">The filter.</param>
  737. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  738. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool includeHidden, bool recursive, Func<BaseItem, bool> filter)
  739. {
  740. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  741. {
  742. if (child.IsVisible(user))
  743. {
  744. if (includeHidden || !child.IsHiddenFromUser(user))
  745. {
  746. if (filter == null || filter(child))
  747. {
  748. result[child.Id] = child;
  749. }
  750. }
  751. if (recursive && child.IsFolder)
  752. {
  753. var folder = (Folder)child;
  754. folder.AddChildren(user, includeLinkedChildren, result, includeHidden, true, filter);
  755. }
  756. }
  757. }
  758. if (includeLinkedChildren)
  759. {
  760. foreach (var child in GetLinkedChildren(user))
  761. {
  762. if (child.IsVisible(user))
  763. {
  764. if (filter == null || filter(child))
  765. {
  766. result[child.Id] = child;
  767. }
  768. }
  769. }
  770. }
  771. }
  772. /// <summary>
  773. /// Gets allowed recursive children of an item
  774. /// </summary>
  775. /// <param name="user">The user.</param>
  776. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  777. /// <returns>IEnumerable{BaseItem}.</returns>
  778. /// <exception cref="System.ArgumentNullException"></exception>
  779. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  780. {
  781. return GetRecursiveChildren(user, i => true);
  782. }
  783. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
  784. {
  785. if (user == null)
  786. {
  787. throw new ArgumentNullException("user");
  788. }
  789. var result = new Dictionary<Guid, BaseItem>();
  790. AddChildren(user, true, result, false, true, filter);
  791. return result.Values;
  792. }
  793. /// <summary>
  794. /// Gets the recursive children.
  795. /// </summary>
  796. /// <returns>IList{BaseItem}.</returns>
  797. public IList<BaseItem> GetRecursiveChildren()
  798. {
  799. return GetRecursiveChildren(i => true);
  800. }
  801. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  802. {
  803. var list = new List<BaseItem>();
  804. AddChildrenToList(list, true, filter);
  805. return list;
  806. }
  807. /// <summary>
  808. /// Adds the children to list.
  809. /// </summary>
  810. /// <param name="list">The list.</param>
  811. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  812. /// <param name="filter">The filter.</param>
  813. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  814. {
  815. foreach (var child in Children)
  816. {
  817. if (filter == null || filter(child))
  818. {
  819. list.Add(child);
  820. }
  821. if (recursive && child.IsFolder)
  822. {
  823. var folder = (Folder)child;
  824. folder.AddChildrenToList(list, true, filter);
  825. }
  826. }
  827. }
  828. /// <summary>
  829. /// Gets the linked children.
  830. /// </summary>
  831. /// <returns>IEnumerable{BaseItem}.</returns>
  832. public IEnumerable<BaseItem> GetLinkedChildren()
  833. {
  834. return LinkedChildren
  835. .Select(GetLinkedChild)
  836. .Where(i => i != null);
  837. }
  838. protected virtual bool FilterLinkedChildrenPerUser
  839. {
  840. get
  841. {
  842. return false;
  843. }
  844. }
  845. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  846. {
  847. if (!FilterLinkedChildrenPerUser || user == null)
  848. {
  849. return GetLinkedChildren();
  850. }
  851. var locations = user.RootFolder
  852. .Children
  853. .OfType<CollectionFolder>()
  854. .Where(i => i.IsVisible(user))
  855. .SelectMany(i => i.PhysicalLocations)
  856. .ToList();
  857. return LinkedChildren
  858. .Select(i =>
  859. {
  860. var requiresPostFilter = true;
  861. if (!string.IsNullOrWhiteSpace(i.Path))
  862. {
  863. requiresPostFilter = false;
  864. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  865. {
  866. return null;
  867. }
  868. }
  869. var child = GetLinkedChild(i);
  870. if (requiresPostFilter && child != null)
  871. {
  872. if (string.IsNullOrWhiteSpace(child.Path))
  873. {
  874. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  875. return child;
  876. }
  877. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  878. {
  879. return null;
  880. }
  881. }
  882. return child;
  883. })
  884. .Where(i => i != null);
  885. }
  886. /// <summary>
  887. /// Gets the linked children.
  888. /// </summary>
  889. /// <returns>IEnumerable{BaseItem}.</returns>
  890. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  891. {
  892. return LinkedChildren
  893. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  894. .Where(i => i.Item2 != null);
  895. }
  896. [IgnoreDataMember]
  897. protected override bool SupportsOwnedItems
  898. {
  899. get
  900. {
  901. return base.SupportsOwnedItems || SupportsShortcutChildren;
  902. }
  903. }
  904. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  905. {
  906. var changesFound = false;
  907. if (LocationType == LocationType.FileSystem)
  908. {
  909. if (RefreshLinkedChildren(fileSystemChildren))
  910. {
  911. changesFound = true;
  912. }
  913. }
  914. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  915. return baseHasChanges || changesFound;
  916. }
  917. /// <summary>
  918. /// Refreshes the linked children.
  919. /// </summary>
  920. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  921. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  922. {
  923. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  924. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  925. List<LinkedChild> newShortcutLinks;
  926. if (SupportsShortcutChildren)
  927. {
  928. newShortcutLinks = fileSystemChildren
  929. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  930. .Select(i =>
  931. {
  932. try
  933. {
  934. Logger.Debug("Found shortcut at {0}", i.FullName);
  935. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  936. if (!string.IsNullOrEmpty(resolvedPath))
  937. {
  938. return new LinkedChild
  939. {
  940. Path = resolvedPath,
  941. Type = LinkedChildType.Shortcut
  942. };
  943. }
  944. Logger.Error("Error resolving shortcut {0}", i.FullName);
  945. return null;
  946. }
  947. catch (IOException ex)
  948. {
  949. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  950. return null;
  951. }
  952. })
  953. .Where(i => i != null)
  954. .ToList();
  955. }
  956. else { newShortcutLinks = new List<LinkedChild>(); }
  957. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  958. {
  959. Logger.Info("Shortcut links have changed for {0}", Path);
  960. newShortcutLinks.AddRange(currentManualLinks);
  961. LinkedChildren = newShortcutLinks;
  962. return true;
  963. }
  964. foreach (var child in LinkedChildren)
  965. {
  966. // Reset the cached value
  967. child.ItemId = null;
  968. }
  969. return false;
  970. }
  971. /// <summary>
  972. /// Folders need to validate and refresh
  973. /// </summary>
  974. /// <returns>Task.</returns>
  975. public override async Task ChangedExternally()
  976. {
  977. var progress = new Progress<double>();
  978. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  979. await base.ChangedExternally().ConfigureAwait(false);
  980. }
  981. /// <summary>
  982. /// Marks the played.
  983. /// </summary>
  984. /// <param name="user">The user.</param>
  985. /// <param name="datePlayed">The date played.</param>
  986. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  987. /// <returns>Task.</returns>
  988. public override async Task MarkPlayed(User user,
  989. DateTime? datePlayed,
  990. bool resetPosition)
  991. {
  992. // Sweep through recursively and update status
  993. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  994. .Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  995. await Task.WhenAll(tasks).ConfigureAwait(false);
  996. }
  997. /// <summary>
  998. /// Marks the unplayed.
  999. /// </summary>
  1000. /// <param name="user">The user.</param>
  1001. /// <returns>Task.</returns>
  1002. public override async Task MarkUnplayed(User user)
  1003. {
  1004. // Sweep through recursively and update status
  1005. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1006. .Select(c => c.MarkUnplayed(user));
  1007. await Task.WhenAll(tasks).ConfigureAwait(false);
  1008. }
  1009. /// <summary>
  1010. /// Finds an item by path, recursively
  1011. /// </summary>
  1012. /// <param name="path">The path.</param>
  1013. /// <returns>BaseItem.</returns>
  1014. /// <exception cref="System.ArgumentNullException"></exception>
  1015. public BaseItem FindByPath(string path)
  1016. {
  1017. if (string.IsNullOrEmpty(path))
  1018. {
  1019. throw new ArgumentNullException();
  1020. }
  1021. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  1022. {
  1023. return this;
  1024. }
  1025. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1026. {
  1027. return this;
  1028. }
  1029. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1030. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1031. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1032. .FirstOrDefault();
  1033. }
  1034. public override bool IsPlayed(User user)
  1035. {
  1036. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1037. .All(i => i.IsPlayed(user));
  1038. }
  1039. public override bool IsUnplayed(User user)
  1040. {
  1041. return !IsPlayed(user);
  1042. }
  1043. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1044. {
  1045. var recursiveItemCount = 0;
  1046. var unplayed = 0;
  1047. double totalPercentPlayed = 0;
  1048. IEnumerable<BaseItem> children;
  1049. var folder = this;
  1050. var season = folder as Season;
  1051. if (season != null)
  1052. {
  1053. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1054. }
  1055. else
  1056. {
  1057. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1058. }
  1059. // Loop through each recursive child
  1060. foreach (var child in children)
  1061. {
  1062. recursiveItemCount++;
  1063. var isUnplayed = true;
  1064. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1065. // Incrememt totalPercentPlayed
  1066. if (itemUserData != null)
  1067. {
  1068. if (itemUserData.Played)
  1069. {
  1070. totalPercentPlayed += 100;
  1071. isUnplayed = false;
  1072. }
  1073. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1074. {
  1075. double itemPercent = itemUserData.PlaybackPositionTicks;
  1076. itemPercent /= child.RunTimeTicks.Value;
  1077. totalPercentPlayed += itemPercent;
  1078. }
  1079. }
  1080. if (isUnplayed)
  1081. {
  1082. unplayed++;
  1083. }
  1084. }
  1085. dto.UnplayedItemCount = unplayed;
  1086. if (recursiveItemCount > 0)
  1087. {
  1088. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1089. dto.Played = dto.PlayedPercentage.Value >= 100;
  1090. }
  1091. }
  1092. }
  1093. }