Folder.cs 45 KB

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