Folder.cs 45 KB

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