SqliteItemRepository.cs 218 KB

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