Folder.cs 45 KB

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