Folder.cs 45 KB

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