Folder.cs 44 KB

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