Folder.cs 44 KB

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