SqliteItemRepository.cs 208 KB

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