SqliteItemRepository.cs 222 KB

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