Skip to content

Commit

Permalink
Merge pull request #53 from chriswebb09/dev-branch
Browse files Browse the repository at this point in the history
Dev branch
  • Loading branch information
chriswebb09 authored Dec 19, 2023
2 parents 4d377f0 + c61b68d commit 1b73a27
Show file tree
Hide file tree
Showing 24 changed files with 412 additions and 225 deletions.
143 changes: 142 additions & 1 deletion DirectReport/browserview/app.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
#!/usr/bin/env python3

import sys
import os
from pathlib import Path
import urllib
import requests

from flask import Flask, render_template, request, redirect, json, url_for
from flask import Flask, render_template, session, request, redirect, json, url_for
from flask import make_response
from datetime import datetime, timedelta
from flask_login import LoginManager, login_required, current_user

from DirectReport.browserview.services.github import GithubClient
Expand All @@ -22,11 +27,147 @@
app.register_blueprint(auth)
app.register_blueprint(reportsbp)
app.secret_key = appsecrets.SECRET_KEY

client_id = appsecrets.GITHUB_CLIENT_ID
client_secret = appsecrets.GITHUB_CLIENT_SECRET

login_manager.init_app(app)
login_manager.login_view = "login"
user_model = UserModel()


@app.route('/authorize/github')
def oauth2_authorize():
github_url = "https://github.com/login/oauth/authorize?scope=user:email&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Fcallback%2Fgithub"
return redirect(github_url)


def get_commits_last_month():
owner = 'chriswebb09'
repo = 'your_repository'
url = f'https://api.github.com/repos/{owner}/{repo}/pulls'

# Replace 'your_token' with your personal access token
headers = {'Authorization': 'token your_token'}

# Calculate the date one month ago
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()
print(pull_requests)
else:
print(f"Error: {response.status_code}")
print(response.text)

@app.route('/repo', methods=['GET', 'POST'])
def reponame():
args_url = request.args.get('repo_url')
h_token = session['header_token']
reponame = "https://api.github.com/repos/" + args_url + "/commits"
headers443 = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer ' + h_token,
'X-GitHub-Api-Version': '2022-11-28'
}
response3 = requests.get(
url=reponame,
headers=headers443,
auth=(client_id, client_secret)
)
json_Data3 = json.loads(response3.content)

USERNAME = "chriswebb09"
REPO = "DirectReport"

# Calculate the date one month ago
last_month = datetime.utcnow() - timedelta(days=30)
last_month_str = last_month.strftime("%Y-%m-%dT%H:%M:%SZ")

# API endpoint to retrieve commits for a repository since the last month
api_url = f"https://api.github.com/repos/{USERNAME}/{REPO}/commits?since={last_month_str}"

# Fetch commits using requests and your GitHub token
headers = {"Authorization": f"token {appsecrets.GITHUB_TOKEN}"}
response = requests.get(api_url, headers=headers)

# Check if the request was successful (status code 200)
results_2 = []
if response.status_code == 200:
commits = response.json()

# Format and print the commits
for commit in commits:
author_name = commit["commit"]["author"]["name"]
commit_message = commit["commit"]["message"]
results_2.append(f"{author_name}: {commit_message}")
else:
print(f"Error: {response.status_code} - {response.text}")
results = []
for commit in json_Data3:
commit_data_res = {
"message": commit["commit"]["message"],
"url": commit["commit"]["url"],
"commit_author_name": commit["commit"]["author"]["name"],
"commit_author_email": commit["commit"]["author"]["email"],
"commit_author_date": commit["commit"]["author"]["date"],
"committer_name": commit["commit"]["committer"]["name"],
"committer_email": commit["commit"]["committer"]["email"],
"committer_date": commit["commit"]["committer"]["date"],
"comment_count": commit["commit"]["comment_count"],
"verified": commit["commit"]["verification"]["verified"],
"verification_reason": commit["commit"]["verification"]["reason"],
"verification_signature": commit["commit"]["verification"]["signature"],
"type": "commit"
}
results.append(commit_data_res)
result_log = " ".join(results_2)
print(result_log)
return json_Data3, 200



