Skip to content

Commit

Permalink
update api routes
Browse files Browse the repository at this point in the history
  • Loading branch information
chriswebb09 committed Jan 9, 2024
1 parent 58f0d75 commit 4d26ffd
Show file tree
Hide file tree
Showing 13 changed files with 235 additions and 241 deletions.
137 changes: 137 additions & 0 deletions DirectReport/browserview/api/reports.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,149 @@
#!/usr/bin/env python3

from datetime import datetime, timedelta
import requests
from flask import session, request, json, jsonify
from flask_login import login_required, current_user
from DirectReport.models.user_model import UserModel
from DirectReport.models.report.report_builder import ReportBuilder
from DirectReport.browserview.services.prompt_logic import generate_email, team_summary_from_shortlog
from DirectReport.browserview.services.github import GithubClient
from DirectReport.browserview.api import bp
from DirectReport.datadependencies import appsecrets

client_id = appsecrets.GITHUB_CLIENT_ID
client_secret = appsecrets.GITHUB_CLIENT_SECRET


@bp.route("/reports/list", methods=['GET'])
@login_required
def get_list():
reports = ReportBuilder.get_reports_for_user_id(current_user.id)
return reports, 201


@bp.route("/reports/update", methods=['GET', 'POST'])
@login_required
def dashboard_reports_update():
prompt = ""
prompt = request.get_json()["prompt"].strip()
client = GithubClient()
h_token = session['header_token']
user_repos = client.get_user_repos(current_user.github_username, h_token)
commits_count_last_month = client.get_commits_count_in_last_month(
current_user.github_username, current_user.github_repo, h_token
)
commits_count_last_sixty = client.get_commits_count_in_last_sixty_days(
current_user.github_username, current_user.github_repo, h_token
)
commits_count_last_ninety = client.get_commits_count_in_last_ninety_days(
current_user.github_username, current_user.github_repo, h_token
)

get_pull_requests_count = client.get_pull_requests_count(
current_user.github_username, current_user.github_repo, h_token
)
get_pull_requests_count_sixty = client.get_pull_requests_count_sixty_days(
current_user.github_username, current_user.github_repo, h_token
)
repo_data = []
for repo in user_repos:
repo_data.append(repo["name"])
raw_data = team_summary_from_shortlog(prompt)["choices"][0]["message"]["content"]
response_data = json.loads(raw_data)
response_data["commit_nums"] = {
"15 days": 4,
"30 days": (commits_count_last_month / 10),
"60 days": (commits_count_last_sixty / 10),
"90 days": (commits_count_last_ninety / 10),
"120 days": 10,
}
response_data["pull_requests"] = {
"30 days": get_pull_requests_count,
"60 days": get_pull_requests_count_sixty,
"90 days": 8,
"120 days": 10,
"150 days": 10,
"1 year": 30,
}
response_data["repos"] = repo_data
print(response_data)
ReportBuilder.new(response_data, prompt, current_user.id, current_user.github_repo)
return response_data, 201


@bp.route('/repo', methods=['GET', 'POST'])
def reponame():
args_url = request.args.get('repo_url')
repo = args_url.split('/')[1]
h_token = session['header_token']
repo_name = "https://api.github.com/repos/" + args_url + "/commits"
client = GithubClient()
user_model = UserModel()
user_model.update_github_repo(current_user.email, repo)

headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer ' + h_token,
'X-GitHub-Api-Version': '2022-11-28',
}

test = client.get_commits_in_last_month(current_user.github_username, current_user.github_repo, h_token)
print(test)
json_response_data = json.dumps(test)
print(json_response_data)
json_response_data_loads = json.loads(json_response_data)
print(json_response_data_loads)
res_json = {"json_array": json_response_data_loads}
return res_json, 200
# response_data = requests.get(url=repo_name, headers=headers, auth=(client_id, client_secret))
# if response_data.status_code == 200:
# json_response_data = json.loads(response_data.content)
# res_json = {"json_array": json_response_data}
# return res_json, 200
# else:
# return jsonify([]), 200


