Spaces:
Running
Running
File size: 5,948 Bytes
30a8511 238042d 30a8511 711884e 30a8511 711884e 30a8511 cfba014 238042d 30a8511 238042d 30a8511 238042d 30a8511 711884e 9c61e67 30a8511 711884e 9c61e67 30a8511 238042d cfba014 238042d cfba014 238042d cfba014 238042d 711884e 7f50e4d | 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 | """
Projects API — list and fetch saved projects by authenticated user.
"""
import logging
import uuid
from datetime import datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, field_validator
from sqlalchemy import select
from agent.scaffold import build_publish_repo, slugify
from auth.crypto import decrypt
from auth.dependencies import get_current_user
from db.database import SessionLocal
from db.models import Project, User
from integrations.github_client import GitHubError, publish_files
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/projects", tags=["projects"])
class ProjectSummary(BaseModel):
id: str
title: str
created_at: datetime
updated_at: datetime
class ProjectDetail(ProjectSummary):
session_id: str
brief: str
files: dict
chat: list
oncall_log: list
framework: str = "react" # default for old rows that predate the column
@router.get("", response_model=list[ProjectSummary])
def list_projects(current_user: User = Depends(get_current_user)) -> list[ProjectSummary]:
with SessionLocal() as db:
rows = db.execute(
select(Project)
.where(Project.user_id == current_user.id)
.order_by(Project.created_at.desc())
).scalars().all()
return [
ProjectSummary(
id=str(r.id),
title=r.title,
created_at=r.created_at,
updated_at=r.updated_at,
)
for r in rows
]
@router.get("/{project_id}", response_model=ProjectDetail)
def get_project(project_id: str, current_user: User = Depends(get_current_user)) -> ProjectDetail:
try:
pid = uuid.UUID(project_id)
except ValueError:
raise HTTPException(status_code=404, detail="Project not found")
with SessionLocal() as db:
row = db.get(Project, pid)
if not row or row.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Project not found")
return ProjectDetail(
id=str(row.id),
title=row.title,
created_at=row.created_at,
updated_at=row.updated_at,
session_id=row.session_id or "",
brief=row.brief,
files=row.files,
chat=row.chat or [],
oncall_log=row.oncall_log or [],
framework=getattr(row, "framework", None) or "react",
)
class PublishResponse(BaseModel):
repo_url: str
vercel_import_url: str
@router.post("/{project_id}/publish", response_model=PublishResponse)
def publish_project(
project_id: str,
current_user: User = Depends(get_current_user),
) -> PublishResponse:
"""Build a framework-aware deployable repo from a project's files and push it to GitHub."""
try:
pid = uuid.UUID(project_id)
except ValueError:
raise HTTPException(status_code=404, detail="Project not found")
with SessionLocal() as db:
row = db.get(Project, pid)
if not row or row.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Project not found")
enc = getattr(current_user, "github_token_enc", None)
if not (isinstance(enc, str) and enc):
raise HTTPException(status_code=400, detail="Connect GitHub first")
token = decrypt(enc)
# Old rows that predate the framework column default to "react".
framework = getattr(row, "framework", None) or "react"
repo_files = build_publish_repo(row.files, framework, row.title)
repo_name = f"appsmith-{slugify(row.title)}"
try:
repo_url = publish_files(token, repo_name, repo_files)
except GitHubError as exc:
logger.error("GitHub publish failed for project %s: %s", project_id, exc)
raise HTTPException(status_code=502, detail=str(exc))
except ValueError:
# ponytail: stored token no longer valid — never echo it.
raise HTTPException(status_code=400, detail="GitHub token is no longer valid; reconnect GitHub")
return PublishResponse(
repo_url=repo_url,
vercel_import_url=f"https://vercel.com/new/clone?repository-url={repo_url}",
)
class HistoryBody(BaseModel):
chat: list[Any]
oncall_log: list[Any]
@field_validator("chat", "oncall_log", mode="before")
@classmethod
def must_be_list(cls, v: Any) -> list:
if not isinstance(v, list):
raise ValueError("must be a list")
return v
@router.put("/{project_id}/history")
def update_history(
project_id: str,
body: HistoryBody,
current_user: User = Depends(get_current_user),
) -> dict:
"""Persist chat + oncall_log arrays for a project (owner-gated)."""
try:
pid = uuid.UUID(project_id)
except ValueError:
raise HTTPException(status_code=404, detail="Project not found")
with SessionLocal() as db:
row = db.get(Project, pid)
if not row or row.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Project not found")
row.chat = body.chat
row.oncall_log = body.oncall_log
db.commit()
return {"ok": True}
@router.delete("/{project_id}")
def delete_project(project_id: str, current_user: User = Depends(get_current_user)) -> dict:
"""Delete a project the authed user owns. 404 (not 403) for missing or
someone else's project — we don't reveal that another user's id exists.
Idempotent from the client's view: the chat/oncall_log live inline on the
row, so deleting the row removes the whole session."""
try:
pid = uuid.UUID(project_id)
except ValueError:
raise HTTPException(status_code=404, detail="Project not found")
with SessionLocal() as db:
row = db.get(Project, pid)
if not row or row.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Project not found")
db.delete(row)
db.commit()
return {"ok": True}
|