SqliteItemRepository.cs 200 KB

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