SqliteItemRepository.cs 191 KB

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