SqliteItemRepository.cs 223 KB

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