From f3f50ecc7c25bfaead67220e8678c82f6767c947 Mon Sep 17 00:00:00 2001
From: kalicyh <34980061+kaliCYH@users.noreply.github.com>
Date: Fri, 9 Aug 2024 08:34:46 +0800
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20=E6=96=B0=E5=A2=9E=E8=BD=AF?=
 =?UTF-8?q?=E4=BB=B6=E6=9B=B4=E6=96=B0=E6=8E=A5=E5=8F=A3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .github/workflows/docker-image.yml | 12 ++++++++
 api/crud.py                        | 37 ++++++++++++++++++++++-
 api/database.py                    |  7 +++--
 api/main.py                        | 47 ++++++++++++++++++++++++++++--
 src/App.vue                        |  2 +-
 5 files changed, 99 insertions(+), 6 deletions(-)

diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml
index 8e4e3d4..8825c72 100644
--- a/.github/workflows/docker-image.yml
+++ b/.github/workflows/docker-image.yml
@@ -44,3 +44,15 @@ jobs:
             ghcr.io/${{ github.repository }}:${{ env.VERSION }}
             ghcr.io/${{ github.repository }}:latest
           platforms: linux/amd64,linux/arm64
+
+      - name: Upload Tag and Artifacts to FastAPI
+        env:
+          FASTAPI_URL: ${{ secrets.FASTAPI_URL }}
+        run: |
+          TAG="${GITHUB_REF#refs/tags/}"
+          echo "Tag: $TAG"
+
+          # 上传 tag
+          curl -X POST "$FASTAPI_URL/store-tag/" \
+                -H "Content-Type: application/json" \
+                -d "{\"tag\": \"$TAG\"}"
\ No newline at end of file
diff --git a/api/crud.py b/api/crud.py
index 689c58b..1b8e5b1 100644
--- a/api/crud.py
+++ b/api/crud.py
@@ -74,4 +74,39 @@ def get_records_by_full_filter(db: Session, category: str, month: str, name: str
         Record.category.like(f'%{category}%'),
         Record.month.like(f'%{month}%'),
         Record.name.like(f'%{name}%')
-    ).all()
\ No newline at end of file
+    ).all()
+
+def update_version_filename(db: Session, filename: str):
+    version_info = db.query(Info).first()
+    if version_info:
+        version_info.client_filename = filename
+    else:
+        new_info = Info(
+            client_filename=filename
+        )
+        db.add(new_info)
+    db.commit()
+
+def update_version_info(db: Session, version: str, client_type: str):
+    if client_type not in ["client", "backend"]:
+        raise ValueError("Invalid client_type. Must be 'client' or 'backend'.")
+    
+    version_info = db.query(Info).first()
+
+    if client_type == "client":
+        if version_info:
+            version_info.client_versions = version
+        else:
+            new_info = Info(
+                client_versions=version
+            )
+            db.add(new_info)
+    elif client_type == "backend":
+        if version_info:
+            version_info.backend_versions = version
+        else:
+            new_info = Info(
+                backend_versions=version
+            )
+            db.add(new_info)
+    db.commit()
diff --git a/api/database.py b/api/database.py
index 9944e43..0dc0de5 100644
--- a/api/database.py
+++ b/api/database.py
@@ -25,8 +25,11 @@ class Record(Base):
 class Info(Base):
     __tablename__ = 'info'
     id = Column(Integer, primary_key=True, index=True, autoincrement=True)
-    last_updated = Column(String(20))
-    total_rows = Column(Integer)
+    last_updated = Column(String(20), nullable=True)
+    total_rows = Column(Integer, nullable=True)
+    client_versions = Column(String(255), nullable=True)
+    client_filename = Column(String(255), nullable=True)
+    backend_versions = Column(String(255), nullable=True)
 
 class Number(Base):
     __tablename__ = 'numbers'
diff --git a/api/main.py b/api/main.py
index a13d8b8..733b771 100644
--- a/api/main.py
+++ b/api/main.py
@@ -1,9 +1,13 @@
-from fastapi import FastAPI
+from fastapi import FastAPI, UploadFile, File
 from fastapi.staticfiles import StaticFiles
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.responses import FileResponse, JSONResponse
 from .routes.talking_points import router as talking_points_router
 from .routes.numbers import router as numbers_router
+from pydantic import BaseModel
+from pathlib import Path
+from .crud import update_version_info, update_version_filename, get_info
+from .database import SessionLocal
 
 app = FastAPI()
 
@@ -26,6 +30,45 @@ def root():
 
 @app.get("/info")
 async def get_infos():
+    db = SessionLocal()
+    info = get_info(db)
+    db.close()
+    print()
     return JSONResponse(content={
-        "version": "v1.6.1"
+        "client_versions": info.client_versions,
+        "backend_versions": info.backend_versions,
+        "client_filename": info.client_filename
     })
+
+# 文件存储路径
+UPLOAD_DIR = Path("./file")
+UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
+
+class TagModel(BaseModel):
+    tag: str
+
+@app.post("/store-tag/")
+async def store_tag(tag: TagModel):
+    tag = tag.tag
+    db = SessionLocal()
+    update_version_info(db, tag, "client")
+    db.close()
+    return {"message": "Tag stored successfully"}
+
+@app.post("/upload-file/")
+async def upload_file(tag: str, file: UploadFile = File(...)):
+    db = SessionLocal()
+    update_version_info(db, tag, "backend")
+    update_version_filename(db, file.filename+"_"+tag)
+    db.close()
+    file_path = UPLOAD_DIR / f"{file.filename}_{tag}"
+    with file_path.open("wb") as buffer:
+        buffer.write(await file.read())
+    return {"message": "File uploaded successfully"}
+
+@app.get("/download-file/{filename}")
+async def download_file(filename: str):
+    file_path = UPLOAD_DIR / filename
+    if file_path.exists():
+        return FileResponse(path=file_path, media_type='application/octet-stream', filename=filename)
+    return {"error": "File not found"}
diff --git a/src/App.vue b/src/App.vue
index 82a917f..7537b3e 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -25,7 +25,7 @@ export default {
     async fetchInfo() {
       try {
         const result = await fetchInfo('/info');
-        this.version = result.version;
+        this.version = result.backend_versions;
       } catch (error) {
         this.error = error.message;
       }