Skip to content

Commit

Permalink
feat: add comment
Browse files Browse the repository at this point in the history
  • Loading branch information
RaoHai committed Apr 14, 2024
1 parent 4f622d0 commit 4990399
Show file tree
Hide file tree
Showing 17 changed files with 572 additions and 323 deletions.
2 changes: 1 addition & 1 deletion .aws/petercat-preview.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ region = "ap-northeast-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
disable_rollback = true
image_repositories = ["FastAPIFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/petercatapipreview49199518/fastapifunctionead79d0drepo", "SQSSubscriptionFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/petercatapipreview49199518/sqssubscriptionfunctiona2fc8b7drepo"]
image_repositories = ["FastAPIFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/petercatapipreview49199518/fastapifunctionead79d0drepo"]
2 changes: 1 addition & 1 deletion .aws/petercat-prod.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ region = "ap-northeast-1"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
disable_rollback = true
image_repositories = ["FastAPIFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/samapp7427b055/fastapifunctionead79d0drepo", "SQSSubscriptionFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/samapp7427b055/sqssubscriptionfunctiona2fc8b7drepo"]
image_repositories = ["FastAPIFunction=654654285942.dkr.ecr.ap-northeast-1.amazonaws.com/samapp7427b055/fastapifunctionead79d0drepo"]
7 changes: 0 additions & 7 deletions server/dao/BaseDAO.py

This file was deleted.

41 changes: 0 additions & 41 deletions server/dao/authorization.py

This file was deleted.

27 changes: 27 additions & 0 deletions server/event_handler/pull_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

from typing import Any, Dict, Union
from typing_extensions import NotRequired, TypedDict
from github import GithubObject, PullRequest, Repository, Organization, Installation, PullRequestComment
from github import Github, Auth

class PullRequestEventHandler():
event: Any
auth: Auth.AppAuth
g: Github

def __init__(self, payload, auth: Auth.AppAuth) -> None:
self.event = payload
self.auth = auth
self.g = Github(auth=auth)

def execute(self):
match self.event['action']:
case 'opened':
repo = self.g.get_repo(self.event['repository']["full_name"])
pr = repo.get_pull(self.event["pull_request"]["number"])
comment = pr.create_issue_comment("This is a comment from PeterCat")

print(repo, pr, comment)
return { "success": True }
case _:
return { "success": True }
3 changes: 1 addition & 2 deletions server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from data_class import ChatData

# Import fastapi routers
from routers import health_checker, messages, github
from routers import health_checker, github

open_api_key = get_env_variable("OPENAI_API_KEY")
is_dev = bool(get_env_variable("IS_DEV"))
Expand All @@ -32,7 +32,6 @@
)

app.include_router(health_checker.router)
app.include_router(messages.router)
app.include_router(github.router)


Expand Down
102 changes: 0 additions & 102 deletions server/message_queue/queue_wrapper.py

This file was deleted.

25 changes: 0 additions & 25 deletions server/models/authorization.py

This file was deleted.

2 changes: 1 addition & 1 deletion server/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ httpx[socks]
load_dotenv
supabase
boto3>=1.34.84
jwt
pyjwt>=2.4.0
pydantic>=2.7.0
80 changes: 20 additions & 60 deletions server/routers/github.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from fastapi import APIRouter, BackgroundTasks, Header, Request
import logging
import requests
import time
from dao.authorization import AuthorizationDAO
import boto3
from botocore.exceptions import ClientError
from jwt import JWT, jwk_from_pem
from models.authorization import Authorization
# from jwt import JWT, jwk_from_pem
from event_handler.pull_request import PullRequestEventHandler
from github import Auth

from uilts.env import get_env_variable

Expand All @@ -24,7 +22,7 @@
responses={404: {"description": "Not found"}},
)

def get_pem():
def get_private_key():
secret_name = "prod/githubapp/petercat/pem"
region_name = "ap-northeast-1"
session = boto3.session.Session()
Expand All @@ -43,63 +41,25 @@ def get_pem():

return get_secret_value_response['SecretString']

def get_jwt():
payload = {
# Issued at time
'iat': int(time.time()),
# JWT expiration time (10 minutes maximum)
'exp': int(time.time()) + 600,
# GitHub App's identifier
'iss': APP_ID
}

pem = get_pem()
signing_key = jwk_from_pem(pem.encode("utf-8"))

print(pem)
jwt_instance = JWT()
return jwt_instance.encode(payload, signing_key, alg='RS256')

def get_app_installations_access_token(installation_id: str, jwt: str):
url = f"https://api.github.com/app/installations/{installation_id}/access_tokens"
print("get_app_installations_access_token", url, jwt)
resp = requests.post(url,
headers={
'X-GitHub-Api-Version': '2022-11-28',
'Accept': 'application/vnd.github+json',
'Authorization': f"Bearer {jwt}"
}
)

return resp.json()

# https://github.com/login/oauth/authorize?client_id=Iv1.c2e88b429e541264
@router.get("/app/installation/callback")
def github_app_callback(code: str, installation_id: str, setup_action: str):
authorizationDAO = AuthorizationDAO()

if setup_action != "install":
return { "success": False, "message": f"Invalid setup_action value {setup_action}" }
elif authorizationDAO.exists(installation_id=installation_id):
return { "success": False, "message": f"Installation_id {installation_id} Exists" }
else:
jwt = get_jwt()
access_token = get_app_installations_access_token(installation_id=installation_id, jwt=jwt)
authorization = Authorization(
**access_token,
code=code,
installation_id=installation_id,
created_at=int(time.time())
)

success, message = authorizationDAO.create(authorization)

return { "success": success, "message": message }
return { "success": True }

@router.post("/app/webhook")
async def github_app_webhook(request: Request, background_tasks: BackgroundTasks, x_github_event: str = Header(...)):
payload = await request.body()
print("x_github_event=", x_github_event)
print("payload=", payload)
logger.info("github_app_webhook: x_github_event=%s, %s", x_github_event, payload)
return {"hello": "world"}
payload = await request.json()

if "installation" in payload:
installation_id = payload["installation"]["id"]
auth = Auth.AppAuth(app_id=APP_ID, private_key=get_private_key(), jwt_algorithm="RS256").get_installation_auth(installation_id=int(installation_id))

match x_github_event:
case 'pull_request':
handler = PullRequestEventHandler(payload=payload, auth=auth)
handler.execute()
case _:
return { "success": True }
else:
return { "success": False, "message": "Invalid Webhook request"}

26 changes: 0 additions & 26 deletions server/routers/messages.py

This file was deleted.

13 changes: 0 additions & 13 deletions subscriber/Dockerfile

This file was deleted.

Empty file removed subscriber/requirements.txt
Empty file.
Loading

0 comments on commit 4990399

Please sign in to comment.