query.py 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225
  1. # -*- coding: utf-8 -*-
  2. """
  3. (c) 2014-2019 - Copyright Red Hat Inc
  4. Authors:
  5. Pierre-Yves Chibon <pingou@pingoured.fr>
  6. Farhaan Bukhsh <farhaan.bukhsh@gmail.com>
  7. """
  8. from __future__ import absolute_import, unicode_literals
  9. # pylint: disable=too-many-branches
  10. # pylint: disable=too-many-arguments
  11. # pylint: disable=too-many-locals
  12. # pylint: disable=too-many-statements
  13. # pylint: disable=too-many-lines
  14. try:
  15. import simplejson as json
  16. except ImportError: # pragma: no cover
  17. import json
  18. import copy
  19. import datetime
  20. import fnmatch
  21. import functools
  22. import hashlib
  23. import logging
  24. import os
  25. import shutil
  26. import subprocess
  27. import tempfile
  28. import uuid
  29. from collections import Counter
  30. from math import ceil
  31. import bleach
  32. import markdown
  33. import redis
  34. import six
  35. import sqlalchemy
  36. import sqlalchemy.schema
  37. import werkzeug.utils
  38. from flask import url_for
  39. from six.moves.urllib_parse import parse_qsl, urlencode, urlparse
  40. from sqlalchemy import Text, asc, cast, desc, func
  41. from sqlalchemy.orm import aliased
  42. import pagure.exceptions
  43. import pagure.lib.git
  44. import pagure.lib.git_auth
  45. import pagure.lib.link
  46. import pagure.lib.login
  47. import pagure.lib.notify
  48. import pagure.lib.plugins
  49. import pagure.lib.tasks
  50. import pagure.lib.tasks_services
  51. import pagure.pfmarkdown
  52. import pagure.utils
  53. from pagure.config import config as pagure_config
  54. from pagure.lib import model
  55. # For backward compatibility since this function used to be in this file
  56. from pagure.lib.model_base import create_session # noqa
  57. REDIS = None
  58. PAGURE_CI = None
  59. _log = logging.getLogger(__name__)
  60. # List of all the possible hooks pagure could generate before it was moved
  61. # to the runner architecture we now use.
  62. # This list is kept so we can ignore all of these hooks.
  63. ORIGINAL_PAGURE_HOOK = [
  64. "post-receive.default",
  65. "post-receive.fedmsg",
  66. "post-receive.irc",
  67. "post-receive.mail",
  68. "post-receive.mirror",
  69. "post-receive.pagure",
  70. "post-receive.pagure-requests",
  71. "post-receive.pagure-ticket",
  72. "post-receive.rtd",
  73. "pre-receive.pagure_no_new_branches",
  74. "pre-receive.pagureforcecommit",
  75. "pre-receive.pagureunsignedcommit",
  76. ]
  77. def get_repotypes():
  78. rt = ["main", "requests"]
  79. if pagure_config["ENABLE_TICKETS"]:
  80. rt.append("tickets")
  81. if pagure_config["ENABLE_DOCS"]:
  82. rt.append("docs")
  83. return tuple(rt)
  84. class Unspecified(object):
  85. """Custom None object used to indicate that the caller has not made
  86. a choice for a particular argument.
  87. """
  88. pass
  89. def set_redis(host=None, port=None, socket=None, dbname=0):
  90. """Set the redis connection with the specified information."""
  91. global REDIS
  92. if socket:
  93. pool = redis.ConnectionPool(
  94. connection_class=redis.UnixDomainSocketConnection, path=socket
  95. )
  96. elif host and port:
  97. pool = redis.ConnectionPool(host=host, port=port, db=dbname)
  98. else:
  99. raise pagure.exceptions.PagureException(
  100. "Configure either REDIS_HOST and REDIS_PORT or REDIS_SOCKET"
  101. )
  102. REDIS = redis.StrictRedis(connection_pool=pool)
  103. def set_pagure_ci(services):
  104. """Set the list of CI services supported by this pagure instance."""
  105. global PAGURE_CI
  106. PAGURE_CI = services
  107. def get_user(session, key):
  108. """Searches for a user in the database for a given username or email."""
  109. user_obj = search_user(session, username=key)
  110. if not user_obj:
  111. user_obj = search_user(session, email=key)
  112. if not user_obj:
  113. raise pagure.exceptions.PagureException('No user "%s" found' % key)
  114. return user_obj
  115. def get_user_by_id(session, userid):
  116. """Searches for a user in the database for a given username or email."""
  117. query = session.query(model.User).filter(model.User.id == userid)
  118. return query.first()
  119. def get_blocked_users(session, username=None, date=None):
  120. """Returns all the users that are blocked in this pagure instance."""
  121. now = datetime.datetime.utcnow()
  122. query = session.query(model.User).filter(
  123. model.User.refuse_sessions_before >= (date or now)
  124. )
  125. if username:
  126. if "*" in username:
  127. username = username.replace("*", "%")
  128. query = query.filter(model.User.user.ilike(username))
  129. else:
  130. query = query.filter(model.User.user == username)
  131. return query.all()
  132. def get_next_id(session, projectid):
  133. """Returns the next identifier of a project ticket or pull-request
  134. based on the identifier already in the database.
  135. """
  136. query1 = session.query(func.max(model.Issue.id)).filter(
  137. model.Issue.project_id == projectid
  138. )
  139. query2 = session.query(func.max(model.PullRequest.id)).filter(
  140. model.PullRequest.project_id == projectid
  141. )
  142. ids = [el[0] for el in query1.union(query2).all() if el[0] is not None]
  143. nid = 0
  144. if ids:
  145. nid = max(ids)
  146. return nid + 1
  147. def search_user(session, username=None, email=None, token=None, pattern=None):
  148. """Searches the database for the user or users matching the given
  149. criterias.
  150. :arg session: the session to use to connect to the database.
  151. :kwarg username: the username of the user to look for.
  152. :type username: string or None
  153. :kwarg email: the email or one of the email of the user to look for
  154. :type email: string or None
  155. :kwarg token: the token of the user to look for
  156. :type token: string or None
  157. :kwarg pattern: a pattern to search the users with.
  158. :type pattern: string or None
  159. :return: A single User object if any of username, email or token is
  160. specified, a list of User objects otherwise.
  161. :rtype: User or [User]
  162. """
  163. query = session.query(model.User).order_by(model.User.user)
  164. if username is not None:
  165. query = query.filter(model.User.user == username)
  166. if email is not None:
  167. query = query.filter(model.UserEmail.user_id == model.User.id).filter(
  168. model.UserEmail.email == email
  169. )
  170. if token is not None:
  171. query = query.filter(model.User.token == token)
  172. if pattern:
  173. pattern = pattern.replace("*", "%")
  174. query = query.filter(model.User.user.like(pattern))
  175. if any([username, email, token]):
  176. output = query.first()
  177. else:
  178. output = query.all()
  179. return output
  180. def is_valid_ssh_key(key, fp_hash="SHA256"):
  181. """Validates the ssh key using ssh-keygen."""
  182. key = key.strip()
  183. if not key:
  184. return None
  185. tmpdirname = tempfile.mkdtemp()
  186. filename = os.path.join(tmpdirname, "key")
  187. with open(filename, "w") as stream:
  188. stream.write(key)
  189. cmd = ["/usr/bin/ssh-keygen", "-l", "-f", filename, "-E", fp_hash]
  190. proc = subprocess.Popen(
  191. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
  192. )
  193. stdout, stderr = proc.communicate()
  194. shutil.rmtree(tmpdirname)
  195. if proc.returncode != 0:
  196. _log.warning("STDOUT: %s", stdout)
  197. _log.warning("STDERR: %s", stderr)
  198. return False
  199. stdout = stdout.decode("utf-8")
  200. return stdout
  201. def are_valid_ssh_keys(keys):
  202. """Checks if all the ssh keys are valid or not."""
  203. return all(
  204. [is_valid_ssh_key(key) is not False for key in keys.split("\n")]
  205. )
  206. def find_ssh_key(session, search_key, username):
  207. """Finds and returns SSHKey matching the requested search_key.
  208. Args:
  209. session: database session
  210. search_key (string): The SSH fingerprint we are requested to look up
  211. username (string or None): If this is provided, the key is looked up
  212. to belong to the requested user.
  213. """
  214. query = session.query(model.SSHKey).filter(
  215. model.SSHKey.ssh_search_key == search_key
  216. )
  217. if username:
  218. userowner = (
  219. session.query(model.User.id)
  220. .filter(model.User.user == username)
  221. .subquery()
  222. )
  223. query = query.filter(model.SSHKey.user_id == userowner)
  224. try:
  225. return query.one()
  226. except sqlalchemy.orm.exc.NoResultFound:
  227. return None
  228. def create_deploykeys_ssh_keys_on_disk(project, gitolite_keydir):
  229. """Create the ssh keys for the projects' deploy keys on the key dir.
  230. This method does NOT support multiple ssh keys per deploy key.
  231. """
  232. if not gitolite_keydir:
  233. # Nothing to do here, move right along
  234. return
  235. # First remove deploykeys that no longer exist
  236. keyfiles = [
  237. "deploykey_%s_%s.pub"
  238. % (werkzeug.utils.secure_filename(project.fullname), key.id)
  239. for key in project.deploykeys
  240. ]
  241. project_key_dir = os.path.join(
  242. gitolite_keydir, "deploykeys", project.fullname
  243. )
  244. if not os.path.exists(project_key_dir):
  245. os.makedirs(project_key_dir)
  246. for keyfile in os.listdir(project_key_dir):
  247. if keyfile not in keyfiles:
  248. # This key is no longer in the project. Remove it.
  249. os.remove(os.path.join(project_key_dir, keyfile))
  250. for deploykey in project.deploykeys:
  251. # See the comment in lib/git.py:write_gitolite_acls about why this
  252. # name for a file is sane and does not inject a new security risk.
  253. keyfile = "deploykey_%s_%s.pub" % (
  254. werkzeug.utils.secure_filename(project.fullname),
  255. deploykey.id,
  256. )
  257. if not os.path.exists(os.path.join(project_key_dir, keyfile)):
  258. # We only take the very first key - deploykeys must be single keys
  259. key = deploykey.public_ssh_key.split("\n")[0]
  260. if not key:
  261. continue
  262. if not is_valid_ssh_key(key):
  263. continue
  264. with open(os.path.join(project_key_dir, keyfile), "w") as f:
  265. f.write(deploykey.public_ssh_key)
  266. def create_user_ssh_keys_on_disk(user, gitolite_keydir):
  267. """Create the ssh keys for the user on the specific folder.
  268. This is the method allowing to have multiple ssh keys per user.
  269. """
  270. if gitolite_keydir:
  271. # First remove any old keyfiles for the user
  272. # Assumption: we populated the keydir. This means that files
  273. # will be in 0/<username>.pub, ..., and not in any deeper
  274. # directory structures. Also, this means that if a user
  275. # had 5 lines, they will be up to at most keys_4/<username>.pub,
  276. # meaning that if a user is not in keys_<i>/<username>.pub, with
  277. # i being any integer, the user is most certainly not in
  278. # keys_<i+1>/<username>.pub.
  279. i = 0
  280. keyline_file = os.path.join(
  281. gitolite_keydir, "keys_%i" % i, "%s.pub" % user.user
  282. )
  283. while os.path.exists(keyline_file):
  284. os.unlink(keyline_file)
  285. i += 1
  286. keyline_file = os.path.join(
  287. gitolite_keydir, "keys_%i" % i, "%s.pub" % user.user
  288. )
  289. if not user.sshkeys:
  290. return
  291. # Now let's create new keyfiles for the user
  292. i = 0
  293. for key in user.sshkeys:
  294. if not is_valid_ssh_key(key.public_ssh_key):
  295. continue
  296. keyline_dir = os.path.join(gitolite_keydir, "keys_%i" % i)
  297. if not os.path.exists(keyline_dir):
  298. os.mkdir(keyline_dir)
  299. keyfile = os.path.join(keyline_dir, "%s.pub" % user.user)
  300. with open(keyfile, "w") as stream:
  301. stream.write(key.public_ssh_key.strip())
  302. i += 1
  303. def add_issue_comment(
  304. session,
  305. issue,
  306. comment,
  307. user,
  308. notify=True,
  309. date_created=None,
  310. notification=False,
  311. ):
  312. """Add a comment to an issue."""
  313. user_obj = get_user(session, user)
  314. issue_comment = model.IssueComment(
  315. issue_uid=issue.uid,
  316. comment=comment,
  317. user_id=user_obj.id,
  318. date_created=date_created,
  319. notification=notification,
  320. )
  321. issue.last_updated = datetime.datetime.utcnow()
  322. session.add(issue)
  323. session.add(issue_comment)
  324. # Make sure we won't have SQLAlchemy error before we continue
  325. session.commit()
  326. if not notification:
  327. log_action(session, "commented", issue, user_obj)
  328. if notify:
  329. pagure.lib.notify.notify_new_comment(issue_comment, user=user_obj)
  330. pagure.lib.git.update_git(issue, repo=issue.project)
  331. if not issue.private:
  332. pagure.lib.notify.log(
  333. issue.project,
  334. topic="issue.comment.added",
  335. msg=dict(
  336. issue=issue.to_json(public=True),
  337. project=issue.project.to_json(public=True),
  338. agent=user_obj.username,
  339. ),
  340. )
  341. # TODO: we should notify the SSE server even on update of the ticket
  342. # via git push to the ticket repo (the only case where notify=False
  343. # basically), but this causes problem with some of our markdown extension
  344. # so until we figure this out, we won't do live-refresh
  345. if REDIS and notify:
  346. if issue.private:
  347. REDIS.publish(
  348. "pagure.%s" % issue.uid,
  349. json.dumps(
  350. {"issue": "private", "comment_id": issue_comment.id}
  351. ),
  352. )
  353. else:
  354. REDIS.publish(
  355. "pagure.%s" % issue.uid,
  356. json.dumps(
  357. {
  358. "comment_id": issue_comment.id,
  359. "issue_id": issue.id,
  360. "project": issue.project.fullname,
  361. "comment_added": text2markdown(issue_comment.comment),
  362. "comment_user": issue_comment.user.user,
  363. "avatar_url": avatar_url_from_email(
  364. issue_comment.user.default_email, size=16
  365. ),
  366. "comment_date": issue_comment.date_created.strftime(
  367. "%Y-%m-%d %H:%M:%S"
  368. ),
  369. "notification": notification,
  370. }
  371. ),
  372. )
  373. return "Comment added"
  374. def add_tag_obj(session, obj, tags, user):
  375. """Add a tag to an object (either an issue or a project)."""
  376. user_obj = get_user(session, user)
  377. if isinstance(tags, six.string_types):
  378. tags = [tags]
  379. added_tags = []
  380. added_tags_color = []
  381. for objtag in tags:
  382. objtag = objtag.strip()
  383. known = False
  384. for tagobj in obj.tags:
  385. if tagobj.tag == objtag:
  386. known = True
  387. if known:
  388. continue
  389. if obj.isa == "project":
  390. tagobj = get_tag(session, objtag)
  391. if not tagobj:
  392. tagobj = model.Tag(tag=objtag)
  393. session.add(tagobj)
  394. session.flush()
  395. dbobjtag = model.TagProject(project_id=obj.id, tag=tagobj.tag)
  396. else:
  397. tagobj = get_colored_tag(session, objtag, obj.project.id)
  398. if not tagobj:
  399. tagobj = model.TagColored(
  400. tag=objtag, project_id=obj.project.id
  401. )
  402. session.add(tagobj)
  403. session.flush()
  404. if obj.isa == "issue":
  405. dbobjtag = model.TagIssueColored(
  406. issue_uid=obj.uid, tag_id=tagobj.id
  407. )
  408. else:
  409. dbobjtag = model.TagPullRequest(
  410. request_uid=obj.uid, tag_id=tagobj.id
  411. )
  412. added_tags_color.append(tagobj.tag_color)
  413. session.add(dbobjtag)
  414. # Make sure we won't have SQLAlchemy error before we continue
  415. # Commit so the tags show up in the notification sent
  416. session.commit()
  417. added_tags.append(tagobj.tag)
  418. if isinstance(obj, model.Issue):
  419. pagure.lib.git.update_git(obj, repo=obj.project)
  420. if not obj.private:
  421. pagure.lib.notify.log(
  422. obj.project,
  423. topic="issue.tag.added",
  424. msg=dict(
  425. issue=obj.to_json(public=True),
  426. project=obj.project.to_json(public=True),
  427. tags=sorted(added_tags),
  428. agent=user_obj.username,
  429. ),
  430. )
  431. # Send notification for the event-source server
  432. if REDIS and not obj.project.private:
  433. REDIS.publish(
  434. "pagure.%s" % obj.uid,
  435. json.dumps(
  436. {
  437. "added_tags": added_tags,
  438. "added_tags_color": added_tags_color,
  439. }
  440. ),
  441. )
  442. elif isinstance(obj, model.PullRequest):
  443. pagure.lib.git.update_git(obj, repo=obj.project)
  444. if not obj.private:
  445. pagure.lib.notify.log(
  446. obj.project,
  447. topic="pull-request.tag.added",
  448. msg=dict(
  449. pull_request=obj.to_json(public=True),
  450. pullrequest=obj.to_json(public=True),
  451. project=obj.project.to_json(public=True),
  452. tags=sorted(added_tags),
  453. agent=user_obj.username,
  454. ),
  455. )
  456. # Send notification for the event-source server
  457. if REDIS and not obj.project.private:
  458. REDIS.publish(
  459. "pagure.%s" % obj.uid,
  460. json.dumps(
  461. {
  462. "added_tags": added_tags,
  463. "added_tags_color": added_tags_color,
  464. }
  465. ),
  466. )
  467. if added_tags:
  468. return "%s tagged with: %s" % (
  469. obj.isa.capitalize(),
  470. ", ".join(added_tags),
  471. )
  472. else:
  473. return "Nothing to add"
  474. def add_issue_assignee(session, issue, assignee, user, notify=True):
  475. """Add an assignee to an issue, in other words, assigned an issue."""
  476. user_obj = get_user(session, user)
  477. old_assignee = issue.assignee
  478. if not assignee and issue.assignee is not None:
  479. issue.assignee_id = None
  480. issue.last_updated = datetime.datetime.utcnow()
  481. session.add(issue)
  482. session.commit()
  483. pagure.lib.git.update_git(issue, repo=issue.project)
  484. if notify:
  485. pagure.lib.notify.notify_assigned_issue(issue, None, user_obj)
  486. if not issue.private:
  487. pagure.lib.notify.log(
  488. issue.project,
  489. topic="issue.assigned.reset",
  490. msg=dict(
  491. issue=issue.to_json(public=True),
  492. project=issue.project.to_json(public=True),
  493. agent=user_obj.username,
  494. ),
  495. )
  496. # Send notification for the event-source server
  497. if REDIS and not issue.project.private:
  498. REDIS.publish(
  499. "pagure.%s" % issue.uid, json.dumps({"unassigned": "-"})
  500. )
  501. return "Assignee reset"
  502. elif not assignee and issue.assignee is None:
  503. return
  504. old_assignee = issue.assignee
  505. # Validate the assignee
  506. assignee_obj = get_user(session, assignee)
  507. if issue.assignee_id != assignee_obj.id:
  508. issue.assignee_id = assignee_obj.id
  509. session.add(issue)
  510. session.commit()
  511. pagure.lib.git.update_git(issue, repo=issue.project)
  512. if notify:
  513. pagure.lib.notify.notify_assigned_issue(
  514. issue, assignee_obj, user_obj
  515. )
  516. if not issue.private:
  517. pagure.lib.notify.log(
  518. issue.project,
  519. topic="issue.assigned.added",
  520. msg=dict(
  521. issue=issue.to_json(public=True),
  522. project=issue.project.to_json(public=True),
  523. agent=user_obj.username,
  524. ),
  525. )
  526. issue.last_updated = datetime.datetime.utcnow()
  527. # Send notification for the event-source server
  528. if REDIS and not issue.project.private:
  529. REDIS.publish(
  530. "pagure.%s" % issue.uid,
  531. json.dumps({"assigned": assignee_obj.to_json(public=True)}),
  532. )
  533. output = "Issue assigned to %s" % assignee
  534. if old_assignee:
  535. output += " (was: %s)" % old_assignee.username
  536. return output
  537. def add_pull_request_assignee(session, request, assignee, user):
  538. """Add an assignee to a request, in other words, assigned an issue."""
  539. get_user(session, assignee)
  540. user_obj = get_user(session, user)
  541. if assignee is None and request.assignee is not None:
  542. request.assignee_id = None
  543. request.updated_on = datetime.datetime.utcnow()
  544. session.add(request)
  545. session.commit()
  546. pagure.lib.git.update_git(request, repo=request.project)
  547. pagure.lib.notify.notify_assigned_request(request, None, user_obj)
  548. # Deprecated -- this is not consistent in both the topic and the body:
  549. # request vs pull-request (topic) and request vs pullrequest (body)
  550. pagure.lib.notify.log(
  551. request.project,
  552. topic="request.assigned.reset",
  553. msg=dict(
  554. request=request.to_json(public=True),
  555. pullrequest=request.to_json(public=True),
  556. project=request.project.to_json(public=True),
  557. agent=user_obj.username,
  558. ),
  559. )
  560. pagure.lib.notify.log(
  561. request.project,
  562. topic="pull-request.assigned.reset",
  563. msg=dict(
  564. pullrequest=request.to_json(public=True),
  565. project=request.project.to_json(public=True),
  566. agent=user_obj.username,
  567. ),
  568. )
  569. return "Request assignee reset"
  570. elif assignee is None and request.assignee is None:
  571. return
  572. # Validate the assignee
  573. assignee_obj = get_user(session, assignee)
  574. if request.assignee_id != assignee_obj.id:
  575. request.assignee_id = assignee_obj.id
  576. request.updated_on = datetime.datetime.utcnow()
  577. session.add(request)
  578. session.flush()
  579. pagure.lib.git.update_git(request, repo=request.project)
  580. pagure.lib.notify.notify_assigned_request(
  581. request, assignee_obj, user_obj
  582. )
  583. # Deprecated -- this is not consistent in both the topic and the body:
  584. # request vs pull-request (topic) and request vs pullrequest (body)
  585. pagure.lib.notify.log(
  586. request.project,
  587. topic="request.assigned.added",
  588. msg=dict(
  589. request=request.to_json(public=True),
  590. pullrequest=request.to_json(public=True),
  591. project=request.project.to_json(public=True),
  592. agent=user_obj.username,
  593. ),
  594. )
  595. pagure.lib.notify.log(
  596. request.project,
  597. topic="pull-request.assigned.added",
  598. msg=dict(
  599. pullrequest=request.to_json(public=True),
  600. project=request.project.to_json(public=True),
  601. agent=user_obj.username,
  602. ),
  603. )
  604. return "Request assigned"
  605. def add_issue_dependency(session, issue, issue_blocked, user):
  606. """Add a dependency between two issues."""
  607. user_obj = get_user(session, user)
  608. if issue.uid == issue_blocked.uid:
  609. raise pagure.exceptions.PagureException(
  610. "An issue cannot depend on itself"
  611. )
  612. if issue_blocked not in issue.children:
  613. i2i = model.IssueToIssue(
  614. parent_issue_id=issue.uid, child_issue_id=issue_blocked.uid
  615. )
  616. session.add(i2i)
  617. # Make sure we won't have SQLAlchemy error before we continue
  618. # and commit so the blocking issue appears in the JSON representation
  619. session.commit()
  620. pagure.lib.git.update_git(issue, repo=issue.project)
  621. pagure.lib.git.update_git(issue_blocked, repo=issue_blocked.project)
  622. if not issue.private:
  623. pagure.lib.notify.log(
  624. issue.project,
  625. topic="issue.dependency.added",
  626. msg=dict(
  627. issue=issue.to_json(public=True),
  628. project=issue.project.to_json(public=True),
  629. added_dependency=issue_blocked.id,
  630. agent=user_obj.username,
  631. ),
  632. )
  633. # Send notification for the event-source server
  634. if REDIS and not issue.project.private:
  635. REDIS.publish(
  636. "pagure.%s" % issue.uid,
  637. json.dumps(
  638. {
  639. "added_dependency": issue_blocked.id,
  640. "issue_uid": issue.uid,
  641. "type": "children",
  642. }
  643. ),
  644. )
  645. REDIS.publish(
  646. "pagure.%s" % issue_blocked.uid,
  647. json.dumps(
  648. {
  649. "added_dependency": issue.id,
  650. "issue_uid": issue_blocked.uid,
  651. "type": "parent",
  652. }
  653. ),
  654. )
  655. return "Issue marked as depending on: #%s" % issue_blocked.id
  656. def remove_issue_dependency(session, issue, issue_blocked, user):
  657. """Remove a dependency between two issues."""
  658. user_obj = get_user(session, user)
  659. if issue.uid == issue_blocked.uid:
  660. raise pagure.exceptions.PagureException(
  661. "An issue cannot depend on itself"
  662. )
  663. if issue_blocked in issue.parents:
  664. parent_del = []
  665. for parent in issue.parents:
  666. if parent.uid == issue_blocked.uid:
  667. parent_del.append(parent.id)
  668. issue.parents.remove(parent)
  669. # Make sure we won't have SQLAlchemy error before we continue
  670. # and commit so the blocking issue appears in the JSON representation
  671. session.commit()
  672. pagure.lib.git.update_git(issue, repo=issue.project)
  673. pagure.lib.git.update_git(issue_blocked, repo=issue_blocked.project)
  674. if not issue.private:
  675. pagure.lib.notify.log(
  676. issue.project,
  677. topic="issue.dependency.removed",
  678. msg=dict(
  679. issue=issue.to_json(public=True),
  680. project=issue.project.to_json(public=True),
  681. removed_dependency=parent_del,
  682. agent=user_obj.username,
  683. ),
  684. )
  685. # Send notification for the event-source server
  686. if REDIS and not issue.project.private:
  687. REDIS.publish(
  688. "pagure.%s" % issue.uid,
  689. json.dumps(
  690. {
  691. "removed_dependency": parent_del,
  692. "issue_uid": issue.uid,
  693. "type": "children",
  694. }
  695. ),
  696. )
  697. REDIS.publish(
  698. "pagure.%s" % issue_blocked.uid,
  699. json.dumps(
  700. {
  701. "removed_dependency": issue.id,
  702. "issue_uid": issue_blocked.uid,
  703. "type": "parent",
  704. }
  705. ),
  706. )
  707. return "Issue **un**marked as depending on: #%s" % " #".join(
  708. [("%s" % id) for id in parent_del]
  709. )
  710. def remove_tags(session, project, tags, user):
  711. """Removes the specified tag of a project."""
  712. user_obj = get_user(session, user)
  713. if not isinstance(tags, list):
  714. tags = [tags]
  715. issues = search_issues(session, project, closed=False, tags=tags)
  716. issues.extend(search_issues(session, project, closed=True, tags=tags))
  717. msgs = []
  718. removed_tags = []
  719. tag_found = False
  720. for tag in tags:
  721. tagobj = get_colored_tag(session, tag, project.id)
  722. if tagobj:
  723. tag_found = True
  724. removed_tags.append(tag)
  725. msgs.append("Tag: %s has been deleted" % tag)
  726. session.delete(tagobj)
  727. if not tag_found:
  728. raise pagure.exceptions.PagureException(
  729. "Tags not found: %s" % ", ".join(tags)
  730. )
  731. for issue in issues:
  732. for issue_tag in issue.tags:
  733. if issue_tag.tag in tags:
  734. tag = issue_tag.tag
  735. session.delete(issue_tag)
  736. pagure.lib.git.update_git(issue, repo=issue.project)
  737. pagure.lib.notify.log(
  738. project,
  739. topic="project.tag.removed",
  740. msg=dict(
  741. project=project.to_json(public=True),
  742. tags=sorted(removed_tags),
  743. agent=user_obj.username,
  744. ),
  745. )
  746. return msgs
  747. def remove_tags_obj(session, obj, tags, user):
  748. """Removes the specified tag(s) of a given object."""
  749. user_obj = get_user(session, user)
  750. if isinstance(tags, six.string_types):
  751. tags = [tags]
  752. removed_tags = []
  753. if obj.isa == "project":
  754. for objtag in obj.tags:
  755. if objtag.tag in tags:
  756. tag = objtag.tag
  757. removed_tags.append(tag)
  758. session.delete(objtag)
  759. elif obj.isa == "issue":
  760. for objtag in obj.tags_issues_colored:
  761. if objtag.tag.tag in tags:
  762. tag = objtag.tag.tag
  763. removed_tags.append(tag)
  764. session.delete(objtag)
  765. elif obj.isa == "pull-request":
  766. for objtag in obj.tags_pr_colored:
  767. if objtag.tag.tag in tags:
  768. tag = objtag.tag.tag
  769. removed_tags.append(tag)
  770. session.delete(objtag)
  771. # Commit so the tags are updated in the notification sent
  772. session.commit()
  773. if isinstance(obj, model.Issue):
  774. pagure.lib.git.update_git(obj, repo=obj.project)
  775. pagure.lib.notify.log(
  776. obj.project,
  777. topic="issue.tag.removed",
  778. msg=dict(
  779. issue=obj.to_json(public=True),
  780. project=obj.project.to_json(public=True),
  781. tags=sorted(removed_tags),
  782. agent=user_obj.username,
  783. ),
  784. )
  785. # Send notification for the event-source server
  786. if REDIS and not obj.project.private:
  787. REDIS.publish(
  788. "pagure.%s" % obj.uid,
  789. json.dumps({"removed_tags": removed_tags}),
  790. )
  791. elif isinstance(obj, model.PullRequest):
  792. pagure.lib.git.update_git(obj, repo=obj.project)
  793. pagure.lib.notify.log(
  794. obj.project,
  795. topic="pull-request.tag.removed",
  796. msg=dict(
  797. pull_request=obj.to_json(public=True),
  798. pullrequest=obj.to_json(public=True),
  799. project=obj.project.to_json(public=True),
  800. tags=sorted(removed_tags),
  801. agent=user_obj.username,
  802. ),
  803. )
  804. # Send notification for the event-source server
  805. if REDIS and not obj.project.private:
  806. REDIS.publish(
  807. "pagure.%s" % obj.uid,
  808. json.dumps({"removed_tags": removed_tags}),
  809. )
  810. return "%s **un**tagged with: %s" % (
  811. obj.isa.capitalize(),
  812. ", ".join(removed_tags),
  813. )
  814. def edit_issue_tags(
  815. session,
  816. project,
  817. old_tag,
  818. new_tag,
  819. new_tag_description,
  820. new_tag_color,
  821. user,
  822. ):
  823. """Edits the specified tag of a project."""
  824. user_obj = get_user(session, user)
  825. old_tag_name = old_tag
  826. if not isinstance(old_tag, model.TagColored):
  827. old_tag = get_colored_tag(session, old_tag_name, project.id)
  828. if not old_tag:
  829. raise pagure.exceptions.PagureException(
  830. 'No tag "%s" found related to this project' % (old_tag_name)
  831. )
  832. old_tag_name = old_tag.tag
  833. old_tag_description = old_tag.tag_description
  834. old_tag_color = old_tag.tag_color
  835. # check for change
  836. no_change_in_tag = (
  837. old_tag.tag == new_tag
  838. and old_tag_description == new_tag_description
  839. and old_tag_color == new_tag_color
  840. )
  841. if no_change_in_tag:
  842. raise pagure.exceptions.PagureException(
  843. 'No change. Old tag "%s(%s)[%s]" is the same as '
  844. 'new tag "%s(%s)[%s]"'
  845. % (
  846. old_tag,
  847. old_tag_description,
  848. old_tag_color,
  849. new_tag,
  850. new_tag_description,
  851. new_tag_color,
  852. )
  853. )
  854. elif old_tag.tag != new_tag:
  855. # Check if new tag already exists
  856. existing_tag = get_colored_tag(session, new_tag, project.id)
  857. if existing_tag:
  858. raise pagure.exceptions.PagureException(
  859. "Can not rename a tag to an existing tag name: %s" % new_tag
  860. )
  861. session.query(model.TagColored).filter(
  862. model.TagColored.tag == old_tag.tag
  863. ).filter(model.TagColored.project_id == project.id).update(
  864. {
  865. model.TagColored.tag: new_tag,
  866. model.TagColored.tag_description: new_tag_description,
  867. model.TagColored.tag_color: new_tag_color,
  868. }
  869. )
  870. issues = (
  871. session.query(model.Issue)
  872. .filter(model.TagIssueColored.tag_id == old_tag.id)
  873. .filter(model.TagIssueColored.issue_uid == model.Issue.uid)
  874. .all()
  875. )
  876. for issue in issues:
  877. # Update the git version
  878. pagure.lib.git.update_git(issue, repo=issue.project)
  879. msgs = []
  880. msgs.append(
  881. "Edited tag: %s(%s)[%s] to %s(%s)[%s]"
  882. % (
  883. old_tag_name,
  884. old_tag_description,
  885. old_tag_color,
  886. new_tag,
  887. new_tag_description,
  888. new_tag_color,
  889. )
  890. )
  891. pagure.lib.notify.log(
  892. project,
  893. topic="project.tag.edited",
  894. msg=dict(
  895. project=project.to_json(public=True),
  896. old_tag=old_tag.tag,
  897. old_tag_description=old_tag_description,
  898. old_tag_color=old_tag_color,
  899. new_tag=new_tag,
  900. new_tag_description=new_tag_description,
  901. new_tag_color=new_tag_color,
  902. agent=user_obj.username,
  903. ),
  904. )
  905. return msgs
  906. def add_sshkey_to_project_or_user(
  907. session, ssh_key, pushaccess, creator, project=None, user=None
  908. ):
  909. """Add a deploy key to a specified project."""
  910. if project is None and user is None:
  911. raise ValueError(
  912. "SSH Keys need to be added to either a project or a user"
  913. )
  914. if project is not None and user is not None:
  915. raise ValueError("SSH Keys need to be assigned to at least one object")
  916. ssh_key = ssh_key.strip()
  917. if "\n" in ssh_key:
  918. raise pagure.exceptions.PagureException("Please add single SSH keys.")
  919. ssh_short_key = is_valid_ssh_key(ssh_key)
  920. if ssh_short_key in [None, False]:
  921. raise pagure.exceptions.PagureException("SSH key invalid.")
  922. # We are sure that this only contains a single key, but ssh-keygen still
  923. # returns a \n at the end
  924. ssh_short_key = ssh_short_key.strip()
  925. if "\n" in ssh_key:
  926. raise pagure.exceptions.PagureException(
  927. "SSH has misbehaved when analyzing the SSH key"
  928. )
  929. # Make sure that this key is not an SSH key for another project or user.
  930. # If we dupe keys, we can't really know who this is for.
  931. ssh_search_key = ssh_short_key.split(" ")[1]
  932. if (
  933. session.query(model.SSHKey)
  934. .filter(model.SSHKey.ssh_search_key == ssh_search_key)
  935. .count()
  936. != 0
  937. ):
  938. raise pagure.exceptions.PagureException("SSH key already exists.")
  939. new_key_obj = model.SSHKey(
  940. pushaccess=pushaccess,
  941. public_ssh_key=ssh_key,
  942. ssh_short_key=ssh_short_key,
  943. ssh_search_key=ssh_search_key,
  944. creator_user_id=creator.id,
  945. )
  946. if project:
  947. new_key_obj.project = project
  948. if user:
  949. new_key_obj.user_id = user.id
  950. session.add(new_key_obj)
  951. # Make sure we won't have SQLAlchemy error before we continue
  952. session.flush()
  953. # We do not send any notifications on purpose
  954. return "SSH key added"
  955. def add_user_to_project(
  956. session,
  957. project,
  958. new_user,
  959. user,
  960. access="admin",
  961. branches=None,
  962. required_groups=None,
  963. ):
  964. """Add a specified user to a specified project with a specified access"""
  965. new_user_obj = get_user(session, new_user)
  966. if required_groups and access != "ticket":
  967. for key in required_groups:
  968. if fnmatch.fnmatch(project.fullname, key):
  969. user_grps = set(new_user_obj.groups)
  970. req_grps = set(required_groups[key])
  971. if not user_grps.intersection(req_grps):
  972. raise pagure.exceptions.PagureException(
  973. "This user must be in one of the following groups "
  974. "to be allowed to be added to this project: %s"
  975. % ", ".join(req_grps)
  976. )
  977. user_obj = get_user(session, user)
  978. users = set(
  979. [
  980. user_.user
  981. for user_ in project.get_project_users(access, combine=False)
  982. ]
  983. )
  984. users.add(project.user.user)
  985. if new_user in users and access != "collaborator":
  986. raise pagure.exceptions.PagureException(
  987. "This user is already listed on this project with the same access"
  988. )
  989. # Reset the branches to None if the user isn't a collaborator
  990. if access != "collaborator":
  991. branches = None
  992. # user has some access on project, so update to new access
  993. if new_user_obj in project.users:
  994. access_obj = get_obj_access(session, project, new_user_obj)
  995. access_obj.access = access
  996. access_obj.branches = branches
  997. project.date_modified = datetime.datetime.utcnow()
  998. update_read_only_mode(session, project, read_only=True)
  999. session.add(access_obj)
  1000. session.add(project)
  1001. session.commit()
  1002. pagure.lib.notify.log(
  1003. project,
  1004. topic="project.user.access.updated",
  1005. msg=dict(
  1006. project=project.to_json(public=True),
  1007. new_user=new_user_obj.username,
  1008. new_access=access,
  1009. new_branches=branches,
  1010. agent=user_obj.username,
  1011. ),
  1012. )
  1013. return "User access updated"
  1014. project_user = model.ProjectUser(
  1015. project_id=project.id,
  1016. user_id=new_user_obj.id,
  1017. access=access,
  1018. branches=branches,
  1019. )
  1020. project.date_modified = datetime.datetime.utcnow()
  1021. session.add(project_user)
  1022. # Mark the project as read only, celery will then unmark it
  1023. update_read_only_mode(session, project, read_only=True)
  1024. session.add(project)
  1025. # Commit so the JSON sent in the notification is up to date
  1026. session.commit()
  1027. pagure.lib.notify.log(
  1028. project,
  1029. topic="project.user.added",
  1030. msg=dict(
  1031. project=project.to_json(public=True),
  1032. new_user=new_user_obj.username,
  1033. access=access,
  1034. branches=branches,
  1035. agent=user_obj.username,
  1036. ),
  1037. )
  1038. return "User added"
  1039. def add_group_to_project(
  1040. session,
  1041. project,
  1042. new_group,
  1043. user,
  1044. access="admin",
  1045. branches=None,
  1046. create=False,
  1047. is_admin=False,
  1048. ):
  1049. """Add a specified group to a specified project with some access"""
  1050. user_obj = search_user(session, username=user)
  1051. if not user_obj:
  1052. raise pagure.exceptions.PagureException("No user %s found." % user)
  1053. group_obj = search_groups(session, group_name=new_group)
  1054. if not group_obj:
  1055. if create:
  1056. group_obj = pagure.lib.model.PagureGroup(
  1057. group_name=new_group,
  1058. display_name=new_group,
  1059. group_type="user",
  1060. user_id=user_obj.id,
  1061. )
  1062. session.add(group_obj)
  1063. session.flush()
  1064. else:
  1065. raise pagure.exceptions.PagureException(
  1066. "No group %s found." % new_group
  1067. )
  1068. if (
  1069. user_obj not in project.users
  1070. and user_obj != project.user
  1071. and not is_admin
  1072. ):
  1073. raise pagure.exceptions.PagureException(
  1074. "You are not allowed to add a group of users to this project"
  1075. )
  1076. groups = set(
  1077. [
  1078. group.group_name
  1079. for group in project.get_project_groups(access, combine=False)
  1080. ]
  1081. )
  1082. if new_group in groups and access != "collaborator":
  1083. raise pagure.exceptions.PagureException(
  1084. "This group already has this access on this project"
  1085. )
  1086. # Reset the branches to None if the group isn't a collaborator
  1087. if access != "collaborator":
  1088. branches = None
  1089. # the group already has some access, update to new access
  1090. if group_obj in project.groups:
  1091. access_obj = get_obj_access(session, project, group_obj)
  1092. access_obj.access = access
  1093. access_obj.branches = branches
  1094. session.add(access_obj)
  1095. project.date_modified = datetime.datetime.utcnow()
  1096. update_read_only_mode(session, project, read_only=True)
  1097. session.add(project)
  1098. # Commit so the JSON sent in the notification is up to date
  1099. session.commit()
  1100. pagure.lib.notify.log(
  1101. project,
  1102. topic="project.group.access.updated",
  1103. msg=dict(
  1104. project=project.to_json(public=True),
  1105. new_group=group_obj.group_name,
  1106. new_access=access,
  1107. new_branches=branches,
  1108. agent=user,
  1109. ),
  1110. )
  1111. return "Group access updated"
  1112. project_group = model.ProjectGroup(
  1113. project_id=project.id,
  1114. group_id=group_obj.id,
  1115. access=access,
  1116. branches=branches,
  1117. )
  1118. session.add(project_group)
  1119. # Make sure we won't have SQLAlchemy error before we continue
  1120. project.date_modified = datetime.datetime.utcnow()
  1121. # Mark the project read_only, celery will then unmark it
  1122. update_read_only_mode(session, project, read_only=True)
  1123. session.add(project)
  1124. # Commit so the JSON sent in the notification is up to date
  1125. session.commit()
  1126. pagure.lib.notify.log(
  1127. project,
  1128. topic="project.group.added",
  1129. msg=dict(
  1130. project=project.to_json(public=True),
  1131. new_group=group_obj.group_name,
  1132. access=access,
  1133. branches=branches,
  1134. agent=user,
  1135. ),
  1136. )
  1137. return "Group added"
  1138. def add_pull_request_comment(
  1139. session,
  1140. request,
  1141. commit,
  1142. tree_id,
  1143. filename,
  1144. row,
  1145. comment,
  1146. user,
  1147. notify=True,
  1148. notification=False,
  1149. trigger_ci=None,
  1150. ):
  1151. """Add a comment to a pull-request."""
  1152. user_obj = get_user(session, user)
  1153. pr_comment = model.PullRequestComment(
  1154. pull_request_uid=request.uid,
  1155. commit_id=commit,
  1156. tree_id=tree_id,
  1157. filename=filename,
  1158. line=row,
  1159. comment=comment,
  1160. user_id=user_obj.id,
  1161. notification=notification,
  1162. )
  1163. session.add(pr_comment)
  1164. # Make sure we won't have SQLAlchemy error before we continue
  1165. session.flush()
  1166. request.updated_on = datetime.datetime.utcnow()
  1167. pagure.lib.git.update_git(request, repo=request.project)
  1168. log_action(session, "commented", request, user_obj)
  1169. if notify:
  1170. pagure.lib.notify.notify_pull_request_comment(pr_comment, user_obj)
  1171. # Send notification for the event-source server
  1172. if REDIS and not request.project.private:
  1173. comment_text = text2markdown(pr_comment.comment)
  1174. REDIS.publish(
  1175. "pagure.%s" % request.uid,
  1176. json.dumps(
  1177. {
  1178. "request_id": request.id,
  1179. "comment_added": comment_text,
  1180. "comment_user": pr_comment.user.user,
  1181. "comment_id": pr_comment.id,
  1182. "project": request.project.fullname,
  1183. "avatar_url": avatar_url_from_email(
  1184. pr_comment.user.default_email, size=16
  1185. ),
  1186. "comment_date": pr_comment.date_created.strftime(
  1187. "%Y-%m-%d %H:%M:%S"
  1188. ),
  1189. "commit_id": commit,
  1190. "filename": filename,
  1191. "line": row,
  1192. "notification": notification,
  1193. }
  1194. ),
  1195. )
  1196. # Send notification to the CI server, if the comment added was a
  1197. # notification and the PR is still open and project is not private
  1198. ci_hook = pagure.lib.plugins.get_plugin("Pagure CI")
  1199. ci_hook.db_object()
  1200. ci_triggered = False
  1201. if (
  1202. notification
  1203. and request.status == "Open"
  1204. and pagure_config.get("PAGURE_CI_SERVICES")
  1205. and request.project.ci_hook
  1206. and request.project.ci_hook.active_pr
  1207. and not request.project.private
  1208. ):
  1209. pagure.lib.tasks_services.trigger_ci_build.delay(
  1210. pr_uid=request.uid,
  1211. cause=request.id,
  1212. branch=request.branch_from,
  1213. branch_to=request.branch,
  1214. ci_type=request.project.ci_hook.ci_type,
  1215. )
  1216. ci_triggered = True
  1217. pagure.lib.notify.log(
  1218. request.project,
  1219. topic="pull-request.comment.added",
  1220. msg=dict(
  1221. pullrequest=request.to_json(public=True), agent=user_obj.username
  1222. ),
  1223. )
  1224. if (
  1225. not ci_triggered
  1226. and trigger_ci
  1227. and comment.strip().lower() in trigger_ci
  1228. and pagure_config.get("PAGURE_CI_SERVICES")
  1229. and request.project.ci_hook
  1230. and request.project.ci_hook.active_pr
  1231. ):
  1232. pagure.lib.tasks_services.trigger_ci_build.delay(
  1233. pr_uid=request.uid,
  1234. cause=request.id,
  1235. branch=request.branch_from,
  1236. branch_to=request.branch,
  1237. ci_type=request.project.ci_hook.ci_type,
  1238. )
  1239. return "Comment added"
  1240. def edit_comment(session, parent, comment, user, updated_comment):
  1241. """Edit a comment."""
  1242. user_obj = get_user(session, user)
  1243. comment.comment = updated_comment
  1244. comment.edited_on = datetime.datetime.utcnow()
  1245. comment.editor = user_obj
  1246. parent.last_updated = comment.edited_on
  1247. session.add(parent)
  1248. session.add(comment)
  1249. # Make sure we won't have SQLAlchemy error before we continue
  1250. session.flush()
  1251. pagure.lib.git.update_git(parent, repo=parent.project)
  1252. topic = "unknown"
  1253. key = "unknown"
  1254. id_ = "unknown"
  1255. private = False
  1256. if parent.isa == "pull-request":
  1257. topic = "pull-request.comment.edited"
  1258. key = "pullrequest"
  1259. id_ = "request_id"
  1260. elif parent.isa == "issue":
  1261. topic = "issue.comment.edited"
  1262. key = "issue"
  1263. id_ = "issue_id"
  1264. private = parent.private
  1265. if not private:
  1266. pagure.lib.notify.log(
  1267. parent.project,
  1268. topic=topic,
  1269. msg={
  1270. key: parent.to_json(public=True, with_comments=False),
  1271. "project": parent.project.to_json(public=True),
  1272. "comment": comment.to_json(public=True),
  1273. "agent": user_obj.username,
  1274. },
  1275. )
  1276. if REDIS and not parent.project.private:
  1277. if private:
  1278. REDIS.publish(
  1279. "pagure.%s" % comment.parent.uid,
  1280. json.dumps(
  1281. {"comment_updated": "private", "comment_id": comment.id}
  1282. ),
  1283. )
  1284. else:
  1285. REDIS.publish(
  1286. "pagure.%s" % parent.uid,
  1287. json.dumps(
  1288. {
  1289. id_: len(parent.comments),
  1290. "comment_updated": text2markdown(comment.comment),
  1291. "comment_id": comment.id,
  1292. "parent_id": comment.parent.id,
  1293. "comment_editor": user_obj.user,
  1294. "avatar_url": avatar_url_from_email(
  1295. comment.user.default_email, size=16
  1296. ),
  1297. "comment_date": comment.edited_on.strftime(
  1298. "%Y-%m-%d %H:%M:%S"
  1299. ),
  1300. }
  1301. ),
  1302. )
  1303. return "Comment updated"
  1304. def add_pull_request_flag(
  1305. session, request, username, percent, comment, url, status, uid, user, token
  1306. ):
  1307. """Add a flag to a pull-request."""
  1308. user_obj = get_user(session, user)
  1309. action, flag_uid = add_commit_flag(
  1310. session=session,
  1311. repo=request.project,
  1312. commit_hash=request.commit_stop,
  1313. username=username,
  1314. status=status,
  1315. percent=percent,
  1316. comment=comment,
  1317. url=url,
  1318. uid=uid,
  1319. user=user,
  1320. token=token,
  1321. )
  1322. action = action.replace("Flag ", "")
  1323. pr_flag = pagure.lib.query.get_commit_flag_by_uid(
  1324. session, request.commit_stop, flag_uid
  1325. )
  1326. if request.project.settings.get("notify_on_pull-request_flag"):
  1327. pagure.lib.notify.notify_pull_request_flag(pr_flag, request, username)
  1328. pagure.lib.git.update_git(request, repo=request.project)
  1329. pagure.lib.notify.log(
  1330. request.project,
  1331. topic="pull-request.flag.%s" % action,
  1332. msg=dict(
  1333. pullrequest=request.to_json(public=True),
  1334. flag=pr_flag.to_json(public=True),
  1335. agent=user_obj.username,
  1336. ),
  1337. )
  1338. return ("Flag %s" % action, pr_flag.uid)
  1339. def add_commit_flag(
  1340. session,
  1341. repo,
  1342. commit_hash,
  1343. username,
  1344. status,
  1345. percent,
  1346. comment,
  1347. url,
  1348. uid,
  1349. user,
  1350. token,
  1351. ):
  1352. """Add a flag to a add_commit_flag."""
  1353. user_obj = get_user(session, user)
  1354. action = "added"
  1355. c_flag = get_commit_flag_by_uid(session, commit_hash, uid)
  1356. if c_flag:
  1357. action = "updated"
  1358. c_flag.comment = comment
  1359. c_flag.percent = percent
  1360. c_flag.status = status
  1361. c_flag.url = url
  1362. else:
  1363. c_flag = model.CommitFlag(
  1364. uid=uid or uuid.uuid4().hex,
  1365. project_id=repo.id,
  1366. commit_hash=commit_hash,
  1367. username=username,
  1368. status=status,
  1369. percent=percent,
  1370. comment=comment,
  1371. url=url,
  1372. user_id=user_obj.id,
  1373. token_id=token,
  1374. )
  1375. session.add(c_flag)
  1376. # Make sure we won't have SQLAlchemy error before we continue
  1377. session.flush()
  1378. if repo.settings.get("notify_on_commit_flag"):
  1379. pagure.lib.notify.notify_commit_flag(c_flag, username)
  1380. pagure.lib.notify.log(
  1381. repo,
  1382. topic="commit.flag.%s" % action,
  1383. msg=dict(
  1384. repo=repo.to_json(public=True),
  1385. flag=c_flag.to_json(public=True),
  1386. agent=user_obj.username,
  1387. ),
  1388. )
  1389. return ("Flag %s" % action, c_flag.uid)
  1390. def get_commit_flag(session, project, commit_hash):
  1391. """Return the commit flags corresponding to the specified git hash
  1392. (commitid) in the specified repository.
  1393. :arg session: the session with which to connect to the database
  1394. :arg repo: the pagure.lib.model.Project object corresponding to the
  1395. project whose commit has been flagged
  1396. :arg commit_hash: the hash of the commit who has been flagged
  1397. :return: list of pagure.lib.model.CommitFlag objects or an empty list
  1398. """
  1399. query = (
  1400. session.query(model.CommitFlag)
  1401. .filter(model.CommitFlag.project_id == project.id)
  1402. .filter(model.CommitFlag.commit_hash == commit_hash)
  1403. ).order_by(model.CommitFlag.date_updated)
  1404. return query.all()
  1405. def new_project(
  1406. session,
  1407. user,
  1408. name,
  1409. blacklist,
  1410. allowed_prefix,
  1411. description=None,
  1412. url=None,
  1413. avatar_email=None,
  1414. parent_id=None,
  1415. add_readme=False,
  1416. mirrored_from=None,
  1417. userobj=None,
  1418. prevent_40_chars=False,
  1419. namespace=None,
  1420. user_ns=False,
  1421. ignore_existing_repo=False,
  1422. private=False,
  1423. default_branch=None,
  1424. ):
  1425. """Create a new project based on the information provided.
  1426. Is an async operation, and returns task ID.
  1427. """
  1428. user_obj = get_user(session, user)
  1429. allowed_prefix = allowed_prefix + [grp for grp in user_obj.groups]
  1430. if user_ns:
  1431. allowed_prefix.append(user)
  1432. if not namespace:
  1433. namespace = user
  1434. if private:
  1435. allowed_prefix.append(user)
  1436. namespace = user
  1437. if namespace and namespace not in allowed_prefix:
  1438. raise pagure.exceptions.PagureException(
  1439. "The namespace of your project must be in the list of allowed "
  1440. "namespaces set by the admins of this pagure instance, or the "
  1441. "name of a group of which you are a member."
  1442. )
  1443. path = name if not namespace else "%s/%s" % (namespace, name)
  1444. matched = any(map(functools.partial(fnmatch.fnmatch, path), blacklist))
  1445. if matched:
  1446. raise pagure.exceptions.ProjectBlackListedException(
  1447. 'No project "%s" are allowed to be created due to potential '
  1448. "conflicts in URLs with pagure itself" % path
  1449. )
  1450. if len(name) == 40 and prevent_40_chars:
  1451. # We must block project with a name <foo>/<bar> where the length
  1452. # of <bar> is exactly 40 characters long as this would otherwise
  1453. # conflict with the old URL schema used for commit that was
  1454. # <foo>/<commit hash>. To keep backward compatibility, we have an
  1455. # endpoint redirecting <foo>/<commit hash> to <foo>/c/<commit hash>
  1456. # available as an option.
  1457. raise pagure.exceptions.PagureException(
  1458. "Your project name cannot have exactly 40 characters after "
  1459. "the `/`"
  1460. )
  1461. # Repo exists in the DB
  1462. repo = _get_project(session, name, namespace=namespace)
  1463. # this is leaking private repos but we're leaking them anyway if we fail
  1464. # to add the requested repo later. Let's be less clear about why :)
  1465. if repo:
  1466. raise pagure.exceptions.RepoExistsException(
  1467. 'It is not possible to create the repo "%s"' % (path)
  1468. )
  1469. project = model.Project(
  1470. name=name,
  1471. namespace=namespace,
  1472. description=description if description else None,
  1473. url=url if url else None,
  1474. avatar_email=avatar_email if avatar_email else None,
  1475. user_id=user_obj.id,
  1476. parent_id=parent_id,
  1477. mirrored_from=mirrored_from,
  1478. private=private,
  1479. hook_token=pagure.lib.login.id_generator(40),
  1480. )
  1481. session.add(project)
  1482. # Flush so that a project ID is generated
  1483. session.flush()
  1484. for ltype in model.ProjectLock.lock_type.type.enums:
  1485. lock = model.ProjectLock(project_id=project.id, lock_type=ltype)
  1486. session.add(lock)
  1487. session.commit()
  1488. # Register creation et al
  1489. log_action(session, "created", project, user_obj)
  1490. pagure.lib.notify.log(
  1491. project,
  1492. topic="project.new",
  1493. msg=dict(
  1494. project=project.to_json(public=True), agent=user_obj.username
  1495. ),
  1496. )
  1497. return pagure.lib.tasks.create_project.delay(
  1498. user_obj.username,
  1499. namespace,
  1500. name,
  1501. add_readme,
  1502. ignore_existing_repo,
  1503. default_branch or pagure_config.get("GIT_DEFAULT_BRANCH"),
  1504. )
  1505. def new_issue(
  1506. session,
  1507. repo,
  1508. title,
  1509. content,
  1510. user,
  1511. issue_id=None,
  1512. issue_uid=None,
  1513. private=False,
  1514. related_prs=[],
  1515. status=None,
  1516. close_status=None,
  1517. notify=True,
  1518. date_created=None,
  1519. milestone=None,
  1520. priority=None,
  1521. assignee=None,
  1522. tags=None,
  1523. ):
  1524. """Create a new issue for the specified repo."""
  1525. user_obj = get_user(session, user)
  1526. # Only store the priority if there is one in the project
  1527. priorities = repo.priorities or []
  1528. try:
  1529. priority = int(priority)
  1530. except (ValueError, TypeError):
  1531. priority = None
  1532. if (
  1533. priorities
  1534. and priority is not None
  1535. and ("%s" % priority) not in priorities
  1536. ):
  1537. raise pagure.exceptions.PagureException(
  1538. "You are trying to create an issue with a priority that does "
  1539. "not exist in the project."
  1540. )
  1541. assignee_id = None
  1542. if assignee is not None:
  1543. assignee_id = get_user(session, assignee).id
  1544. issue = model.Issue(
  1545. id=issue_id or get_next_id(session, repo.id),
  1546. project_id=repo.id,
  1547. title=title,
  1548. content=content,
  1549. priority=priority,
  1550. milestone=milestone,
  1551. assignee_id=assignee_id,
  1552. user_id=user_obj.id,
  1553. uid=issue_uid or uuid.uuid4().hex,
  1554. private=private,
  1555. date_created=date_created,
  1556. )
  1557. if status is not None:
  1558. issue.status = status
  1559. if close_status is not None:
  1560. issue.close_status = close_status
  1561. issue.last_updated = datetime.datetime.utcnow()
  1562. session.add(issue)
  1563. # Make sure we won't have SQLAlchemy error before we create the issue
  1564. session.flush()
  1565. # Add the tags if any are specified
  1566. if tags is not None:
  1567. for lbl in tags:
  1568. tagobj = get_colored_tag(session, lbl, repo.id)
  1569. if not tagobj:
  1570. tagobj = model.TagColored(tag=lbl, project_id=repo.id)
  1571. session.add(tagobj)
  1572. session.flush()
  1573. dbobjtag = model.TagIssueColored(
  1574. issue_uid=issue.uid, tag_id=tagobj.id
  1575. )
  1576. session.add(dbobjtag)
  1577. session.commit()
  1578. pagure.lib.git.update_git(issue, repo=repo)
  1579. log_action(session, "created", issue, user_obj)
  1580. if notify:
  1581. pagure.lib.notify.notify_new_issue(issue, user=user_obj)
  1582. if not private:
  1583. pagure.lib.notify.log(
  1584. issue.project,
  1585. topic="issue.new",
  1586. msg=dict(
  1587. issue=issue.to_json(public=True),
  1588. project=issue.project.to_json(public=True),
  1589. agent=user_obj.username,
  1590. ),
  1591. )
  1592. return issue
  1593. def drop_issue(session, issue, user):
  1594. """Delete a specified issue."""
  1595. user_obj = get_user(session, user)
  1596. repotype = issue.repotype
  1597. uid = issue.uid
  1598. private = issue.private
  1599. session.delete(issue)
  1600. # Make sure we won't have SQLAlchemy error before we create the issue
  1601. session.flush()
  1602. if not private:
  1603. pagure.lib.notify.log(
  1604. issue.project,
  1605. topic="issue.drop",
  1606. msg=dict(
  1607. issue=issue.to_json(public=True),
  1608. project=issue.project.to_json(public=True),
  1609. agent=user_obj.username,
  1610. ),
  1611. )
  1612. session.commit()
  1613. pagure.lib.git.clean_git(issue.project, repotype, uid)
  1614. return issue
  1615. def new_pull_request(
  1616. session,
  1617. branch_from,
  1618. repo_to,
  1619. branch_to,
  1620. title,
  1621. user,
  1622. initial_comment=None,
  1623. allow_rebase=False,
  1624. repo_from=None,
  1625. remote_git=None,
  1626. requestuid=None,
  1627. requestid=None,
  1628. status="Open",
  1629. notify=True,
  1630. commit_start=None,
  1631. commit_stop=None,
  1632. ):
  1633. """Create a new pull request on the specified repo."""
  1634. if not repo_from and not remote_git:
  1635. raise pagure.exceptions.PagureException(
  1636. "Invalid input, you must specify either a local repo or a "
  1637. "remote one"
  1638. )
  1639. user_obj = get_user(session, user)
  1640. request = model.PullRequest(
  1641. id=requestid or get_next_id(session, repo_to.id),
  1642. uid=requestuid or uuid.uuid4().hex,
  1643. project_id=repo_to.id,
  1644. project_id_from=repo_from.id if repo_from else None,
  1645. remote_git=remote_git if remote_git else None,
  1646. branch=branch_to,
  1647. branch_from=branch_from,
  1648. title=title,
  1649. initial_comment=initial_comment or None,
  1650. allow_rebase=allow_rebase,
  1651. user_id=user_obj.id,
  1652. status=status,
  1653. commit_start=commit_start,
  1654. commit_stop=commit_stop,
  1655. )
  1656. request.last_updated = datetime.datetime.utcnow()
  1657. request.updated_on = datetime.datetime.utcnow()
  1658. session.add(request)
  1659. # Link the PR to issue(s) if there is such link
  1660. link_pr_to_issue_on_description(session, request)
  1661. # Make sure we won't have SQLAlchemy error before we create the request
  1662. session.flush()
  1663. pagure.lib.git.update_git(request, repo=request.project)
  1664. pagure.lib.tasks.link_pr_to_ticket.delay(request.uid)
  1665. log_action(session, "created", request, user_obj)
  1666. if notify:
  1667. pagure.lib.notify.notify_new_pull_request(request)
  1668. pagure.lib.notify.log(
  1669. request.project,
  1670. topic="pull-request.new",
  1671. msg=dict(
  1672. pullrequest=request.to_json(public=True), agent=user_obj.username
  1673. ),
  1674. )
  1675. # Send notification to the CI server
  1676. ci_hook = pagure.lib.plugins.get_plugin("Pagure CI")
  1677. ci_hook.db_object()
  1678. if (
  1679. pagure_config.get("PAGURE_CI_SERVICES")
  1680. and request.project.ci_hook
  1681. and request.project.ci_hook.active_pr
  1682. and not request.project.private
  1683. ):
  1684. pagure.lib.tasks_services.trigger_ci_build.delay(
  1685. pr_uid=request.uid,
  1686. cause=request.id,
  1687. branch=request.branch_from,
  1688. branch_to=request.branch,
  1689. ci_type=request.project.ci_hook.ci_type,
  1690. )
  1691. # Create the ref from the start
  1692. pagure.lib.tasks.sync_pull_ref.delay(
  1693. request.project.name,
  1694. request.project.namespace,
  1695. request.project.user.username if request.project.is_fork else None,
  1696. request.id,
  1697. )
  1698. return request
  1699. def link_pr_to_issue_on_description(session, request):
  1700. """Link the given request to issues it may be referring to in its
  1701. description if there is a description and such link in it.
  1702. """
  1703. _log.debug("Drop the existing relations")
  1704. # Drop the existing initial_comment_pr-based relations
  1705. session.query(model.PrToIssue).filter(
  1706. model.PrToIssue.pull_request_uid == request.uid
  1707. ).filter(model.PrToIssue.origin == "initial_comment_pr").delete(
  1708. synchronize_session="fetch"
  1709. )
  1710. # Rebuild the relations from the initial comment
  1711. if request.initial_comment:
  1712. _log.debug("Checking the initial comment for relations")
  1713. for line in request.initial_comment.split("\n"):
  1714. for issue in pagure.lib.link.get_relation(
  1715. session,
  1716. request.project.name,
  1717. request.project.user.user if request.project.is_fork else None,
  1718. request.project.namespace,
  1719. line,
  1720. "fixes",
  1721. include_prs=False,
  1722. ):
  1723. _log.debug(
  1724. "Link (fix) request %s to issue: %s (project: %s)"
  1725. % (request.id, issue.id, request.project.fullname)
  1726. )
  1727. pagure.lib.query.link_pr_issue(
  1728. session, issue, request, origin="initial_comment_pr"
  1729. )
  1730. for issue in pagure.lib.link.get_relation(
  1731. session,
  1732. request.project.name,
  1733. request.project.user.user if request.project.is_fork else None,
  1734. request.project.namespace,
  1735. line,
  1736. "relates",
  1737. include_prs=False,
  1738. ):
  1739. _log.debug(
  1740. "Link (relate) request %s to issue: %s (project: %s)"
  1741. % (request.id, issue.id, request.project.fullname)
  1742. )
  1743. pagure.lib.query.link_pr_issue(
  1744. session, issue, request, origin="initial_comment_pr"
  1745. )
  1746. else:
  1747. _log.debug("No initial comment, no need to continue")
  1748. def new_tag(session, tag_name, tag_description, tag_color, project_id):
  1749. """Return a new tag object"""
  1750. tagobj = model.TagColored(
  1751. tag=tag_name,
  1752. tag_description=tag_description,
  1753. tag_color=tag_color,
  1754. project_id=project_id,
  1755. )
  1756. session.add(tagobj)
  1757. session.flush()
  1758. return tagobj
  1759. def edit_issue(
  1760. session,
  1761. issue,
  1762. user,
  1763. repo=None,
  1764. title=None,
  1765. content=None,
  1766. status=None,
  1767. close_status=Unspecified,
  1768. priority=Unspecified,
  1769. milestone=Unspecified,
  1770. private=None,
  1771. ):
  1772. """Edit the specified issue.
  1773. :arg session: the session to use to connect to the database.
  1774. :arg issue: the pagure.lib.model.Issue object to edit.
  1775. :arg user: the username of the user editing the issue,
  1776. :kwarg repo: somehow this isn't used anywhere here...
  1777. :kwarg title: the new title of the issue if it's being changed
  1778. :kwarg content: the new content of the issue if it's being changed
  1779. :kwarg status: the new status of the issue if it's being changed
  1780. :kwarg close_status: the new close_status of the issue if it's being
  1781. changed
  1782. :kwarg priority: the new priority of the issue if it's being changed
  1783. :kwarg milestone: the new milestone of the issue if it's being changed
  1784. :kwarg private: the new private of the issue if it's being changed
  1785. """
  1786. user_obj = get_user(session, user)
  1787. if status and status != "Open" and issue.parents:
  1788. for parent in issue.parents:
  1789. if parent.status == "Open":
  1790. raise pagure.exceptions.PagureException(
  1791. "You cannot close a ticket that has ticket "
  1792. "depending that are still open."
  1793. )
  1794. edit = []
  1795. messages = []
  1796. if title and title != issue.title:
  1797. issue.title = title
  1798. edit.append("title")
  1799. if content and content != issue.content:
  1800. issue.content = content
  1801. edit.append("content")
  1802. if status and status != issue.status:
  1803. old_status = issue.status
  1804. issue.status = status
  1805. if status.lower() != "open":
  1806. issue.closed_at = datetime.datetime.utcnow()
  1807. issue.closed_by_id = user_obj.id
  1808. elif issue.close_status:
  1809. issue.close_status = None
  1810. close_status = Unspecified
  1811. edit.append("close_status")
  1812. edit.append("status")
  1813. messages.append(
  1814. "Issue status updated to: %s (was: %s)" % (status, old_status)
  1815. )
  1816. if close_status != Unspecified and close_status != issue.close_status:
  1817. old_status = issue.close_status
  1818. issue.close_status = close_status
  1819. edit.append("close_status")
  1820. msg = "Issue close_status updated to: %s" % close_status
  1821. if old_status:
  1822. msg += " (was: %s)" % old_status
  1823. if issue.status.lower() == "open" and close_status:
  1824. issue.status = "Closed"
  1825. issue.closed_at = datetime.datetime.utcnow()
  1826. edit.append("status")
  1827. messages.append(msg)
  1828. if priority != Unspecified:
  1829. priorities = issue.project.priorities
  1830. try:
  1831. priority = int(priority)
  1832. except (ValueError, TypeError):
  1833. priority = None
  1834. priority_string = "%s" % priority
  1835. if priority_string not in priorities:
  1836. priority = None
  1837. if priority != issue.priority:
  1838. old_priority = issue.priority
  1839. issue.priority = priority
  1840. edit.append("priority")
  1841. msg = "Issue priority set to: %s" % (
  1842. priorities[priority_string] if priority else None
  1843. )
  1844. if old_priority:
  1845. msg += " (was: %s)" % priorities.get(
  1846. "%s" % old_priority, old_priority
  1847. )
  1848. messages.append(msg)
  1849. if private in [True, False] and private != issue.private:
  1850. old_private = issue.private
  1851. issue.private = private
  1852. edit.append("private")
  1853. msg = "Issue private status set to: %s" % private
  1854. if old_private:
  1855. msg += " (was: %s)" % old_private
  1856. messages.append(msg)
  1857. if milestone != Unspecified and milestone != issue.milestone:
  1858. old_milestone = issue.milestone
  1859. issue.milestone = milestone
  1860. edit.append("milestone")
  1861. msg = "Issue set to the milestone: %s" % milestone
  1862. if old_milestone:
  1863. msg += " (was: %s)" % old_milestone
  1864. messages.append(msg)
  1865. issue.last_updated = datetime.datetime.utcnow()
  1866. # uniquify the list of edited fields
  1867. edit = list(set(edit))
  1868. pagure.lib.git.update_git(issue, repo=issue.project)
  1869. if "status" in edit:
  1870. log_action(session, issue.status.lower(), issue, user_obj)
  1871. pagure.lib.notify.notify_status_change_issue(issue, user_obj)
  1872. if not issue.private and edit:
  1873. pagure.lib.notify.log(
  1874. issue.project,
  1875. topic="issue.edit",
  1876. msg=dict(
  1877. issue=issue.to_json(public=True),
  1878. project=issue.project.to_json(public=True),
  1879. fields=sorted(set(edit)),
  1880. agent=user_obj.username,
  1881. ),
  1882. )
  1883. if REDIS and edit and not issue.project.private:
  1884. if issue.private:
  1885. REDIS.publish(
  1886. "pagure.%s" % issue.uid,
  1887. json.dumps({"issue": "private", "fields": edit}),
  1888. )
  1889. else:
  1890. REDIS.publish(
  1891. "pagure.%s" % issue.uid,
  1892. json.dumps(
  1893. {
  1894. "fields": edit,
  1895. "issue": issue.to_json(
  1896. public=True, with_comments=False
  1897. ),
  1898. "priorities": issue.project.priorities,
  1899. "content_updated": text2markdown(issue.content),
  1900. }
  1901. ),
  1902. )
  1903. if edit:
  1904. session.add(issue)
  1905. session.flush()
  1906. return messages
  1907. def update_project_settings(session, repo, settings, user, from_api=False):
  1908. """Update the settings of a project.
  1909. If from_api is true, all values that are not specified will be changed
  1910. back to their default value.
  1911. Otherwise, if from_api is False, all non-specified values are assumed
  1912. to be set to ``False`` or ``None``.
  1913. """
  1914. user_obj = get_user(session, user)
  1915. update = []
  1916. new_settings = repo.settings
  1917. for key in new_settings:
  1918. if key in settings:
  1919. if key == "Minimum_score_to_merge_pull-request":
  1920. try:
  1921. settings[key] = int(settings[key]) if settings[key] else -1
  1922. except (ValueError, TypeError):
  1923. raise pagure.exceptions.PagureException(
  1924. "Please enter a numeric value for the 'minimum "
  1925. "score to merge pull request' field."
  1926. )
  1927. elif key == "Web-hooks":
  1928. settings[key] = settings[key] or None
  1929. else:
  1930. # All the remaining keys are boolean, so True is provided
  1931. # as 'y' by the html, let's convert it back
  1932. settings[key] = settings[key] in ["y", True]
  1933. if new_settings[key] != settings[key]:
  1934. update.append(key)
  1935. new_settings[key] = settings[key]
  1936. else:
  1937. if from_api:
  1938. val = new_settings[key]
  1939. else:
  1940. val = False
  1941. if key == "Web-hooks":
  1942. val = None
  1943. # Ensure the default value is different from what is stored.
  1944. if new_settings[key] != val:
  1945. update.append(key)
  1946. new_settings[key] = val
  1947. if not update:
  1948. return "No settings to change"
  1949. else:
  1950. repo.settings = new_settings
  1951. repo.date_modified = datetime.datetime.utcnow()
  1952. session.add(repo)
  1953. session.flush()
  1954. pagure.lib.notify.log(
  1955. repo,
  1956. topic="project.edit",
  1957. msg=dict(
  1958. project=repo.to_json(public=True),
  1959. fields=sorted(update),
  1960. agent=user_obj.username,
  1961. ),
  1962. )
  1963. if "pull_request_access_only" in update:
  1964. update_read_only_mode(session, repo, read_only=True)
  1965. session.add(repo)
  1966. session.flush()
  1967. pagure.lib.git.generate_gitolite_acls(project=repo)
  1968. return "Edited successfully settings of repo: %s" % repo.fullname
  1969. def update_user_settings(session, settings, user):
  1970. """Update the settings of a project."""
  1971. user_obj = get_user(session, user)
  1972. update = []
  1973. new_settings = user_obj.settings
  1974. for key in new_settings:
  1975. if key in settings:
  1976. if new_settings[key] != settings[key]:
  1977. update.append(key)
  1978. new_settings[key] = settings[key]
  1979. else:
  1980. if new_settings[key] is not False:
  1981. update.append(key)
  1982. new_settings[key] = False
  1983. if not update:
  1984. return "No settings to change"
  1985. else:
  1986. user_obj.settings = new_settings
  1987. session.add(user_obj)
  1988. session.flush()
  1989. return "Successfully edited your settings"
  1990. def fork_project(session, user, repo, editbranch=None, editfile=None):
  1991. """Fork a given project into the user's forks."""
  1992. if _get_project(session, repo.name, user, repo.namespace) is not None:
  1993. raise pagure.exceptions.RepoExistsException(
  1994. 'Repo "forks/%s/%s" already exists' % (user, repo.name)
  1995. )
  1996. user_obj = get_user(session, user)
  1997. project = model.Project(
  1998. name=repo.name,
  1999. namespace=repo.namespace,
  2000. description=repo.description,
  2001. private=repo.private,
  2002. user_id=user_obj.id,
  2003. parent_id=repo.id,
  2004. is_fork=True,
  2005. hook_token=pagure.lib.login.id_generator(40),
  2006. )
  2007. # disable issues, PRs in the fork by default
  2008. default_repo_settings = project.settings
  2009. default_repo_settings["issue_tracker"] = False
  2010. default_repo_settings["pull_requests"] = False
  2011. project.settings = default_repo_settings
  2012. session.add(project)
  2013. # Make sure we won't have SQLAlchemy error before we create the repo
  2014. session.flush()
  2015. session.commit()
  2016. task = pagure.lib.tasks.fork.delay(
  2017. repo.name,
  2018. repo.namespace,
  2019. repo.user.username if repo.is_fork else None,
  2020. user,
  2021. editbranch,
  2022. editfile,
  2023. )
  2024. return task
  2025. def search_projects(
  2026. session,
  2027. username=None,
  2028. fork=None,
  2029. tags=None,
  2030. namespace=None,
  2031. pattern=None,
  2032. start=None,
  2033. limit=None,
  2034. count=False,
  2035. sort=None,
  2036. exclude_groups=None,
  2037. private=None,
  2038. owner=None,
  2039. ):
  2040. """List existing projects"""
  2041. projects = session.query(sqlalchemy.distinct(model.Project.id))
  2042. if owner is not None and username is not None:
  2043. raise RuntimeError(
  2044. "You cannot supply both a username and an owner "
  2045. "as parameters in the `search_projects` function"
  2046. )
  2047. elif owner is not None:
  2048. if owner.startswith("!"):
  2049. projects = projects.join(model.User).filter(
  2050. model.User.user != owner[1:]
  2051. )
  2052. else:
  2053. projects = projects.join(model.User).filter(
  2054. model.User.user == owner
  2055. )
  2056. elif username is not None:
  2057. projects = projects.filter(
  2058. # User created the project
  2059. sqlalchemy.and_(
  2060. model.User.user == username,
  2061. model.User.id == model.Project.user_id,
  2062. )
  2063. )
  2064. sub_q2 = session.query(model.Project.id).filter(
  2065. # User got admin or commit right
  2066. sqlalchemy.and_(
  2067. model.User.user == username,
  2068. model.User.id == model.ProjectUser.user_id,
  2069. model.ProjectUser.project_id == model.Project.id,
  2070. sqlalchemy.or_(
  2071. model.ProjectUser.access == "admin",
  2072. model.ProjectUser.access == "commit",
  2073. model.ProjectUser.access == "collaborator",
  2074. ),
  2075. )
  2076. )
  2077. sub_q3 = session.query(model.Project.id).filter(
  2078. # User created a group that has admin or commit right
  2079. sqlalchemy.and_(
  2080. model.User.user == username,
  2081. model.PagureGroup.user_id == model.User.id,
  2082. model.PagureGroup.group_type == "user",
  2083. model.PagureGroup.id == model.ProjectGroup.group_id,
  2084. model.Project.id == model.ProjectGroup.project_id,
  2085. sqlalchemy.or_(
  2086. model.ProjectGroup.access == "admin",
  2087. model.ProjectGroup.access == "commit",
  2088. model.ProjectGroup.access == "collaborator",
  2089. ),
  2090. )
  2091. )
  2092. sub_q4 = session.query(model.Project.id).filter(
  2093. # User is part of a group that has admin or commit right
  2094. sqlalchemy.and_(
  2095. model.User.user == username,
  2096. model.PagureUserGroup.user_id == model.User.id,
  2097. model.PagureUserGroup.group_id == model.PagureGroup.id,
  2098. model.PagureGroup.group_type == "user",
  2099. model.PagureGroup.id == model.ProjectGroup.group_id,
  2100. model.Project.id == model.ProjectGroup.project_id,
  2101. sqlalchemy.or_(
  2102. model.ProjectGroup.access == "admin",
  2103. model.ProjectGroup.access == "commit",
  2104. model.ProjectGroup.access == "collaborator",
  2105. ),
  2106. )
  2107. )
  2108. # Exclude projects that the user has accessed via a group that we
  2109. # do not want to include
  2110. if exclude_groups:
  2111. sub_q3 = sub_q3.filter(
  2112. model.PagureGroup.group_name.notin_(exclude_groups)
  2113. )
  2114. sub_q4 = sub_q4.filter(
  2115. model.PagureGroup.group_name.notin_(exclude_groups)
  2116. )
  2117. projects = projects.union(sub_q2).union(sub_q3).union(sub_q4)
  2118. if not private:
  2119. projects = projects.filter(
  2120. model.Project.private == False # noqa: E712
  2121. )
  2122. # No filtering is done if private == username i.e if the owner of the
  2123. # project is viewing the project
  2124. elif isinstance(private, six.string_types) and private != username:
  2125. # All the public repo
  2126. subquery0 = session.query(
  2127. sqlalchemy.distinct(model.Project.id)
  2128. ).filter(
  2129. model.Project.private == False # noqa: E712
  2130. )
  2131. sub_q1 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  2132. sqlalchemy.and_(
  2133. model.Project.private == True, # noqa: E712
  2134. model.User.id == model.Project.user_id,
  2135. model.User.user == private,
  2136. )
  2137. )
  2138. sub_q2 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  2139. # User got admin or commit right
  2140. sqlalchemy.and_(
  2141. model.Project.private == True, # noqa: E712
  2142. model.User.user == private,
  2143. model.User.id == model.ProjectUser.user_id,
  2144. model.ProjectUser.project_id == model.Project.id,
  2145. sqlalchemy.or_(
  2146. model.ProjectUser.access == "admin",
  2147. model.ProjectUser.access == "commit",
  2148. model.ProjectUser.access == "collaborator",
  2149. ),
  2150. )
  2151. )
  2152. sub_q3 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  2153. # User created a group that has admin or commit right
  2154. sqlalchemy.and_(
  2155. model.Project.private == True, # noqa: E712
  2156. model.User.user == private,
  2157. model.PagureGroup.user_id == model.User.id,
  2158. model.PagureGroup.group_type == "user",
  2159. model.PagureGroup.id == model.ProjectGroup.group_id,
  2160. model.Project.id == model.ProjectGroup.project_id,
  2161. sqlalchemy.or_(
  2162. model.ProjectGroup.access == "admin",
  2163. model.ProjectGroup.access == "commit",
  2164. model.ProjectGroup.access == "collaborator",
  2165. ),
  2166. )
  2167. )
  2168. sub_q4 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  2169. # User is part of a group that has admin or commit right
  2170. sqlalchemy.and_(
  2171. model.Project.private == True, # noqa: E712
  2172. model.User.user == private,
  2173. model.PagureUserGroup.user_id == model.User.id,
  2174. model.PagureUserGroup.group_id == model.PagureGroup.id,
  2175. model.PagureGroup.group_type == "user",
  2176. model.PagureGroup.id == model.ProjectGroup.group_id,
  2177. model.Project.id == model.ProjectGroup.project_id,
  2178. sqlalchemy.or_(
  2179. model.ProjectGroup.access == "admin",
  2180. model.ProjectGroup.access == "commit",
  2181. model.ProjectGroup.access == "collaborator",
  2182. ),
  2183. )
  2184. )
  2185. # Exclude projects that the user has accessed via a group that we
  2186. # do not want to include
  2187. if exclude_groups:
  2188. sub_q3 = sub_q3.filter(
  2189. model.PagureGroup.group_name.notin_(exclude_groups)
  2190. )
  2191. sub_q4 = sub_q4.filter(
  2192. model.PagureGroup.group_name.notin_(exclude_groups)
  2193. )
  2194. private_repo_subq = (
  2195. subquery0.union(sub_q1).union(sub_q2).union(sub_q3).union(sub_q4)
  2196. )
  2197. # There is something going on here, we shouldn't have to invoke/call
  2198. # the sub-query, it should work fine with:
  2199. # model.Project.id.in_(private_repo_subq.subquery())
  2200. # however, it does not. Either something gets really confused with
  2201. # sqlite or the generated SQL is broken
  2202. # The issues seems to be with the unions in the subquery just above.
  2203. # Since we can't quite get this to work, let's bite the bullet and go
  2204. # with this approach, but damn I don't like it!
  2205. # This issue appeared with sqlalchemy 1.3.0 and is still present in
  2206. # 1.3.13 tested today.
  2207. private_repos = private_repo_subq.all()
  2208. if private_repos:
  2209. projects = projects.filter(
  2210. model.Project.id.in_(list(set(zip(*private_repos)))[0])
  2211. )
  2212. if fork is not None:
  2213. if fork is True:
  2214. projects = projects.filter(
  2215. model.Project.is_fork == True # noqa: E712
  2216. )
  2217. elif fork is False:
  2218. projects = projects.filter(
  2219. model.Project.is_fork == False # noqa: E712
  2220. )
  2221. if tags:
  2222. if not isinstance(tags, (list, tuple)):
  2223. tags = [tags]
  2224. projects = projects.filter(
  2225. model.Project.id == model.TagProject.project_id
  2226. ).filter(model.TagProject.tag.in_(tags))
  2227. if pattern:
  2228. pattern = pattern.replace("*", "%")
  2229. if "%" in pattern:
  2230. projects = projects.filter(model.Project.name.ilike(pattern))
  2231. else:
  2232. projects = projects.filter(model.Project.name == pattern)
  2233. if namespace:
  2234. projects = projects.filter(model.Project.namespace == namespace)
  2235. query = session.query(model.Project).filter(
  2236. model.Project.id.in_(projects.as_scalar())
  2237. )
  2238. if sort == "latest":
  2239. query = query.order_by(model.Project.date_created.desc())
  2240. elif sort == "oldest":
  2241. query = query.order_by(model.Project.date_created.asc())
  2242. else:
  2243. query = query.order_by(asc(func.lower(model.Project.name)))
  2244. if start is not None:
  2245. query = query.offset(start)
  2246. if limit is not None:
  2247. query = query.limit(limit)
  2248. if count:
  2249. return query.count()
  2250. else:
  2251. return query.all()
  2252. def list_users_projects(
  2253. session,
  2254. username,
  2255. fork=None,
  2256. tags=None,
  2257. namespace=None,
  2258. pattern=None,
  2259. start=None,
  2260. limit=None,
  2261. count=False,
  2262. sort=None,
  2263. exclude_groups=None,
  2264. private=None,
  2265. acls=None,
  2266. ):
  2267. """List a users projects"""
  2268. projects = session.query(sqlalchemy.distinct(model.Project.id))
  2269. if acls is None:
  2270. acls = ["main admin", "admin", "collaborator", "commit", "ticket"]
  2271. if username is not None:
  2272. projects = projects.filter(
  2273. # User created the project
  2274. sqlalchemy.and_(
  2275. model.User.user == username,
  2276. model.User.id == model.Project.user_id,
  2277. )
  2278. )
  2279. if "main admin" not in acls:
  2280. projects = projects.filter(model.User.id != model.Project.user_id)
  2281. sub_q2 = session.query(model.Project.id).filter(
  2282. # User got admin or commit right
  2283. sqlalchemy.and_(
  2284. model.User.user == username,
  2285. model.User.id == model.ProjectUser.user_id,
  2286. model.ProjectUser.project_id == model.Project.id,
  2287. model.ProjectUser.access.in_(acls),
  2288. )
  2289. )
  2290. sub_q3 = session.query(model.Project.id).filter(
  2291. # User created a group that has admin or commit right
  2292. sqlalchemy.and_(
  2293. model.User.user == username,
  2294. model.PagureGroup.user_id == model.User.id,
  2295. model.PagureGroup.group_type == "user",
  2296. model.PagureGroup.id == model.ProjectGroup.group_id,
  2297. model.Project.id == model.ProjectGroup.project_id,
  2298. model.ProjectGroup.access.in_(acls),
  2299. )
  2300. )
  2301. sub_q4 = session.query(model.Project.id).filter(
  2302. # User is part of a group that has admin or commit right
  2303. sqlalchemy.and_(
  2304. model.User.user == username,
  2305. model.PagureUserGroup.user_id == model.User.id,
  2306. model.PagureUserGroup.group_id == model.PagureGroup.id,
  2307. model.PagureGroup.group_type == "user",
  2308. model.PagureGroup.id == model.ProjectGroup.group_id,
  2309. model.Project.id == model.ProjectGroup.project_id,
  2310. model.ProjectGroup.access.in_(acls),
  2311. )
  2312. )
  2313. # Exclude projects that the user has accessed via a group that we
  2314. # do not want to include
  2315. if exclude_groups:
  2316. sub_q3 = sub_q3.filter(
  2317. model.PagureGroup.group_name.notin_(exclude_groups)
  2318. )
  2319. sub_q4 = sub_q4.filter(
  2320. model.PagureGroup.group_name.notin_(exclude_groups)
  2321. )
  2322. projects = projects.union(sub_q2).union(sub_q3).union(sub_q4)
  2323. if not private:
  2324. projects = projects.filter(
  2325. model.Project.private == False # noqa: E712
  2326. )
  2327. # No filtering is done if private == username i.e if the owner of the
  2328. # project is viewing the project
  2329. elif isinstance(private, six.string_types) and private != username:
  2330. # All the public repo
  2331. subquery0 = session.query(
  2332. sqlalchemy.distinct(model.Project.id)
  2333. ).filter(
  2334. model.Project.private == False # noqa: E712
  2335. )
  2336. sub_q1 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  2337. sqlalchemy.and_(
  2338. model.Project.private == True, # noqa: E712
  2339. model.User.id == model.Project.user_id,
  2340. model.User.user == private,
  2341. )
  2342. )
  2343. sub_q2 = session.query(model.Project.id).filter(
  2344. # User got admin or commit right
  2345. sqlalchemy.and_(
  2346. model.Project.private == True, # noqa: E712
  2347. model.User.user == private,
  2348. model.User.id == model.ProjectUser.user_id,
  2349. model.ProjectUser.project_id == model.Project.id,
  2350. model.ProjectUser.access.in_(acls),
  2351. )
  2352. )
  2353. sub_q3 = session.query(model.Project.id).filter(
  2354. # User created a group that has admin or commit right
  2355. sqlalchemy.and_(
  2356. model.Project.private == True, # noqa: E712
  2357. model.User.user == private,
  2358. model.PagureGroup.user_id == model.User.id,
  2359. model.PagureGroup.group_type == "user",
  2360. model.PagureGroup.id == model.ProjectGroup.group_id,
  2361. model.Project.id == model.ProjectGroup.project_id,
  2362. model.ProjectGroup.access.in_(acls),
  2363. )
  2364. )
  2365. sub_q4 = session.query(model.Project.id).filter(
  2366. # User is part of a group that has admin or commit right
  2367. sqlalchemy.and_(
  2368. model.Project.private == True, # noqa: E712
  2369. model.User.user == private,
  2370. model.PagureUserGroup.user_id == model.User.id,
  2371. model.PagureUserGroup.group_id == model.PagureGroup.id,
  2372. model.PagureGroup.group_type == "user",
  2373. model.PagureGroup.id == model.ProjectGroup.group_id,
  2374. model.Project.id == model.ProjectGroup.project_id,
  2375. model.ProjectGroup.access.in_(acls),
  2376. )
  2377. )
  2378. # Exclude projects that the user has accessed via a group that we
  2379. # do not want to include
  2380. if exclude_groups:
  2381. sub_q3 = sub_q3.filter(
  2382. model.PagureGroup.group_name.notin_(exclude_groups)
  2383. )
  2384. sub_q4 = sub_q4.filter(
  2385. model.PagureGroup.group_name.notin_(exclude_groups)
  2386. )
  2387. projects = projects.filter(
  2388. model.Project.id.in_(
  2389. subquery0.union(sub_q1)
  2390. .union(sub_q2)
  2391. .union(sub_q3)
  2392. .union(sub_q4)
  2393. )
  2394. )
  2395. if fork is not None:
  2396. if fork is True:
  2397. projects = projects.filter(
  2398. model.Project.is_fork == True # noqa: E712
  2399. )
  2400. elif fork is False:
  2401. projects = projects.filter(
  2402. model.Project.is_fork == False # noqa: E712
  2403. )
  2404. if tags:
  2405. if not isinstance(tags, (list, tuple)):
  2406. tags = [tags]
  2407. projects = projects.filter(
  2408. model.Project.id == model.TagProject.project_id
  2409. ).filter(model.TagProject.tag.in_(tags))
  2410. if pattern:
  2411. pattern = pattern.replace("*", "%")
  2412. if "%" in pattern:
  2413. projects = projects.filter(model.Project.name.ilike(pattern))
  2414. else:
  2415. projects = projects.filter(model.Project.name == pattern)
  2416. if namespace:
  2417. projects = projects.filter(model.Project.namespace == namespace)
  2418. query = session.query(model.Project).filter(
  2419. model.Project.id.in_(projects.as_scalar())
  2420. )
  2421. if sort == "latest":
  2422. query = query.order_by(model.Project.date_created.desc())
  2423. elif sort == "oldest":
  2424. query = query.order_by(model.Project.date_created.asc())
  2425. else:
  2426. query = query.order_by(asc(func.lower(model.Project.name)))
  2427. if start is not None:
  2428. query = query.offset(start)
  2429. if limit is not None:
  2430. query = query.limit(limit)
  2431. if count:
  2432. return query.count()
  2433. else:
  2434. return query.all()
  2435. def _get_project(session, name, user=None, namespace=None):
  2436. """Get a project from the database"""
  2437. case = pagure_config.get("CASE_SENSITIVE", False)
  2438. query = session.query(model.Project)
  2439. if not case:
  2440. query = query.filter(func.lower(model.Project.name) == name.lower())
  2441. else:
  2442. query = query.filter(model.Project.name == name)
  2443. if namespace:
  2444. if not case:
  2445. query = query.filter(
  2446. func.lower(model.Project.namespace) == namespace.lower()
  2447. )
  2448. else:
  2449. query = query.filter(model.Project.namespace == namespace)
  2450. else:
  2451. query = query.filter(model.Project.namespace == namespace)
  2452. if user is not None:
  2453. query = (
  2454. query.filter(model.User.user == user)
  2455. .filter(model.User.id == model.Project.user_id)
  2456. .filter(model.Project.is_fork == True) # noqa: E712
  2457. )
  2458. else:
  2459. query = query.filter(model.Project.is_fork == False) # noqa: E712
  2460. try:
  2461. return query.one()
  2462. except sqlalchemy.orm.exc.NoResultFound:
  2463. return None
  2464. def search_issues(
  2465. session,
  2466. repo=None,
  2467. issueid=None,
  2468. issueuid=None,
  2469. status=None,
  2470. closed=False,
  2471. tags=None,
  2472. assignee=None,
  2473. author=None,
  2474. private=None,
  2475. priority=None,
  2476. milestones=None,
  2477. count=False,
  2478. offset=None,
  2479. limit=None,
  2480. search_id=None,
  2481. search_pattern=None,
  2482. search_content=None,
  2483. custom_search=None,
  2484. updated_after=None,
  2485. no_milestones=None,
  2486. created_since=None,
  2487. created_until=None,
  2488. updated_since=None,
  2489. updated_until=None,
  2490. closed_since=None,
  2491. closed_until=None,
  2492. order="desc",
  2493. order_key=None,
  2494. ):
  2495. """Retrieve one or more issues associated to a project with the given
  2496. criterias.
  2497. Watch out that the closed argument is incompatible with the status
  2498. argument. The closed argument will return all the issues whose status
  2499. is not 'Open', otherwise it will return the issues having the specified
  2500. status.
  2501. The `tags` argument can be used to filter the issues returned based on
  2502. a certain tag.
  2503. If the `issueid` argument is specified a single Issue object (or None)
  2504. will be returned instead of a list of Issue objects.
  2505. :arg session: the session to use to connect to the database.
  2506. :arg repo: a Project object to which the issues should be associated
  2507. :type repo: pagure.lib.model.Project
  2508. :kwarg issueid: the identifier of the issue to look for
  2509. :type issueid: int or None
  2510. :kwarg issueuid: the unique identifier of the issue to look for
  2511. :type issueuid: str or None
  2512. :kwarg status: the status of the issue to look for (incompatible with
  2513. the `closed` argument).
  2514. :type status: str or None
  2515. :kwarg closed: a boolean indicating whether the issue to retrieve are
  2516. closed or open (incompatible with the `status` argument).
  2517. :type closed: bool or None
  2518. :kwarg tags: a tag the issue(s) returned should be associated with
  2519. :type tags: str or list(str) or None
  2520. :kwarg assignee: the name of the user assigned to the issues to search
  2521. :type assignee: str or None
  2522. :kwarg author: the name of the user who created the issues to search
  2523. :type author: str or None
  2524. :kwarg private: boolean or string to use to include or exclude private
  2525. tickets. Defaults to False.
  2526. If False: private tickets are excluded
  2527. If None: private tickets are included
  2528. If user name is specified: private tickets reported by that user
  2529. are included.
  2530. :type private: False, None or str
  2531. :kwarg priority: the priority of the issues to search
  2532. :type priority: int or None
  2533. :kwarg milestones: a milestone the issue(s) returned should be
  2534. associated with.
  2535. :type milestones: str or list(str) or None
  2536. :kwarg count: a boolean to specify if the method should return the list
  2537. of Issues or just do a COUNT query.
  2538. :type count: boolean
  2539. :kwarg search_id: an integer to search in issues identifier
  2540. :type search_id: int or None
  2541. :kwarg search_pattern: a string to search in issues title
  2542. :type search_pattern: str or None
  2543. :kwarg search_content: a string to search in the issues comments
  2544. :type search_content: str or None
  2545. :kwarg custom_search: a dictionary of key/values to be used when
  2546. searching issues with a custom key constraint
  2547. :type custom_search: dict or None
  2548. :kwarg updated_after: datetime's date format (e.g. 2016-11-15) used to
  2549. filter issues updated after that date
  2550. :type updated_after: str or None
  2551. :kwarg no_milestones: Request issues that do not have a milestone set yet
  2552. :type None, True, or False
  2553. :kwarg order: Order issues in 'asc' or 'desc' order.
  2554. :type order: None, str
  2555. :kwarg order_key: Order issues by database column
  2556. :type order_key: None, str
  2557. :return: A single Issue object if issueid is specified, a list of Project
  2558. objects otherwise.
  2559. :rtype: Project or [Project]
  2560. """
  2561. query = session.query(sqlalchemy.distinct(model.Issue.uid))
  2562. if repo is not None:
  2563. query = query.filter(model.Issue.project_id == repo.id)
  2564. if updated_after:
  2565. query = query.filter(model.Issue.last_updated >= updated_after)
  2566. if issueid is not None:
  2567. query = query.filter(model.Issue.id == issueid)
  2568. if issueuid is not None:
  2569. query = query.filter(model.Issue.uid == issueuid)
  2570. if status is not None:
  2571. if status in ["Open", "Closed"]:
  2572. query = query.filter(model.Issue.status == status)
  2573. else:
  2574. query = query.filter(model.Issue.close_status == status)
  2575. if closed:
  2576. query = query.filter(model.Issue.status != "Open")
  2577. if priority:
  2578. query = query.filter(model.Issue.priority == priority)
  2579. if tags is not None and tags != []:
  2580. if isinstance(tags, six.string_types):
  2581. tags = [tags]
  2582. notags = []
  2583. ytags = []
  2584. for tag in tags:
  2585. if tag.startswith("!"):
  2586. notags.append(tag[1:])
  2587. else:
  2588. ytags.append(tag)
  2589. if ytags:
  2590. sub_q2 = session.query(sqlalchemy.distinct(model.Issue.uid))
  2591. if repo is not None:
  2592. sub_q2 = sub_q2.filter(model.Issue.project_id == repo.id)
  2593. sub_q2 = (
  2594. sub_q2.filter(
  2595. model.Issue.uid == model.TagIssueColored.issue_uid
  2596. )
  2597. .filter(model.TagIssueColored.tag_id == model.TagColored.id)
  2598. .filter(model.TagColored.tag.in_(ytags))
  2599. )
  2600. if notags:
  2601. sub_q3 = session.query(sqlalchemy.distinct(model.Issue.uid))
  2602. if repo is not None:
  2603. sub_q3 = sub_q3.filter(model.Issue.project_id == repo.id)
  2604. sub_q3 = (
  2605. sub_q3.filter(
  2606. model.Issue.uid == model.TagIssueColored.issue_uid
  2607. )
  2608. .filter(model.TagIssueColored.tag_id == model.TagColored.id)
  2609. .filter(model.TagColored.tag.in_(notags))
  2610. )
  2611. # Adjust the main query based on the parameters specified
  2612. if ytags and not notags:
  2613. query = query.filter(model.Issue.uid.in_(sub_q2))
  2614. elif not ytags and notags:
  2615. query = query.filter(~model.Issue.uid.in_(sub_q3))
  2616. elif ytags and notags:
  2617. final_set = set([i[0] for i in sub_q2.all()]) - set(
  2618. [i[0] for i in sub_q3.all()]
  2619. )
  2620. if final_set:
  2621. query = query.filter(model.Issue.uid.in_(list(final_set)))
  2622. if assignee is not None:
  2623. assignee = "%s" % assignee
  2624. if not pagure.utils.is_true(assignee, ["false", "0", "true", "1"]):
  2625. reverseassignee = False
  2626. if assignee.startswith("!"):
  2627. reverseassignee = True
  2628. assignee = assignee[1:]
  2629. userassignee = (
  2630. session.query(model.User.id)
  2631. .filter(model.User.user == assignee)
  2632. .subquery()
  2633. )
  2634. if reverseassignee:
  2635. sub = session.query(model.Issue.uid).filter(
  2636. model.Issue.assignee_id == userassignee
  2637. )
  2638. query = query.filter(~model.Issue.uid.in_(sub))
  2639. else:
  2640. query = query.filter(model.Issue.assignee_id == userassignee)
  2641. elif pagure.utils.is_true(assignee):
  2642. query = query.filter(model.Issue.assignee_id.isnot(None))
  2643. else:
  2644. query = query.filter(model.Issue.assignee_id.is_(None))
  2645. if author is not None:
  2646. userauthor = (
  2647. session.query(model.User.id)
  2648. .filter(model.User.user == author)
  2649. .subquery()
  2650. )
  2651. query = query.filter(model.Issue.user_id == userauthor)
  2652. if private is False:
  2653. query = query.filter(model.Issue.private == False) # noqa: E712
  2654. elif isinstance(private, six.string_types):
  2655. userprivate = (
  2656. session.query(model.User.id)
  2657. .filter(model.User.user == private)
  2658. .subquery()
  2659. )
  2660. query = query.filter(
  2661. sqlalchemy.or_(
  2662. model.Issue.private == False, # noqa: E712
  2663. sqlalchemy.and_(
  2664. model.Issue.private == True, # noqa: E712
  2665. model.Issue.user_id == userprivate,
  2666. ),
  2667. sqlalchemy.and_(
  2668. model.Issue.private == True, # noqa: E712
  2669. model.Issue.assignee_id == userprivate,
  2670. ),
  2671. )
  2672. )
  2673. if no_milestones and milestones is not None and milestones != []:
  2674. # Asking for issues with no milestone or a specific milestone
  2675. if isinstance(milestones, six.string_types):
  2676. milestones = [milestones]
  2677. query = query.filter(
  2678. (model.Issue.milestone.is_(None))
  2679. | (model.Issue.milestone.in_(milestones))
  2680. )
  2681. elif no_milestones:
  2682. # Asking for issues without a milestone
  2683. query = query.filter(model.Issue.milestone.is_(None))
  2684. elif milestones is not None and milestones != []:
  2685. # Asking for a single specific milestone
  2686. if isinstance(milestones, six.string_types):
  2687. milestones = [milestones]
  2688. query = query.filter(model.Issue.milestone.in_(milestones))
  2689. elif no_milestones is False:
  2690. # Asking for all ticket with a milestone
  2691. query = query.filter(model.Issue.milestone.isnot(None))
  2692. if created_since:
  2693. query = query.filter(model.Issue.date_created >= created_since)
  2694. if created_until:
  2695. query = query.filter(model.Issue.date_created <= created_until)
  2696. if updated_since:
  2697. query = query.filter(model.Issue.last_updated <= updated_since)
  2698. if updated_until:
  2699. query = query.filter(model.Issue.last_updated <= updated_until)
  2700. if closed_since:
  2701. query = query.filter(model.Issue.closed_at <= closed_since)
  2702. if closed_until:
  2703. query = query.filter(model.Issue.closed_at <= closed_until)
  2704. if custom_search:
  2705. constraints = []
  2706. for key in custom_search:
  2707. value = custom_search[key]
  2708. if "*" in value:
  2709. value = value.replace("*", "%")
  2710. constraints.append(
  2711. sqlalchemy.and_(
  2712. model.IssueKeys.name == key,
  2713. model.IssueValues.value.ilike(value),
  2714. )
  2715. )
  2716. else:
  2717. constraints.append(
  2718. sqlalchemy.and_(
  2719. model.IssueKeys.name == key,
  2720. model.IssueValues.value == value,
  2721. )
  2722. )
  2723. if constraints:
  2724. query = query.filter(
  2725. model.Issue.uid == model.IssueValues.issue_uid
  2726. ).filter(model.IssueValues.key_id == model.IssueKeys.id)
  2727. query = query.filter(
  2728. sqlalchemy.or_((const for const in constraints))
  2729. )
  2730. if search_content is not None:
  2731. query = query.outerjoin(model.IssueComment).filter(
  2732. sqlalchemy.or_(
  2733. model.Issue.content.ilike("%%%s%%" % search_content),
  2734. sqlalchemy.and_(
  2735. model.Issue.uid == model.IssueComment.issue_uid,
  2736. model.IssueComment.comment.ilike(
  2737. "%%%s%%" % search_content
  2738. ),
  2739. ),
  2740. )
  2741. )
  2742. query = session.query(model.Issue).filter(
  2743. model.Issue.uid.in_(query.subquery())
  2744. )
  2745. if repo is not None:
  2746. query = query.filter(model.Issue.project_id == repo.id)
  2747. if search_pattern is not None:
  2748. query = query.filter(
  2749. model.Issue.title.ilike("%%%s%%" % search_pattern)
  2750. )
  2751. if search_id is not None:
  2752. query = query.filter(
  2753. cast(model.Issue.id, Text).ilike("%%%s%%" % search_id)
  2754. )
  2755. column = model.Issue.date_created
  2756. if order_key:
  2757. # If we are ordering by assignee, then order by the assignees'
  2758. # usernames
  2759. if order_key == "assignee":
  2760. # We must do a LEFT JOIN on model.Issue.assignee because there are
  2761. # two foreign keys on model.Issue tied to model.User. This tells
  2762. # SQLAlchemy which foreign key on model.User to order on.
  2763. query = query.outerjoin(
  2764. model.User, model.Issue.assignee_id == model.User.id
  2765. )
  2766. column = model.User.user
  2767. # If we are ordering by user, then order by reporters' usernames
  2768. elif order_key == "user":
  2769. # We must do a LEFT JOIN on model.Issue.user because there are
  2770. # two foreign keys on model.Issue tied to model.User. This tells
  2771. # SQLAlchemy which foreign key on model.User to order on.
  2772. query = query.outerjoin(
  2773. model.User, model.Issue.user_id == model.User.id
  2774. )
  2775. column = model.User.user
  2776. elif order_key in model.Issue.__table__.columns.keys():
  2777. column = getattr(model.Issue, order_key)
  2778. if ("%s" % column.type) == "TEXT":
  2779. column = func.lower(column)
  2780. # The priority is sorted differently because it is by weight and the lower
  2781. # the number, the higher the priority
  2782. if (order_key != "priority" and order == "asc") or (
  2783. order_key == "priority" and order == "desc"
  2784. ):
  2785. query = query.order_by(asc(column))
  2786. else:
  2787. query = query.order_by(desc(column))
  2788. if issueid is not None or issueuid is not None:
  2789. output = query.first()
  2790. elif count:
  2791. output = query.count()
  2792. else:
  2793. if offset is not None:
  2794. query = query.offset(offset)
  2795. if limit:
  2796. query = query.limit(limit)
  2797. output = query.all()
  2798. return output
  2799. def get_tags_of_project(session, project, pattern=None):
  2800. """Returns the list of tags associated with the issues of a project."""
  2801. query = (
  2802. session.query(model.TagColored)
  2803. .filter(model.TagColored.tag != "")
  2804. .filter(model.TagColored.project_id == project.id)
  2805. .order_by(model.TagColored.tag)
  2806. )
  2807. if pattern:
  2808. query = query.filter(
  2809. model.TagColored.tag.ilike(pattern.replace("*", "%"))
  2810. )
  2811. return query.all()
  2812. def get_tag(session, tag):
  2813. """Returns a Tag object for the given tag text."""
  2814. query = session.query(model.Tag).filter(model.Tag.tag == tag)
  2815. return query.first()
  2816. def get_colored_tag(session, tag, project_id):
  2817. """Returns a TagColored object for the given tag text."""
  2818. query = (
  2819. session.query(model.TagColored)
  2820. .filter(model.TagColored.tag == tag)
  2821. .filter(model.TagColored.project_id == project_id)
  2822. )
  2823. return query.first()
  2824. def search_pull_requests(
  2825. session,
  2826. requestid=None,
  2827. project_id=None,
  2828. project_id_from=None,
  2829. status=None,
  2830. author=None,
  2831. assignee=None,
  2832. tags=None,
  2833. count=False,
  2834. offset=None,
  2835. limit=None,
  2836. updated_after=None,
  2837. branch_from=None,
  2838. order="desc",
  2839. order_key=None,
  2840. search_pattern=None,
  2841. ):
  2842. """Retrieve the specified pull-requests."""
  2843. query = session.query(model.PullRequest)
  2844. # by default sort request by date_created.
  2845. column = model.PullRequest.date_created
  2846. if order_key == "last_updated":
  2847. # We actually want to order on updated_on and not last_updated
  2848. # https://pagure.io/pagure/issue/4464#comment-624915
  2849. column = model.PullRequest.updated_on
  2850. if requestid:
  2851. query = query.filter(model.PullRequest.id == requestid)
  2852. if updated_after:
  2853. query = query.filter(model.PullRequest.last_updated >= updated_after)
  2854. if project_id:
  2855. query = query.filter(model.PullRequest.project_id == project_id)
  2856. if project_id_from:
  2857. query = query.filter(
  2858. model.PullRequest.project_id_from == project_id_from
  2859. )
  2860. if status is not None:
  2861. if isinstance(status, bool):
  2862. if status:
  2863. query = query.filter(model.PullRequest.status == "Open")
  2864. else:
  2865. query = query.filter(model.PullRequest.status != "Open")
  2866. else:
  2867. query = query.filter(
  2868. func.lower(model.PullRequest.status) == status.lower()
  2869. )
  2870. if assignee is not None:
  2871. assignee = "%s" % assignee
  2872. if not pagure.utils.is_true(assignee, ["false", "0", "true", "1"]):
  2873. user2 = aliased(model.User)
  2874. if assignee.startswith("!"):
  2875. sub = (
  2876. session.query(model.PullRequest.uid)
  2877. .filter(model.PullRequest.assignee_id == user2.id)
  2878. .filter(user2.user == assignee[1:])
  2879. )
  2880. query = query.filter(~model.PullRequest.uid.in_(sub))
  2881. else:
  2882. query = query.filter(
  2883. model.PullRequest.assignee_id == user2.id
  2884. ).filter(user2.user == assignee)
  2885. elif pagure.utils.is_true(assignee):
  2886. query = query.filter(model.PullRequest.assignee_id.isnot(None))
  2887. else:
  2888. query = query.filter(model.PullRequest.assignee_id.is_(None))
  2889. if author is not None:
  2890. user3 = aliased(model.User)
  2891. query = query.filter(model.PullRequest.user_id == user3.id).filter(
  2892. user3.user == author
  2893. )
  2894. if branch_from is not None:
  2895. query = query.filter(model.PullRequest.branch_from == branch_from)
  2896. if tags is not None and tags != []:
  2897. if isinstance(tags, six.string_types):
  2898. tags = [tags]
  2899. notags = []
  2900. ytags = []
  2901. for tag in tags:
  2902. if tag.startswith("!"):
  2903. notags.append(tag[1:])
  2904. else:
  2905. ytags.append(tag)
  2906. if ytags:
  2907. sub_q2 = session.query(sqlalchemy.distinct(model.PullRequest.uid))
  2908. if project_id is not None:
  2909. sub_q2 = sub_q2.filter(
  2910. model.PullRequest.project_id == project_id
  2911. )
  2912. sub_q2 = (
  2913. sub_q2.filter(
  2914. model.PullRequest.uid == model.TagPullRequest.request_uid
  2915. )
  2916. .filter(model.TagPullRequest.tag_id == model.TagColored.id)
  2917. .filter(model.TagColored.tag.in_(ytags))
  2918. )
  2919. if notags:
  2920. sub_q3 = session.query(sqlalchemy.distinct(model.PullRequest.uid))
  2921. if project_id is not None:
  2922. sub_q3 = sub_q3.filter(
  2923. model.PullRequest.project_id == project_id
  2924. )
  2925. sub_q3 = (
  2926. sub_q3.filter(
  2927. model.PullRequest.uid == model.TagPullRequest.request_uid
  2928. )
  2929. .filter(model.TagPullRequest.tag_id == model.TagColored.id)
  2930. .filter(model.TagColored.tag.in_(notags))
  2931. )
  2932. # Adjust the main query based on the parameters specified
  2933. if ytags and not notags:
  2934. query = query.filter(model.PullRequest.uid.in_(sub_q2))
  2935. elif not ytags and notags:
  2936. query = query.filter(~model.PullRequest.uid.in_(sub_q3))
  2937. elif ytags and notags:
  2938. final_set = set([i[0] for i in sub_q2.all()]) - set(
  2939. [i[0] for i in sub_q3.all()]
  2940. )
  2941. if final_set:
  2942. query = query.filter(
  2943. model.PullRequest.uid.in_(list(final_set))
  2944. )
  2945. if search_pattern is not None:
  2946. if "*" in search_pattern:
  2947. search_pattern = search_pattern.replace("*", "%")
  2948. else:
  2949. search_pattern = "%%%s%%" % search_pattern
  2950. query = query.filter(model.PullRequest.title.ilike(search_pattern))
  2951. # Depending on the order, the query is sorted(default is desc)
  2952. if order == "asc":
  2953. query = query.order_by(asc(column))
  2954. else:
  2955. query = query.order_by(desc(column))
  2956. if requestid:
  2957. output = query.first()
  2958. elif count:
  2959. output = query.count()
  2960. else:
  2961. if offset:
  2962. query = query.offset(offset)
  2963. if limit:
  2964. query = query.limit(limit)
  2965. output = query.all()
  2966. return output
  2967. def reopen_pull_request(session, request, user):
  2968. """Re-Open the provided pull request"""
  2969. if request.status != "Closed":
  2970. raise pagure.exceptions.PagureException(
  2971. "Trying to reopen a pull request that is not closed"
  2972. )
  2973. user_obj = get_user(session, user)
  2974. request.status = "Open"
  2975. session.add(request)
  2976. session.flush()
  2977. log_action(session, request.status.lower(), request, user_obj)
  2978. pagure.lib.notify.notify_reopen_pull_request(request, user_obj)
  2979. pagure.lib.git.update_git(request, repo=request.project)
  2980. add_pull_request_comment(
  2981. session,
  2982. request,
  2983. commit=None,
  2984. tree_id=None,
  2985. filename=None,
  2986. row=None,
  2987. comment="Pull-Request has been reopened by %s" % (user),
  2988. user=user,
  2989. notify=False,
  2990. notification=True,
  2991. )
  2992. pagure.lib.notify.log(
  2993. request.project,
  2994. topic="pull-request.reopened",
  2995. msg=dict(
  2996. pullrequest=request.to_json(public=True), agent=user_obj.username
  2997. ),
  2998. )
  2999. def close_pull_request(session, request, user, merged=True):
  3000. """Close the provided pull-request."""
  3001. user_obj = get_user(session, user)
  3002. if merged is True:
  3003. request.status = "Merged"
  3004. else:
  3005. request.status = "Closed"
  3006. request.closed_by_id = user_obj.id
  3007. request.closed_at = datetime.datetime.utcnow()
  3008. session.add(request)
  3009. session.flush()
  3010. log_action(session, request.status.lower(), request, user_obj)
  3011. if merged is True:
  3012. pagure.lib.notify.notify_merge_pull_request(request, user_obj)
  3013. else:
  3014. pagure.lib.notify.notify_closed_pull_request(request, user_obj)
  3015. pagure.lib.git.update_git(request, repo=request.project)
  3016. add_pull_request_comment(
  3017. session,
  3018. request,
  3019. commit=None,
  3020. tree_id=None,
  3021. filename=None,
  3022. row=None,
  3023. comment="Pull-Request has been %s by %s"
  3024. % (request.status.lower(), user),
  3025. user=user,
  3026. notify=False,
  3027. notification=True,
  3028. )
  3029. pagure.lib.notify.log(
  3030. request.project,
  3031. topic="pull-request.closed",
  3032. msg=dict(
  3033. pullrequest=request.to_json(public=True),
  3034. merged=merged,
  3035. agent=user_obj.username,
  3036. ),
  3037. )
  3038. def reset_status_pull_request(session, project, but_uids=None):
  3039. """Reset the status of all opened Pull-Requests of a project."""
  3040. query = (
  3041. session.query(model.PullRequest)
  3042. .filter(model.PullRequest.project_id == project.id)
  3043. .filter(model.PullRequest.status == "Open")
  3044. )
  3045. if but_uids:
  3046. query = query.filter(model.PullRequest.uid.notin_(but_uids))
  3047. query.update(
  3048. {model.PullRequest.merge_status: None}, synchronize_session=False
  3049. )
  3050. session.commit()
  3051. def add_attachment(repo, issue, attachmentfolder, user, filename, filestream):
  3052. """Add a file to the attachments folder of repo and update git."""
  3053. _log.info(
  3054. "Adding file: %s to the git repo: %s",
  3055. repo.path,
  3056. werkzeug.utils.secure_filename(filename),
  3057. )
  3058. # Prefix the filename with a timestamp:
  3059. filename = "%s-%s" % (
  3060. hashlib.sha256(filestream.read()).hexdigest(),
  3061. werkzeug.utils.secure_filename(filename),
  3062. )
  3063. filedir = os.path.join(attachmentfolder, repo.fullname, "files")
  3064. filepath = os.path.join(filedir, filename)
  3065. if os.path.exists(filepath):
  3066. return filename
  3067. if not os.path.exists(filedir):
  3068. os.makedirs(filedir)
  3069. # Write file
  3070. filestream.seek(0)
  3071. with open(filepath, "wb") as stream:
  3072. stream.write(filestream.read())
  3073. pagure.lib.tasks.add_file_to_git.delay(
  3074. repo.name,
  3075. repo.namespace,
  3076. repo.user.username if repo.is_fork else None,
  3077. user.username,
  3078. issue.uid,
  3079. filename,
  3080. )
  3081. return filename
  3082. def get_issue_statuses(session):
  3083. """Return the complete list of status an issue can have."""
  3084. output = []
  3085. statuses = session.query(model.StatusIssue).all()
  3086. for status in statuses:
  3087. output.append(status.status)
  3088. return output
  3089. def get_issue_comment(session, issue_uid, comment_id):
  3090. """Return a specific comment of a specified issue."""
  3091. query = (
  3092. session.query(model.IssueComment)
  3093. .filter(model.IssueComment.issue_uid == issue_uid)
  3094. .filter(model.IssueComment.id == comment_id)
  3095. )
  3096. return query.first()
  3097. def get_issue_comment_by_user_and_comment(
  3098. session, issue_uid, user_id, content
  3099. ):
  3100. """Return a specific comment of a specified issue."""
  3101. query = (
  3102. session.query(model.IssueComment)
  3103. .filter(model.IssueComment.issue_uid == issue_uid)
  3104. .filter(model.IssueComment.user_id == user_id)
  3105. .filter(model.IssueComment.comment == content)
  3106. )
  3107. return query.first()
  3108. def get_request_comment(session, request_uid, comment_id):
  3109. """Return a specific comment of a specified request."""
  3110. query = (
  3111. session.query(model.PullRequestComment)
  3112. .filter(model.PullRequestComment.pull_request_uid == request_uid)
  3113. .filter(model.PullRequestComment.id == comment_id)
  3114. )
  3115. return query.first()
  3116. def get_issue_by_uid(session, issue_uid):
  3117. """Return the issue corresponding to the specified unique identifier.
  3118. :arg session: the session to use to connect to the database.
  3119. :arg issue_uid: the unique identifier of an issue. This identifier is
  3120. unique accross all projects on this pagure instance and should be
  3121. unique accross multiple pagure instances as well
  3122. :type issue_uid: str or None
  3123. :return: A single Issue object.
  3124. :rtype: pagure.lib.model.Issue
  3125. """
  3126. query = session.query(model.Issue).filter(model.Issue.uid == issue_uid)
  3127. return query.first()
  3128. def get_request_by_uid(session, request_uid):
  3129. """Return the request corresponding to the specified unique identifier.
  3130. :arg session: the session to use to connect to the database.
  3131. :arg request_uid: the unique identifier of a request. This identifier is
  3132. unique accross all projects on this pagure instance and should be
  3133. unique accross multiple pagure instances as well
  3134. :type request_uid: str or None
  3135. :return: A single Issue object.
  3136. :rtype: pagure.lib.model.PullRequest
  3137. """
  3138. query = session.query(model.PullRequest).filter(
  3139. model.PullRequest.uid == request_uid
  3140. )
  3141. return query.first()
  3142. def get_pull_request_flag_by_uid(session, request, flag_uid):
  3143. """Return the flag corresponding to the specified unique identifier.
  3144. :arg session: the session to use to connect to the database.
  3145. :arg request: the pull-request that was flagged
  3146. :arg flag_uid: the unique identifier of a request. This identifier is
  3147. unique accross all flags on this pagure instance and should be
  3148. unique accross multiple pagure instances as well
  3149. :type request_uid: str or None
  3150. :return: A single Issue object.
  3151. :rtype: pagure.lib.model.PullRequestFlag
  3152. """
  3153. query = (
  3154. session.query(model.PullRequestFlag)
  3155. .filter(model.PullRequestFlag.pull_request_uid == request.uid)
  3156. .filter(model.PullRequestFlag.uid == flag_uid.strip())
  3157. )
  3158. return query.first()
  3159. def get_commit_flag_by_uid(session, commit_hash, flag_uid):
  3160. """Return the flag corresponding to the specified unique identifier.
  3161. :arg session: the session to use to connect to the database.
  3162. :arg commit_hash: the hash of the commit that got flagged
  3163. :arg flag_uid: the unique identifier of a request. This identifier is
  3164. unique accross all flags on this pagure instance and should be
  3165. unique accross multiple pagure instances as well
  3166. :type request_uid: str or None
  3167. :return: A single Issue object.
  3168. :rtype: pagure.lib.model.PullRequestFlag
  3169. """
  3170. query = (
  3171. session.query(model.CommitFlag)
  3172. .filter(model.CommitFlag.commit_hash == commit_hash)
  3173. .filter(model.CommitFlag.uid == flag_uid.strip() if flag_uid else None)
  3174. )
  3175. return query.first()
  3176. def set_up_user(
  3177. session,
  3178. username,
  3179. fullname,
  3180. default_email,
  3181. emails=None,
  3182. ssh_key=None,
  3183. keydir=None,
  3184. ):
  3185. """Set up a new user into the database or update its information."""
  3186. user = search_user(session, username=username)
  3187. if not user:
  3188. user = model.User(
  3189. user=username, fullname=fullname, default_email=default_email
  3190. )
  3191. session.add(user)
  3192. session.flush()
  3193. if user.fullname != fullname:
  3194. user.fullname = fullname
  3195. session.add(user)
  3196. session.flush()
  3197. if emails:
  3198. emails = set(emails)
  3199. else:
  3200. emails = set()
  3201. emails.add(default_email)
  3202. for email in emails:
  3203. try:
  3204. add_email_to_user(session, user, email)
  3205. except pagure.exceptions.PagureException as err:
  3206. _log.exception(err)
  3207. if ssh_key and not user.sshkeys:
  3208. update_user_ssh(session, user, ssh_key, keydir)
  3209. return user
  3210. def allowed_emailaddress(email):
  3211. """check if email domains are restricted and if a given email address
  3212. is allowed."""
  3213. allowed_email_domains = pagure_config.get("ALLOWED_EMAIL_DOMAINS", None)
  3214. if allowed_email_domains:
  3215. for domain in allowed_email_domains:
  3216. if email.endswith(domain):
  3217. return
  3218. raise pagure.exceptions.PagureException(
  3219. "The email address "
  3220. + email
  3221. + " "
  3222. + "is not in the list of allowed email domains:\n"
  3223. + "\n".join(allowed_email_domains)
  3224. )
  3225. def add_email_to_user(session, user, user_email):
  3226. """Add the provided email to the specified user."""
  3227. try:
  3228. allowed_emailaddress(user_email)
  3229. except pagure.exceptions.PagureException:
  3230. raise
  3231. emails = [email.email for email in user.emails]
  3232. if user_email not in emails:
  3233. useremail = model.UserEmail(user_id=user.id, email=user_email)
  3234. session.add(useremail)
  3235. session.flush()
  3236. if email_logs_count(session, user_email):
  3237. update_log_email_user(session, user_email, user)
  3238. def update_user_ssh(session, user, ssh_key, keydir, update_only=False):
  3239. """Set up a new user into the database or update its information."""
  3240. if isinstance(user, six.string_types):
  3241. user = get_user(session, user)
  3242. if ssh_key:
  3243. for key in user.sshkeys:
  3244. session.delete(key)
  3245. for key in ssh_key.strip().split("\n"):
  3246. key = key.strip()
  3247. add_sshkey_to_project_or_user(
  3248. session=session,
  3249. ssh_key=key,
  3250. user=user,
  3251. pushaccess=True,
  3252. creator=user,
  3253. )
  3254. session.commit()
  3255. if keydir:
  3256. create_user_ssh_keys_on_disk(user, keydir)
  3257. if update_only:
  3258. pagure.lib.tasks.gitolite_post_compile_only.delay()
  3259. else:
  3260. pagure.lib.git.generate_gitolite_acls(project=None)
  3261. session.add(user)
  3262. session.flush()
  3263. def avatar_url_from_email(email, size=64, default="retro", dns=False):
  3264. """
  3265. Our own implementation since fas doesn't support this nicely yet.
  3266. """
  3267. if not email:
  3268. return
  3269. if dns: # pragma: no cover
  3270. # This makes an extra DNS SRV query, which can slow down our webapps.
  3271. # It is necessary for libravatar federation, though.
  3272. import libravatar
  3273. return libravatar.libravatar_url(
  3274. openid=email, size=size, default=default
  3275. )
  3276. else:
  3277. query = urlencode({"s": size, "d": default})
  3278. email = email.encode("utf-8")
  3279. hashhex = hashlib.sha256(email).hexdigest()
  3280. return "https://seccdn.libravatar.org/avatar/%s?%s" % (hashhex, query)
  3281. def update_tags(session, obj, tags, username):
  3282. """Update the tags of a specified object (adding or removing them).
  3283. This object can be either an issue or a project.
  3284. """
  3285. if isinstance(tags, six.string_types):
  3286. tags = [tags]
  3287. toadd = set(tags) - set(obj.tags_text)
  3288. torm = set(obj.tags_text) - set(tags)
  3289. messages = []
  3290. if toadd:
  3291. add_tag_obj(session, obj=obj, tags=toadd, user=username)
  3292. messages.append(
  3293. "%s tagged with: %s"
  3294. % (obj.isa.capitalize(), ", ".join(sorted(toadd)))
  3295. )
  3296. if torm:
  3297. remove_tags_obj(session, obj=obj, tags=torm, user=username)
  3298. messages.append(
  3299. "%s **un**tagged with: %s"
  3300. % (obj.isa.capitalize(), ", ".join(sorted(torm)))
  3301. )
  3302. session.commit()
  3303. return messages
  3304. def update_dependency_issue(session, repo, issue, depends, username):
  3305. """Update the dependency of a specified issue (adding or removing them)"""
  3306. if isinstance(depends, six.string_types):
  3307. depends = [depends]
  3308. toadd = set(depends) - set(issue.depending_text)
  3309. torm = set(issue.depending_text) - set(depends)
  3310. messages = []
  3311. # Add issue depending
  3312. for depend in sorted([int(i) for i in toadd]):
  3313. messages.append("Issue marked as depending on: #%s" % depend)
  3314. issue_depend = search_issues(session, repo, issueid=depend)
  3315. if issue_depend is None:
  3316. continue
  3317. if issue_depend.id in issue.depending_text: # pragma: no cover
  3318. # we should never be in this case but better safe than sorry...
  3319. continue
  3320. add_issue_dependency(
  3321. session, issue=issue_depend, issue_blocked=issue, user=username
  3322. )
  3323. # Remove issue depending
  3324. for depend in sorted([int(i) for i in torm]):
  3325. messages.append("Issue **un**marked as depending on: #%s" % depend)
  3326. issue_depend = search_issues(session, repo, issueid=depend)
  3327. if issue_depend is None: # pragma: no cover
  3328. # We cannot test this as it would mean we managed to put in an
  3329. # invalid ticket as dependency earlier
  3330. continue
  3331. if issue_depend.id not in issue.depending_text: # pragma: no cover
  3332. # we should never be in this case but better safe than sorry...
  3333. continue
  3334. remove_issue_dependency(
  3335. session, issue=issue, issue_blocked=issue_depend, user=username
  3336. )
  3337. session.commit()
  3338. return messages
  3339. def update_blocked_issue(session, repo, issue, blocks, username):
  3340. """Update the upstream dependency of a specified issue (adding or
  3341. removing them)
  3342. """
  3343. if isinstance(blocks, six.string_types):
  3344. blocks = [blocks]
  3345. toadd = set(blocks) - set(issue.blocking_text)
  3346. torm = set(issue.blocking_text) - set(blocks)
  3347. messages = []
  3348. # Add issue blocked
  3349. for block in sorted([int(i) for i in toadd]):
  3350. messages.append("Issue marked as blocking: #%s" % block)
  3351. issue_block = search_issues(session, repo, issueid=block)
  3352. if issue_block is None:
  3353. continue
  3354. if issue_block.id in issue.blocking_text: # pragma: no cover
  3355. # we should never be in this case but better safe than sorry...
  3356. continue
  3357. add_issue_dependency(
  3358. session, issue=issue, issue_blocked=issue_block, user=username
  3359. )
  3360. session.commit()
  3361. # Remove issue blocked
  3362. for block in sorted([int(i) for i in torm]):
  3363. messages.append("Issue **un**marked as blocking: #%s" % block)
  3364. issue_block = search_issues(session, repo, issueid=block)
  3365. if issue_block is None: # pragma: no cover
  3366. # We cannot test this as it would mean we managed to put in an
  3367. # invalid ticket as dependency earlier
  3368. continue
  3369. if issue_block.id not in issue.blocking_text: # pragma: no cover
  3370. # we should never be in this case but better safe than sorry...
  3371. continue
  3372. remove_issue_dependency(
  3373. session, issue=issue_block, issue_blocked=issue, user=username
  3374. )
  3375. session.commit()
  3376. return messages
  3377. def add_user_pending_email(session, userobj, email):
  3378. """Add the provided email to the specified user."""
  3379. try:
  3380. allowed_emailaddress(email)
  3381. except pagure.exceptions.PagureException:
  3382. raise
  3383. other_user = search_user(session, email=email)
  3384. if other_user and other_user != userobj:
  3385. raise pagure.exceptions.PagureException(
  3386. "Someone else has already registered this email"
  3387. )
  3388. pending_email = search_pending_email(session, email=email)
  3389. if pending_email:
  3390. raise pagure.exceptions.PagureException(
  3391. "This email is already pending confirmation"
  3392. )
  3393. tmpemail = pagure.lib.model.UserEmailPending(
  3394. user_id=userobj.id,
  3395. token=pagure.lib.login.id_generator(40),
  3396. email=email,
  3397. )
  3398. session.add(tmpemail)
  3399. session.flush()
  3400. pagure.lib.notify.notify_new_email(tmpemail, user=userobj)
  3401. def resend_pending_email(session, userobj, email):
  3402. """Resend to the user the confirmation email for the provided email
  3403. address.
  3404. """
  3405. other_user = search_user(session, email=email)
  3406. if other_user and other_user != userobj:
  3407. raise pagure.exceptions.PagureException(
  3408. "Someone else has already registered this email address"
  3409. )
  3410. pending_email = search_pending_email(session, email=email)
  3411. if not pending_email:
  3412. raise pagure.exceptions.PagureException(
  3413. "This email address has already been confirmed"
  3414. )
  3415. pending_email.token = pagure.lib.login.id_generator(40)
  3416. session.add(pending_email)
  3417. session.flush()
  3418. pagure.lib.notify.notify_new_email(pending_email, user=userobj)
  3419. def search_pending_email(session, email=None, token=None):
  3420. """Searches the database for the pending email matching the given
  3421. criterias.
  3422. :arg session: the session to use to connect to the database.
  3423. :kwarg email: the email to look for
  3424. :type email: string or None
  3425. :kwarg token: the token of the pending email to look for
  3426. :type token: string or None
  3427. :return: A single UserEmailPending object
  3428. :rtype: UserEmailPending
  3429. """
  3430. query = session.query(model.UserEmailPending)
  3431. if email is not None:
  3432. query = query.filter(model.UserEmailPending.email == email)
  3433. if token is not None:
  3434. query = query.filter(model.UserEmailPending.token == token)
  3435. output = query.first()
  3436. return output
  3437. def generate_hook_token(session):
  3438. """For each project in the database, re-generate a unique hook_token."""
  3439. for project in search_projects(session):
  3440. project.hook_token = pagure.lib.login.id_generator(40)
  3441. session.add(project)
  3442. session.commit()
  3443. def get_group_types(session, group_type=None):
  3444. """Return the list of type a group can have."""
  3445. query = session.query(model.PagureGroupType).order_by(
  3446. model.PagureGroupType.group_type
  3447. )
  3448. if group_type:
  3449. query = query.filter(model.PagureGroupType.group_type == group_type)
  3450. return query.all()
  3451. def search_groups(
  3452. session,
  3453. pattern=None,
  3454. group_name=None,
  3455. group_type=None,
  3456. display_name=None,
  3457. offset=None,
  3458. limit=None,
  3459. count=False,
  3460. ):
  3461. """Return the groups based on the criteria specified."""
  3462. query = session.query(model.PagureGroup).order_by(
  3463. model.PagureGroup.group_type, model.PagureGroup.group_name
  3464. )
  3465. if pattern:
  3466. pattern = pattern.replace("*", "%")
  3467. query = query.filter(
  3468. sqlalchemy.or_(
  3469. model.PagureGroup.group_name.ilike(pattern),
  3470. model.PagureGroup.display_name.ilike(pattern),
  3471. )
  3472. )
  3473. if group_name:
  3474. query = query.filter(model.PagureGroup.group_name == group_name)
  3475. if display_name:
  3476. query = query.filter(model.PagureGroup.display_name == display_name)
  3477. if group_type:
  3478. query = query.filter(model.PagureGroup.group_type == group_type)
  3479. if offset:
  3480. query = query.offset(offset)
  3481. if limit:
  3482. query = query.limit(limit)
  3483. if group_name:
  3484. return query.first()
  3485. elif count:
  3486. return query.count()
  3487. else:
  3488. return query.all()
  3489. def add_user_to_group(
  3490. session, username, group, user, is_admin, from_external=False
  3491. ):
  3492. """Add the specified user to the given group.
  3493. from_external indicates whether this is a remotely synced group.
  3494. """
  3495. new_user = search_user(session, username=username)
  3496. if not new_user:
  3497. raise pagure.exceptions.PagureException(
  3498. "No user `%s` found" % username
  3499. )
  3500. action_user = user
  3501. user = search_user(session, username=user)
  3502. if not user:
  3503. raise pagure.exceptions.PagureException(
  3504. "No user `%s` found" % action_user
  3505. )
  3506. if (
  3507. not from_external
  3508. and group.group_name not in user.groups
  3509. and not is_admin
  3510. and user.username != group.creator.username
  3511. ):
  3512. raise pagure.exceptions.PagureException(
  3513. "You are not allowed to add user to this group"
  3514. )
  3515. for guser in group.users:
  3516. if guser.username == new_user.username:
  3517. return "User `%s` already in the group, nothing to change." % (
  3518. new_user.username
  3519. )
  3520. grp = model.PagureUserGroup(group_id=group.id, user_id=new_user.id)
  3521. session.add(grp)
  3522. session.flush()
  3523. return "User `%s` added to the group `%s`." % (
  3524. new_user.username,
  3525. group.group_name,
  3526. )
  3527. def edit_group_info(session, group, display_name, description, user, is_admin):
  3528. """Edit the information regarding a given group."""
  3529. action_user = user
  3530. user = search_user(session, username=user)
  3531. if not user:
  3532. raise pagure.exceptions.PagureException(
  3533. "No user `%s` found" % action_user
  3534. )
  3535. if (
  3536. group.group_name not in user.groups
  3537. and not is_admin
  3538. and user.username != group.creator.username
  3539. ):
  3540. raise pagure.exceptions.PagureException(
  3541. "You are not allowed to edit this group"
  3542. )
  3543. edits = []
  3544. if display_name and display_name != group.display_name:
  3545. group.display_name = display_name
  3546. edits.append("display_name")
  3547. if description and description != group.description:
  3548. group.description = description
  3549. edits.append("description")
  3550. session.add(group)
  3551. session.flush()
  3552. msg = "Nothing changed"
  3553. if edits:
  3554. pagure.lib.notify.log(
  3555. None,
  3556. topic="group.edit",
  3557. msg=dict(
  3558. group=group.to_json(public=True),
  3559. fields=edits,
  3560. agent=user.username,
  3561. ),
  3562. )
  3563. msg = 'Group "%s" (%s) edited' % (group.display_name, group.group_name)
  3564. return msg
  3565. def delete_user_of_group(
  3566. session,
  3567. username,
  3568. groupname,
  3569. user,
  3570. is_admin,
  3571. force=False,
  3572. from_external=False,
  3573. ):
  3574. """Removes the specified user from the given group."""
  3575. group_obj = search_groups(session, group_name=groupname)
  3576. if not group_obj:
  3577. raise pagure.exceptions.PagureException(
  3578. "No group `%s` found" % groupname
  3579. )
  3580. drop_user = search_user(session, username=username)
  3581. if not drop_user:
  3582. raise pagure.exceptions.PagureException(
  3583. "No user `%s` found" % username
  3584. )
  3585. action_user = user
  3586. user = search_user(session, username=user)
  3587. if not user:
  3588. raise pagure.exceptions.PagureException(
  3589. "Could not find user %s" % action_user
  3590. )
  3591. if (
  3592. not from_external
  3593. and group_obj.group_name not in user.groups
  3594. and not is_admin
  3595. ):
  3596. raise pagure.exceptions.PagureException(
  3597. "You are not allowed to remove user from this group"
  3598. )
  3599. if drop_user.username == group_obj.creator.username and not force:
  3600. raise pagure.exceptions.PagureException(
  3601. "The creator of a group cannot be removed"
  3602. )
  3603. user_grp = get_user_group(session, drop_user.id, group_obj.id)
  3604. if not user_grp:
  3605. raise pagure.exceptions.PagureException(
  3606. "User `%s` could not be found in the group `%s`"
  3607. % (username, groupname)
  3608. )
  3609. session.delete(user_grp)
  3610. session.flush()
  3611. def add_group(
  3612. session,
  3613. group_name,
  3614. display_name,
  3615. description,
  3616. group_type,
  3617. user,
  3618. is_admin,
  3619. blacklist,
  3620. ):
  3621. """Creates a new group with the given information."""
  3622. if " " in group_name:
  3623. raise pagure.exceptions.PagureException(
  3624. "Spaces are not allowed in group names: %s" % group_name
  3625. )
  3626. if group_name in blacklist:
  3627. raise pagure.exceptions.PagureException(
  3628. "This group name has been blacklisted, "
  3629. "please choose another one"
  3630. )
  3631. group_types = ["user"]
  3632. if is_admin:
  3633. group_types = [grp.group_type for grp in get_group_types(session)]
  3634. if not is_admin:
  3635. group_type = "user"
  3636. if group_type not in group_types:
  3637. raise pagure.exceptions.PagureException("Invalide type for this group")
  3638. username = user
  3639. user = search_user(session, username=user)
  3640. if not user:
  3641. raise pagure.exceptions.PagureException(
  3642. "Could not find user %s" % username
  3643. )
  3644. group = search_groups(session, group_name=group_name)
  3645. if group:
  3646. raise pagure.exceptions.PagureException(
  3647. "There is already a group named %s" % group_name
  3648. )
  3649. display = search_groups(session, display_name=display_name)
  3650. if display:
  3651. raise pagure.exceptions.PagureException(
  3652. "There is already a group with display name `%s` created."
  3653. % display_name
  3654. )
  3655. grp = pagure.lib.model.PagureGroup(
  3656. group_name=group_name,
  3657. display_name=display_name,
  3658. description=description,
  3659. group_type=group_type,
  3660. user_id=user.id,
  3661. )
  3662. session.add(grp)
  3663. session.flush()
  3664. return add_user_to_group(
  3665. session, user.username, grp, user.username, is_admin
  3666. )
  3667. def get_user_group(session, userid, groupid):
  3668. """Return a specific user_group for the specified group and user
  3669. identifiers.
  3670. :arg session: the session with which to connect to the database.
  3671. """
  3672. query = (
  3673. session.query(model.PagureUserGroup)
  3674. .filter(model.PagureUserGroup.user_id == userid)
  3675. .filter(model.PagureUserGroup.group_id == groupid)
  3676. )
  3677. return query.first()
  3678. def is_group_member(session, user, groupname):
  3679. """Return whether the user is a member of the specified group."""
  3680. if not user:
  3681. return False
  3682. user = search_user(session, username=user)
  3683. if not user:
  3684. return False
  3685. return groupname in user.groups
  3686. def get_api_token(session, token_str):
  3687. """Return the Token object corresponding to the provided token string
  3688. if there is any, returns None otherwise.
  3689. """
  3690. query = session.query(model.Token).filter(model.Token.id == token_str)
  3691. return query.first()
  3692. def get_acls(session, restrict=None):
  3693. """Returns all the possible ACLs a token can have according to the
  3694. database.
  3695. """
  3696. query = session.query(model.ACL).order_by(model.ACL.name)
  3697. if restrict:
  3698. if isinstance(restrict, list):
  3699. query = query.filter(model.ACL.name.in_(restrict))
  3700. else:
  3701. query = query.filter(model.ACL.name == restrict)
  3702. return query.all()
  3703. def add_token_to_user(
  3704. session, project, acls, username, expiration_date, description=None
  3705. ):
  3706. """Create a new token for the specified user on the specified project
  3707. with the given ACLs.
  3708. """
  3709. acls_obj = session.query(model.ACL).filter(model.ACL.name.in_(acls)).all()
  3710. user = search_user(session, username=username)
  3711. if expiration_date > (
  3712. datetime.date.today() + datetime.timedelta(days=730)
  3713. ):
  3714. raise pagure.exceptions.PagureException(
  3715. "API tokens can only be created up to 2 years"
  3716. )
  3717. token = pagure.lib.model.Token(
  3718. id=pagure.lib.login.id_generator(64),
  3719. user_id=user.id,
  3720. project_id=project.id if project else None,
  3721. description=description,
  3722. expiration=expiration_date,
  3723. )
  3724. session.add(token)
  3725. session.flush()
  3726. for acl in acls_obj:
  3727. item = pagure.lib.model.TokenAcl(token_id=token.id, acl_id=acl.id)
  3728. session.add(item)
  3729. session.commit()
  3730. return token
  3731. def _convert_markdown(md_processor, text):
  3732. """Small function converting the text to html using the given markdown
  3733. processor.
  3734. This was done in order to make testing it easier.
  3735. """
  3736. return md_processor.convert(text)
  3737. def text2markdown(text, extended=True, readme=False):
  3738. """Simple text to html converter using the markdown library."""
  3739. extensions = [
  3740. "markdown.extensions.def_list",
  3741. "markdown.extensions.fenced_code",
  3742. "markdown.extensions.tables",
  3743. # All of the above are the .extra extensions
  3744. # w/o the "attribute lists" one
  3745. "markdown.extensions.admonition",
  3746. "markdown.extensions.codehilite",
  3747. "markdown.extensions.sane_lists",
  3748. "markdown.extensions.toc",
  3749. ]
  3750. # smart_strong is not an extension anymore in markdown 3.0+
  3751. try:
  3752. md_version = markdown.__version__.version_info
  3753. except AttributeError: # pragma: no cover
  3754. md_version = markdown.__version_info__
  3755. if md_version < (3, 0, 0):
  3756. extensions.append("markdown.extensions.smart_strong")
  3757. # Some extensions are enabled for READMEs and disabled otherwise
  3758. if readme:
  3759. extensions.extend(
  3760. ["markdown.extensions.abbr", "markdown.extensions.footnotes"]
  3761. )
  3762. else:
  3763. extensions.append("markdown.extensions.nl2br")
  3764. if extended:
  3765. # Install our markdown modifications
  3766. extensions.append("pagure.pfmarkdown")
  3767. md_processor = markdown.Markdown(
  3768. extensions=extensions,
  3769. extension_configs={
  3770. "markdown.extensions.codehilite": {"guess_lang": False}
  3771. },
  3772. output_format="xhtml5",
  3773. )
  3774. if text:
  3775. try:
  3776. text = _convert_markdown(md_processor, text)
  3777. except Exception as err:
  3778. print(err)
  3779. _log.debug(
  3780. "A markdown error occured while processing: ``%s``", text
  3781. )
  3782. return clean_input(text)
  3783. return ""
  3784. def filter_img_src(name, value):
  3785. """Filter in img html tags images coming from a different domain."""
  3786. if name in ("alt", "height", "width", "class", "data-src"):
  3787. return True
  3788. if name == "src":
  3789. parsed = urlparse(value)
  3790. return (not parsed.netloc) or parsed.netloc == urlparse(
  3791. pagure_config["APP_URL"]
  3792. ).netloc
  3793. return False
  3794. def clean_input(text, ignore=None):
  3795. """For a given html text, escape everything we do not want to support
  3796. to avoid potential security breach.
  3797. """
  3798. if ignore and not isinstance(ignore, (tuple, set, list)):
  3799. ignore = [ignore]
  3800. bleach_v = bleach.__version__.split(".")
  3801. for idx, val in enumerate(bleach_v):
  3802. try:
  3803. val = int(val)
  3804. except ValueError: # pragma: no cover
  3805. pass
  3806. bleach_v[idx] = val
  3807. attrs = bleach.ALLOWED_ATTRIBUTES.copy()
  3808. attrs["table"] = ["class"]
  3809. attrs["span"] = ["class", "id"]
  3810. attrs["div"] = ["class", "id"]
  3811. attrs["td"] = ["align", "class"]
  3812. attrs["th"] = ["align"]
  3813. attrs["a"].extend(["id", "data-line-number"])
  3814. if not ignore or "img" not in ignore:
  3815. # newer bleach need three args for attribute callable
  3816. if tuple(bleach_v) >= (2, 0, 0): # pragma: no cover
  3817. attrs["img"] = lambda tag, name, val: filter_img_src(name, val)
  3818. else:
  3819. attrs["img"] = filter_img_src
  3820. tags = bleach.ALLOWED_TAGS + [
  3821. "p",
  3822. "br",
  3823. "div",
  3824. "h1",
  3825. "h2",
  3826. "h3",
  3827. "h4",
  3828. "h5",
  3829. "h6",
  3830. "table",
  3831. "td",
  3832. "tr",
  3833. "th",
  3834. "thead",
  3835. "tbody",
  3836. "col",
  3837. "pre",
  3838. "img",
  3839. "hr",
  3840. "dl",
  3841. "dt",
  3842. "dd",
  3843. "span",
  3844. "kbd",
  3845. "var",
  3846. "del",
  3847. "cite",
  3848. "noscript",
  3849. "colgroup",
  3850. ]
  3851. if ignore:
  3852. for tag in ignore:
  3853. if tag in tags:
  3854. tags.remove(tag)
  3855. kwargs = {"tags": tags, "attributes": attrs}
  3856. # newer bleach allow to customize the protocol supported
  3857. if tuple(bleach_v) >= (1, 5, 0): # pragma: no cover
  3858. protocols = bleach.ALLOWED_PROTOCOLS + ["irc", "ircs"]
  3859. kwargs["protocols"] = protocols
  3860. return bleach.clean(text, **kwargs)
  3861. def could_be_text(text):
  3862. """Returns whether we think this chain of character could be text or not"""
  3863. try:
  3864. text.decode("utf-8")
  3865. return True
  3866. except (UnicodeDecodeError, UnicodeEncodeError):
  3867. return False
  3868. def get_pull_request_of_user(
  3869. session,
  3870. username,
  3871. status=None,
  3872. filed=None,
  3873. actionable=None,
  3874. offset=None,
  3875. limit=None,
  3876. created_since=None,
  3877. created_until=None,
  3878. updated_since=None,
  3879. updated_until=None,
  3880. closed_since=None,
  3881. closed_until=None,
  3882. count=False,
  3883. ):
  3884. """List the opened pull-requests of an user.
  3885. These pull-requests have either been opened by that user or against
  3886. projects that user has commit on.
  3887. If filed: only the PRs opened/filed by the specified username will be
  3888. returned.
  3889. If actionable: only the PRs not opened/filed by the specified username
  3890. will be returned.
  3891. """
  3892. projects = session.query(sqlalchemy.distinct(model.Project.id))
  3893. projects = projects.filter(
  3894. # User created the project
  3895. sqlalchemy.and_(
  3896. model.User.user == username, model.User.id == model.Project.user_id
  3897. )
  3898. )
  3899. sub_q2 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  3900. # User got commit right
  3901. sqlalchemy.and_(
  3902. model.User.user == username,
  3903. model.User.id == model.ProjectUser.user_id,
  3904. model.ProjectUser.project_id == model.Project.id,
  3905. sqlalchemy.or_(
  3906. model.ProjectUser.access == "admin",
  3907. model.ProjectUser.access == "commit",
  3908. ),
  3909. )
  3910. )
  3911. sub_q3 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  3912. # User created a group that has commit right
  3913. sqlalchemy.and_(
  3914. model.User.user == username,
  3915. model.PagureGroup.user_id == model.User.id,
  3916. model.PagureGroup.group_type == "user",
  3917. model.PagureGroup.id == model.ProjectGroup.group_id,
  3918. model.Project.id == model.ProjectGroup.project_id,
  3919. sqlalchemy.or_(
  3920. model.ProjectGroup.access == "admin",
  3921. model.ProjectGroup.access == "commit",
  3922. ),
  3923. )
  3924. )
  3925. sub_q4 = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  3926. # User is part of a group that has commit right
  3927. sqlalchemy.and_(
  3928. model.User.user == username,
  3929. model.PagureUserGroup.user_id == model.User.id,
  3930. model.PagureUserGroup.group_id == model.PagureGroup.id,
  3931. model.PagureGroup.group_type == "user",
  3932. model.PagureGroup.id == model.ProjectGroup.group_id,
  3933. model.Project.id == model.ProjectGroup.project_id,
  3934. sqlalchemy.or_(
  3935. model.ProjectGroup.access == "admin",
  3936. model.ProjectGroup.access == "commit",
  3937. ),
  3938. )
  3939. )
  3940. projects = projects.union(sub_q2).union(sub_q3).union(sub_q4)
  3941. query = session.query(sqlalchemy.distinct(model.PullRequest.uid)).filter(
  3942. model.PullRequest.project_id.in_(projects.subquery())
  3943. )
  3944. query_2 = session.query(sqlalchemy.distinct(model.PullRequest.uid)).filter(
  3945. # User open the PR
  3946. sqlalchemy.and_(
  3947. model.PullRequest.user_id == model.User.id,
  3948. model.User.user == username,
  3949. )
  3950. )
  3951. final_sub = query.union(query_2)
  3952. query = (
  3953. session.query(model.PullRequest)
  3954. .filter(model.PullRequest.uid.in_(final_sub.subquery()))
  3955. .order_by(model.PullRequest.date_created.desc())
  3956. )
  3957. if status:
  3958. query = query.filter(model.PullRequest.status == status)
  3959. if filed:
  3960. query = query.filter(
  3961. model.PullRequest.user_id == model.User.id,
  3962. model.User.user == filed,
  3963. )
  3964. elif actionable:
  3965. query = query.filter(
  3966. model.PullRequest.user_id == model.User.id,
  3967. model.User.user != actionable,
  3968. )
  3969. if created_since:
  3970. query = query.filter(model.PullRequest.date_created >= created_since)
  3971. if created_until:
  3972. query = query.filter(model.PullRequest.date_created <= created_until)
  3973. if updated_since:
  3974. query = query.filter(model.PullRequest.updated_on >= updated_since)
  3975. if updated_until:
  3976. query = query.filter(model.PullRequest.updated_on <= updated_until)
  3977. if closed_since:
  3978. query = query.filter(model.PullRequest.closed_at >= closed_since)
  3979. if closed_until:
  3980. query = query.filter(model.PullRequest.closed_at <= closed_until)
  3981. if offset:
  3982. query = query.offset(offset)
  3983. if limit:
  3984. query = query.limit(limit)
  3985. if count:
  3986. return query.count()
  3987. else:
  3988. return query.all()
  3989. def update_watch_status(session, project, user, watch):
  3990. """Update the user status for watching a project.
  3991. The watch status can be:
  3992. -1: reset the watch status to default
  3993. 0: unwatch, don't notify the user of anything
  3994. 1: watch issues and PRs
  3995. 2: watch commits
  3996. 3: watch issues, PRs and commits
  3997. """
  3998. if watch not in ["-1", "0", "1", "2", "3"]:
  3999. raise pagure.exceptions.PagureException(
  4000. 'The watch value of "%s" is invalid' % watch
  4001. )
  4002. user_obj = get_user(session, user)
  4003. watcher = (
  4004. session.query(model.Watcher)
  4005. .filter(
  4006. sqlalchemy.and_(
  4007. model.Watcher.project_id == project.id,
  4008. model.Watcher.user_id == user_obj.id,
  4009. )
  4010. )
  4011. .first()
  4012. )
  4013. if watch == "-1":
  4014. if not watcher:
  4015. return "Watch status is already reset"
  4016. session.delete(watcher)
  4017. session.flush()
  4018. return "Watch status reset"
  4019. should_watch_issues = False
  4020. should_watch_commits = False
  4021. if watch == "1":
  4022. should_watch_issues = True
  4023. elif watch == "2":
  4024. should_watch_commits = True
  4025. elif watch == "3":
  4026. should_watch_issues = True
  4027. should_watch_commits = True
  4028. if not watcher:
  4029. watcher = model.Watcher(
  4030. project_id=project.id,
  4031. user_id=user_obj.id,
  4032. watch_issues=should_watch_issues,
  4033. watch_commits=should_watch_commits,
  4034. )
  4035. else:
  4036. watcher.watch_issues = should_watch_issues
  4037. watcher.watch_commits = should_watch_commits
  4038. session.add(watcher)
  4039. session.flush()
  4040. if should_watch_issues and should_watch_commits:
  4041. return "You are now watching issues, PRs, and commits on this project"
  4042. elif should_watch_issues:
  4043. return "You are now watching issues and PRs on this project"
  4044. elif should_watch_commits:
  4045. return "You are now watching commits on this project"
  4046. else:
  4047. return "You are no longer watching this project"
  4048. def get_watch_level_on_repo(
  4049. session, user, repo, repouser=None, namespace=None
  4050. ):
  4051. """Get a list representing the watch level of the user on the project."""
  4052. # If a user wasn't passed in, we can't determine their watch level
  4053. if user is None:
  4054. return []
  4055. elif isinstance(user, six.string_types):
  4056. user_obj = search_user(session, username=user)
  4057. else:
  4058. user_obj = search_user(session, username=user.username)
  4059. # If we can't find the user in the database, we can't determine their
  4060. # watch level
  4061. if not user_obj:
  4062. return []
  4063. # If the project passed in a Project for the repo parameter, then we
  4064. # don't need to query for it
  4065. if isinstance(repo, model.Project):
  4066. project = repo
  4067. # If the project passed in a string, then assume it is a project name
  4068. elif isinstance(repo, six.string_types):
  4069. project = _get_project(
  4070. session, repo, user=repouser, namespace=namespace
  4071. )
  4072. else:
  4073. raise RuntimeError(
  4074. 'The passed in repo is an invalid type of "{0}"'.format(
  4075. type(repo).__name__
  4076. )
  4077. )
  4078. # If the project is not found, we can't determine the involvement of the
  4079. # user in the project
  4080. if not project:
  4081. return []
  4082. query = (
  4083. session.query(model.Watcher)
  4084. .filter(model.Watcher.user_id == user_obj.id)
  4085. .filter(model.Watcher.project_id == project.id)
  4086. )
  4087. watcher = query.first()
  4088. # If there is a watcher issue, that means the user explicitly set a watch
  4089. # level on the project
  4090. if watcher:
  4091. if watcher.watch_issues and watcher.watch_commits:
  4092. return ["issues", "commits"]
  4093. elif watcher.watch_issues:
  4094. return ["issues"]
  4095. elif watcher.watch_commits:
  4096. return ["commits"]
  4097. else:
  4098. # If a watcher entry is set and both are set to False, that
  4099. # means the user explicitly asked to not be notified
  4100. return []
  4101. # If the user is the project owner, by default they will be watching
  4102. # issues and PRs
  4103. if user_obj.username == project.user.username:
  4104. return ["issues"]
  4105. # If the user is a contributor, by default they will be watching issues
  4106. # and PRs
  4107. for contributor in project.users:
  4108. if user_obj.username == contributor.username:
  4109. return ["issues"]
  4110. # If the user is in a project group, by default they will be watching
  4111. # issues and PRs
  4112. for group in project.groups:
  4113. for guser in group.users:
  4114. if user_obj.username == guser.username:
  4115. return ["issues"]
  4116. # If no other condition is true, then they are not explicitly watching
  4117. # the project or are not involved in the project to the point that
  4118. # comes with aq default watch level
  4119. return []
  4120. def user_watch_list(session, user, exclude_groups=None):
  4121. """Returns list of all the projects which the user is watching"""
  4122. user_obj = search_user(session, username=user)
  4123. if not user_obj:
  4124. return []
  4125. unwatched = (
  4126. session.query(model.Watcher)
  4127. .filter(model.Watcher.user_id == user_obj.id)
  4128. .filter(model.Watcher.watch_issues == False) # noqa: E712
  4129. .filter(model.Watcher.watch_commits == False) # noqa: E712
  4130. )
  4131. unwatched_list = []
  4132. if unwatched:
  4133. unwatched_list = [unwatch.project for unwatch in unwatched.all()]
  4134. watched = (
  4135. session.query(model.Watcher)
  4136. .filter(model.Watcher.user_id == user_obj.id)
  4137. .filter(model.Watcher.watch_issues == True) # noqa: E712
  4138. .filter(model.Watcher.watch_commits == True) # noqa: E712
  4139. )
  4140. watched_list = []
  4141. if watched:
  4142. watched_list = [watch.project for watch in watched.all()]
  4143. user_projects = search_projects(
  4144. session, username=user_obj.user, exclude_groups=exclude_groups
  4145. )
  4146. watch = set(watched_list + user_projects)
  4147. for project in user_projects:
  4148. if project in unwatched_list:
  4149. watch.remove(project)
  4150. return sorted(list(watch), key=lambda proj: proj.name)
  4151. def set_watch_obj(session, user, obj, watch_status):
  4152. """Set the watch status of the user on the specified object.
  4153. Objects can be either an issue or a pull-request
  4154. """
  4155. user_obj = get_user(session, user)
  4156. if obj.isa == "issue":
  4157. query = (
  4158. session.query(model.IssueWatcher)
  4159. .filter(model.IssueWatcher.user_id == user_obj.id)
  4160. .filter(model.IssueWatcher.issue_uid == obj.uid)
  4161. )
  4162. elif obj.isa == "pull-request":
  4163. query = (
  4164. session.query(model.PullRequestWatcher)
  4165. .filter(model.PullRequestWatcher.user_id == user_obj.id)
  4166. .filter(model.PullRequestWatcher.pull_request_uid == obj.uid)
  4167. )
  4168. else:
  4169. raise pagure.exceptions.InvalidObjectException(
  4170. 'Unsupported object found: "%s"' % obj
  4171. )
  4172. dbobj = query.first()
  4173. if not dbobj:
  4174. if obj.isa == "issue":
  4175. dbobj = model.IssueWatcher(
  4176. user_id=user_obj.id, issue_uid=obj.uid, watch=watch_status
  4177. )
  4178. elif obj.isa == "pull-request":
  4179. dbobj = model.PullRequestWatcher(
  4180. user_id=user_obj.id,
  4181. pull_request_uid=obj.uid,
  4182. watch=watch_status,
  4183. )
  4184. else:
  4185. dbobj.watch = watch_status
  4186. session.add(dbobj)
  4187. output = "You are no longer watching this %s" % obj.isa
  4188. if watch_status:
  4189. output = "You are now watching this %s" % obj.isa
  4190. return output
  4191. def get_watch_list(session, obj):
  4192. """Return a list of all the users that are watching the "object" """
  4193. private = False
  4194. if obj.isa == "issue":
  4195. private = obj.private
  4196. obj_watchers_query = session.query(model.IssueWatcher).filter(
  4197. model.IssueWatcher.issue_uid == obj.uid
  4198. )
  4199. elif obj.isa == "pull-request":
  4200. obj_watchers_query = session.query(model.PullRequestWatcher).filter(
  4201. model.PullRequestWatcher.pull_request_uid == obj.uid
  4202. )
  4203. else:
  4204. raise pagure.exceptions.InvalidObjectException(
  4205. 'Unsupported object found: "%s"' % obj
  4206. )
  4207. project_watchers_query = session.query(model.Watcher).filter(
  4208. model.Watcher.project_id == obj.project.id
  4209. )
  4210. users = set()
  4211. # Add the person who opened the object
  4212. users.add(obj.user.username)
  4213. # Add all the people who commented on that object
  4214. for comment in obj.comments:
  4215. users.add(comment.user.username)
  4216. # Add the user of the project
  4217. users.add(obj.project.user.username)
  4218. # Add the assignee if there is one
  4219. if obj.assignee:
  4220. users.add(obj.assignee.username)
  4221. # Add the regular contributors
  4222. for contributor in obj.project.users:
  4223. users.add(contributor.username)
  4224. # Add people in groups with commit access
  4225. for group in obj.project.groups:
  4226. for member in group.users:
  4227. users.add(member.username)
  4228. # If the issue isn't private:
  4229. if not private:
  4230. # Add all the people watching the repo, remove those who opted-out
  4231. for watcher in project_watchers_query.all():
  4232. if watcher.watch_issues:
  4233. users.add(watcher.user.username)
  4234. else:
  4235. if watcher.user.username in users:
  4236. users.remove(watcher.user.username)
  4237. # Add all the people watching this object, remove those who opted-out
  4238. for watcher in obj_watchers_query.all():
  4239. if watcher.watch:
  4240. users.add(watcher.user.username)
  4241. else:
  4242. if watcher.user.username in users:
  4243. users.remove(watcher.user.username)
  4244. return users
  4245. def save_report(session, repo, name, url, username):
  4246. """Save the report of issues based on the given URL of the project."""
  4247. url_obj = urlparse(url)
  4248. url = url_obj.geturl().replace(url_obj.query, "")
  4249. query = {}
  4250. for k, v in parse_qsl(url_obj.query):
  4251. if k in query:
  4252. if isinstance(query[k], list):
  4253. query[k].append(v)
  4254. else:
  4255. query[k] = [query[k], v]
  4256. else:
  4257. query[k] = v
  4258. reports = repo.reports
  4259. reports[name] = query
  4260. repo.reports = reports
  4261. session.add(repo)
  4262. def set_custom_key_fields(session, project, fields, types, data, notify=None):
  4263. """Set or update the custom key fields of a project with the values
  4264. provided. "data" is currently only used for lists and dates
  4265. """
  4266. current_keys = {}
  4267. for key in project.issue_keys:
  4268. current_keys[key.name] = key
  4269. for idx, key in enumerate(fields):
  4270. if types[idx] == "list":
  4271. if data[idx]:
  4272. data[idx] = [item.strip() for item in data[idx].split(",")]
  4273. elif types[idx] == "date":
  4274. if data[idx]:
  4275. data[idx] = data[idx].strip()
  4276. else:
  4277. data[idx] = None
  4278. if notify and notify[idx] == "on":
  4279. notify_flag = True
  4280. else:
  4281. notify_flag = False
  4282. if key in current_keys:
  4283. issuekey = current_keys[key]
  4284. issuekey.key_type = types[idx]
  4285. issuekey.data = data[idx]
  4286. issuekey.key_notify = notify_flag
  4287. else:
  4288. issuekey = model.IssueKeys(
  4289. project_id=project.id,
  4290. name=key,
  4291. key_type=types[idx],
  4292. data=data[idx],
  4293. key_notify=notify_flag,
  4294. )
  4295. session.add(issuekey)
  4296. # Delete keys
  4297. for key in current_keys:
  4298. if key not in fields:
  4299. session.delete(current_keys[key])
  4300. return "List of custom fields updated"
  4301. def set_custom_key_value(session, issue, key, value):
  4302. """Set or update the value of the specified custom key."""
  4303. query = (
  4304. session.query(model.IssueValues)
  4305. .filter(model.IssueValues.key_id == key.id)
  4306. .filter(model.IssueValues.issue_uid == issue.uid)
  4307. )
  4308. current_field = query.first()
  4309. updated = False
  4310. delete = False
  4311. old_value = None
  4312. if current_field:
  4313. old_value = current_field.value
  4314. if current_field.key.key_type == "boolean":
  4315. value = value or False
  4316. if value is None or value == "":
  4317. session.delete(current_field)
  4318. updated = True
  4319. delete = True
  4320. elif current_field.value != value:
  4321. current_field.value = value
  4322. updated = True
  4323. else:
  4324. if value is None or value == "":
  4325. delete = True
  4326. else:
  4327. current_field = model.IssueValues(
  4328. issue_uid=issue.uid, key_id=key.id, value=value
  4329. )
  4330. updated = True
  4331. if not delete:
  4332. session.add(current_field)
  4333. if REDIS and updated:
  4334. if issue.private:
  4335. REDIS.publish(
  4336. "pagure.%s" % issue.uid,
  4337. json.dumps({"issue": "private", "custom_fields": [key.name]}),
  4338. )
  4339. else:
  4340. REDIS.publish(
  4341. "pagure.%s" % issue.uid,
  4342. json.dumps(
  4343. {
  4344. "custom_fields": [key.name],
  4345. "issue": issue.to_json(
  4346. public=True, with_comments=False
  4347. ),
  4348. }
  4349. ),
  4350. )
  4351. if updated and value:
  4352. output = "Custom field %s adjusted to %s" % (key.name, value)
  4353. if old_value:
  4354. output += " (was: %s)" % old_value
  4355. return output
  4356. elif updated and old_value:
  4357. return "Custom field %s reset (from %s)" % (key.name, old_value)
  4358. def get_yearly_stats_user(session, user, date, tz="UTC"):
  4359. """Return the activity of the specified user in the year preceding the
  4360. specified date. 'offset' is intended to be a timezone offset from UTC,
  4361. in minutes: you can discover the offset for a timezone and pass that
  4362. in order for the results to be relative to that timezone. Note, offset
  4363. should be the amount of minutes that should be added to the UTC time to
  4364. produce the local time - so for timezones behind UTC the number should
  4365. be negative, and for timezones ahead of UTC the number should be
  4366. positive. This is the opposite of what Javascript getTimezoneOffset()
  4367. does, so you have to invert any value you get from that.
  4368. """
  4369. start_date = datetime.datetime(date.year - 1, date.month, date.day)
  4370. events = (
  4371. session.query(model.PagureLog)
  4372. .filter(model.PagureLog.date_created.between(start_date, date))
  4373. .filter(model.PagureLog.user_id == user.id)
  4374. .all()
  4375. )
  4376. # Counter very handily does exactly what we want here: it gives
  4377. # us a dict with the dates as keys and the number of times each
  4378. # date occurs in the data as the values, we return its items as
  4379. # a list of tuples
  4380. return list(Counter([event.date_tz(tz) for event in events]).items())
  4381. def get_user_activity_day(session, user, date, tz="UTC"):
  4382. """Return the activity of the specified user on the specified date.
  4383. 'offset' is intended to be a timezone offset from UTC, in minutes:
  4384. you can discover the offset for a timezone and pass that, so this
  4385. will return activity that occurred on the specified date in the
  4386. desired timezone. Note, offset should be the amount of minutes
  4387. that should be added to the UTC time to produce the local time -
  4388. so for timezones behind UTC the number should be negative, and
  4389. for timezones ahead of UTC the number should be positive. This is
  4390. the opposite of what Javascript getTimezoneOffset() does, so you
  4391. have to invert any value you get from that.
  4392. """
  4393. dt = datetime.datetime.strptime(date, "%Y-%m-%d")
  4394. # if the offset is *negative* some of the events we want may be
  4395. # on the next day in UTC terms. if the offset is *positive* some
  4396. # of the events we want may be on the previous day in UTC terms.
  4397. # 'dt' will be at 00:00, so we subtract 1 day for prevday but add
  4398. # 2 days for nextday. e.g. 2018-02-15 00:00 - prevday will be
  4399. # 2018-02-14 00:00, nextday will be 2018-02-17 00:00. We'll get
  4400. # all events that occurred on 2018-02-14, 2018-02-15 or 2018-02-16
  4401. # in UTC time.
  4402. prevday = dt - datetime.timedelta(days=1)
  4403. nextday = dt + datetime.timedelta(days=2)
  4404. query = (
  4405. session.query(model.PagureLog)
  4406. .filter(model.PagureLog.date_created.between(prevday, nextday))
  4407. .filter(model.PagureLog.user_id == user.id)
  4408. .order_by(model.PagureLog.id.asc())
  4409. )
  4410. events = query.all()
  4411. # Now we filter down to the events that *really* occurred on the
  4412. # date we were asked for with the offset applied, and return
  4413. return [ev for ev in events if ev.date_tz(tz) == dt.date()]
  4414. def get_watchlist_messages(session, user, limit=None):
  4415. watched = user_watch_list(session, user.username)
  4416. watched_list = [watch.id for watch in watched]
  4417. events = (
  4418. session.query(model.PagureLog)
  4419. .filter(model.PagureLog.project_id.in_(watched_list))
  4420. .order_by(model.PagureLog.id.desc())
  4421. )
  4422. if limit is not None:
  4423. events = events.limit(limit)
  4424. events = events.all()
  4425. return events
  4426. def log_action(session, action, obj, user_obj):
  4427. """Log an user action on a project/issue/PR."""
  4428. project_id = None
  4429. if obj.isa in ["issue", "pull-request"]:
  4430. project_id = obj.project_id
  4431. if obj.project.private:
  4432. return
  4433. elif obj.isa == "project":
  4434. project_id = obj.id
  4435. if obj.private:
  4436. return
  4437. else:
  4438. raise pagure.exceptions.InvalidObjectException(
  4439. 'Unsupported object found: "%s"' % obj
  4440. )
  4441. if obj.private:
  4442. return
  4443. log = model.PagureLog(
  4444. user_id=user_obj.id,
  4445. project_id=project_id,
  4446. log_type=action,
  4447. ref_id=obj.id,
  4448. )
  4449. if obj.isa == "issue":
  4450. setattr(log, "issue_uid", obj.uid)
  4451. elif obj.isa == "pull-request":
  4452. setattr(log, "pull_request_uid", obj.uid)
  4453. session.add(log)
  4454. session.commit()
  4455. def email_logs_count(session, email):
  4456. """Returns the number of logs associated with a given email."""
  4457. query = session.query(model.PagureLog).filter(
  4458. model.PagureLog.user_email == email
  4459. )
  4460. return query.count()
  4461. def update_log_email_user(session, email, user):
  4462. """Update the logs with the provided email to point to the specified
  4463. user.
  4464. """
  4465. session.query(model.PagureLog).filter(
  4466. model.PagureLog.user_email == email
  4467. ).update({model.PagureLog.user_id: user.id}, synchronize_session=False)
  4468. def get_custom_key(session, project, keyname):
  4469. """Returns custom key object given it's name and the project"""
  4470. query = (
  4471. session.query(model.IssueKeys)
  4472. .filter(model.IssueKeys.project_id == project.id)
  4473. .filter(model.IssueKeys.name == keyname)
  4474. )
  4475. return query.first()
  4476. def get_active_milestones(session, project):
  4477. """Returns the list of all the active milestones for a given project."""
  4478. query = (
  4479. session.query(model.Issue.milestone)
  4480. .filter(model.Issue.project_id == project.id)
  4481. .filter(model.Issue.status == "Open")
  4482. .filter(model.Issue.milestone.isnot(None))
  4483. )
  4484. return sorted([item[0] for item in query.distinct()])
  4485. def add_metadata_update_notif(session, obj, messages, user):
  4486. """Add a notification to the specified issue with the given messages
  4487. which should reflect changes made to the meta-data of the issue.
  4488. """
  4489. if not messages:
  4490. return
  4491. if not isinstance(messages, (list, set)):
  4492. messages = [messages]
  4493. user_id = None
  4494. if user:
  4495. user_obj = get_user(session, user)
  4496. user_id = user_obj.id
  4497. if obj.isa == "issue":
  4498. obj_comment = model.IssueComment(
  4499. issue_uid=obj.uid,
  4500. comment="**Metadata Update from @%s**:\n- %s"
  4501. % (user, "\n- ".join(sorted(messages))),
  4502. user_id=user_id,
  4503. notification=True,
  4504. )
  4505. obj.last_updated = datetime.datetime.utcnow()
  4506. elif obj.isa == "pull-request":
  4507. obj_comment = model.PullRequestComment(
  4508. pull_request_uid=obj.uid,
  4509. comment="**Metadata Update from @%s**:\n- %s"
  4510. % (user, "\n- ".join(sorted(messages))),
  4511. user_id=user_id,
  4512. notification=True,
  4513. )
  4514. obj.updated_on = datetime.datetime.utcnow()
  4515. session.add(obj)
  4516. session.add(obj_comment)
  4517. # Make sure we won't have SQLAlchemy error before we continue
  4518. session.commit()
  4519. if REDIS:
  4520. REDIS.publish(
  4521. "pagure.%s" % obj.uid,
  4522. json.dumps(
  4523. {
  4524. "comment_id": obj_comment.id,
  4525. "%s_id" % obj.isa: obj.id,
  4526. "project": obj.project.fullname,
  4527. "comment_added": text2markdown(obj_comment.comment),
  4528. "comment_user": obj_comment.user.user,
  4529. "avatar_url": avatar_url_from_email(
  4530. obj_comment.user.default_email, size=16
  4531. ),
  4532. "comment_date": obj_comment.date_created.strftime(
  4533. "%Y-%m-%d %H:%M:%S"
  4534. ),
  4535. "notification": True,
  4536. }
  4537. ),
  4538. )
  4539. pagure.lib.git.update_git(obj, repo=obj.project)
  4540. def tokenize_search_string(pattern):
  4541. """This function tokenizes search patterns into key:value and rest.
  4542. It will also correctly parse key values between quotes.
  4543. """
  4544. if pattern is None:
  4545. return {}, None
  4546. def finalize_token(token, custom_search):
  4547. if ":" in token:
  4548. # This was a "key:value" parameter
  4549. key, value = token.split(":", 1)
  4550. custom_search[key] = value
  4551. return ""
  4552. else:
  4553. # This was a token without colon, thus a search pattern
  4554. return "%s " % token
  4555. custom_search = {}
  4556. # Remaining is the remaining real search_pattern (aka, non-key:values)
  4557. remaining = ""
  4558. # Token is the current "search token" we are processing
  4559. token = ""
  4560. in_quotes = False
  4561. for char in pattern:
  4562. if char == " " and not in_quotes:
  4563. remaining += finalize_token(token, custom_search)
  4564. token = ""
  4565. elif char == '"':
  4566. in_quotes = not in_quotes
  4567. else:
  4568. token += char
  4569. # Parse the final token
  4570. remaining += finalize_token(token, custom_search)
  4571. return custom_search, remaining.strip()
  4572. def get_access_levels(session):
  4573. """Returns all the access levels a user/group can have for a project"""
  4574. access_level_objs = session.query(model.AccessLevels).all()
  4575. return [access_level.access for access_level in access_level_objs]
  4576. def get_obj_access(session, project_obj, obj):
  4577. """Returns the level of access the user/group has on the project.
  4578. :arg session: the session to use to connect to the database.
  4579. :arg project_obj: SQLAlchemy object of Project class
  4580. :arg obj: SQLAlchemy object of either User or PagureGroup class
  4581. """
  4582. if isinstance(obj, model.User):
  4583. query = (
  4584. session.query(model.ProjectUser)
  4585. .filter(model.ProjectUser.project_id == project_obj.id)
  4586. .filter(model.ProjectUser.user_id == obj.id)
  4587. )
  4588. else:
  4589. query = (
  4590. session.query(model.ProjectGroup)
  4591. .filter(model.ProjectGroup.project_id == project_obj.id)
  4592. .filter(model.ProjectGroup.group_id == obj.id)
  4593. )
  4594. return query.first()
  4595. def search_token(
  4596. session,
  4597. acls,
  4598. user=None,
  4599. token=None,
  4600. active=False,
  4601. expired=False,
  4602. description=None,
  4603. ):
  4604. """Searches the API tokens corresponding to the criterias specified.
  4605. :arg session: the session to use to connect to the database.
  4606. :arg acls: List of the ACL associated with these API tokens
  4607. :arg user: restrict the API tokens to this given user
  4608. :arg token: restrict the API tokens to this specified token (if it
  4609. exists)
  4610. :arg description: restrict the API tokens to this given description
  4611. """
  4612. query = (
  4613. session.query(model.Token)
  4614. .filter(model.Token.id == model.TokenAcl.token_id)
  4615. .filter(model.TokenAcl.acl_id == model.ACL.id)
  4616. )
  4617. if acls:
  4618. if isinstance(acls, list):
  4619. query = query.filter(model.ACL.name.in_(acls))
  4620. else:
  4621. query = query.filter(model.ACL.name == acls)
  4622. if user:
  4623. query = query.filter(model.Token.user_id == model.User.id).filter(
  4624. model.User.user == user
  4625. )
  4626. if description:
  4627. query = query.filter(model.Token.description == description)
  4628. if active:
  4629. query = query.filter(
  4630. model.Token.expiration > datetime.datetime.utcnow()
  4631. )
  4632. elif expired:
  4633. query = query.filter(
  4634. model.Token.expiration <= datetime.datetime.utcnow()
  4635. )
  4636. if token:
  4637. query = query.filter(model.Token.id == token)
  4638. return query.first()
  4639. else:
  4640. return query.all()
  4641. def set_project_owner(session, project, user, required_groups=None):
  4642. """Set the ownership of a project
  4643. :arg session: the session to use to connect to the database.
  4644. :arg project: a Project object representing the project's ownership to
  4645. change.
  4646. :arg user: a User object representing the new owner of the project.
  4647. :arg required_groups: a dict of {pattern: [list of groups]} the new user
  4648. should be in to become owner if one of the pattern matches the
  4649. project fullname.
  4650. :return: None
  4651. """
  4652. if required_groups:
  4653. for key in required_groups:
  4654. if fnmatch.fnmatch(project.fullname, key):
  4655. user_grps = set(user.groups)
  4656. req_grps = set(required_groups[key])
  4657. if not user_grps.intersection(req_grps):
  4658. raise pagure.exceptions.PagureException(
  4659. "This user must be in one of the following groups "
  4660. "to be allowed to be added to this project: %s"
  4661. % ", ".join(req_grps)
  4662. )
  4663. for contributor in project.users:
  4664. if user.id == contributor.id:
  4665. project.users.remove(contributor)
  4666. break
  4667. project.user = user
  4668. project.date_modified = datetime.datetime.utcnow()
  4669. session.add(project)
  4670. def get_pagination_metadata(
  4671. flask_request, page, per_page, total, key_page="page"
  4672. ):
  4673. """
  4674. Returns pagination metadata for an API. The code was inspired by
  4675. Flask-SQLAlchemy.
  4676. :param flask_request: flask.request object
  4677. :param page: int of the current page
  4678. :param per_page: int of results per page
  4679. :param total: int of total results
  4680. :param key_page: the name of the argument corresponding to the page
  4681. :return: dictionary of pagination metadata
  4682. """
  4683. pages = int(ceil(total / float(per_page)))
  4684. request_args_wo_page = dict(copy.deepcopy(flask_request.args))
  4685. # Remove pagination related args because those are handled elsewhere
  4686. # Also, remove any args that url_for accepts in case the user entered
  4687. # those in
  4688. for key in [key_page, "per_page", "endpoint"]:
  4689. if key in request_args_wo_page:
  4690. request_args_wo_page.pop(key)
  4691. for key in flask_request.args:
  4692. if key.startswith("_"):
  4693. request_args_wo_page.pop(key)
  4694. request_args_wo_page.update(flask_request.view_args)
  4695. next_page = None
  4696. if page < pages:
  4697. request_args_wo_page.update({key_page: page + 1})
  4698. next_page = url_for(
  4699. flask_request.endpoint,
  4700. per_page=per_page,
  4701. _external=True,
  4702. **request_args_wo_page,
  4703. )
  4704. prev_page = None
  4705. if page > 1:
  4706. request_args_wo_page.update({key_page: page - 1})
  4707. prev_page = url_for(
  4708. flask_request.endpoint,
  4709. per_page=per_page,
  4710. _external=True,
  4711. **request_args_wo_page,
  4712. )
  4713. request_args_wo_page.update({key_page: 1})
  4714. first_page = url_for(
  4715. flask_request.endpoint,
  4716. per_page=per_page,
  4717. _external=True,
  4718. **request_args_wo_page,
  4719. )
  4720. request_args_wo_page.update({key_page: pages})
  4721. last_page = url_for(
  4722. flask_request.endpoint,
  4723. per_page=per_page,
  4724. _external=True,
  4725. **request_args_wo_page,
  4726. )
  4727. return {
  4728. key_page: page,
  4729. "pages": pages,
  4730. "per_page": per_page,
  4731. "prev": prev_page,
  4732. "next": next_page,
  4733. "first": first_page,
  4734. "last": last_page,
  4735. }
  4736. def update_star_project(session, repo, star, user):
  4737. """Unset or set the star status depending on the star value.
  4738. :arg session: the session to use to connect to the database.
  4739. :arg repo: a model.Project object representing the project to star/unstar
  4740. :arg star: '1' for starring and '0' for unstarring
  4741. :arg user: string representing the user
  4742. :return: None or string containing 'You starred this project' or
  4743. 'You unstarred this project'
  4744. """
  4745. if not all([repo, user, star]):
  4746. return
  4747. user_obj = get_user(session, user)
  4748. msg = None
  4749. if star == "1":
  4750. msg = _star_project(session, repo=repo, user=user_obj)
  4751. elif star == "0":
  4752. msg = _unstar_project(session, repo=repo, user=user_obj)
  4753. return msg
  4754. def _star_project(session, repo, user):
  4755. """Star a project
  4756. :arg session: Session object to connect to db with
  4757. :arg repo: model.Project object representing the repo to star
  4758. :arg user: model.User object who is starring this repo
  4759. :return: None or string containing 'You starred this project'
  4760. """
  4761. if not all([repo, user]):
  4762. return
  4763. stargazer_obj = model.Star(project_id=repo.id, user_id=user.id)
  4764. session.add(stargazer_obj)
  4765. return "You starred this project"
  4766. def _unstar_project(session, repo, user):
  4767. """Unstar a project
  4768. :arg session: Session object to connect to db with
  4769. :arg repo: model.Project object representing the repo to unstar
  4770. :arg user: model.User object who is unstarring this repo
  4771. :return: None or string containing 'You unstarred this project'
  4772. or 'You never starred the project'
  4773. """
  4774. if not all([repo, user]):
  4775. return
  4776. # First find the stargazer_obj object
  4777. stargazer_obj = _get_stargazer_obj(session, repo, user)
  4778. if isinstance(stargazer_obj, model.Star):
  4779. session.delete(stargazer_obj)
  4780. msg = "You unstarred this project"
  4781. else:
  4782. msg = "You never starred the project"
  4783. return msg
  4784. def _get_stargazer_obj(session, repo, user):
  4785. """Query the db to find stargazer object with given repo and user
  4786. :arg session: Session object to connect to db with
  4787. :arg repo: model.Project object
  4788. :arg user: model.User object
  4789. :return: None or model.Star object
  4790. """
  4791. if not all([repo, user]):
  4792. return
  4793. stargazer_obj = (
  4794. session.query(model.Star)
  4795. .filter(model.Star.project_id == repo.id)
  4796. .filter(model.Star.user_id == user.id)
  4797. )
  4798. return stargazer_obj.first()
  4799. def has_starred(session, repo, user):
  4800. """Check if a given user has starred a particular project
  4801. :arg session: The session object to query the db with
  4802. :arg repo: model.Project object for which the star is checked
  4803. :arg user: The username of the user in question
  4804. :return: True if user has starred the project, False otherwise
  4805. """
  4806. if not all([repo, user]):
  4807. return
  4808. user_obj = search_user(session, username=user)
  4809. stargazer_obj = _get_stargazer_obj(session, repo, user_obj)
  4810. if isinstance(stargazer_obj, model.Star):
  4811. return True
  4812. return False
  4813. def update_read_only_mode(session, repo, read_only=True):
  4814. """Remove the read only mode from the project
  4815. :arg session: The session object to query the db with
  4816. :arg repo: model.Project object to mark/unmark read only
  4817. :arg read_only: True if project is to be made read only,
  4818. False otherwise
  4819. """
  4820. if (
  4821. not repo
  4822. or not isinstance(repo, model.Project)
  4823. or read_only not in [True, False]
  4824. ):
  4825. return
  4826. helper = pagure.lib.git_auth.get_git_auth_helper()
  4827. if helper.is_dynamic and read_only:
  4828. # No need to set a readonly flag if a dynamic auth backend is in use
  4829. return
  4830. if repo.read_only != read_only:
  4831. repo.read_only = read_only
  4832. session.add(repo)
  4833. def issues_history_stats(session, project, detailed=False, weeks_range=53):
  4834. """Returns the number of opened issues on the specified project over
  4835. the last 365 days
  4836. :arg session: The session object to query the db with
  4837. :arg repo: model.Project object to get the issues stats about
  4838. """
  4839. tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
  4840. current_open = (
  4841. session.query(model.Issue)
  4842. .filter(model.Issue.project_id == project.id)
  4843. .filter(model.Issue.status == "Open")
  4844. .count()
  4845. )
  4846. # Check if the oldest ticket with a closed_at date is older than a year
  4847. # ago, if it is, we will assume that all tickets that were closed last year
  4848. # have a closed_at date set.
  4849. oldest_closed = (
  4850. session.query(model.Issue)
  4851. .filter(model.Issue.project_id == project.id)
  4852. .filter(model.Issue.closed_at != None) # noqa
  4853. .order_by(sqlalchemy.asc(model.Issue.closed_at))
  4854. .first()
  4855. )
  4856. a_year_ago = tomorrow - datetime.timedelta(days=(weeks_range * 7))
  4857. if oldest_closed and oldest_closed.closed_at < a_year_ago:
  4858. to_ignore = 0
  4859. else:
  4860. # Some ticket got imported as closed but without a closed_at date, so
  4861. # let's ignore them all
  4862. to_ignore = (
  4863. session.query(model.Issue)
  4864. .filter(model.Issue.project_id == project.id)
  4865. .filter(model.Issue.closed_at == None) # noqa
  4866. .filter(model.Issue.status == "Closed")
  4867. .count()
  4868. )
  4869. # For each week from tomorrow, get the number of open tickets
  4870. output = {}
  4871. for week in range(weeks_range):
  4872. end = tomorrow - datetime.timedelta(days=(week * 7))
  4873. start = end - datetime.timedelta(days=7)
  4874. closed_ticket = (
  4875. session.query(model.Issue)
  4876. .filter(model.Issue.project_id == project.id)
  4877. .filter(model.Issue.closed_at >= start)
  4878. .filter(model.Issue.closed_at < end)
  4879. ).count()
  4880. query_open = (
  4881. session.query(model.Issue)
  4882. .filter(model.Issue.project_id == project.id)
  4883. .filter(model.Issue.date_created >= start)
  4884. .filter(model.Issue.date_created < end)
  4885. )
  4886. # For backward compatibility
  4887. if detailed is False:
  4888. query_open = query_open.filter(model.Issue.status == "Open")
  4889. open_ticket = query_open.count()
  4890. cnt = open_ticket + closed_ticket - to_ignore
  4891. current_open = current_open - open_ticket + closed_ticket
  4892. if current_open < 0:
  4893. current_open = 0
  4894. if cnt < 0:
  4895. cnt = 0
  4896. if detailed is False:
  4897. output[start.isoformat()] = cnt
  4898. else:
  4899. output[start.isoformat()] = {
  4900. "open_ticket": open_ticket,
  4901. "closed_ticket": closed_ticket,
  4902. "count": current_open,
  4903. }
  4904. return output
  4905. def get_authorized_project(
  4906. session, project_name, user=None, namespace=None, asuser=None
  4907. ):
  4908. """Retrieving the project with user permission constraint
  4909. :arg session: The SQLAlchemy session to use
  4910. :type session: sqlalchemy.orm.session.Session
  4911. :arg project_name: Name of the project on pagure
  4912. :type project_name: String
  4913. :arg user: Pagure username
  4914. :type user: String
  4915. :arg namespace: Pagure namespace
  4916. :type namespace: String
  4917. :arg asuser: Username to check for access
  4918. :type asuser: String
  4919. :return: The project object if project is public or user has
  4920. permissions for the project else it returns None
  4921. :rtype: Project
  4922. """
  4923. repo = _get_project(session, project_name, user, namespace)
  4924. if repo and repo.private and not pagure.utils.is_repo_user(repo, asuser):
  4925. return None
  4926. return repo
  4927. def get_project_family(session, project):
  4928. """Retrieve the family of the specified project, ie: all the forks
  4929. of the main project.
  4930. If the specified project is a fork, let's work our way up the chain
  4931. until we find the main project so we can go down and get all the forks
  4932. and the forks of the forks (but not one level more).
  4933. :arg session: The SQLAlchemy session to use
  4934. :type session: sqlalchemy.orm.session.Session
  4935. :arg project: The project whose family is searched
  4936. :type project: pagure.lib.model.Project
  4937. """
  4938. parent = project
  4939. while parent.is_fork:
  4940. parent = parent.parent
  4941. sub = session.query(sqlalchemy.distinct(model.Project.id)).filter(
  4942. model.Project.parent_id == parent.id
  4943. )
  4944. query = (
  4945. session.query(model.Project)
  4946. .filter(
  4947. sqlalchemy.or_(
  4948. model.Project.parent_id.in_(sub.subquery()),
  4949. model.Project.parent_id == parent.id,
  4950. )
  4951. )
  4952. .filter(model.Project.user_id == model.User.id)
  4953. .order_by(model.User.user)
  4954. )
  4955. return [parent] + query.all()
  4956. def link_pr_issue(session, issue, request, origin="commit"):
  4957. """Associate the specified issue with the specified pull-requets.
  4958. :arg session: The SQLAlchemy session to use
  4959. :type session: sqlalchemy.orm.session.Session
  4960. :arg issue: The issue mentioned in the commits of the pull-requests to
  4961. be associated with
  4962. :type issue: pagure.lib.model.Issue
  4963. :arg request: A pull-request to associate the specified issue with
  4964. :type request: pagure.lib.model.PullRequest
  4965. """
  4966. associated_issues = [iss.uid for iss in request.related_issues]
  4967. if issue.uid not in associated_issues:
  4968. obj = model.PrToIssue(
  4969. pull_request_uid=request.uid, issue_uid=issue.uid, origin=origin
  4970. )
  4971. session.add(obj)
  4972. session.flush()
  4973. def remove_user_of_project(session, user, project, agent):
  4974. """Remove the specified user from the given project.
  4975. :arg session: the session with which to connect to the database.
  4976. :arg user: an pagure.lib.model.User object to remove from the project.
  4977. :arg project: an pagure.lib.model.Project object from which to remove
  4978. the specified user.
  4979. :arg agent: the username of the user performing the action.
  4980. """
  4981. userids = [u.id for u in project.users]
  4982. if user.id not in userids:
  4983. raise pagure.exceptions.PagureException(
  4984. "User does not have any access on the repo"
  4985. )
  4986. for u in project.users:
  4987. if u.id == user.id:
  4988. user = u
  4989. project.users.remove(u)
  4990. break
  4991. # Mark the project as read_only, celery will unmark it
  4992. update_read_only_mode(session, project, read_only=True)
  4993. session.commit()
  4994. pagure.lib.git.generate_gitolite_acls(project=project)
  4995. pagure.lib.notify.log(
  4996. project,
  4997. topic="project.user.removed",
  4998. msg=dict(
  4999. project=project.to_json(public=True),
  5000. removed_user=user.username,
  5001. agent=agent,
  5002. ),
  5003. )
  5004. return "User removed"
  5005. def create_board(session, project, name, active, tag):
  5006. """Create a board on a given project.
  5007. :arg session: the session with which to connect to the database.
  5008. :arg project: the model.Project of the project that is creating the
  5009. board.
  5010. :arg name: the name of the board to create.
  5011. :arg active: a boolean specifying if the board is active or not.
  5012. :arg tag: the name of the tag associated with this board.
  5013. """
  5014. tag_obj = get_colored_tag(session=session, tag=tag, project_id=project.id)
  5015. if not tag_obj:
  5016. raise pagure.exceptions.PagureException(
  5017. "No tag found with the name %s" % tag
  5018. )
  5019. board = model.Board(
  5020. project_id=project.id, name=name, active=active, tag_id=tag_obj.id
  5021. )
  5022. session.add(board)
  5023. return board
  5024. def edit_board(session, project, name, active, tag, bg_color=None):
  5025. """Edit an existing board on a given project.
  5026. :arg session: the session with which to connect to the database.
  5027. :arg project: the model.Project of the project that is creating the
  5028. board.
  5029. :arg name: the name of the board to create.
  5030. :arg active: a boolean specifying if the board is active or not.
  5031. :arg tag: the name of the tag associated with this board.
  5032. """
  5033. tag_obj = get_colored_tag(session=session, tag=tag, project_id=project.id)
  5034. if not tag_obj:
  5035. raise pagure.exceptions.PagureException(
  5036. "No tag found with the name %s" % tag
  5037. )
  5038. board_obj = None
  5039. for board in project.boards:
  5040. if board.name == name:
  5041. board_obj = board
  5042. break
  5043. if not board_obj:
  5044. raise pagure.exceptions.PagureException(
  5045. 'Could not find the board "%s"' % name
  5046. )
  5047. board.active = active
  5048. board.tag_id = tag_obj.id
  5049. if bg_color:
  5050. board.bg_colar = bg_color
  5051. session.add(board)
  5052. return board
  5053. def delete_board(session, project, names):
  5054. """Delete boards of a given project.
  5055. :arg session: the session with which to connect to the database.
  5056. :arg project: the model.Project of the project that is creating the
  5057. board.
  5058. :arg names: a list of the name of the boards to remove.
  5059. """
  5060. for name in names:
  5061. board_obj = None
  5062. for board in project.boards:
  5063. if board.name == name:
  5064. board_obj = board
  5065. break
  5066. if board_obj:
  5067. session.delete(board_obj)
  5068. def update_board_status(
  5069. session, board, name, rank, default, close, close_status, bg_color
  5070. ):
  5071. """Create or update the board statuses of a project.
  5072. :arg session: the session with which to connect to the database.
  5073. :arg board: the model.Board of the board being updated.
  5074. :arg name: the name of the status.
  5075. :arg rank: the position of the status on the board, the lower the value,
  5076. the more to the left the status.
  5077. :arg default: whether tickets are added to this status by default.
  5078. :arg close: boolean indicating if ticket reaching this status should
  5079. be closed or not
  5080. :arg close_status: the close_status ticket reaching this status should
  5081. be close as.
  5082. :arg bg_color: the background color of the status on the board.
  5083. """
  5084. status = (
  5085. session.query(model.BoardStatus)
  5086. .filter(model.BoardStatus.board_id == board.id)
  5087. .filter(model.BoardStatus.name == name)
  5088. .first()
  5089. )
  5090. if status:
  5091. status.default = default
  5092. status.rank = rank
  5093. status.bg_color = bg_color
  5094. status.close = close
  5095. status.close_status = close_status
  5096. else:
  5097. status = model.BoardStatus(
  5098. board_id=board.id,
  5099. name=name,
  5100. rank=rank,
  5101. default=default,
  5102. bg_color=bg_color,
  5103. close=close,
  5104. close_status=close_status,
  5105. )
  5106. session.add(status)
  5107. return status
  5108. def add_issue_to_boards(
  5109. session, issue, board_name, user, status_id=None, rank=None
  5110. ):
  5111. """Add the given issue to the boards specified.
  5112. :arg session: the session with which to connect to the database.
  5113. :arg issue: the model.Issue of the issue to add to the boards.
  5114. :arg board_names: a list of board name to which the issue should be added.
  5115. :arg user: the username of the user performing the action
  5116. :kwarg rank: the rank of the issue on the status.
  5117. :kwarg rank: the rank of the issue on the status.
  5118. """
  5119. get_user(session, user)
  5120. board_obj = None
  5121. for board in issue.project.boards:
  5122. if board.name == board_name:
  5123. board_obj = board
  5124. break
  5125. if not board_obj:
  5126. _log.info(
  5127. "Could not add issue %s to %s : board not found", issue, board_name
  5128. )
  5129. raise pagure.exceptions.PagureException("Board not found")
  5130. status = (
  5131. session.query(model.BoardStatus)
  5132. .filter(model.BoardStatus.id == status_id)
  5133. .first()
  5134. )
  5135. if not status:
  5136. status = board.default_status
  5137. if not status:
  5138. raise pagure.exceptions.PagureException(
  5139. "No status provided or default status found"
  5140. )
  5141. if rank is None:
  5142. rank = len(status.boards_issues) + 1
  5143. board_issue = model.BoardIssues(
  5144. issue_uid=issue.uid,
  5145. status_id=status.id,
  5146. rank=rank,
  5147. )
  5148. session.add(board_issue)
  5149. def remove_issue_from_boards(session, issue, board_names, user):
  5150. """Remove the given issue from the specified boards.
  5151. :arg session: the session with which to connect to the database.
  5152. :arg issue: the model.Issue of the issue to add to the boards.
  5153. :arg board_names: a list of board name to which the issue should be added.
  5154. :arg user: the username of the user performing the action
  5155. """
  5156. get_user(session, user)
  5157. for board_issue in issue.boards_issues:
  5158. if board_issue.board.active and board_issue.board.name in board_names:
  5159. _log.debug("Removing %s from %s", board_issue, issue)
  5160. session.delete(board_issue)
  5161. def update_ticket_board_status(
  5162. session,
  5163. board,
  5164. user,
  5165. rank=None,
  5166. status_name=None,
  5167. ticket_uid=None,
  5168. ticket_id=None,
  5169. ):
  5170. """Set the status of a ticket on a given board."""
  5171. if not ticket_uid and not ticket_id:
  5172. raise pagure.exceptions.PagureException(
  5173. "One of ticket_id/ticket_uid must be provided"
  5174. )
  5175. if ticket_uid:
  5176. _log.debug(
  5177. "Looking to add ticket %s to board %s with status %s (rank %s)",
  5178. ticket_uid,
  5179. board.name,
  5180. status_name,
  5181. rank,
  5182. )
  5183. ticket = get_issue_by_uid(session, ticket_uid)
  5184. else:
  5185. _log.debug(
  5186. "Looking to add ticket %s to board %s with status %s (rank %s)",
  5187. ticket_id,
  5188. board.name,
  5189. status_name,
  5190. rank,
  5191. )
  5192. ticket = search_issues(session, board.project, issueid=ticket_id)
  5193. if not ticket:
  5194. raise pagure.exceptions.PagureException(
  5195. "No ticket found with this identifier"
  5196. )
  5197. _log.debug("Ticket found")
  5198. status = (
  5199. session.query(model.BoardStatus)
  5200. .filter(model.BoardStatus.board_id == board.id)
  5201. .filter(model.BoardStatus.name == status_name)
  5202. .first()
  5203. )
  5204. if not status:
  5205. _log.debug(
  5206. "No status found with %s, using the default status" % status_name
  5207. )
  5208. status = board.default_status
  5209. if not status:
  5210. raise pagure.exceptions.PagureException(
  5211. "No status provided or default status found"
  5212. )
  5213. if rank is None:
  5214. rank = len(status.boards_issues) + 1
  5215. comments = []
  5216. seen = []
  5217. if ticket.boards_issues:
  5218. for board_issue in ticket.boards_issues:
  5219. if board_issue.status.board.name == board.name:
  5220. _log.debug("Updating existing board")
  5221. board_issue.status_id = status.id
  5222. board_issue.rank = rank
  5223. session.add(board_issue)
  5224. seen.append(board.name)
  5225. break
  5226. if board.name not in seen:
  5227. _log.debug("Adding to a new board")
  5228. board_issue = model.BoardIssues(
  5229. issue_uid=ticket.uid,
  5230. status_id=status.id,
  5231. rank=rank,
  5232. )
  5233. session.add(board_issue)
  5234. # Flag the ticket if needed
  5235. if board.tag.tag not in ticket.tags_text:
  5236. add_tag_obj(session, obj=ticket, tags=board.tag.tag, user=user)
  5237. comments.append(
  5238. "%s tagged with: %s" % (ticket.isa.capitalize(), board.tag.tag)
  5239. )
  5240. if status.close and ticket.status == "Open":
  5241. _log.debug(
  5242. "Closing ticket %s as the new status on the board is "
  5243. "set to close tickets",
  5244. ticket,
  5245. )
  5246. comments.extend(
  5247. edit_issue(
  5248. session=session,
  5249. issue=ticket,
  5250. user=user,
  5251. status="Closed",
  5252. close_status=status.close_status or None,
  5253. )
  5254. )
  5255. session.add(ticket)
  5256. elif not status.close and ticket.status != "Open":
  5257. comments.extend(
  5258. edit_issue(
  5259. session=session,
  5260. issue=ticket,
  5261. user=user,
  5262. status="Open",
  5263. )
  5264. )
  5265. session.add(ticket)
  5266. if comments:
  5267. add_issue_comment(
  5268. session=session,
  5269. issue=ticket,
  5270. comment="\n".join(comments),
  5271. user=user,
  5272. notification=True,
  5273. )
  5274. def find_warning_characters(repo_obj, commits):
  5275. """Return whether the given list of commits of the specified repository
  5276. object contains forbidden characters or not.
  5277. """
  5278. warn_characters = pagure_config["PR_WARN_CHARACTERS"]
  5279. for commit in commits:
  5280. if commit.parents:
  5281. diff = repo_obj.diff(commit.parents[0], commit)
  5282. else:
  5283. # First commit in the repo
  5284. diff = commit.tree.diff_to_tree(swap=True)
  5285. for patch in diff:
  5286. for hunk in patch.hunks:
  5287. for line in hunk.lines:
  5288. subset = [c for c in line.content if c in warn_characters]
  5289. if subset:
  5290. return True
  5291. return False