SqliteItemRepository.cs 221 KB

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