BaseItemManager.cs 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918
  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. foreach (var item in query.ExcludeProviderIds.Where(e => e.Key != nameof(MetadataProvider.TmdbCollection))
  778. .Select(e => $"{e.Key}={e.Value}"))
  779. {
  780. baseQuery = baseQuery
  781. .Where(e => e.ProviderIds == null || !e.ProviderIds.Contains(item));
  782. }
  783. }
  784. if (query.HasAnyProviderId is not null && query.HasAnyProviderId.Count > 0)
  785. {
  786. baseQuery = baseQuery
  787. .Where(e => e.ProviderIds == null || !e.ProviderIds.Contains(item));
  788. var hasProviderIds = new List<string>();
  789. var index = 0;
  790. foreach (var pair in query.HasAnyProviderId)
  791. {
  792. if (string.Equals(pair.Key, nameof(MetadataProvider.TmdbCollection), StringComparison.OrdinalIgnoreCase))
  793. {
  794. continue;
  795. }
  796. // TODO this seems to be an idea for a better schema where ProviderIds are their own table
  797. // but this is not implemented
  798. // hasProviderIds.Add("(COALESCE((select value from ProviderIds where ItemId=Guid and Name = '" + pair.Key + "'), '') <> " + paramName + ")");
  799. // TODO this is a really BAD way to do it since the pair:
  800. // Tmdb, 1234 matches Tmdb=1234 but also Tmdb=1234567
  801. // and maybe even NotTmdb=1234.
  802. // this is a placeholder for this specific pair to correlate it in the bigger query
  803. var paramName = "@HasAnyProviderId" + index;
  804. // this is a search for the placeholder
  805. hasProviderIds.Add("ProviderIds like " + paramName);
  806. // this replaces the placeholder with a value, here: %key=val%
  807. statement?.TryBind(paramName, "%" + pair.Key + "=" + pair.Value + "%");
  808. index++;
  809. break;
  810. }
  811. if (hasProviderIds.Count > 0)
  812. {
  813. whereClauses.Add("(" + string.Join(" OR ", hasProviderIds) + ")");
  814. }
  815. }
  816. if (query.HasImdbId.HasValue)
  817. {
  818. whereClauses.Add(GetProviderIdClause(query.HasImdbId.Value, "imdb"));
  819. }
  820. if (query.HasTmdbId.HasValue)
  821. {
  822. whereClauses.Add(GetProviderIdClause(query.HasTmdbId.Value, "tmdb"));
  823. }
  824. if (query.HasTvdbId.HasValue)
  825. {
  826. whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb"));
  827. }
  828. var queryTopParentIds = query.TopParentIds;
  829. if (queryTopParentIds.Length > 0)
  830. {
  831. var includedItemByNameTypes = GetItemByNameTypesInQuery(query);
  832. var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0;
  833. if (queryTopParentIds.Length == 1)
  834. {
  835. if (enableItemsByName && includedItemByNameTypes.Count == 1)
  836. {
  837. whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)");
  838. statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
  839. }
  840. else if (enableItemsByName && includedItemByNameTypes.Count > 1)
  841. {
  842. var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
  843. whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))");
  844. }
  845. else
  846. {
  847. whereClauses.Add("(TopParentId=@TopParentId)");
  848. }
  849. statement?.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture));
  850. }
  851. else if (queryTopParentIds.Length > 1)
  852. {
  853. var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
  854. if (enableItemsByName && includedItemByNameTypes.Count == 1)
  855. {
  856. whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))");
  857. statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
  858. }
  859. else if (enableItemsByName && includedItemByNameTypes.Count > 1)
  860. {
  861. var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
  862. whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))");
  863. }
  864. else
  865. {
  866. whereClauses.Add("TopParentId in (" + val + ")");
  867. }
  868. }
  869. }
  870. if (query.AncestorIds.Length == 1)
  871. {
  872. whereClauses.Add("Guid in (select itemId from AncestorIds where AncestorId=@AncestorId)");
  873. statement?.TryBind("@AncestorId", query.AncestorIds[0]);
  874. }
  875. if (query.AncestorIds.Length > 1)
  876. {
  877. var inClause = string.Join(',', query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
  878. whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause));
  879. }
  880. if (!string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey))
  881. {
  882. var inClause = "select guid from TypedBaseItems where PresentationUniqueKey=@AncestorWithPresentationUniqueKey";
  883. whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorId in ({0}))", inClause));
  884. statement?.TryBind("@AncestorWithPresentationUniqueKey", query.AncestorWithPresentationUniqueKey);
  885. }
  886. if (!string.IsNullOrWhiteSpace(query.SeriesPresentationUniqueKey))
  887. {
  888. whereClauses.Add("SeriesPresentationUniqueKey=@SeriesPresentationUniqueKey");
  889. statement?.TryBind("@SeriesPresentationUniqueKey", query.SeriesPresentationUniqueKey);
  890. }
  891. if (query.ExcludeInheritedTags.Length > 0)
  892. {
  893. var paramName = "@ExcludeInheritedTags";
  894. if (statement is null)
  895. {
  896. int index = 0;
  897. string excludedTags = string.Join(',', query.ExcludeInheritedTags.Select(_ => paramName + index++));
  898. whereClauses.Add("((select CleanValue from ItemValues where ItemId=Guid and Type=6 and cleanvalue in (" + excludedTags + ")) is null)");
  899. }
  900. else
  901. {
  902. for (int index = 0; index < query.ExcludeInheritedTags.Length; index++)
  903. {
  904. statement.TryBind(paramName + index, GetCleanValue(query.ExcludeInheritedTags[index]));
  905. }
  906. }
  907. }
  908. if (query.IncludeInheritedTags.Length > 0)
  909. {
  910. var paramName = "@IncludeInheritedTags";
  911. if (statement is null)
  912. {
  913. int index = 0;
  914. string includedTags = string.Join(',', query.IncludeInheritedTags.Select(_ => paramName + index++));
  915. // Episodes do not store inherit tags from their parents in the database, and the tag may be still required by the client.
  916. // In addtion to the tags for the episodes themselves, we need to manually query its parent (the season)'s tags as well.
  917. if (includeTypes.Length == 1 && includeTypes.FirstOrDefault() is BaseItemKind.Episode)
  918. {
  919. whereClauses.Add($"""
  920. ((select CleanValue from ItemValues where ItemId=Guid and Type=6 and CleanValue in ({includedTags})) is not null
  921. OR (select CleanValue from ItemValues where ItemId=ParentId and Type=6 and CleanValue in ({includedTags})) is not null)
  922. """);
  923. }
  924. // A playlist should be accessible to its owner regardless of allowed tags.
  925. else if (includeTypes.Length == 1 && includeTypes.FirstOrDefault() is BaseItemKind.Playlist)
  926. {
  927. whereClauses.Add($"""
  928. ((select CleanValue from ItemValues where ItemId=Guid and Type=6 and CleanValue in ({includedTags})) is not null
  929. OR data like @PlaylistOwnerUserId)
  930. """);
  931. }
  932. else
  933. {
  934. whereClauses.Add("((select CleanValue from ItemValues where ItemId=Guid and Type=6 and cleanvalue in (" + includedTags + ")) is not null)");
  935. }
  936. }
  937. else
  938. {
  939. for (int index = 0; index < query.IncludeInheritedTags.Length; index++)
  940. {
  941. statement.TryBind(paramName + index, GetCleanValue(query.IncludeInheritedTags[index]));
  942. }
  943. if (query.User is not null)
  944. {
  945. statement.TryBind("@PlaylistOwnerUserId", $"""%"OwnerUserId":"{query.User.Id.ToString("N")}"%""");
  946. }
  947. }
  948. }
  949. if (query.SeriesStatuses.Length > 0)
  950. {
  951. var statuses = new List<string>();
  952. foreach (var seriesStatus in query.SeriesStatuses)
  953. {
  954. statuses.Add("data like '%" + seriesStatus + "%'");
  955. }
  956. whereClauses.Add("(" + string.Join(" OR ", statuses) + ")");
  957. }
  958. if (query.BoxSetLibraryFolders.Length > 0)
  959. {
  960. var folderIdQueries = new List<string>();
  961. foreach (var folderId in query.BoxSetLibraryFolders)
  962. {
  963. folderIdQueries.Add("data like '%" + folderId.ToString("N", CultureInfo.InvariantCulture) + "%'");
  964. }
  965. whereClauses.Add("(" + string.Join(" OR ", folderIdQueries) + ")");
  966. }
  967. if (query.VideoTypes.Length > 0)
  968. {
  969. var videoTypes = new List<string>();
  970. foreach (var videoType in query.VideoTypes)
  971. {
  972. videoTypes.Add("data like '%\"VideoType\":\"" + videoType + "\"%'");
  973. }
  974. whereClauses.Add("(" + string.Join(" OR ", videoTypes) + ")");
  975. }
  976. if (query.Is3D.HasValue)
  977. {
  978. if (query.Is3D.Value)
  979. {
  980. whereClauses.Add("data like '%Video3DFormat%'");
  981. }
  982. else
  983. {
  984. whereClauses.Add("data not like '%Video3DFormat%'");
  985. }
  986. }
  987. if (query.IsPlaceHolder.HasValue)
  988. {
  989. if (query.IsPlaceHolder.Value)
  990. {
  991. whereClauses.Add("data like '%\"IsPlaceHolder\":true%'");
  992. }
  993. else
  994. {
  995. whereClauses.Add("(data is null or data not like '%\"IsPlaceHolder\":true%')");
  996. }
  997. }
  998. if (query.HasSpecialFeature.HasValue)
  999. {
  1000. if (query.HasSpecialFeature.Value)
  1001. {
  1002. whereClauses.Add("ExtraIds not null");
  1003. }
  1004. else
  1005. {
  1006. whereClauses.Add("ExtraIds is null");
  1007. }
  1008. }
  1009. if (query.HasTrailer.HasValue)
  1010. {
  1011. if (query.HasTrailer.Value)
  1012. {
  1013. whereClauses.Add("ExtraIds not null");
  1014. }
  1015. else
  1016. {
  1017. whereClauses.Add("ExtraIds is null");
  1018. }
  1019. }
  1020. if (query.HasThemeSong.HasValue)
  1021. {
  1022. if (query.HasThemeSong.Value)
  1023. {
  1024. whereClauses.Add("ExtraIds not null");
  1025. }
  1026. else
  1027. {
  1028. whereClauses.Add("ExtraIds is null");
  1029. }
  1030. }
  1031. if (query.HasThemeVideo.HasValue)
  1032. {
  1033. if (query.HasThemeVideo.Value)
  1034. {
  1035. whereClauses.Add("ExtraIds not null");
  1036. }
  1037. else
  1038. {
  1039. whereClauses.Add("ExtraIds is null");
  1040. }
  1041. }
  1042. }
  1043. /// <summary>
  1044. /// Gets the type.
  1045. /// </summary>
  1046. /// <param name="typeName">Name of the type.</param>
  1047. /// <returns>Type.</returns>
  1048. /// <exception cref="ArgumentNullException"><c>typeName</c> is null.</exception>
  1049. private static Type? GetType(string typeName)
  1050. {
  1051. ArgumentException.ThrowIfNullOrEmpty(typeName);
  1052. return _typeMap.GetOrAdd(typeName, k => AppDomain.CurrentDomain.GetAssemblies()
  1053. .Select(a => a.GetType(k))
  1054. .FirstOrDefault(t => t is not null));
  1055. }
  1056. /// <inheritdoc cref="IItemRepository" />
  1057. public void SaveImages(BaseItem item)
  1058. {
  1059. ArgumentNullException.ThrowIfNull(item);
  1060. var images = SerializeImages(item.ImageInfos);
  1061. using var db = _dbProvider.CreateDbContext();
  1062. db.BaseItems
  1063. .Where(e => e.Id.Equals(item.Id))
  1064. .ExecuteUpdate(e => e.SetProperty(f => f.Images, images));
  1065. }
  1066. /// <inheritdoc cref="IItemRepository" />
  1067. public void SaveItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
  1068. {
  1069. UpdateOrInsertItems(items, cancellationToken);
  1070. }
  1071. /// <inheritdoc cref="IItemRepository" />
  1072. public void UpdateOrInsertItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
  1073. {
  1074. ArgumentNullException.ThrowIfNull(items);
  1075. cancellationToken.ThrowIfCancellationRequested();
  1076. var itemsLen = items.Count;
  1077. var tuples = new (BaseItemDto Item, List<Guid>? AncestorIds, BaseItemDto TopParent, string? UserDataKey, List<string> InheritedTags)[itemsLen];
  1078. for (int i = 0; i < itemsLen; i++)
  1079. {
  1080. var item = items[i];
  1081. var ancestorIds = item.SupportsAncestors ?
  1082. item.GetAncestorIds().Distinct().ToList() :
  1083. null;
  1084. var topParent = item.GetTopParent();
  1085. var userdataKey = item.GetUserDataKeys().FirstOrDefault();
  1086. var inheritedTags = item.GetInheritedTags();
  1087. tuples[i] = (item, ancestorIds, topParent, userdataKey, inheritedTags);
  1088. }
  1089. using var context = _dbProvider.CreateDbContext();
  1090. foreach (var item in tuples)
  1091. {
  1092. var entity = Map(item.Item);
  1093. context.BaseItems.Add(entity);
  1094. if (item.Item.SupportsAncestors && item.AncestorIds != null)
  1095. {
  1096. foreach (var ancestorId in item.AncestorIds)
  1097. {
  1098. context.AncestorIds.Add(new Data.Entities.AncestorId()
  1099. {
  1100. Item = entity,
  1101. AncestorIdText = ancestorId.ToString(),
  1102. Id = ancestorId
  1103. });
  1104. }
  1105. }
  1106. var itemValues = GetItemValuesToSave(item.Item, item.InheritedTags);
  1107. context.ItemValues.Where(e => e.ItemId.Equals(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. });
  1117. }
  1118. }
  1119. context.SaveChanges(true);
  1120. }
  1121. /// <inheritdoc cref="IItemRepository" />
  1122. public BaseItemDto? RetrieveItem(Guid id)
  1123. {
  1124. if (id.IsEmpty())
  1125. {
  1126. throw new ArgumentException("Guid can't be empty", nameof(id));
  1127. }
  1128. using var context = _dbProvider.CreateDbContext();
  1129. var item = context.BaseItems.FirstOrDefault(e => e.Id.Equals(id));
  1130. if (item is null)
  1131. {
  1132. return null;
  1133. }
  1134. return DeserialiseBaseItem(item);
  1135. }
  1136. /// <summary>
  1137. /// Maps a Entity to the DTO.
  1138. /// </summary>
  1139. /// <param name="entity">The entity.</param>
  1140. /// <param name="dto">The dto base instance.</param>
  1141. /// <returns>The dto to map.</returns>
  1142. public BaseItemDto Map(BaseItemEntity entity, BaseItemDto dto)
  1143. {
  1144. dto.Id = entity.Id;
  1145. dto.ParentId = entity.ParentId.GetValueOrDefault();
  1146. dto.Path = entity.Path;
  1147. dto.EndDate = entity.EndDate;
  1148. dto.CommunityRating = entity.CommunityRating;
  1149. dto.CustomRating = entity.CustomRating;
  1150. dto.IndexNumber = entity.IndexNumber;
  1151. dto.IsLocked = entity.IsLocked;
  1152. dto.Name = entity.Name;
  1153. dto.OfficialRating = entity.OfficialRating;
  1154. dto.Overview = entity.Overview;
  1155. dto.ParentIndexNumber = entity.ParentIndexNumber;
  1156. dto.PremiereDate = entity.PremiereDate;
  1157. dto.ProductionYear = entity.ProductionYear;
  1158. dto.SortName = entity.SortName;
  1159. dto.ForcedSortName = entity.ForcedSortName;
  1160. dto.RunTimeTicks = entity.RunTimeTicks;
  1161. dto.PreferredMetadataLanguage = entity.PreferredMetadataLanguage;
  1162. dto.PreferredMetadataCountryCode = entity.PreferredMetadataCountryCode;
  1163. dto.IsInMixedFolder = entity.IsInMixedFolder;
  1164. dto.InheritedParentalRatingValue = entity.InheritedParentalRatingValue;
  1165. dto.CriticRating = entity.CriticRating;
  1166. dto.PresentationUniqueKey = entity.PresentationUniqueKey;
  1167. dto.OriginalTitle = entity.OriginalTitle;
  1168. dto.Album = entity.Album;
  1169. dto.LUFS = entity.LUFS;
  1170. dto.NormalizationGain = entity.NormalizationGain;
  1171. dto.IsVirtualItem = entity.IsVirtualItem;
  1172. dto.ExternalSeriesId = entity.ExternalSeriesId;
  1173. dto.Tagline = entity.Tagline;
  1174. dto.TotalBitrate = entity.TotalBitrate;
  1175. dto.ExternalId = entity.ExternalId;
  1176. dto.Size = entity.Size;
  1177. dto.Genres = entity.Genres?.Split('|');
  1178. dto.DateCreated = entity.DateCreated.GetValueOrDefault();
  1179. dto.DateModified = entity.DateModified.GetValueOrDefault();
  1180. dto.ChannelId = string.IsNullOrWhiteSpace(entity.ChannelId) ? Guid.Empty : Guid.Parse(entity.ChannelId);
  1181. dto.DateLastRefreshed = entity.DateLastRefreshed.GetValueOrDefault();
  1182. dto.DateLastSaved = entity.DateLastSaved.GetValueOrDefault();
  1183. dto.OwnerId = string.IsNullOrWhiteSpace(entity.OwnerId) ? Guid.Empty : Guid.Parse(entity.OwnerId);
  1184. dto.Width = entity.Width.GetValueOrDefault();
  1185. dto.Height = entity.Height.GetValueOrDefault();
  1186. if (entity.ProviderIds is not null)
  1187. {
  1188. DeserializeProviderIds(entity.ProviderIds, dto);
  1189. }
  1190. if (entity.ExtraType is not null)
  1191. {
  1192. dto.ExtraType = Enum.Parse<ExtraType>(entity.ExtraType);
  1193. }
  1194. if (entity.LockedFields is not null)
  1195. {
  1196. List<MetadataField>? fields = null;
  1197. foreach (var i in entity.LockedFields.AsSpan().Split('|'))
  1198. {
  1199. if (Enum.TryParse(i, true, out MetadataField parsedValue))
  1200. {
  1201. (fields ??= new List<MetadataField>()).Add(parsedValue);
  1202. }
  1203. }
  1204. dto.LockedFields = fields?.ToArray() ?? Array.Empty<MetadataField>();
  1205. }
  1206. if (entity.Audio is not null)
  1207. {
  1208. dto.Audio = Enum.Parse<ProgramAudio>(entity.Audio);
  1209. }
  1210. dto.ExtraIds = entity.ExtraIds?.Split('|').Select(e => Guid.Parse(e)).ToArray();
  1211. dto.ProductionLocations = entity.ProductionLocations?.Split('|');
  1212. dto.Studios = entity.Studios?.Split('|');
  1213. dto.Tags = entity.Tags?.Split('|');
  1214. if (dto is IHasProgramAttributes hasProgramAttributes)
  1215. {
  1216. hasProgramAttributes.IsMovie = entity.IsMovie;
  1217. hasProgramAttributes.IsSeries = entity.IsSeries;
  1218. hasProgramAttributes.EpisodeTitle = entity.EpisodeTitle;
  1219. hasProgramAttributes.IsRepeat = entity.IsRepeat;
  1220. }
  1221. if (dto is LiveTvChannel liveTvChannel)
  1222. {
  1223. liveTvChannel.ServiceName = entity.ExternalServiceId;
  1224. }
  1225. if (dto is Trailer trailer)
  1226. {
  1227. List<TrailerType>? types = null;
  1228. foreach (var i in entity.TrailerTypes.AsSpan().Split('|'))
  1229. {
  1230. if (Enum.TryParse(i, true, out TrailerType parsedValue))
  1231. {
  1232. (types ??= new List<TrailerType>()).Add(parsedValue);
  1233. }
  1234. }
  1235. trailer.TrailerTypes = types?.ToArray() ?? Array.Empty<TrailerType>();
  1236. }
  1237. if (dto is Video video)
  1238. {
  1239. video.PrimaryVersionId = entity.PrimaryVersionId;
  1240. }
  1241. if (dto is IHasSeries hasSeriesName)
  1242. {
  1243. hasSeriesName.SeriesName = entity.SeriesName;
  1244. hasSeriesName.SeriesId = entity.SeriesId.GetValueOrDefault();
  1245. hasSeriesName.SeriesPresentationUniqueKey = entity.SeriesPresentationUniqueKey;
  1246. }
  1247. if (dto is Episode episode)
  1248. {
  1249. episode.SeasonName = entity.SeasonName;
  1250. episode.SeasonId = entity.SeasonId.GetValueOrDefault();
  1251. }
  1252. if (dto is IHasArtist hasArtists)
  1253. {
  1254. hasArtists.Artists = entity.Artists?.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1255. }
  1256. if (dto is IHasAlbumArtist hasAlbumArtists)
  1257. {
  1258. hasAlbumArtists.AlbumArtists = entity.AlbumArtists?.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1259. }
  1260. if (dto is LiveTvProgram program)
  1261. {
  1262. program.ShowId = entity.ShowId;
  1263. }
  1264. if (entity.Images is not null)
  1265. {
  1266. dto.ImageInfos = DeserializeImages(entity.Images);
  1267. }
  1268. // dto.Type = entity.Type;
  1269. // dto.Data = entity.Data;
  1270. // dto.MediaType = entity.MediaType;
  1271. if (dto is IHasStartDate hasStartDate)
  1272. {
  1273. hasStartDate.StartDate = entity.StartDate;
  1274. }
  1275. // Fields that are present in the DB but are never actually used
  1276. // dto.UnratedType = entity.UnratedType;
  1277. // dto.TopParentId = entity.TopParentId;
  1278. // dto.CleanName = entity.CleanName;
  1279. // dto.UserDataKey = entity.UserDataKey;
  1280. if (dto is Folder folder)
  1281. {
  1282. folder.DateLastMediaAdded = entity.DateLastMediaAdded;
  1283. }
  1284. return dto;
  1285. }
  1286. /// <summary>
  1287. /// Maps a Entity to the DTO.
  1288. /// </summary>
  1289. /// <param name="dto">The entity.</param>
  1290. /// <returns>The dto to map.</returns>
  1291. public BaseItemEntity Map(BaseItemDto dto)
  1292. {
  1293. var entity = new BaseItemEntity()
  1294. {
  1295. Type = dto.GetType().ToString(),
  1296. };
  1297. entity.Id = dto.Id;
  1298. entity.ParentId = dto.ParentId;
  1299. entity.Path = GetPathToSave(dto.Path);
  1300. entity.EndDate = dto.EndDate.GetValueOrDefault();
  1301. entity.CommunityRating = dto.CommunityRating;
  1302. entity.CustomRating = dto.CustomRating;
  1303. entity.IndexNumber = dto.IndexNumber;
  1304. entity.IsLocked = dto.IsLocked;
  1305. entity.Name = dto.Name;
  1306. entity.OfficialRating = dto.OfficialRating;
  1307. entity.Overview = dto.Overview;
  1308. entity.ParentIndexNumber = dto.ParentIndexNumber;
  1309. entity.PremiereDate = dto.PremiereDate;
  1310. entity.ProductionYear = dto.ProductionYear;
  1311. entity.SortName = dto.SortName;
  1312. entity.ForcedSortName = dto.ForcedSortName;
  1313. entity.RunTimeTicks = dto.RunTimeTicks;
  1314. entity.PreferredMetadataLanguage = dto.PreferredMetadataLanguage;
  1315. entity.PreferredMetadataCountryCode = dto.PreferredMetadataCountryCode;
  1316. entity.IsInMixedFolder = dto.IsInMixedFolder;
  1317. entity.InheritedParentalRatingValue = dto.InheritedParentalRatingValue;
  1318. entity.CriticRating = dto.CriticRating;
  1319. entity.PresentationUniqueKey = dto.PresentationUniqueKey;
  1320. entity.OriginalTitle = dto.OriginalTitle;
  1321. entity.Album = dto.Album;
  1322. entity.LUFS = dto.LUFS;
  1323. entity.NormalizationGain = dto.NormalizationGain;
  1324. entity.IsVirtualItem = dto.IsVirtualItem;
  1325. entity.ExternalSeriesId = dto.ExternalSeriesId;
  1326. entity.Tagline = dto.Tagline;
  1327. entity.TotalBitrate = dto.TotalBitrate;
  1328. entity.ExternalId = dto.ExternalId;
  1329. entity.Size = dto.Size;
  1330. entity.Genres = string.Join('|', dto.Genres);
  1331. entity.DateCreated = dto.DateCreated;
  1332. entity.DateModified = dto.DateModified;
  1333. entity.ChannelId = dto.ChannelId.ToString();
  1334. entity.DateLastRefreshed = dto.DateLastRefreshed;
  1335. entity.DateLastSaved = dto.DateLastSaved;
  1336. entity.OwnerId = dto.OwnerId.ToString();
  1337. entity.Width = dto.Width;
  1338. entity.Height = dto.Height;
  1339. entity.ProviderIds = SerializeProviderIds(dto.ProviderIds);
  1340. entity.Audio = dto.Audio?.ToString();
  1341. entity.ExtraType = dto.ExtraType?.ToString();
  1342. entity.ExtraIds = string.Join('|', dto.ExtraIds);
  1343. entity.ProductionLocations = string.Join('|', dto.ProductionLocations);
  1344. entity.Studios = dto.Studios is not null ? string.Join('|', dto.Studios) : null;
  1345. entity.Tags = dto.Tags is not null ? string.Join('|', dto.Tags) : null;
  1346. entity.LockedFields = dto.LockedFields is not null ? string.Join('|', dto.LockedFields) : null;
  1347. if (dto is IHasProgramAttributes hasProgramAttributes)
  1348. {
  1349. entity.IsMovie = hasProgramAttributes.IsMovie;
  1350. entity.IsSeries = hasProgramAttributes.IsSeries;
  1351. entity.EpisodeTitle = hasProgramAttributes.EpisodeTitle;
  1352. entity.IsRepeat = hasProgramAttributes.IsRepeat;
  1353. }
  1354. if (dto is LiveTvChannel liveTvChannel)
  1355. {
  1356. entity.ExternalServiceId = liveTvChannel.ServiceName;
  1357. }
  1358. if (dto is Trailer trailer)
  1359. {
  1360. entity.LockedFields = trailer.LockedFields is not null ? string.Join('|', trailer.LockedFields) : null;
  1361. }
  1362. if (dto is Video video)
  1363. {
  1364. entity.PrimaryVersionId = video.PrimaryVersionId;
  1365. }
  1366. if (dto is IHasSeries hasSeriesName)
  1367. {
  1368. entity.SeriesName = hasSeriesName.SeriesName;
  1369. entity.SeriesId = hasSeriesName.SeriesId;
  1370. entity.SeriesPresentationUniqueKey = hasSeriesName.SeriesPresentationUniqueKey;
  1371. }
  1372. if (dto is Episode episode)
  1373. {
  1374. entity.SeasonName = episode.SeasonName;
  1375. entity.SeasonId = episode.SeasonId;
  1376. }
  1377. if (dto is IHasArtist hasArtists)
  1378. {
  1379. entity.Artists = hasArtists.Artists is not null ? string.Join('|', hasArtists.Artists) : null;
  1380. }
  1381. if (dto is IHasAlbumArtist hasAlbumArtists)
  1382. {
  1383. entity.AlbumArtists = hasAlbumArtists.AlbumArtists is not null ? string.Join('|', hasAlbumArtists.AlbumArtists) : null;
  1384. }
  1385. if (dto is LiveTvProgram program)
  1386. {
  1387. entity.ShowId = program.ShowId;
  1388. }
  1389. if (dto.ImageInfos is not null)
  1390. {
  1391. entity.Images = SerializeImages(dto.ImageInfos);
  1392. }
  1393. // dto.Type = entity.Type;
  1394. // dto.Data = entity.Data;
  1395. // dto.MediaType = entity.MediaType;
  1396. if (dto is IHasStartDate hasStartDate)
  1397. {
  1398. entity.StartDate = hasStartDate.StartDate;
  1399. }
  1400. // Fields that are present in the DB but are never actually used
  1401. // dto.UnratedType = entity.UnratedType;
  1402. // dto.TopParentId = entity.TopParentId;
  1403. // dto.CleanName = entity.CleanName;
  1404. // dto.UserDataKey = entity.UserDataKey;
  1405. if (dto is Folder folder)
  1406. {
  1407. entity.DateLastMediaAdded = folder.DateLastMediaAdded;
  1408. entity.IsFolder = folder.IsFolder;
  1409. }
  1410. return entity;
  1411. }
  1412. private BaseItemDto DeserialiseBaseItem(BaseItemEntity baseItemEntity)
  1413. {
  1414. var type = GetType(baseItemEntity.Type) ?? throw new InvalidOperationException("Cannot deserialise unkown type.");
  1415. var dto = Activator.CreateInstance(type) as BaseItemDto ?? throw new InvalidOperationException("Cannot deserialise unkown type."); ;
  1416. return Map(baseItemEntity, dto);
  1417. }
  1418. private string GetCleanValue(string value)
  1419. {
  1420. if (string.IsNullOrWhiteSpace(value))
  1421. {
  1422. return value;
  1423. }
  1424. return value.RemoveDiacritics().ToLowerInvariant();
  1425. }
  1426. private List<(int MagicNumber, string Value)> GetItemValuesToSave(BaseItem item, List<string> inheritedTags)
  1427. {
  1428. var list = new List<(int, string)>();
  1429. if (item is IHasArtist hasArtist)
  1430. {
  1431. list.AddRange(hasArtist.Artists.Select(i => (0, i)));
  1432. }
  1433. if (item is IHasAlbumArtist hasAlbumArtist)
  1434. {
  1435. list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i)));
  1436. }
  1437. list.AddRange(item.Genres.Select(i => (2, i)));
  1438. list.AddRange(item.Studios.Select(i => (3, i)));
  1439. list.AddRange(item.Tags.Select(i => (4, i)));
  1440. // keywords was 5
  1441. list.AddRange(inheritedTags.Select(i => (6, i)));
  1442. // Remove all invalid values.
  1443. list.RemoveAll(i => string.IsNullOrWhiteSpace(i.Item2));
  1444. return list;
  1445. }
  1446. internal static string? SerializeProviderIds(Dictionary<string, string> providerIds)
  1447. {
  1448. StringBuilder str = new StringBuilder();
  1449. foreach (var i in providerIds)
  1450. {
  1451. // Ideally we shouldn't need this IsNullOrWhiteSpace check,
  1452. // but we're seeing some cases of bad data slip through
  1453. if (string.IsNullOrWhiteSpace(i.Value))
  1454. {
  1455. continue;
  1456. }
  1457. str.Append(i.Key)
  1458. .Append('=')
  1459. .Append(i.Value)
  1460. .Append('|');
  1461. }
  1462. if (str.Length == 0)
  1463. {
  1464. return null;
  1465. }
  1466. str.Length -= 1; // Remove last |
  1467. return str.ToString();
  1468. }
  1469. internal static void DeserializeProviderIds(string value, IHasProviderIds item)
  1470. {
  1471. if (string.IsNullOrWhiteSpace(value))
  1472. {
  1473. return;
  1474. }
  1475. foreach (var part in value.SpanSplit('|'))
  1476. {
  1477. var providerDelimiterIndex = part.IndexOf('=');
  1478. // Don't let empty values through
  1479. if (providerDelimiterIndex != -1 && part.Length != providerDelimiterIndex + 1)
  1480. {
  1481. item.SetProviderId(part[..providerDelimiterIndex].ToString(), part[(providerDelimiterIndex + 1)..].ToString());
  1482. }
  1483. }
  1484. }
  1485. internal string? SerializeImages(ItemImageInfo[] images)
  1486. {
  1487. if (images.Length == 0)
  1488. {
  1489. return null;
  1490. }
  1491. StringBuilder str = new StringBuilder();
  1492. foreach (var i in images)
  1493. {
  1494. if (string.IsNullOrWhiteSpace(i.Path))
  1495. {
  1496. continue;
  1497. }
  1498. AppendItemImageInfo(str, i);
  1499. str.Append('|');
  1500. }
  1501. str.Length -= 1; // Remove last |
  1502. return str.ToString();
  1503. }
  1504. internal ItemImageInfo[] DeserializeImages(string value)
  1505. {
  1506. if (string.IsNullOrWhiteSpace(value))
  1507. {
  1508. return Array.Empty<ItemImageInfo>();
  1509. }
  1510. // TODO The following is an ugly performance optimization, but it's extremely unlikely that the data in the database would be malformed
  1511. var valueSpan = value.AsSpan();
  1512. var count = valueSpan.Count('|') + 1;
  1513. var position = 0;
  1514. var result = new ItemImageInfo[count];
  1515. foreach (var part in valueSpan.Split('|'))
  1516. {
  1517. var image = ItemImageInfoFromValueString(part);
  1518. if (image is not null)
  1519. {
  1520. result[position++] = image;
  1521. }
  1522. }
  1523. if (position == count)
  1524. {
  1525. return result;
  1526. }
  1527. if (position == 0)
  1528. {
  1529. return Array.Empty<ItemImageInfo>();
  1530. }
  1531. // Extremely unlikely, but somehow one or more of the image strings were malformed. Cut the array.
  1532. return result[..position];
  1533. }
  1534. private void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image)
  1535. {
  1536. const char Delimiter = '*';
  1537. var path = image.Path ?? string.Empty;
  1538. bldr.Append(GetPathToSave(path))
  1539. .Append(Delimiter)
  1540. .Append(image.DateModified.Ticks)
  1541. .Append(Delimiter)
  1542. .Append(image.Type)
  1543. .Append(Delimiter)
  1544. .Append(image.Width)
  1545. .Append(Delimiter)
  1546. .Append(image.Height);
  1547. var hash = image.BlurHash;
  1548. if (!string.IsNullOrEmpty(hash))
  1549. {
  1550. bldr.Append(Delimiter)
  1551. // Replace delimiters with other characters.
  1552. // This can be removed when we migrate to a proper DB.
  1553. .Append(hash.Replace(Delimiter, '/').Replace('|', '\\'));
  1554. }
  1555. }
  1556. private string? GetPathToSave(string path)
  1557. {
  1558. if (path is null)
  1559. {
  1560. return null;
  1561. }
  1562. return _appHost.ReverseVirtualPath(path);
  1563. }
  1564. private string RestorePath(string path)
  1565. {
  1566. return _appHost.ExpandVirtualPath(path);
  1567. }
  1568. internal ItemImageInfo? ItemImageInfoFromValueString(ReadOnlySpan<char> value)
  1569. {
  1570. const char Delimiter = '*';
  1571. var nextSegment = value.IndexOf(Delimiter);
  1572. if (nextSegment == -1)
  1573. {
  1574. return null;
  1575. }
  1576. ReadOnlySpan<char> path = value[..nextSegment];
  1577. value = value[(nextSegment + 1)..];
  1578. nextSegment = value.IndexOf(Delimiter);
  1579. if (nextSegment == -1)
  1580. {
  1581. return null;
  1582. }
  1583. ReadOnlySpan<char> dateModified = 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> imageType = value[..nextSegment];
  1591. var image = new ItemImageInfo
  1592. {
  1593. Path = RestorePath(path.ToString())
  1594. };
  1595. if (long.TryParse(dateModified, CultureInfo.InvariantCulture, out var ticks)
  1596. && ticks >= DateTime.MinValue.Ticks
  1597. && ticks <= DateTime.MaxValue.Ticks)
  1598. {
  1599. image.DateModified = new DateTime(ticks, DateTimeKind.Utc);
  1600. }
  1601. else
  1602. {
  1603. return null;
  1604. }
  1605. if (Enum.TryParse(imageType, true, out ImageType type))
  1606. {
  1607. image.Type = type;
  1608. }
  1609. else
  1610. {
  1611. return null;
  1612. }
  1613. // Optional parameters: width*height*blurhash
  1614. if (nextSegment + 1 < value.Length - 1)
  1615. {
  1616. value = value[(nextSegment + 1)..];
  1617. nextSegment = value.IndexOf(Delimiter);
  1618. if (nextSegment == -1 || nextSegment == value.Length)
  1619. {
  1620. return image;
  1621. }
  1622. ReadOnlySpan<char> widthSpan = value[..nextSegment];
  1623. value = value[(nextSegment + 1)..];
  1624. nextSegment = value.IndexOf(Delimiter);
  1625. if (nextSegment == -1)
  1626. {
  1627. nextSegment = value.Length;
  1628. }
  1629. ReadOnlySpan<char> heightSpan = value[..nextSegment];
  1630. if (int.TryParse(widthSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var width)
  1631. && int.TryParse(heightSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var height))
  1632. {
  1633. image.Width = width;
  1634. image.Height = height;
  1635. }
  1636. if (nextSegment < value.Length - 1)
  1637. {
  1638. value = value[(nextSegment + 1)..];
  1639. var length = value.Length;
  1640. Span<char> blurHashSpan = stackalloc char[length];
  1641. for (int i = 0; i < length; i++)
  1642. {
  1643. var c = value[i];
  1644. blurHashSpan[i] = c switch
  1645. {
  1646. '/' => Delimiter,
  1647. '\\' => '|',
  1648. _ => c
  1649. };
  1650. }
  1651. image.BlurHash = new string(blurHashSpan);
  1652. }
  1653. }
  1654. return image;
  1655. }
  1656. }