Folder.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 MoreLinq;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Runtime.Serialization;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Controller.Entities
  19. {
  20. /// <summary>
  21. /// Class Folder
  22. /// </summary>
  23. public class Folder : BaseItem, IHasThemeMedia, IHasTags
  24. {
  25. public static IUserManager UserManager { get; set; }
  26. public List<Guid> ThemeSongIds { get; set; }
  27. public List<Guid> ThemeVideoIds { get; set; }
  28. public List<string> Tags { get; set; }
  29. public Folder()
  30. {
  31. LinkedChildren = new List<LinkedChild>();
  32. ThemeSongIds = new List<Guid>();
  33. ThemeVideoIds = new List<Guid>();
  34. Tags = new List<string>();
  35. }
  36. [IgnoreDataMember]
  37. public virtual bool IsPreSorted
  38. {
  39. get { return false; }
  40. }
  41. /// <summary>
  42. /// Gets a value indicating whether this instance is folder.
  43. /// </summary>
  44. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  45. [IgnoreDataMember]
  46. public override bool IsFolder
  47. {
  48. get
  49. {
  50. return true;
  51. }
  52. }
  53. /// <summary>
  54. /// Gets or sets a value indicating whether this instance is physical root.
  55. /// </summary>
  56. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  57. public bool IsPhysicalRoot { get; set; }
  58. /// <summary>
  59. /// Gets or sets a value indicating whether this instance is root.
  60. /// </summary>
  61. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  62. public bool IsRoot { get; set; }
  63. /// <summary>
  64. /// Gets a value indicating whether this instance is virtual folder.
  65. /// </summary>
  66. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  67. [IgnoreDataMember]
  68. public virtual bool IsVirtualFolder
  69. {
  70. get
  71. {
  72. return false;
  73. }
  74. }
  75. public virtual List<LinkedChild> LinkedChildren { get; set; }
  76. protected virtual bool SupportsShortcutChildren
  77. {
  78. get { return true; }
  79. }
  80. /// <summary>
  81. /// Adds the child.
  82. /// </summary>
  83. /// <param name="item">The item.</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task.</returns>
  86. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  87. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  88. {
  89. item.Parent = this;
  90. if (item.Id == Guid.Empty)
  91. {
  92. item.Id = item.Path.GetMBId(item.GetType());
  93. }
  94. if (ActualChildren.Any(i => i.Id == item.Id))
  95. {
  96. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  97. }
  98. if (item.DateCreated == DateTime.MinValue)
  99. {
  100. item.DateCreated = DateTime.UtcNow;
  101. }
  102. if (item.DateModified == DateTime.MinValue)
  103. {
  104. item.DateModified = DateTime.UtcNow;
  105. }
  106. AddChildInternal(item);
  107. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  108. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  109. }
  110. protected void AddChildrenInternal(IEnumerable<BaseItem> children)
  111. {
  112. lock (_childrenSyncLock)
  113. {
  114. var newChildren = ActualChildren.ToList();
  115. newChildren.AddRange(children);
  116. _children = newChildren;
  117. }
  118. }
  119. protected void AddChildInternal(BaseItem child)
  120. {
  121. lock (_childrenSyncLock)
  122. {
  123. var newChildren = ActualChildren.ToList();
  124. newChildren.Add(child);
  125. _children = newChildren;
  126. }
  127. }
  128. protected void RemoveChildrenInternal(IEnumerable<BaseItem> children)
  129. {
  130. var ids = children.Select(i => i.Id).ToList();
  131. lock (_childrenSyncLock)
  132. {
  133. _children = ActualChildren.Where(i => !ids.Contains(i.Id)).ToList();
  134. }
  135. }
  136. protected void ClearChildrenInternal()
  137. {
  138. lock (_childrenSyncLock)
  139. {
  140. _children = new List<BaseItem>();
  141. }
  142. }
  143. /// <summary>
  144. /// Never want folders to be blocked by "BlockNotRated"
  145. /// </summary>
  146. [IgnoreDataMember]
  147. public override string OfficialRatingForComparison
  148. {
  149. get
  150. {
  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());
  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. metadataRefreshOptions.DirectoryService = metadataRefreshOptions.DirectoryService ?? new DirectoryService(Logger);
  291. return ValidateChildrenWithCancellationSupport(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  292. }
  293. private Task ValidateChildrenWithCancellationSupport(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  294. {
  295. return ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService);
  296. }
  297. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  298. {
  299. var dictionary = new Dictionary<Guid, BaseItem>();
  300. foreach (var child in ActualChildren)
  301. {
  302. var id = child.Id;
  303. if (dictionary.ContainsKey(id))
  304. {
  305. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  306. Path ?? Name,
  307. child.Path ?? child.Name);
  308. }
  309. else
  310. {
  311. dictionary[id] = child;
  312. }
  313. }
  314. return dictionary;
  315. }
  316. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  317. {
  318. var currentAsVideo = current as Video;
  319. if (currentAsVideo != null)
  320. {
  321. var newAsVideo = newItem as Video;
  322. if (newAsVideo != null)
  323. {
  324. if (currentAsVideo.IsPlaceHolder != newAsVideo.IsPlaceHolder)
  325. {
  326. return false;
  327. }
  328. if (currentAsVideo.IsMultiPart != newAsVideo.IsMultiPart)
  329. {
  330. return false;
  331. }
  332. if (currentAsVideo.HasLocalAlternateVersions != newAsVideo.HasLocalAlternateVersions)
  333. {
  334. return false;
  335. }
  336. }
  337. }
  338. else
  339. {
  340. var currentAsPlaceHolder = current as ISupportsPlaceHolders;
  341. if (currentAsPlaceHolder != null)
  342. {
  343. var newHasPlaceHolder = newItem as ISupportsPlaceHolders;
  344. if (newHasPlaceHolder != null)
  345. {
  346. if (currentAsPlaceHolder.IsPlaceHolder != newHasPlaceHolder.IsPlaceHolder)
  347. {
  348. return false;
  349. }
  350. }
  351. }
  352. }
  353. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  354. }
  355. /// <summary>
  356. /// Validates the children internal.
  357. /// </summary>
  358. /// <param name="progress">The progress.</param>
  359. /// <param name="cancellationToken">The cancellation token.</param>
  360. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  361. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  362. /// <param name="refreshOptions">The refresh options.</param>
  363. /// <param name="directoryService">The directory service.</param>
  364. /// <returns>Task.</returns>
  365. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  366. {
  367. var locationType = LocationType;
  368. cancellationToken.ThrowIfCancellationRequested();
  369. var validChildren = new List<BaseItem>();
  370. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  371. {
  372. IEnumerable<BaseItem> nonCachedChildren;
  373. try
  374. {
  375. nonCachedChildren = GetNonCachedChildren(directoryService);
  376. }
  377. catch (IOException ex)
  378. {
  379. nonCachedChildren = new BaseItem[] { };
  380. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  381. }
  382. if (nonCachedChildren == null) return; //nothing to validate
  383. progress.Report(5);
  384. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  385. var currentChildren = GetActualChildrenDictionary();
  386. //create a list for our validated children
  387. var newItems = new List<BaseItem>();
  388. cancellationToken.ThrowIfCancellationRequested();
  389. foreach (var child in nonCachedChildren)
  390. {
  391. BaseItem currentChild;
  392. if (currentChildren.TryGetValue(child.Id, out currentChild))
  393. {
  394. if (IsValidFromResolver(currentChild, child))
  395. {
  396. var currentChildLocationType = currentChild.LocationType;
  397. if (currentChildLocationType != LocationType.Remote &&
  398. currentChildLocationType != LocationType.Virtual)
  399. {
  400. currentChild.DateModified = child.DateModified;
  401. }
  402. currentChild.IsOffline = false;
  403. validChildren.Add(currentChild);
  404. }
  405. else
  406. {
  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. return LibraryManager.ResolvePaths<BaseItem>(GetFileSystemChildren(directoryService), directoryService, this);
  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. return ItemRepository.GetChildren(Id).Select(RetrieveChild).Where(i => i != null);
  629. }
  630. /// <summary>
  631. /// Retrieves the child.
  632. /// </summary>
  633. /// <param name="child">The child.</param>
  634. /// <returns>BaseItem.</returns>
  635. private BaseItem RetrieveChild(Guid child)
  636. {
  637. var item = LibraryManager.GetItemById(child);
  638. if (item != null)
  639. {
  640. if (item is IByReferenceItem)
  641. {
  642. return LibraryManager.GetOrAddByReferenceItem(item);
  643. }
  644. item.Parent = this;
  645. }
  646. return item;
  647. }
  648. /// <summary>
  649. /// Gets allowed children of an item
  650. /// </summary>
  651. /// <param name="user">The user.</param>
  652. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  653. /// <returns>IEnumerable{BaseItem}.</returns>
  654. /// <exception cref="System.ArgumentNullException"></exception>
  655. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  656. {
  657. return GetChildren(user, includeLinkedChildren, false);
  658. }
  659. internal IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren, bool includeHidden)
  660. {
  661. if (user == null)
  662. {
  663. throw new ArgumentNullException();
  664. }
  665. //the true root should return our users root folder children
  666. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  667. var list = new List<BaseItem>();
  668. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, includeHidden, false);
  669. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  670. }
  671. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  672. {
  673. return Children;
  674. }
  675. /// <summary>
  676. /// Adds the children to list.
  677. /// </summary>
  678. /// <param name="user">The user.</param>
  679. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  680. /// <param name="list">The list.</param>
  681. /// <param name="includeHidden">if set to <c>true</c> [include hidden].</param>
  682. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  683. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  684. private bool AddChildrenToList(User user, bool includeLinkedChildren, List<BaseItem> list, bool includeHidden, bool recursive)
  685. {
  686. var hasLinkedChildren = false;
  687. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  688. {
  689. if (child.IsVisible(user))
  690. {
  691. if (includeHidden || !child.IsHiddenFromUser(user))
  692. {
  693. list.Add(child);
  694. }
  695. if (recursive && child.IsFolder)
  696. {
  697. var folder = (Folder)child;
  698. if (folder.AddChildrenToList(user, includeLinkedChildren, list, includeHidden, true))
  699. {
  700. hasLinkedChildren = true;
  701. }
  702. }
  703. }
  704. }
  705. if (includeLinkedChildren)
  706. {
  707. foreach (var child in GetLinkedChildren())
  708. {
  709. if (child.IsVisible(user))
  710. {
  711. hasLinkedChildren = true;
  712. list.Add(child);
  713. }
  714. }
  715. }
  716. return hasLinkedChildren;
  717. }
  718. /// <summary>
  719. /// Gets allowed recursive children of an item
  720. /// </summary>
  721. /// <param name="user">The user.</param>
  722. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  723. /// <returns>IEnumerable{BaseItem}.</returns>
  724. /// <exception cref="System.ArgumentNullException"></exception>
  725. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  726. {
  727. if (user == null)
  728. {
  729. throw new ArgumentNullException("user");
  730. }
  731. var list = new List<BaseItem>();
  732. var hasLinkedChildren = AddChildrenToList(user, includeLinkedChildren, list, false, true);
  733. return hasLinkedChildren ? list.DistinctBy(i => i.Id).ToList() : list;
  734. }
  735. /// <summary>
  736. /// Gets the recursive children.
  737. /// </summary>
  738. /// <returns>IList{BaseItem}.</returns>
  739. public IList<BaseItem> GetRecursiveChildren()
  740. {
  741. var list = new List<BaseItem>();
  742. AddChildrenToList(list, true, null);
  743. return list;
  744. }
  745. /// <summary>
  746. /// Adds the children to list.
  747. /// </summary>
  748. /// <param name="list">The list.</param>
  749. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  750. /// <param name="filter">The filter.</param>
  751. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  752. {
  753. foreach (var child in Children)
  754. {
  755. if (filter == null || filter(child))
  756. {
  757. list.Add(child);
  758. }
  759. if (recursive && child.IsFolder)
  760. {
  761. var folder = (Folder)child;
  762. folder.AddChildrenToList(list, true, filter);
  763. }
  764. }
  765. }
  766. /// <summary>
  767. /// Gets the linked children.
  768. /// </summary>
  769. /// <returns>IEnumerable{BaseItem}.</returns>
  770. public IEnumerable<BaseItem> GetLinkedChildren()
  771. {
  772. return LinkedChildren
  773. .Select(GetLinkedChild)
  774. .Where(i => i != null);
  775. }
  776. /// <summary>
  777. /// Gets the linked children.
  778. /// </summary>
  779. /// <returns>IEnumerable{BaseItem}.</returns>
  780. public IEnumerable<Tuple<LinkedChild,BaseItem>> GetLinkedChildrenInfos()
  781. {
  782. return LinkedChildren
  783. .Select(i => new Tuple<LinkedChild,BaseItem>(i, GetLinkedChild(i)))
  784. .Where(i => i.Item2 != null);
  785. }
  786. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  787. {
  788. var changesFound = false;
  789. if (SupportsShortcutChildren && LocationType == LocationType.FileSystem)
  790. {
  791. if (RefreshLinkedChildren(fileSystemChildren))
  792. {
  793. changesFound = true;
  794. }
  795. }
  796. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  797. return baseHasChanges || changesFound;
  798. }
  799. /// <summary>
  800. /// Refreshes the linked children.
  801. /// </summary>
  802. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  803. private bool RefreshLinkedChildren(IEnumerable<FileSystemInfo> fileSystemChildren)
  804. {
  805. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  806. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  807. var newShortcutLinks = fileSystemChildren
  808. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  809. .Select(i =>
  810. {
  811. try
  812. {
  813. Logger.Debug("Found shortcut at {0}", i.FullName);
  814. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  815. if (!string.IsNullOrEmpty(resolvedPath))
  816. {
  817. return new LinkedChild
  818. {
  819. Path = resolvedPath,
  820. Type = LinkedChildType.Shortcut
  821. };
  822. }
  823. Logger.Error("Error resolving shortcut {0}", i.FullName);
  824. return null;
  825. }
  826. catch (IOException ex)
  827. {
  828. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  829. return null;
  830. }
  831. })
  832. .Where(i => i != null)
  833. .ToList();
  834. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  835. {
  836. Logger.Info("Shortcut links have changed for {0}", Path);
  837. newShortcutLinks.AddRange(currentManualLinks);
  838. LinkedChildren = newShortcutLinks;
  839. return true;
  840. }
  841. foreach (var child in LinkedChildren)
  842. {
  843. // Reset the cached value
  844. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  845. {
  846. child.ItemId = null;
  847. }
  848. }
  849. return false;
  850. }
  851. /// <summary>
  852. /// Folders need to validate and refresh
  853. /// </summary>
  854. /// <returns>Task.</returns>
  855. public override async Task ChangedExternally()
  856. {
  857. var progress = new Progress<double>();
  858. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  859. await base.ChangedExternally().ConfigureAwait(false);
  860. }
  861. /// <summary>
  862. /// Marks the played.
  863. /// </summary>
  864. /// <param name="user">The user.</param>
  865. /// <param name="datePlayed">The date played.</param>
  866. /// <param name="userManager">The user manager.</param>
  867. /// <returns>Task.</returns>
  868. public override async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  869. {
  870. // Sweep through recursively and update status
  871. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkPlayed(user, datePlayed, userManager));
  872. await Task.WhenAll(tasks).ConfigureAwait(false);
  873. }
  874. /// <summary>
  875. /// Marks the unplayed.
  876. /// </summary>
  877. /// <param name="user">The user.</param>
  878. /// <param name="userManager">The user manager.</param>
  879. /// <returns>Task.</returns>
  880. public override async Task MarkUnplayed(User user, IUserDataManager userManager)
  881. {
  882. // Sweep through recursively and update status
  883. var tasks = GetRecursiveChildren(user, true).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual).Select(c => c.MarkUnplayed(user, userManager));
  884. await Task.WhenAll(tasks).ConfigureAwait(false);
  885. }
  886. /// <summary>
  887. /// Finds an item by path, recursively
  888. /// </summary>
  889. /// <param name="path">The path.</param>
  890. /// <returns>BaseItem.</returns>
  891. /// <exception cref="System.ArgumentNullException"></exception>
  892. public BaseItem FindByPath(string path)
  893. {
  894. if (string.IsNullOrEmpty(path))
  895. {
  896. throw new ArgumentNullException();
  897. }
  898. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  899. {
  900. return this;
  901. }
  902. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  903. {
  904. return this;
  905. }
  906. return RecursiveChildren.FirstOrDefault(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  907. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  908. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase));
  909. }
  910. public override bool IsPlayed(User user)
  911. {
  912. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  913. .All(i => i.IsPlayed(user));
  914. }
  915. public override bool IsUnplayed(User user)
  916. {
  917. return GetRecursiveChildren(user).Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  918. .All(i => i.IsUnplayed(user));
  919. }
  920. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  921. {
  922. var recursiveItemCount = 0;
  923. var unplayed = 0;
  924. double totalPercentPlayed = 0;
  925. IEnumerable<BaseItem> children;
  926. var folder = this;
  927. var season = folder as Season;
  928. if (season != null)
  929. {
  930. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  931. }
  932. else
  933. {
  934. children = folder.GetRecursiveChildren(user)
  935. .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  936. }
  937. // Loop through each recursive child
  938. foreach (var child in children)
  939. {
  940. recursiveItemCount++;
  941. var isUnplayed = true;
  942. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  943. // Incrememt totalPercentPlayed
  944. if (itemUserData != null)
  945. {
  946. if (itemUserData.Played)
  947. {
  948. totalPercentPlayed += 100;
  949. isUnplayed = false;
  950. }
  951. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  952. {
  953. double itemPercent = itemUserData.PlaybackPositionTicks;
  954. itemPercent /= child.RunTimeTicks.Value;
  955. totalPercentPlayed += itemPercent;
  956. }
  957. }
  958. if (isUnplayed)
  959. {
  960. unplayed++;
  961. }
  962. }
  963. dto.UnplayedItemCount = unplayed;
  964. if (recursiveItemCount > 0)
  965. {
  966. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  967. dto.Played = dto.PlayedPercentage.Value >= 100;
  968. }
  969. }
  970. }
  971. }