2
0

Folder.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Entities.TV;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Providers;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Querying;
  8. using System;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Runtime.Serialization;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Controller.Entities
  17. {
  18. /// <summary>
  19. /// Class Folder
  20. /// </summary>
  21. public class Folder : BaseItem, IHasThemeMedia, IHasTags
  22. {
  23. public static IUserManager UserManager { get; set; }
  24. public static IUserViewManager UserViewManager { get; set; }
  25. public List<Guid> ThemeSongIds { get; set; }
  26. public List<Guid> ThemeVideoIds { get; set; }
  27. public List<string> Tags { get; set; }
  28. public Folder()
  29. {
  30. LinkedChildren = new List<LinkedChild>();
  31. ThemeSongIds = new List<Guid>();
  32. ThemeVideoIds = new List<Guid>();
  33. Tags = new List<string>();
  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.IsNullOrEmpty(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; }
  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<FileSystemInfo> 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<FileSystemInfo> 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. // Sweep through recursively and update status
  992. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  993. .Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  994. await Task.WhenAll(tasks).ConfigureAwait(false);
  995. }
  996. /// <summary>
  997. /// Marks the unplayed.
  998. /// </summary>
  999. /// <param name="user">The user.</param>
  1000. /// <returns>Task.</returns>
  1001. public override async Task MarkUnplayed(User user)
  1002. {
  1003. // Sweep through recursively and update status
  1004. var tasks = GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1005. .Select(c => c.MarkUnplayed(user));
  1006. await Task.WhenAll(tasks).ConfigureAwait(false);
  1007. }
  1008. /// <summary>
  1009. /// Finds an item by path, recursively
  1010. /// </summary>
  1011. /// <param name="path">The path.</param>
  1012. /// <returns>BaseItem.</returns>
  1013. /// <exception cref="System.ArgumentNullException"></exception>
  1014. public BaseItem FindByPath(string path)
  1015. {
  1016. if (string.IsNullOrEmpty(path))
  1017. {
  1018. throw new ArgumentNullException();
  1019. }
  1020. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  1021. {
  1022. return this;
  1023. }
  1024. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1025. {
  1026. return this;
  1027. }
  1028. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1029. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1030. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1031. .FirstOrDefault();
  1032. }
  1033. public override bool IsPlayed(User user)
  1034. {
  1035. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1036. .All(i => i.IsPlayed(user));
  1037. }
  1038. public override bool IsUnplayed(User user)
  1039. {
  1040. return !IsPlayed(user);
  1041. }
  1042. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1043. {
  1044. var recursiveItemCount = 0;
  1045. var unplayed = 0;
  1046. double totalPercentPlayed = 0;
  1047. IEnumerable<BaseItem> children;
  1048. var folder = this;
  1049. var season = folder as Season;
  1050. if (season != null)
  1051. {
  1052. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1053. }
  1054. else
  1055. {
  1056. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1057. }
  1058. // Loop through each recursive child
  1059. foreach (var child in children)
  1060. {
  1061. recursiveItemCount++;
  1062. var isUnplayed = true;
  1063. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1064. // Incrememt totalPercentPlayed
  1065. if (itemUserData != null)
  1066. {
  1067. if (itemUserData.Played)
  1068. {
  1069. totalPercentPlayed += 100;
  1070. isUnplayed = false;
  1071. }
  1072. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1073. {
  1074. double itemPercent = itemUserData.PlaybackPositionTicks;
  1075. itemPercent /= child.RunTimeTicks.Value;
  1076. totalPercentPlayed += itemPercent;
  1077. }
  1078. }
  1079. if (isUnplayed)
  1080. {
  1081. unplayed++;
  1082. }
  1083. }
  1084. dto.UnplayedItemCount = unplayed;
  1085. if (recursiveItemCount > 0)
  1086. {
  1087. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1088. dto.Played = dto.PlayedPercentage.Value >= 100;
  1089. }
  1090. }
  1091. }
  1092. }