SqliteItemRepository.cs 202 KB

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