2
0

SqliteItemRepository.cs 230 KB

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