3 namespace app\Controller\Github\Hook
;
7 use app\Model\Accounts
;
11 class Receive
implements Controller
17 function __construct(Web
$app, API
$github, Accounts
$accounts) {
19 $this->github
= $github;
20 $this->accounts
= $accounts;
23 function __invoke(array $args = null) {
24 $request = $this->app
->getRequest();
25 $response = $this->app
->getResponse();
27 if (!($sig = $request->getHeader("X-Hub-Signature")) ||
!($evt = $request->getHeader("X-Github-Event"))) {
28 $response->setResponseCode(400);
29 $response->setContentType("message/http");
30 $response->getBody()->append($request);
32 $key = $this->github
->getConfig()->client
->secret
;
33 foreach ((new Params($sig))->params
as $algo => $mac) {
34 if ($mac["value"] !== hash_hmac($algo, $request->getBody(), $key)) {
35 $response->setResponseCode(403);
36 $response->getBody()->append("Invalid signature");
44 $response->setResponseCode(202);
45 $response->getBody()->append("Not a configured event");
48 $response->setResponseCode(204);
49 $response->setResponseStatus("PONG");
53 if (($json = json_decode($request->getBody()))) {
54 if (($queue = $this->$evt($json))) {
55 $queue->done(function($result) use($response) {
56 list($created) = $result;
57 $response->setResponseCode(201);
58 $response->setHeader("Location", $created->url
);
60 $this->github
->drain();
63 $response->setResponseCode(415);
64 $response->setContentType($request->getHeader("Content-Type"));
65 $response->getBody()->append($request->getBody());
71 private function setTokenForUser($login) {
73 $this->accounts
->getTokens()->getRelation("accounts"),
74 $this->accounts
->getOwners()->getRelation("accounts")
76 $tokens = $this->accounts
->getTokens()->with($relations, [
78 "tokens.authority=" => "github",
82 $this->github
->setToken($tokens->current()->token
->get());
86 private function release($release) {
87 $response = $this->app
->getResponse();
89 if ($release->action
!== "published") {
90 $response->setResponseCode(202);
91 $response->getBody()->append("Not published");
92 } elseif (!empty($release->release
->assets
)) {
93 foreach ($release->release
->assets
as $asset) {
94 if ($asset->content_type
=== "application/phar") {
95 /* we've already uploaded the asset when we created the release */
96 $response->setResponseCode(202);
97 $response->getBody()->append("Already published");
103 $this->setTokenForUser($release->repository
->owner
->login
);
104 return $this->github
->uploadAssetForRelease(
110 private function create($create) {
111 $response = $this->app
->getResponse();
113 if ($create->ref_type
!== "tag") {
114 $response->setResponseCode(202);
115 $response->getBody()->append("Not a tag");
119 $this->setTokenForUser($create->repository
->owner
->login
);
120 return $this->github
->createReleaseFromTag(