SqliteItemRepository.cs 223 KB

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