@bp.route('/repos', methods=['GET', 'POST'])
def repos():
if request.method == 'GET':
h_token = session['header_token']
username = current_user.github_username
url = f"https://api.github.com/users/{username}/repos" + "?sort=updated&direction=desc"
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer ' + h_token,
'X-GitHub-Api-Version': '2022-11-28',
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
repos = response.json()
results = []
for repo in repos:
owner = repo['owner']
url_repo = repo['url']
data_res = {
"name": repo['name'],
"description": repo['description'],
"url": repo['url'],
'url_repo': url_repo,
"owner_url": owner['url'],
}
results.append(data_res)
return jsonify(results), 200
else:
print(f"Error Response FROM API: {response.status_code} - {response.text}")
return jsonify([]), 200
else:
return jsonify([]), 200


@bp.route("/generate_email", methods=['POST'])
def generateemail():
prompt = ""
if request.method == "POST":
prompt = json.dumps(request.get_json()["prompt"])
report = generate_email(prompt)
elements = {"email": report.choices[0].message.content}
return elements, 201
63 changes: 2 additions & 61 deletions DirectReport/browserview/dashboard/routes.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
#!/usr/bin/env python3

import requests
from flask import render_template, session, request, redirect, json, jsonify
from flask_login import login_user, login_required, logout_user, current_user
import re
from flask import render_template
from flask_login import login_required, current_user
from DirectReport.browserview.dashboard import bp
from DirectReport.models.report.report_builder import ReportBuilder
from DirectReport.browserview.services.github import GithubClient
from DirectReport.browserview.services.huggingface_client import HuggingFaceClient
from DirectReport.browserview.services.googleai_client import GoogleAIClient
from DirectReport.browserview.services.prompt_logic import generate_email, team_summary_from_shortlog
from DirectReport.models.report.report_model import ReportModel
from DirectReport.datadependencies import appsecrets

client_id = appsecrets.GITHUB_CLIENT_ID
Expand All @@ -36,7 +30,6 @@ def dashboard_reports_saved():
Retrieves and renders the list of all entries.
:return: Rendered HTML template for the list page.
"""

results = requests.get('http://127.0.0.1:5000/api/reports/list')
return render_template('list.html', title='List', data=results)

Expand All @@ -47,63 +40,11 @@ def dashboard_reports_new():
return render_template('team/teamreport.html', title='Team Report', data=[])


@bp.route("/reports/update", methods=['GET', 'POST'])
@login_required
def dashboard_reports_update():
prompt = ""
# googleAi = GoogleAIClient()
prompt = request.get_json()["prompt"].strip()
client = GithubClient()
h_token = session['header_token']
user_repos = client.get_user_repos(current_user.github_username, h_token)
commits_last_month = client.get_commits_in_last_month(
current_user.github_username, current_user.github_repo, h_token
)
commits_last_sixty = client.get_commits_in_last_sixty_days(
current_user.github_username, current_user.github_repo, h_token
)
commits_last_ninety = client.get_commits_in_last_ninety_days(
current_user.github_username, current_user.github_repo, h_token
)
get_pull_requests_count = client.get_pull_requests_count(
current_user.github_username, current_user.github_repo, h_token
)
get_pull_requests_count_sixty = client.get_pull_requests_count_sixty_days(
current_user.github_username, current_user.github_repo, h_token
)
repo_data = []
for repo in user_repos:
repo_data.append(repo["name"])
raw_data = team_summary_from_shortlog(prompt)["choices"][0]["message"]["content"]
response_data = json.loads(raw_data)
print(response_data)
response_data["commit_nums"] = {
"15 days": 4,
"30 days": (commits_last_month / 10),
"60 days": (commits_last_sixty / 10),
"90 days": (commits_last_ninety / 10),
"120 days": 10,
}
response_data["pull_requests"] = {
"30 days": get_pull_requests_count,
"60 days": get_pull_requests_count_sixty,
"90 days": 8,
"120 days": 10,
"150 days": 10,
"1 year": 30,
}
response_data["repos"] = repo_data
print(repo_data)
ReportBuilder.new(response_data, prompt, current_user.id, current_user.github_repo)
return response_data, 201


@bp.route("/reports/<uid>", methods=['GET'])
@login_required
def dashboard_saved_report(uid=None):
reports = ReportBuilder.get_reports_for_user_id(current_user.id)
report = list(filter(lambda report: report["uuid"] == uid, reports))[0]
print(report)
report["commit_nums"] = {
"15 days": 4,
"30 days": (8 / 10),
Expand Down
2 changes: 0 additions & 2 deletions DirectReport/browserview/errors/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@ def page_not_found(e):
:return: Rendered HTML template for the 404 error page.
"""
if wants_json_response():
print(e)
return api_error_response(404)
return render_template('404.html', error=e), 404


