SqliteItemRepository.cs 223 KB

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