@app.route('/callback/github', methods=['GET', 'POST'])
def ouath2_callback():
data = {'client_id': client_id, 'client_secret': client_secret, 'code': request.args.get("code")}
response = requests.post('https://github.com/login/oauth/access_token', data=data)
res = response.text.split('&', 1)
token = res[0].split('=')[1]
HEADER_TOKEN = token
session['header_token'] = token
headers2 = {
'Accept': 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/x-www-form-urlencoded',
}
HEADER_TOKEN = token
data2 = '{\n' + ' "access_token": "' + HEADER_TOKEN + '" \n}'
response2 = requests.post(
url="https://api.github.com/applications/" + client_id + "/token",
headers=headers2,
data=data2,
auth=(client_id, client_secret),
)
json_Data = json.loads(response2.content)
repos = requests.get(json_Data["user"]['repos_url'] + "?sort=updated&direction=desc", data=data2, auth=(client_id, client_secret))
json_Data2 = json.loads(repos.content)
results = []
for repo in json_Data2:
owner = repo['owner']
url_repo = "https://api.github.com/repos/" + owner['login'] + "/" + repo['name']

data_res = {
"name": repo['name'],
"description": repo['description'],
"url": repo['url'],
'url_repo': url_repo,
"owner_url": owner['url']
}
results.append(data_res)
return render_template('team/teamreport.html', title='Team', data=results)

@app.route("/")
def home():
"""
Expand Down
5 changes: 4 additions & 1 deletion DirectReport/browserview/blueprints/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from DirectReport.models.user_model import UserModel
from flask_login import login_user, login_required, logout_user, current_user
from DirectReport.browserview import app
from DirectReport.datadependencies import appsecrets
from DirectReport.models.Report.report_builder import ReportBuilder
from DirectReport.browserview.services.github import GithubClient

Expand Down Expand Up @@ -50,7 +51,9 @@ def login():
else:
print("password no match")
flash("Please check your login details and try again.")
return render_template('auth/login.html')
return render_template(
'auth/login.html', client_id=appsecrets.GITHUB_CLIENT_ID, client_secret=appsecrets.GITHUB_CLIENT_SECRET
)


@auth.route("/account", methods=['GET', 'POST'])
Expand Down
14 changes: 7 additions & 7 deletions DirectReport/browserview/blueprints/reports/reportbp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

from DirectReport.browserview.services.github import GithubClient
from DirectReport.browserview.services.github import GoogleAIClient
from DirectReport.models.Report.report_builder import ReportBuilder
from DirectReport.models.Report.report_model import ReportModel
from DirectReport.models.report.report_builder import ReportBuilder
from DirectReport.models.report.report_model import ReportModel

reportsbp = Blueprint('reportsbp', __name__)

Expand Down Expand Up @@ -40,11 +40,11 @@ def report():
}
data_json["shortlog"] = client.parse_git_shortlog(log_item)
data_json["repos"] = repodata
ReportBuilder.new(data_json, prompt, current_user.id)
ReportBuilder.new(data_json, prompt, current_user.id, "DirectReport")
return data_json, 201


@reportsbp.route("/teamreport", methods=['GET', 'POST'])
@reportsbp.route("/reports/new", methods=['GET', 'POST'])
@login_required
def team_report():
if request.method == "POST":
Expand All @@ -54,7 +54,7 @@ def team_report():
return render_template('team/teamreport.html', title='Team Report', data=[])


@reportsbp.route("/getreport/<uid>", methods=['GET'])
@reportsbp.route("/reports/<uid>", methods=['GET'])
@login_required
def get_report(uid=None):
reports = ReportBuilder.get_reports_for_user_id(current_user.id)
Expand All @@ -63,14 +63,14 @@ def get_report(uid=None):
return render_template('team/teamreport.html', title='Team Report', teamData=report["report"])


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


@reportsbp.route("/list", methods=['GET', 'POST'])
@reportsbp.route("/reports", methods=['GET', 'POST'])
@login_required
def list_entries():
"""
Expand Down
14 changes: 6 additions & 8 deletions DirectReport/browserview/static/js/account/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const { useState, useEffect } = React;

