query.py 174 KB

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