BaseItemManager.cs 64 KB

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