SqliteItemRepository.cs 195 KB

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