SqliteItemRepository.cs 226 KB

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