BaseItemRepository.cs 77 KB

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