SqliteItemRepository.cs 225 KB

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