Folder.cs 46 KB

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