@bp.app_errorhandler(500)
def internal_error(error):
if wants_json_response():
print(error)
return api_error_response(500)
return render_template('500.html', error=error), 500
87 changes: 0 additions & 87 deletions DirectReport/browserview/main/routes.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
#!/usr/bin/env python3

from datetime import datetime, timedelta

import requests
from flask import render_template, session, request, redirect, json, jsonify
from flask_login import current_user

from DirectReport.models.user_model import UserModel
from DirectReport.browserview.main import bp
from DirectReport.browserview.services.github import GithubClient
from DirectReport.browserview.services.prompt_logic import generate_email
from DirectReport.datadependencies import appsecrets


Expand Down Expand Up @@ -42,45 +38,6 @@ def oauth2_authorize():
return redirect(github_url)


def get_commits_last_month(repo_name):
owner = current_user.github_username
url = f'https://api.github.com/repos/{owner}/{repo_name}/pulls'
h_token = session['header_token']
headers = {"Authorization": f"token {h_token}"}
since_date = (datetime.utcnow() - timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%SZ')
params = {'state': 'all', 'sort': 'created', 'direction': 'desc', 'since': since_date}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
pull_requests = response.json()
return pull_requests
else:
print(f"Error: {response.status_code}")
print(response.text)


@bp.route('/repo', methods=['GET', 'POST'])
def reponame():
args_url = request.args.get('repo_url')
repo = args_url.split('/')[1]
h_token = session['header_token']
repo_name = "https://api.github.com/repos/" + args_url + "/commits"
user_model = UserModel()
user_model.update_github_repo(current_user.email, repo)
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer ' + h_token,
'X-GitHub-Api-Version': '2022-11-28',
}
response_data = requests.get(url=repo_name, headers=headers, auth=(client_id, client_secret))
print(response_data)
if response_data.status_code == 200:
json_response_data = json.loads(response_data.content)
res_json = {"json_array": json_response_data}
return res_json, 200
else:
return jsonify([]), 200


@bp.route('/callback/github', methods=['GET', 'POST'])
def ouath2_callback():
data = {'client_id': client_id, 'client_secret': client_secret, 'code': request.args.get("code")}
Expand All @@ -107,55 +64,11 @@ def ouath2_callback():
return render_template('team/teamreport.html', title='Team', data=[])


@bp.route('/repos', methods=['GET', 'POST'])
def repos():
if request.method == 'GET':
h_token = session['header_token']
username = current_user.github_username
url = f"https://api.github.com/users/{username}/repos" + "?sort=updated&direction=desc"
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer ' + h_token,
'X-GitHub-Api-Version': '2022-11-28',
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
repos = response.json()
results = []
for repo in repos:
owner = repo['owner']
url_repo = repo['url']
data_res = {
"name": repo['name'],
"description": repo['description'],
"url": repo['url'],
'url_repo': url_repo,
"owner_url": owner['url'],
}
results.append(data_res)
return jsonify(results), 200
else:
print(f"Error Response FROM API: {response.status_code} - {response.text}")
return jsonify([]), 200
else:
return jsonify([]), 200


@bp.route("/team", methods=['GET'])
def team():
return render_template('team/team.html', title='Team', data=[])


@bp.route("/generate_email", methods=['POST'])
def generateemail():
prompt = ""
if request.method == "POST":
prompt = json.dumps(request.get_json()["prompt"])
report = generate_email(prompt)
elements = {"email": report.choices[0].message.content}
return elements, 201


@bp.route("/repo/<reponame>", methods=['GET'])
def repo(reponame=None):
client = GithubClient()
Expand Down
Loading

0 comments on commit 4d26ffd

Please sign in to comment.