BaseItemRepository.cs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Text;
  9. using System.Threading;
  10. using Jellyfin.Data.Entities;
  11. using Jellyfin.Data.Enums;
  12. using Jellyfin.Extensions;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Entities.Audio;
  16. using MediaBrowser.Controller.Entities.TV;
  17. using MediaBrowser.Controller.LiveTv;
  18. using MediaBrowser.Controller.Persistence;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.LiveTv;
  22. using MediaBrowser.Model.Querying;
  23. using Microsoft.EntityFrameworkCore;
  24. using SQLitePCL;
  25. using BaseItemDto = MediaBrowser.Controller.Entities.BaseItem;
  26. using BaseItemEntity = Jellyfin.Data.Entities.BaseItemEntity;
  27. #pragma warning disable RS0030 // Do not use banned APIs
  28. namespace Jellyfin.Server.Implementations.Item;
  29. /// <summary>
  30. /// Handles all storage logic for BaseItems.
  31. /// </summary>
  32. /// <remarks>
  33. /// Initializes a new instance of the <see cref="BaseItemRepository"/> class.
  34. /// </remarks>
  35. /// <param name="dbProvider">The db factory.</param>
  36. /// <param name="appHost">The Application host.</param>
  37. /// <param name="itemTypeLookup">The static type lookup.</param>
  38. public sealed class BaseItemRepository(IDbContextFactory<JellyfinDbContext> dbProvider, IServerApplicationHost appHost, IItemTypeLookup itemTypeLookup)
  39. : IItemRepository, IDisposable
  40. {
  41. /// <summary>
  42. /// This holds all the types in the running assemblies
  43. /// so that we can de-serialize properly when we don't have strong types.
  44. /// </summary>
  45. private static readonly ConcurrentDictionary<string, Type?> _typeMap = new ConcurrentDictionary<string, Type?>();
  46. private bool _disposed;
  47. /// <inheritdoc/>
  48. public void Dispose()
  49. {
  50. if (_disposed)
  51. {
  52. return;
  53. }
  54. _disposed = true;
  55. }
  56. /// <inheritdoc />
  57. public void DeleteItem(Guid id)
  58. {
  59. ArgumentNullException.ThrowIfNull(id.IsEmpty() ? null : id);
  60. using var context = dbProvider.CreateDbContext();
  61. using var transaction = context.Database.BeginTransaction();
  62. context.Peoples.Where(e => e.ItemId == id).ExecuteDelete();
  63. context.Chapters.Where(e => e.ItemId == id).ExecuteDelete();
  64. context.MediaStreamInfos.Where(e => e.ItemId == id).ExecuteDelete();
  65. context.AncestorIds.Where(e => e.ItemId == id).ExecuteDelete();
  66. context.ItemValuesMap.Where(e => e.ItemId == id).ExecuteDelete();
  67. context.ItemValues.Where(e => e.BaseItemsMap!.Count == 0).ExecuteDelete();
  68. context.BaseItemImageInfos.Where(e => e.ItemId == id).ExecuteDelete();
  69. context.BaseItemProviders.Where(e => e.ItemId == id).ExecuteDelete();
  70. context.BaseItems.Where(e => e.Id == id).ExecuteDelete();
  71. context.SaveChanges();
  72. transaction.Commit();
  73. }
  74. /// <inheritdoc />
  75. public void UpdateInheritedValues()
  76. {
  77. using var context = dbProvider.CreateDbContext();
  78. using var transaction = context.Database.BeginTransaction();
  79. context.ItemValuesMap.Where(e => e.ItemValue.Type == ItemValueType.InheritedTags).ExecuteDelete();
  80. // ItemValue Inheritence is now correctly mapped via AncestorId on demand
  81. context.SaveChanges();
  82. transaction.Commit();
  83. }
  84. /// <inheritdoc cref="IItemRepository"/>
  85. public IReadOnlyList<Guid> GetItemIdsList(InternalItemsQuery filter)
  86. {
  87. ArgumentNullException.ThrowIfNull(filter);
  88. PrepareFilterQuery(filter);
  89. using var context = dbProvider.CreateDbContext();
  90. var dbQuery = TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
  91. // .DistinctBy(e => e.Id);
  92. var enableGroupByPresentationUniqueKey = EnableGroupByPresentationUniqueKey(filter);
  93. if (enableGroupByPresentationUniqueKey && filter.GroupBySeriesPresentationUniqueKey)
  94. {
  95. dbQuery = dbQuery.GroupBy(e => new { e.PresentationUniqueKey, e.SeriesPresentationUniqueKey }).SelectMany(e => e);
  96. }
  97. if (enableGroupByPresentationUniqueKey)
  98. {
  99. dbQuery = dbQuery.GroupBy(e => e.PresentationUniqueKey).SelectMany(e => e);
  100. }
  101. if (filter.GroupBySeriesPresentationUniqueKey)
  102. {
  103. dbQuery = dbQuery.GroupBy(e => e.SeriesPresentationUniqueKey).SelectMany(e => e);
  104. }
  105. dbQuery = ApplyOrder(dbQuery, filter);
  106. return Pageinate(dbQuery, filter).Select(e => e.Id).ToImmutableArray();
  107. }
  108. /// <inheritdoc />
  109. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery filter)
  110. {
  111. return GetItemValues(filter, [0, 1], typeof(MusicArtist).FullName!);
  112. }
  113. /// <inheritdoc />
  114. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery filter)
  115. {
  116. return GetItemValues(filter, [0], typeof(MusicArtist).FullName!);
  117. }
  118. /// <inheritdoc />
  119. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery filter)
  120. {
  121. return GetItemValues(filter, [1], typeof(MusicArtist).FullName!);
  122. }
  123. /// <inheritdoc />
  124. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery filter)
  125. {
  126. return GetItemValues(filter, [3], typeof(Studio).FullName!);
  127. }
  128. /// <inheritdoc />
  129. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery filter)
  130. {
  131. return GetItemValues(filter, [2], typeof(Genre).FullName!);
  132. }
  133. /// <inheritdoc />
  134. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery filter)
  135. {
  136. return GetItemValues(filter, [2], typeof(MusicGenre).FullName!);
  137. }
  138. /// <inheritdoc />
  139. public IReadOnlyList<string> GetStudioNames()
  140. {
  141. return GetItemValueNames([3], Array.Empty<string>(), Array.Empty<string>());
  142. }
  143. /// <inheritdoc />
  144. public IReadOnlyList<string> GetAllArtistNames()
  145. {
  146. return GetItemValueNames([0, 1], Array.Empty<string>(), Array.Empty<string>());
  147. }
  148. /// <inheritdoc />
  149. public IReadOnlyList<string> GetMusicGenreNames()
  150. {
  151. return GetItemValueNames(
  152. [2],
  153. new string[]
  154. {
  155. typeof(Audio).FullName!,
  156. typeof(MusicVideo).FullName!,
  157. typeof(MusicAlbum).FullName!,
  158. typeof(MusicArtist).FullName!
  159. },
  160. Array.Empty<string>());
  161. }
  162. /// <inheritdoc />
  163. public IReadOnlyList<string> GetGenreNames()
  164. {
  165. return GetItemValueNames(
  166. [2],
  167. Array.Empty<string>(),
  168. new string[]
  169. {
  170. typeof(Audio).FullName!,
  171. typeof(MusicVideo).FullName!,
  172. typeof(MusicAlbum).FullName!,
  173. typeof(MusicArtist).FullName!
  174. });
  175. }
  176. /// <inheritdoc cref="IItemRepository"/>
  177. public QueryResult<BaseItemDto> GetItems(InternalItemsQuery filter)
  178. {
  179. ArgumentNullException.ThrowIfNull(filter);
  180. if (!filter.EnableTotalRecordCount || (!filter.Limit.HasValue && (filter.StartIndex ?? 0) == 0))
  181. {
  182. var returnList = GetItemList(filter);
  183. return new QueryResult<BaseItemDto>(
  184. filter.StartIndex,
  185. returnList.Count,
  186. returnList);
  187. }
  188. PrepareFilterQuery(filter);
  189. var result = new QueryResult<BaseItemDto>();
  190. using var context = dbProvider.CreateDbContext();
  191. IQueryable<BaseItemEntity> dbQuery = context.BaseItems.AsNoTracking()
  192. .Include(e => e.ExtraType)
  193. .Include(e => e.TrailerTypes)
  194. .Include(e => e.Images)
  195. .Include(e => e.LockedFields);
  196. dbQuery = TranslateQuery(dbQuery, context, filter)
  197. .DistinctBy(e => e.Id);
  198. if (filter.EnableTotalRecordCount)
  199. {
  200. result.TotalRecordCount = dbQuery.Count();
  201. }
  202. if (filter.Limit.HasValue || filter.StartIndex.HasValue)
  203. {
  204. var offset = filter.StartIndex ?? 0;
  205. if (offset > 0)
  206. {
  207. dbQuery = dbQuery.Skip(offset);
  208. }
  209. if (filter.Limit.HasValue)
  210. {
  211. dbQuery = dbQuery.Take(filter.Limit.Value);
  212. }
  213. }
  214. result.Items = dbQuery.ToList().Select(DeserialiseBaseItem).ToImmutableArray();
  215. result.StartIndex = filter.StartIndex ?? 0;
  216. return result;
  217. }
  218. /// <inheritdoc cref="IItemRepository"/>
  219. public IReadOnlyList<BaseItemDto> GetItemList(InternalItemsQuery filter)
  220. {
  221. ArgumentNullException.ThrowIfNull(filter);
  222. PrepareFilterQuery(filter);
  223. using var context = dbProvider.CreateDbContext();
  224. var dbQuery = TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
  225. if (filter.Limit.HasValue || filter.StartIndex.HasValue)
  226. {
  227. var offset = filter.StartIndex ?? 0;
  228. if (offset > 0)
  229. {
  230. dbQuery = dbQuery.Skip(offset);
  231. }
  232. if (filter.Limit.HasValue)
  233. {
  234. dbQuery = dbQuery.Take(filter.Limit.Value);
  235. }
  236. }
  237. return dbQuery.ToList().Select(DeserialiseBaseItem).ToImmutableArray();
  238. }
  239. /// <inheritdoc/>
  240. public int GetCount(InternalItemsQuery filter)
  241. {
  242. ArgumentNullException.ThrowIfNull(filter);
  243. // Hack for right now since we currently don't support filtering out these duplicates within a query
  244. PrepareFilterQuery(filter);
  245. using var context = dbProvider.CreateDbContext();
  246. var dbQuery = TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
  247. return dbQuery.Count();
  248. }
  249. #pragma warning disable CA1307 // Specify StringComparison for clarity
  250. private IQueryable<BaseItemEntity> TranslateQuery(
  251. IQueryable<BaseItemEntity> baseQuery,
  252. JellyfinDbContext context,
  253. InternalItemsQuery filter)
  254. {
  255. var minWidth = filter.MinWidth;
  256. var maxWidth = filter.MaxWidth;
  257. var now = DateTime.UtcNow;
  258. if (filter.IsHD.HasValue)
  259. {
  260. const int Threshold = 1200;
  261. if (filter.IsHD.Value)
  262. {
  263. minWidth = Threshold;
  264. }
  265. else
  266. {
  267. maxWidth = Threshold - 1;
  268. }
  269. }
  270. if (filter.Is4K.HasValue)
  271. {
  272. const int Threshold = 3800;
  273. if (filter.Is4K.Value)
  274. {
  275. minWidth = Threshold;
  276. }
  277. else
  278. {
  279. maxWidth = Threshold - 1;
  280. }
  281. }
  282. if (minWidth.HasValue)
  283. {
  284. baseQuery = baseQuery.Where(e => e.Width >= minWidth);
  285. }
  286. if (filter.MinHeight.HasValue)
  287. {
  288. baseQuery = baseQuery.Where(e => e.Height >= filter.MinHeight);
  289. }
  290. if (maxWidth.HasValue)
  291. {
  292. baseQuery = baseQuery.Where(e => e.Width >= maxWidth);
  293. }
  294. if (filter.MaxHeight.HasValue)
  295. {
  296. baseQuery = baseQuery.Where(e => e.Height <= filter.MaxHeight);
  297. }
  298. if (filter.IsLocked.HasValue)
  299. {
  300. baseQuery = baseQuery.Where(e => e.IsLocked == filter.IsLocked);
  301. }
  302. var tags = filter.Tags.ToList();
  303. var excludeTags = filter.ExcludeTags.ToList();
  304. if (filter.IsMovie == true)
  305. {
  306. if (filter.IncludeItemTypes.Length == 0
  307. || filter.IncludeItemTypes.Contains(BaseItemKind.Movie)
  308. || filter.IncludeItemTypes.Contains(BaseItemKind.Trailer))
  309. {
  310. baseQuery = baseQuery.Where(e => e.IsMovie);
  311. }
  312. }
  313. else if (filter.IsMovie.HasValue)
  314. {
  315. baseQuery = baseQuery.Where(e => e.IsMovie == filter.IsMovie);
  316. }
  317. if (filter.IsSeries.HasValue)
  318. {
  319. baseQuery = baseQuery.Where(e => e.IsSeries == filter.IsSeries);
  320. }
  321. if (filter.IsSports.HasValue)
  322. {
  323. if (filter.IsSports.Value)
  324. {
  325. tags.Add("Sports");
  326. }
  327. else
  328. {
  329. excludeTags.Add("Sports");
  330. }
  331. }
  332. if (filter.IsNews.HasValue)
  333. {
  334. if (filter.IsNews.Value)
  335. {
  336. tags.Add("News");
  337. }
  338. else
  339. {
  340. excludeTags.Add("News");
  341. }
  342. }
  343. if (filter.IsKids.HasValue)
  344. {
  345. if (filter.IsKids.Value)
  346. {
  347. tags.Add("Kids");
  348. }
  349. else
  350. {
  351. excludeTags.Add("Kids");
  352. }
  353. }
  354. if (!string.IsNullOrEmpty(filter.SearchTerm))
  355. {
  356. baseQuery = baseQuery.Where(e => e.CleanName!.Contains(filter.SearchTerm) || (e.OriginalTitle != null && e.OriginalTitle.Contains(filter.SearchTerm)));
  357. }
  358. if (filter.IsFolder.HasValue)
  359. {
  360. baseQuery = baseQuery.Where(e => e.IsFolder == filter.IsFolder);
  361. }
  362. var includeTypes = filter.IncludeItemTypes;
  363. // Only specify excluded types if no included types are specified
  364. if (filter.IncludeItemTypes.Length == 0)
  365. {
  366. var excludeTypes = filter.ExcludeItemTypes;
  367. if (excludeTypes.Length == 1)
  368. {
  369. if (itemTypeLookup.BaseItemKindNames.TryGetValue(excludeTypes[0], out var excludeTypeName))
  370. {
  371. baseQuery = baseQuery.Where(e => e.Type != excludeTypeName);
  372. }
  373. }
  374. else if (excludeTypes.Length > 1)
  375. {
  376. var excludeTypeName = new List<string>();
  377. foreach (var excludeType in excludeTypes)
  378. {
  379. if (itemTypeLookup.BaseItemKindNames.TryGetValue(excludeType, out var baseItemKindName))
  380. {
  381. excludeTypeName.Add(baseItemKindName!);
  382. }
  383. }
  384. baseQuery = baseQuery.Where(e => !excludeTypeName.Contains(e.Type));
  385. }
  386. }
  387. else if (includeTypes.Length == 1)
  388. {
  389. if (itemTypeLookup.BaseItemKindNames.TryGetValue(includeTypes[0], out var includeTypeName))
  390. {
  391. baseQuery = baseQuery.Where(e => e.Type == includeTypeName);
  392. }
  393. }
  394. else if (includeTypes.Length > 1)
  395. {
  396. var includeTypeName = new List<string>();
  397. foreach (var includeType in includeTypes)
  398. {
  399. if (itemTypeLookup.BaseItemKindNames.TryGetValue(includeType, out var baseItemKindName))
  400. {
  401. includeTypeName.Add(baseItemKindName!);
  402. }
  403. }
  404. baseQuery = baseQuery.Where(e => includeTypeName.Contains(e.Type));
  405. }
  406. if (filter.ChannelIds.Count > 0)
  407. {
  408. var channelIds = filter.ChannelIds.Select(e => e.ToString("N", CultureInfo.InvariantCulture)).ToArray();
  409. baseQuery = baseQuery.Where(e => channelIds.Contains(e.ChannelId));
  410. }
  411. if (!filter.ParentId.IsEmpty())
  412. {
  413. baseQuery = baseQuery.Where(e => e.ParentId!.Value == filter.ParentId);
  414. }
  415. if (!string.IsNullOrWhiteSpace(filter.Path))
  416. {
  417. baseQuery = baseQuery.Where(e => e.Path == filter.Path);
  418. }
  419. if (!string.IsNullOrWhiteSpace(filter.PresentationUniqueKey))
  420. {
  421. baseQuery = baseQuery.Where(e => e.PresentationUniqueKey == filter.PresentationUniqueKey);
  422. }
  423. if (filter.MinCommunityRating.HasValue)
  424. {
  425. baseQuery = baseQuery.Where(e => e.CommunityRating >= filter.MinCommunityRating);
  426. }
  427. if (filter.MinIndexNumber.HasValue)
  428. {
  429. baseQuery = baseQuery.Where(e => e.IndexNumber >= filter.MinIndexNumber);
  430. }
  431. if (filter.MinParentAndIndexNumber.HasValue)
  432. {
  433. baseQuery = baseQuery
  434. .Where(e => (e.ParentIndexNumber == filter.MinParentAndIndexNumber.Value.ParentIndexNumber && e.IndexNumber >= filter.MinParentAndIndexNumber.Value.IndexNumber) || e.ParentIndexNumber > filter.MinParentAndIndexNumber.Value.ParentIndexNumber);
  435. }
  436. if (filter.MinDateCreated.HasValue)
  437. {
  438. baseQuery = baseQuery.Where(e => e.DateCreated >= filter.MinDateCreated);
  439. }
  440. if (filter.MinDateLastSaved.HasValue)
  441. {
  442. baseQuery = baseQuery.Where(e => e.DateLastSaved != null && e.DateLastSaved >= filter.MinDateLastSaved.Value);
  443. }
  444. if (filter.MinDateLastSavedForUser.HasValue)
  445. {
  446. baseQuery = baseQuery.Where(e => e.DateLastSaved != null && e.DateLastSaved >= filter.MinDateLastSavedForUser.Value);
  447. }
  448. if (filter.IndexNumber.HasValue)
  449. {
  450. baseQuery = baseQuery.Where(e => e.IndexNumber == filter.IndexNumber.Value);
  451. }
  452. if (filter.ParentIndexNumber.HasValue)
  453. {
  454. baseQuery = baseQuery.Where(e => e.ParentIndexNumber == filter.ParentIndexNumber.Value);
  455. }
  456. if (filter.ParentIndexNumberNotEquals.HasValue)
  457. {
  458. baseQuery = baseQuery.Where(e => e.ParentIndexNumber != filter.ParentIndexNumberNotEquals.Value || e.ParentIndexNumber == null);
  459. }
  460. var minEndDate = filter.MinEndDate;
  461. var maxEndDate = filter.MaxEndDate;
  462. if (filter.HasAired.HasValue)
  463. {
  464. if (filter.HasAired.Value)
  465. {
  466. maxEndDate = DateTime.UtcNow;
  467. }
  468. else
  469. {
  470. minEndDate = DateTime.UtcNow;
  471. }
  472. }
  473. if (minEndDate.HasValue)
  474. {
  475. baseQuery = baseQuery.Where(e => e.EndDate >= minEndDate);
  476. }
  477. if (maxEndDate.HasValue)
  478. {
  479. baseQuery = baseQuery.Where(e => e.EndDate <= maxEndDate);
  480. }
  481. if (filter.MinStartDate.HasValue)
  482. {
  483. baseQuery = baseQuery.Where(e => e.StartDate >= filter.MinStartDate.Value);
  484. }
  485. if (filter.MaxStartDate.HasValue)
  486. {
  487. baseQuery = baseQuery.Where(e => e.StartDate <= filter.MaxStartDate.Value);
  488. }
  489. if (filter.MinPremiereDate.HasValue)
  490. {
  491. baseQuery = baseQuery.Where(e => e.PremiereDate <= filter.MinPremiereDate.Value);
  492. }
  493. if (filter.MaxPremiereDate.HasValue)
  494. {
  495. baseQuery = baseQuery.Where(e => e.PremiereDate <= filter.MaxPremiereDate.Value);
  496. }
  497. if (filter.TrailerTypes.Length > 0)
  498. {
  499. var trailerTypes = filter.TrailerTypes.Select(e => (int)e).ToArray();
  500. baseQuery = baseQuery.Where(e => trailerTypes.Any(f => e.TrailerTypes!.Any(w => w.Id == f)));
  501. }
  502. if (filter.IsAiring.HasValue)
  503. {
  504. if (filter.IsAiring.Value)
  505. {
  506. baseQuery = baseQuery.Where(e => e.StartDate <= now && e.EndDate >= now);
  507. }
  508. else
  509. {
  510. baseQuery = baseQuery.Where(e => e.StartDate > now && e.EndDate < now);
  511. }
  512. }
  513. if (filter.PersonIds.Length > 0)
  514. {
  515. baseQuery = baseQuery
  516. .Where(e =>
  517. context.Peoples.Where(w => context.BaseItems.Where(w => filter.PersonIds.Contains(w.Id)).Any(f => f.Name == w.Name))
  518. .Any(f => f.ItemId == e.Id));
  519. }
  520. if (!string.IsNullOrWhiteSpace(filter.Person))
  521. {
  522. baseQuery = baseQuery.Where(e => e.Peoples!.Any(f => f.Name == filter.Person));
  523. }
  524. if (!string.IsNullOrWhiteSpace(filter.MinSortName))
  525. {
  526. // this does not makes sense.
  527. // baseQuery = baseQuery.Where(e => e.SortName >= query.MinSortName);
  528. // whereClauses.Add("SortName>=@MinSortName");
  529. // statement?.TryBind("@MinSortName", query.MinSortName);
  530. }
  531. if (!string.IsNullOrWhiteSpace(filter.ExternalSeriesId))
  532. {
  533. baseQuery = baseQuery.Where(e => e.ExternalSeriesId == filter.ExternalSeriesId);
  534. }
  535. if (!string.IsNullOrWhiteSpace(filter.ExternalId))
  536. {
  537. baseQuery = baseQuery.Where(e => e.ExternalId == filter.ExternalId);
  538. }
  539. if (!string.IsNullOrWhiteSpace(filter.Name))
  540. {
  541. var cleanName = GetCleanValue(filter.Name);
  542. baseQuery = baseQuery.Where(e => e.CleanName == cleanName);
  543. }
  544. // These are the same, for now
  545. var nameContains = filter.NameContains;
  546. if (!string.IsNullOrWhiteSpace(nameContains))
  547. {
  548. baseQuery = baseQuery.Where(e =>
  549. e.CleanName == filter.NameContains
  550. || e.OriginalTitle!.Contains(filter.NameContains!));
  551. }
  552. if (!string.IsNullOrWhiteSpace(filter.NameStartsWith))
  553. {
  554. baseQuery = baseQuery.Where(e => e.SortName!.Contains(filter.NameStartsWith));
  555. }
  556. if (!string.IsNullOrWhiteSpace(filter.NameStartsWithOrGreater))
  557. {
  558. // i hate this
  559. baseQuery = baseQuery.Where(e => e.SortName![0] > filter.NameStartsWithOrGreater[0]);
  560. }
  561. if (!string.IsNullOrWhiteSpace(filter.NameLessThan))
  562. {
  563. // i hate this
  564. baseQuery = baseQuery.Where(e => e.SortName![0] < filter.NameLessThan[0]);
  565. }
  566. if (filter.ImageTypes.Length > 0)
  567. {
  568. var imgTypes = filter.ImageTypes.Select(e => (ImageInfoImageType)e).ToArray();
  569. baseQuery = baseQuery.Where(e => imgTypes.Any(f => e.Images!.Any(w => w.ImageType == f)));
  570. }
  571. if (filter.IsLiked.HasValue)
  572. {
  573. baseQuery = baseQuery
  574. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.Rating >= UserItemData.MinLikeValue);
  575. }
  576. if (filter.IsFavoriteOrLiked.HasValue)
  577. {
  578. baseQuery = baseQuery
  579. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.IsFavorite == filter.IsFavoriteOrLiked);
  580. }
  581. if (filter.IsFavorite.HasValue)
  582. {
  583. baseQuery = baseQuery
  584. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.IsFavorite == filter.IsFavorite);
  585. }
  586. if (filter.IsPlayed.HasValue)
  587. {
  588. baseQuery = baseQuery
  589. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.Played == filter.IsPlayed.Value);
  590. }
  591. if (filter.IsResumable.HasValue)
  592. {
  593. if (filter.IsResumable.Value)
  594. {
  595. baseQuery = baseQuery
  596. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.PlaybackPositionTicks > 0);
  597. }
  598. else
  599. {
  600. baseQuery = baseQuery
  601. .Where(e => e.UserData!.FirstOrDefault(f => f.UserId == filter.User!.Id && f.Key == e.UserDataKey)!.PlaybackPositionTicks == 0);
  602. }
  603. }
  604. if (filter.ArtistIds.Length > 0)
  605. {
  606. baseQuery = baseQuery
  607. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type <= ItemValueType.Artist && filter.ArtistIds.Contains(f.ItemId)));
  608. }
  609. if (filter.AlbumArtistIds.Length > 0)
  610. {
  611. baseQuery = baseQuery
  612. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.AlbumArtistIds.Contains(f.ItemId)));
  613. }
  614. if (filter.ContributingArtistIds.Length > 0)
  615. {
  616. baseQuery = baseQuery
  617. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.ContributingArtistIds.Contains(f.ItemId)));
  618. }
  619. if (filter.AlbumIds.Length > 0)
  620. {
  621. baseQuery = baseQuery.Where(e => context.BaseItems.Where(e => filter.AlbumIds.Contains(e.Id)).Any(f => f.Name == e.Album));
  622. }
  623. if (filter.ExcludeArtistIds.Length > 0)
  624. {
  625. baseQuery = baseQuery
  626. .Where(e => !e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Artist && filter.ExcludeArtistIds.Contains(f.ItemId)));
  627. }
  628. if (filter.GenreIds.Count > 0)
  629. {
  630. baseQuery = baseQuery
  631. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Genre && filter.GenreIds.Contains(f.ItemId)));
  632. }
  633. if (filter.Genres.Count > 0)
  634. {
  635. var cleanGenres = filter.Genres.Select(e => GetCleanValue(e)).ToArray();
  636. baseQuery = baseQuery
  637. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Genre && cleanGenres.Contains(f.ItemValue.CleanValue)));
  638. }
  639. if (tags.Count > 0)
  640. {
  641. var cleanValues = tags.Select(e => GetCleanValue(e)).ToArray();
  642. baseQuery = baseQuery
  643. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Tags && cleanValues.Contains(f.ItemValue.CleanValue)));
  644. }
  645. if (excludeTags.Count > 0)
  646. {
  647. var cleanValues = excludeTags.Select(e => GetCleanValue(e)).ToArray();
  648. baseQuery = baseQuery
  649. .Where(e => !e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Tags && cleanValues.Contains(f.ItemValue.CleanValue)));
  650. }
  651. if (filter.StudioIds.Length > 0)
  652. {
  653. baseQuery = baseQuery
  654. .Where(e => e.ItemValues!.Any(f => f.ItemValue.Type == ItemValueType.Studios && filter.StudioIds.Contains(f.ItemId)));
  655. }
  656. if (filter.OfficialRatings.Length > 0)
  657. {
  658. baseQuery = baseQuery
  659. .Where(e => filter.OfficialRatings.Contains(e.OfficialRating));
  660. }
  661. if (filter.HasParentalRating ?? false)
  662. {
  663. if (filter.MinParentalRating.HasValue)
  664. {
  665. baseQuery = baseQuery
  666. .Where(e => e.InheritedParentalRatingValue >= filter.MinParentalRating.Value);
  667. }
  668. if (filter.MaxParentalRating.HasValue)
  669. {
  670. baseQuery = baseQuery
  671. .Where(e => e.InheritedParentalRatingValue < filter.MaxParentalRating.Value);
  672. }
  673. }
  674. else if (filter.BlockUnratedItems.Length > 0)
  675. {
  676. if (filter.MinParentalRating.HasValue)
  677. {
  678. if (filter.MaxParentalRating.HasValue)
  679. {
  680. baseQuery = baseQuery
  681. .Where(e => (e.InheritedParentalRatingValue == null && !filter.BlockUnratedItems.Select(e => e.ToString()).Contains(e.UnratedType))
  682. || (e.InheritedParentalRatingValue >= filter.MinParentalRating && e.InheritedParentalRatingValue <= filter.MaxParentalRating));
  683. }
  684. else
  685. {
  686. baseQuery = baseQuery
  687. .Where(e => (e.InheritedParentalRatingValue == null && !filter.BlockUnratedItems.Select(e => e.ToString()).Contains(e.UnratedType))
  688. || e.InheritedParentalRatingValue >= filter.MinParentalRating);
  689. }
  690. }
  691. else
  692. {
  693. baseQuery = baseQuery
  694. .Where(e => e.InheritedParentalRatingValue != null && !filter.BlockUnratedItems.Select(e => e.ToString()).Contains(e.UnratedType));
  695. }
  696. }
  697. else if (filter.MinParentalRating.HasValue)
  698. {
  699. if (filter.MaxParentalRating.HasValue)
  700. {
  701. baseQuery = baseQuery
  702. .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MinParentalRating.Value && e.InheritedParentalRatingValue <= filter.MaxParentalRating.Value);
  703. }
  704. else
  705. {
  706. baseQuery = baseQuery
  707. .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MinParentalRating.Value);
  708. }
  709. }
  710. else if (filter.MaxParentalRating.HasValue)
  711. {
  712. baseQuery = baseQuery
  713. .Where(e => e.InheritedParentalRatingValue != null && e.InheritedParentalRatingValue >= filter.MaxParentalRating.Value);
  714. }
  715. else if (!filter.HasParentalRating ?? false)
  716. {
  717. baseQuery = baseQuery
  718. .Where(e => e.InheritedParentalRatingValue == null);
  719. }
  720. if (filter.HasOfficialRating.HasValue)
  721. {
  722. if (filter.HasOfficialRating.Value)
  723. {
  724. baseQuery = baseQuery
  725. .Where(e => e.OfficialRating != null && e.OfficialRating != string.Empty);
  726. }
  727. else
  728. {
  729. baseQuery = baseQuery
  730. .Where(e => e.OfficialRating == null || e.OfficialRating == string.Empty);
  731. }
  732. }
  733. if (filter.HasOverview.HasValue)
  734. {
  735. if (filter.HasOverview.Value)
  736. {
  737. baseQuery = baseQuery
  738. .Where(e => e.Overview != null && e.Overview != string.Empty);
  739. }
  740. else
  741. {
  742. baseQuery = baseQuery
  743. .Where(e => e.Overview == null || e.Overview == string.Empty);
  744. }
  745. }
  746. if (filter.HasOwnerId.HasValue)
  747. {
  748. if (filter.HasOwnerId.Value)
  749. {
  750. baseQuery = baseQuery
  751. .Where(e => e.OwnerId != null);
  752. }
  753. else
  754. {
  755. baseQuery = baseQuery
  756. .Where(e => e.OwnerId == null);
  757. }
  758. }
  759. if (!string.IsNullOrWhiteSpace(filter.HasNoAudioTrackWithLanguage))
  760. {
  761. baseQuery = baseQuery
  762. .Where(e => !e.MediaStreams!.Any(e => e.StreamType == MediaStreamTypeEntity.Audio && e.Language == filter.HasNoAudioTrackWithLanguage));
  763. }
  764. if (!string.IsNullOrWhiteSpace(filter.HasNoInternalSubtitleTrackWithLanguage))
  765. {
  766. baseQuery = baseQuery
  767. .Where(e => !e.MediaStreams!.Any(e => e.StreamType == MediaStreamTypeEntity.Subtitle && !e.IsExternal && e.Language == filter.HasNoInternalSubtitleTrackWithLanguage));
  768. }
  769. if (!string.IsNullOrWhiteSpace(filter.HasNoExternalSubtitleTrackWithLanguage))
  770. {
  771. baseQuery = baseQuery
  772. .Where(e => !e.MediaStreams!.Any(e => e.StreamType == MediaStreamTypeEntity.Subtitle && e.IsExternal && e.Language == filter.HasNoExternalSubtitleTrackWithLanguage));
  773. }
  774. if (!string.IsNullOrWhiteSpace(filter.HasNoSubtitleTrackWithLanguage))
  775. {
  776. baseQuery = baseQuery
  777. .Where(e => !e.MediaStreams!.Any(e => e.StreamType == MediaStreamTypeEntity.Subtitle && e.Language == filter.HasNoSubtitleTrackWithLanguage));
  778. }
  779. if (filter.HasSubtitles.HasValue)
  780. {
  781. baseQuery = baseQuery
  782. .Where(e => e.MediaStreams!.Any(e => e.StreamType == MediaStreamTypeEntity.Subtitle) == filter.HasSubtitles.Value);
  783. }
  784. if (filter.HasChapterImages.HasValue)
  785. {
  786. baseQuery = baseQuery
  787. .Where(e => e.Chapters!.Any(e => e.ImagePath != null) == filter.HasChapterImages.Value);
  788. }
  789. if (filter.HasDeadParentId.HasValue && filter.HasDeadParentId.Value)
  790. {
  791. baseQuery = baseQuery
  792. .Where(e => e.ParentId.HasValue && !context.BaseItems.Any(f => f.Id == e.ParentId.Value));
  793. }
  794. if (filter.IsDeadArtist.HasValue && filter.IsDeadArtist.Value)
  795. {
  796. baseQuery = baseQuery
  797. .Where(e => e.ItemValues!.Count(f => (f.ItemValue.Type == ItemValueType.Artist || f.ItemValue.Type == ItemValueType.AlbumArtist)) == 1);
  798. }
  799. if (filter.IsDeadStudio.HasValue && filter.IsDeadStudio.Value)
  800. {
  801. baseQuery = baseQuery
  802. .Where(e => e.ItemValues!.Count(f => f.ItemValue.Type == ItemValueType.Studios) == 1);
  803. }
  804. if (filter.IsDeadPerson.HasValue && filter.IsDeadPerson.Value)
  805. {
  806. baseQuery = baseQuery
  807. .Where(e => !e.Peoples!.Any(f => f.Name == e.Name));
  808. }
  809. if (filter.Years.Length == 1)
  810. {
  811. baseQuery = baseQuery
  812. .Where(e => e.ProductionYear == filter.Years[0]);
  813. }
  814. else if (filter.Years.Length > 1)
  815. {
  816. baseQuery = baseQuery
  817. .Where(e => filter.Years.Any(f => f == e.ProductionYear));
  818. }
  819. var isVirtualItem = filter.IsVirtualItem ?? filter.IsMissing;
  820. if (isVirtualItem.HasValue)
  821. {
  822. baseQuery = baseQuery
  823. .Where(e => e.IsVirtualItem == isVirtualItem.Value);
  824. }
  825. if (filter.IsSpecialSeason.HasValue)
  826. {
  827. if (filter.IsSpecialSeason.Value)
  828. {
  829. baseQuery = baseQuery
  830. .Where(e => e.IndexNumber == 0);
  831. }
  832. else
  833. {
  834. baseQuery = baseQuery
  835. .Where(e => e.IndexNumber != 0);
  836. }
  837. }
  838. if (filter.IsUnaired.HasValue)
  839. {
  840. if (filter.IsUnaired.Value)
  841. {
  842. baseQuery = baseQuery
  843. .Where(e => e.PremiereDate >= now);
  844. }
  845. else
  846. {
  847. baseQuery = baseQuery
  848. .Where(e => e.PremiereDate < now);
  849. }
  850. }
  851. if (filter.MediaTypes.Length == 1)
  852. {
  853. baseQuery = baseQuery
  854. .Where(e => e.MediaType == filter.MediaTypes[0].ToString());
  855. }
  856. else if (filter.MediaTypes.Length > 1)
  857. {
  858. baseQuery = baseQuery
  859. .Where(e => filter.MediaTypes.Select(f => f.ToString()).Contains(e.MediaType));
  860. }
  861. if (filter.ItemIds.Length > 0)
  862. {
  863. baseQuery = baseQuery
  864. .Where(e => filter.ItemIds.Contains(e.Id));
  865. }
  866. if (filter.ExcludeItemIds.Length > 0)
  867. {
  868. baseQuery = baseQuery
  869. .Where(e => !filter.ItemIds.Contains(e.Id));
  870. }
  871. if (filter.ExcludeProviderIds is not null && filter.ExcludeProviderIds.Count > 0)
  872. {
  873. baseQuery = baseQuery.Where(e => !e.Provider!.All(f => !filter.ExcludeProviderIds.All(w => f.ProviderId == w.Key && f.ProviderValue == w.Value)));
  874. }
  875. if (filter.HasAnyProviderId is not null && filter.HasAnyProviderId.Count > 0)
  876. {
  877. baseQuery = baseQuery.Where(e => e.Provider!.Any(f => !filter.HasAnyProviderId.Any(w => f.ProviderId == w.Key && f.ProviderValue == w.Value)));
  878. }
  879. if (filter.HasImdbId.HasValue)
  880. {
  881. baseQuery = baseQuery.Where(e => e.Provider!.Any(f => f.ProviderId == "imdb"));
  882. }
  883. if (filter.HasTmdbId.HasValue)
  884. {
  885. baseQuery = baseQuery.Where(e => e.Provider!.Any(f => f.ProviderId == "tmdb"));
  886. }
  887. if (filter.HasTvdbId.HasValue)
  888. {
  889. baseQuery = baseQuery.Where(e => e.Provider!.Any(f => f.ProviderId == "tvdb"));
  890. }
  891. var queryTopParentIds = filter.TopParentIds;
  892. if (queryTopParentIds.Length > 0)
  893. {
  894. var includedItemByNameTypes = GetItemByNameTypesInQuery(filter);
  895. var enableItemsByName = (filter.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0;
  896. if (enableItemsByName && includedItemByNameTypes.Count > 0)
  897. {
  898. baseQuery = baseQuery.Where(e => includedItemByNameTypes.Contains(e.Type) || queryTopParentIds.Any(w => w == e.TopParentId!.Value));
  899. }
  900. else
  901. {
  902. baseQuery = baseQuery.Where(e => queryTopParentIds.Any(w => w == e.TopParentId!.Value));
  903. }
  904. }
  905. if (filter.AncestorIds.Length > 0)
  906. {
  907. baseQuery = baseQuery.Where(e => e.AncestorIds!.Any(f => filter.AncestorIds.Contains(f.ParentItemId)));
  908. }
  909. if (!string.IsNullOrWhiteSpace(filter.AncestorWithPresentationUniqueKey))
  910. {
  911. baseQuery = baseQuery
  912. .Where(e => context.BaseItems.Where(f => f.PresentationUniqueKey == filter.AncestorWithPresentationUniqueKey).Any(f => f.AncestorIds!.Any(w => w.ItemId == f.Id)));
  913. }
  914. if (!string.IsNullOrWhiteSpace(filter.SeriesPresentationUniqueKey))
  915. {
  916. baseQuery = baseQuery
  917. .Where(e => e.SeriesPresentationUniqueKey == filter.SeriesPresentationUniqueKey);
  918. }
  919. if (filter.ExcludeInheritedTags.Length > 0)
  920. {
  921. baseQuery = baseQuery
  922. .Where(e => !e.ItemValues!.Where(e => e.ItemValue.Type == ItemValueType.InheritedTags)
  923. .Any(f => filter.ExcludeInheritedTags.Contains(f.ItemValue.CleanValue)));
  924. }
  925. if (filter.IncludeInheritedTags.Length > 0)
  926. {
  927. // Episodes do not store inherit tags from their parents in the database, and the tag may be still required by the client.
  928. // In addtion to the tags for the episodes themselves, we need to manually query its parent (the season)'s tags as well.
  929. if (includeTypes.Length == 1 && includeTypes.FirstOrDefault() is BaseItemKind.Episode)
  930. {
  931. baseQuery = baseQuery
  932. .Where(e => e.ItemValues!.Where(e => e.ItemValue.Type == ItemValueType.InheritedTags)
  933. .Any(f => filter.IncludeInheritedTags.Contains(f.ItemValue.CleanValue))
  934. ||
  935. (e.ParentId.HasValue && context.ItemValuesMap.Where(w => w.ItemId == e.ParentId.Value)!.Where(e => e.ItemValue.Type == ItemValueType.InheritedTags)
  936. .Any(f => filter.IncludeInheritedTags.Contains(f.ItemValue.CleanValue))));
  937. }
  938. // A playlist should be accessible to its owner regardless of allowed tags.
  939. else if (includeTypes.Length == 1 && includeTypes.FirstOrDefault() is BaseItemKind.Playlist)
  940. {
  941. baseQuery = baseQuery
  942. .Where(e => e.AncestorIds!.Any(f => f.ParentItem.ItemValues!.Any(w => w.ItemValue.Type == ItemValueType.Tags && filter.IncludeInheritedTags.Contains(w.ItemValue.CleanValue))
  943. || e.Data!.Contains($"OwnerUserId\":\"{filter.User!.Id:N}\"")));
  944. // d ^^ this is stupid it hate this.
  945. }
  946. else
  947. {
  948. baseQuery = baseQuery
  949. .Where(e => e.AncestorIds!.Any(f => f.ParentItem.ItemValues!.Any(w => w.ItemValue.Type == ItemValueType.Tags && filter.IncludeInheritedTags.Contains(w.ItemValue.CleanValue))));
  950. }
  951. }
  952. if (filter.SeriesStatuses.Length > 0)
  953. {
  954. var seriesStatus = filter.SeriesStatuses.Select(e => e.ToString()).ToArray();
  955. baseQuery = baseQuery
  956. .Where(e => seriesStatus.Any(f => e.Data!.Contains(f)));
  957. }
  958. if (filter.BoxSetLibraryFolders.Length > 0)
  959. {
  960. var boxsetFolders = filter.BoxSetLibraryFolders.Select(e => e.ToString("N", CultureInfo.InvariantCulture)).ToArray();
  961. baseQuery = baseQuery
  962. .Where(e => boxsetFolders.Any(f => e.Data!.Contains(f)));
  963. }
  964. if (filter.VideoTypes.Length > 0)
  965. {
  966. var videoTypeBs = filter.VideoTypes.Select(e => $"\"VideoType\":\"" + e + "\"");
  967. baseQuery = baseQuery
  968. .Where(e => videoTypeBs.Any(f => e.Data!.Contains(f)));
  969. }
  970. if (filter.Is3D.HasValue)
  971. {
  972. if (filter.Is3D.Value)
  973. {
  974. baseQuery = baseQuery
  975. .Where(e => e.Data!.Contains("Video3DFormat"));
  976. }
  977. else
  978. {
  979. baseQuery = baseQuery
  980. .Where(e => !e.Data!.Contains("Video3DFormat"));
  981. }
  982. }
  983. if (filter.IsPlaceHolder.HasValue)
  984. {
  985. if (filter.IsPlaceHolder.Value)
  986. {
  987. baseQuery = baseQuery
  988. .Where(e => e.Data!.Contains("IsPlaceHolder\":true"));
  989. }
  990. else
  991. {
  992. baseQuery = baseQuery
  993. .Where(e => !e.Data!.Contains("IsPlaceHolder\":true"));
  994. }
  995. }
  996. if (filter.HasSpecialFeature.HasValue)
  997. {
  998. if (filter.HasSpecialFeature.Value)
  999. {
  1000. baseQuery = baseQuery
  1001. .Where(e => e.ExtraIds != null);
  1002. }
  1003. else
  1004. {
  1005. baseQuery = baseQuery
  1006. .Where(e => e.ExtraIds == null);
  1007. }
  1008. }
  1009. if (filter.HasTrailer.HasValue || filter.HasThemeSong.HasValue || filter.HasThemeVideo.HasValue)
  1010. {
  1011. if (filter.HasTrailer.GetValueOrDefault() || filter.HasThemeSong.GetValueOrDefault() || filter.HasThemeVideo.GetValueOrDefault())
  1012. {
  1013. baseQuery = baseQuery
  1014. .Where(e => e.ExtraIds != null);
  1015. }
  1016. else
  1017. {
  1018. baseQuery = baseQuery
  1019. .Where(e => e.ExtraIds == null);
  1020. }
  1021. }
  1022. return baseQuery;
  1023. }
  1024. /// <summary>
  1025. /// Gets the type.
  1026. /// </summary>
  1027. /// <param name="typeName">Name of the type.</param>
  1028. /// <returns>Type.</returns>
  1029. /// <exception cref="ArgumentNullException"><c>typeName</c> is null.</exception>
  1030. private static Type? GetType(string typeName)
  1031. {
  1032. ArgumentException.ThrowIfNullOrEmpty(typeName);
  1033. return _typeMap.GetOrAdd(typeName, k => AppDomain.CurrentDomain.GetAssemblies()
  1034. .Select(a => a.GetType(k))
  1035. .FirstOrDefault(t => t is not null));
  1036. }
  1037. /// <inheritdoc cref="IItemRepository" />
  1038. public void SaveImages(BaseItem item)
  1039. {
  1040. ArgumentNullException.ThrowIfNull(item);
  1041. var images = item.ImageInfos.Select(e => Map(item.Id, e));
  1042. using var db = dbProvider.CreateDbContext();
  1043. using var transaction = db.Database.BeginTransaction();
  1044. db.BaseItemImageInfos.Where(e => e.ItemId == item.Id).ExecuteDelete();
  1045. db.BaseItemImageInfos.AddRange(images);
  1046. transaction.Commit();
  1047. }
  1048. /// <inheritdoc cref="IItemRepository" />
  1049. public void SaveItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
  1050. {
  1051. UpdateOrInsertItems(items, cancellationToken);
  1052. }
  1053. /// <inheritdoc cref="IItemRepository" />
  1054. public void UpdateOrInsertItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
  1055. {
  1056. ArgumentNullException.ThrowIfNull(items);
  1057. cancellationToken.ThrowIfCancellationRequested();
  1058. var itemsLen = items.Count;
  1059. var tuples = new (BaseItemDto Item, List<Guid>? AncestorIds, BaseItemDto TopParent, string? UserDataKey, List<string> InheritedTags)[itemsLen];
  1060. for (int i = 0; i < itemsLen; i++)
  1061. {
  1062. var item = items[i];
  1063. var ancestorIds = item.SupportsAncestors ?
  1064. item.GetAncestorIds().Distinct().ToList() :
  1065. null;
  1066. var topParent = item.GetTopParent();
  1067. var userdataKey = item.GetUserDataKeys().FirstOrDefault();
  1068. var inheritedTags = item.GetInheritedTags();
  1069. tuples[i] = (item, ancestorIds, topParent, userdataKey, inheritedTags);
  1070. }
  1071. try
  1072. {
  1073. using var context = dbProvider.CreateDbContext();
  1074. using var transaction = context.Database.BeginTransaction();
  1075. foreach (var item in tuples)
  1076. {
  1077. var entity = Map(item.Item);
  1078. if (!context.BaseItems.Any(e => e.Id == entity.Id))
  1079. {
  1080. context.BaseItems.Add(entity);
  1081. }
  1082. else
  1083. {
  1084. context.BaseItems.Attach(entity).State = EntityState.Modified;
  1085. }
  1086. context.AncestorIds.Where(e => e.ItemId == entity.Id).ExecuteDelete();
  1087. if (item.Item.SupportsAncestors && item.AncestorIds != null)
  1088. {
  1089. entity.AncestorIds = new List<AncestorId>();
  1090. foreach (var ancestorId in item.AncestorIds)
  1091. {
  1092. entity.AncestorIds.Add(new AncestorId()
  1093. {
  1094. ParentItemId = ancestorId,
  1095. ItemId = entity.Id,
  1096. Item = null!,
  1097. ParentItem = null!
  1098. });
  1099. }
  1100. }
  1101. var itemValuesToSave = GetItemValuesToSave(item.Item, item.InheritedTags);
  1102. var itemValues = itemValuesToSave.Select(e => e.Value).ToArray();
  1103. context.ItemValuesMap.Where(e => e.ItemId == entity.Id).ExecuteDelete();
  1104. entity.ItemValues = new List<ItemValueMap>();
  1105. var referenceValues = context.ItemValues.Where(e => itemValues.Any(f => f == e.CleanValue)).ToArray();
  1106. foreach (var itemValue in itemValuesToSave)
  1107. {
  1108. var refValue = referenceValues.FirstOrDefault(f => f.CleanValue == itemValue.Value && (int)f.Type == itemValue.MagicNumber);
  1109. if (refValue is not null)
  1110. {
  1111. entity.ItemValues.Add(new ItemValueMap()
  1112. {
  1113. Item = entity,
  1114. ItemId = entity.Id,
  1115. ItemValue = null!,
  1116. ItemValueId = refValue.ItemValueId
  1117. });
  1118. }
  1119. else
  1120. {
  1121. entity.ItemValues.Add(new ItemValueMap()
  1122. {
  1123. Item = entity,
  1124. ItemId = entity.Id,
  1125. ItemValue = new ItemValue()
  1126. {
  1127. CleanValue = GetCleanValue(itemValue.Value),
  1128. Type = (ItemValueType)itemValue.MagicNumber,
  1129. ItemValueId = Guid.NewGuid(),
  1130. Value = itemValue.Value
  1131. },
  1132. ItemValueId = Guid.Empty
  1133. });
  1134. }
  1135. }
  1136. }
  1137. context.SaveChanges();
  1138. transaction.Commit();
  1139. }
  1140. catch (System.Exception)
  1141. {
  1142. System.Console.WriteLine();
  1143. throw;
  1144. }
  1145. }
  1146. /// <inheritdoc cref="IItemRepository" />
  1147. public BaseItemDto? RetrieveItem(Guid id)
  1148. {
  1149. if (id.IsEmpty())
  1150. {
  1151. throw new ArgumentException("Guid can't be empty", nameof(id));
  1152. }
  1153. using var context = dbProvider.CreateDbContext();
  1154. var item = context.BaseItems.AsNoTracking().FirstOrDefault(e => e.Id == id);
  1155. if (item is null)
  1156. {
  1157. return null;
  1158. }
  1159. return DeserialiseBaseItem(item);
  1160. }
  1161. /// <summary>
  1162. /// Maps a Entity to the DTO.
  1163. /// </summary>
  1164. /// <param name="entity">The entity.</param>
  1165. /// <param name="dto">The dto base instance.</param>
  1166. /// <returns>The dto to map.</returns>
  1167. public BaseItemDto Map(BaseItemEntity entity, BaseItemDto dto)
  1168. {
  1169. dto.Id = entity.Id;
  1170. dto.ParentId = entity.ParentId.GetValueOrDefault();
  1171. dto.Path = entity.Path;
  1172. dto.EndDate = entity.EndDate;
  1173. dto.CommunityRating = entity.CommunityRating;
  1174. dto.CustomRating = entity.CustomRating;
  1175. dto.IndexNumber = entity.IndexNumber;
  1176. dto.IsLocked = entity.IsLocked;
  1177. dto.Name = entity.Name;
  1178. dto.OfficialRating = entity.OfficialRating;
  1179. dto.Overview = entity.Overview;
  1180. dto.ParentIndexNumber = entity.ParentIndexNumber;
  1181. dto.PremiereDate = entity.PremiereDate;
  1182. dto.ProductionYear = entity.ProductionYear;
  1183. dto.SortName = entity.SortName;
  1184. dto.ForcedSortName = entity.ForcedSortName;
  1185. dto.RunTimeTicks = entity.RunTimeTicks;
  1186. dto.PreferredMetadataLanguage = entity.PreferredMetadataLanguage;
  1187. dto.PreferredMetadataCountryCode = entity.PreferredMetadataCountryCode;
  1188. dto.IsInMixedFolder = entity.IsInMixedFolder;
  1189. dto.InheritedParentalRatingValue = entity.InheritedParentalRatingValue;
  1190. dto.CriticRating = entity.CriticRating;
  1191. dto.PresentationUniqueKey = entity.PresentationUniqueKey;
  1192. dto.OriginalTitle = entity.OriginalTitle;
  1193. dto.Album = entity.Album;
  1194. dto.LUFS = entity.LUFS;
  1195. dto.NormalizationGain = entity.NormalizationGain;
  1196. dto.IsVirtualItem = entity.IsVirtualItem;
  1197. dto.ExternalSeriesId = entity.ExternalSeriesId;
  1198. dto.Tagline = entity.Tagline;
  1199. dto.TotalBitrate = entity.TotalBitrate;
  1200. dto.ExternalId = entity.ExternalId;
  1201. dto.Size = entity.Size;
  1202. dto.Genres = entity.Genres?.Split('|');
  1203. dto.DateCreated = entity.DateCreated.GetValueOrDefault();
  1204. dto.DateModified = entity.DateModified.GetValueOrDefault();
  1205. dto.ChannelId = string.IsNullOrWhiteSpace(entity.ChannelId) ? Guid.Empty : Guid.Parse(entity.ChannelId);
  1206. dto.DateLastRefreshed = entity.DateLastRefreshed.GetValueOrDefault();
  1207. dto.DateLastSaved = entity.DateLastSaved.GetValueOrDefault();
  1208. dto.OwnerId = string.IsNullOrWhiteSpace(entity.OwnerId) ? Guid.Empty : Guid.Parse(entity.OwnerId);
  1209. dto.Width = entity.Width.GetValueOrDefault();
  1210. dto.Height = entity.Height.GetValueOrDefault();
  1211. if (entity.Provider is not null)
  1212. {
  1213. dto.ProviderIds = entity.Provider.ToDictionary(e => e.ProviderId, e => e.ProviderValue);
  1214. }
  1215. if (entity.ExtraType is not null)
  1216. {
  1217. dto.ExtraType = (ExtraType)entity.ExtraType;
  1218. }
  1219. if (entity.LockedFields is not null)
  1220. {
  1221. dto.LockedFields = entity.LockedFields?.Select(e => (MetadataField)e.Id).ToArray() ?? [];
  1222. }
  1223. if (entity.Audio is not null)
  1224. {
  1225. dto.Audio = (ProgramAudio)entity.Audio;
  1226. }
  1227. dto.ExtraIds = string.IsNullOrWhiteSpace(entity.ExtraIds) ? null : entity.ExtraIds.Split('|').Select(e => Guid.Parse(e)).ToArray();
  1228. dto.ProductionLocations = entity.ProductionLocations?.Split('|');
  1229. dto.Studios = entity.Studios?.Split('|');
  1230. dto.Tags = entity.Tags?.Split('|');
  1231. if (dto is IHasProgramAttributes hasProgramAttributes)
  1232. {
  1233. hasProgramAttributes.IsMovie = entity.IsMovie;
  1234. hasProgramAttributes.IsSeries = entity.IsSeries;
  1235. hasProgramAttributes.EpisodeTitle = entity.EpisodeTitle;
  1236. hasProgramAttributes.IsRepeat = entity.IsRepeat;
  1237. }
  1238. if (dto is LiveTvChannel liveTvChannel)
  1239. {
  1240. liveTvChannel.ServiceName = entity.ExternalServiceId;
  1241. }
  1242. if (dto is Trailer trailer)
  1243. {
  1244. trailer.TrailerTypes = entity.TrailerTypes?.Select(e => (TrailerType)e.Id).ToArray() ?? [];
  1245. }
  1246. if (dto is Video video)
  1247. {
  1248. video.PrimaryVersionId = entity.PrimaryVersionId;
  1249. }
  1250. if (dto is IHasSeries hasSeriesName)
  1251. {
  1252. hasSeriesName.SeriesName = entity.SeriesName;
  1253. hasSeriesName.SeriesId = entity.SeriesId.GetValueOrDefault();
  1254. hasSeriesName.SeriesPresentationUniqueKey = entity.SeriesPresentationUniqueKey;
  1255. }
  1256. if (dto is Episode episode)
  1257. {
  1258. episode.SeasonName = entity.SeasonName;
  1259. episode.SeasonId = entity.SeasonId.GetValueOrDefault();
  1260. }
  1261. if (dto is IHasArtist hasArtists)
  1262. {
  1263. hasArtists.Artists = entity.Artists?.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1264. }
  1265. if (dto is IHasAlbumArtist hasAlbumArtists)
  1266. {
  1267. hasAlbumArtists.AlbumArtists = entity.AlbumArtists?.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1268. }
  1269. if (dto is LiveTvProgram program)
  1270. {
  1271. program.ShowId = entity.ShowId;
  1272. }
  1273. if (entity.Images is not null)
  1274. {
  1275. dto.ImageInfos = entity.Images.Select(Map).ToArray();
  1276. }
  1277. // dto.Type = entity.Type;
  1278. // dto.Data = entity.Data;
  1279. // dto.MediaType = entity.MediaType;
  1280. if (dto is IHasStartDate hasStartDate)
  1281. {
  1282. hasStartDate.StartDate = entity.StartDate;
  1283. }
  1284. // Fields that are present in the DB but are never actually used
  1285. // dto.UnratedType = entity.UnratedType;
  1286. // dto.TopParentId = entity.TopParentId;
  1287. // dto.CleanName = entity.CleanName;
  1288. // dto.UserDataKey = entity.UserDataKey;
  1289. if (dto is Folder folder)
  1290. {
  1291. folder.DateLastMediaAdded = entity.DateLastMediaAdded;
  1292. }
  1293. return dto;
  1294. }
  1295. /// <summary>
  1296. /// Maps a Entity to the DTO.
  1297. /// </summary>
  1298. /// <param name="dto">The entity.</param>
  1299. /// <returns>The dto to map.</returns>
  1300. public BaseItemEntity Map(BaseItemDto dto)
  1301. {
  1302. var entity = new BaseItemEntity()
  1303. {
  1304. Type = dto.GetType().ToString(),
  1305. Id = dto.Id
  1306. };
  1307. entity.ParentId = !dto.ParentId.IsEmpty() ? dto.ParentId : null;
  1308. entity.Path = GetPathToSave(dto.Path);
  1309. entity.EndDate = dto.EndDate.GetValueOrDefault();
  1310. entity.CommunityRating = dto.CommunityRating;
  1311. entity.CustomRating = dto.CustomRating;
  1312. entity.IndexNumber = dto.IndexNumber;
  1313. entity.IsLocked = dto.IsLocked;
  1314. entity.Name = dto.Name;
  1315. entity.OfficialRating = dto.OfficialRating;
  1316. entity.Overview = dto.Overview;
  1317. entity.ParentIndexNumber = dto.ParentIndexNumber;
  1318. entity.PremiereDate = dto.PremiereDate;
  1319. entity.ProductionYear = dto.ProductionYear;
  1320. entity.SortName = dto.SortName;
  1321. entity.ForcedSortName = dto.ForcedSortName;
  1322. entity.RunTimeTicks = dto.RunTimeTicks;
  1323. entity.PreferredMetadataLanguage = dto.PreferredMetadataLanguage;
  1324. entity.PreferredMetadataCountryCode = dto.PreferredMetadataCountryCode;
  1325. entity.IsInMixedFolder = dto.IsInMixedFolder;
  1326. entity.InheritedParentalRatingValue = dto.InheritedParentalRatingValue;
  1327. entity.CriticRating = dto.CriticRating;
  1328. entity.PresentationUniqueKey = dto.PresentationUniqueKey;
  1329. entity.OriginalTitle = dto.OriginalTitle;
  1330. entity.Album = dto.Album;
  1331. entity.LUFS = dto.LUFS;
  1332. entity.NormalizationGain = dto.NormalizationGain;
  1333. entity.IsVirtualItem = dto.IsVirtualItem;
  1334. entity.ExternalSeriesId = dto.ExternalSeriesId;
  1335. entity.Tagline = dto.Tagline;
  1336. entity.TotalBitrate = dto.TotalBitrate;
  1337. entity.ExternalId = dto.ExternalId;
  1338. entity.Size = dto.Size;
  1339. entity.Genres = string.Join('|', dto.Genres);
  1340. entity.DateCreated = dto.DateCreated;
  1341. entity.DateModified = dto.DateModified;
  1342. entity.ChannelId = dto.ChannelId.ToString();
  1343. entity.DateLastRefreshed = dto.DateLastRefreshed;
  1344. entity.DateLastSaved = dto.DateLastSaved;
  1345. entity.OwnerId = dto.OwnerId.ToString();
  1346. entity.Width = dto.Width;
  1347. entity.Height = dto.Height;
  1348. entity.Provider = dto.ProviderIds.Select(e => new BaseItemProvider()
  1349. {
  1350. Item = entity,
  1351. ProviderId = e.Key,
  1352. ProviderValue = e.Value
  1353. }).ToList();
  1354. if (dto.Audio.HasValue)
  1355. {
  1356. entity.Audio = (ProgramAudioEntity)dto.Audio;
  1357. }
  1358. if (dto.ExtraType.HasValue)
  1359. {
  1360. entity.ExtraType = (BaseItemExtraType)dto.ExtraType;
  1361. }
  1362. entity.ExtraIds = dto.ExtraIds is not null ? string.Join('|', dto.ExtraIds) : null;
  1363. entity.ProductionLocations = dto.ProductionLocations is not null ? string.Join('|', dto.ProductionLocations) : null;
  1364. entity.Studios = dto.Studios is not null ? string.Join('|', dto.Studios) : null;
  1365. entity.Tags = dto.Tags is not null ? string.Join('|', dto.Tags) : null;
  1366. entity.LockedFields = dto.LockedFields is not null ? dto.LockedFields
  1367. .Select(e => new BaseItemMetadataField()
  1368. {
  1369. Id = (int)e,
  1370. Item = entity,
  1371. ItemId = entity.Id
  1372. })
  1373. .ToArray() : null;
  1374. if (dto is IHasProgramAttributes hasProgramAttributes)
  1375. {
  1376. entity.IsMovie = hasProgramAttributes.IsMovie;
  1377. entity.IsSeries = hasProgramAttributes.IsSeries;
  1378. entity.EpisodeTitle = hasProgramAttributes.EpisodeTitle;
  1379. entity.IsRepeat = hasProgramAttributes.IsRepeat;
  1380. }
  1381. if (dto is LiveTvChannel liveTvChannel)
  1382. {
  1383. entity.ExternalServiceId = liveTvChannel.ServiceName;
  1384. }
  1385. if (dto is Video video)
  1386. {
  1387. entity.PrimaryVersionId = video.PrimaryVersionId;
  1388. }
  1389. if (dto is IHasSeries hasSeriesName)
  1390. {
  1391. entity.SeriesName = hasSeriesName.SeriesName;
  1392. entity.SeriesId = hasSeriesName.SeriesId;
  1393. entity.SeriesPresentationUniqueKey = hasSeriesName.SeriesPresentationUniqueKey;
  1394. }
  1395. if (dto is Episode episode)
  1396. {
  1397. entity.SeasonName = episode.SeasonName;
  1398. entity.SeasonId = episode.SeasonId;
  1399. }
  1400. if (dto is IHasArtist hasArtists)
  1401. {
  1402. entity.Artists = hasArtists.Artists is not null ? string.Join('|', hasArtists.Artists) : null;
  1403. }
  1404. if (dto is IHasAlbumArtist hasAlbumArtists)
  1405. {
  1406. entity.AlbumArtists = hasAlbumArtists.AlbumArtists is not null ? string.Join('|', hasAlbumArtists.AlbumArtists) : null;
  1407. }
  1408. if (dto is LiveTvProgram program)
  1409. {
  1410. entity.ShowId = program.ShowId;
  1411. }
  1412. if (dto.ImageInfos is not null)
  1413. {
  1414. entity.Images = dto.ImageInfos.Select(f => Map(dto.Id, f)).ToArray();
  1415. }
  1416. if (dto is Trailer trailer)
  1417. {
  1418. entity.TrailerTypes = trailer.TrailerTypes?.Select(e => new BaseItemTrailerType()
  1419. {
  1420. Id = (int)e,
  1421. Item = entity,
  1422. ItemId = entity.Id
  1423. }).ToArray() ?? [];
  1424. }
  1425. // dto.Type = entity.Type;
  1426. // dto.Data = entity.Data;
  1427. // dto.MediaType = entity.MediaType;
  1428. if (dto is IHasStartDate hasStartDate)
  1429. {
  1430. entity.StartDate = hasStartDate.StartDate;
  1431. }
  1432. // Fields that are present in the DB but are never actually used
  1433. // dto.UnratedType = entity.UnratedType;
  1434. // dto.TopParentId = entity.TopParentId;
  1435. // dto.CleanName = entity.CleanName;
  1436. // dto.UserDataKey = entity.UserDataKey;
  1437. if (dto is Folder folder)
  1438. {
  1439. entity.DateLastMediaAdded = folder.DateLastMediaAdded;
  1440. entity.IsFolder = folder.IsFolder;
  1441. }
  1442. return entity;
  1443. }
  1444. private IReadOnlyList<string> GetItemValueNames(int[] itemValueTypes, IReadOnlyList<string> withItemTypes, IReadOnlyList<string> excludeItemTypes)
  1445. {
  1446. using var context = dbProvider.CreateDbContext();
  1447. var query = context.ItemValuesMap
  1448. .AsNoTracking()
  1449. .Where(e => itemValueTypes.Any(w => (ItemValueType)w == e.ItemValue.Type));
  1450. if (withItemTypes.Count > 0)
  1451. {
  1452. query = query.Where(e => withItemTypes.Contains(e.Item.Type));
  1453. }
  1454. if (excludeItemTypes.Count > 0)
  1455. {
  1456. query = query.Where(e => !excludeItemTypes.Contains(e.Item.Type));
  1457. }
  1458. // query = query.DistinctBy(e => e.CleanValue);
  1459. return query.Select(e => e.ItemValue.CleanValue).ToImmutableArray();
  1460. }
  1461. private BaseItemDto DeserialiseBaseItem(BaseItemEntity baseItemEntity)
  1462. {
  1463. var type = GetType(baseItemEntity.Type) ?? throw new InvalidOperationException("Cannot deserialise unkown type.");
  1464. var dto = Activator.CreateInstance(type) as BaseItemDto ?? throw new InvalidOperationException("Cannot deserialise unkown type.");
  1465. return Map(baseItemEntity, dto);
  1466. }
  1467. private QueryResult<(BaseItemDto Item, ItemCounts ItemCounts)> GetItemValues(InternalItemsQuery filter, int[] itemValueTypes, string returnType)
  1468. {
  1469. ArgumentNullException.ThrowIfNull(filter);
  1470. if (!filter.Limit.HasValue)
  1471. {
  1472. filter.EnableTotalRecordCount = false;
  1473. }
  1474. using var context = dbProvider.CreateDbContext();
  1475. var innerQuery = new InternalItemsQuery(filter.User)
  1476. {
  1477. ExcludeItemTypes = filter.ExcludeItemTypes,
  1478. IncludeItemTypes = filter.IncludeItemTypes,
  1479. MediaTypes = filter.MediaTypes,
  1480. AncestorIds = filter.AncestorIds,
  1481. ItemIds = filter.ItemIds,
  1482. TopParentIds = filter.TopParentIds,
  1483. ParentId = filter.ParentId,
  1484. IsAiring = filter.IsAiring,
  1485. IsMovie = filter.IsMovie,
  1486. IsSports = filter.IsSports,
  1487. IsKids = filter.IsKids,
  1488. IsNews = filter.IsNews,
  1489. IsSeries = filter.IsSeries
  1490. };
  1491. var query = TranslateQuery(context.BaseItems.AsNoTracking(), context, innerQuery);
  1492. query = query.Where(e => e.Type == returnType && e.ItemValues!.Any(f => e.CleanName == f.ItemValue.CleanValue && itemValueTypes.Any(w => (ItemValueType)w == f.ItemValue.Type)));
  1493. if (filter.OrderBy.Count != 0
  1494. || !string.IsNullOrEmpty(filter.SearchTerm))
  1495. {
  1496. query = ApplyOrder(query, filter);
  1497. }
  1498. else
  1499. {
  1500. query = query.OrderBy(e => e.SortName);
  1501. }
  1502. if (filter.Limit.HasValue || filter.StartIndex.HasValue)
  1503. {
  1504. var offset = filter.StartIndex ?? 0;
  1505. if (offset > 0)
  1506. {
  1507. query = query.Skip(offset);
  1508. }
  1509. if (filter.Limit.HasValue)
  1510. {
  1511. query.Take(filter.Limit.Value);
  1512. }
  1513. }
  1514. var result = new QueryResult<(BaseItem, ItemCounts)>();
  1515. string countText = string.Empty;
  1516. if (filter.EnableTotalRecordCount)
  1517. {
  1518. result.TotalRecordCount = query.DistinctBy(e => e.PresentationUniqueKey).Count();
  1519. }
  1520. var resultQuery = query.Select(e => new
  1521. {
  1522. item = e,
  1523. // TODO: This is bad refactor!
  1524. itemCount = new ItemCounts()
  1525. {
  1526. SeriesCount = e.ItemValues!.Count(f => f.Item.Type == typeof(Series).FullName),
  1527. EpisodeCount = e.ItemValues!.Count(f => f.Item.Type == typeof(Data.Entities.Libraries.Movie).FullName),
  1528. MovieCount = e.ItemValues!.Count(f => f.Item.Type == typeof(Series).FullName),
  1529. AlbumCount = e.ItemValues!.Count(f => f.Item.Type == typeof(MusicAlbum).FullName),
  1530. ArtistCount = e.ItemValues!.Count(f => f.Item.Type == typeof(MusicArtist).FullName),
  1531. SongCount = e.ItemValues!.Count(f => f.Item.Type == typeof(Audio).FullName),
  1532. TrailerCount = e.ItemValues!.Count(f => f.Item.Type == typeof(Trailer).FullName),
  1533. }
  1534. });
  1535. result.StartIndex = filter.StartIndex ?? 0;
  1536. result.Items = resultQuery.ToImmutableArray().Select(e =>
  1537. {
  1538. return (DeserialiseBaseItem(e.item), e.itemCount);
  1539. }).ToImmutableArray();
  1540. return result;
  1541. }
  1542. private static void PrepareFilterQuery(InternalItemsQuery query)
  1543. {
  1544. if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
  1545. {
  1546. query.Limit = query.Limit.Value + 4;
  1547. }
  1548. if (query.IsResumable ?? false)
  1549. {
  1550. query.IsVirtualItem = false;
  1551. }
  1552. }
  1553. private string GetCleanValue(string value)
  1554. {
  1555. if (string.IsNullOrWhiteSpace(value))
  1556. {
  1557. return value;
  1558. }
  1559. return value.RemoveDiacritics().ToLowerInvariant();
  1560. }
  1561. private List<(int MagicNumber, string Value)> GetItemValuesToSave(BaseItem item, List<string> inheritedTags)
  1562. {
  1563. var list = new List<(int, string)>();
  1564. if (item is IHasArtist hasArtist)
  1565. {
  1566. list.AddRange(hasArtist.Artists.Select(i => (0, i)));
  1567. }
  1568. if (item is IHasAlbumArtist hasAlbumArtist)
  1569. {
  1570. list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i)));
  1571. }
  1572. list.AddRange(item.Genres.Select(i => (2, i)));
  1573. list.AddRange(item.Studios.Select(i => (3, i)));
  1574. list.AddRange(item.Tags.Select(i => (4, i)));
  1575. // keywords was 5
  1576. list.AddRange(inheritedTags.Select(i => (6, i)));
  1577. // Remove all invalid values.
  1578. list.RemoveAll(i => string.IsNullOrWhiteSpace(i.Item2));
  1579. return list;
  1580. }
  1581. internal static string? SerializeProviderIds(Dictionary<string, string> providerIds)
  1582. {
  1583. StringBuilder str = new StringBuilder();
  1584. foreach (var i in providerIds)
  1585. {
  1586. // Ideally we shouldn't need this IsNullOrWhiteSpace check,
  1587. // but we're seeing some cases of bad data slip through
  1588. if (string.IsNullOrWhiteSpace(i.Value))
  1589. {
  1590. continue;
  1591. }
  1592. str.Append(i.Key)
  1593. .Append('=')
  1594. .Append(i.Value)
  1595. .Append('|');
  1596. }
  1597. if (str.Length == 0)
  1598. {
  1599. return null;
  1600. }
  1601. str.Length -= 1; // Remove last |
  1602. return str.ToString();
  1603. }
  1604. internal static void DeserializeProviderIds(string value, IHasProviderIds item)
  1605. {
  1606. if (string.IsNullOrWhiteSpace(value))
  1607. {
  1608. return;
  1609. }
  1610. foreach (var part in value.SpanSplit('|'))
  1611. {
  1612. var providerDelimiterIndex = part.IndexOf('=');
  1613. // Don't let empty values through
  1614. if (providerDelimiterIndex != -1 && part.Length != providerDelimiterIndex + 1)
  1615. {
  1616. item.SetProviderId(part[..providerDelimiterIndex].ToString(), part[(providerDelimiterIndex + 1)..].ToString());
  1617. }
  1618. }
  1619. }
  1620. private static BaseItemImageInfo Map(Guid baseItemId, ItemImageInfo e)
  1621. {
  1622. return new BaseItemImageInfo()
  1623. {
  1624. ItemId = baseItemId,
  1625. Id = Guid.NewGuid(),
  1626. Path = e.Path,
  1627. Blurhash = e.BlurHash != null ? Encoding.UTF8.GetBytes(e.BlurHash) : null,
  1628. DateModified = e.DateModified,
  1629. Height = e.Height,
  1630. Width = e.Width,
  1631. ImageType = (ImageInfoImageType)e.Type,
  1632. Item = null!
  1633. };
  1634. }
  1635. private static ItemImageInfo Map(BaseItemImageInfo e)
  1636. {
  1637. return new ItemImageInfo()
  1638. {
  1639. Path = e.Path,
  1640. BlurHash = e.Blurhash != null ? Encoding.UTF8.GetString(e.Blurhash) : null,
  1641. DateModified = e.DateModified,
  1642. Height = e.Height,
  1643. Width = e.Width,
  1644. Type = (ImageType)e.ImageType
  1645. };
  1646. }
  1647. private string? GetPathToSave(string path)
  1648. {
  1649. if (path is null)
  1650. {
  1651. return null;
  1652. }
  1653. return appHost.ReverseVirtualPath(path);
  1654. }
  1655. private string RestorePath(string path)
  1656. {
  1657. return appHost.ExpandVirtualPath(path);
  1658. }
  1659. private List<string> GetItemByNameTypesInQuery(InternalItemsQuery query)
  1660. {
  1661. var list = new List<string>();
  1662. if (IsTypeInQuery(BaseItemKind.Person, query))
  1663. {
  1664. list.Add(typeof(Person).FullName!);
  1665. }
  1666. if (IsTypeInQuery(BaseItemKind.Genre, query))
  1667. {
  1668. list.Add(typeof(Genre).FullName!);
  1669. }
  1670. if (IsTypeInQuery(BaseItemKind.MusicGenre, query))
  1671. {
  1672. list.Add(typeof(MusicGenre).FullName!);
  1673. }
  1674. if (IsTypeInQuery(BaseItemKind.MusicArtist, query))
  1675. {
  1676. list.Add(typeof(MusicArtist).FullName!);
  1677. }
  1678. if (IsTypeInQuery(BaseItemKind.Studio, query))
  1679. {
  1680. list.Add(typeof(Studio).FullName!);
  1681. }
  1682. return list;
  1683. }
  1684. private bool IsTypeInQuery(BaseItemKind type, InternalItemsQuery query)
  1685. {
  1686. if (query.ExcludeItemTypes.Contains(type))
  1687. {
  1688. return false;
  1689. }
  1690. return query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(type);
  1691. }
  1692. private IQueryable<T> Pageinate<T>(IQueryable<T> query, InternalItemsQuery filter)
  1693. {
  1694. if (filter.Limit.HasValue || filter.StartIndex.HasValue)
  1695. {
  1696. var offset = filter.StartIndex ?? 0;
  1697. if (offset > 0)
  1698. {
  1699. query = query.Skip(offset);
  1700. }
  1701. if (filter.Limit.HasValue)
  1702. {
  1703. query = query.Take(filter.Limit.Value);
  1704. }
  1705. }
  1706. return query;
  1707. }
  1708. private Expression<Func<BaseItemEntity, object>> MapOrderByField(ItemSortBy sortBy, InternalItemsQuery query)
  1709. {
  1710. #pragma warning disable CS8603 // Possible null reference return.
  1711. return sortBy switch
  1712. {
  1713. ItemSortBy.AirTime => e => e.SortName, // TODO
  1714. ItemSortBy.Runtime => e => e.RunTimeTicks,
  1715. ItemSortBy.Random => e => EF.Functions.Random(),
  1716. ItemSortBy.DatePlayed => e => e.UserData!.FirstOrDefault(f => f.UserId == query.User!.Id && f.Key == e.UserDataKey)!.LastPlayedDate,
  1717. ItemSortBy.PlayCount => e => e.UserData!.FirstOrDefault(f => f.UserId == query.User!.Id && f.Key == e.UserDataKey)!.PlayCount,
  1718. ItemSortBy.IsFavoriteOrLiked => e => e.UserData!.FirstOrDefault(f => f.UserId == query.User!.Id && f.Key == e.UserDataKey)!.IsFavorite,
  1719. ItemSortBy.IsFolder => e => e.IsFolder,
  1720. ItemSortBy.IsPlayed => e => e.UserData!.FirstOrDefault(f => f.UserId == query.User!.Id && f.Key == e.UserDataKey)!.Played,
  1721. ItemSortBy.IsUnplayed => e => !e.UserData!.FirstOrDefault(f => f.UserId == query.User!.Id && f.Key == e.UserDataKey)!.Played,
  1722. ItemSortBy.DateLastContentAdded => e => e.DateLastMediaAdded,
  1723. ItemSortBy.Artist => e => e.ItemValues!.Where(f => f.ItemValue.Type == ItemValueType.Artist).Select(f => f.ItemValue.CleanValue),
  1724. ItemSortBy.AlbumArtist => e => e.ItemValues!.Where(f => f.ItemValue.Type == ItemValueType.AlbumArtist).Select(f => f.ItemValue.CleanValue),
  1725. ItemSortBy.Studio => e => e.ItemValues!.Where(f => f.ItemValue.Type == ItemValueType.Studios).Select(f => f.ItemValue.CleanValue),
  1726. ItemSortBy.OfficialRating => e => e.InheritedParentalRatingValue,
  1727. // ItemSortBy.SeriesDatePlayed => "(Select MAX(LastPlayedDate) from TypedBaseItems B" + GetJoinUserDataText(query) + " where Played=1 and B.SeriesPresentationUniqueKey=A.PresentationUniqueKey)",
  1728. ItemSortBy.SeriesSortName => e => e.SeriesName,
  1729. // ItemSortBy.AiredEpisodeOrder => "AiredEpisodeOrder",
  1730. ItemSortBy.Album => e => e.Album,
  1731. ItemSortBy.DateCreated => e => e.DateCreated,
  1732. ItemSortBy.PremiereDate => e => e.PremiereDate,
  1733. ItemSortBy.StartDate => e => e.StartDate,
  1734. ItemSortBy.Name => e => e.Name,
  1735. ItemSortBy.CommunityRating => e => e.CommunityRating,
  1736. ItemSortBy.ProductionYear => e => e.ProductionYear,
  1737. ItemSortBy.CriticRating => e => e.CriticRating,
  1738. ItemSortBy.VideoBitRate => e => e.TotalBitrate,
  1739. ItemSortBy.ParentIndexNumber => e => e.ParentIndexNumber,
  1740. ItemSortBy.IndexNumber => e => e.IndexNumber,
  1741. _ => e => e.SortName
  1742. };
  1743. #pragma warning restore CS8603 // Possible null reference return.
  1744. }
  1745. private bool EnableGroupByPresentationUniqueKey(InternalItemsQuery query)
  1746. {
  1747. if (!query.GroupByPresentationUniqueKey)
  1748. {
  1749. return false;
  1750. }
  1751. if (query.GroupBySeriesPresentationUniqueKey)
  1752. {
  1753. return false;
  1754. }
  1755. if (!string.IsNullOrWhiteSpace(query.PresentationUniqueKey))
  1756. {
  1757. return false;
  1758. }
  1759. if (query.User is null)
  1760. {
  1761. return false;
  1762. }
  1763. if (query.IncludeItemTypes.Length == 0)
  1764. {
  1765. return true;
  1766. }
  1767. return query.IncludeItemTypes.Contains(BaseItemKind.Episode)
  1768. || query.IncludeItemTypes.Contains(BaseItemKind.Video)
  1769. || query.IncludeItemTypes.Contains(BaseItemKind.Movie)
  1770. || query.IncludeItemTypes.Contains(BaseItemKind.MusicVideo)
  1771. || query.IncludeItemTypes.Contains(BaseItemKind.Series)
  1772. || query.IncludeItemTypes.Contains(BaseItemKind.Season);
  1773. }
  1774. private IQueryable<BaseItemEntity> ApplyOrder(IQueryable<BaseItemEntity> query, InternalItemsQuery filter)
  1775. {
  1776. var orderBy = filter.OrderBy;
  1777. bool hasSearch = !string.IsNullOrEmpty(filter.SearchTerm);
  1778. if (hasSearch)
  1779. {
  1780. List<(ItemSortBy, SortOrder)> prepend = new List<(ItemSortBy, SortOrder)>(4);
  1781. if (hasSearch)
  1782. {
  1783. prepend.Add((ItemSortBy.SortName, SortOrder.Ascending));
  1784. }
  1785. orderBy = filter.OrderBy = [.. prepend, .. orderBy];
  1786. }
  1787. else if (orderBy.Count == 0)
  1788. {
  1789. return query;
  1790. }
  1791. foreach (var item in orderBy)
  1792. {
  1793. var expression = MapOrderByField(item.OrderBy, filter);
  1794. if (item.SortOrder == SortOrder.Ascending)
  1795. {
  1796. query = query.OrderBy(expression);
  1797. }
  1798. else
  1799. {
  1800. query = query.OrderByDescending(expression);
  1801. }
  1802. }
  1803. return query;
  1804. }
  1805. }