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