SqliteItemRepository.cs 199 KB

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