Folder.cs 44 KB

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