SqliteItemRepository.cs 230 KB

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