SqliteItemRepository.cs 226 KB

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