Folder.cs 44 KB

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