2
0

SqliteItemRepository.cs 209 KB

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