SqliteItemRepository.cs 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Buffers.Text;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading;
  12. using Emby.Server.Implementations.Playlists;
  13. using Jellyfin.Data.Enums;
  14. using Jellyfin.Extensions;
  15. using Jellyfin.Extensions.Json;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Controller.Channels;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Drawing;
  20. using MediaBrowser.Controller.Entities;
  21. using MediaBrowser.Controller.Entities.Audio;
  22. using MediaBrowser.Controller.Entities.Movies;
  23. using MediaBrowser.Controller.Entities.TV;
  24. using MediaBrowser.Controller.Library;
  25. using MediaBrowser.Controller.LiveTv;
  26. using MediaBrowser.Controller.Persistence;
  27. using MediaBrowser.Controller.Playlists;
  28. using MediaBrowser.Model.Dto;
  29. using MediaBrowser.Model.Entities;
  30. using MediaBrowser.Model.Globalization;
  31. using MediaBrowser.Model.LiveTv;
  32. using MediaBrowser.Model.Querying;
  33. using Microsoft.Extensions.Logging;
  34. using SQLitePCL.pretty;
  35. namespace Emby.Server.Implementations.Data
  36. {
  37. /// <summary>
  38. /// Class SQLiteItemRepository.
  39. /// </summary>
  40. public class SqliteItemRepository : BaseSqliteRepository, IItemRepository
  41. {
  42. private const string FromText = " from TypedBaseItems A";
  43. private const string ChaptersTableName = "Chapters2";
  44. private const string SaveItemCommandText =
  45. @"replace into TypedBaseItems
  46. (guid,type,data,Path,StartDate,EndDate,ChannelId,IsMovie,IsSeries,EpisodeTitle,IsRepeat,CommunityRating,CustomRating,IndexNumber,IsLocked,Name,OfficialRating,MediaType,Overview,ParentIndexNumber,PremiereDate,ProductionYear,ParentId,Genres,InheritedParentalRatingValue,SortName,ForcedSortName,RunTimeTicks,Size,DateCreated,DateModified,PreferredMetadataLanguage,PreferredMetadataCountryCode,Width,Height,DateLastRefreshed,DateLastSaved,IsInMixedFolder,LockedFields,Studios,Audio,ExternalServiceId,Tags,IsFolder,UnratedType,TopParentId,TrailerTypes,CriticRating,CleanName,PresentationUniqueKey,OriginalTitle,PrimaryVersionId,DateLastMediaAdded,Album,IsVirtualItem,SeriesName,UserDataKey,SeasonName,SeasonId,SeriesId,ExternalSeriesId,Tagline,ProviderIds,Images,ProductionLocations,ExtraIds,TotalBitrate,ExtraType,Artists,AlbumArtists,ExternalId,SeriesPresentationUniqueKey,ShowId,OwnerId)
  47. values (@guid,@type,@data,@Path,@StartDate,@EndDate,@ChannelId,@IsMovie,@IsSeries,@EpisodeTitle,@IsRepeat,@CommunityRating,@CustomRating,@IndexNumber,@IsLocked,@Name,@OfficialRating,@MediaType,@Overview,@ParentIndexNumber,@PremiereDate,@ProductionYear,@ParentId,@Genres,@InheritedParentalRatingValue,@SortName,@ForcedSortName,@RunTimeTicks,@Size,@DateCreated,@DateModified,@PreferredMetadataLanguage,@PreferredMetadataCountryCode,@Width,@Height,@DateLastRefreshed,@DateLastSaved,@IsInMixedFolder,@LockedFields,@Studios,@Audio,@ExternalServiceId,@Tags,@IsFolder,@UnratedType,@TopParentId,@TrailerTypes,@CriticRating,@CleanName,@PresentationUniqueKey,@OriginalTitle,@PrimaryVersionId,@DateLastMediaAdded,@Album,@IsVirtualItem,@SeriesName,@UserDataKey,@SeasonName,@SeasonId,@SeriesId,@ExternalSeriesId,@Tagline,@ProviderIds,@Images,@ProductionLocations,@ExtraIds,@TotalBitrate,@ExtraType,@Artists,@AlbumArtists,@ExternalId,@SeriesPresentationUniqueKey,@ShowId,@OwnerId)";
  48. private readonly IServerConfigurationManager _config;
  49. private readonly IServerApplicationHost _appHost;
  50. private readonly ILocalizationManager _localization;
  51. // TODO: Remove this dependency. GetImageCacheTag() is the only method used and it can be converted to a static helper method
  52. private readonly IImageProcessor _imageProcessor;
  53. private readonly TypeMapper _typeMapper;
  54. private readonly JsonSerializerOptions _jsonOptions;
  55. private readonly ItemFields[] _allItemFields = Enum.GetValues<ItemFields>();
  56. private static readonly string[] _retrieveItemColumns =
  57. {
  58. "type",
  59. "data",
  60. "StartDate",
  61. "EndDate",
  62. "ChannelId",
  63. "IsMovie",
  64. "IsSeries",
  65. "EpisodeTitle",
  66. "IsRepeat",
  67. "CommunityRating",
  68. "CustomRating",
  69. "IndexNumber",
  70. "IsLocked",
  71. "PreferredMetadataLanguage",
  72. "PreferredMetadataCountryCode",
  73. "Width",
  74. "Height",
  75. "DateLastRefreshed",
  76. "Name",
  77. "Path",
  78. "PremiereDate",
  79. "Overview",
  80. "ParentIndexNumber",
  81. "ProductionYear",
  82. "OfficialRating",
  83. "ForcedSortName",
  84. "RunTimeTicks",
  85. "Size",
  86. "DateCreated",
  87. "DateModified",
  88. "guid",
  89. "Genres",
  90. "ParentId",
  91. "Audio",
  92. "ExternalServiceId",
  93. "IsInMixedFolder",
  94. "DateLastSaved",
  95. "LockedFields",
  96. "Studios",
  97. "Tags",
  98. "TrailerTypes",
  99. "OriginalTitle",
  100. "PrimaryVersionId",
  101. "DateLastMediaAdded",
  102. "Album",
  103. "CriticRating",
  104. "IsVirtualItem",
  105. "SeriesName",
  106. "SeasonName",
  107. "SeasonId",
  108. "SeriesId",
  109. "PresentationUniqueKey",
  110. "InheritedParentalRatingValue",
  111. "ExternalSeriesId",
  112. "Tagline",
  113. "ProviderIds",
  114. "Images",
  115. "ProductionLocations",
  116. "ExtraIds",
  117. "TotalBitrate",
  118. "ExtraType",
  119. "Artists",
  120. "AlbumArtists",
  121. "ExternalId",
  122. "SeriesPresentationUniqueKey",
  123. "ShowId",
  124. "OwnerId"
  125. };
  126. private static readonly string _retrieveItemColumnsSelectQuery = $"select {string.Join(',', _retrieveItemColumns)} from TypedBaseItems where guid = @guid";
  127. private static readonly string[] _mediaStreamSaveColumns =
  128. {
  129. "ItemId",
  130. "StreamIndex",
  131. "StreamType",
  132. "Codec",
  133. "Language",
  134. "ChannelLayout",
  135. "Profile",
  136. "AspectRatio",
  137. "Path",
  138. "IsInterlaced",
  139. "BitRate",
  140. "Channels",
  141. "SampleRate",
  142. "IsDefault",
  143. "IsForced",
  144. "IsExternal",
  145. "Height",
  146. "Width",
  147. "AverageFrameRate",
  148. "RealFrameRate",
  149. "Level",
  150. "PixelFormat",
  151. "BitDepth",
  152. "IsAnamorphic",
  153. "RefFrames",
  154. "CodecTag",
  155. "Comment",
  156. "NalLengthSize",
  157. "IsAvc",
  158. "Title",
  159. "TimeBase",
  160. "CodecTimeBase",
  161. "ColorPrimaries",
  162. "ColorSpace",
  163. "ColorTransfer",
  164. "DvVersionMajor",
  165. "DvVersionMinor",
  166. "DvProfile",
  167. "DvLevel",
  168. "RpuPresentFlag",
  169. "ElPresentFlag",
  170. "BlPresentFlag",
  171. "DvBlSignalCompatibilityId",
  172. "IsHearingImpaired"
  173. };
  174. private static readonly string _mediaStreamSaveColumnsInsertQuery =
  175. $"insert into mediastreams ({string.Join(',', _mediaStreamSaveColumns)}) values ";
  176. private static readonly string _mediaStreamSaveColumnsSelectQuery =
  177. $"select {string.Join(',', _mediaStreamSaveColumns)} from mediastreams where ItemId=@ItemId";
  178. private static readonly string[] _mediaAttachmentSaveColumns =
  179. {
  180. "ItemId",
  181. "AttachmentIndex",
  182. "Codec",
  183. "CodecTag",
  184. "Comment",
  185. "Filename",
  186. "MIMEType"
  187. };
  188. private static readonly string _mediaAttachmentSaveColumnsSelectQuery =
  189. $"select {string.Join(',', _mediaAttachmentSaveColumns)} from mediaattachments where ItemId=@ItemId";
  190. private static readonly string _mediaAttachmentInsertPrefix;
  191. private static readonly BaseItemKind[] _programTypes = new[]
  192. {
  193. BaseItemKind.Program,
  194. BaseItemKind.TvChannel,
  195. BaseItemKind.LiveTvProgram,
  196. BaseItemKind.LiveTvChannel
  197. };
  198. private static readonly BaseItemKind[] _programExcludeParentTypes = new[]
  199. {
  200. BaseItemKind.Series,
  201. BaseItemKind.Season,
  202. BaseItemKind.MusicAlbum,
  203. BaseItemKind.MusicArtist,
  204. BaseItemKind.PhotoAlbum
  205. };
  206. private static readonly BaseItemKind[] _serviceTypes = new[]
  207. {
  208. BaseItemKind.TvChannel,
  209. BaseItemKind.LiveTvChannel
  210. };
  211. private static readonly BaseItemKind[] _startDateTypes = new[]
  212. {
  213. BaseItemKind.Program,
  214. BaseItemKind.LiveTvProgram
  215. };
  216. private static readonly BaseItemKind[] _seriesTypes = new[]
  217. {
  218. BaseItemKind.Book,
  219. BaseItemKind.AudioBook,
  220. BaseItemKind.Episode,
  221. BaseItemKind.Season
  222. };
  223. private static readonly BaseItemKind[] _artistExcludeParentTypes = new[]
  224. {
  225. BaseItemKind.Series,
  226. BaseItemKind.Season,
  227. BaseItemKind.PhotoAlbum
  228. };
  229. private static readonly BaseItemKind[] _artistsTypes = new[]
  230. {
  231. BaseItemKind.Audio,
  232. BaseItemKind.MusicAlbum,
  233. BaseItemKind.MusicVideo,
  234. BaseItemKind.AudioBook
  235. };
  236. private static readonly Dictionary<BaseItemKind, string> _baseItemKindNames = new()
  237. {
  238. { BaseItemKind.AggregateFolder, typeof(AggregateFolder).FullName },
  239. { BaseItemKind.Audio, typeof(Audio).FullName },
  240. { BaseItemKind.AudioBook, typeof(AudioBook).FullName },
  241. { BaseItemKind.BasePluginFolder, typeof(BasePluginFolder).FullName },
  242. { BaseItemKind.Book, typeof(Book).FullName },
  243. { BaseItemKind.BoxSet, typeof(BoxSet).FullName },
  244. { BaseItemKind.Channel, typeof(Channel).FullName },
  245. { BaseItemKind.CollectionFolder, typeof(CollectionFolder).FullName },
  246. { BaseItemKind.Episode, typeof(Episode).FullName },
  247. { BaseItemKind.Folder, typeof(Folder).FullName },
  248. { BaseItemKind.Genre, typeof(Genre).FullName },
  249. { BaseItemKind.Movie, typeof(Movie).FullName },
  250. { BaseItemKind.LiveTvChannel, typeof(LiveTvChannel).FullName },
  251. { BaseItemKind.LiveTvProgram, typeof(LiveTvProgram).FullName },
  252. { BaseItemKind.MusicAlbum, typeof(MusicAlbum).FullName },
  253. { BaseItemKind.MusicArtist, typeof(MusicArtist).FullName },
  254. { BaseItemKind.MusicGenre, typeof(MusicGenre).FullName },
  255. { BaseItemKind.MusicVideo, typeof(MusicVideo).FullName },
  256. { BaseItemKind.Person, typeof(Person).FullName },
  257. { BaseItemKind.Photo, typeof(Photo).FullName },
  258. { BaseItemKind.PhotoAlbum, typeof(PhotoAlbum).FullName },
  259. { BaseItemKind.Playlist, typeof(Playlist).FullName },
  260. { BaseItemKind.PlaylistsFolder, typeof(PlaylistsFolder).FullName },
  261. { BaseItemKind.Season, typeof(Season).FullName },
  262. { BaseItemKind.Series, typeof(Series).FullName },
  263. { BaseItemKind.Studio, typeof(Studio).FullName },
  264. { BaseItemKind.Trailer, typeof(Trailer).FullName },
  265. { BaseItemKind.TvChannel, typeof(LiveTvChannel).FullName },
  266. { BaseItemKind.TvProgram, typeof(LiveTvProgram).FullName },
  267. { BaseItemKind.UserRootFolder, typeof(UserRootFolder).FullName },
  268. { BaseItemKind.UserView, typeof(UserView).FullName },
  269. { BaseItemKind.Video, typeof(Video).FullName },
  270. { BaseItemKind.Year, typeof(Year).FullName }
  271. };
  272. static SqliteItemRepository()
  273. {
  274. var queryPrefixText = new StringBuilder();
  275. queryPrefixText.Append("insert into mediaattachments (");
  276. foreach (var column in _mediaAttachmentSaveColumns)
  277. {
  278. queryPrefixText.Append(column)
  279. .Append(',');
  280. }
  281. queryPrefixText.Length -= 1;
  282. queryPrefixText.Append(") values ");
  283. _mediaAttachmentInsertPrefix = queryPrefixText.ToString();
  284. }
  285. /// <summary>
  286. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  287. /// </summary>
  288. /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  289. /// <param name="appHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
  290. /// <param name="logger">Instance of the <see cref="ILogger{SqliteItemRepository}"/> interface.</param>
  291. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  292. /// <param name="imageProcessor">Instance of the <see cref="IImageProcessor"/> interface.</param>
  293. /// <exception cref="ArgumentNullException">config is null.</exception>
  294. public SqliteItemRepository(
  295. IServerConfigurationManager config,
  296. IServerApplicationHost appHost,
  297. ILogger<SqliteItemRepository> logger,
  298. ILocalizationManager localization,
  299. IImageProcessor imageProcessor)
  300. : base(logger)
  301. {
  302. _config = config;
  303. _appHost = appHost;
  304. _localization = localization;
  305. _imageProcessor = imageProcessor;
  306. _typeMapper = new TypeMapper();
  307. _jsonOptions = JsonDefaults.Options;
  308. DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");
  309. }
  310. /// <inheritdoc />
  311. protected override int? CacheSize => 20000;
  312. /// <inheritdoc />
  313. protected override TempStoreMode TempStore => TempStoreMode.Memory;
  314. /// <summary>
  315. /// Opens the connection to the database.
  316. /// </summary>
  317. /// <param name="userDataRepo">The user data repository.</param>
  318. /// <param name="userManager">The user manager.</param>
  319. public void Initialize(SqliteUserDataRepository userDataRepo, IUserManager userManager)
  320. {
  321. const string CreateMediaStreamsTableCommand
  322. = "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, CodecTag TEXT NULL, Comment TEXT NULL, NalLengthSize TEXT NULL, IsAvc BIT NULL, Title TEXT NULL, TimeBase TEXT NULL, CodecTimeBase TEXT NULL, ColorPrimaries TEXT NULL, ColorSpace TEXT NULL, ColorTransfer TEXT NULL, DvVersionMajor INT NULL, DvVersionMinor INT NULL, DvProfile INT NULL, DvLevel INT NULL, RpuPresentFlag INT NULL, ElPresentFlag INT NULL, BlPresentFlag INT NULL, DvBlSignalCompatibilityId INT NULL, IsHearingImpaired BIT NULL, PRIMARY KEY (ItemId, StreamIndex))";
  323. const string CreateMediaAttachmentsTableCommand
  324. = "create table if not exists mediaattachments (ItemId GUID, AttachmentIndex INT, Codec TEXT, CodecTag TEXT NULL, Comment TEXT NULL, Filename TEXT NULL, MIMEType TEXT NULL, PRIMARY KEY (ItemId, AttachmentIndex))";
  325. string[] queries =
  326. {
  327. "PRAGMA locking_mode=EXCLUSIVE",
  328. "create table if not exists TypedBaseItems (guid GUID primary key NOT NULL, type TEXT NOT NULL, data BLOB NULL, ParentId GUID NULL, Path TEXT NULL)",
  329. "create table if not exists AncestorIds (ItemId GUID NOT NULL, AncestorId GUID NOT NULL, AncestorIdText TEXT NOT NULL, PRIMARY KEY (ItemId, AncestorId))",
  330. "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)",
  331. "create index if not exists idx_AncestorIds5 on AncestorIds(AncestorIdText,ItemId)",
  332. "create table if not exists ItemValues (ItemId GUID NOT NULL, Type INT NOT NULL, Value TEXT NOT NULL, CleanValue TEXT NOT NULL)",
  333. "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
  334. "drop index if exists idxPeopleItemId",
  335. "create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)",
  336. "create index if not exists idxPeopleName on People(Name)",
  337. "create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT NOT NULL, StartPositionTicks BIGINT NOT NULL, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
  338. CreateMediaStreamsTableCommand,
  339. CreateMediaAttachmentsTableCommand,
  340. "pragma shrink_memory"
  341. };
  342. string[] postQueries =
  343. {
  344. // obsolete
  345. "drop index if exists idx_TypedBaseItems",
  346. "drop index if exists idx_mediastreams",
  347. "drop index if exists idx_mediastreams1",
  348. "drop index if exists idx_" + ChaptersTableName,
  349. "drop index if exists idx_UserDataKeys1",
  350. "drop index if exists idx_UserDataKeys2",
  351. "drop index if exists idx_TypeTopParentId3",
  352. "drop index if exists idx_TypeTopParentId2",
  353. "drop index if exists idx_TypeTopParentId4",
  354. "drop index if exists idx_Type",
  355. "drop index if exists idx_TypeTopParentId",
  356. "drop index if exists idx_GuidType",
  357. "drop index if exists idx_TopParentId",
  358. "drop index if exists idx_TypeTopParentId6",
  359. "drop index if exists idx_ItemValues2",
  360. "drop index if exists Idx_ProviderIds",
  361. "drop index if exists idx_ItemValues3",
  362. "drop index if exists idx_ItemValues4",
  363. "drop index if exists idx_ItemValues5",
  364. "drop index if exists idx_UserDataKeys3",
  365. "drop table if exists UserDataKeys",
  366. "drop table if exists ProviderIds",
  367. "drop index if exists Idx_ProviderIds1",
  368. "drop table if exists Images",
  369. "drop index if exists idx_Images",
  370. "drop index if exists idx_TypeSeriesPresentationUniqueKey",
  371. "drop index if exists idx_SeriesPresentationUniqueKey",
  372. "drop index if exists idx_TypeSeriesPresentationUniqueKey2",
  373. "drop index if exists idx_AncestorIds3",
  374. "drop index if exists idx_AncestorIds4",
  375. "drop index if exists idx_AncestorIds2",
  376. "create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)",
  377. "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)",
  378. "create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)",
  379. "create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)",
  380. "create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)",
  381. // covering index
  382. "create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)",
  383. // series
  384. "create index if not exists idx_TypeSeriesPresentationUniqueKey1 on TypedBaseItems(Type,SeriesPresentationUniqueKey,PresentationUniqueKey,SortName)",
  385. // series counts
  386. // seriesdateplayed sort order
  387. "create index if not exists idx_TypeSeriesPresentationUniqueKey3 on TypedBaseItems(SeriesPresentationUniqueKey,Type,IsFolder,IsVirtualItem)",
  388. // live tv programs
  389. "create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)",
  390. // covering index for getitemvalues
  391. "create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)",
  392. // used by movie suggestions
  393. "create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)",
  394. "create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)",
  395. // latest items
  396. "create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)",
  397. "create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)",
  398. // resume
  399. "create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)",
  400. // items by name
  401. "create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)",
  402. "create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)",
  403. // Used to update inherited tags
  404. "create index if not exists idx_ItemValues8 on ItemValues(Type, ItemId, Value)",
  405. };
  406. using (var connection = GetConnection())
  407. {
  408. connection.RunQueries(queries);
  409. connection.RunInTransaction(
  410. db =>
  411. {
  412. var existingColumnNames = GetColumnNames(db, "AncestorIds");
  413. AddColumn(db, "AncestorIds", "AncestorIdText", "Text", existingColumnNames);
  414. existingColumnNames = GetColumnNames(db, "TypedBaseItems");
  415. AddColumn(db, "TypedBaseItems", "Path", "Text", existingColumnNames);
  416. AddColumn(db, "TypedBaseItems", "StartDate", "DATETIME", existingColumnNames);
  417. AddColumn(db, "TypedBaseItems", "EndDate", "DATETIME", existingColumnNames);
  418. AddColumn(db, "TypedBaseItems", "ChannelId", "Text", existingColumnNames);
  419. AddColumn(db, "TypedBaseItems", "IsMovie", "BIT", existingColumnNames);
  420. AddColumn(db, "TypedBaseItems", "CommunityRating", "Float", existingColumnNames);
  421. AddColumn(db, "TypedBaseItems", "CustomRating", "Text", existingColumnNames);
  422. AddColumn(db, "TypedBaseItems", "IndexNumber", "INT", existingColumnNames);
  423. AddColumn(db, "TypedBaseItems", "IsLocked", "BIT", existingColumnNames);
  424. AddColumn(db, "TypedBaseItems", "Name", "Text", existingColumnNames);
  425. AddColumn(db, "TypedBaseItems", "OfficialRating", "Text", existingColumnNames);
  426. AddColumn(db, "TypedBaseItems", "MediaType", "Text", existingColumnNames);
  427. AddColumn(db, "TypedBaseItems", "Overview", "Text", existingColumnNames);
  428. AddColumn(db, "TypedBaseItems", "ParentIndexNumber", "INT", existingColumnNames);
  429. AddColumn(db, "TypedBaseItems", "PremiereDate", "DATETIME", existingColumnNames);
  430. AddColumn(db, "TypedBaseItems", "ProductionYear", "INT", existingColumnNames);
  431. AddColumn(db, "TypedBaseItems", "ParentId", "GUID", existingColumnNames);
  432. AddColumn(db, "TypedBaseItems", "Genres", "Text", existingColumnNames);
  433. AddColumn(db, "TypedBaseItems", "SortName", "Text", existingColumnNames);
  434. AddColumn(db, "TypedBaseItems", "ForcedSortName", "Text", existingColumnNames);
  435. AddColumn(db, "TypedBaseItems", "RunTimeTicks", "BIGINT", existingColumnNames);
  436. AddColumn(db, "TypedBaseItems", "DateCreated", "DATETIME", existingColumnNames);
  437. AddColumn(db, "TypedBaseItems", "DateModified", "DATETIME", existingColumnNames);
  438. AddColumn(db, "TypedBaseItems", "IsSeries", "BIT", existingColumnNames);
  439. AddColumn(db, "TypedBaseItems", "EpisodeTitle", "Text", existingColumnNames);
  440. AddColumn(db, "TypedBaseItems", "IsRepeat", "BIT", existingColumnNames);
  441. AddColumn(db, "TypedBaseItems", "PreferredMetadataLanguage", "Text", existingColumnNames);
  442. AddColumn(db, "TypedBaseItems", "PreferredMetadataCountryCode", "Text", existingColumnNames);
  443. AddColumn(db, "TypedBaseItems", "DateLastRefreshed", "DATETIME", existingColumnNames);
  444. AddColumn(db, "TypedBaseItems", "DateLastSaved", "DATETIME", existingColumnNames);
  445. AddColumn(db, "TypedBaseItems", "IsInMixedFolder", "BIT", existingColumnNames);
  446. AddColumn(db, "TypedBaseItems", "LockedFields", "Text", existingColumnNames);
  447. AddColumn(db, "TypedBaseItems", "Studios", "Text", existingColumnNames);
  448. AddColumn(db, "TypedBaseItems", "Audio", "Text", existingColumnNames);
  449. AddColumn(db, "TypedBaseItems", "ExternalServiceId", "Text", existingColumnNames);
  450. AddColumn(db, "TypedBaseItems", "Tags", "Text", existingColumnNames);
  451. AddColumn(db, "TypedBaseItems", "IsFolder", "BIT", existingColumnNames);
  452. AddColumn(db, "TypedBaseItems", "InheritedParentalRatingValue", "INT", existingColumnNames);
  453. AddColumn(db, "TypedBaseItems", "UnratedType", "Text", existingColumnNames);
  454. AddColumn(db, "TypedBaseItems", "TopParentId", "Text", existingColumnNames);
  455. AddColumn(db, "TypedBaseItems", "TrailerTypes", "Text", existingColumnNames);
  456. AddColumn(db, "TypedBaseItems", "CriticRating", "Float", existingColumnNames);
  457. AddColumn(db, "TypedBaseItems", "CleanName", "Text", existingColumnNames);
  458. AddColumn(db, "TypedBaseItems", "PresentationUniqueKey", "Text", existingColumnNames);
  459. AddColumn(db, "TypedBaseItems", "OriginalTitle", "Text", existingColumnNames);
  460. AddColumn(db, "TypedBaseItems", "PrimaryVersionId", "Text", existingColumnNames);
  461. AddColumn(db, "TypedBaseItems", "DateLastMediaAdded", "DATETIME", existingColumnNames);
  462. AddColumn(db, "TypedBaseItems", "Album", "Text", existingColumnNames);
  463. AddColumn(db, "TypedBaseItems", "IsVirtualItem", "BIT", existingColumnNames);
  464. AddColumn(db, "TypedBaseItems", "SeriesName", "Text", existingColumnNames);
  465. AddColumn(db, "TypedBaseItems", "UserDataKey", "Text", existingColumnNames);
  466. AddColumn(db, "TypedBaseItems", "SeasonName", "Text", existingColumnNames);
  467. AddColumn(db, "TypedBaseItems", "SeasonId", "GUID", existingColumnNames);
  468. AddColumn(db, "TypedBaseItems", "SeriesId", "GUID", existingColumnNames);
  469. AddColumn(db, "TypedBaseItems", "ExternalSeriesId", "Text", existingColumnNames);
  470. AddColumn(db, "TypedBaseItems", "Tagline", "Text", existingColumnNames);
  471. AddColumn(db, "TypedBaseItems", "ProviderIds", "Text", existingColumnNames);
  472. AddColumn(db, "TypedBaseItems", "Images", "Text", existingColumnNames);
  473. AddColumn(db, "TypedBaseItems", "ProductionLocations", "Text", existingColumnNames);
  474. AddColumn(db, "TypedBaseItems", "ExtraIds", "Text", existingColumnNames);
  475. AddColumn(db, "TypedBaseItems", "TotalBitrate", "INT", existingColumnNames);
  476. AddColumn(db, "TypedBaseItems", "ExtraType", "Text", existingColumnNames);
  477. AddColumn(db, "TypedBaseItems", "Artists", "Text", existingColumnNames);
  478. AddColumn(db, "TypedBaseItems", "AlbumArtists", "Text", existingColumnNames);
  479. AddColumn(db, "TypedBaseItems", "ExternalId", "Text", existingColumnNames);
  480. AddColumn(db, "TypedBaseItems", "SeriesPresentationUniqueKey", "Text", existingColumnNames);
  481. AddColumn(db, "TypedBaseItems", "ShowId", "Text", existingColumnNames);
  482. AddColumn(db, "TypedBaseItems", "OwnerId", "Text", existingColumnNames);
  483. AddColumn(db, "TypedBaseItems", "Width", "INT", existingColumnNames);
  484. AddColumn(db, "TypedBaseItems", "Height", "INT", existingColumnNames);
  485. AddColumn(db, "TypedBaseItems", "Size", "BIGINT", existingColumnNames);
  486. existingColumnNames = GetColumnNames(db, "ItemValues");
  487. AddColumn(db, "ItemValues", "CleanValue", "Text", existingColumnNames);
  488. existingColumnNames = GetColumnNames(db, ChaptersTableName);
  489. AddColumn(db, ChaptersTableName, "ImageDateModified", "DATETIME", existingColumnNames);
  490. existingColumnNames = GetColumnNames(db, "MediaStreams");
  491. AddColumn(db, "MediaStreams", "IsAvc", "BIT", existingColumnNames);
  492. AddColumn(db, "MediaStreams", "TimeBase", "TEXT", existingColumnNames);
  493. AddColumn(db, "MediaStreams", "CodecTimeBase", "TEXT", existingColumnNames);
  494. AddColumn(db, "MediaStreams", "Title", "TEXT", existingColumnNames);
  495. AddColumn(db, "MediaStreams", "NalLengthSize", "TEXT", existingColumnNames);
  496. AddColumn(db, "MediaStreams", "Comment", "TEXT", existingColumnNames);
  497. AddColumn(db, "MediaStreams", "CodecTag", "TEXT", existingColumnNames);
  498. AddColumn(db, "MediaStreams", "PixelFormat", "TEXT", existingColumnNames);
  499. AddColumn(db, "MediaStreams", "BitDepth", "INT", existingColumnNames);
  500. AddColumn(db, "MediaStreams", "RefFrames", "INT", existingColumnNames);
  501. AddColumn(db, "MediaStreams", "KeyFrames", "TEXT", existingColumnNames);
  502. AddColumn(db, "MediaStreams", "IsAnamorphic", "BIT", existingColumnNames);
  503. AddColumn(db, "MediaStreams", "ColorPrimaries", "TEXT", existingColumnNames);
  504. AddColumn(db, "MediaStreams", "ColorSpace", "TEXT", existingColumnNames);
  505. AddColumn(db, "MediaStreams", "ColorTransfer", "TEXT", existingColumnNames);
  506. AddColumn(db, "MediaStreams", "DvVersionMajor", "INT", existingColumnNames);
  507. AddColumn(db, "MediaStreams", "DvVersionMinor", "INT", existingColumnNames);
  508. AddColumn(db, "MediaStreams", "DvProfile", "INT", existingColumnNames);
  509. AddColumn(db, "MediaStreams", "DvLevel", "INT", existingColumnNames);
  510. AddColumn(db, "MediaStreams", "RpuPresentFlag", "INT", existingColumnNames);
  511. AddColumn(db, "MediaStreams", "ElPresentFlag", "INT", existingColumnNames);
  512. AddColumn(db, "MediaStreams", "BlPresentFlag", "INT", existingColumnNames);
  513. AddColumn(db, "MediaStreams", "DvBlSignalCompatibilityId", "INT", existingColumnNames);
  514. AddColumn(db, "MediaStreams", "IsHearingImpaired", "BIT", existingColumnNames);
  515. },
  516. TransactionMode);
  517. connection.RunQueries(postQueries);
  518. }
  519. userDataRepo.Initialize(userManager, WriteLock, WriteConnection);
  520. }
  521. public void SaveImages(BaseItem item)
  522. {
  523. ArgumentNullException.ThrowIfNull(item);
  524. CheckDisposed();
  525. using (var connection = GetConnection())
  526. {
  527. connection.RunInTransaction(
  528. db =>
  529. {
  530. using (var saveImagesStatement = PrepareStatement(db, "Update TypedBaseItems set Images=@Images where guid=@Id"))
  531. {
  532. saveImagesStatement.TryBind("@Id", item.Id);
  533. saveImagesStatement.TryBind("@Images", SerializeImages(item.ImageInfos));
  534. saveImagesStatement.MoveNext();
  535. }
  536. },
  537. TransactionMode);
  538. }
  539. }
  540. /// <summary>
  541. /// Saves the items.
  542. /// </summary>
  543. /// <param name="items">The items.</param>
  544. /// <param name="cancellationToken">The cancellation token.</param>
  545. /// <exception cref="ArgumentNullException">
  546. /// <paramref name="items"/> or <paramref name="cancellationToken"/> is <c>null</c>.
  547. /// </exception>
  548. public void SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  549. {
  550. ArgumentNullException.ThrowIfNull(items);
  551. cancellationToken.ThrowIfCancellationRequested();
  552. CheckDisposed();
  553. var tuples = new List<(BaseItem, List<Guid>, BaseItem, string, List<string>)>();
  554. foreach (var item in items)
  555. {
  556. var ancestorIds = item.SupportsAncestors ?
  557. item.GetAncestorIds().Distinct().ToList() :
  558. null;
  559. var topParent = item.GetTopParent();
  560. var userdataKey = item.GetUserDataKeys().FirstOrDefault();
  561. var inheritedTags = item.GetInheritedTags();
  562. tuples.Add((item, ancestorIds, topParent, userdataKey, inheritedTags));
  563. }
  564. using (var connection = GetConnection())
  565. {
  566. connection.RunInTransaction(
  567. db =>
  568. {
  569. SaveItemsInTransaction(db, tuples);
  570. },
  571. TransactionMode);
  572. }
  573. }
  574. private void SaveItemsInTransaction(IDatabaseConnection db, IEnumerable<(BaseItem Item, List<Guid> AncestorIds, BaseItem TopParent, string UserDataKey, List<string> InheritedTags)> tuples)
  575. {
  576. var statements = PrepareAll(db, new string[]
  577. {
  578. SaveItemCommandText,
  579. "delete from AncestorIds where ItemId=@ItemId"
  580. });
  581. using (var saveItemStatement = statements[0])
  582. using (var deleteAncestorsStatement = statements[1])
  583. {
  584. var requiresReset = false;
  585. foreach (var tuple in tuples)
  586. {
  587. if (requiresReset)
  588. {
  589. saveItemStatement.Reset();
  590. }
  591. var item = tuple.Item;
  592. var topParent = tuple.TopParent;
  593. var userDataKey = tuple.UserDataKey;
  594. SaveItem(item, topParent, userDataKey, saveItemStatement);
  595. var inheritedTags = tuple.InheritedTags;
  596. if (item.SupportsAncestors)
  597. {
  598. UpdateAncestors(item.Id, tuple.AncestorIds, db, deleteAncestorsStatement);
  599. }
  600. UpdateItemValues(item.Id, GetItemValuesToSave(item, inheritedTags), db);
  601. requiresReset = true;
  602. }
  603. }
  604. }
  605. private string GetPathToSave(string path)
  606. {
  607. if (path is null)
  608. {
  609. return null;
  610. }
  611. return _appHost.ReverseVirtualPath(path);
  612. }
  613. private string RestorePath(string path)
  614. {
  615. return _appHost.ExpandVirtualPath(path);
  616. }
  617. private void SaveItem(BaseItem item, BaseItem topParent, string userDataKey, IStatement saveItemStatement)
  618. {
  619. Type type = item.GetType();
  620. saveItemStatement.TryBind("@guid", item.Id);
  621. saveItemStatement.TryBind("@type", type.FullName);
  622. if (TypeRequiresDeserialization(type))
  623. {
  624. saveItemStatement.TryBind("@data", JsonSerializer.SerializeToUtf8Bytes(item, type, _jsonOptions));
  625. }
  626. else
  627. {
  628. saveItemStatement.TryBindNull("@data");
  629. }
  630. saveItemStatement.TryBind("@Path", GetPathToSave(item.Path));
  631. if (item is IHasStartDate hasStartDate)
  632. {
  633. saveItemStatement.TryBind("@StartDate", hasStartDate.StartDate);
  634. }
  635. else
  636. {
  637. saveItemStatement.TryBindNull("@StartDate");
  638. }
  639. if (item.EndDate.HasValue)
  640. {
  641. saveItemStatement.TryBind("@EndDate", item.EndDate.Value);
  642. }
  643. else
  644. {
  645. saveItemStatement.TryBindNull("@EndDate");
  646. }
  647. saveItemStatement.TryBind("@ChannelId", item.ChannelId.Equals(default) ? null : item.ChannelId.ToString("N", CultureInfo.InvariantCulture));
  648. if (item is IHasProgramAttributes hasProgramAttributes)
  649. {
  650. saveItemStatement.TryBind("@IsMovie", hasProgramAttributes.IsMovie);
  651. saveItemStatement.TryBind("@IsSeries", hasProgramAttributes.IsSeries);
  652. saveItemStatement.TryBind("@EpisodeTitle", hasProgramAttributes.EpisodeTitle);
  653. saveItemStatement.TryBind("@IsRepeat", hasProgramAttributes.IsRepeat);
  654. }
  655. else
  656. {
  657. saveItemStatement.TryBindNull("@IsMovie");
  658. saveItemStatement.TryBindNull("@IsSeries");
  659. saveItemStatement.TryBindNull("@EpisodeTitle");
  660. saveItemStatement.TryBindNull("@IsRepeat");
  661. }
  662. saveItemStatement.TryBind("@CommunityRating", item.CommunityRating);
  663. saveItemStatement.TryBind("@CustomRating", item.CustomRating);
  664. saveItemStatement.TryBind("@IndexNumber", item.IndexNumber);
  665. saveItemStatement.TryBind("@IsLocked", item.IsLocked);
  666. saveItemStatement.TryBind("@Name", item.Name);
  667. saveItemStatement.TryBind("@OfficialRating", item.OfficialRating);
  668. saveItemStatement.TryBind("@MediaType", item.MediaType);
  669. saveItemStatement.TryBind("@Overview", item.Overview);
  670. saveItemStatement.TryBind("@ParentIndexNumber", item.ParentIndexNumber);
  671. saveItemStatement.TryBind("@PremiereDate", item.PremiereDate);
  672. saveItemStatement.TryBind("@ProductionYear", item.ProductionYear);
  673. var parentId = item.ParentId;
  674. if (parentId.Equals(default))
  675. {
  676. saveItemStatement.TryBindNull("@ParentId");
  677. }
  678. else
  679. {
  680. saveItemStatement.TryBind("@ParentId", parentId);
  681. }
  682. if (item.Genres.Length > 0)
  683. {
  684. saveItemStatement.TryBind("@Genres", string.Join('|', item.Genres));
  685. }
  686. else
  687. {
  688. saveItemStatement.TryBindNull("@Genres");
  689. }
  690. saveItemStatement.TryBind("@InheritedParentalRatingValue", item.InheritedParentalRatingValue);
  691. saveItemStatement.TryBind("@SortName", item.SortName);
  692. saveItemStatement.TryBind("@ForcedSortName", item.ForcedSortName);
  693. saveItemStatement.TryBind("@RunTimeTicks", item.RunTimeTicks);
  694. saveItemStatement.TryBind("@Size", item.Size);
  695. saveItemStatement.TryBind("@DateCreated", item.DateCreated);
  696. saveItemStatement.TryBind("@DateModified", item.DateModified);
  697. saveItemStatement.TryBind("@PreferredMetadataLanguage", item.PreferredMetadataLanguage);
  698. saveItemStatement.TryBind("@PreferredMetadataCountryCode", item.PreferredMetadataCountryCode);
  699. if (item.Width > 0)
  700. {
  701. saveItemStatement.TryBind("@Width", item.Width);
  702. }
  703. else
  704. {
  705. saveItemStatement.TryBindNull("@Width");
  706. }
  707. if (item.Height > 0)
  708. {
  709. saveItemStatement.TryBind("@Height", item.Height);
  710. }
  711. else
  712. {
  713. saveItemStatement.TryBindNull("@Height");
  714. }
  715. if (item.DateLastRefreshed != default(DateTime))
  716. {
  717. saveItemStatement.TryBind("@DateLastRefreshed", item.DateLastRefreshed);
  718. }
  719. else
  720. {
  721. saveItemStatement.TryBindNull("@DateLastRefreshed");
  722. }
  723. if (item.DateLastSaved != default(DateTime))
  724. {
  725. saveItemStatement.TryBind("@DateLastSaved", item.DateLastSaved);
  726. }
  727. else
  728. {
  729. saveItemStatement.TryBindNull("@DateLastSaved");
  730. }
  731. saveItemStatement.TryBind("@IsInMixedFolder", item.IsInMixedFolder);
  732. if (item.LockedFields.Length > 0)
  733. {
  734. saveItemStatement.TryBind("@LockedFields", string.Join('|', item.LockedFields));
  735. }
  736. else
  737. {
  738. saveItemStatement.TryBindNull("@LockedFields");
  739. }
  740. if (item.Studios.Length > 0)
  741. {
  742. saveItemStatement.TryBind("@Studios", string.Join('|', item.Studios));
  743. }
  744. else
  745. {
  746. saveItemStatement.TryBindNull("@Studios");
  747. }
  748. if (item.Audio.HasValue)
  749. {
  750. saveItemStatement.TryBind("@Audio", item.Audio.Value.ToString());
  751. }
  752. else
  753. {
  754. saveItemStatement.TryBindNull("@Audio");
  755. }
  756. if (item is LiveTvChannel liveTvChannel)
  757. {
  758. saveItemStatement.TryBind("@ExternalServiceId", liveTvChannel.ServiceName);
  759. }
  760. else
  761. {
  762. saveItemStatement.TryBindNull("@ExternalServiceId");
  763. }
  764. if (item.Tags.Length > 0)
  765. {
  766. saveItemStatement.TryBind("@Tags", string.Join('|', item.Tags));
  767. }
  768. else
  769. {
  770. saveItemStatement.TryBindNull("@Tags");
  771. }
  772. saveItemStatement.TryBind("@IsFolder", item.IsFolder);
  773. saveItemStatement.TryBind("@UnratedType", item.GetBlockUnratedType().ToString());
  774. if (topParent is null)
  775. {
  776. saveItemStatement.TryBindNull("@TopParentId");
  777. }
  778. else
  779. {
  780. saveItemStatement.TryBind("@TopParentId", topParent.Id.ToString("N", CultureInfo.InvariantCulture));
  781. }
  782. if (item is Trailer trailer && trailer.TrailerTypes.Length > 0)
  783. {
  784. saveItemStatement.TryBind("@TrailerTypes", string.Join('|', trailer.TrailerTypes));
  785. }
  786. else
  787. {
  788. saveItemStatement.TryBindNull("@TrailerTypes");
  789. }
  790. saveItemStatement.TryBind("@CriticRating", item.CriticRating);
  791. if (string.IsNullOrWhiteSpace(item.Name))
  792. {
  793. saveItemStatement.TryBindNull("@CleanName");
  794. }
  795. else
  796. {
  797. saveItemStatement.TryBind("@CleanName", GetCleanValue(item.Name));
  798. }
  799. saveItemStatement.TryBind("@PresentationUniqueKey", item.PresentationUniqueKey);
  800. saveItemStatement.TryBind("@OriginalTitle", item.OriginalTitle);
  801. if (item is Video video)
  802. {
  803. saveItemStatement.TryBind("@PrimaryVersionId", video.PrimaryVersionId);
  804. }
  805. else
  806. {
  807. saveItemStatement.TryBindNull("@PrimaryVersionId");
  808. }
  809. if (item is Folder folder && folder.DateLastMediaAdded.HasValue)
  810. {
  811. saveItemStatement.TryBind("@DateLastMediaAdded", folder.DateLastMediaAdded.Value);
  812. }
  813. else
  814. {
  815. saveItemStatement.TryBindNull("@DateLastMediaAdded");
  816. }
  817. saveItemStatement.TryBind("@Album", item.Album);
  818. saveItemStatement.TryBind("@IsVirtualItem", item.IsVirtualItem);
  819. if (item is IHasSeries hasSeriesName)
  820. {
  821. saveItemStatement.TryBind("@SeriesName", hasSeriesName.SeriesName);
  822. }
  823. else
  824. {
  825. saveItemStatement.TryBindNull("@SeriesName");
  826. }
  827. if (string.IsNullOrWhiteSpace(userDataKey))
  828. {
  829. saveItemStatement.TryBindNull("@UserDataKey");
  830. }
  831. else
  832. {
  833. saveItemStatement.TryBind("@UserDataKey", userDataKey);
  834. }
  835. if (item is Episode episode)
  836. {
  837. saveItemStatement.TryBind("@SeasonName", episode.SeasonName);
  838. var nullableSeasonId = episode.SeasonId.Equals(default) ? (Guid?)null : episode.SeasonId;
  839. saveItemStatement.TryBind("@SeasonId", nullableSeasonId);
  840. }
  841. else
  842. {
  843. saveItemStatement.TryBindNull("@SeasonName");
  844. saveItemStatement.TryBindNull("@SeasonId");
  845. }
  846. if (item is IHasSeries hasSeries)
  847. {
  848. var nullableSeriesId = hasSeries.SeriesId.Equals(default) ? (Guid?)null : hasSeries.SeriesId;
  849. saveItemStatement.TryBind("@SeriesId", nullableSeriesId);
  850. saveItemStatement.TryBind("@SeriesPresentationUniqueKey", hasSeries.SeriesPresentationUniqueKey);
  851. }
  852. else
  853. {
  854. saveItemStatement.TryBindNull("@SeriesId");
  855. saveItemStatement.TryBindNull("@SeriesPresentationUniqueKey");
  856. }
  857. saveItemStatement.TryBind("@ExternalSeriesId", item.ExternalSeriesId);
  858. saveItemStatement.TryBind("@Tagline", item.Tagline);
  859. saveItemStatement.TryBind("@ProviderIds", SerializeProviderIds(item.ProviderIds));
  860. saveItemStatement.TryBind("@Images", SerializeImages(item.ImageInfos));
  861. if (item.ProductionLocations.Length > 0)
  862. {
  863. saveItemStatement.TryBind("@ProductionLocations", string.Join('|', item.ProductionLocations));
  864. }
  865. else
  866. {
  867. saveItemStatement.TryBindNull("@ProductionLocations");
  868. }
  869. if (item.ExtraIds.Length > 0)
  870. {
  871. saveItemStatement.TryBind("@ExtraIds", string.Join('|', item.ExtraIds));
  872. }
  873. else
  874. {
  875. saveItemStatement.TryBindNull("@ExtraIds");
  876. }
  877. saveItemStatement.TryBind("@TotalBitrate", item.TotalBitrate);
  878. if (item.ExtraType.HasValue)
  879. {
  880. saveItemStatement.TryBind("@ExtraType", item.ExtraType.Value.ToString());
  881. }
  882. else
  883. {
  884. saveItemStatement.TryBindNull("@ExtraType");
  885. }
  886. string artists = null;
  887. if (item is IHasArtist hasArtists && hasArtists.Artists.Count > 0)
  888. {
  889. artists = string.Join('|', hasArtists.Artists);
  890. }
  891. saveItemStatement.TryBind("@Artists", artists);
  892. string albumArtists = null;
  893. if (item is IHasAlbumArtist hasAlbumArtists
  894. && hasAlbumArtists.AlbumArtists.Count > 0)
  895. {
  896. albumArtists = string.Join('|', hasAlbumArtists.AlbumArtists);
  897. }
  898. saveItemStatement.TryBind("@AlbumArtists", albumArtists);
  899. saveItemStatement.TryBind("@ExternalId", item.ExternalId);
  900. if (item is LiveTvProgram program)
  901. {
  902. saveItemStatement.TryBind("@ShowId", program.ShowId);
  903. }
  904. else
  905. {
  906. saveItemStatement.TryBindNull("@ShowId");
  907. }
  908. Guid ownerId = item.OwnerId;
  909. if (ownerId.Equals(default))
  910. {
  911. saveItemStatement.TryBindNull("@OwnerId");
  912. }
  913. else
  914. {
  915. saveItemStatement.TryBind("@OwnerId", ownerId);
  916. }
  917. saveItemStatement.MoveNext();
  918. }
  919. internal static string SerializeProviderIds(Dictionary<string, string> providerIds)
  920. {
  921. StringBuilder str = new StringBuilder();
  922. foreach (var i in providerIds)
  923. {
  924. // Ideally we shouldn't need this IsNullOrWhiteSpace check,
  925. // but we're seeing some cases of bad data slip through
  926. if (string.IsNullOrWhiteSpace(i.Value))
  927. {
  928. continue;
  929. }
  930. str.Append(i.Key)
  931. .Append('=')
  932. .Append(i.Value)
  933. .Append('|');
  934. }
  935. if (str.Length == 0)
  936. {
  937. return null;
  938. }
  939. str.Length -= 1; // Remove last |
  940. return str.ToString();
  941. }
  942. internal static void DeserializeProviderIds(string value, IHasProviderIds item)
  943. {
  944. if (string.IsNullOrWhiteSpace(value))
  945. {
  946. return;
  947. }
  948. foreach (var part in value.SpanSplit('|'))
  949. {
  950. var providerDelimiterIndex = part.IndexOf('=');
  951. if (providerDelimiterIndex != -1 && providerDelimiterIndex == part.LastIndexOf('='))
  952. {
  953. item.SetProviderId(part.Slice(0, providerDelimiterIndex).ToString(), part.Slice(providerDelimiterIndex + 1).ToString());
  954. }
  955. }
  956. }
  957. internal string SerializeImages(ItemImageInfo[] images)
  958. {
  959. if (images.Length == 0)
  960. {
  961. return null;
  962. }
  963. StringBuilder str = new StringBuilder();
  964. foreach (var i in images)
  965. {
  966. if (string.IsNullOrWhiteSpace(i.Path))
  967. {
  968. continue;
  969. }
  970. AppendItemImageInfo(str, i);
  971. str.Append('|');
  972. }
  973. str.Length -= 1; // Remove last |
  974. return str.ToString();
  975. }
  976. internal ItemImageInfo[] DeserializeImages(string value)
  977. {
  978. if (string.IsNullOrWhiteSpace(value))
  979. {
  980. return Array.Empty<ItemImageInfo>();
  981. }
  982. // TODO The following is an ugly performance optimization, but it's extremely unlikely that the data in the database would be malformed
  983. var valueSpan = value.AsSpan();
  984. var count = valueSpan.Count('|') + 1;
  985. var position = 0;
  986. var result = new ItemImageInfo[count];
  987. foreach (var part in valueSpan.Split('|'))
  988. {
  989. var image = ItemImageInfoFromValueString(part);
  990. if (image is not null)
  991. {
  992. result[position++] = image;
  993. }
  994. }
  995. if (position == count)
  996. {
  997. return result;
  998. }
  999. if (position == 0)
  1000. {
  1001. return Array.Empty<ItemImageInfo>();
  1002. }
  1003. // Extremely unlikely, but somehow one or more of the image strings were malformed. Cut the array.
  1004. return result[..position];
  1005. }
  1006. private void AppendItemImageInfo(StringBuilder bldr, ItemImageInfo image)
  1007. {
  1008. const char Delimiter = '*';
  1009. var path = image.Path ?? string.Empty;
  1010. bldr.Append(GetPathToSave(path))
  1011. .Append(Delimiter)
  1012. .Append(image.DateModified.Ticks)
  1013. .Append(Delimiter)
  1014. .Append(image.Type)
  1015. .Append(Delimiter)
  1016. .Append(image.Width)
  1017. .Append(Delimiter)
  1018. .Append(image.Height);
  1019. var hash = image.BlurHash;
  1020. if (!string.IsNullOrEmpty(hash))
  1021. {
  1022. bldr.Append(Delimiter)
  1023. // Replace delimiters with other characters.
  1024. // This can be removed when we migrate to a proper DB.
  1025. .Append(hash.Replace(Delimiter, '/').Replace('|', '\\'));
  1026. }
  1027. }
  1028. internal ItemImageInfo ItemImageInfoFromValueString(ReadOnlySpan<char> value)
  1029. {
  1030. const char Delimiter = '*';
  1031. var nextSegment = value.IndexOf(Delimiter);
  1032. if (nextSegment == -1)
  1033. {
  1034. return null;
  1035. }
  1036. ReadOnlySpan<char> path = value[..nextSegment];
  1037. value = value[(nextSegment + 1)..];
  1038. nextSegment = value.IndexOf(Delimiter);
  1039. if (nextSegment == -1)
  1040. {
  1041. return null;
  1042. }
  1043. ReadOnlySpan<char> dateModified = value[..nextSegment];
  1044. value = value[(nextSegment + 1)..];
  1045. nextSegment = value.IndexOf(Delimiter);
  1046. if (nextSegment == -1)
  1047. {
  1048. nextSegment = value.Length;
  1049. }
  1050. ReadOnlySpan<char> imageType = value[..nextSegment];
  1051. var image = new ItemImageInfo
  1052. {
  1053. Path = RestorePath(path.ToString())
  1054. };
  1055. if (long.TryParse(dateModified, NumberStyles.Any, CultureInfo.InvariantCulture, out var ticks)
  1056. && ticks >= DateTime.MinValue.Ticks
  1057. && ticks <= DateTime.MaxValue.Ticks)
  1058. {
  1059. image.DateModified = new DateTime(ticks, DateTimeKind.Utc);
  1060. }
  1061. else
  1062. {
  1063. return null;
  1064. }
  1065. if (Enum.TryParse(imageType, true, out ImageType type))
  1066. {
  1067. image.Type = type;
  1068. }
  1069. else
  1070. {
  1071. return null;
  1072. }
  1073. // Optional parameters: width*height*blurhash
  1074. if (nextSegment + 1 < value.Length - 1)
  1075. {
  1076. value = value[(nextSegment + 1)..];
  1077. nextSegment = value.IndexOf(Delimiter);
  1078. if (nextSegment == -1 || nextSegment == value.Length)
  1079. {
  1080. return image;
  1081. }
  1082. ReadOnlySpan<char> widthSpan = value[..nextSegment];
  1083. value = value[(nextSegment + 1)..];
  1084. nextSegment = value.IndexOf(Delimiter);
  1085. if (nextSegment == -1)
  1086. {
  1087. nextSegment = value.Length;
  1088. }
  1089. ReadOnlySpan<char> heightSpan = value[..nextSegment];
  1090. if (int.TryParse(widthSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var width)
  1091. && int.TryParse(heightSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var height))
  1092. {
  1093. image.Width = width;
  1094. image.Height = height;
  1095. }
  1096. if (nextSegment < value.Length - 1)
  1097. {
  1098. value = value[(nextSegment + 1)..];
  1099. var length = value.Length;
  1100. Span<char> blurHashSpan = stackalloc char[length];
  1101. for (int i = 0; i < length; i++)
  1102. {
  1103. var c = value[i];
  1104. blurHashSpan[i] = c switch
  1105. {
  1106. '/' => Delimiter,
  1107. '\\' => '|',
  1108. _ => c
  1109. };
  1110. }
  1111. image.BlurHash = new string(blurHashSpan);
  1112. }
  1113. }
  1114. return image;
  1115. }
  1116. /// <summary>
  1117. /// Internal retrieve from items or users table.
  1118. /// </summary>
  1119. /// <param name="id">The id.</param>
  1120. /// <returns>BaseItem.</returns>
  1121. /// <exception cref="ArgumentNullException"><paramref name="id"/> is <c>null</c>.</exception>
  1122. /// <exception cref="ArgumentException"><paramr name="id"/> is <seealso cref="Guid.Empty"/>.</exception>
  1123. public BaseItem RetrieveItem(Guid id)
  1124. {
  1125. if (id.Equals(default))
  1126. {
  1127. throw new ArgumentException("Guid can't be empty", nameof(id));
  1128. }
  1129. CheckDisposed();
  1130. using (var connection = GetConnection(true))
  1131. {
  1132. using (var statement = PrepareStatement(connection, _retrieveItemColumnsSelectQuery))
  1133. {
  1134. statement.TryBind("@guid", id);
  1135. foreach (var row in statement.ExecuteQuery())
  1136. {
  1137. return GetItem(row, new InternalItemsQuery());
  1138. }
  1139. }
  1140. }
  1141. return null;
  1142. }
  1143. private bool TypeRequiresDeserialization(Type type)
  1144. {
  1145. if (_config.Configuration.SkipDeserializationForBasicTypes)
  1146. {
  1147. if (type == typeof(Channel))
  1148. {
  1149. return false;
  1150. }
  1151. else if (type == typeof(UserRootFolder))
  1152. {
  1153. return false;
  1154. }
  1155. }
  1156. if (type == typeof(Season))
  1157. {
  1158. return false;
  1159. }
  1160. else if (type == typeof(MusicArtist))
  1161. {
  1162. return false;
  1163. }
  1164. else if (type == typeof(Person))
  1165. {
  1166. return false;
  1167. }
  1168. else if (type == typeof(MusicGenre))
  1169. {
  1170. return false;
  1171. }
  1172. else if (type == typeof(Genre))
  1173. {
  1174. return false;
  1175. }
  1176. else if (type == typeof(Studio))
  1177. {
  1178. return false;
  1179. }
  1180. else if (type == typeof(PlaylistsFolder))
  1181. {
  1182. return false;
  1183. }
  1184. else if (type == typeof(PhotoAlbum))
  1185. {
  1186. return false;
  1187. }
  1188. else if (type == typeof(Year))
  1189. {
  1190. return false;
  1191. }
  1192. else if (type == typeof(Book))
  1193. {
  1194. return false;
  1195. }
  1196. else if (type == typeof(LiveTvProgram))
  1197. {
  1198. return false;
  1199. }
  1200. else if (type == typeof(AudioBook))
  1201. {
  1202. return false;
  1203. }
  1204. else if (type == typeof(Audio))
  1205. {
  1206. return false;
  1207. }
  1208. else if (type == typeof(MusicAlbum))
  1209. {
  1210. return false;
  1211. }
  1212. return true;
  1213. }
  1214. private BaseItem GetItem(IReadOnlyList<ResultSetValue> reader, InternalItemsQuery query)
  1215. {
  1216. return GetItem(reader, query, HasProgramAttributes(query), HasEpisodeAttributes(query), HasServiceName(query), HasStartDate(query), HasTrailerTypes(query), HasArtistFields(query), HasSeriesFields(query));
  1217. }
  1218. private BaseItem GetItem(IReadOnlyList<ResultSetValue> reader, InternalItemsQuery query, bool enableProgramAttributes, bool hasEpisodeAttributes, bool hasServiceName, bool queryHasStartDate, bool hasTrailerTypes, bool hasArtistFields, bool hasSeriesFields)
  1219. {
  1220. var typeString = reader.GetString(0);
  1221. var type = _typeMapper.GetType(typeString);
  1222. if (type is null)
  1223. {
  1224. return null;
  1225. }
  1226. BaseItem item = null;
  1227. if (TypeRequiresDeserialization(type))
  1228. {
  1229. try
  1230. {
  1231. item = JsonSerializer.Deserialize(reader[1].ToBlob(), type, _jsonOptions) as BaseItem;
  1232. }
  1233. catch (JsonException ex)
  1234. {
  1235. Logger.LogError(ex, "Error deserializing item with JSON: {Data}", reader.GetString(1));
  1236. }
  1237. }
  1238. if (item is null)
  1239. {
  1240. try
  1241. {
  1242. item = Activator.CreateInstance(type) as BaseItem;
  1243. }
  1244. catch
  1245. {
  1246. }
  1247. }
  1248. if (item is null)
  1249. {
  1250. return null;
  1251. }
  1252. var index = 2;
  1253. if (queryHasStartDate)
  1254. {
  1255. if (item is IHasStartDate hasStartDate && reader.TryReadDateTime(index, out var startDate))
  1256. {
  1257. hasStartDate.StartDate = startDate;
  1258. }
  1259. index++;
  1260. }
  1261. if (reader.TryReadDateTime(index++, out var endDate))
  1262. {
  1263. item.EndDate = endDate;
  1264. }
  1265. var channelId = reader[index];
  1266. if (!channelId.IsDbNull())
  1267. {
  1268. if (!Utf8Parser.TryParse(channelId.ToBlob(), out Guid value, out _, standardFormat: 'N'))
  1269. {
  1270. var str = reader.GetString(index);
  1271. Logger.LogWarning("{ChannelId} isn't in the expected format", str);
  1272. value = new Guid(str);
  1273. }
  1274. item.ChannelId = value;
  1275. }
  1276. index++;
  1277. if (enableProgramAttributes)
  1278. {
  1279. if (item is IHasProgramAttributes hasProgramAttributes)
  1280. {
  1281. if (reader.TryGetBoolean(index++, out var isMovie))
  1282. {
  1283. hasProgramAttributes.IsMovie = isMovie;
  1284. }
  1285. if (reader.TryGetBoolean(index++, out var isSeries))
  1286. {
  1287. hasProgramAttributes.IsSeries = isSeries;
  1288. }
  1289. if (reader.TryGetString(index++, out var episodeTitle))
  1290. {
  1291. hasProgramAttributes.EpisodeTitle = episodeTitle;
  1292. }
  1293. if (reader.TryGetBoolean(index++, out var isRepeat))
  1294. {
  1295. hasProgramAttributes.IsRepeat = isRepeat;
  1296. }
  1297. }
  1298. else
  1299. {
  1300. index += 4;
  1301. }
  1302. }
  1303. if (reader.TryGetSingle(index++, out var communityRating))
  1304. {
  1305. item.CommunityRating = communityRating;
  1306. }
  1307. if (HasField(query, ItemFields.CustomRating))
  1308. {
  1309. if (reader.TryGetString(index++, out var customRating))
  1310. {
  1311. item.CustomRating = customRating;
  1312. }
  1313. }
  1314. if (reader.TryGetInt32(index++, out var indexNumber))
  1315. {
  1316. item.IndexNumber = indexNumber;
  1317. }
  1318. if (HasField(query, ItemFields.Settings))
  1319. {
  1320. if (reader.TryGetBoolean(index++, out var isLocked))
  1321. {
  1322. item.IsLocked = isLocked;
  1323. }
  1324. if (reader.TryGetString(index++, out var preferredMetadataLanguage))
  1325. {
  1326. item.PreferredMetadataLanguage = preferredMetadataLanguage;
  1327. }
  1328. if (reader.TryGetString(index++, out var preferredMetadataCountryCode))
  1329. {
  1330. item.PreferredMetadataCountryCode = preferredMetadataCountryCode;
  1331. }
  1332. }
  1333. if (HasField(query, ItemFields.Width))
  1334. {
  1335. if (reader.TryGetInt32(index++, out var width))
  1336. {
  1337. item.Width = width;
  1338. }
  1339. }
  1340. if (HasField(query, ItemFields.Height))
  1341. {
  1342. if (reader.TryGetInt32(index++, out var height))
  1343. {
  1344. item.Height = height;
  1345. }
  1346. }
  1347. if (HasField(query, ItemFields.DateLastRefreshed))
  1348. {
  1349. if (reader.TryReadDateTime(index++, out var dateLastRefreshed))
  1350. {
  1351. item.DateLastRefreshed = dateLastRefreshed;
  1352. }
  1353. }
  1354. if (reader.TryGetString(index++, out var name))
  1355. {
  1356. item.Name = name;
  1357. }
  1358. if (reader.TryGetString(index++, out var restorePath))
  1359. {
  1360. item.Path = RestorePath(restorePath);
  1361. }
  1362. if (reader.TryReadDateTime(index++, out var premiereDate))
  1363. {
  1364. item.PremiereDate = premiereDate;
  1365. }
  1366. if (HasField(query, ItemFields.Overview))
  1367. {
  1368. if (reader.TryGetString(index++, out var overview))
  1369. {
  1370. item.Overview = overview;
  1371. }
  1372. }
  1373. if (reader.TryGetInt32(index++, out var parentIndexNumber))
  1374. {
  1375. item.ParentIndexNumber = parentIndexNumber;
  1376. }
  1377. if (reader.TryGetInt32(index++, out var productionYear))
  1378. {
  1379. item.ProductionYear = productionYear;
  1380. }
  1381. if (reader.TryGetString(index++, out var officialRating))
  1382. {
  1383. item.OfficialRating = officialRating;
  1384. }
  1385. if (HasField(query, ItemFields.SortName))
  1386. {
  1387. if (reader.TryGetString(index++, out var forcedSortName))
  1388. {
  1389. item.ForcedSortName = forcedSortName;
  1390. }
  1391. }
  1392. if (reader.TryGetInt64(index++, out var runTimeTicks))
  1393. {
  1394. item.RunTimeTicks = runTimeTicks;
  1395. }
  1396. if (reader.TryGetInt64(index++, out var size))
  1397. {
  1398. item.Size = size;
  1399. }
  1400. if (HasField(query, ItemFields.DateCreated))
  1401. {
  1402. if (reader.TryReadDateTime(index++, out var dateCreated))
  1403. {
  1404. item.DateCreated = dateCreated;
  1405. }
  1406. }
  1407. if (reader.TryReadDateTime(index++, out var dateModified))
  1408. {
  1409. item.DateModified = dateModified;
  1410. }
  1411. item.Id = reader.GetGuid(index++);
  1412. if (HasField(query, ItemFields.Genres))
  1413. {
  1414. if (reader.TryGetString(index++, out var genres))
  1415. {
  1416. item.Genres = genres.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1417. }
  1418. }
  1419. if (reader.TryGetGuid(index++, out var parentId))
  1420. {
  1421. item.ParentId = parentId;
  1422. }
  1423. if (reader.TryGetString(index++, out var audioString))
  1424. {
  1425. if (Enum.TryParse(audioString, true, out ProgramAudio audio))
  1426. {
  1427. item.Audio = audio;
  1428. }
  1429. }
  1430. // TODO: Even if not needed by apps, the server needs it internally
  1431. // But get this excluded from contexts where it is not needed
  1432. if (hasServiceName)
  1433. {
  1434. if (item is LiveTvChannel liveTvChannel)
  1435. {
  1436. if (reader.TryGetString(index, out var serviceName))
  1437. {
  1438. liveTvChannel.ServiceName = serviceName;
  1439. }
  1440. }
  1441. index++;
  1442. }
  1443. if (reader.TryGetBoolean(index++, out var isInMixedFolder))
  1444. {
  1445. item.IsInMixedFolder = isInMixedFolder;
  1446. }
  1447. if (HasField(query, ItemFields.DateLastSaved))
  1448. {
  1449. if (reader.TryReadDateTime(index++, out var dateLastSaved))
  1450. {
  1451. item.DateLastSaved = dateLastSaved;
  1452. }
  1453. }
  1454. if (HasField(query, ItemFields.Settings))
  1455. {
  1456. if (reader.TryGetString(index++, out var lockedFields))
  1457. {
  1458. List<MetadataField> fields = null;
  1459. foreach (var i in lockedFields.AsSpan().Split('|'))
  1460. {
  1461. if (Enum.TryParse(i, true, out MetadataField parsedValue))
  1462. {
  1463. (fields ??= new List<MetadataField>()).Add(parsedValue);
  1464. }
  1465. }
  1466. item.LockedFields = fields?.ToArray() ?? Array.Empty<MetadataField>();
  1467. }
  1468. }
  1469. if (HasField(query, ItemFields.Studios))
  1470. {
  1471. if (reader.TryGetString(index++, out var studios))
  1472. {
  1473. item.Studios = studios.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1474. }
  1475. }
  1476. if (HasField(query, ItemFields.Tags))
  1477. {
  1478. if (reader.TryGetString(index++, out var tags))
  1479. {
  1480. item.Tags = tags.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1481. }
  1482. }
  1483. if (hasTrailerTypes)
  1484. {
  1485. if (item is Trailer trailer)
  1486. {
  1487. if (reader.TryGetString(index, out var trailerTypes))
  1488. {
  1489. List<TrailerType> types = null;
  1490. foreach (var i in trailerTypes.AsSpan().Split('|'))
  1491. {
  1492. if (Enum.TryParse(i, true, out TrailerType parsedValue))
  1493. {
  1494. (types ??= new List<TrailerType>()).Add(parsedValue);
  1495. }
  1496. }
  1497. trailer.TrailerTypes = types?.ToArray() ?? Array.Empty<TrailerType>();
  1498. }
  1499. }
  1500. index++;
  1501. }
  1502. if (HasField(query, ItemFields.OriginalTitle))
  1503. {
  1504. if (reader.TryGetString(index++, out var originalTitle))
  1505. {
  1506. item.OriginalTitle = originalTitle;
  1507. }
  1508. }
  1509. if (item is Video video)
  1510. {
  1511. if (reader.TryGetString(index, out var primaryVersionId))
  1512. {
  1513. video.PrimaryVersionId = primaryVersionId;
  1514. }
  1515. }
  1516. index++;
  1517. if (HasField(query, ItemFields.DateLastMediaAdded))
  1518. {
  1519. if (item is Folder folder && reader.TryReadDateTime(index, out var dateLastMediaAdded))
  1520. {
  1521. folder.DateLastMediaAdded = dateLastMediaAdded;
  1522. }
  1523. index++;
  1524. }
  1525. if (reader.TryGetString(index++, out var album))
  1526. {
  1527. item.Album = album;
  1528. }
  1529. if (reader.TryGetSingle(index++, out var criticRating))
  1530. {
  1531. item.CriticRating = criticRating;
  1532. }
  1533. if (reader.TryGetBoolean(index++, out var isVirtualItem))
  1534. {
  1535. item.IsVirtualItem = isVirtualItem;
  1536. }
  1537. if (item is IHasSeries hasSeriesName)
  1538. {
  1539. if (reader.TryGetString(index, out var seriesName))
  1540. {
  1541. hasSeriesName.SeriesName = seriesName;
  1542. }
  1543. }
  1544. index++;
  1545. if (hasEpisodeAttributes)
  1546. {
  1547. if (item is Episode episode)
  1548. {
  1549. if (reader.TryGetString(index, out var seasonName))
  1550. {
  1551. episode.SeasonName = seasonName;
  1552. }
  1553. index++;
  1554. if (reader.TryGetGuid(index, out var seasonId))
  1555. {
  1556. episode.SeasonId = seasonId;
  1557. }
  1558. }
  1559. else
  1560. {
  1561. index++;
  1562. }
  1563. index++;
  1564. }
  1565. var hasSeries = item as IHasSeries;
  1566. if (hasSeriesFields)
  1567. {
  1568. if (hasSeries is not null)
  1569. {
  1570. if (reader.TryGetGuid(index, out var seriesId))
  1571. {
  1572. hasSeries.SeriesId = seriesId;
  1573. }
  1574. }
  1575. index++;
  1576. }
  1577. if (HasField(query, ItemFields.PresentationUniqueKey))
  1578. {
  1579. if (reader.TryGetString(index++, out var presentationUniqueKey))
  1580. {
  1581. item.PresentationUniqueKey = presentationUniqueKey;
  1582. }
  1583. }
  1584. if (HasField(query, ItemFields.InheritedParentalRatingValue))
  1585. {
  1586. if (reader.TryGetInt32(index++, out var parentalRating))
  1587. {
  1588. item.InheritedParentalRatingValue = parentalRating;
  1589. }
  1590. }
  1591. if (HasField(query, ItemFields.ExternalSeriesId))
  1592. {
  1593. if (reader.TryGetString(index++, out var externalSeriesId))
  1594. {
  1595. item.ExternalSeriesId = externalSeriesId;
  1596. }
  1597. }
  1598. if (HasField(query, ItemFields.Taglines))
  1599. {
  1600. if (reader.TryGetString(index++, out var tagLine))
  1601. {
  1602. item.Tagline = tagLine;
  1603. }
  1604. }
  1605. if (item.ProviderIds.Count == 0 && reader.TryGetString(index, out var providerIds))
  1606. {
  1607. DeserializeProviderIds(providerIds, item);
  1608. }
  1609. index++;
  1610. if (query.DtoOptions.EnableImages)
  1611. {
  1612. if (item.ImageInfos.Length == 0 && reader.TryGetString(index, out var imageInfos))
  1613. {
  1614. item.ImageInfos = DeserializeImages(imageInfos);
  1615. }
  1616. index++;
  1617. }
  1618. if (HasField(query, ItemFields.ProductionLocations))
  1619. {
  1620. if (reader.TryGetString(index++, out var productionLocations))
  1621. {
  1622. item.ProductionLocations = productionLocations.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1623. }
  1624. }
  1625. if (HasField(query, ItemFields.ExtraIds))
  1626. {
  1627. if (reader.TryGetString(index++, out var extraIds))
  1628. {
  1629. item.ExtraIds = SplitToGuids(extraIds);
  1630. }
  1631. }
  1632. if (reader.TryGetInt32(index++, out var totalBitrate))
  1633. {
  1634. item.TotalBitrate = totalBitrate;
  1635. }
  1636. if (reader.TryGetString(index++, out var extraTypeString))
  1637. {
  1638. if (Enum.TryParse(extraTypeString, true, out ExtraType extraType))
  1639. {
  1640. item.ExtraType = extraType;
  1641. }
  1642. }
  1643. if (hasArtistFields)
  1644. {
  1645. if (item is IHasArtist hasArtists && reader.TryGetString(index, out var artists))
  1646. {
  1647. hasArtists.Artists = artists.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1648. }
  1649. index++;
  1650. if (item is IHasAlbumArtist hasAlbumArtists && reader.TryGetString(index, out var albumArtists))
  1651. {
  1652. hasAlbumArtists.AlbumArtists = albumArtists.Split('|', StringSplitOptions.RemoveEmptyEntries);
  1653. }
  1654. index++;
  1655. }
  1656. if (reader.TryGetString(index++, out var externalId))
  1657. {
  1658. item.ExternalId = externalId;
  1659. }
  1660. if (HasField(query, ItemFields.SeriesPresentationUniqueKey))
  1661. {
  1662. if (hasSeries is not null)
  1663. {
  1664. if (reader.TryGetString(index, out var seriesPresentationUniqueKey))
  1665. {
  1666. hasSeries.SeriesPresentationUniqueKey = seriesPresentationUniqueKey;
  1667. }
  1668. }
  1669. index++;
  1670. }
  1671. if (enableProgramAttributes)
  1672. {
  1673. if (item is LiveTvProgram program && reader.TryGetString(index, out var showId))
  1674. {
  1675. program.ShowId = showId;
  1676. }
  1677. index++;
  1678. }
  1679. if (reader.TryGetGuid(index, out var ownerId))
  1680. {
  1681. item.OwnerId = ownerId;
  1682. }
  1683. return item;
  1684. }
  1685. private static Guid[] SplitToGuids(string value)
  1686. {
  1687. var ids = value.Split('|');
  1688. var result = new Guid[ids.Length];
  1689. for (var i = 0; i < result.Length; i++)
  1690. {
  1691. result[i] = new Guid(ids[i]);
  1692. }
  1693. return result;
  1694. }
  1695. /// <inheritdoc />
  1696. public List<ChapterInfo> GetChapters(BaseItem item)
  1697. {
  1698. CheckDisposed();
  1699. using (var connection = GetConnection(true))
  1700. {
  1701. var chapters = new List<ChapterInfo>();
  1702. using (var statement = PrepareStatement(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc"))
  1703. {
  1704. statement.TryBind("@ItemId", item.Id);
  1705. foreach (var row in statement.ExecuteQuery())
  1706. {
  1707. chapters.Add(GetChapter(row, item));
  1708. }
  1709. }
  1710. return chapters;
  1711. }
  1712. }
  1713. /// <inheritdoc />
  1714. public ChapterInfo GetChapter(BaseItem item, int index)
  1715. {
  1716. CheckDisposed();
  1717. using (var connection = GetConnection(true))
  1718. {
  1719. using (var statement = PrepareStatement(connection, "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex"))
  1720. {
  1721. statement.TryBind("@ItemId", item.Id);
  1722. statement.TryBind("@ChapterIndex", index);
  1723. foreach (var row in statement.ExecuteQuery())
  1724. {
  1725. return GetChapter(row, item);
  1726. }
  1727. }
  1728. }
  1729. return null;
  1730. }
  1731. /// <summary>
  1732. /// Gets the chapter.
  1733. /// </summary>
  1734. /// <param name="reader">The reader.</param>
  1735. /// <param name="item">The item.</param>
  1736. /// <returns>ChapterInfo.</returns>
  1737. private ChapterInfo GetChapter(IReadOnlyList<ResultSetValue> reader, BaseItem item)
  1738. {
  1739. var chapter = new ChapterInfo
  1740. {
  1741. StartPositionTicks = reader.GetInt64(0)
  1742. };
  1743. if (reader.TryGetString(1, out var chapterName))
  1744. {
  1745. chapter.Name = chapterName;
  1746. }
  1747. if (reader.TryGetString(2, out var imagePath))
  1748. {
  1749. chapter.ImagePath = imagePath;
  1750. if (!string.IsNullOrEmpty(chapter.ImagePath))
  1751. {
  1752. try
  1753. {
  1754. chapter.ImageTag = _imageProcessor.GetImageCacheTag(item, chapter);
  1755. }
  1756. catch (Exception ex)
  1757. {
  1758. Logger.LogError(ex, "Failed to create image cache tag.");
  1759. }
  1760. }
  1761. }
  1762. if (reader.TryReadDateTime(3, out var imageDateModified))
  1763. {
  1764. chapter.ImageDateModified = imageDateModified;
  1765. }
  1766. return chapter;
  1767. }
  1768. /// <summary>
  1769. /// Saves the chapters.
  1770. /// </summary>
  1771. /// <param name="id">The item id.</param>
  1772. /// <param name="chapters">The chapters.</param>
  1773. public void SaveChapters(Guid id, IReadOnlyList<ChapterInfo> chapters)
  1774. {
  1775. CheckDisposed();
  1776. if (id.Equals(default))
  1777. {
  1778. throw new ArgumentNullException(nameof(id));
  1779. }
  1780. ArgumentNullException.ThrowIfNull(chapters);
  1781. var idBlob = id.ToByteArray();
  1782. using (var connection = GetConnection())
  1783. {
  1784. connection.RunInTransaction(
  1785. db =>
  1786. {
  1787. // First delete chapters
  1788. db.Execute("delete from " + ChaptersTableName + " where ItemId=@ItemId", idBlob);
  1789. InsertChapters(idBlob, chapters, db);
  1790. },
  1791. TransactionMode);
  1792. }
  1793. }
  1794. private void InsertChapters(byte[] idBlob, IReadOnlyList<ChapterInfo> chapters, IDatabaseConnection db)
  1795. {
  1796. var startIndex = 0;
  1797. var limit = 100;
  1798. var chapterIndex = 0;
  1799. const string StartInsertText = "insert into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath, ImageDateModified) values ";
  1800. var insertText = new StringBuilder(StartInsertText, 256);
  1801. while (startIndex < chapters.Count)
  1802. {
  1803. var endIndex = Math.Min(chapters.Count, startIndex + limit);
  1804. for (var i = startIndex; i < endIndex; i++)
  1805. {
  1806. insertText.AppendFormat(CultureInfo.InvariantCulture, "(@ItemId, @ChapterIndex{0}, @StartPositionTicks{0}, @Name{0}, @ImagePath{0}, @ImageDateModified{0}),", i.ToString(CultureInfo.InvariantCulture));
  1807. }
  1808. insertText.Length -= 1; // Remove last ,
  1809. using (var statement = PrepareStatement(db, insertText.ToString()))
  1810. {
  1811. statement.TryBind("@ItemId", idBlob);
  1812. for (var i = startIndex; i < endIndex; i++)
  1813. {
  1814. var index = i.ToString(CultureInfo.InvariantCulture);
  1815. var chapter = chapters[i];
  1816. statement.TryBind("@ChapterIndex" + index, chapterIndex);
  1817. statement.TryBind("@StartPositionTicks" + index, chapter.StartPositionTicks);
  1818. statement.TryBind("@Name" + index, chapter.Name);
  1819. statement.TryBind("@ImagePath" + index, chapter.ImagePath);
  1820. statement.TryBind("@ImageDateModified" + index, chapter.ImageDateModified);
  1821. chapterIndex++;
  1822. }
  1823. statement.Reset();
  1824. statement.MoveNext();
  1825. }
  1826. startIndex += limit;
  1827. insertText.Length = StartInsertText.Length;
  1828. }
  1829. }
  1830. private static bool EnableJoinUserData(InternalItemsQuery query)
  1831. {
  1832. if (query.User is null)
  1833. {
  1834. return false;
  1835. }
  1836. var sortingFields = new HashSet<string>(query.OrderBy.Select(i => i.OrderBy), StringComparer.OrdinalIgnoreCase);
  1837. return sortingFields.Contains(ItemSortBy.IsFavoriteOrLiked)
  1838. || sortingFields.Contains(ItemSortBy.IsPlayed)
  1839. || sortingFields.Contains(ItemSortBy.IsUnplayed)
  1840. || sortingFields.Contains(ItemSortBy.PlayCount)
  1841. || sortingFields.Contains(ItemSortBy.DatePlayed)
  1842. || sortingFields.Contains(ItemSortBy.SeriesDatePlayed)
  1843. || query.IsFavoriteOrLiked.HasValue
  1844. || query.IsFavorite.HasValue
  1845. || query.IsResumable.HasValue
  1846. || query.IsPlayed.HasValue
  1847. || query.IsLiked.HasValue;
  1848. }
  1849. private bool HasField(InternalItemsQuery query, ItemFields name)
  1850. {
  1851. switch (name)
  1852. {
  1853. case ItemFields.Tags:
  1854. return query.DtoOptions.ContainsField(name) || HasProgramAttributes(query);
  1855. case ItemFields.CustomRating:
  1856. case ItemFields.ProductionLocations:
  1857. case ItemFields.Settings:
  1858. case ItemFields.OriginalTitle:
  1859. case ItemFields.Taglines:
  1860. case ItemFields.SortName:
  1861. case ItemFields.Studios:
  1862. case ItemFields.ExtraIds:
  1863. case ItemFields.DateCreated:
  1864. case ItemFields.Overview:
  1865. case ItemFields.Genres:
  1866. case ItemFields.DateLastMediaAdded:
  1867. case ItemFields.PresentationUniqueKey:
  1868. case ItemFields.InheritedParentalRatingValue:
  1869. case ItemFields.ExternalSeriesId:
  1870. case ItemFields.SeriesPresentationUniqueKey:
  1871. case ItemFields.DateLastRefreshed:
  1872. case ItemFields.DateLastSaved:
  1873. return query.DtoOptions.ContainsField(name);
  1874. case ItemFields.ServiceName:
  1875. return HasServiceName(query);
  1876. default:
  1877. return true;
  1878. }
  1879. }
  1880. private bool HasProgramAttributes(InternalItemsQuery query)
  1881. {
  1882. if (query.ParentType is not null && _programExcludeParentTypes.Contains(query.ParentType.Value))
  1883. {
  1884. return false;
  1885. }
  1886. if (query.IncludeItemTypes.Length == 0)
  1887. {
  1888. return true;
  1889. }
  1890. return query.IncludeItemTypes.Any(x => _programTypes.Contains(x));
  1891. }
  1892. private bool HasServiceName(InternalItemsQuery query)
  1893. {
  1894. if (query.ParentType is not null && _programExcludeParentTypes.Contains(query.ParentType.Value))
  1895. {
  1896. return false;
  1897. }
  1898. if (query.IncludeItemTypes.Length == 0)
  1899. {
  1900. return true;
  1901. }
  1902. return query.IncludeItemTypes.Any(x => _serviceTypes.Contains(x));
  1903. }
  1904. private bool HasStartDate(InternalItemsQuery query)
  1905. {
  1906. if (query.ParentType is not null && _programExcludeParentTypes.Contains(query.ParentType.Value))
  1907. {
  1908. return false;
  1909. }
  1910. if (query.IncludeItemTypes.Length == 0)
  1911. {
  1912. return true;
  1913. }
  1914. return query.IncludeItemTypes.Any(x => _startDateTypes.Contains(x));
  1915. }
  1916. private bool HasEpisodeAttributes(InternalItemsQuery query)
  1917. {
  1918. if (query.IncludeItemTypes.Length == 0)
  1919. {
  1920. return true;
  1921. }
  1922. return query.IncludeItemTypes.Contains(BaseItemKind.Episode);
  1923. }
  1924. private bool HasTrailerTypes(InternalItemsQuery query)
  1925. {
  1926. if (query.IncludeItemTypes.Length == 0)
  1927. {
  1928. return true;
  1929. }
  1930. return query.IncludeItemTypes.Contains(BaseItemKind.Trailer);
  1931. }
  1932. private bool HasArtistFields(InternalItemsQuery query)
  1933. {
  1934. if (query.ParentType is not null && _artistExcludeParentTypes.Contains(query.ParentType.Value))
  1935. {
  1936. return false;
  1937. }
  1938. if (query.IncludeItemTypes.Length == 0)
  1939. {
  1940. return true;
  1941. }
  1942. return query.IncludeItemTypes.Any(x => _artistsTypes.Contains(x));
  1943. }
  1944. private bool HasSeriesFields(InternalItemsQuery query)
  1945. {
  1946. if (query.ParentType == BaseItemKind.PhotoAlbum)
  1947. {
  1948. return false;
  1949. }
  1950. if (query.IncludeItemTypes.Length == 0)
  1951. {
  1952. return true;
  1953. }
  1954. return query.IncludeItemTypes.Any(x => _seriesTypes.Contains(x));
  1955. }
  1956. private void SetFinalColumnsToSelect(InternalItemsQuery query, List<string> columns)
  1957. {
  1958. foreach (var field in _allItemFields)
  1959. {
  1960. if (!HasField(query, field))
  1961. {
  1962. switch (field)
  1963. {
  1964. case ItemFields.Settings:
  1965. columns.Remove("IsLocked");
  1966. columns.Remove("PreferredMetadataCountryCode");
  1967. columns.Remove("PreferredMetadataLanguage");
  1968. columns.Remove("LockedFields");
  1969. break;
  1970. case ItemFields.ServiceName:
  1971. columns.Remove("ExternalServiceId");
  1972. break;
  1973. case ItemFields.SortName:
  1974. columns.Remove("ForcedSortName");
  1975. break;
  1976. case ItemFields.Taglines:
  1977. columns.Remove("Tagline");
  1978. break;
  1979. case ItemFields.Tags:
  1980. columns.Remove("Tags");
  1981. break;
  1982. case ItemFields.IsHD:
  1983. // do nothing
  1984. break;
  1985. default:
  1986. columns.Remove(field.ToString());
  1987. break;
  1988. }
  1989. }
  1990. }
  1991. if (!HasProgramAttributes(query))
  1992. {
  1993. columns.Remove("IsMovie");
  1994. columns.Remove("IsSeries");
  1995. columns.Remove("EpisodeTitle");
  1996. columns.Remove("IsRepeat");
  1997. columns.Remove("ShowId");
  1998. }
  1999. if (!HasEpisodeAttributes(query))
  2000. {
  2001. columns.Remove("SeasonName");
  2002. columns.Remove("SeasonId");
  2003. }
  2004. if (!HasStartDate(query))
  2005. {
  2006. columns.Remove("StartDate");
  2007. }
  2008. if (!HasTrailerTypes(query))
  2009. {
  2010. columns.Remove("TrailerTypes");
  2011. }
  2012. if (!HasArtistFields(query))
  2013. {
  2014. columns.Remove("AlbumArtists");
  2015. columns.Remove("Artists");
  2016. }
  2017. if (!HasSeriesFields(query))
  2018. {
  2019. columns.Remove("SeriesId");
  2020. }
  2021. if (!HasEpisodeAttributes(query))
  2022. {
  2023. columns.Remove("SeasonName");
  2024. columns.Remove("SeasonId");
  2025. }
  2026. if (!query.DtoOptions.EnableImages)
  2027. {
  2028. columns.Remove("Images");
  2029. }
  2030. if (EnableJoinUserData(query))
  2031. {
  2032. columns.Add("UserDatas.UserId");
  2033. columns.Add("UserDatas.lastPlayedDate");
  2034. columns.Add("UserDatas.playbackPositionTicks");
  2035. columns.Add("UserDatas.playcount");
  2036. columns.Add("UserDatas.isFavorite");
  2037. columns.Add("UserDatas.played");
  2038. columns.Add("UserDatas.rating");
  2039. }
  2040. if (query.SimilarTo is not null)
  2041. {
  2042. var item = query.SimilarTo;
  2043. var builder = new StringBuilder();
  2044. builder.Append('(');
  2045. if (string.IsNullOrEmpty(item.OfficialRating))
  2046. {
  2047. builder.Append("(OfficialRating is null * 10)");
  2048. }
  2049. else
  2050. {
  2051. builder.Append("(OfficialRating=@ItemOfficialRating * 10)");
  2052. }
  2053. if (item.ProductionYear.HasValue)
  2054. {
  2055. builder.Append("+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 10 Then 10 Else 0 End )");
  2056. builder.Append("+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 5 Then 5 Else 0 End )");
  2057. }
  2058. // genres, tags, studios, person, year?
  2059. builder.Append("+ (Select count(1) * 10 from ItemValues where ItemId=Guid and CleanValue in (select CleanValue from ItemValues where ItemId=@SimilarItemId))");
  2060. if (item is MusicArtist)
  2061. {
  2062. // Match albums where the artist is AlbumArtist against other albums.
  2063. // It is assumed that similar albums => similar artists.
  2064. builder.Append(
  2065. @"+ (WITH artistValues AS (
  2066. SELECT DISTINCT albumValues.CleanValue
  2067. FROM ItemValues albumValues
  2068. INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
  2069. INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = @SimilarItemId
  2070. ), similarArtist AS (
  2071. SELECT albumValues.ItemId
  2072. FROM ItemValues albumValues
  2073. INNER JOIN ItemValues artistAlbums ON albumValues.ItemId = artistAlbums.ItemId
  2074. INNER JOIN TypedBaseItems artistItem ON artistAlbums.CleanValue = artistItem.CleanName AND artistAlbums.TYPE = 1 AND artistItem.Guid = A.Guid
  2075. ) SELECT COUNT(DISTINCT(CleanValue)) * 10 FROM ItemValues WHERE ItemId IN (SELECT ItemId FROM similarArtist) AND CleanValue IN (SELECT CleanValue FROM artistValues))");
  2076. }
  2077. builder.Append(") as SimilarityScore");
  2078. columns.Add(builder.ToString());
  2079. var oldLen = query.ExcludeItemIds.Length;
  2080. var newLen = oldLen + item.ExtraIds.Length + 1;
  2081. var excludeIds = new Guid[newLen];
  2082. query.ExcludeItemIds.CopyTo(excludeIds, 0);
  2083. excludeIds[oldLen] = item.Id;
  2084. item.ExtraIds.CopyTo(excludeIds, oldLen + 1);
  2085. query.ExcludeItemIds = excludeIds;
  2086. query.ExcludeProviderIds = item.ProviderIds;
  2087. }
  2088. if (!string.IsNullOrEmpty(query.SearchTerm))
  2089. {
  2090. var builder = new StringBuilder();
  2091. builder.Append('(');
  2092. builder.Append("((CleanName like @SearchTermStartsWith or (OriginalTitle not null and OriginalTitle like @SearchTermStartsWith)) * 10)");
  2093. builder.Append("+ ((CleanName = @SearchTermStartsWith COLLATE NOCASE or (OriginalTitle not null and OriginalTitle = @SearchTermStartsWith COLLATE NOCASE)) * 10)");
  2094. if (query.SearchTerm.Length > 1)
  2095. {
  2096. builder.Append("+ ((CleanName like @SearchTermContains or (OriginalTitle not null and OriginalTitle like @SearchTermContains)) * 10)");
  2097. }
  2098. builder.Append(") as SearchScore");
  2099. columns.Add(builder.ToString());
  2100. }
  2101. }
  2102. private void BindSearchParams(InternalItemsQuery query, IStatement statement)
  2103. {
  2104. var searchTerm = query.SearchTerm;
  2105. if (string.IsNullOrEmpty(searchTerm))
  2106. {
  2107. return;
  2108. }
  2109. searchTerm = FixUnicodeChars(searchTerm);
  2110. searchTerm = GetCleanValue(searchTerm);
  2111. var commandText = statement.SQL;
  2112. if (commandText.Contains("@SearchTermStartsWith", StringComparison.OrdinalIgnoreCase))
  2113. {
  2114. statement.TryBind("@SearchTermStartsWith", searchTerm + "%");
  2115. }
  2116. if (commandText.Contains("@SearchTermContains", StringComparison.OrdinalIgnoreCase))
  2117. {
  2118. statement.TryBind("@SearchTermContains", "%" + searchTerm + "%");
  2119. }
  2120. }
  2121. private void BindSimilarParams(InternalItemsQuery query, IStatement statement)
  2122. {
  2123. var item = query.SimilarTo;
  2124. if (item is null)
  2125. {
  2126. return;
  2127. }
  2128. var commandText = statement.SQL;
  2129. if (commandText.Contains("@ItemOfficialRating", StringComparison.OrdinalIgnoreCase))
  2130. {
  2131. statement.TryBind("@ItemOfficialRating", item.OfficialRating);
  2132. }
  2133. if (commandText.Contains("@ItemProductionYear", StringComparison.OrdinalIgnoreCase))
  2134. {
  2135. statement.TryBind("@ItemProductionYear", item.ProductionYear ?? 0);
  2136. }
  2137. if (commandText.Contains("@SimilarItemId", StringComparison.OrdinalIgnoreCase))
  2138. {
  2139. statement.TryBind("@SimilarItemId", item.Id);
  2140. }
  2141. }
  2142. private string GetJoinUserDataText(InternalItemsQuery query)
  2143. {
  2144. if (!EnableJoinUserData(query))
  2145. {
  2146. return string.Empty;
  2147. }
  2148. return " left join UserDatas on UserDataKey=UserDatas.Key And (UserId=@UserId)";
  2149. }
  2150. private string GetGroupBy(InternalItemsQuery query)
  2151. {
  2152. var enableGroupByPresentationUniqueKey = EnableGroupByPresentationUniqueKey(query);
  2153. if (enableGroupByPresentationUniqueKey && query.GroupBySeriesPresentationUniqueKey)
  2154. {
  2155. return " Group by PresentationUniqueKey, SeriesPresentationUniqueKey";
  2156. }
  2157. if (enableGroupByPresentationUniqueKey)
  2158. {
  2159. return " Group by PresentationUniqueKey";
  2160. }
  2161. if (query.GroupBySeriesPresentationUniqueKey)
  2162. {
  2163. return " Group by SeriesPresentationUniqueKey";
  2164. }
  2165. return string.Empty;
  2166. }
  2167. public int GetCount(InternalItemsQuery query)
  2168. {
  2169. ArgumentNullException.ThrowIfNull(query);
  2170. CheckDisposed();
  2171. var now = DateTime.UtcNow;
  2172. // Hack for right now since we currently don't support filtering out these duplicates within a query
  2173. if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
  2174. {
  2175. query.Limit = query.Limit.Value + 4;
  2176. }
  2177. var columns = new List<string> { "count(distinct PresentationUniqueKey)" };
  2178. SetFinalColumnsToSelect(query, columns);
  2179. var commandTextBuilder = new StringBuilder("select ", 256)
  2180. .AppendJoin(',', columns)
  2181. .Append(FromText)
  2182. .Append(GetJoinUserDataText(query));
  2183. var whereClauses = GetWhereClauses(query, null);
  2184. if (whereClauses.Count != 0)
  2185. {
  2186. commandTextBuilder.Append(" where ")
  2187. .AppendJoin(" AND ", whereClauses);
  2188. }
  2189. var commandText = commandTextBuilder.ToString();
  2190. int count;
  2191. using (var connection = GetConnection(true))
  2192. {
  2193. using (var statement = PrepareStatement(connection, commandText))
  2194. {
  2195. if (EnableJoinUserData(query))
  2196. {
  2197. statement.TryBind("@UserId", query.User.InternalId);
  2198. }
  2199. BindSimilarParams(query, statement);
  2200. BindSearchParams(query, statement);
  2201. // Running this again will bind the params
  2202. GetWhereClauses(query, statement);
  2203. count = statement.ExecuteQuery().SelectScalarInt().First();
  2204. }
  2205. }
  2206. LogQueryTime("GetCount", commandText, now);
  2207. return count;
  2208. }
  2209. public List<BaseItem> GetItemList(InternalItemsQuery query)
  2210. {
  2211. ArgumentNullException.ThrowIfNull(query);
  2212. CheckDisposed();
  2213. var now = DateTime.UtcNow;
  2214. // Hack for right now since we currently don't support filtering out these duplicates within a query
  2215. if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
  2216. {
  2217. query.Limit = query.Limit.Value + 4;
  2218. }
  2219. var columns = _retrieveItemColumns.ToList();
  2220. SetFinalColumnsToSelect(query, columns);
  2221. var commandTextBuilder = new StringBuilder("select ", 1024)
  2222. .AppendJoin(',', columns)
  2223. .Append(FromText)
  2224. .Append(GetJoinUserDataText(query));
  2225. var whereClauses = GetWhereClauses(query, null);
  2226. if (whereClauses.Count != 0)
  2227. {
  2228. commandTextBuilder.Append(" where ")
  2229. .AppendJoin(" AND ", whereClauses);
  2230. }
  2231. commandTextBuilder.Append(GetGroupBy(query))
  2232. .Append(GetOrderByText(query));
  2233. if (query.Limit.HasValue || query.StartIndex.HasValue)
  2234. {
  2235. var offset = query.StartIndex ?? 0;
  2236. if (query.Limit.HasValue || offset > 0)
  2237. {
  2238. commandTextBuilder.Append(" LIMIT ")
  2239. .Append(query.Limit ?? int.MaxValue);
  2240. }
  2241. if (offset > 0)
  2242. {
  2243. commandTextBuilder.Append(" OFFSET ")
  2244. .Append(offset);
  2245. }
  2246. }
  2247. var commandText = commandTextBuilder.ToString();
  2248. var items = new List<BaseItem>();
  2249. using (var connection = GetConnection(true))
  2250. {
  2251. using (var statement = PrepareStatement(connection, commandText))
  2252. {
  2253. if (EnableJoinUserData(query))
  2254. {
  2255. statement.TryBind("@UserId", query.User.InternalId);
  2256. }
  2257. BindSimilarParams(query, statement);
  2258. BindSearchParams(query, statement);
  2259. // Running this again will bind the params
  2260. GetWhereClauses(query, statement);
  2261. var hasEpisodeAttributes = HasEpisodeAttributes(query);
  2262. var hasServiceName = HasServiceName(query);
  2263. var hasProgramAttributes = HasProgramAttributes(query);
  2264. var hasStartDate = HasStartDate(query);
  2265. var hasTrailerTypes = HasTrailerTypes(query);
  2266. var hasArtistFields = HasArtistFields(query);
  2267. var hasSeriesFields = HasSeriesFields(query);
  2268. foreach (var row in statement.ExecuteQuery())
  2269. {
  2270. var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
  2271. if (item is not null)
  2272. {
  2273. items.Add(item);
  2274. }
  2275. }
  2276. }
  2277. // Hack for right now since we currently don't support filtering out these duplicates within a query
  2278. if (query.EnableGroupByMetadataKey)
  2279. {
  2280. var limit = query.Limit ?? int.MaxValue;
  2281. limit -= 4;
  2282. var newList = new List<BaseItem>();
  2283. foreach (var item in items)
  2284. {
  2285. AddItem(newList, item);
  2286. if (newList.Count >= limit)
  2287. {
  2288. break;
  2289. }
  2290. }
  2291. items = newList;
  2292. }
  2293. }
  2294. LogQueryTime("GetItemList", commandText, now);
  2295. return items;
  2296. }
  2297. private string FixUnicodeChars(string buffer)
  2298. {
  2299. buffer = buffer.Replace('\u2013', '-'); // en dash
  2300. buffer = buffer.Replace('\u2014', '-'); // em dash
  2301. buffer = buffer.Replace('\u2015', '-'); // horizontal bar
  2302. buffer = buffer.Replace('\u2017', '_'); // double low line
  2303. buffer = buffer.Replace('\u2018', '\''); // left single quotation mark
  2304. buffer = buffer.Replace('\u2019', '\''); // right single quotation mark
  2305. buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark
  2306. buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark
  2307. buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark
  2308. buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark
  2309. buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark
  2310. buffer = buffer.Replace("\u2026", "...", StringComparison.Ordinal); // horizontal ellipsis
  2311. buffer = buffer.Replace('\u2032', '\''); // prime
  2312. buffer = buffer.Replace('\u2033', '\"'); // double prime
  2313. buffer = buffer.Replace('\u0060', '\''); // grave accent
  2314. return buffer.Replace('\u00B4', '\''); // acute accent
  2315. }
  2316. private void AddItem(List<BaseItem> items, BaseItem newItem)
  2317. {
  2318. for (var i = 0; i < items.Count; i++)
  2319. {
  2320. var item = items[i];
  2321. foreach (var providerId in newItem.ProviderIds)
  2322. {
  2323. if (string.Equals(providerId.Key, nameof(MetadataProvider.TmdbCollection), StringComparison.Ordinal))
  2324. {
  2325. continue;
  2326. }
  2327. if (string.Equals(item.GetProviderId(providerId.Key), providerId.Value, StringComparison.Ordinal))
  2328. {
  2329. if (newItem.SourceType == SourceType.Library)
  2330. {
  2331. items[i] = newItem;
  2332. }
  2333. return;
  2334. }
  2335. }
  2336. }
  2337. items.Add(newItem);
  2338. }
  2339. private void LogQueryTime(string methodName, string commandText, DateTime startDate)
  2340. {
  2341. var elapsed = (DateTime.UtcNow - startDate).TotalMilliseconds;
  2342. #if DEBUG
  2343. const int SlowThreshold = 100;
  2344. #else
  2345. const int SlowThreshold = 10;
  2346. #endif
  2347. if (elapsed >= SlowThreshold)
  2348. {
  2349. Logger.LogDebug(
  2350. "{Method} query time (slow): {ElapsedMs}ms. Query: {Query}",
  2351. methodName,
  2352. elapsed,
  2353. commandText);
  2354. }
  2355. }
  2356. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  2357. {
  2358. ArgumentNullException.ThrowIfNull(query);
  2359. CheckDisposed();
  2360. if (!query.EnableTotalRecordCount || (!query.Limit.HasValue && (query.StartIndex ?? 0) == 0))
  2361. {
  2362. var returnList = GetItemList(query);
  2363. return new QueryResult<BaseItem>(
  2364. query.StartIndex,
  2365. returnList.Count,
  2366. returnList);
  2367. }
  2368. var now = DateTime.UtcNow;
  2369. // Hack for right now since we currently don't support filtering out these duplicates within a query
  2370. if (query.Limit.HasValue && query.EnableGroupByMetadataKey)
  2371. {
  2372. query.Limit = query.Limit.Value + 4;
  2373. }
  2374. var columns = _retrieveItemColumns.ToList();
  2375. SetFinalColumnsToSelect(query, columns);
  2376. var commandTextBuilder = new StringBuilder("select ", 512)
  2377. .AppendJoin(',', columns)
  2378. .Append(FromText)
  2379. .Append(GetJoinUserDataText(query));
  2380. var whereClauses = GetWhereClauses(query, null);
  2381. var whereText = whereClauses.Count == 0 ?
  2382. string.Empty :
  2383. string.Join(" AND ", whereClauses);
  2384. if (!string.IsNullOrEmpty(whereText))
  2385. {
  2386. commandTextBuilder.Append(" where ")
  2387. .Append(whereText);
  2388. }
  2389. commandTextBuilder.Append(GetGroupBy(query))
  2390. .Append(GetOrderByText(query));
  2391. if (query.Limit.HasValue || query.StartIndex.HasValue)
  2392. {
  2393. var offset = query.StartIndex ?? 0;
  2394. if (query.Limit.HasValue || offset > 0)
  2395. {
  2396. commandTextBuilder.Append(" LIMIT ")
  2397. .Append(query.Limit ?? int.MaxValue);
  2398. }
  2399. if (offset > 0)
  2400. {
  2401. commandTextBuilder.Append(" OFFSET ")
  2402. .Append(offset);
  2403. }
  2404. }
  2405. var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
  2406. var itemQuery = string.Empty;
  2407. var totalRecordCountQuery = string.Empty;
  2408. if (!isReturningZeroItems)
  2409. {
  2410. itemQuery = commandTextBuilder.ToString();
  2411. }
  2412. if (query.EnableTotalRecordCount)
  2413. {
  2414. commandTextBuilder.Clear();
  2415. commandTextBuilder.Append(" select ");
  2416. List<string> columnsToSelect;
  2417. if (EnableGroupByPresentationUniqueKey(query))
  2418. {
  2419. columnsToSelect = new List<string> { "count (distinct PresentationUniqueKey)" };
  2420. }
  2421. else if (query.GroupBySeriesPresentationUniqueKey)
  2422. {
  2423. columnsToSelect = new List<string> { "count (distinct SeriesPresentationUniqueKey)" };
  2424. }
  2425. else
  2426. {
  2427. columnsToSelect = new List<string> { "count (guid)" };
  2428. }
  2429. SetFinalColumnsToSelect(query, columnsToSelect);
  2430. commandTextBuilder.AppendJoin(',', columnsToSelect)
  2431. .Append(FromText)
  2432. .Append(GetJoinUserDataText(query));
  2433. if (!string.IsNullOrEmpty(whereText))
  2434. {
  2435. commandTextBuilder.Append(" where ")
  2436. .Append(whereText);
  2437. }
  2438. totalRecordCountQuery = commandTextBuilder.ToString();
  2439. }
  2440. var list = new List<BaseItem>();
  2441. var result = new QueryResult<BaseItem>();
  2442. using (var connection = GetConnection(true))
  2443. {
  2444. connection.RunInTransaction(
  2445. db =>
  2446. {
  2447. var itemQueryStatement = PrepareStatement(db, itemQuery);
  2448. var totalRecordCountQueryStatement = PrepareStatement(db, totalRecordCountQuery);
  2449. if (!isReturningZeroItems)
  2450. {
  2451. using (var statement = itemQueryStatement)
  2452. {
  2453. if (EnableJoinUserData(query))
  2454. {
  2455. statement.TryBind("@UserId", query.User.InternalId);
  2456. }
  2457. BindSimilarParams(query, statement);
  2458. BindSearchParams(query, statement);
  2459. // Running this again will bind the params
  2460. GetWhereClauses(query, statement);
  2461. var hasEpisodeAttributes = HasEpisodeAttributes(query);
  2462. var hasServiceName = HasServiceName(query);
  2463. var hasProgramAttributes = HasProgramAttributes(query);
  2464. var hasStartDate = HasStartDate(query);
  2465. var hasTrailerTypes = HasTrailerTypes(query);
  2466. var hasArtistFields = HasArtistFields(query);
  2467. var hasSeriesFields = HasSeriesFields(query);
  2468. foreach (var row in statement.ExecuteQuery())
  2469. {
  2470. var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
  2471. if (item is not null)
  2472. {
  2473. list.Add(item);
  2474. }
  2475. }
  2476. }
  2477. LogQueryTime("GetItems.ItemQuery", itemQuery, now);
  2478. }
  2479. now = DateTime.UtcNow;
  2480. if (query.EnableTotalRecordCount)
  2481. {
  2482. using (var statement = totalRecordCountQueryStatement)
  2483. {
  2484. if (EnableJoinUserData(query))
  2485. {
  2486. statement.TryBind("@UserId", query.User.InternalId);
  2487. }
  2488. BindSimilarParams(query, statement);
  2489. BindSearchParams(query, statement);
  2490. // Running this again will bind the params
  2491. GetWhereClauses(query, statement);
  2492. result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
  2493. }
  2494. LogQueryTime("GetItems.TotalRecordCount", totalRecordCountQuery, now);
  2495. }
  2496. },
  2497. ReadTransactionMode);
  2498. }
  2499. result.StartIndex = query.StartIndex ?? 0;
  2500. result.Items = list;
  2501. return result;
  2502. }
  2503. private string GetOrderByText(InternalItemsQuery query)
  2504. {
  2505. var orderBy = query.OrderBy;
  2506. bool hasSimilar = query.SimilarTo is not null;
  2507. bool hasSearch = !string.IsNullOrEmpty(query.SearchTerm);
  2508. if (hasSimilar || hasSearch)
  2509. {
  2510. List<(string, SortOrder)> prepend = new List<(string, SortOrder)>(4);
  2511. if (hasSearch)
  2512. {
  2513. prepend.Add(("SearchScore", SortOrder.Descending));
  2514. prepend.Add((ItemSortBy.SortName, SortOrder.Ascending));
  2515. }
  2516. if (hasSimilar)
  2517. {
  2518. prepend.Add(("SimilarityScore", SortOrder.Descending));
  2519. prepend.Add((ItemSortBy.Random, SortOrder.Ascending));
  2520. }
  2521. var arr = new (string, SortOrder)[prepend.Count + orderBy.Count];
  2522. prepend.CopyTo(arr, 0);
  2523. orderBy.CopyTo(arr, prepend.Count);
  2524. orderBy = query.OrderBy = arr;
  2525. }
  2526. else if (orderBy.Count == 0)
  2527. {
  2528. return string.Empty;
  2529. }
  2530. return " ORDER BY " + string.Join(',', orderBy.Select(i =>
  2531. {
  2532. var sortBy = MapOrderByField(i.OrderBy, query);
  2533. var sortOrder = i.SortOrder == SortOrder.Ascending ? "ASC" : "DESC";
  2534. return sortBy + " " + sortOrder;
  2535. }));
  2536. }
  2537. private string MapOrderByField(string name, InternalItemsQuery query)
  2538. {
  2539. if (string.Equals(name, ItemSortBy.AirTime, StringComparison.OrdinalIgnoreCase))
  2540. {
  2541. // TODO
  2542. return "SortName";
  2543. }
  2544. if (string.Equals(name, ItemSortBy.Runtime, StringComparison.OrdinalIgnoreCase))
  2545. {
  2546. return "RuntimeTicks";
  2547. }
  2548. if (string.Equals(name, ItemSortBy.Random, StringComparison.OrdinalIgnoreCase))
  2549. {
  2550. return "RANDOM()";
  2551. }
  2552. if (string.Equals(name, ItemSortBy.DatePlayed, StringComparison.OrdinalIgnoreCase))
  2553. {
  2554. if (query.GroupBySeriesPresentationUniqueKey)
  2555. {
  2556. return "MAX(LastPlayedDate)";
  2557. }
  2558. return "LastPlayedDate";
  2559. }
  2560. if (string.Equals(name, ItemSortBy.PlayCount, StringComparison.OrdinalIgnoreCase))
  2561. {
  2562. return ItemSortBy.PlayCount;
  2563. }
  2564. if (string.Equals(name, ItemSortBy.IsFavoriteOrLiked, StringComparison.OrdinalIgnoreCase))
  2565. {
  2566. return "(Select Case When IsFavorite is null Then 0 Else IsFavorite End )";
  2567. }
  2568. if (string.Equals(name, ItemSortBy.IsFolder, StringComparison.OrdinalIgnoreCase))
  2569. {
  2570. return ItemSortBy.IsFolder;
  2571. }
  2572. if (string.Equals(name, ItemSortBy.IsPlayed, StringComparison.OrdinalIgnoreCase))
  2573. {
  2574. return "played";
  2575. }
  2576. if (string.Equals(name, ItemSortBy.IsUnplayed, StringComparison.OrdinalIgnoreCase))
  2577. {
  2578. return "played";
  2579. }
  2580. if (string.Equals(name, ItemSortBy.DateLastContentAdded, StringComparison.OrdinalIgnoreCase))
  2581. {
  2582. return "DateLastMediaAdded";
  2583. }
  2584. if (string.Equals(name, ItemSortBy.Artist, StringComparison.OrdinalIgnoreCase))
  2585. {
  2586. return "(select CleanValue from ItemValues where ItemId=Guid and Type=0 LIMIT 1)";
  2587. }
  2588. if (string.Equals(name, ItemSortBy.AlbumArtist, StringComparison.OrdinalIgnoreCase))
  2589. {
  2590. return "(select CleanValue from ItemValues where ItemId=Guid and Type=1 LIMIT 1)";
  2591. }
  2592. if (string.Equals(name, ItemSortBy.OfficialRating, StringComparison.OrdinalIgnoreCase))
  2593. {
  2594. return "InheritedParentalRatingValue";
  2595. }
  2596. if (string.Equals(name, ItemSortBy.Studio, StringComparison.OrdinalIgnoreCase))
  2597. {
  2598. return "(select CleanValue from ItemValues where ItemId=Guid and Type=3 LIMIT 1)";
  2599. }
  2600. if (string.Equals(name, ItemSortBy.SeriesDatePlayed, StringComparison.OrdinalIgnoreCase))
  2601. {
  2602. return "(Select MAX(LastPlayedDate) from TypedBaseItems B" + GetJoinUserDataText(query) + " where Played=1 and B.SeriesPresentationUniqueKey=A.PresentationUniqueKey)";
  2603. }
  2604. if (string.Equals(name, ItemSortBy.SeriesSortName, StringComparison.OrdinalIgnoreCase))
  2605. {
  2606. return "SeriesName";
  2607. }
  2608. if (string.Equals(name, ItemSortBy.AiredEpisodeOrder, StringComparison.OrdinalIgnoreCase))
  2609. {
  2610. return ItemSortBy.AiredEpisodeOrder;
  2611. }
  2612. if (string.Equals(name, ItemSortBy.Album, StringComparison.OrdinalIgnoreCase))
  2613. {
  2614. return ItemSortBy.Album;
  2615. }
  2616. if (string.Equals(name, ItemSortBy.DateCreated, StringComparison.OrdinalIgnoreCase))
  2617. {
  2618. return ItemSortBy.DateCreated;
  2619. }
  2620. if (string.Equals(name, ItemSortBy.PremiereDate, StringComparison.OrdinalIgnoreCase))
  2621. {
  2622. return ItemSortBy.PremiereDate;
  2623. }
  2624. if (string.Equals(name, ItemSortBy.StartDate, StringComparison.OrdinalIgnoreCase))
  2625. {
  2626. return ItemSortBy.StartDate;
  2627. }
  2628. if (string.Equals(name, ItemSortBy.Name, StringComparison.OrdinalIgnoreCase))
  2629. {
  2630. return ItemSortBy.Name;
  2631. }
  2632. if (string.Equals(name, ItemSortBy.CommunityRating, StringComparison.OrdinalIgnoreCase))
  2633. {
  2634. return ItemSortBy.CommunityRating;
  2635. }
  2636. if (string.Equals(name, ItemSortBy.ProductionYear, StringComparison.OrdinalIgnoreCase))
  2637. {
  2638. return ItemSortBy.ProductionYear;
  2639. }
  2640. if (string.Equals(name, ItemSortBy.CriticRating, StringComparison.OrdinalIgnoreCase))
  2641. {
  2642. return ItemSortBy.CriticRating;
  2643. }
  2644. if (string.Equals(name, ItemSortBy.VideoBitRate, StringComparison.OrdinalIgnoreCase))
  2645. {
  2646. return ItemSortBy.VideoBitRate;
  2647. }
  2648. if (string.Equals(name, ItemSortBy.ParentIndexNumber, StringComparison.OrdinalIgnoreCase))
  2649. {
  2650. return ItemSortBy.ParentIndexNumber;
  2651. }
  2652. if (string.Equals(name, ItemSortBy.IndexNumber, StringComparison.OrdinalIgnoreCase))
  2653. {
  2654. return ItemSortBy.IndexNumber;
  2655. }
  2656. if (string.Equals(name, ItemSortBy.SimilarityScore, StringComparison.OrdinalIgnoreCase))
  2657. {
  2658. return ItemSortBy.SimilarityScore;
  2659. }
  2660. if (string.Equals(name, ItemSortBy.SearchScore, StringComparison.OrdinalIgnoreCase))
  2661. {
  2662. return ItemSortBy.SearchScore;
  2663. }
  2664. // Unknown SortBy, just sort by the SortName.
  2665. return ItemSortBy.SortName;
  2666. }
  2667. public List<Guid> GetItemIdsList(InternalItemsQuery query)
  2668. {
  2669. ArgumentNullException.ThrowIfNull(query);
  2670. CheckDisposed();
  2671. var now = DateTime.UtcNow;
  2672. var columns = new List<string> { "guid" };
  2673. SetFinalColumnsToSelect(query, columns);
  2674. var commandTextBuilder = new StringBuilder("select ", 256)
  2675. .AppendJoin(',', columns)
  2676. .Append(FromText)
  2677. .Append(GetJoinUserDataText(query));
  2678. var whereClauses = GetWhereClauses(query, null);
  2679. if (whereClauses.Count != 0)
  2680. {
  2681. commandTextBuilder.Append(" where ")
  2682. .AppendJoin(" AND ", whereClauses);
  2683. }
  2684. commandTextBuilder.Append(GetGroupBy(query))
  2685. .Append(GetOrderByText(query));
  2686. if (query.Limit.HasValue || query.StartIndex.HasValue)
  2687. {
  2688. var offset = query.StartIndex ?? 0;
  2689. if (query.Limit.HasValue || offset > 0)
  2690. {
  2691. commandTextBuilder.Append(" LIMIT ")
  2692. .Append(query.Limit ?? int.MaxValue);
  2693. }
  2694. if (offset > 0)
  2695. {
  2696. commandTextBuilder.Append(" OFFSET ")
  2697. .Append(offset);
  2698. }
  2699. }
  2700. var commandText = commandTextBuilder.ToString();
  2701. var list = new List<Guid>();
  2702. using (var connection = GetConnection(true))
  2703. {
  2704. using (var statement = PrepareStatement(connection, commandText))
  2705. {
  2706. if (EnableJoinUserData(query))
  2707. {
  2708. statement.TryBind("@UserId", query.User.InternalId);
  2709. }
  2710. BindSimilarParams(query, statement);
  2711. BindSearchParams(query, statement);
  2712. // Running this again will bind the params
  2713. GetWhereClauses(query, statement);
  2714. foreach (var row in statement.ExecuteQuery())
  2715. {
  2716. list.Add(row[0].ReadGuidFromBlob());
  2717. }
  2718. }
  2719. }
  2720. LogQueryTime("GetItemList", commandText, now);
  2721. return list;
  2722. }
  2723. private bool IsAlphaNumeric(string str)
  2724. {
  2725. if (string.IsNullOrWhiteSpace(str))
  2726. {
  2727. return false;
  2728. }
  2729. for (int i = 0; i < str.Length; i++)
  2730. {
  2731. if (!char.IsLetter(str[i]) && !char.IsNumber(str[i]))
  2732. {
  2733. return false;
  2734. }
  2735. }
  2736. return true;
  2737. }
  2738. private bool IsValidMediaType(string value)
  2739. {
  2740. return IsAlphaNumeric(value);
  2741. }
  2742. private bool IsValidPersonType(string value)
  2743. {
  2744. return IsAlphaNumeric(value);
  2745. }
  2746. private List<string> GetWhereClauses(InternalItemsQuery query, IStatement statement)
  2747. {
  2748. if (query.IsResumable ?? false)
  2749. {
  2750. query.IsVirtualItem = false;
  2751. }
  2752. var minWidth = query.MinWidth;
  2753. var maxWidth = query.MaxWidth;
  2754. if (query.IsHD.HasValue)
  2755. {
  2756. const int Threshold = 1200;
  2757. if (query.IsHD.Value)
  2758. {
  2759. minWidth = Threshold;
  2760. }
  2761. else
  2762. {
  2763. maxWidth = Threshold - 1;
  2764. }
  2765. }
  2766. if (query.Is4K.HasValue)
  2767. {
  2768. const int Threshold = 3800;
  2769. if (query.Is4K.Value)
  2770. {
  2771. minWidth = Threshold;
  2772. }
  2773. else
  2774. {
  2775. maxWidth = Threshold - 1;
  2776. }
  2777. }
  2778. var whereClauses = new List<string>();
  2779. if (minWidth.HasValue)
  2780. {
  2781. whereClauses.Add("Width>=@MinWidth");
  2782. statement?.TryBind("@MinWidth", minWidth);
  2783. }
  2784. if (query.MinHeight.HasValue)
  2785. {
  2786. whereClauses.Add("Height>=@MinHeight");
  2787. statement?.TryBind("@MinHeight", query.MinHeight);
  2788. }
  2789. if (maxWidth.HasValue)
  2790. {
  2791. whereClauses.Add("Width<=@MaxWidth");
  2792. statement?.TryBind("@MaxWidth", maxWidth);
  2793. }
  2794. if (query.MaxHeight.HasValue)
  2795. {
  2796. whereClauses.Add("Height<=@MaxHeight");
  2797. statement?.TryBind("@MaxHeight", query.MaxHeight);
  2798. }
  2799. if (query.IsLocked.HasValue)
  2800. {
  2801. whereClauses.Add("IsLocked=@IsLocked");
  2802. statement?.TryBind("@IsLocked", query.IsLocked);
  2803. }
  2804. var tags = query.Tags.ToList();
  2805. var excludeTags = query.ExcludeTags.ToList();
  2806. if (query.IsMovie == true)
  2807. {
  2808. if (query.IncludeItemTypes.Length == 0
  2809. || query.IncludeItemTypes.Contains(BaseItemKind.Movie)
  2810. || query.IncludeItemTypes.Contains(BaseItemKind.Trailer))
  2811. {
  2812. whereClauses.Add("(IsMovie is null OR IsMovie=@IsMovie)");
  2813. }
  2814. else
  2815. {
  2816. whereClauses.Add("IsMovie=@IsMovie");
  2817. }
  2818. statement?.TryBind("@IsMovie", true);
  2819. }
  2820. else if (query.IsMovie.HasValue)
  2821. {
  2822. whereClauses.Add("IsMovie=@IsMovie");
  2823. statement?.TryBind("@IsMovie", query.IsMovie);
  2824. }
  2825. if (query.IsSeries.HasValue)
  2826. {
  2827. whereClauses.Add("IsSeries=@IsSeries");
  2828. statement?.TryBind("@IsSeries", query.IsSeries);
  2829. }
  2830. if (query.IsSports.HasValue)
  2831. {
  2832. if (query.IsSports.Value)
  2833. {
  2834. tags.Add("Sports");
  2835. }
  2836. else
  2837. {
  2838. excludeTags.Add("Sports");
  2839. }
  2840. }
  2841. if (query.IsNews.HasValue)
  2842. {
  2843. if (query.IsNews.Value)
  2844. {
  2845. tags.Add("News");
  2846. }
  2847. else
  2848. {
  2849. excludeTags.Add("News");
  2850. }
  2851. }
  2852. if (query.IsKids.HasValue)
  2853. {
  2854. if (query.IsKids.Value)
  2855. {
  2856. tags.Add("Kids");
  2857. }
  2858. else
  2859. {
  2860. excludeTags.Add("Kids");
  2861. }
  2862. }
  2863. if (query.SimilarTo is not null && query.MinSimilarityScore > 0)
  2864. {
  2865. whereClauses.Add("SimilarityScore > " + (query.MinSimilarityScore - 1).ToString(CultureInfo.InvariantCulture));
  2866. }
  2867. if (!string.IsNullOrEmpty(query.SearchTerm))
  2868. {
  2869. whereClauses.Add("SearchScore > 0");
  2870. }
  2871. if (query.IsFolder.HasValue)
  2872. {
  2873. whereClauses.Add("IsFolder=@IsFolder");
  2874. statement?.TryBind("@IsFolder", query.IsFolder);
  2875. }
  2876. var includeTypes = query.IncludeItemTypes;
  2877. // Only specify excluded types if no included types are specified
  2878. if (query.IncludeItemTypes.Length == 0)
  2879. {
  2880. var excludeTypes = query.ExcludeItemTypes;
  2881. if (excludeTypes.Length == 1)
  2882. {
  2883. if (_baseItemKindNames.TryGetValue(excludeTypes[0], out var excludeTypeName))
  2884. {
  2885. whereClauses.Add("type<>@type");
  2886. statement?.TryBind("@type", excludeTypeName);
  2887. }
  2888. else
  2889. {
  2890. Logger.LogWarning("Undefined BaseItemKind to Type mapping: {BaseItemKind}", excludeTypes[0]);
  2891. }
  2892. }
  2893. else if (excludeTypes.Length > 1)
  2894. {
  2895. var whereBuilder = new StringBuilder("type not in (");
  2896. foreach (var excludeType in excludeTypes)
  2897. {
  2898. if (_baseItemKindNames.TryGetValue(excludeType, out var baseItemKindName))
  2899. {
  2900. whereBuilder
  2901. .Append('\'')
  2902. .Append(baseItemKindName)
  2903. .Append("',");
  2904. }
  2905. else
  2906. {
  2907. Logger.LogWarning("Undefined BaseItemKind to Type mapping: {BaseItemKind}", excludeType);
  2908. }
  2909. }
  2910. // Remove trailing comma.
  2911. whereBuilder.Length--;
  2912. whereBuilder.Append(')');
  2913. whereClauses.Add(whereBuilder.ToString());
  2914. }
  2915. }
  2916. else if (includeTypes.Length == 1)
  2917. {
  2918. if (_baseItemKindNames.TryGetValue(includeTypes[0], out var includeTypeName))
  2919. {
  2920. whereClauses.Add("type=@type");
  2921. statement?.TryBind("@type", includeTypeName);
  2922. }
  2923. else
  2924. {
  2925. Logger.LogWarning("Undefined BaseItemKind to Type mapping: {BaseItemKind}", includeTypes[0]);
  2926. }
  2927. }
  2928. else if (includeTypes.Length > 1)
  2929. {
  2930. var whereBuilder = new StringBuilder("type in (");
  2931. foreach (var includeType in includeTypes)
  2932. {
  2933. if (_baseItemKindNames.TryGetValue(includeType, out var baseItemKindName))
  2934. {
  2935. whereBuilder
  2936. .Append('\'')
  2937. .Append(baseItemKindName)
  2938. .Append("',");
  2939. }
  2940. else
  2941. {
  2942. Logger.LogWarning("Undefined BaseItemKind to Type mapping: {BaseItemKind}", includeType);
  2943. }
  2944. }
  2945. // Remove trailing comma.
  2946. whereBuilder.Length--;
  2947. whereBuilder.Append(')');
  2948. whereClauses.Add(whereBuilder.ToString());
  2949. }
  2950. if (query.ChannelIds.Count == 1)
  2951. {
  2952. whereClauses.Add("ChannelId=@ChannelId");
  2953. statement?.TryBind("@ChannelId", query.ChannelIds[0].ToString("N", CultureInfo.InvariantCulture));
  2954. }
  2955. else if (query.ChannelIds.Count > 1)
  2956. {
  2957. var inClause = string.Join(',', query.ChannelIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
  2958. whereClauses.Add($"ChannelId in ({inClause})");
  2959. }
  2960. if (!query.ParentId.Equals(default))
  2961. {
  2962. whereClauses.Add("ParentId=@ParentId");
  2963. statement?.TryBind("@ParentId", query.ParentId);
  2964. }
  2965. if (!string.IsNullOrWhiteSpace(query.Path))
  2966. {
  2967. whereClauses.Add("Path=@Path");
  2968. statement?.TryBind("@Path", GetPathToSave(query.Path));
  2969. }
  2970. if (!string.IsNullOrWhiteSpace(query.PresentationUniqueKey))
  2971. {
  2972. whereClauses.Add("PresentationUniqueKey=@PresentationUniqueKey");
  2973. statement?.TryBind("@PresentationUniqueKey", query.PresentationUniqueKey);
  2974. }
  2975. if (query.MinCommunityRating.HasValue)
  2976. {
  2977. whereClauses.Add("CommunityRating>=@MinCommunityRating");
  2978. statement?.TryBind("@MinCommunityRating", query.MinCommunityRating.Value);
  2979. }
  2980. if (query.MinIndexNumber.HasValue)
  2981. {
  2982. whereClauses.Add("IndexNumber>=@MinIndexNumber");
  2983. statement?.TryBind("@MinIndexNumber", query.MinIndexNumber.Value);
  2984. }
  2985. if (query.MinParentAndIndexNumber.HasValue)
  2986. {
  2987. whereClauses.Add("((ParentIndexNumber=@MinParentAndIndexNumberParent and IndexNumber>=@MinParentAndIndexNumberIndex) or ParentIndexNumber>@MinParentAndIndexNumberParent)");
  2988. statement?.TryBind("@MinParentAndIndexNumberParent", query.MinParentAndIndexNumber.Value.ParentIndexNumber);
  2989. statement?.TryBind("@MinParentAndIndexNumberIndex", query.MinParentAndIndexNumber.Value.IndexNumber);
  2990. }
  2991. if (query.MinDateCreated.HasValue)
  2992. {
  2993. whereClauses.Add("DateCreated>=@MinDateCreated");
  2994. statement?.TryBind("@MinDateCreated", query.MinDateCreated.Value);
  2995. }
  2996. if (query.MinDateLastSaved.HasValue)
  2997. {
  2998. whereClauses.Add("(DateLastSaved not null and DateLastSaved>=@MinDateLastSavedForUser)");
  2999. statement?.TryBind("@MinDateLastSaved", query.MinDateLastSaved.Value);
  3000. }
  3001. if (query.MinDateLastSavedForUser.HasValue)
  3002. {
  3003. whereClauses.Add("(DateLastSaved not null and DateLastSaved>=@MinDateLastSavedForUser)");
  3004. statement?.TryBind("@MinDateLastSavedForUser", query.MinDateLastSavedForUser.Value);
  3005. }
  3006. if (query.IndexNumber.HasValue)
  3007. {
  3008. whereClauses.Add("IndexNumber=@IndexNumber");
  3009. statement?.TryBind("@IndexNumber", query.IndexNumber.Value);
  3010. }
  3011. if (query.ParentIndexNumber.HasValue)
  3012. {
  3013. whereClauses.Add("ParentIndexNumber=@ParentIndexNumber");
  3014. statement?.TryBind("@ParentIndexNumber", query.ParentIndexNumber.Value);
  3015. }
  3016. if (query.ParentIndexNumberNotEquals.HasValue)
  3017. {
  3018. whereClauses.Add("(ParentIndexNumber<>@ParentIndexNumberNotEquals or ParentIndexNumber is null)");
  3019. statement?.TryBind("@ParentIndexNumberNotEquals", query.ParentIndexNumberNotEquals.Value);
  3020. }
  3021. var minEndDate = query.MinEndDate;
  3022. var maxEndDate = query.MaxEndDate;
  3023. if (query.HasAired.HasValue)
  3024. {
  3025. if (query.HasAired.Value)
  3026. {
  3027. maxEndDate = DateTime.UtcNow;
  3028. }
  3029. else
  3030. {
  3031. minEndDate = DateTime.UtcNow;
  3032. }
  3033. }
  3034. if (minEndDate.HasValue)
  3035. {
  3036. whereClauses.Add("EndDate>=@MinEndDate");
  3037. statement?.TryBind("@MinEndDate", minEndDate.Value);
  3038. }
  3039. if (maxEndDate.HasValue)
  3040. {
  3041. whereClauses.Add("EndDate<=@MaxEndDate");
  3042. statement?.TryBind("@MaxEndDate", maxEndDate.Value);
  3043. }
  3044. if (query.MinStartDate.HasValue)
  3045. {
  3046. whereClauses.Add("StartDate>=@MinStartDate");
  3047. statement?.TryBind("@MinStartDate", query.MinStartDate.Value);
  3048. }
  3049. if (query.MaxStartDate.HasValue)
  3050. {
  3051. whereClauses.Add("StartDate<=@MaxStartDate");
  3052. statement?.TryBind("@MaxStartDate", query.MaxStartDate.Value);
  3053. }
  3054. if (query.MinPremiereDate.HasValue)
  3055. {
  3056. whereClauses.Add("PremiereDate>=@MinPremiereDate");
  3057. statement?.TryBind("@MinPremiereDate", query.MinPremiereDate.Value);
  3058. }
  3059. if (query.MaxPremiereDate.HasValue)
  3060. {
  3061. whereClauses.Add("PremiereDate<=@MaxPremiereDate");
  3062. statement?.TryBind("@MaxPremiereDate", query.MaxPremiereDate.Value);
  3063. }
  3064. StringBuilder clauseBuilder = new StringBuilder();
  3065. const string Or = " OR ";
  3066. var trailerTypes = query.TrailerTypes;
  3067. int trailerTypesLen = trailerTypes.Length;
  3068. if (trailerTypesLen > 0)
  3069. {
  3070. clauseBuilder.Append('(');
  3071. for (int i = 0; i < trailerTypesLen; i++)
  3072. {
  3073. var paramName = "@TrailerTypes" + i;
  3074. clauseBuilder.Append("TrailerTypes like ")
  3075. .Append(paramName)
  3076. .Append(Or);
  3077. statement?.TryBind(paramName, "%" + trailerTypes[i] + "%");
  3078. }
  3079. // Remove last " OR "
  3080. clauseBuilder.Length -= Or.Length;
  3081. clauseBuilder.Append(')');
  3082. whereClauses.Add(clauseBuilder.ToString());
  3083. clauseBuilder.Length = 0;
  3084. }
  3085. if (query.IsAiring.HasValue)
  3086. {
  3087. if (query.IsAiring.Value)
  3088. {
  3089. whereClauses.Add("StartDate<=@MaxStartDate");
  3090. statement?.TryBind("@MaxStartDate", DateTime.UtcNow);
  3091. whereClauses.Add("EndDate>=@MinEndDate");
  3092. statement?.TryBind("@MinEndDate", DateTime.UtcNow);
  3093. }
  3094. else
  3095. {
  3096. whereClauses.Add("(StartDate>@IsAiringDate OR EndDate < @IsAiringDate)");
  3097. statement?.TryBind("@IsAiringDate", DateTime.UtcNow);
  3098. }
  3099. }
  3100. int personIdsLen = query.PersonIds.Length;
  3101. if (personIdsLen > 0)
  3102. {
  3103. // TODO: Should this query with CleanName ?
  3104. clauseBuilder.Append('(');
  3105. Span<byte> idBytes = stackalloc byte[16];
  3106. for (int i = 0; i < personIdsLen; i++)
  3107. {
  3108. string paramName = "@PersonId" + i;
  3109. clauseBuilder.Append("(guid in (select itemid from People where Name = (select Name from TypedBaseItems where guid=")
  3110. .Append(paramName)
  3111. .Append("))) OR ");
  3112. if (statement is not null)
  3113. {
  3114. query.PersonIds[i].TryWriteBytes(idBytes);
  3115. statement.TryBind(paramName, idBytes);
  3116. }
  3117. }
  3118. // Remove last " OR "
  3119. clauseBuilder.Length -= Or.Length;
  3120. clauseBuilder.Append(')');
  3121. whereClauses.Add(clauseBuilder.ToString());
  3122. clauseBuilder.Length = 0;
  3123. }
  3124. if (!string.IsNullOrWhiteSpace(query.Person))
  3125. {
  3126. whereClauses.Add("Guid in (select ItemId from People where Name=@PersonName)");
  3127. statement?.TryBind("@PersonName", query.Person);
  3128. }
  3129. if (!string.IsNullOrWhiteSpace(query.MinSortName))
  3130. {
  3131. whereClauses.Add("SortName>=@MinSortName");
  3132. statement?.TryBind("@MinSortName", query.MinSortName);
  3133. }
  3134. if (!string.IsNullOrWhiteSpace(query.ExternalSeriesId))
  3135. {
  3136. whereClauses.Add("ExternalSeriesId=@ExternalSeriesId");
  3137. statement?.TryBind("@ExternalSeriesId", query.ExternalSeriesId);
  3138. }
  3139. if (!string.IsNullOrWhiteSpace(query.ExternalId))
  3140. {
  3141. whereClauses.Add("ExternalId=@ExternalId");
  3142. statement?.TryBind("@ExternalId", query.ExternalId);
  3143. }
  3144. if (!string.IsNullOrWhiteSpace(query.Name))
  3145. {
  3146. whereClauses.Add("CleanName=@Name");
  3147. statement?.TryBind("@Name", GetCleanValue(query.Name));
  3148. }
  3149. // These are the same, for now
  3150. var nameContains = query.NameContains;
  3151. if (!string.IsNullOrWhiteSpace(nameContains))
  3152. {
  3153. whereClauses.Add("(CleanName like @NameContains or OriginalTitle like @NameContains)");
  3154. if (statement is not null)
  3155. {
  3156. nameContains = FixUnicodeChars(nameContains);
  3157. statement.TryBind("@NameContains", "%" + GetCleanValue(nameContains) + "%");
  3158. }
  3159. }
  3160. if (!string.IsNullOrWhiteSpace(query.NameStartsWith))
  3161. {
  3162. whereClauses.Add("SortName like @NameStartsWith");
  3163. statement?.TryBind("@NameStartsWith", query.NameStartsWith + "%");
  3164. }
  3165. if (!string.IsNullOrWhiteSpace(query.NameStartsWithOrGreater))
  3166. {
  3167. whereClauses.Add("SortName >= @NameStartsWithOrGreater");
  3168. // lowercase this because SortName is stored as lowercase
  3169. statement?.TryBind("@NameStartsWithOrGreater", query.NameStartsWithOrGreater.ToLowerInvariant());
  3170. }
  3171. if (!string.IsNullOrWhiteSpace(query.NameLessThan))
  3172. {
  3173. whereClauses.Add("SortName < @NameLessThan");
  3174. // lowercase this because SortName is stored as lowercase
  3175. statement?.TryBind("@NameLessThan", query.NameLessThan.ToLowerInvariant());
  3176. }
  3177. if (query.ImageTypes.Length > 0)
  3178. {
  3179. foreach (var requiredImage in query.ImageTypes)
  3180. {
  3181. whereClauses.Add("Images like '%" + requiredImage + "%'");
  3182. }
  3183. }
  3184. if (query.IsLiked.HasValue)
  3185. {
  3186. if (query.IsLiked.Value)
  3187. {
  3188. whereClauses.Add("rating>=@UserRating");
  3189. statement?.TryBind("@UserRating", UserItemData.MinLikeValue);
  3190. }
  3191. else
  3192. {
  3193. whereClauses.Add("(rating is null or rating<@UserRating)");
  3194. statement?.TryBind("@UserRating", UserItemData.MinLikeValue);
  3195. }
  3196. }
  3197. if (query.IsFavoriteOrLiked.HasValue)
  3198. {
  3199. if (query.IsFavoriteOrLiked.Value)
  3200. {
  3201. whereClauses.Add("IsFavorite=@IsFavoriteOrLiked");
  3202. }
  3203. else
  3204. {
  3205. whereClauses.Add("(IsFavorite is null or IsFavorite=@IsFavoriteOrLiked)");
  3206. }
  3207. statement?.TryBind("@IsFavoriteOrLiked", query.IsFavoriteOrLiked.Value);
  3208. }
  3209. if (query.IsFavorite.HasValue)
  3210. {
  3211. if (query.IsFavorite.Value)
  3212. {
  3213. whereClauses.Add("IsFavorite=@IsFavorite");
  3214. }
  3215. else
  3216. {
  3217. whereClauses.Add("(IsFavorite is null or IsFavorite=@IsFavorite)");
  3218. }
  3219. statement?.TryBind("@IsFavorite", query.IsFavorite.Value);
  3220. }
  3221. if (EnableJoinUserData(query))
  3222. {
  3223. if (query.IsPlayed.HasValue)
  3224. {
  3225. // We should probably figure this out for all folders, but for right now, this is the only place where we need it
  3226. if (query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.Series)
  3227. {
  3228. if (query.IsPlayed.Value)
  3229. {
  3230. whereClauses.Add("PresentationUniqueKey not in (select S.SeriesPresentationUniqueKey from TypedBaseitems S left join UserDatas UD on S.UserDataKey=UD.Key And UD.UserId=@UserId where Coalesce(UD.Played, 0)=0 and S.IsFolder=0 and S.IsVirtualItem=0 and S.SeriesPresentationUniqueKey not null)");
  3231. }
  3232. else
  3233. {
  3234. whereClauses.Add("PresentationUniqueKey in (select S.SeriesPresentationUniqueKey from TypedBaseitems S left join UserDatas UD on S.UserDataKey=UD.Key And UD.UserId=@UserId where Coalesce(UD.Played, 0)=0 and S.IsFolder=0 and S.IsVirtualItem=0 and S.SeriesPresentationUniqueKey not null)");
  3235. }
  3236. }
  3237. else
  3238. {
  3239. if (query.IsPlayed.Value)
  3240. {
  3241. whereClauses.Add("(played=@IsPlayed)");
  3242. }
  3243. else
  3244. {
  3245. whereClauses.Add("(played is null or played=@IsPlayed)");
  3246. }
  3247. statement?.TryBind("@IsPlayed", query.IsPlayed.Value);
  3248. }
  3249. }
  3250. }
  3251. if (query.IsResumable.HasValue)
  3252. {
  3253. if (query.IsResumable.Value)
  3254. {
  3255. whereClauses.Add("playbackPositionTicks > 0");
  3256. }
  3257. else
  3258. {
  3259. whereClauses.Add("(playbackPositionTicks is null or playbackPositionTicks = 0)");
  3260. }
  3261. }
  3262. if (query.ArtistIds.Length > 0)
  3263. {
  3264. var clauses = new List<string>();
  3265. var index = 0;
  3266. foreach (var artistId in query.ArtistIds)
  3267. {
  3268. var paramName = "@ArtistIds" + index;
  3269. clauses.Add("(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))");
  3270. if (statement is not null)
  3271. {
  3272. statement.TryBind(paramName, artistId);
  3273. }
  3274. index++;
  3275. }
  3276. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3277. whereClauses.Add(clause);
  3278. }
  3279. if (query.AlbumArtistIds.Length > 0)
  3280. {
  3281. var clauses = new List<string>();
  3282. var index = 0;
  3283. foreach (var artistId in query.AlbumArtistIds)
  3284. {
  3285. var paramName = "@ArtistIds" + index;
  3286. clauses.Add("(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=1))");
  3287. if (statement is not null)
  3288. {
  3289. statement.TryBind(paramName, artistId);
  3290. }
  3291. index++;
  3292. }
  3293. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3294. whereClauses.Add(clause);
  3295. }
  3296. if (query.ContributingArtistIds.Length > 0)
  3297. {
  3298. var clauses = new List<string>();
  3299. var index = 0;
  3300. foreach (var artistId in query.ContributingArtistIds)
  3301. {
  3302. var paramName = "@ArtistIds" + index;
  3303. clauses.Add("((select CleanName from TypedBaseItems where guid=" + paramName + ") in (select CleanValue from ItemValues where ItemId=Guid and Type=0) AND (select CleanName from TypedBaseItems where guid=" + paramName + ") not in (select CleanValue from ItemValues where ItemId=Guid and Type=1))");
  3304. if (statement is not null)
  3305. {
  3306. statement.TryBind(paramName, artistId);
  3307. }
  3308. index++;
  3309. }
  3310. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3311. whereClauses.Add(clause);
  3312. }
  3313. if (query.AlbumIds.Length > 0)
  3314. {
  3315. var clauses = new List<string>();
  3316. var index = 0;
  3317. foreach (var albumId in query.AlbumIds)
  3318. {
  3319. var paramName = "@AlbumIds" + index;
  3320. clauses.Add("Album in (select Name from typedbaseitems where guid=" + paramName + ")");
  3321. if (statement is not null)
  3322. {
  3323. statement.TryBind(paramName, albumId);
  3324. }
  3325. index++;
  3326. }
  3327. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3328. whereClauses.Add(clause);
  3329. }
  3330. if (query.ExcludeArtistIds.Length > 0)
  3331. {
  3332. var clauses = new List<string>();
  3333. var index = 0;
  3334. foreach (var artistId in query.ExcludeArtistIds)
  3335. {
  3336. var paramName = "@ExcludeArtistId" + index;
  3337. clauses.Add("(guid not in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type<=1))");
  3338. if (statement is not null)
  3339. {
  3340. statement.TryBind(paramName, artistId);
  3341. }
  3342. index++;
  3343. }
  3344. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3345. whereClauses.Add(clause);
  3346. }
  3347. if (query.GenreIds.Count > 0)
  3348. {
  3349. var clauses = new List<string>();
  3350. var index = 0;
  3351. foreach (var genreId in query.GenreIds)
  3352. {
  3353. var paramName = "@GenreId" + index;
  3354. clauses.Add("(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=2))");
  3355. if (statement is not null)
  3356. {
  3357. statement.TryBind(paramName, genreId);
  3358. }
  3359. index++;
  3360. }
  3361. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3362. whereClauses.Add(clause);
  3363. }
  3364. if (query.Genres.Count > 0)
  3365. {
  3366. var clauses = new List<string>();
  3367. var index = 0;
  3368. foreach (var item in query.Genres)
  3369. {
  3370. clauses.Add("@Genre" + index + " in (select CleanValue from ItemValues where ItemId=Guid and Type=2)");
  3371. if (statement is not null)
  3372. {
  3373. statement.TryBind("@Genre" + index, GetCleanValue(item));
  3374. }
  3375. index++;
  3376. }
  3377. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3378. whereClauses.Add(clause);
  3379. }
  3380. if (tags.Count > 0)
  3381. {
  3382. var clauses = new List<string>();
  3383. var index = 0;
  3384. foreach (var item in tags)
  3385. {
  3386. clauses.Add("@Tag" + index + " in (select CleanValue from ItemValues where ItemId=Guid and Type=4)");
  3387. if (statement is not null)
  3388. {
  3389. statement.TryBind("@Tag" + index, GetCleanValue(item));
  3390. }
  3391. index++;
  3392. }
  3393. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3394. whereClauses.Add(clause);
  3395. }
  3396. if (excludeTags.Count > 0)
  3397. {
  3398. var clauses = new List<string>();
  3399. var index = 0;
  3400. foreach (var item in excludeTags)
  3401. {
  3402. clauses.Add("@ExcludeTag" + index + " not in (select CleanValue from ItemValues where ItemId=Guid and Type=4)");
  3403. if (statement is not null)
  3404. {
  3405. statement.TryBind("@ExcludeTag" + index, GetCleanValue(item));
  3406. }
  3407. index++;
  3408. }
  3409. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3410. whereClauses.Add(clause);
  3411. }
  3412. if (query.StudioIds.Length > 0)
  3413. {
  3414. var clauses = new List<string>();
  3415. var index = 0;
  3416. foreach (var studioId in query.StudioIds)
  3417. {
  3418. var paramName = "@StudioId" + index;
  3419. clauses.Add("(guid in (select itemid from ItemValues where CleanValue = (select CleanName from TypedBaseItems where guid=" + paramName + ") and Type=3))");
  3420. if (statement is not null)
  3421. {
  3422. statement.TryBind(paramName, studioId);
  3423. }
  3424. index++;
  3425. }
  3426. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3427. whereClauses.Add(clause);
  3428. }
  3429. if (query.OfficialRatings.Length > 0)
  3430. {
  3431. var clauses = new List<string>();
  3432. var index = 0;
  3433. foreach (var item in query.OfficialRatings)
  3434. {
  3435. clauses.Add("OfficialRating=@OfficialRating" + index);
  3436. if (statement is not null)
  3437. {
  3438. statement.TryBind("@OfficialRating" + index, item);
  3439. }
  3440. index++;
  3441. }
  3442. var clause = "(" + string.Join(" OR ", clauses) + ")";
  3443. whereClauses.Add(clause);
  3444. }
  3445. if (query.MinParentalRating.HasValue)
  3446. {
  3447. whereClauses.Add("InheritedParentalRatingValue>=@MinParentalRating");
  3448. if (statement is not null)
  3449. {
  3450. statement.TryBind("@MinParentalRating", query.MinParentalRating.Value);
  3451. }
  3452. }
  3453. if (query.MaxParentalRating.HasValue)
  3454. {
  3455. whereClauses.Add("InheritedParentalRatingValue<=@MaxParentalRating");
  3456. if (statement is not null)
  3457. {
  3458. statement.TryBind("@MaxParentalRating", query.MaxParentalRating.Value);
  3459. }
  3460. }
  3461. if (query.HasParentalRating.HasValue)
  3462. {
  3463. if (query.HasParentalRating.Value)
  3464. {
  3465. whereClauses.Add("InheritedParentalRatingValue > 0");
  3466. }
  3467. else
  3468. {
  3469. whereClauses.Add("InheritedParentalRatingValue = 0");
  3470. }
  3471. }
  3472. if (query.HasOfficialRating.HasValue)
  3473. {
  3474. if (query.HasOfficialRating.Value)
  3475. {
  3476. whereClauses.Add("(OfficialRating not null AND OfficialRating<>'')");
  3477. }
  3478. else
  3479. {
  3480. whereClauses.Add("(OfficialRating is null OR OfficialRating='')");
  3481. }
  3482. }
  3483. if (query.HasOverview.HasValue)
  3484. {
  3485. if (query.HasOverview.Value)
  3486. {
  3487. whereClauses.Add("(Overview not null AND Overview<>'')");
  3488. }
  3489. else
  3490. {
  3491. whereClauses.Add("(Overview is null OR Overview='')");
  3492. }
  3493. }
  3494. if (query.HasOwnerId.HasValue)
  3495. {
  3496. if (query.HasOwnerId.Value)
  3497. {
  3498. whereClauses.Add("OwnerId not null");
  3499. }
  3500. else
  3501. {
  3502. whereClauses.Add("OwnerId is null");
  3503. }
  3504. }
  3505. if (!string.IsNullOrWhiteSpace(query.HasNoAudioTrackWithLanguage))
  3506. {
  3507. whereClauses.Add("((select language from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Audio' and MediaStreams.Language=@HasNoAudioTrackWithLanguage limit 1) is null)");
  3508. if (statement is not null)
  3509. {
  3510. statement.TryBind("@HasNoAudioTrackWithLanguage", query.HasNoAudioTrackWithLanguage);
  3511. }
  3512. }
  3513. if (!string.IsNullOrWhiteSpace(query.HasNoInternalSubtitleTrackWithLanguage))
  3514. {
  3515. whereClauses.Add("((select language from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Subtitle' and MediaStreams.IsExternal=0 and MediaStreams.Language=@HasNoInternalSubtitleTrackWithLanguage limit 1) is null)");
  3516. if (statement is not null)
  3517. {
  3518. statement.TryBind("@HasNoInternalSubtitleTrackWithLanguage", query.HasNoInternalSubtitleTrackWithLanguage);
  3519. }
  3520. }
  3521. if (!string.IsNullOrWhiteSpace(query.HasNoExternalSubtitleTrackWithLanguage))
  3522. {
  3523. whereClauses.Add("((select language from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Subtitle' and MediaStreams.IsExternal=1 and MediaStreams.Language=@HasNoExternalSubtitleTrackWithLanguage limit 1) is null)");
  3524. if (statement is not null)
  3525. {
  3526. statement.TryBind("@HasNoExternalSubtitleTrackWithLanguage", query.HasNoExternalSubtitleTrackWithLanguage);
  3527. }
  3528. }
  3529. if (!string.IsNullOrWhiteSpace(query.HasNoSubtitleTrackWithLanguage))
  3530. {
  3531. whereClauses.Add("((select language from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Subtitle' and MediaStreams.Language=@HasNoSubtitleTrackWithLanguage limit 1) is null)");
  3532. if (statement is not null)
  3533. {
  3534. statement.TryBind("@HasNoSubtitleTrackWithLanguage", query.HasNoSubtitleTrackWithLanguage);
  3535. }
  3536. }
  3537. if (query.HasSubtitles.HasValue)
  3538. {
  3539. if (query.HasSubtitles.Value)
  3540. {
  3541. whereClauses.Add("((select type from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Subtitle' limit 1) not null)");
  3542. }
  3543. else
  3544. {
  3545. whereClauses.Add("((select type from MediaStreams where MediaStreams.ItemId=A.Guid and MediaStreams.StreamType='Subtitle' limit 1) is null)");
  3546. }
  3547. }
  3548. if (query.HasChapterImages.HasValue)
  3549. {
  3550. if (query.HasChapterImages.Value)
  3551. {
  3552. whereClauses.Add("((select imagepath from Chapters2 where Chapters2.ItemId=A.Guid and imagepath not null limit 1) not null)");
  3553. }
  3554. else
  3555. {
  3556. whereClauses.Add("((select imagepath from Chapters2 where Chapters2.ItemId=A.Guid and imagepath not null limit 1) is null)");
  3557. }
  3558. }
  3559. if (query.HasDeadParentId.HasValue && query.HasDeadParentId.Value)
  3560. {
  3561. whereClauses.Add("ParentId NOT NULL AND ParentId NOT IN (select guid from TypedBaseItems)");
  3562. }
  3563. if (query.IsDeadArtist.HasValue && query.IsDeadArtist.Value)
  3564. {
  3565. whereClauses.Add("CleanName not in (Select CleanValue From ItemValues where Type in (0,1))");
  3566. }
  3567. if (query.IsDeadStudio.HasValue && query.IsDeadStudio.Value)
  3568. {
  3569. whereClauses.Add("CleanName not in (Select CleanValue From ItemValues where Type = 3)");
  3570. }
  3571. if (query.IsDeadPerson.HasValue && query.IsDeadPerson.Value)
  3572. {
  3573. whereClauses.Add("Name not in (Select Name From People)");
  3574. }
  3575. if (query.Years.Length == 1)
  3576. {
  3577. whereClauses.Add("ProductionYear=@Years");
  3578. if (statement is not null)
  3579. {
  3580. statement.TryBind("@Years", query.Years[0].ToString(CultureInfo.InvariantCulture));
  3581. }
  3582. }
  3583. else if (query.Years.Length > 1)
  3584. {
  3585. var val = string.Join(',', query.Years);
  3586. whereClauses.Add("ProductionYear in (" + val + ")");
  3587. }
  3588. var isVirtualItem = query.IsVirtualItem ?? query.IsMissing;
  3589. if (isVirtualItem.HasValue)
  3590. {
  3591. whereClauses.Add("IsVirtualItem=@IsVirtualItem");
  3592. if (statement is not null)
  3593. {
  3594. statement.TryBind("@IsVirtualItem", isVirtualItem.Value);
  3595. }
  3596. }
  3597. if (query.IsSpecialSeason.HasValue)
  3598. {
  3599. if (query.IsSpecialSeason.Value)
  3600. {
  3601. whereClauses.Add("IndexNumber = 0");
  3602. }
  3603. else
  3604. {
  3605. whereClauses.Add("IndexNumber <> 0");
  3606. }
  3607. }
  3608. if (query.IsUnaired.HasValue)
  3609. {
  3610. if (query.IsUnaired.Value)
  3611. {
  3612. whereClauses.Add("PremiereDate >= DATETIME('now')");
  3613. }
  3614. else
  3615. {
  3616. whereClauses.Add("PremiereDate < DATETIME('now')");
  3617. }
  3618. }
  3619. var queryMediaTypes = query.MediaTypes.Where(IsValidMediaType).ToArray();
  3620. if (queryMediaTypes.Length == 1)
  3621. {
  3622. whereClauses.Add("MediaType=@MediaTypes");
  3623. if (statement is not null)
  3624. {
  3625. statement.TryBind("@MediaTypes", queryMediaTypes[0]);
  3626. }
  3627. }
  3628. else if (queryMediaTypes.Length > 1)
  3629. {
  3630. var val = string.Join(',', queryMediaTypes.Select(i => "'" + i + "'"));
  3631. whereClauses.Add("MediaType in (" + val + ")");
  3632. }
  3633. if (query.ItemIds.Length > 0)
  3634. {
  3635. var includeIds = new List<string>();
  3636. var index = 0;
  3637. foreach (var id in query.ItemIds)
  3638. {
  3639. includeIds.Add("Guid = @IncludeId" + index);
  3640. if (statement is not null)
  3641. {
  3642. statement.TryBind("@IncludeId" + index, id);
  3643. }
  3644. index++;
  3645. }
  3646. whereClauses.Add("(" + string.Join(" OR ", includeIds) + ")");
  3647. }
  3648. if (query.ExcludeItemIds.Length > 0)
  3649. {
  3650. var excludeIds = new List<string>();
  3651. var index = 0;
  3652. foreach (var id in query.ExcludeItemIds)
  3653. {
  3654. excludeIds.Add("Guid <> @ExcludeId" + index);
  3655. if (statement is not null)
  3656. {
  3657. statement.TryBind("@ExcludeId" + index, id);
  3658. }
  3659. index++;
  3660. }
  3661. whereClauses.Add(string.Join(" AND ", excludeIds));
  3662. }
  3663. if (query.ExcludeProviderIds is not null && query.ExcludeProviderIds.Count > 0)
  3664. {
  3665. var excludeIds = new List<string>();
  3666. var index = 0;
  3667. foreach (var pair in query.ExcludeProviderIds)
  3668. {
  3669. if (string.Equals(pair.Key, nameof(MetadataProvider.TmdbCollection), StringComparison.OrdinalIgnoreCase))
  3670. {
  3671. continue;
  3672. }
  3673. var paramName = "@ExcludeProviderId" + index;
  3674. excludeIds.Add("(ProviderIds is null or ProviderIds not like " + paramName + ")");
  3675. if (statement is not null)
  3676. {
  3677. statement.TryBind(paramName, "%" + pair.Key + "=" + pair.Value + "%");
  3678. }
  3679. index++;
  3680. break;
  3681. }
  3682. if (excludeIds.Count > 0)
  3683. {
  3684. whereClauses.Add(string.Join(" AND ", excludeIds));
  3685. }
  3686. }
  3687. if (query.HasAnyProviderId is not null && query.HasAnyProviderId.Count > 0)
  3688. {
  3689. var hasProviderIds = new List<string>();
  3690. var index = 0;
  3691. foreach (var pair in query.HasAnyProviderId)
  3692. {
  3693. if (string.Equals(pair.Key, nameof(MetadataProvider.TmdbCollection), StringComparison.OrdinalIgnoreCase))
  3694. {
  3695. continue;
  3696. }
  3697. // TODO this seems to be an idea for a better schema where ProviderIds are their own table
  3698. // buut this is not implemented
  3699. // hasProviderIds.Add("(COALESCE((select value from ProviderIds where ItemId=Guid and Name = '" + pair.Key + "'), '') <> " + paramName + ")");
  3700. // TODO this is a really BAD way to do it since the pair:
  3701. // Tmdb, 1234 matches Tmdb=1234 but also Tmdb=1234567
  3702. // and maybe even NotTmdb=1234.
  3703. // this is a placeholder for this specific pair to correlate it in the bigger query
  3704. var paramName = "@HasAnyProviderId" + index;
  3705. // this is a search for the placeholder
  3706. hasProviderIds.Add("ProviderIds like " + paramName);
  3707. // this replaces the placeholder with a value, here: %key=val%
  3708. if (statement is not null)
  3709. {
  3710. statement.TryBind(paramName, "%" + pair.Key + "=" + pair.Value + "%");
  3711. }
  3712. index++;
  3713. break;
  3714. }
  3715. if (hasProviderIds.Count > 0)
  3716. {
  3717. whereClauses.Add("(" + string.Join(" OR ", hasProviderIds) + ")");
  3718. }
  3719. }
  3720. if (query.HasImdbId.HasValue)
  3721. {
  3722. whereClauses.Add(GetProviderIdClause(query.HasImdbId.Value, "imdb"));
  3723. }
  3724. if (query.HasTmdbId.HasValue)
  3725. {
  3726. whereClauses.Add(GetProviderIdClause(query.HasTmdbId.Value, "tmdb"));
  3727. }
  3728. if (query.HasTvdbId.HasValue)
  3729. {
  3730. whereClauses.Add(GetProviderIdClause(query.HasTvdbId.Value, "tvdb"));
  3731. }
  3732. var queryTopParentIds = query.TopParentIds;
  3733. if (queryTopParentIds.Length > 0)
  3734. {
  3735. var includedItemByNameTypes = GetItemByNameTypesInQuery(query);
  3736. var enableItemsByName = (query.IncludeItemsByName ?? false) && includedItemByNameTypes.Count > 0;
  3737. if (queryTopParentIds.Length == 1)
  3738. {
  3739. if (enableItemsByName && includedItemByNameTypes.Count == 1)
  3740. {
  3741. whereClauses.Add("(TopParentId=@TopParentId or Type=@IncludedItemByNameType)");
  3742. statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
  3743. }
  3744. else if (enableItemsByName && includedItemByNameTypes.Count > 1)
  3745. {
  3746. var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
  3747. whereClauses.Add("(TopParentId=@TopParentId or Type in (" + itemByNameTypeVal + "))");
  3748. }
  3749. else
  3750. {
  3751. whereClauses.Add("(TopParentId=@TopParentId)");
  3752. }
  3753. statement?.TryBind("@TopParentId", queryTopParentIds[0].ToString("N", CultureInfo.InvariantCulture));
  3754. }
  3755. else if (queryTopParentIds.Length > 1)
  3756. {
  3757. var val = string.Join(',', queryTopParentIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
  3758. if (enableItemsByName && includedItemByNameTypes.Count == 1)
  3759. {
  3760. whereClauses.Add("(Type=@IncludedItemByNameType or TopParentId in (" + val + "))");
  3761. statement?.TryBind("@IncludedItemByNameType", includedItemByNameTypes[0]);
  3762. }
  3763. else if (enableItemsByName && includedItemByNameTypes.Count > 1)
  3764. {
  3765. var itemByNameTypeVal = string.Join(',', includedItemByNameTypes.Select(i => "'" + i + "'"));
  3766. whereClauses.Add("(Type in (" + itemByNameTypeVal + ") or TopParentId in (" + val + "))");
  3767. }
  3768. else
  3769. {
  3770. whereClauses.Add("TopParentId in (" + val + ")");
  3771. }
  3772. }
  3773. }
  3774. if (query.AncestorIds.Length == 1)
  3775. {
  3776. whereClauses.Add("Guid in (select itemId from AncestorIds where AncestorId=@AncestorId)");
  3777. if (statement is not null)
  3778. {
  3779. statement.TryBind("@AncestorId", query.AncestorIds[0]);
  3780. }
  3781. }
  3782. if (query.AncestorIds.Length > 1)
  3783. {
  3784. var inClause = string.Join(',', query.AncestorIds.Select(i => "'" + i.ToString("N", CultureInfo.InvariantCulture) + "'"));
  3785. whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause));
  3786. }
  3787. if (!string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey))
  3788. {
  3789. var inClause = "select guid from TypedBaseItems where PresentationUniqueKey=@AncestorWithPresentationUniqueKey";
  3790. whereClauses.Add(string.Format(CultureInfo.InvariantCulture, "Guid in (select itemId from AncestorIds where AncestorId in ({0}))", inClause));
  3791. if (statement is not null)
  3792. {
  3793. statement.TryBind("@AncestorWithPresentationUniqueKey", query.AncestorWithPresentationUniqueKey);
  3794. }
  3795. }
  3796. if (!string.IsNullOrWhiteSpace(query.SeriesPresentationUniqueKey))
  3797. {
  3798. whereClauses.Add("SeriesPresentationUniqueKey=@SeriesPresentationUniqueKey");
  3799. if (statement is not null)
  3800. {
  3801. statement.TryBind("@SeriesPresentationUniqueKey", query.SeriesPresentationUniqueKey);
  3802. }
  3803. }
  3804. if (query.BlockUnratedItems.Length == 1)
  3805. {
  3806. whereClauses.Add("(InheritedParentalRatingValue > 0 or UnratedType <> @UnratedType)");
  3807. if (statement is not null)
  3808. {
  3809. statement.TryBind("@UnratedType", query.BlockUnratedItems[0].ToString());
  3810. }
  3811. }
  3812. if (query.BlockUnratedItems.Length > 1)
  3813. {
  3814. var inClause = string.Join(',', query.BlockUnratedItems.Select(i => "'" + i.ToString() + "'"));
  3815. whereClauses.Add(
  3816. string.Format(
  3817. CultureInfo.InvariantCulture,
  3818. "(InheritedParentalRatingValue > 0 or UnratedType not in ({0}))",
  3819. inClause));
  3820. }
  3821. if (query.ExcludeInheritedTags.Length > 0)
  3822. {
  3823. var paramName = "@ExcludeInheritedTags";
  3824. if (statement is null)
  3825. {
  3826. int index = 0;
  3827. string excludedTags = string.Join(',', query.ExcludeInheritedTags.Select(_ => paramName + index++));
  3828. whereClauses.Add("((select CleanValue from ItemValues where ItemId=Guid and Type=6 and cleanvalue in (" + excludedTags + ")) is null)");
  3829. }
  3830. else
  3831. {
  3832. for (int index = 0; index < query.ExcludeInheritedTags.Length; index++)
  3833. {
  3834. statement.TryBind(paramName + index, GetCleanValue(query.ExcludeInheritedTags[index]));
  3835. }
  3836. }
  3837. }
  3838. if (query.SeriesStatuses.Length > 0)
  3839. {
  3840. var statuses = new List<string>();
  3841. foreach (var seriesStatus in query.SeriesStatuses)
  3842. {
  3843. statuses.Add("data like '%" + seriesStatus + "%'");
  3844. }
  3845. whereClauses.Add("(" + string.Join(" OR ", statuses) + ")");
  3846. }
  3847. if (query.BoxSetLibraryFolders.Length > 0)
  3848. {
  3849. var folderIdQueries = new List<string>();
  3850. foreach (var folderId in query.BoxSetLibraryFolders)
  3851. {
  3852. folderIdQueries.Add("data like '%" + folderId.ToString("N", CultureInfo.InvariantCulture) + "%'");
  3853. }
  3854. whereClauses.Add("(" + string.Join(" OR ", folderIdQueries) + ")");
  3855. }
  3856. if (query.VideoTypes.Length > 0)
  3857. {
  3858. var videoTypes = new List<string>();
  3859. foreach (var videoType in query.VideoTypes)
  3860. {
  3861. videoTypes.Add("data like '%\"VideoType\":\"" + videoType.ToString() + "\"%'");
  3862. }
  3863. whereClauses.Add("(" + string.Join(" OR ", videoTypes) + ")");
  3864. }
  3865. if (query.Is3D.HasValue)
  3866. {
  3867. if (query.Is3D.Value)
  3868. {
  3869. whereClauses.Add("data like '%Video3DFormat%'");
  3870. }
  3871. else
  3872. {
  3873. whereClauses.Add("data not like '%Video3DFormat%'");
  3874. }
  3875. }
  3876. if (query.IsPlaceHolder.HasValue)
  3877. {
  3878. if (query.IsPlaceHolder.Value)
  3879. {
  3880. whereClauses.Add("data like '%\"IsPlaceHolder\":true%'");
  3881. }
  3882. else
  3883. {
  3884. whereClauses.Add("(data is null or data not like '%\"IsPlaceHolder\":true%')");
  3885. }
  3886. }
  3887. if (query.HasSpecialFeature.HasValue)
  3888. {
  3889. if (query.HasSpecialFeature.Value)
  3890. {
  3891. whereClauses.Add("ExtraIds not null");
  3892. }
  3893. else
  3894. {
  3895. whereClauses.Add("ExtraIds is null");
  3896. }
  3897. }
  3898. if (query.HasTrailer.HasValue)
  3899. {
  3900. if (query.HasTrailer.Value)
  3901. {
  3902. whereClauses.Add("ExtraIds not null");
  3903. }
  3904. else
  3905. {
  3906. whereClauses.Add("ExtraIds is null");
  3907. }
  3908. }
  3909. if (query.HasThemeSong.HasValue)
  3910. {
  3911. if (query.HasThemeSong.Value)
  3912. {
  3913. whereClauses.Add("ExtraIds not null");
  3914. }
  3915. else
  3916. {
  3917. whereClauses.Add("ExtraIds is null");
  3918. }
  3919. }
  3920. if (query.HasThemeVideo.HasValue)
  3921. {
  3922. if (query.HasThemeVideo.Value)
  3923. {
  3924. whereClauses.Add("ExtraIds not null");
  3925. }
  3926. else
  3927. {
  3928. whereClauses.Add("ExtraIds is null");
  3929. }
  3930. }
  3931. return whereClauses;
  3932. }
  3933. /// <summary>
  3934. /// Formats a where clause for the specified provider.
  3935. /// </summary>
  3936. /// <param name="includeResults">Whether or not to include items with this provider's ids.</param>
  3937. /// <param name="provider">Provider name.</param>
  3938. /// <returns>Formatted SQL clause.</returns>
  3939. private string GetProviderIdClause(bool includeResults, string provider)
  3940. {
  3941. return string.Format(
  3942. CultureInfo.InvariantCulture,
  3943. "ProviderIds {0} like '%{1}=%'",
  3944. includeResults ? string.Empty : "not",
  3945. provider);
  3946. }
  3947. private List<string> GetItemByNameTypesInQuery(InternalItemsQuery query)
  3948. {
  3949. var list = new List<string>();
  3950. if (IsTypeInQuery(BaseItemKind.Person, query))
  3951. {
  3952. list.Add(typeof(Person).FullName);
  3953. }
  3954. if (IsTypeInQuery(BaseItemKind.Genre, query))
  3955. {
  3956. list.Add(typeof(Genre).FullName);
  3957. }
  3958. if (IsTypeInQuery(BaseItemKind.MusicGenre, query))
  3959. {
  3960. list.Add(typeof(MusicGenre).FullName);
  3961. }
  3962. if (IsTypeInQuery(BaseItemKind.MusicArtist, query))
  3963. {
  3964. list.Add(typeof(MusicArtist).FullName);
  3965. }
  3966. if (IsTypeInQuery(BaseItemKind.Studio, query))
  3967. {
  3968. list.Add(typeof(Studio).FullName);
  3969. }
  3970. return list;
  3971. }
  3972. private bool IsTypeInQuery(BaseItemKind type, InternalItemsQuery query)
  3973. {
  3974. if (query.ExcludeItemTypes.Contains(type))
  3975. {
  3976. return false;
  3977. }
  3978. return query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains(type);
  3979. }
  3980. private string GetCleanValue(string value)
  3981. {
  3982. if (string.IsNullOrWhiteSpace(value))
  3983. {
  3984. return value;
  3985. }
  3986. return value.RemoveDiacritics().ToLowerInvariant();
  3987. }
  3988. private bool EnableGroupByPresentationUniqueKey(InternalItemsQuery query)
  3989. {
  3990. if (!query.GroupByPresentationUniqueKey)
  3991. {
  3992. return false;
  3993. }
  3994. if (query.GroupBySeriesPresentationUniqueKey)
  3995. {
  3996. return false;
  3997. }
  3998. if (!string.IsNullOrWhiteSpace(query.PresentationUniqueKey))
  3999. {
  4000. return false;
  4001. }
  4002. if (query.User is null)
  4003. {
  4004. return false;
  4005. }
  4006. if (query.IncludeItemTypes.Length == 0)
  4007. {
  4008. return true;
  4009. }
  4010. if (query.IncludeItemTypes.Contains(BaseItemKind.Episode)
  4011. || query.IncludeItemTypes.Contains(BaseItemKind.Video)
  4012. || query.IncludeItemTypes.Contains(BaseItemKind.Movie)
  4013. || query.IncludeItemTypes.Contains(BaseItemKind.MusicVideo)
  4014. || query.IncludeItemTypes.Contains(BaseItemKind.Series)
  4015. || query.IncludeItemTypes.Contains(BaseItemKind.Season))
  4016. {
  4017. return true;
  4018. }
  4019. return false;
  4020. }
  4021. public void UpdateInheritedValues()
  4022. {
  4023. string sql = string.Join(
  4024. ';',
  4025. new string[]
  4026. {
  4027. "delete from ItemValues where type = 6",
  4028. "insert into ItemValues (ItemId, Type, Value, CleanValue) select ItemId, 6, Value, CleanValue from ItemValues where Type=4",
  4029. @"insert into ItemValues (ItemId, Type, Value, CleanValue) select AncestorIds.itemid, 6, ItemValues.Value, ItemValues.CleanValue
  4030. FROM AncestorIds
  4031. LEFT JOIN ItemValues ON (AncestorIds.AncestorId = ItemValues.ItemId)
  4032. where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type = 4 "
  4033. });
  4034. using (var connection = GetConnection())
  4035. {
  4036. connection.RunInTransaction(
  4037. db =>
  4038. {
  4039. connection.ExecuteAll(sql);
  4040. },
  4041. TransactionMode);
  4042. }
  4043. }
  4044. public void DeleteItem(Guid id)
  4045. {
  4046. if (id.Equals(default))
  4047. {
  4048. throw new ArgumentNullException(nameof(id));
  4049. }
  4050. CheckDisposed();
  4051. using (var connection = GetConnection())
  4052. {
  4053. connection.RunInTransaction(
  4054. db =>
  4055. {
  4056. Span<byte> idBlob = stackalloc byte[16];
  4057. id.TryWriteBytes(idBlob);
  4058. // Delete people
  4059. ExecuteWithSingleParam(db, "delete from People where ItemId=@Id", idBlob);
  4060. // Delete chapters
  4061. ExecuteWithSingleParam(db, "delete from " + ChaptersTableName + " where ItemId=@Id", idBlob);
  4062. // Delete media streams
  4063. ExecuteWithSingleParam(db, "delete from mediastreams where ItemId=@Id", idBlob);
  4064. // Delete ancestors
  4065. ExecuteWithSingleParam(db, "delete from AncestorIds where ItemId=@Id", idBlob);
  4066. // Delete item values
  4067. ExecuteWithSingleParam(db, "delete from ItemValues where ItemId=@Id", idBlob);
  4068. // Delete the item
  4069. ExecuteWithSingleParam(db, "delete from TypedBaseItems where guid=@Id", idBlob);
  4070. },
  4071. TransactionMode);
  4072. }
  4073. }
  4074. private void ExecuteWithSingleParam(IDatabaseConnection db, string query, ReadOnlySpan<byte> value)
  4075. {
  4076. using (var statement = PrepareStatement(db, query))
  4077. {
  4078. statement.TryBind("@Id", value);
  4079. statement.MoveNext();
  4080. }
  4081. }
  4082. public List<string> GetPeopleNames(InternalPeopleQuery query)
  4083. {
  4084. ArgumentNullException.ThrowIfNull(query);
  4085. CheckDisposed();
  4086. var commandText = new StringBuilder("select Distinct p.Name from People p");
  4087. var whereClauses = GetPeopleWhereClauses(query, null);
  4088. if (whereClauses.Count != 0)
  4089. {
  4090. commandText.Append(" where ").AppendJoin(" AND ", whereClauses);
  4091. }
  4092. commandText.Append(" order by ListOrder");
  4093. if (query.Limit > 0)
  4094. {
  4095. commandText.Append(" LIMIT ").Append(query.Limit);
  4096. }
  4097. using (var connection = GetConnection(true))
  4098. {
  4099. var list = new List<string>();
  4100. using (var statement = PrepareStatement(connection, commandText.ToString()))
  4101. {
  4102. // Run this again to bind the params
  4103. GetPeopleWhereClauses(query, statement);
  4104. foreach (var row in statement.ExecuteQuery())
  4105. {
  4106. list.Add(row.GetString(0));
  4107. }
  4108. }
  4109. return list;
  4110. }
  4111. }
  4112. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  4113. {
  4114. ArgumentNullException.ThrowIfNull(query);
  4115. CheckDisposed();
  4116. var commandText = "select ItemId, Name, Role, PersonType, SortOrder from People p";
  4117. var whereClauses = GetPeopleWhereClauses(query, null);
  4118. if (whereClauses.Count != 0)
  4119. {
  4120. commandText += " where " + string.Join(" AND ", whereClauses);
  4121. }
  4122. commandText += " order by ListOrder";
  4123. if (query.Limit > 0)
  4124. {
  4125. commandText += " LIMIT " + query.Limit;
  4126. }
  4127. using (var connection = GetConnection(true))
  4128. {
  4129. var list = new List<PersonInfo>();
  4130. using (var statement = PrepareStatement(connection, commandText))
  4131. {
  4132. // Run this again to bind the params
  4133. GetPeopleWhereClauses(query, statement);
  4134. foreach (var row in statement.ExecuteQuery())
  4135. {
  4136. list.Add(GetPerson(row));
  4137. }
  4138. }
  4139. return list;
  4140. }
  4141. }
  4142. private List<string> GetPeopleWhereClauses(InternalPeopleQuery query, IStatement statement)
  4143. {
  4144. var whereClauses = new List<string>();
  4145. if (query.User is not null && query.IsFavorite.HasValue)
  4146. {
  4147. whereClauses.Add(@"p.Name IN (
  4148. SELECT Name FROM TypedBaseItems WHERE UserDataKey IN (
  4149. SELECT key FROM UserDatas WHERE isFavorite=@IsFavorite AND userId=@UserId)
  4150. AND Type = @InternalPersonType)");
  4151. statement?.TryBind("@IsFavorite", query.IsFavorite.Value);
  4152. statement?.TryBind("@InternalPersonType", typeof(Person).FullName);
  4153. statement?.TryBind("@UserId", query.User.InternalId);
  4154. }
  4155. if (!query.ItemId.Equals(default))
  4156. {
  4157. whereClauses.Add("ItemId=@ItemId");
  4158. statement?.TryBind("@ItemId", query.ItemId);
  4159. }
  4160. if (!query.AppearsInItemId.Equals(default))
  4161. {
  4162. whereClauses.Add("p.Name in (Select Name from People where ItemId=@AppearsInItemId)");
  4163. statement?.TryBind("@AppearsInItemId", query.AppearsInItemId);
  4164. }
  4165. var queryPersonTypes = query.PersonTypes.Where(IsValidPersonType).ToList();
  4166. if (queryPersonTypes.Count == 1)
  4167. {
  4168. whereClauses.Add("PersonType=@PersonType");
  4169. statement?.TryBind("@PersonType", queryPersonTypes[0]);
  4170. }
  4171. else if (queryPersonTypes.Count > 1)
  4172. {
  4173. var val = string.Join(',', queryPersonTypes.Select(i => "'" + i + "'"));
  4174. whereClauses.Add("PersonType in (" + val + ")");
  4175. }
  4176. var queryExcludePersonTypes = query.ExcludePersonTypes.Where(IsValidPersonType).ToList();
  4177. if (queryExcludePersonTypes.Count == 1)
  4178. {
  4179. whereClauses.Add("PersonType<>@PersonType");
  4180. statement?.TryBind("@PersonType", queryExcludePersonTypes[0]);
  4181. }
  4182. else if (queryExcludePersonTypes.Count > 1)
  4183. {
  4184. var val = string.Join(',', queryExcludePersonTypes.Select(i => "'" + i + "'"));
  4185. whereClauses.Add("PersonType not in (" + val + ")");
  4186. }
  4187. if (query.MaxListOrder.HasValue)
  4188. {
  4189. whereClauses.Add("ListOrder<=@MaxListOrder");
  4190. statement?.TryBind("@MaxListOrder", query.MaxListOrder.Value);
  4191. }
  4192. if (!string.IsNullOrWhiteSpace(query.NameContains))
  4193. {
  4194. whereClauses.Add("p.Name like @NameContains");
  4195. statement?.TryBind("@NameContains", "%" + query.NameContains + "%");
  4196. }
  4197. return whereClauses;
  4198. }
  4199. private void UpdateAncestors(Guid itemId, List<Guid> ancestorIds, IDatabaseConnection db, IStatement deleteAncestorsStatement)
  4200. {
  4201. if (itemId.Equals(default))
  4202. {
  4203. throw new ArgumentNullException(nameof(itemId));
  4204. }
  4205. ArgumentNullException.ThrowIfNull(ancestorIds);
  4206. CheckDisposed();
  4207. Span<byte> itemIdBlob = stackalloc byte[16];
  4208. itemId.TryWriteBytes(itemIdBlob);
  4209. // First delete
  4210. deleteAncestorsStatement.Reset();
  4211. deleteAncestorsStatement.TryBind("@ItemId", itemIdBlob);
  4212. deleteAncestorsStatement.MoveNext();
  4213. if (ancestorIds.Count == 0)
  4214. {
  4215. return;
  4216. }
  4217. var insertText = new StringBuilder("insert into AncestorIds (ItemId, AncestorId, AncestorIdText) values ");
  4218. for (var i = 0; i < ancestorIds.Count; i++)
  4219. {
  4220. insertText.AppendFormat(
  4221. CultureInfo.InvariantCulture,
  4222. "(@ItemId, @AncestorId{0}, @AncestorIdText{0}),",
  4223. i.ToString(CultureInfo.InvariantCulture));
  4224. }
  4225. // Remove last ,
  4226. insertText.Length--;
  4227. using (var statement = PrepareStatement(db, insertText.ToString()))
  4228. {
  4229. statement.TryBind("@ItemId", itemIdBlob);
  4230. for (var i = 0; i < ancestorIds.Count; i++)
  4231. {
  4232. var index = i.ToString(CultureInfo.InvariantCulture);
  4233. var ancestorId = ancestorIds[i];
  4234. ancestorId.TryWriteBytes(itemIdBlob);
  4235. statement.TryBind("@AncestorId" + index, itemIdBlob);
  4236. statement.TryBind("@AncestorIdText" + index, ancestorId.ToString("N", CultureInfo.InvariantCulture));
  4237. }
  4238. statement.Reset();
  4239. statement.MoveNext();
  4240. }
  4241. }
  4242. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
  4243. {
  4244. return GetItemValues(query, new[] { 0, 1 }, typeof(MusicArtist).FullName);
  4245. }
  4246. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
  4247. {
  4248. return GetItemValues(query, new[] { 0 }, typeof(MusicArtist).FullName);
  4249. }
  4250. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
  4251. {
  4252. return GetItemValues(query, new[] { 1 }, typeof(MusicArtist).FullName);
  4253. }
  4254. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
  4255. {
  4256. return GetItemValues(query, new[] { 3 }, typeof(Studio).FullName);
  4257. }
  4258. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
  4259. {
  4260. return GetItemValues(query, new[] { 2 }, typeof(Genre).FullName);
  4261. }
  4262. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
  4263. {
  4264. return GetItemValues(query, new[] { 2 }, typeof(MusicGenre).FullName);
  4265. }
  4266. public List<string> GetStudioNames()
  4267. {
  4268. return GetItemValueNames(new[] { 3 }, Array.Empty<string>(), Array.Empty<string>());
  4269. }
  4270. public List<string> GetAllArtistNames()
  4271. {
  4272. return GetItemValueNames(new[] { 0, 1 }, Array.Empty<string>(), Array.Empty<string>());
  4273. }
  4274. public List<string> GetMusicGenreNames()
  4275. {
  4276. return GetItemValueNames(
  4277. new[] { 2 },
  4278. new string[]
  4279. {
  4280. typeof(Audio).FullName,
  4281. typeof(MusicVideo).FullName,
  4282. typeof(MusicAlbum).FullName,
  4283. typeof(MusicArtist).FullName
  4284. },
  4285. Array.Empty<string>());
  4286. }
  4287. public List<string> GetGenreNames()
  4288. {
  4289. return GetItemValueNames(
  4290. new[] { 2 },
  4291. Array.Empty<string>(),
  4292. new string[]
  4293. {
  4294. typeof(Audio).FullName,
  4295. typeof(MusicVideo).FullName,
  4296. typeof(MusicAlbum).FullName,
  4297. typeof(MusicArtist).FullName
  4298. });
  4299. }
  4300. private List<string> GetItemValueNames(int[] itemValueTypes, IReadOnlyList<string> withItemTypes, IReadOnlyList<string> excludeItemTypes)
  4301. {
  4302. CheckDisposed();
  4303. var now = DateTime.UtcNow;
  4304. var stringBuilder = new StringBuilder("Select Value From ItemValues where Type", 128);
  4305. if (itemValueTypes.Length == 1)
  4306. {
  4307. stringBuilder.Append('=')
  4308. .Append(itemValueTypes[0]);
  4309. }
  4310. else
  4311. {
  4312. stringBuilder.Append(" in (")
  4313. .AppendJoin(',', itemValueTypes)
  4314. .Append(')');
  4315. }
  4316. if (withItemTypes.Count > 0)
  4317. {
  4318. stringBuilder.Append(" AND ItemId In (select guid from typedbaseitems where type in (")
  4319. .AppendJoinInSingleQuotes(',', withItemTypes)
  4320. .Append("))");
  4321. }
  4322. if (excludeItemTypes.Count > 0)
  4323. {
  4324. stringBuilder.Append(" AND ItemId not In (select guid from typedbaseitems where type in (")
  4325. .AppendJoinInSingleQuotes(',', excludeItemTypes)
  4326. .Append("))");
  4327. }
  4328. stringBuilder.Append(" Group By CleanValue");
  4329. var commandText = stringBuilder.ToString();
  4330. var list = new List<string>();
  4331. using (var connection = GetConnection(true))
  4332. using (var statement = PrepareStatement(connection, commandText))
  4333. {
  4334. foreach (var row in statement.ExecuteQuery())
  4335. {
  4336. if (row.TryGetString(0, out var result))
  4337. {
  4338. list.Add(result);
  4339. }
  4340. }
  4341. }
  4342. LogQueryTime("GetItemValueNames", commandText, now);
  4343. return list;
  4344. }
  4345. private QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetItemValues(InternalItemsQuery query, int[] itemValueTypes, string returnType)
  4346. {
  4347. ArgumentNullException.ThrowIfNull(query);
  4348. if (!query.Limit.HasValue)
  4349. {
  4350. query.EnableTotalRecordCount = false;
  4351. }
  4352. CheckDisposed();
  4353. var now = DateTime.UtcNow;
  4354. var typeClause = itemValueTypes.Length == 1 ?
  4355. ("Type=" + itemValueTypes[0]) :
  4356. ("Type in (" + string.Join(',', itemValueTypes) + ")");
  4357. InternalItemsQuery typeSubQuery = null;
  4358. string itemCountColumns = null;
  4359. var stringBuilder = new StringBuilder(1024);
  4360. var typesToCount = query.IncludeItemTypes;
  4361. if (typesToCount.Length > 0)
  4362. {
  4363. stringBuilder.Append("(select group_concat(type, '|') from TypedBaseItems B");
  4364. typeSubQuery = new InternalItemsQuery(query.User)
  4365. {
  4366. ExcludeItemTypes = query.ExcludeItemTypes,
  4367. IncludeItemTypes = query.IncludeItemTypes,
  4368. MediaTypes = query.MediaTypes,
  4369. AncestorIds = query.AncestorIds,
  4370. ExcludeItemIds = query.ExcludeItemIds,
  4371. ItemIds = query.ItemIds,
  4372. TopParentIds = query.TopParentIds,
  4373. ParentId = query.ParentId,
  4374. IsPlayed = query.IsPlayed
  4375. };
  4376. var whereClauses = GetWhereClauses(typeSubQuery, null);
  4377. stringBuilder.Append(" where ")
  4378. .AppendJoin(" AND ", whereClauses)
  4379. .Append(" AND ")
  4380. .Append("guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND ")
  4381. .Append(typeClause)
  4382. .Append(")) as itemTypes");
  4383. itemCountColumns = stringBuilder.ToString();
  4384. stringBuilder.Clear();
  4385. }
  4386. List<string> columns = _retrieveItemColumns.ToList();
  4387. // Unfortunately we need to add it to columns to ensure the order of the columns in the select
  4388. if (!string.IsNullOrEmpty(itemCountColumns))
  4389. {
  4390. columns.Add(itemCountColumns);
  4391. }
  4392. // do this first before calling GetFinalColumnsToSelect, otherwise ExcludeItemIds will be set by SimilarTo
  4393. var innerQuery = new InternalItemsQuery(query.User)
  4394. {
  4395. ExcludeItemTypes = query.ExcludeItemTypes,
  4396. IncludeItemTypes = query.IncludeItemTypes,
  4397. MediaTypes = query.MediaTypes,
  4398. AncestorIds = query.AncestorIds,
  4399. ItemIds = query.ItemIds,
  4400. TopParentIds = query.TopParentIds,
  4401. ParentId = query.ParentId,
  4402. IsAiring = query.IsAiring,
  4403. IsMovie = query.IsMovie,
  4404. IsSports = query.IsSports,
  4405. IsKids = query.IsKids,
  4406. IsNews = query.IsNews,
  4407. IsSeries = query.IsSeries
  4408. };
  4409. SetFinalColumnsToSelect(query, columns);
  4410. var innerWhereClauses = GetWhereClauses(innerQuery, null);
  4411. stringBuilder.Append(" where Type=@SelectType And CleanName In (Select CleanValue from ItemValues where ")
  4412. .Append(typeClause)
  4413. .Append(" AND ItemId in (select guid from TypedBaseItems");
  4414. if (innerWhereClauses.Count > 0)
  4415. {
  4416. stringBuilder.Append(" where ")
  4417. .AppendJoin(" AND ", innerWhereClauses);
  4418. }
  4419. stringBuilder.Append("))");
  4420. var outerQuery = new InternalItemsQuery(query.User)
  4421. {
  4422. IsPlayed = query.IsPlayed,
  4423. IsFavorite = query.IsFavorite,
  4424. IsFavoriteOrLiked = query.IsFavoriteOrLiked,
  4425. IsLiked = query.IsLiked,
  4426. IsLocked = query.IsLocked,
  4427. NameLessThan = query.NameLessThan,
  4428. NameStartsWith = query.NameStartsWith,
  4429. NameStartsWithOrGreater = query.NameStartsWithOrGreater,
  4430. Tags = query.Tags,
  4431. OfficialRatings = query.OfficialRatings,
  4432. StudioIds = query.StudioIds,
  4433. GenreIds = query.GenreIds,
  4434. Genres = query.Genres,
  4435. Years = query.Years,
  4436. NameContains = query.NameContains,
  4437. SearchTerm = query.SearchTerm,
  4438. SimilarTo = query.SimilarTo,
  4439. ExcludeItemIds = query.ExcludeItemIds
  4440. };
  4441. var outerWhereClauses = GetWhereClauses(outerQuery, null);
  4442. if (outerWhereClauses.Count != 0)
  4443. {
  4444. stringBuilder.Append(" AND ")
  4445. .AppendJoin(" AND ", outerWhereClauses);
  4446. }
  4447. var whereText = stringBuilder.ToString();
  4448. stringBuilder.Clear();
  4449. stringBuilder.Append("select ")
  4450. .AppendJoin(',', columns)
  4451. .Append(FromText)
  4452. .Append(GetJoinUserDataText(query))
  4453. .Append(whereText)
  4454. .Append(" group by PresentationUniqueKey");
  4455. if (query.OrderBy.Count != 0
  4456. || query.SimilarTo is not null
  4457. || !string.IsNullOrEmpty(query.SearchTerm))
  4458. {
  4459. stringBuilder.Append(GetOrderByText(query));
  4460. }
  4461. else
  4462. {
  4463. stringBuilder.Append(" order by SortName");
  4464. }
  4465. if (query.Limit.HasValue || query.StartIndex.HasValue)
  4466. {
  4467. var offset = query.StartIndex ?? 0;
  4468. if (query.Limit.HasValue || offset > 0)
  4469. {
  4470. stringBuilder.Append(" LIMIT ")
  4471. .Append(query.Limit ?? int.MaxValue);
  4472. }
  4473. if (offset > 0)
  4474. {
  4475. stringBuilder.Append(" OFFSET ")
  4476. .Append(offset);
  4477. }
  4478. }
  4479. var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0;
  4480. string commandText = string.Empty;
  4481. if (!isReturningZeroItems)
  4482. {
  4483. commandText = stringBuilder.ToString();
  4484. }
  4485. string countText = string.Empty;
  4486. if (query.EnableTotalRecordCount)
  4487. {
  4488. stringBuilder.Clear();
  4489. var columnsToSelect = new List<string> { "count (distinct PresentationUniqueKey)" };
  4490. SetFinalColumnsToSelect(query, columnsToSelect);
  4491. stringBuilder.Append("select ")
  4492. .AppendJoin(',', columnsToSelect)
  4493. .Append(FromText)
  4494. .Append(GetJoinUserDataText(query))
  4495. .Append(whereText);
  4496. countText = stringBuilder.ToString();
  4497. }
  4498. var list = new List<(BaseItem, ItemCounts)>();
  4499. var result = new QueryResult<(BaseItem, ItemCounts)>();
  4500. using (var connection = GetConnection(true))
  4501. {
  4502. connection.RunInTransaction(
  4503. db =>
  4504. {
  4505. if (!isReturningZeroItems)
  4506. {
  4507. using (var statement = PrepareStatement(db, commandText))
  4508. {
  4509. statement.TryBind("@SelectType", returnType);
  4510. if (EnableJoinUserData(query))
  4511. {
  4512. statement.TryBind("@UserId", query.User.InternalId);
  4513. }
  4514. if (typeSubQuery is not null)
  4515. {
  4516. GetWhereClauses(typeSubQuery, null);
  4517. }
  4518. BindSimilarParams(query, statement);
  4519. BindSearchParams(query, statement);
  4520. GetWhereClauses(innerQuery, statement);
  4521. GetWhereClauses(outerQuery, statement);
  4522. var hasEpisodeAttributes = HasEpisodeAttributes(query);
  4523. var hasProgramAttributes = HasProgramAttributes(query);
  4524. var hasServiceName = HasServiceName(query);
  4525. var hasStartDate = HasStartDate(query);
  4526. var hasTrailerTypes = HasTrailerTypes(query);
  4527. var hasArtistFields = HasArtistFields(query);
  4528. var hasSeriesFields = HasSeriesFields(query);
  4529. foreach (var row in statement.ExecuteQuery())
  4530. {
  4531. var item = GetItem(row, query, hasProgramAttributes, hasEpisodeAttributes, hasServiceName, hasStartDate, hasTrailerTypes, hasArtistFields, hasSeriesFields);
  4532. if (item is not null)
  4533. {
  4534. var countStartColumn = columns.Count - 1;
  4535. list.Add((item, GetItemCounts(row, countStartColumn, typesToCount)));
  4536. }
  4537. }
  4538. }
  4539. }
  4540. if (query.EnableTotalRecordCount)
  4541. {
  4542. using (var statement = PrepareStatement(db, countText))
  4543. {
  4544. statement.TryBind("@SelectType", returnType);
  4545. if (EnableJoinUserData(query))
  4546. {
  4547. statement.TryBind("@UserId", query.User.InternalId);
  4548. }
  4549. if (typeSubQuery is not null)
  4550. {
  4551. GetWhereClauses(typeSubQuery, null);
  4552. }
  4553. BindSimilarParams(query, statement);
  4554. BindSearchParams(query, statement);
  4555. GetWhereClauses(innerQuery, statement);
  4556. GetWhereClauses(outerQuery, statement);
  4557. result.TotalRecordCount = statement.ExecuteQuery().SelectScalarInt().First();
  4558. }
  4559. }
  4560. },
  4561. ReadTransactionMode);
  4562. }
  4563. LogQueryTime("GetItemValues", commandText, now);
  4564. if (result.TotalRecordCount == 0)
  4565. {
  4566. result.TotalRecordCount = list.Count;
  4567. }
  4568. result.StartIndex = query.StartIndex ?? 0;
  4569. result.Items = list;
  4570. return result;
  4571. }
  4572. private static ItemCounts GetItemCounts(IReadOnlyList<ResultSetValue> reader, int countStartColumn, BaseItemKind[] typesToCount)
  4573. {
  4574. var counts = new ItemCounts();
  4575. if (typesToCount.Length == 0)
  4576. {
  4577. return counts;
  4578. }
  4579. if (!reader.TryGetString(countStartColumn, out var typeString))
  4580. {
  4581. return counts;
  4582. }
  4583. foreach (var typeName in typeString.AsSpan().Split('|'))
  4584. {
  4585. if (typeName.Equals(typeof(Series).FullName, StringComparison.OrdinalIgnoreCase))
  4586. {
  4587. counts.SeriesCount++;
  4588. }
  4589. else if (typeName.Equals(typeof(Episode).FullName, StringComparison.OrdinalIgnoreCase))
  4590. {
  4591. counts.EpisodeCount++;
  4592. }
  4593. else if (typeName.Equals(typeof(Movie).FullName, StringComparison.OrdinalIgnoreCase))
  4594. {
  4595. counts.MovieCount++;
  4596. }
  4597. else if (typeName.Equals(typeof(MusicAlbum).FullName, StringComparison.OrdinalIgnoreCase))
  4598. {
  4599. counts.AlbumCount++;
  4600. }
  4601. else if (typeName.Equals(typeof(MusicArtist).FullName, StringComparison.OrdinalIgnoreCase))
  4602. {
  4603. counts.ArtistCount++;
  4604. }
  4605. else if (typeName.Equals(typeof(Audio).FullName, StringComparison.OrdinalIgnoreCase))
  4606. {
  4607. counts.SongCount++;
  4608. }
  4609. else if (typeName.Equals(typeof(Trailer).FullName, StringComparison.OrdinalIgnoreCase))
  4610. {
  4611. counts.TrailerCount++;
  4612. }
  4613. counts.ItemCount++;
  4614. }
  4615. return counts;
  4616. }
  4617. private List<(int MagicNumber, string Value)> GetItemValuesToSave(BaseItem item, List<string> inheritedTags)
  4618. {
  4619. var list = new List<(int, string)>();
  4620. if (item is IHasArtist hasArtist)
  4621. {
  4622. list.AddRange(hasArtist.Artists.Select(i => (0, i)));
  4623. }
  4624. if (item is IHasAlbumArtist hasAlbumArtist)
  4625. {
  4626. list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (1, i)));
  4627. }
  4628. list.AddRange(item.Genres.Select(i => (2, i)));
  4629. list.AddRange(item.Studios.Select(i => (3, i)));
  4630. list.AddRange(item.Tags.Select(i => (4, i)));
  4631. // keywords was 5
  4632. list.AddRange(inheritedTags.Select(i => (6, i)));
  4633. return list;
  4634. }
  4635. private void UpdateItemValues(Guid itemId, List<(int MagicNumber, string Value)> values, IDatabaseConnection db)
  4636. {
  4637. if (itemId.Equals(default))
  4638. {
  4639. throw new ArgumentNullException(nameof(itemId));
  4640. }
  4641. ArgumentNullException.ThrowIfNull(values);
  4642. CheckDisposed();
  4643. var guidBlob = itemId.ToByteArray();
  4644. // First delete
  4645. db.Execute("delete from ItemValues where ItemId=@Id", guidBlob);
  4646. InsertItemValues(guidBlob, values, db);
  4647. }
  4648. private void InsertItemValues(byte[] idBlob, List<(int MagicNumber, string Value)> values, IDatabaseConnection db)
  4649. {
  4650. const int Limit = 100;
  4651. var startIndex = 0;
  4652. const string StartInsertText = "insert into ItemValues (ItemId, Type, Value, CleanValue) values ";
  4653. var insertText = new StringBuilder(StartInsertText);
  4654. while (startIndex < values.Count)
  4655. {
  4656. var endIndex = Math.Min(values.Count, startIndex + Limit);
  4657. for (var i = startIndex; i < endIndex; i++)
  4658. {
  4659. insertText.AppendFormat(
  4660. CultureInfo.InvariantCulture,
  4661. "(@ItemId, @Type{0}, @Value{0}, @CleanValue{0}),",
  4662. i);
  4663. }
  4664. // Remove last comma
  4665. insertText.Length--;
  4666. using (var statement = PrepareStatement(db, insertText.ToString()))
  4667. {
  4668. statement.TryBind("@ItemId", idBlob);
  4669. for (var i = startIndex; i < endIndex; i++)
  4670. {
  4671. var index = i.ToString(CultureInfo.InvariantCulture);
  4672. var currentValueInfo = values[i];
  4673. var itemValue = currentValueInfo.Value;
  4674. // Don't save if invalid
  4675. if (string.IsNullOrWhiteSpace(itemValue))
  4676. {
  4677. continue;
  4678. }
  4679. statement.TryBind("@Type" + index, currentValueInfo.MagicNumber);
  4680. statement.TryBind("@Value" + index, itemValue);
  4681. statement.TryBind("@CleanValue" + index, GetCleanValue(itemValue));
  4682. }
  4683. statement.Reset();
  4684. statement.MoveNext();
  4685. }
  4686. startIndex += Limit;
  4687. insertText.Length = StartInsertText.Length;
  4688. }
  4689. }
  4690. public void UpdatePeople(Guid itemId, List<PersonInfo> people)
  4691. {
  4692. if (itemId.Equals(default))
  4693. {
  4694. throw new ArgumentNullException(nameof(itemId));
  4695. }
  4696. ArgumentNullException.ThrowIfNull(people);
  4697. CheckDisposed();
  4698. using (var connection = GetConnection())
  4699. {
  4700. connection.RunInTransaction(
  4701. db =>
  4702. {
  4703. var itemIdBlob = itemId.ToByteArray();
  4704. // First delete chapters
  4705. db.Execute("delete from People where ItemId=@ItemId", itemIdBlob);
  4706. InsertPeople(itemIdBlob, people, db);
  4707. },
  4708. TransactionMode);
  4709. }
  4710. }
  4711. private void InsertPeople(byte[] idBlob, List<PersonInfo> people, IDatabaseConnection db)
  4712. {
  4713. const int Limit = 100;
  4714. var startIndex = 0;
  4715. var listIndex = 0;
  4716. const string StartInsertText = "insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values ";
  4717. var insertText = new StringBuilder(StartInsertText);
  4718. while (startIndex < people.Count)
  4719. {
  4720. var endIndex = Math.Min(people.Count, startIndex + Limit);
  4721. for (var i = startIndex; i < endIndex; i++)
  4722. {
  4723. insertText.AppendFormat(
  4724. CultureInfo.InvariantCulture,
  4725. "(@ItemId, @Name{0}, @Role{0}, @PersonType{0}, @SortOrder{0}, @ListOrder{0}),",
  4726. i.ToString(CultureInfo.InvariantCulture));
  4727. }
  4728. // Remove last comma
  4729. insertText.Length--;
  4730. using (var statement = PrepareStatement(db, insertText.ToString()))
  4731. {
  4732. statement.TryBind("@ItemId", idBlob);
  4733. for (var i = startIndex; i < endIndex; i++)
  4734. {
  4735. var index = i.ToString(CultureInfo.InvariantCulture);
  4736. var person = people[i];
  4737. statement.TryBind("@Name" + index, person.Name);
  4738. statement.TryBind("@Role" + index, person.Role);
  4739. statement.TryBind("@PersonType" + index, person.Type);
  4740. statement.TryBind("@SortOrder" + index, person.SortOrder);
  4741. statement.TryBind("@ListOrder" + index, listIndex);
  4742. listIndex++;
  4743. }
  4744. statement.Reset();
  4745. statement.MoveNext();
  4746. }
  4747. startIndex += Limit;
  4748. insertText.Length = StartInsertText.Length;
  4749. }
  4750. }
  4751. private PersonInfo GetPerson(IReadOnlyList<ResultSetValue> reader)
  4752. {
  4753. var item = new PersonInfo
  4754. {
  4755. ItemId = reader.GetGuid(0),
  4756. Name = reader.GetString(1)
  4757. };
  4758. if (reader.TryGetString(2, out var role))
  4759. {
  4760. item.Role = role;
  4761. }
  4762. if (reader.TryGetString(3, out var type))
  4763. {
  4764. item.Type = type;
  4765. }
  4766. if (reader.TryGetInt32(4, out var sortOrder))
  4767. {
  4768. item.SortOrder = sortOrder;
  4769. }
  4770. return item;
  4771. }
  4772. public List<MediaStream> GetMediaStreams(MediaStreamQuery query)
  4773. {
  4774. CheckDisposed();
  4775. ArgumentNullException.ThrowIfNull(query);
  4776. var cmdText = _mediaStreamSaveColumnsSelectQuery;
  4777. if (query.Type.HasValue)
  4778. {
  4779. cmdText += " AND StreamType=@StreamType";
  4780. }
  4781. if (query.Index.HasValue)
  4782. {
  4783. cmdText += " AND StreamIndex=@StreamIndex";
  4784. }
  4785. cmdText += " order by StreamIndex ASC";
  4786. using (var connection = GetConnection(true))
  4787. {
  4788. var list = new List<MediaStream>();
  4789. using (var statement = PrepareStatement(connection, cmdText))
  4790. {
  4791. statement.TryBind("@ItemId", query.ItemId);
  4792. if (query.Type.HasValue)
  4793. {
  4794. statement.TryBind("@StreamType", query.Type.Value.ToString());
  4795. }
  4796. if (query.Index.HasValue)
  4797. {
  4798. statement.TryBind("@StreamIndex", query.Index.Value);
  4799. }
  4800. foreach (var row in statement.ExecuteQuery())
  4801. {
  4802. list.Add(GetMediaStream(row));
  4803. }
  4804. }
  4805. return list;
  4806. }
  4807. }
  4808. public void SaveMediaStreams(Guid id, IReadOnlyList<MediaStream> streams, CancellationToken cancellationToken)
  4809. {
  4810. CheckDisposed();
  4811. if (id.Equals(default))
  4812. {
  4813. throw new ArgumentNullException(nameof(id));
  4814. }
  4815. ArgumentNullException.ThrowIfNull(streams);
  4816. cancellationToken.ThrowIfCancellationRequested();
  4817. using (var connection = GetConnection())
  4818. {
  4819. connection.RunInTransaction(
  4820. db =>
  4821. {
  4822. var itemIdBlob = id.ToByteArray();
  4823. // Delete existing mediastreams
  4824. db.Execute("delete from mediastreams where ItemId=@ItemId", itemIdBlob);
  4825. InsertMediaStreams(itemIdBlob, streams, db);
  4826. },
  4827. TransactionMode);
  4828. }
  4829. }
  4830. private void InsertMediaStreams(byte[] idBlob, IReadOnlyList<MediaStream> streams, IDatabaseConnection db)
  4831. {
  4832. const int Limit = 10;
  4833. var startIndex = 0;
  4834. var insertText = new StringBuilder(_mediaStreamSaveColumnsInsertQuery);
  4835. while (startIndex < streams.Count)
  4836. {
  4837. var endIndex = Math.Min(streams.Count, startIndex + Limit);
  4838. for (var i = startIndex; i < endIndex; i++)
  4839. {
  4840. if (i != startIndex)
  4841. {
  4842. insertText.Append(',');
  4843. }
  4844. var index = i.ToString(CultureInfo.InvariantCulture);
  4845. insertText.Append("(@ItemId, ");
  4846. foreach (var column in _mediaStreamSaveColumns.Skip(1))
  4847. {
  4848. insertText.Append('@').Append(column).Append(index).Append(',');
  4849. }
  4850. insertText.Length -= 1; // Remove the last comma
  4851. insertText.Append(')');
  4852. }
  4853. using (var statement = PrepareStatement(db, insertText.ToString()))
  4854. {
  4855. statement.TryBind("@ItemId", idBlob);
  4856. for (var i = startIndex; i < endIndex; i++)
  4857. {
  4858. var index = i.ToString(CultureInfo.InvariantCulture);
  4859. var stream = streams[i];
  4860. statement.TryBind("@StreamIndex" + index, stream.Index);
  4861. statement.TryBind("@StreamType" + index, stream.Type.ToString());
  4862. statement.TryBind("@Codec" + index, stream.Codec);
  4863. statement.TryBind("@Language" + index, stream.Language);
  4864. statement.TryBind("@ChannelLayout" + index, stream.ChannelLayout);
  4865. statement.TryBind("@Profile" + index, stream.Profile);
  4866. statement.TryBind("@AspectRatio" + index, stream.AspectRatio);
  4867. statement.TryBind("@Path" + index, GetPathToSave(stream.Path));
  4868. statement.TryBind("@IsInterlaced" + index, stream.IsInterlaced);
  4869. statement.TryBind("@BitRate" + index, stream.BitRate);
  4870. statement.TryBind("@Channels" + index, stream.Channels);
  4871. statement.TryBind("@SampleRate" + index, stream.SampleRate);
  4872. statement.TryBind("@IsDefault" + index, stream.IsDefault);
  4873. statement.TryBind("@IsForced" + index, stream.IsForced);
  4874. statement.TryBind("@IsExternal" + index, stream.IsExternal);
  4875. // Yes these are backwards due to a mistake
  4876. statement.TryBind("@Width" + index, stream.Height);
  4877. statement.TryBind("@Height" + index, stream.Width);
  4878. statement.TryBind("@AverageFrameRate" + index, stream.AverageFrameRate);
  4879. statement.TryBind("@RealFrameRate" + index, stream.RealFrameRate);
  4880. statement.TryBind("@Level" + index, stream.Level);
  4881. statement.TryBind("@PixelFormat" + index, stream.PixelFormat);
  4882. statement.TryBind("@BitDepth" + index, stream.BitDepth);
  4883. statement.TryBind("@IsExternal" + index, stream.IsExternal);
  4884. statement.TryBind("@RefFrames" + index, stream.RefFrames);
  4885. statement.TryBind("@CodecTag" + index, stream.CodecTag);
  4886. statement.TryBind("@Comment" + index, stream.Comment);
  4887. statement.TryBind("@NalLengthSize" + index, stream.NalLengthSize);
  4888. statement.TryBind("@IsAvc" + index, stream.IsAVC);
  4889. statement.TryBind("@Title" + index, stream.Title);
  4890. statement.TryBind("@TimeBase" + index, stream.TimeBase);
  4891. statement.TryBind("@CodecTimeBase" + index, stream.CodecTimeBase);
  4892. statement.TryBind("@ColorPrimaries" + index, stream.ColorPrimaries);
  4893. statement.TryBind("@ColorSpace" + index, stream.ColorSpace);
  4894. statement.TryBind("@ColorTransfer" + index, stream.ColorTransfer);
  4895. statement.TryBind("@DvVersionMajor" + index, stream.DvVersionMajor);
  4896. statement.TryBind("@DvVersionMinor" + index, stream.DvVersionMinor);
  4897. statement.TryBind("@DvProfile" + index, stream.DvProfile);
  4898. statement.TryBind("@DvLevel" + index, stream.DvLevel);
  4899. statement.TryBind("@RpuPresentFlag" + index, stream.RpuPresentFlag);
  4900. statement.TryBind("@ElPresentFlag" + index, stream.ElPresentFlag);
  4901. statement.TryBind("@BlPresentFlag" + index, stream.BlPresentFlag);
  4902. statement.TryBind("@DvBlSignalCompatibilityId" + index, stream.DvBlSignalCompatibilityId);
  4903. statement.TryBind("@IsHearingImpaired" + index, stream.IsHearingImpaired);
  4904. }
  4905. statement.Reset();
  4906. statement.MoveNext();
  4907. }
  4908. startIndex += Limit;
  4909. insertText.Length = _mediaStreamSaveColumnsInsertQuery.Length;
  4910. }
  4911. }
  4912. /// <summary>
  4913. /// Gets the media stream.
  4914. /// </summary>
  4915. /// <param name="reader">The reader.</param>
  4916. /// <returns>MediaStream.</returns>
  4917. private MediaStream GetMediaStream(IReadOnlyList<ResultSetValue> reader)
  4918. {
  4919. var item = new MediaStream
  4920. {
  4921. Index = reader[1].ToInt()
  4922. };
  4923. item.Type = Enum.Parse<MediaStreamType>(reader[2].ToString(), true);
  4924. if (reader.TryGetString(3, out var codec))
  4925. {
  4926. item.Codec = codec;
  4927. }
  4928. if (reader.TryGetString(4, out var language))
  4929. {
  4930. item.Language = language;
  4931. }
  4932. if (reader.TryGetString(5, out var channelLayout))
  4933. {
  4934. item.ChannelLayout = channelLayout;
  4935. }
  4936. if (reader.TryGetString(6, out var profile))
  4937. {
  4938. item.Profile = profile;
  4939. }
  4940. if (reader.TryGetString(7, out var aspectRatio))
  4941. {
  4942. item.AspectRatio = aspectRatio;
  4943. }
  4944. if (reader.TryGetString(8, out var path))
  4945. {
  4946. item.Path = RestorePath(path);
  4947. }
  4948. item.IsInterlaced = reader.GetBoolean(9);
  4949. if (reader.TryGetInt32(10, out var bitrate))
  4950. {
  4951. item.BitRate = bitrate;
  4952. }
  4953. if (reader.TryGetInt32(11, out var channels))
  4954. {
  4955. item.Channels = channels;
  4956. }
  4957. if (reader.TryGetInt32(12, out var sampleRate))
  4958. {
  4959. item.SampleRate = sampleRate;
  4960. }
  4961. item.IsDefault = reader.GetBoolean(13);
  4962. item.IsForced = reader.GetBoolean(14);
  4963. item.IsExternal = reader.GetBoolean(15);
  4964. if (reader.TryGetInt32(16, out var width))
  4965. {
  4966. item.Width = width;
  4967. }
  4968. if (reader.TryGetInt32(17, out var height))
  4969. {
  4970. item.Height = height;
  4971. }
  4972. if (reader.TryGetSingle(18, out var averageFrameRate))
  4973. {
  4974. item.AverageFrameRate = averageFrameRate;
  4975. }
  4976. if (reader.TryGetSingle(19, out var realFrameRate))
  4977. {
  4978. item.RealFrameRate = realFrameRate;
  4979. }
  4980. if (reader.TryGetSingle(20, out var level))
  4981. {
  4982. item.Level = level;
  4983. }
  4984. if (reader.TryGetString(21, out var pixelFormat))
  4985. {
  4986. item.PixelFormat = pixelFormat;
  4987. }
  4988. if (reader.TryGetInt32(22, out var bitDepth))
  4989. {
  4990. item.BitDepth = bitDepth;
  4991. }
  4992. if (reader.TryGetBoolean(23, out var isAnamorphic))
  4993. {
  4994. item.IsAnamorphic = isAnamorphic;
  4995. }
  4996. if (reader.TryGetInt32(24, out var refFrames))
  4997. {
  4998. item.RefFrames = refFrames;
  4999. }
  5000. if (reader.TryGetString(25, out var codecTag))
  5001. {
  5002. item.CodecTag = codecTag;
  5003. }
  5004. if (reader.TryGetString(26, out var comment))
  5005. {
  5006. item.Comment = comment;
  5007. }
  5008. if (reader.TryGetString(27, out var nalLengthSize))
  5009. {
  5010. item.NalLengthSize = nalLengthSize;
  5011. }
  5012. if (reader.TryGetBoolean(28, out var isAVC))
  5013. {
  5014. item.IsAVC = isAVC;
  5015. }
  5016. if (reader.TryGetString(29, out var title))
  5017. {
  5018. item.Title = title;
  5019. }
  5020. if (reader.TryGetString(30, out var timeBase))
  5021. {
  5022. item.TimeBase = timeBase;
  5023. }
  5024. if (reader.TryGetString(31, out var codecTimeBase))
  5025. {
  5026. item.CodecTimeBase = codecTimeBase;
  5027. }
  5028. if (reader.TryGetString(32, out var colorPrimaries))
  5029. {
  5030. item.ColorPrimaries = colorPrimaries;
  5031. }
  5032. if (reader.TryGetString(33, out var colorSpace))
  5033. {
  5034. item.ColorSpace = colorSpace;
  5035. }
  5036. if (reader.TryGetString(34, out var colorTransfer))
  5037. {
  5038. item.ColorTransfer = colorTransfer;
  5039. }
  5040. if (reader.TryGetInt32(35, out var dvVersionMajor))
  5041. {
  5042. item.DvVersionMajor = dvVersionMajor;
  5043. }
  5044. if (reader.TryGetInt32(36, out var dvVersionMinor))
  5045. {
  5046. item.DvVersionMinor = dvVersionMinor;
  5047. }
  5048. if (reader.TryGetInt32(37, out var dvProfile))
  5049. {
  5050. item.DvProfile = dvProfile;
  5051. }
  5052. if (reader.TryGetInt32(38, out var dvLevel))
  5053. {
  5054. item.DvLevel = dvLevel;
  5055. }
  5056. if (reader.TryGetInt32(39, out var rpuPresentFlag))
  5057. {
  5058. item.RpuPresentFlag = rpuPresentFlag;
  5059. }
  5060. if (reader.TryGetInt32(40, out var elPresentFlag))
  5061. {
  5062. item.ElPresentFlag = elPresentFlag;
  5063. }
  5064. if (reader.TryGetInt32(41, out var blPresentFlag))
  5065. {
  5066. item.BlPresentFlag = blPresentFlag;
  5067. }
  5068. if (reader.TryGetInt32(42, out var dvBlSignalCompatibilityId))
  5069. {
  5070. item.DvBlSignalCompatibilityId = dvBlSignalCompatibilityId;
  5071. }
  5072. item.IsHearingImpaired = reader.GetBoolean(43);
  5073. if (item.Type == MediaStreamType.Subtitle)
  5074. {
  5075. item.LocalizedUndefined = _localization.GetLocalizedString("Undefined");
  5076. item.LocalizedDefault = _localization.GetLocalizedString("Default");
  5077. item.LocalizedForced = _localization.GetLocalizedString("Forced");
  5078. item.LocalizedExternal = _localization.GetLocalizedString("External");
  5079. item.LocalizedHearingImpaired = _localization.GetLocalizedString("HearingImpaired");
  5080. }
  5081. return item;
  5082. }
  5083. public List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
  5084. {
  5085. CheckDisposed();
  5086. ArgumentNullException.ThrowIfNull(query);
  5087. var cmdText = _mediaAttachmentSaveColumnsSelectQuery;
  5088. if (query.Index.HasValue)
  5089. {
  5090. cmdText += " AND AttachmentIndex=@AttachmentIndex";
  5091. }
  5092. cmdText += " order by AttachmentIndex ASC";
  5093. var list = new List<MediaAttachment>();
  5094. using (var connection = GetConnection(true))
  5095. using (var statement = PrepareStatement(connection, cmdText))
  5096. {
  5097. statement.TryBind("@ItemId", query.ItemId.ToByteArray());
  5098. if (query.Index.HasValue)
  5099. {
  5100. statement.TryBind("@AttachmentIndex", query.Index.Value);
  5101. }
  5102. foreach (var row in statement.ExecuteQuery())
  5103. {
  5104. list.Add(GetMediaAttachment(row));
  5105. }
  5106. }
  5107. return list;
  5108. }
  5109. public void SaveMediaAttachments(
  5110. Guid id,
  5111. IReadOnlyList<MediaAttachment> attachments,
  5112. CancellationToken cancellationToken)
  5113. {
  5114. CheckDisposed();
  5115. if (id.Equals(default))
  5116. {
  5117. throw new ArgumentException("Guid can't be empty.", nameof(id));
  5118. }
  5119. ArgumentNullException.ThrowIfNull(attachments);
  5120. cancellationToken.ThrowIfCancellationRequested();
  5121. using (var connection = GetConnection())
  5122. {
  5123. connection.RunInTransaction(
  5124. db =>
  5125. {
  5126. var itemIdBlob = id.ToByteArray();
  5127. db.Execute("delete from mediaattachments where ItemId=@ItemId", itemIdBlob);
  5128. InsertMediaAttachments(itemIdBlob, attachments, db, cancellationToken);
  5129. },
  5130. TransactionMode);
  5131. }
  5132. }
  5133. private void InsertMediaAttachments(
  5134. byte[] idBlob,
  5135. IReadOnlyList<MediaAttachment> attachments,
  5136. IDatabaseConnection db,
  5137. CancellationToken cancellationToken)
  5138. {
  5139. const int InsertAtOnce = 10;
  5140. var insertText = new StringBuilder(_mediaAttachmentInsertPrefix);
  5141. for (var startIndex = 0; startIndex < attachments.Count; startIndex += InsertAtOnce)
  5142. {
  5143. var endIndex = Math.Min(attachments.Count, startIndex + InsertAtOnce);
  5144. for (var i = startIndex; i < endIndex; i++)
  5145. {
  5146. var index = i.ToString(CultureInfo.InvariantCulture);
  5147. insertText.Append("(@ItemId, ");
  5148. foreach (var column in _mediaAttachmentSaveColumns.Skip(1))
  5149. {
  5150. insertText.Append('@')
  5151. .Append(column)
  5152. .Append(index)
  5153. .Append(',');
  5154. }
  5155. insertText.Length -= 1;
  5156. insertText.Append("),");
  5157. }
  5158. insertText.Length--;
  5159. cancellationToken.ThrowIfCancellationRequested();
  5160. using (var statement = PrepareStatement(db, insertText.ToString()))
  5161. {
  5162. statement.TryBind("@ItemId", idBlob);
  5163. for (var i = startIndex; i < endIndex; i++)
  5164. {
  5165. var index = i.ToString(CultureInfo.InvariantCulture);
  5166. var attachment = attachments[i];
  5167. statement.TryBind("@AttachmentIndex" + index, attachment.Index);
  5168. statement.TryBind("@Codec" + index, attachment.Codec);
  5169. statement.TryBind("@CodecTag" + index, attachment.CodecTag);
  5170. statement.TryBind("@Comment" + index, attachment.Comment);
  5171. statement.TryBind("@Filename" + index, attachment.FileName);
  5172. statement.TryBind("@MIMEType" + index, attachment.MimeType);
  5173. }
  5174. statement.Reset();
  5175. statement.MoveNext();
  5176. }
  5177. insertText.Length = _mediaAttachmentInsertPrefix.Length;
  5178. }
  5179. }
  5180. /// <summary>
  5181. /// Gets the attachment.
  5182. /// </summary>
  5183. /// <param name="reader">The reader.</param>
  5184. /// <returns>MediaAttachment.</returns>
  5185. private MediaAttachment GetMediaAttachment(IReadOnlyList<ResultSetValue> reader)
  5186. {
  5187. var item = new MediaAttachment
  5188. {
  5189. Index = reader[1].ToInt()
  5190. };
  5191. if (reader.TryGetString(2, out var codec))
  5192. {
  5193. item.Codec = codec;
  5194. }
  5195. if (reader.TryGetString(3, out var codecTag))
  5196. {
  5197. item.CodecTag = codecTag;
  5198. }
  5199. if (reader.TryGetString(4, out var comment))
  5200. {
  5201. item.Comment = comment;
  5202. }
  5203. if (reader.TryGetString(5, out var fileName))
  5204. {
  5205. item.FileName = fileName;
  5206. }
  5207. if (reader.TryGetString(6, out var mimeType))
  5208. {
  5209. item.MimeType = mimeType;
  5210. }
  5211. return item;
  5212. }
  5213. }
  5214. }