SqliteItemRepository.cs 230 KB

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