mirror of
https://github.com/ZTatman/myst.git
synced 2026-11-22 21:07:57 +00:00
feat(links): add repository and branch listing with Forgejo token dependency
This commit is contained in:
parent
3c3f47d20e
commit
f00c25b7a0
2 changed files with 192 additions and 9 deletions
|
|
@ -1,11 +1,127 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import HTTPException, status
|
from fastapi import HTTPException, status
|
||||||
|
from pydantic import AliasChoices, AliasPath, BaseModel, Field, field_validator
|
||||||
|
|
||||||
from app.models.app_settings import AppSettings
|
from app.models.app_settings import AppSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Repo(BaseModel):
|
||||||
|
repo_name: str = Field(validation_alias="name")
|
||||||
|
repo_full_name: str = Field(validation_alias="full_name")
|
||||||
|
repo_owner: str = Field(validation_alias=AliasPath("owner", "username"))
|
||||||
|
default_branch: str
|
||||||
|
description: str | None
|
||||||
|
visibility: Literal["private", "public"] = Field(validation_alias="private")
|
||||||
|
html_url: str
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
archived: bool
|
||||||
|
archived_at: datetime | None
|
||||||
|
|
||||||
|
@field_validator("visibility", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def map_visibility(cls, value: Any) -> Literal["private", "public"]:
|
||||||
|
if not isinstance(value, bool):
|
||||||
|
raise TypeError(f"expected a boolean, got {value!r}")
|
||||||
|
return "private" if value else "public"
|
||||||
|
|
||||||
|
|
||||||
|
class Commit(BaseModel):
|
||||||
|
id: str = Field(validation_alias=AliasChoices("sha", "id"))
|
||||||
|
message: str
|
||||||
|
url: str
|
||||||
|
created_at: datetime = Field(validation_alias="timestamp")
|
||||||
|
|
||||||
|
|
||||||
|
class Branch(BaseModel):
|
||||||
|
name: str
|
||||||
|
protected: bool
|
||||||
|
commit: Commit
|
||||||
|
|
||||||
|
|
||||||
|
async def get_repos(app_settings: AppSettings, access_token: str) -> list[Repo]:
|
||||||
|
"""Get the user's repositories from the Forgejo API.
|
||||||
|
Args:
|
||||||
|
access_token: The Forgejo API token.
|
||||||
|
Returns:
|
||||||
|
A list of repositories.
|
||||||
|
"""
|
||||||
|
|
||||||
|
repos = await get(app_settings, "/api/v1/user/repos", access_token)
|
||||||
|
if not repos:
|
||||||
|
return []
|
||||||
|
return [Repo.model_validate(r) for r in repos]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_branches(
|
||||||
|
app_settings: AppSettings,
|
||||||
|
access_token: str,
|
||||||
|
owner: str,
|
||||||
|
repo: str,
|
||||||
|
*,
|
||||||
|
limit=10,
|
||||||
|
page=1,
|
||||||
|
) -> list[Branch]:
|
||||||
|
"""Get the branches of a repository from the Forgejo API.
|
||||||
|
Args:
|
||||||
|
access_token: The Forgejo API token.
|
||||||
|
owner: The owner of the repository.
|
||||||
|
repo: The name of the repository.
|
||||||
|
limit: The maximum number of branches to return.
|
||||||
|
page: The page number to return.
|
||||||
|
Returns:
|
||||||
|
A list of branches.
|
||||||
|
"""
|
||||||
|
|
||||||
|
branches = await get(
|
||||||
|
app_settings,
|
||||||
|
f"/api/v1/repos/{owner}/{repo}/branches?limit={limit}&page={page}",
|
||||||
|
access_token,
|
||||||
|
)
|
||||||
|
if not branches:
|
||||||
|
return []
|
||||||
|
return [Branch.model_validate(b) for b in branches]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_commits(
|
||||||
|
app_settings: AppSettings,
|
||||||
|
access_token: str,
|
||||||
|
owner: str,
|
||||||
|
repo: str,
|
||||||
|
*,
|
||||||
|
branch: str,
|
||||||
|
limit: int = 10,
|
||||||
|
page: int = 1,
|
||||||
|
) -> list[Commit]:
|
||||||
|
"""Get the commits of a branch from the Forgejo API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
access_token: The Forgejo API token.
|
||||||
|
owner: The owner of the repository.
|
||||||
|
repo: The name of the repository.
|
||||||
|
branch: The branch to list commits for.
|
||||||
|
limit: The maximum number of commits to return.
|
||||||
|
page: The page number to return.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A list of commits.
|
||||||
|
"""
|
||||||
|
commits = await get(
|
||||||
|
app_settings,
|
||||||
|
f"/api/v1/repos/{owner}/{repo}/commits?branch={branch}&limit={limit}&page={page}",
|
||||||
|
access_token,
|
||||||
|
)
|
||||||
|
if not commits:
|
||||||
|
return []
|
||||||
|
return commits
|
||||||
|
# return [Commit.model_validate(c) for c in commits]
|
||||||
|
|
||||||
|
|
||||||
async def post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
async def post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
||||||
"""Send a POST request to the Forgejo API.
|
"""Send a POST request to the Forgejo API.
|
||||||
|
|
||||||
|
|
@ -37,7 +153,9 @@ async def post(app_settings: AppSettings, path: str, data: dict) -> dict:
|
||||||
return resp.json()
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
async def get(app_settings: AppSettings, path: str, access_token: str) -> dict | list[dict]:
|
async def get(
|
||||||
|
app_settings: AppSettings, path: str, access_token: str
|
||||||
|
) -> dict | list[dict]:
|
||||||
"""Send a GET request to the Forgejo API.
|
"""Send a GET request to the Forgejo API.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,96 @@
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Literal
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter, Depends, HTTPException, Path, status
|
||||||
from pydantic import BaseModel, EmailStr
|
from pydantic import BaseModel, EmailStr
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.crypto import decrypt_token
|
||||||
|
from app.auth.session import get_current_session
|
||||||
|
from app.clients import forgejo
|
||||||
|
from app.deps import get_db
|
||||||
|
from app.models.app_settings import AppSettings
|
||||||
|
from app.models.session import Session as UserBrowserSession
|
||||||
|
from app.models.user import LinkedIdentity
|
||||||
|
from app.settings import get_app_settings, get_fernet
|
||||||
|
|
||||||
router = APIRouter(prefix="/links", tags=["links"])
|
router = APIRouter(prefix="/links", tags=["links"])
|
||||||
|
|
||||||
|
|
||||||
class CreateLinkRequest(BaseModel):
|
class CreateLinkRequest(BaseModel):
|
||||||
repo_owner: str
|
|
||||||
repo_name: str
|
repo_name: str
|
||||||
branch: str
|
repo_owner: str
|
||||||
|
commit_sha: str
|
||||||
expires_at: datetime
|
expires_at: datetime
|
||||||
link_type: Literal["public", "private"] = "public"
|
link_type: Literal["public", "private"] = "public"
|
||||||
recipient_email: EmailStr | None = None
|
recipient_email: EmailStr | None = None
|
||||||
|
|
||||||
|
|
||||||
class CreateLinkResponse(BaseModel):
|
class CreateLinkResponse(BaseModel):
|
||||||
repo_owner: str
|
|
||||||
repo_name: str
|
|
||||||
branch: str
|
|
||||||
expires_at: datetime
|
expires_at: datetime
|
||||||
commit_sha: str
|
commit_sha: str
|
||||||
share_url: str
|
share_url: str
|
||||||
|
|
||||||
|
|
||||||
|
async def get_forgejo_token(
|
||||||
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
|
) -> str:
|
||||||
|
if not sess.user.has_pat:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Personal access token not found. Please register one and try again.",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return decrypt_token(get_fernet(), sess.user.pat_encrypted)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
|
detail="Stored Forgejo token cannot be decrypted. Reconnect your account in settings.",
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
@router.post("/", status_code=501)
|
@router.post("/", status_code=501)
|
||||||
async def create_link(request: CreateLinkRequest) -> dict:
|
async def create_link(request: CreateLinkRequest) -> dict:
|
||||||
"""Stub — link creation not yet implemented."""
|
"""Stub — link creation not yet implemented."""
|
||||||
return {"detail": "Link creation is not yet implemented."}
|
return {"detail": "Link creation is not yet implemented."}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/repositories")
|
||||||
|
async def get_repositories(
|
||||||
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
|
access_token: Annotated[str, Depends(get_forgejo_token)],
|
||||||
|
):
|
||||||
|
"""Get a list of the user's repositories from Forgejo."""
|
||||||
|
|
||||||
|
repos = await forgejo.get_repos(app_settings, access_token)
|
||||||
|
return repos
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/repositories/{repo}/branches")
|
||||||
|
async def get_repository_branches(
|
||||||
|
app_settings: Annotated[AppSettings, Depends(get_app_settings)],
|
||||||
|
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
|
||||||
|
access_token: Annotated[str, Depends(get_forgejo_token)],
|
||||||
|
db: Annotated[AsyncSession, Depends(get_db)],
|
||||||
|
repo: Annotated[str, Path(min_length=1, description="The name of the repository")],
|
||||||
|
limit: int = 10,
|
||||||
|
page: int = 1,
|
||||||
|
):
|
||||||
|
# Derive {owner} path param from users linked identity provider server-side
|
||||||
|
stmt = select(LinkedIdentity).where(
|
||||||
|
LinkedIdentity.user_id == sess.user_id, LinkedIdentity.provider == "forgejo"
|
||||||
|
)
|
||||||
|
result = await db.execute(stmt)
|
||||||
|
identity = result.scalar_one_or_none()
|
||||||
|
if identity is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="No linked identity for forgejo was found. Please sign-in and try again.",
|
||||||
|
)
|
||||||
|
owner = identity.provider_username
|
||||||
|
|
||||||
|
branches = await forgejo.get_branches(
|
||||||
|
app_settings, access_token, owner, repo, limit=limit, page=page
|
||||||
|
)
|
||||||
|
return branches
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue