-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
279 lines (240 loc) · 9.78 KB
/
Copy pathmain.py
File metadata and controls
279 lines (240 loc) · 9.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
from fastapi import FastAPI, HTTPException, Request, Depends, Form
from starlette.middleware.sessions import SessionMiddleware
from cachetools import TTLCache, cached
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
import requests
from sqlalchemy.orm import Session
from datetime import datetime
from auth import router as auth_router
from database import engine, SessionLocal, Base
from models import Project
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# Session middleware (replace 'your-secret-key' with a secure key)
app.add_middleware(SessionMiddleware, secret_key="your-secret-key")
templates = Jinja2Templates(directory="templates")
# Include auth routes
app.include_router(auth_router)
app.mount("/static", StaticFiles(directory="static"), name="static")
# Create database tables
Base.metadata.create_all(bind=engine)
# Dependency: Database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# Set up caches: 100 items max, 5 minute TTL (adjust as needed)
repo_cache = TTLCache(maxsize=100, ttl=300)
branches_cache = TTLCache(maxsize=100, ttl=300)
commits_cache = TTLCache(maxsize=200, ttl=300)
# Cache for GraphQL queries: 100 items max, TTL 300 seconds
graphql_repo_cache = TTLCache(maxsize=100, ttl=300)
@cached(graphql_repo_cache)
def get_repo_data_graphql(owner: str, repo: str, token: str):
url = "https://api.github.com/graphql"
query = """
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
name
stargazerCount
forkCount
issues(states: OPEN) {
totalCount
}
refs(refPrefix: "refs/heads/", first: 100) {
nodes {
name
target {
... on Commit {
history(first: 1) {
nodes {
committedDate
message
}
}
}
}
}
}
}
}
"""
variables = {"owner": owner, "repo": repo}
headers = {"Authorization": f"Bearer {token}"}
response = requests.post(url, json={"query": query, "variables": variables}, headers=headers)
if response.status_code == 200:
return response.json()
else:
return {"error": f"Query failed with status {response.status_code}"}
@cached(repo_cache)
def get_repo_data(owner: str, repo: str):
url = f"https://api.github.com/repos/{owner}/{repo}"
r = requests.get(url)
if r.status_code == 200:
return r.json()
else:
return {"error": f"Failed to fetch repo data: {r.status_code}"}
@cached(branches_cache)
def get_branches(owner: str, repo: str):
url = f"https://api.github.com/repos/{owner}/{repo}/branches"
r = requests.get(url)
if r.status_code == 200:
return r.json()
else:
return {"error": f"Failed to fetch branch data: {r.status_code}"}
@cached(commits_cache)
def get_latest_commit_for_branch(owner: str, repo: str, branch_name: str):
url = f"https://api.github.com/repos/{owner}/{repo}/commits"
params = {"sha": branch_name, "per_page": 1}
r = requests.get(url, params=params)
if r.status_code == 200:
commits = r.json()
if commits:
commit = commits[0]
commit_date_str = commit.get("commit", {}).get("author", {}).get("date")
commit_message = commit.get("commit", {}).get("message")
return {"date": commit_date_str, "message": commit_message}
return None
@app.get("/project/{project_id}", response_class=HTMLResponse)
async def project_detail(request: Request, project_id: int, db: Session = Depends(get_db)):
project = db.query(Project).filter(Project.id == project_id).first()
if not project:
raise HTTPException(status_code=404, detail="Project not found")
# Fetch repository stats from GitHub
stats = get_repo_stats(str(project.owner), str(project.repo))
# Fetch latest commit info using your existing helper
commit_info = get_latest_commit(str(project.owner), str(project.repo))
context = {
"request": request,
"project": {
"id": project.id,
"owner": project.owner,
"repo": project.repo,
"stars": stats.get("stars"),
"forks": stats.get("forks"),
"open_issues": stats.get("open_issues"),
"latest_commit": commit_info,
},
}
return templates.TemplateResponse("project_detail.html", context)
# Landing page
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
user = request.session.get('user')
return templates.TemplateResponse("index.html", {"request": request, "user": user})
# Dashboard: Shows user projects with enriched GitHub data
@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request, db: Session = Depends(get_db)):
user = request.session.get('user')
token = request.session.get('github_token')
if not user or not token:
return RedirectResponse(url="/")
projects = db.query(Project).filter(Project.user_id == user['id']).all()
project_details = []
for project in projects:
owner = str(project.owner)
repo = str(project.repo)
graphql_response = get_repo_data_graphql(owner, repo, token)
repo_data = graphql_response.get('data', {}).get('repository') # type: ignore
if not repo_data:
project_details.append({
"id": project.id,
"owner": owner,
"repo": repo,
"error": "Failed to fetch repo data"
})
continue
stars = repo_data.get("stargazerCount")
forks = repo_data.get("forkCount")
open_issues = repo_data.get("issues", {}).get("totalCount")
# Determine the latest commit across branches
refs = repo_data.get("refs", {}).get("nodes", [])
latest_commit = None
latest_dt = None
for ref in refs:
commit_nodes = ref.get("target", {}).get("history", {}).get("nodes", [])
if commit_nodes:
commit = commit_nodes[0]
date_str = commit.get("committedDate")
message = commit.get("message")
if date_str:
try:
commit_dt = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
except ValueError:
commit_dt = None
if commit_dt and (latest_dt is None or commit_dt > latest_dt):
latest_dt = commit_dt
latest_commit = {"date": date_str, "message": message}
project_details.append({
"id": project.id,
"owner": owner,
"repo": repo,
"stars": stars,
"forks": forks,
"open_issues": open_issues,
"latest_commit": latest_commit,
})
return templates.TemplateResponse("dashboard.html", {"request": request, "user": user, "projects": project_details})
# GET endpoint for the add project form (separate page)
@app.get("/add-project", response_class=HTMLResponse)
async def add_project_form(request: Request):
user = request.session.get('user')
if not user:
return RedirectResponse(url="/")
return templates.TemplateResponse("add_project.html", {"request": request, "user": user})
# POST endpoint to process the form submission
@app.post("/add-project", response_class=HTMLResponse)
async def add_project(request: Request, repo_full: str = Form(...), db: Session = Depends(get_db)):
user = request.session.get('user')
if not user:
return RedirectResponse(url="/")
# Expect repo_full in the format "owner/repo"
if "/" not in repo_full:
# Optionally, add an error message or flash message
return RedirectResponse(url="/add-project", status_code=302)
owner, repo = repo_full.split("/", 1)
owner = owner.strip()
repo = repo.strip()
new_project = Project(user_id=user['id'], owner=owner, repo=repo)
db.add(new_project)
db.commit()
return RedirectResponse(url="/dashboard", status_code=302)
@app.post("/delete-project/{project_id}")
async def delete_project(request: Request, project_id: int, db: Session = Depends(get_db)):
user = request.session.get('user')
if not user:
return RedirectResponse(url="/")
# Query the project to ensure it belongs to the logged-in user
project = db.query(Project).filter(Project.id == project_id, Project.user_id == user['id']).first()
if project:
db.delete(project)
db.commit()
return RedirectResponse(url="/dashboard", status_code=302)
def get_latest_commit(owner: str, repo: str):
# Fetch the most recent commit for the default branch
url = f"https://api.github.com/repos/{owner}/{repo}/commits"
params = {"per_page": 1}
response = requests.get(url, params=params)
if response.status_code == 200:
commits = response.json()
if commits:
commit = commits[0]
commit_date = commit.get("commit", {}).get("author", {}).get("date")
commit_message = commit.get("commit", {}).get("message")
return {"date": commit_date, "message": commit_message}
return None
def get_repo_stats(owner: str, repo: str):
url = f"https://api.github.com/repos/{owner}/{repo}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
"stars": data.get("stargazers_count"),
"forks": data.get("forks_count"),
"open_issues": data.get("open_issues_count")
}
return {"stars": None, "forks": None, "open_issues": None}