Folder.cs 45 KB

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