Folder.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. using MediaBrowser.Common.Progress;
  2. using MediaBrowser.Controller.Entities.TV;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Providers;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Querying;
  8. using System;
  9. using System.Collections;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Runtime.Serialization;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using CommonIO;
  17. using MediaBrowser.Common.IO;
  18. using MediaBrowser.Controller.Entities.Movies;
  19. using MediaBrowser.Controller.Playlists;
  20. using MediaBrowser.Model.Channels;
  21. namespace MediaBrowser.Controller.Entities
  22. {
  23. /// <summary>
  24. /// Class Folder
  25. /// </summary>
  26. public class Folder : BaseItem, IHasThemeMedia, IHasTags
  27. {
  28. public static IUserManager UserManager { get; set; }
  29. public static IUserViewManager UserViewManager { get; set; }
  30. public List<Guid> ThemeSongIds { get; set; }
  31. public List<Guid> ThemeVideoIds { get; set; }
  32. public Folder()
  33. {
  34. LinkedChildren = new List<LinkedChild>();
  35. ThemeSongIds = new List<Guid>();
  36. ThemeVideoIds = new List<Guid>();
  37. }
  38. [IgnoreDataMember]
  39. public virtual bool IsPreSorted
  40. {
  41. get { return false; }
  42. }
  43. /// <summary>
  44. /// Gets a value indicating whether this instance is folder.
  45. /// </summary>
  46. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  47. [IgnoreDataMember]
  48. public override bool IsFolder
  49. {
  50. get
  51. {
  52. return true;
  53. }
  54. }
  55. [IgnoreDataMember]
  56. public override string FileNameWithoutExtension
  57. {
  58. get
  59. {
  60. if (LocationType == LocationType.FileSystem)
  61. {
  62. return System.IO.Path.GetFileName(Path);
  63. }
  64. return null;
  65. }
  66. }
  67. protected override bool IsAllowTagFilterEnforced()
  68. {
  69. if (this is ICollectionFolder)
  70. {
  71. return false;
  72. }
  73. if (this is UserView)
  74. {
  75. return false;
  76. }
  77. return true;
  78. }
  79. /// <summary>
  80. /// Gets or sets a value indicating whether this instance is physical root.
  81. /// </summary>
  82. /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value>
  83. public bool IsPhysicalRoot { get; set; }
  84. /// <summary>
  85. /// Gets or sets a value indicating whether this instance is root.
  86. /// </summary>
  87. /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value>
  88. public bool IsRoot { get; set; }
  89. /// <summary>
  90. /// Gets a value indicating whether this instance is virtual folder.
  91. /// </summary>
  92. /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value>
  93. [IgnoreDataMember]
  94. public virtual bool IsVirtualFolder
  95. {
  96. get
  97. {
  98. return false;
  99. }
  100. }
  101. public virtual List<LinkedChild> LinkedChildren { get; set; }
  102. [IgnoreDataMember]
  103. protected virtual bool SupportsShortcutChildren
  104. {
  105. get { return ConfigurationManager.Configuration.EnableWindowsShortcuts; }
  106. }
  107. /// <summary>
  108. /// Adds the child.
  109. /// </summary>
  110. /// <param name="item">The item.</param>
  111. /// <param name="cancellationToken">The cancellation token.</param>
  112. /// <returns>Task.</returns>
  113. /// <exception cref="System.InvalidOperationException">Unable to add + item.Name</exception>
  114. public async Task AddChild(BaseItem item, CancellationToken cancellationToken)
  115. {
  116. item.SetParent(this);
  117. if (item.Id == Guid.Empty)
  118. {
  119. item.Id = LibraryManager.GetNewItemId(item.Path, item.GetType());
  120. }
  121. if (ActualChildren.Any(i => i.Id == item.Id))
  122. {
  123. throw new ArgumentException(string.Format("A child with the Id {0} already exists.", item.Id));
  124. }
  125. if (item.DateCreated == DateTime.MinValue)
  126. {
  127. item.DateCreated = DateTime.UtcNow;
  128. }
  129. if (item.DateModified == DateTime.MinValue)
  130. {
  131. item.DateModified = DateTime.UtcNow;
  132. }
  133. AddChildInternal(item.Id);
  134. await LibraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  135. if (!EnableNewFolderQuerying())
  136. {
  137. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  138. }
  139. }
  140. private static bool EnableNewFolderQuerying()
  141. {
  142. return ConfigurationManager.Configuration.MigrationVersion >= 1;
  143. }
  144. protected void AddChildrenInternal(List<Guid> children)
  145. {
  146. lock (_childrenSyncLock)
  147. {
  148. var newChildren = ChildIds.ToList();
  149. newChildren.AddRange(children);
  150. _children = newChildren.ToList();
  151. }
  152. }
  153. protected void AddChildInternal(Guid child)
  154. {
  155. lock (_childrenSyncLock)
  156. {
  157. var childIds = ChildIds.ToList();
  158. if (!childIds.Contains(child))
  159. {
  160. childIds.Add(child);
  161. _children = childIds.ToList();
  162. }
  163. }
  164. }
  165. protected void RemoveChildrenInternal(List<Guid> children)
  166. {
  167. lock (_childrenSyncLock)
  168. {
  169. _children = ChildIds.Except(children).ToList();
  170. }
  171. }
  172. /// <summary>
  173. /// Removes the child.
  174. /// </summary>
  175. /// <param name="item">The item.</param>
  176. /// <param name="cancellationToken">The cancellation token.</param>
  177. /// <returns>Task.</returns>
  178. /// <exception cref="System.InvalidOperationException">Unable to remove + item.Name</exception>
  179. public Task RemoveChild(BaseItem item, CancellationToken cancellationToken)
  180. {
  181. RemoveChildrenInternal(new[] { item.Id }.ToList());
  182. item.SetParent(null);
  183. if (!EnableNewFolderQuerying())
  184. {
  185. return ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken);
  186. }
  187. return Task.FromResult(true);
  188. }
  189. #region Indexing
  190. /// <summary>
  191. /// Returns the valid set of index by options for this folder type.
  192. /// Override or extend to modify.
  193. /// </summary>
  194. /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns>
  195. protected virtual IEnumerable<string> GetIndexByOptions()
  196. {
  197. return new List<string> {
  198. {"None"},
  199. {"Performer"},
  200. {"Genre"},
  201. {"Director"},
  202. {"Year"},
  203. {"Studio"}
  204. };
  205. }
  206. /// <summary>
  207. /// Get the list of indexy by choices for this folder (localized).
  208. /// </summary>
  209. /// <value>The index by option strings.</value>
  210. [IgnoreDataMember]
  211. public IEnumerable<string> IndexByOptionStrings
  212. {
  213. get { return GetIndexByOptions(); }
  214. }
  215. #endregion
  216. /// <summary>
  217. /// The children
  218. /// </summary>
  219. private IReadOnlyList<Guid> _children;
  220. /// <summary>
  221. /// The _children sync lock
  222. /// </summary>
  223. private readonly object _childrenSyncLock = new object();
  224. /// <summary>
  225. /// Gets or sets the actual children.
  226. /// </summary>
  227. /// <value>The actual children.</value>
  228. protected virtual IEnumerable<Guid> ChildIds
  229. {
  230. get
  231. {
  232. lock (_childrenSyncLock)
  233. {
  234. if (_children == null)
  235. {
  236. _children = LoadChildren().ToList();
  237. }
  238. return _children.ToList();
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Gets the actual children.
  244. /// </summary>
  245. /// <value>The actual children.</value>
  246. protected virtual IEnumerable<BaseItem> ActualChildren
  247. {
  248. get
  249. {
  250. return ChildIds.Select(LibraryManager.GetItemById).Where(i => i != null);
  251. }
  252. }
  253. /// <summary>
  254. /// thread-safe access to the actual children of this folder - without regard to user
  255. /// </summary>
  256. /// <value>The children.</value>
  257. [IgnoreDataMember]
  258. public IEnumerable<BaseItem> Children
  259. {
  260. get { return ActualChildren.ToList(); }
  261. }
  262. /// <summary>
  263. /// thread-safe access to all recursive children of this folder - without regard to user
  264. /// </summary>
  265. /// <value>The recursive children.</value>
  266. [IgnoreDataMember]
  267. public IEnumerable<BaseItem> RecursiveChildren
  268. {
  269. get { return GetRecursiveChildren(); }
  270. }
  271. public override bool IsVisible(User user)
  272. {
  273. if (this is ICollectionFolder && !(this is BasePluginFolder))
  274. {
  275. if (user.Policy.BlockedMediaFolders != null)
  276. {
  277. if (user.Policy.BlockedMediaFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase) ||
  278. // Backwards compatibility
  279. user.Policy.BlockedMediaFolders.Contains(Name, StringComparer.OrdinalIgnoreCase))
  280. {
  281. return false;
  282. }
  283. }
  284. else
  285. {
  286. if (!user.Policy.EnableAllFolders && !user.Policy.EnabledFolders.Contains(Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  287. {
  288. return false;
  289. }
  290. }
  291. }
  292. return base.IsVisible(user);
  293. }
  294. /// <summary>
  295. /// Loads our children. Validation will occur externally.
  296. /// We want this sychronous.
  297. /// </summary>
  298. protected virtual IEnumerable<Guid> LoadChildren()
  299. {
  300. //just load our children from the repo - the library will be validated and maintained in other processes
  301. return GetCachedChildren();
  302. }
  303. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken)
  304. {
  305. return ValidateChildren(progress, cancellationToken, new MetadataRefreshOptions(new DirectoryService(FileSystem)));
  306. }
  307. /// <summary>
  308. /// Validates that the children of the folder still exist
  309. /// </summary>
  310. /// <param name="progress">The progress.</param>
  311. /// <param name="cancellationToken">The cancellation token.</param>
  312. /// <param name="metadataRefreshOptions">The metadata refresh options.</param>
  313. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  314. /// <returns>Task.</returns>
  315. public Task ValidateChildren(IProgress<double> progress, CancellationToken cancellationToken, MetadataRefreshOptions metadataRefreshOptions, bool recursive = true)
  316. {
  317. return ValidateChildrenInternal(progress, cancellationToken, recursive, true, metadataRefreshOptions, metadataRefreshOptions.DirectoryService);
  318. }
  319. private Dictionary<Guid, BaseItem> GetActualChildrenDictionary()
  320. {
  321. var dictionary = new Dictionary<Guid, BaseItem>();
  322. foreach (var child in ActualChildren)
  323. {
  324. var id = child.Id;
  325. if (dictionary.ContainsKey(id))
  326. {
  327. Logger.Error("Found folder containing items with duplicate id. Path: {0}, Child Name: {1}",
  328. Path ?? Name,
  329. child.Path ?? child.Name);
  330. }
  331. else
  332. {
  333. dictionary[id] = child;
  334. }
  335. }
  336. return dictionary;
  337. }
  338. private bool IsValidFromResolver(BaseItem current, BaseItem newItem)
  339. {
  340. return current.IsValidFromResolver(newItem);
  341. }
  342. /// <summary>
  343. /// Validates the children internal.
  344. /// </summary>
  345. /// <param name="progress">The progress.</param>
  346. /// <param name="cancellationToken">The cancellation token.</param>
  347. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  348. /// <param name="refreshChildMetadata">if set to <c>true</c> [refresh child metadata].</param>
  349. /// <param name="refreshOptions">The refresh options.</param>
  350. /// <param name="directoryService">The directory service.</param>
  351. /// <returns>Task.</returns>
  352. protected async virtual Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService)
  353. {
  354. var locationType = LocationType;
  355. cancellationToken.ThrowIfCancellationRequested();
  356. var validChildren = new List<BaseItem>();
  357. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  358. {
  359. IEnumerable<BaseItem> nonCachedChildren;
  360. try
  361. {
  362. nonCachedChildren = GetNonCachedChildren(directoryService);
  363. }
  364. catch (IOException ex)
  365. {
  366. nonCachedChildren = new BaseItem[] { };
  367. Logger.ErrorException("Error getting file system entries for {0}", ex, Path);
  368. }
  369. if (nonCachedChildren == null) return; //nothing to validate
  370. progress.Report(5);
  371. //build a dictionary of the current children we have now by Id so we can compare quickly and easily
  372. var currentChildren = GetActualChildrenDictionary();
  373. //create a list for our validated children
  374. var newItems = new List<BaseItem>();
  375. cancellationToken.ThrowIfCancellationRequested();
  376. foreach (var child in nonCachedChildren)
  377. {
  378. BaseItem currentChild;
  379. if (currentChildren.TryGetValue(child.Id, out currentChild) && IsValidFromResolver(currentChild, child))
  380. {
  381. var currentChildLocationType = currentChild.LocationType;
  382. if (currentChildLocationType != LocationType.Remote &&
  383. currentChildLocationType != LocationType.Virtual)
  384. {
  385. currentChild.DateModified = child.DateModified;
  386. }
  387. await UpdateIsOffline(currentChild, false).ConfigureAwait(false);
  388. validChildren.Add(currentChild);
  389. continue;
  390. }
  391. // Brand new item - needs to be added
  392. child.SetParent(this);
  393. newItems.Add(child);
  394. validChildren.Add(child);
  395. }
  396. // If any items were added or removed....
  397. if (newItems.Count > 0 || currentChildren.Count != validChildren.Count)
  398. {
  399. // That's all the new and changed ones - now see if there are any that are missing
  400. var itemsRemoved = currentChildren.Values.Except(validChildren).ToList();
  401. var actualRemovals = new List<BaseItem>();
  402. foreach (var item in itemsRemoved)
  403. {
  404. if (item.LocationType == LocationType.Virtual ||
  405. item.LocationType == LocationType.Remote)
  406. {
  407. // Don't remove these because there's no way to accurately validate them.
  408. validChildren.Add(item);
  409. }
  410. else if (!string.IsNullOrEmpty(item.Path) && IsPathOffline(item.Path))
  411. {
  412. await UpdateIsOffline(item, true).ConfigureAwait(false);
  413. validChildren.Add(item);
  414. }
  415. else
  416. {
  417. actualRemovals.Add(item);
  418. }
  419. }
  420. if (actualRemovals.Count > 0)
  421. {
  422. RemoveChildrenInternal(actualRemovals.Select(i => i.Id).ToList());
  423. foreach (var item in actualRemovals)
  424. {
  425. Logger.Debug("Removed item: " + item.Path);
  426. item.SetParent(null);
  427. item.IsOffline = false;
  428. await LibraryManager.DeleteItem(item, new DeleteOptions { DeleteFileLocation = false }).ConfigureAwait(false);
  429. LibraryManager.ReportItemRemoved(item);
  430. }
  431. }
  432. await LibraryManager.CreateItems(newItems, cancellationToken).ConfigureAwait(false);
  433. AddChildrenInternal(newItems.Select(i => i.Id).ToList());
  434. if (!EnableNewFolderQuerying())
  435. {
  436. await ItemRepository.SaveChildren(Id, ActualChildren.Select(i => i.Id).ToList(), cancellationToken).ConfigureAwait(false);
  437. }
  438. }
  439. }
  440. progress.Report(10);
  441. cancellationToken.ThrowIfCancellationRequested();
  442. if (recursive)
  443. {
  444. await ValidateSubFolders(ActualChildren.OfType<Folder>().ToList(), directoryService, progress, cancellationToken).ConfigureAwait(false);
  445. }
  446. progress.Report(20);
  447. if (refreshChildMetadata)
  448. {
  449. var container = this as IMetadataContainer;
  450. var innerProgress = new ActionableProgress<double>();
  451. innerProgress.RegisterAction(p => progress.Report((.80 * p) + 20));
  452. if (container != null)
  453. {
  454. await container.RefreshAllMetadata(refreshOptions, innerProgress, cancellationToken).ConfigureAwait(false);
  455. }
  456. else
  457. {
  458. await RefreshMetadataRecursive(refreshOptions, recursive, innerProgress, cancellationToken);
  459. }
  460. }
  461. progress.Report(100);
  462. }
  463. private Task UpdateIsOffline(BaseItem item, bool newValue)
  464. {
  465. if (item.IsOffline != newValue)
  466. {
  467. item.IsOffline = newValue;
  468. return item.UpdateToRepository(ItemUpdateType.None, CancellationToken.None);
  469. }
  470. return Task.FromResult(true);
  471. }
  472. private async Task RefreshMetadataRecursive(MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  473. {
  474. var children = ActualChildren.ToList();
  475. var percentages = new Dictionary<Guid, double>(children.Count);
  476. var numComplete = 0;
  477. var count = children.Count;
  478. foreach (var child in children)
  479. {
  480. cancellationToken.ThrowIfCancellationRequested();
  481. if (child.IsFolder)
  482. {
  483. var innerProgress = new ActionableProgress<double>();
  484. // Avoid implicitly captured closure
  485. var currentChild = child;
  486. innerProgress.RegisterAction(p =>
  487. {
  488. lock (percentages)
  489. {
  490. percentages[currentChild.Id] = p / 100;
  491. var innerPercent = percentages.Values.Sum();
  492. innerPercent /= count;
  493. innerPercent *= 100;
  494. progress.Report(innerPercent);
  495. }
  496. });
  497. await RefreshChildMetadata(child, refreshOptions, recursive, innerProgress, cancellationToken)
  498. .ConfigureAwait(false);
  499. }
  500. else
  501. {
  502. await RefreshChildMetadata(child, refreshOptions, false, new Progress<double>(), cancellationToken)
  503. .ConfigureAwait(false);
  504. }
  505. numComplete++;
  506. double percent = numComplete;
  507. percent /= count;
  508. percent *= 100;
  509. progress.Report(percent);
  510. }
  511. progress.Report(100);
  512. }
  513. private async Task RefreshChildMetadata(BaseItem child, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
  514. {
  515. var container = child as IMetadataContainer;
  516. if (container != null)
  517. {
  518. await container.RefreshAllMetadata(refreshOptions, progress, cancellationToken).ConfigureAwait(false);
  519. }
  520. else
  521. {
  522. await child.RefreshMetadata(refreshOptions, cancellationToken).ConfigureAwait(false);
  523. if (recursive)
  524. {
  525. var folder = child as Folder;
  526. if (folder != null)
  527. {
  528. await folder.RefreshMetadataRecursive(refreshOptions, true, progress, cancellationToken);
  529. }
  530. }
  531. }
  532. progress.Report(100);
  533. }
  534. /// <summary>
  535. /// Refreshes the children.
  536. /// </summary>
  537. /// <param name="children">The children.</param>
  538. /// <param name="directoryService">The directory service.</param>
  539. /// <param name="progress">The progress.</param>
  540. /// <param name="cancellationToken">The cancellation token.</param>
  541. /// <returns>Task.</returns>
  542. private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
  543. {
  544. var list = children;
  545. var childCount = list.Count;
  546. var percentages = new Dictionary<Guid, double>(list.Count);
  547. foreach (var item in list)
  548. {
  549. cancellationToken.ThrowIfCancellationRequested();
  550. var child = item;
  551. var innerProgress = new ActionableProgress<double>();
  552. innerProgress.RegisterAction(p =>
  553. {
  554. lock (percentages)
  555. {
  556. percentages[child.Id] = p / 100;
  557. var percent = percentages.Values.Sum();
  558. percent /= childCount;
  559. progress.Report((10 * percent) + 10);
  560. }
  561. });
  562. await child.ValidateChildrenInternal(innerProgress, cancellationToken, true, false, null, directoryService)
  563. .ConfigureAwait(false);
  564. }
  565. }
  566. /// <summary>
  567. /// Determines whether the specified path is offline.
  568. /// </summary>
  569. /// <param name="path">The path.</param>
  570. /// <returns><c>true</c> if the specified path is offline; otherwise, <c>false</c>.</returns>
  571. public static bool IsPathOffline(string path)
  572. {
  573. if (FileSystem.FileExists(path))
  574. {
  575. return false;
  576. }
  577. var originalPath = path;
  578. // Depending on whether the path is local or unc, it may return either null or '\' at the top
  579. while (!string.IsNullOrEmpty(path) && path.Length > 1)
  580. {
  581. if (FileSystem.DirectoryExists(path))
  582. {
  583. return false;
  584. }
  585. path = System.IO.Path.GetDirectoryName(path);
  586. }
  587. if (ContainsPath(LibraryManager.GetVirtualFolders(), originalPath))
  588. {
  589. return true;
  590. }
  591. return false;
  592. }
  593. /// <summary>
  594. /// Determines whether the specified folders contains path.
  595. /// </summary>
  596. /// <param name="folders">The folders.</param>
  597. /// <param name="path">The path.</param>
  598. /// <returns><c>true</c> if the specified folders contains path; otherwise, <c>false</c>.</returns>
  599. private static bool ContainsPath(IEnumerable<VirtualFolderInfo> folders, string path)
  600. {
  601. return folders.SelectMany(i => i.Locations).Any(i => ContainsPath(i, path));
  602. }
  603. private static bool ContainsPath(string parent, string path)
  604. {
  605. return string.Equals(parent, path, StringComparison.OrdinalIgnoreCase) || FileSystem.ContainsSubPath(parent, path);
  606. }
  607. /// <summary>
  608. /// Get the children of this folder from the actual file system
  609. /// </summary>
  610. /// <returns>IEnumerable{BaseItem}.</returns>
  611. protected virtual IEnumerable<BaseItem> GetNonCachedChildren(IDirectoryService directoryService)
  612. {
  613. var collectionType = LibraryManager.GetContentType(this);
  614. return LibraryManager.ResolvePaths(GetFileSystemChildren(directoryService), directoryService, this, collectionType);
  615. }
  616. /// <summary>
  617. /// Get our children from the repo - stubbed for now
  618. /// </summary>
  619. /// <returns>IEnumerable{BaseItem}.</returns>
  620. protected IEnumerable<Guid> GetCachedChildren()
  621. {
  622. if (EnableNewFolderQuerying())
  623. {
  624. return ItemRepository.GetItemIdsList(new InternalItemsQuery
  625. {
  626. ParentId = Id
  627. });
  628. }
  629. return ItemRepository.GetChildrenItems(Id).Select(RetrieveChild).Where(i => i != null).Select(i => i.Id);
  630. }
  631. private BaseItem RetrieveChild(BaseItem child)
  632. {
  633. if (child == null || 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.SetParent(this);
  646. }
  647. else
  648. {
  649. child.SetParent(this);
  650. LibraryManager.RegisterItem(child);
  651. item = child;
  652. }
  653. return item;
  654. }
  655. public QueryResult<BaseItem> QueryRecursive(InternalItemsQuery query)
  656. {
  657. var user = query.User;
  658. if (RequiresPostFiltering(query))
  659. {
  660. IEnumerable<BaseItem> items;
  661. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  662. if (query.User == null)
  663. {
  664. items = GetRecursiveChildren(filter);
  665. }
  666. else
  667. {
  668. items = GetRecursiveChildren(user, filter);
  669. }
  670. return PostFilterAndSort(items, query);
  671. }
  672. if (!(this is UserRootFolder) && !(this is AggregateFolder))
  673. {
  674. query.ParentId = query.ParentId ?? Id;
  675. }
  676. return LibraryManager.GetItemsResult(query);
  677. }
  678. private bool RequiresPostFiltering(InternalItemsQuery query)
  679. {
  680. if (LinkedChildren.Count > 0)
  681. {
  682. if (!(this is ICollectionFolder))
  683. {
  684. Logger.Debug("Query requires post-filtering due to LinkedChildren");
  685. return true;
  686. }
  687. }
  688. if (query.SortBy != null && query.SortBy.Length > 0)
  689. {
  690. if (query.SortBy.Contains(ItemSortBy.DatePlayed, StringComparer.OrdinalIgnoreCase))
  691. {
  692. Logger.Debug("Query requires post-filtering due to ItemSortBy.DatePlayed");
  693. return true;
  694. }
  695. if (query.SortBy.Contains(ItemSortBy.IsFavoriteOrLiked, StringComparer.OrdinalIgnoreCase))
  696. {
  697. Logger.Debug("Query requires post-filtering due to ItemSortBy.IsFavoriteOrLiked");
  698. return true;
  699. }
  700. if (query.SortBy.Contains(ItemSortBy.IsPlayed, StringComparer.OrdinalIgnoreCase))
  701. {
  702. Logger.Debug("Query requires post-filtering due to ItemSortBy.IsPlayed");
  703. return true;
  704. }
  705. if (query.SortBy.Contains(ItemSortBy.IsUnplayed, StringComparer.OrdinalIgnoreCase))
  706. {
  707. Logger.Debug("Query requires post-filtering due to ItemSortBy.IsUnplayed");
  708. return true;
  709. }
  710. if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase))
  711. {
  712. Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder");
  713. return true;
  714. }
  715. if (query.SortBy.Contains(ItemSortBy.Album, StringComparer.OrdinalIgnoreCase))
  716. {
  717. Logger.Debug("Query requires post-filtering due to ItemSortBy.Album");
  718. return true;
  719. }
  720. if (query.SortBy.Contains(ItemSortBy.AlbumArtist, StringComparer.OrdinalIgnoreCase))
  721. {
  722. Logger.Debug("Query requires post-filtering due to ItemSortBy.AlbumArtist");
  723. return true;
  724. }
  725. if (query.SortBy.Contains(ItemSortBy.Artist, StringComparer.OrdinalIgnoreCase))
  726. {
  727. Logger.Debug("Query requires post-filtering due to ItemSortBy.Artist");
  728. return true;
  729. }
  730. if (query.SortBy.Contains(ItemSortBy.Budget, StringComparer.OrdinalIgnoreCase))
  731. {
  732. Logger.Debug("Query requires post-filtering due to ItemSortBy.Budget");
  733. return true;
  734. }
  735. if (query.SortBy.Contains(ItemSortBy.CriticRating, StringComparer.OrdinalIgnoreCase))
  736. {
  737. Logger.Debug("Query requires post-filtering due to ItemSortBy.CriticRating");
  738. return true;
  739. }
  740. if (query.SortBy.Contains(ItemSortBy.DateLastContentAdded, StringComparer.OrdinalIgnoreCase))
  741. {
  742. Logger.Debug("Query requires post-filtering due to ItemSortBy.DateLastContentAdded");
  743. return true;
  744. }
  745. if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase))
  746. {
  747. Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem");
  748. return true;
  749. }
  750. if (query.SortBy.Contains(ItemSortBy.Metascore, StringComparer.OrdinalIgnoreCase))
  751. {
  752. Logger.Debug("Query requires post-filtering due to ItemSortBy.Metascore");
  753. return true;
  754. }
  755. if (query.SortBy.Contains(ItemSortBy.OfficialRating, StringComparer.OrdinalIgnoreCase))
  756. {
  757. Logger.Debug("Query requires post-filtering due to ItemSortBy.OfficialRating");
  758. return true;
  759. }
  760. if (query.SortBy.Contains(ItemSortBy.PlayCount, StringComparer.OrdinalIgnoreCase))
  761. {
  762. Logger.Debug("Query requires post-filtering due to ItemSortBy.PlayCount");
  763. return true;
  764. }
  765. if (query.SortBy.Contains(ItemSortBy.Players, StringComparer.OrdinalIgnoreCase))
  766. {
  767. Logger.Debug("Query requires post-filtering due to ItemSortBy.Players");
  768. return true;
  769. }
  770. if (query.SortBy.Contains(ItemSortBy.Revenue, StringComparer.OrdinalIgnoreCase))
  771. {
  772. Logger.Debug("Query requires post-filtering due to ItemSortBy.Revenue");
  773. return true;
  774. }
  775. if (query.SortBy.Contains(ItemSortBy.SeriesSortName, StringComparer.OrdinalIgnoreCase))
  776. {
  777. Logger.Debug("Query requires post-filtering due to ItemSortBy.SeriesSortName");
  778. return true;
  779. }
  780. if (query.SortBy.Contains(ItemSortBy.StartDate, StringComparer.OrdinalIgnoreCase))
  781. {
  782. Logger.Debug("Query requires post-filtering due to ItemSortBy.StartDate");
  783. return true;
  784. }
  785. if (query.SortBy.Contains(ItemSortBy.Studio, StringComparer.OrdinalIgnoreCase))
  786. {
  787. Logger.Debug("Query requires post-filtering due to ItemSortBy.Studio");
  788. return true;
  789. }
  790. if (query.SortBy.Contains(ItemSortBy.VideoBitRate, StringComparer.OrdinalIgnoreCase))
  791. {
  792. Logger.Debug("Query requires post-filtering due to ItemSortBy.VideoBitRate");
  793. return true;
  794. }
  795. }
  796. if (query.ItemIds.Length > 0)
  797. {
  798. Logger.Debug("Query requires post-filtering due to ItemIds");
  799. return true;
  800. }
  801. if (query.PersonIds.Length > 0)
  802. {
  803. Logger.Debug("Query requires post-filtering due to PersonIds");
  804. return true;
  805. }
  806. if (query.IsLiked.HasValue)
  807. {
  808. Logger.Debug("Query requires post-filtering due to IsLiked");
  809. return true;
  810. }
  811. if (query.IsFavoriteOrLiked.HasValue)
  812. {
  813. Logger.Debug("Query requires post-filtering due to IsFavoriteOrLiked");
  814. return true;
  815. }
  816. if (query.IsFavorite.HasValue)
  817. {
  818. Logger.Debug("Query requires post-filtering due to IsFavorite");
  819. return true;
  820. }
  821. if (query.IsResumable.HasValue)
  822. {
  823. Logger.Debug("Query requires post-filtering due to IsResumable");
  824. return true;
  825. }
  826. if (query.IsPlayed.HasValue)
  827. {
  828. Logger.Debug("Query requires post-filtering due to IsPlayed");
  829. return true;
  830. }
  831. if (query.IsInBoxSet.HasValue)
  832. {
  833. Logger.Debug("Query requires post-filtering due to IsInBoxSet");
  834. return true;
  835. }
  836. // Filter by Video3DFormat
  837. if (query.Is3D.HasValue)
  838. {
  839. Logger.Debug("Query requires post-filtering due to Is3D");
  840. return true;
  841. }
  842. if (query.HasOverview.HasValue)
  843. {
  844. Logger.Debug("Query requires post-filtering due to HasOverview");
  845. return true;
  846. }
  847. if (query.HasImdbId.HasValue)
  848. {
  849. Logger.Debug("Query requires post-filtering due to HasImdbId");
  850. return true;
  851. }
  852. if (query.HasTmdbId.HasValue)
  853. {
  854. Logger.Debug("Query requires post-filtering due to HasTmdbId");
  855. return true;
  856. }
  857. if (query.HasTvdbId.HasValue)
  858. {
  859. Logger.Debug("Query requires post-filtering due to HasTvdbId");
  860. return true;
  861. }
  862. if (query.IsYearMismatched.HasValue)
  863. {
  864. Logger.Debug("Query requires post-filtering due to IsYearMismatched");
  865. return true;
  866. }
  867. if (query.HasOfficialRating.HasValue)
  868. {
  869. Logger.Debug("Query requires post-filtering due to HasOfficialRating");
  870. return true;
  871. }
  872. if (query.IsPlaceHolder.HasValue)
  873. {
  874. Logger.Debug("Query requires post-filtering due to IsPlaceHolder");
  875. return true;
  876. }
  877. if (query.HasSpecialFeature.HasValue)
  878. {
  879. Logger.Debug("Query requires post-filtering due to HasSpecialFeature");
  880. return true;
  881. }
  882. if (query.HasSubtitles.HasValue)
  883. {
  884. Logger.Debug("Query requires post-filtering due to HasSubtitles");
  885. return true;
  886. }
  887. if (query.HasTrailer.HasValue)
  888. {
  889. Logger.Debug("Query requires post-filtering due to HasTrailer");
  890. return true;
  891. }
  892. if (query.HasThemeSong.HasValue)
  893. {
  894. Logger.Debug("Query requires post-filtering due to HasThemeSong");
  895. return true;
  896. }
  897. if (query.HasThemeVideo.HasValue)
  898. {
  899. Logger.Debug("Query requires post-filtering due to HasThemeVideo");
  900. return true;
  901. }
  902. // Filter by VideoType
  903. if (query.VideoTypes.Length > 0)
  904. {
  905. Logger.Debug("Query requires post-filtering due to VideoTypes");
  906. return true;
  907. }
  908. if (query.ImageTypes.Length > 0)
  909. {
  910. Logger.Debug("Query requires post-filtering due to ImageTypes");
  911. return true;
  912. }
  913. // Apply studio filter
  914. if (query.StudioIds.Length > 0)
  915. {
  916. Logger.Debug("Query requires post-filtering due to StudioIds");
  917. return true;
  918. }
  919. // Apply genre filter
  920. if (query.GenreIds.Length > 0)
  921. {
  922. Logger.Debug("Query requires post-filtering due to GenreIds");
  923. return true;
  924. }
  925. // Apply official rating filter
  926. if (query.OfficialRatings.Length > 0)
  927. {
  928. Logger.Debug("Query requires post-filtering due to OfficialRatings");
  929. return true;
  930. }
  931. // Apply person filter
  932. if (query.ItemIdsFromPersonFilters != null)
  933. {
  934. Logger.Debug("Query requires post-filtering due to ItemIdsFromPersonFilters");
  935. return true;
  936. }
  937. if (query.MinPlayers.HasValue)
  938. {
  939. Logger.Debug("Query requires post-filtering due to MinPlayers");
  940. return true;
  941. }
  942. if (query.MaxPlayers.HasValue)
  943. {
  944. Logger.Debug("Query requires post-filtering due to MaxPlayers");
  945. return true;
  946. }
  947. if (query.MinIndexNumber.HasValue)
  948. {
  949. Logger.Debug("Query requires post-filtering due to MinIndexNumber");
  950. return true;
  951. }
  952. if (query.OfficialRatings.Length > 0)
  953. {
  954. Logger.Debug("Query requires post-filtering due to OfficialRatings");
  955. return true;
  956. }
  957. if (query.IsMissing.HasValue)
  958. {
  959. Logger.Debug("Query requires post-filtering due to IsMissing");
  960. return true;
  961. }
  962. if (query.IsUnaired.HasValue)
  963. {
  964. Logger.Debug("Query requires post-filtering due to IsUnaired");
  965. return true;
  966. }
  967. if (query.IsVirtualUnaired.HasValue)
  968. {
  969. Logger.Debug("Query requires post-filtering due to IsVirtualUnaired");
  970. return true;
  971. }
  972. if (UserViewBuilder.CollapseBoxSetItems(query, this, query.User))
  973. {
  974. Logger.Debug("Query requires post-filtering due to CollapseBoxSetItems");
  975. return true;
  976. }
  977. if (!string.IsNullOrWhiteSpace(query.AdjacentTo))
  978. {
  979. Logger.Debug("Query requires post-filtering due to AdjacentTo");
  980. return true;
  981. }
  982. if (!string.IsNullOrWhiteSpace(query.NameContains))
  983. {
  984. Logger.Debug("Query requires post-filtering due to NameContains");
  985. return true;
  986. }
  987. if (!string.IsNullOrWhiteSpace(query.NameLessThan))
  988. {
  989. Logger.Debug("Query requires post-filtering due to NameLessThan");
  990. return true;
  991. }
  992. if (!string.IsNullOrWhiteSpace(query.NameStartsWith))
  993. {
  994. Logger.Debug("Query requires post-filtering due to NameStartsWith");
  995. return true;
  996. }
  997. if (!string.IsNullOrWhiteSpace(query.NameStartsWithOrGreater))
  998. {
  999. Logger.Debug("Query requires post-filtering due to NameStartsWithOrGreater");
  1000. return true;
  1001. }
  1002. if (query.AirDays.Length > 0)
  1003. {
  1004. Logger.Debug("Query requires post-filtering due to AirDays");
  1005. return true;
  1006. }
  1007. if (query.SeriesStatuses.Length > 0)
  1008. {
  1009. Logger.Debug("Query requires post-filtering due to SeriesStatuses");
  1010. return true;
  1011. }
  1012. if (query.AiredDuringSeason.HasValue)
  1013. {
  1014. Logger.Debug("Query requires post-filtering due to AiredDuringSeason");
  1015. return true;
  1016. }
  1017. if (!string.IsNullOrWhiteSpace(query.AlbumArtistStartsWithOrGreater))
  1018. {
  1019. Logger.Debug("Query requires post-filtering due to AlbumArtistStartsWithOrGreater");
  1020. return true;
  1021. }
  1022. return false;
  1023. }
  1024. public virtual async Task<QueryResult<BaseItem>> GetItems(InternalItemsQuery query)
  1025. {
  1026. if (SourceType == SourceType.Channel)
  1027. {
  1028. try
  1029. {
  1030. // Don't blow up here because it could cause parent screens with other content to fail
  1031. return await ChannelManager.GetChannelItemsInternal(new ChannelItemQuery
  1032. {
  1033. ChannelId = ChannelId,
  1034. FolderId = Id.ToString("N"),
  1035. Limit = query.Limit,
  1036. StartIndex = query.StartIndex,
  1037. UserId = query.User.Id.ToString("N"),
  1038. SortBy = query.SortBy,
  1039. SortOrder = query.SortOrder
  1040. }, new Progress<double>(), CancellationToken.None);
  1041. }
  1042. catch
  1043. {
  1044. // Already logged at lower levels
  1045. return new QueryResult<BaseItem>
  1046. {
  1047. };
  1048. }
  1049. }
  1050. if (query.Recursive)
  1051. {
  1052. return QueryRecursive(query);
  1053. }
  1054. var user = query.User;
  1055. Func<BaseItem, bool> filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager);
  1056. IEnumerable<BaseItem> items;
  1057. if (query.User == null)
  1058. {
  1059. items = query.Recursive
  1060. ? GetRecursiveChildren(filter)
  1061. : Children.Where(filter);
  1062. }
  1063. else
  1064. {
  1065. items = query.Recursive
  1066. ? GetRecursiveChildren(user, filter)
  1067. : GetChildren(user, true).Where(filter);
  1068. }
  1069. var result = PostFilterAndSort(items, query);
  1070. return result;
  1071. }
  1072. protected QueryResult<BaseItem> PostFilterAndSort(IEnumerable<BaseItem> items, InternalItemsQuery query)
  1073. {
  1074. return UserViewBuilder.PostFilterAndSort(items, this, null, query, LibraryManager);
  1075. }
  1076. public virtual IEnumerable<BaseItem> GetChildren(User user, bool includeLinkedChildren)
  1077. {
  1078. if (user == null)
  1079. {
  1080. throw new ArgumentNullException();
  1081. }
  1082. //the true root should return our users root folder children
  1083. if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, includeLinkedChildren);
  1084. var result = new Dictionary<Guid, BaseItem>();
  1085. AddChildren(user, includeLinkedChildren, result, false, null);
  1086. return result.Values;
  1087. }
  1088. protected virtual IEnumerable<BaseItem> GetEligibleChildrenForRecursiveChildren(User user)
  1089. {
  1090. return Children;
  1091. }
  1092. /// <summary>
  1093. /// Adds the children to list.
  1094. /// </summary>
  1095. /// <param name="user">The user.</param>
  1096. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  1097. /// <param name="result">The result.</param>
  1098. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  1099. /// <param name="filter">The filter.</param>
  1100. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1101. private void AddChildren(User user, bool includeLinkedChildren, Dictionary<Guid, BaseItem> result, bool recursive, Func<BaseItem, bool> filter)
  1102. {
  1103. foreach (var child in GetEligibleChildrenForRecursiveChildren(user))
  1104. {
  1105. if (child.IsVisible(user))
  1106. {
  1107. if (filter == null || filter(child))
  1108. {
  1109. result[child.Id] = child;
  1110. }
  1111. if (recursive && child.IsFolder)
  1112. {
  1113. var folder = (Folder)child;
  1114. folder.AddChildren(user, includeLinkedChildren, result, true, filter);
  1115. }
  1116. }
  1117. }
  1118. if (includeLinkedChildren)
  1119. {
  1120. foreach (var child in GetLinkedChildren(user))
  1121. {
  1122. if (child.IsVisible(user))
  1123. {
  1124. if (filter == null || filter(child))
  1125. {
  1126. result[child.Id] = child;
  1127. }
  1128. }
  1129. }
  1130. }
  1131. }
  1132. /// <summary>
  1133. /// Gets allowed recursive children of an item
  1134. /// </summary>
  1135. /// <param name="user">The user.</param>
  1136. /// <param name="includeLinkedChildren">if set to <c>true</c> [include linked children].</param>
  1137. /// <returns>IEnumerable{BaseItem}.</returns>
  1138. /// <exception cref="System.ArgumentNullException"></exception>
  1139. public IEnumerable<BaseItem> GetRecursiveChildren(User user, bool includeLinkedChildren = true)
  1140. {
  1141. return GetRecursiveChildren(user, i => true);
  1142. }
  1143. public virtual IEnumerable<BaseItem> GetRecursiveChildren(User user, Func<BaseItem, bool> filter)
  1144. {
  1145. if (user == null)
  1146. {
  1147. throw new ArgumentNullException("user");
  1148. }
  1149. var result = new Dictionary<Guid, BaseItem>();
  1150. AddChildren(user, true, result, true, filter);
  1151. return result.Values;
  1152. }
  1153. /// <summary>
  1154. /// Gets the recursive children.
  1155. /// </summary>
  1156. /// <returns>IList{BaseItem}.</returns>
  1157. public IList<BaseItem> GetRecursiveChildren()
  1158. {
  1159. return GetRecursiveChildren(i => true);
  1160. }
  1161. public IList<BaseItem> GetRecursiveChildren(Func<BaseItem, bool> filter)
  1162. {
  1163. var list = new List<BaseItem>();
  1164. AddChildrenToList(list, true, filter);
  1165. return list;
  1166. }
  1167. /// <summary>
  1168. /// Adds the children to list.
  1169. /// </summary>
  1170. /// <param name="list">The list.</param>
  1171. /// <param name="recursive">if set to <c>true</c> [recursive].</param>
  1172. /// <param name="filter">The filter.</param>
  1173. private void AddChildrenToList(List<BaseItem> list, bool recursive, Func<BaseItem, bool> filter)
  1174. {
  1175. foreach (var child in Children)
  1176. {
  1177. if (filter == null || filter(child))
  1178. {
  1179. list.Add(child);
  1180. }
  1181. if (recursive && child.IsFolder)
  1182. {
  1183. var folder = (Folder)child;
  1184. folder.AddChildrenToList(list, true, filter);
  1185. }
  1186. }
  1187. }
  1188. /// <summary>
  1189. /// Gets the linked children.
  1190. /// </summary>
  1191. /// <returns>IEnumerable{BaseItem}.</returns>
  1192. public IEnumerable<BaseItem> GetLinkedChildren()
  1193. {
  1194. return LinkedChildren
  1195. .Select(GetLinkedChild)
  1196. .Where(i => i != null);
  1197. }
  1198. protected virtual bool FilterLinkedChildrenPerUser
  1199. {
  1200. get
  1201. {
  1202. return false;
  1203. }
  1204. }
  1205. public IEnumerable<BaseItem> GetLinkedChildren(User user)
  1206. {
  1207. if (!FilterLinkedChildrenPerUser || user == null)
  1208. {
  1209. return GetLinkedChildren();
  1210. }
  1211. var locations = user.RootFolder
  1212. .Children
  1213. .OfType<CollectionFolder>()
  1214. .Where(i => i.IsVisible(user))
  1215. .SelectMany(i => i.PhysicalLocations)
  1216. .ToList();
  1217. return LinkedChildren
  1218. .Select(i =>
  1219. {
  1220. var requiresPostFilter = true;
  1221. if (!string.IsNullOrWhiteSpace(i.Path))
  1222. {
  1223. requiresPostFilter = false;
  1224. if (!locations.Any(l => FileSystem.ContainsSubPath(l, i.Path)))
  1225. {
  1226. return null;
  1227. }
  1228. }
  1229. var child = GetLinkedChild(i);
  1230. if (requiresPostFilter && child != null)
  1231. {
  1232. if (string.IsNullOrWhiteSpace(child.Path))
  1233. {
  1234. Logger.Debug("Found LinkedChild with null path: {0}", child.Name);
  1235. return child;
  1236. }
  1237. if (!locations.Any(l => FileSystem.ContainsSubPath(l, child.Path)))
  1238. {
  1239. return null;
  1240. }
  1241. }
  1242. return child;
  1243. })
  1244. .Where(i => i != null);
  1245. }
  1246. /// <summary>
  1247. /// Gets the linked children.
  1248. /// </summary>
  1249. /// <returns>IEnumerable{BaseItem}.</returns>
  1250. public IEnumerable<Tuple<LinkedChild, BaseItem>> GetLinkedChildrenInfos()
  1251. {
  1252. return LinkedChildren
  1253. .Select(i => new Tuple<LinkedChild, BaseItem>(i, GetLinkedChild(i)))
  1254. .Where(i => i.Item2 != null);
  1255. }
  1256. [IgnoreDataMember]
  1257. protected override bool SupportsOwnedItems
  1258. {
  1259. get
  1260. {
  1261. return base.SupportsOwnedItems || SupportsShortcutChildren;
  1262. }
  1263. }
  1264. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1265. {
  1266. var changesFound = false;
  1267. if (LocationType == LocationType.FileSystem)
  1268. {
  1269. if (RefreshLinkedChildren(fileSystemChildren))
  1270. {
  1271. changesFound = true;
  1272. }
  1273. }
  1274. var baseHasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1275. return baseHasChanges || changesFound;
  1276. }
  1277. /// <summary>
  1278. /// Refreshes the linked children.
  1279. /// </summary>
  1280. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  1281. private bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)
  1282. {
  1283. var currentManualLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Manual).ToList();
  1284. var currentShortcutLinks = LinkedChildren.Where(i => i.Type == LinkedChildType.Shortcut).ToList();
  1285. List<LinkedChild> newShortcutLinks;
  1286. if (SupportsShortcutChildren)
  1287. {
  1288. newShortcutLinks = fileSystemChildren
  1289. .Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && FileSystem.IsShortcut(i.FullName))
  1290. .Select(i =>
  1291. {
  1292. try
  1293. {
  1294. Logger.Debug("Found shortcut at {0}", i.FullName);
  1295. var resolvedPath = FileSystem.ResolveShortcut(i.FullName);
  1296. if (!string.IsNullOrEmpty(resolvedPath))
  1297. {
  1298. return new LinkedChild
  1299. {
  1300. Path = resolvedPath,
  1301. Type = LinkedChildType.Shortcut
  1302. };
  1303. }
  1304. Logger.Error("Error resolving shortcut {0}", i.FullName);
  1305. return null;
  1306. }
  1307. catch (IOException ex)
  1308. {
  1309. Logger.ErrorException("Error resolving shortcut {0}", ex, i.FullName);
  1310. return null;
  1311. }
  1312. })
  1313. .Where(i => i != null)
  1314. .ToList();
  1315. }
  1316. else { newShortcutLinks = new List<LinkedChild>(); }
  1317. if (!newShortcutLinks.SequenceEqual(currentShortcutLinks, new LinkedChildComparer()))
  1318. {
  1319. Logger.Info("Shortcut links have changed for {0}", Path);
  1320. newShortcutLinks.AddRange(currentManualLinks);
  1321. LinkedChildren = newShortcutLinks;
  1322. return true;
  1323. }
  1324. foreach (var child in LinkedChildren)
  1325. {
  1326. // Reset the cached value
  1327. child.ItemId = null;
  1328. }
  1329. return false;
  1330. }
  1331. /// <summary>
  1332. /// Folders need to validate and refresh
  1333. /// </summary>
  1334. /// <returns>Task.</returns>
  1335. public override async Task ChangedExternally()
  1336. {
  1337. var progress = new Progress<double>();
  1338. await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false);
  1339. await base.ChangedExternally().ConfigureAwait(false);
  1340. }
  1341. /// <summary>
  1342. /// Marks the played.
  1343. /// </summary>
  1344. /// <param name="user">The user.</param>
  1345. /// <param name="datePlayed">The date played.</param>
  1346. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1347. /// <returns>Task.</returns>
  1348. public override async Task MarkPlayed(User user,
  1349. DateTime? datePlayed,
  1350. bool resetPosition)
  1351. {
  1352. var query = new InternalItemsQuery
  1353. {
  1354. User = user,
  1355. Recursive = true,
  1356. IsFolder = false,
  1357. IsUnaired = false
  1358. };
  1359. if (!user.Configuration.DisplayMissingEpisodes)
  1360. {
  1361. query.IsMissing = false;
  1362. }
  1363. var itemsResult = await GetItems(query).ConfigureAwait(false);
  1364. // Sweep through recursively and update status
  1365. var tasks = itemsResult.Items.Select(c => c.MarkPlayed(user, datePlayed, resetPosition));
  1366. await Task.WhenAll(tasks).ConfigureAwait(false);
  1367. }
  1368. /// <summary>
  1369. /// Marks the unplayed.
  1370. /// </summary>
  1371. /// <param name="user">The user.</param>
  1372. /// <returns>Task.</returns>
  1373. public override async Task MarkUnplayed(User user)
  1374. {
  1375. var itemsResult = await GetItems(new InternalItemsQuery
  1376. {
  1377. User = user,
  1378. Recursive = true,
  1379. IsFolder = false
  1380. }).ConfigureAwait(false);
  1381. // Sweep through recursively and update status
  1382. var tasks = itemsResult.Items.Select(c => c.MarkUnplayed(user));
  1383. await Task.WhenAll(tasks).ConfigureAwait(false);
  1384. }
  1385. /// <summary>
  1386. /// Finds an item by path, recursively
  1387. /// </summary>
  1388. /// <param name="path">The path.</param>
  1389. /// <returns>BaseItem.</returns>
  1390. /// <exception cref="System.ArgumentNullException"></exception>
  1391. public BaseItem FindByPath(string path)
  1392. {
  1393. if (string.IsNullOrEmpty(path))
  1394. {
  1395. throw new ArgumentNullException();
  1396. }
  1397. if (string.Equals(Path, path, StringComparison.OrdinalIgnoreCase))
  1398. {
  1399. return this;
  1400. }
  1401. if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1402. {
  1403. return this;
  1404. }
  1405. return GetRecursiveChildren(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) ||
  1406. (!i.IsFolder && !i.IsInMixedFolder && string.Equals(i.ContainingFolderPath, path, StringComparison.OrdinalIgnoreCase)) ||
  1407. i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
  1408. .FirstOrDefault();
  1409. }
  1410. public override bool IsPlayed(User user)
  1411. {
  1412. return GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual)
  1413. .All(i => i.IsPlayed(user));
  1414. }
  1415. public override bool IsUnplayed(User user)
  1416. {
  1417. return !IsPlayed(user);
  1418. }
  1419. public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1420. {
  1421. var recursiveItemCount = 0;
  1422. var unplayed = 0;
  1423. double totalPercentPlayed = 0;
  1424. IEnumerable<BaseItem> children;
  1425. var folder = this;
  1426. var season = folder as Season;
  1427. if (season != null)
  1428. {
  1429. children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
  1430. }
  1431. else
  1432. {
  1433. children = folder.GetRecursiveChildren(user, i => !i.IsFolder && i.LocationType != LocationType.Virtual);
  1434. }
  1435. // Loop through each recursive child
  1436. foreach (var child in children)
  1437. {
  1438. recursiveItemCount++;
  1439. var isUnplayed = true;
  1440. var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey());
  1441. // Incrememt totalPercentPlayed
  1442. if (itemUserData != null)
  1443. {
  1444. if (itemUserData.Played)
  1445. {
  1446. totalPercentPlayed += 100;
  1447. isUnplayed = false;
  1448. }
  1449. else if (itemUserData.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
  1450. {
  1451. double itemPercent = itemUserData.PlaybackPositionTicks;
  1452. itemPercent /= child.RunTimeTicks.Value;
  1453. totalPercentPlayed += itemPercent;
  1454. }
  1455. }
  1456. if (isUnplayed)
  1457. {
  1458. unplayed++;
  1459. }
  1460. }
  1461. dto.UnplayedItemCount = unplayed;
  1462. if (recursiveItemCount > 0)
  1463. {
  1464. dto.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
  1465. dto.Played = dto.PlayedPercentage.Value >= 100;
  1466. }
  1467. }
  1468. }
  1469. }