const Account = () => {
const [userData, setUserData] = useState({});
const [actualData, setActualData] = useState({});
const [reportData, setReportData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
Expand All @@ -18,10 +17,9 @@ const Account = () => {
}
return response.json();
})
.then((actualData) => {
setUserData(actualData["user"]);
setReportData(actualData["reports"]);
setActualData(actualData);
.then((responseData) => {
setUserData(responseData["user"]);
setReportData(responseData["reports"]);
setError(null);
})
.catch((err) => {
Expand All @@ -39,14 +37,14 @@ const Account = () => {
)
} else {
return (
<div className="mx-30 content-center mt-0 mb-48 h-150">
<div className="pt-5 pb-3 mt-0 mb-5 ml-20 px-20">
<div className="mx-10 content-center mt-0 mb-28 h-130">
<div className="pt-2 pb-3 mt-0 mb-5 ml-20 px-0">
<h1 className="text-2xl text-blue-800 text-left font-bold font-mono pt-5">
User Account
</h1>
</div>

<div className="grid grid-cols-3 gap-8 mb-1 mx-20 px-20 justify-center">
<div className="grid grid-cols-3 gap-8 mb-1 mx-10 px-10 justify-center">
{userData && AccountUserInfo(userData, reportData)}
</div>
</div>
Expand Down
15 changes: 12 additions & 3 deletions DirectReport/browserview/static/js/auth/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ const LoginForm = () => {
placeholder="[email protected]" required=""/>
</div>
<div>
<label htmlFor="password" className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
<label htmlFor="password"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Password
</label>
<input type="password" name="password" id="password" placeholder="••••••••"
Expand All @@ -29,17 +30,25 @@ const LoginForm = () => {
<div className="flex items-start">
{RememberMe()}
</div>
<a href="#" className="text-sm font-medium text-primary-600 hover:underline dark:text-primary-500">
<a href="#"
className="text-sm font-medium text-primary-600 hover:underline dark:text-primary-500">
Forgot password?
</a>
</div>
<button type="submit"
className="w-full text-white bg-indigo-700 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
Sign in
</button>
<button
className="w-80 sm:w-90 bg-slate-100 hover:bg-blue-400 text-blue-500 shadow-[1.5px_2px_1.0px_0.5px_rgba(0,0,0,0.48)] hover:text-white hover:border-gray-200 text-lg font-semibold py-2 px-5 rounded-2xl mt-2"
type="button">
<a className="btn btn-primary" href="/authorize/github">Login
with GitHub</a>
</button>
<p className="text-sm font-light text-gray-500 dark:text-gray-400 ml-14">
Don’t have an account yet?
<a href="/signup" className="font-medium text-primary-600 ml-3 hover:underline dark:text-primary-500">
<a href="/signup"
className="font-medium text-primary-600 ml-3 hover:underline dark:text-primary-500">
Sign up
</a>
</p>
Expand Down
1 change: 1 addition & 0 deletions DirectReport/browserview/static/js/entryform.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { useState, useEffect } = React;

const { axios } = axios;
class EntryForm extends React.Component {
constructor(props) {
super(props);
Expand Down
1 change: 1 addition & 0 deletions DirectReport/browserview/static/js/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';
const elem = React.createElement;


class Home extends React.Component {
render() {
return elem(
Expand Down
2 changes: 1 addition & 1 deletion DirectReport/browserview/static/js/list/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const SavedReportListApp = () => {
const [error, setError] = useState(null);

useEffect(() => {
fetch(`/getlist`)
fetch(`/reports/list/new`)
.then((response) => {
if (!response.ok) {
throw new Error(
Expand Down
2 changes: 1 addition & 1 deletion DirectReport/browserview/static/js/list/listcomponents.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class SavedReportList extends React.Component {
{this.props.listdata.map(item =>
<div className="col-span-1 justify-center mt-3 mb-3">
<article className="mx-4 mt-2 w-90 rounded-2xl border border-gray-200 p-1 shadow-lg transition hover:shadow-xl">
<a className="block rounded-xl bg-white p-1 sm:p-6 lg:p-8" href={'/getreport/' + item.uuid}>
<a className="block rounded-xl bg-white p-1 sm:p-6 lg:p-8" href={'/reports/' + item.uuid}>
<div className="mt-1">
<h2 className="text-2xl font-bold text-gray-800 sm:text-xl">{'User: ' + item.user_id}</h2>
<p className="mt-3 text-sm text-justify line-clamp-3 text-gray-500">{'Raw Input: ' + item.raw_input}</p>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

const { useState, useEffect } = React;

const TeamMember = () => {

const [userData, setUserData] = useState({});
Expand Down
Loading

0 comments on commit 1b73a27

Please sign in to comment.