|
| 1 | +""" |
| 2 | +Worker HTTP local (127.0.0.1) : publication Vinted / nodriver sur le PC utilisateur. |
| 3 | +
|
| 4 | +Les métadonnées et le JWT sont lus sur l’API distante ; Chrome et nodriver tournent ici. |
| 5 | +
|
| 6 | +Lancer depuis le dossier ``api/`` (venv activé) :: |
| 7 | +
|
| 8 | + python desktop_vinted_server.py |
| 9 | +
|
| 10 | +Variables utiles : ``GOUPIX_VINTED_LOCAL_PORT`` (défaut 18766), ``GOUPIX_REMOTE_API`` (URL API si |
| 11 | +le client n’envoie pas ``X-Goupix-Remote-Api``). |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import asyncio |
| 17 | +import json |
| 18 | +import logging |
| 19 | +import os |
| 20 | +import sys |
| 21 | +import uuid |
| 22 | +from typing import Annotated |
| 23 | + |
| 24 | +import httpx |
| 25 | +import uvicorn |
| 26 | +from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, Query, status |
| 27 | +from fastapi.middleware.cors import CORSMiddleware |
| 28 | +from fastapi.responses import StreamingResponse |
| 29 | + |
| 30 | +from core.deps import get_bearer_or_query_token |
| 31 | +from core.win32_asyncio import ensure_proactor_event_loop |
| 32 | +from schemas.articles import VintedBatchStartBody |
| 33 | +from services import vinted_batch_progress as vinted_batch_hub |
| 34 | +from services import vinted_progress as vinted_progress_hub |
| 35 | +from services.desktop_vinted_runner import run_desktop_vinted_batch_job, run_desktop_vinted_publish_job |
| 36 | + |
| 37 | +ensure_proactor_event_loop() |
| 38 | + |
| 39 | +logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s") |
| 40 | +logger = logging.getLogger("goupixdex.vinted_local") |
| 41 | + |
| 42 | +try: |
| 43 | + from dotenv import load_dotenv |
| 44 | + |
| 45 | + load_dotenv() |
| 46 | +except ImportError: |
| 47 | + pass |
| 48 | + |
| 49 | + |
| 50 | +def get_remote_base_flexible( |
| 51 | + x_goupix_remote_api: Annotated[str | None, Header(alias="X-Goupix-Remote-Api")] = None, |
| 52 | + remote_api: Annotated[str | None, Query(description="URL API (SSE / EventSource)")] = None, |
| 53 | +) -> str: |
| 54 | + for cand in (x_goupix_remote_api, remote_api, os.environ.get("GOUPIX_REMOTE_API", "")): |
| 55 | + if cand and str(cand).strip(): |
| 56 | + return str(cand).strip().rstrip("/") |
| 57 | + raise HTTPException( |
| 58 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 59 | + detail=( |
| 60 | + "URL API distante requise (header X-Goupix-Remote-Api, query remote_api ou GOUPIX_REMOTE_API)." |
| 61 | + ), |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +async def get_user_id_introspected( |
| 66 | + raw_token: Annotated[str, Depends(get_bearer_or_query_token)], |
| 67 | + remote: Annotated[str, Depends(get_remote_base_flexible)], |
| 68 | +) -> int: |
| 69 | + """Valide le JWT via l’API distante (pas besoin du secret JWT en local).""" |
| 70 | + async with httpx.AsyncClient(timeout=30.0) as client: |
| 71 | + r = await client.get( |
| 72 | + f"{remote}/users/me", |
| 73 | + headers={"Authorization": f"Bearer {raw_token}", "Accept": "application/json"}, |
| 74 | + ) |
| 75 | + if r.status_code == status.HTTP_401_UNAUTHORIZED: |
| 76 | + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated") |
| 77 | + if not r.is_success: |
| 78 | + raise HTTPException( |
| 79 | + status_code=status.HTTP_502_BAD_GATEWAY, |
| 80 | + detail="Impossible de joindre l’API distante pour valider la session.", |
| 81 | + ) |
| 82 | + return int(r.json()["id"]) |
| 83 | + |
| 84 | + |
| 85 | +router = APIRouter(prefix="/articles", tags=["articles-vinted-local"]) |
| 86 | + |
| 87 | + |
| 88 | +@router.post("/{article_id}/publish-vinted") |
| 89 | +async def publish_vinted_for_article( |
| 90 | + article_id: int, |
| 91 | + user_id: Annotated[int, Depends(get_user_id_introspected)], |
| 92 | + raw_token: Annotated[str, Depends(get_bearer_or_query_token)], |
| 93 | + remote: Annotated[str, Depends(get_remote_base_flexible)], |
| 94 | +) -> dict[str, object]: |
| 95 | + vinted_progress_hub.register(article_id) |
| 96 | + asyncio.create_task(run_desktop_vinted_publish_job(article_id, user_id, raw_token, remote)) |
| 97 | + return { |
| 98 | + "vinted": { |
| 99 | + "status": "running", |
| 100 | + "stream_path": f"/articles/{article_id}/vinted-progress", |
| 101 | + }, |
| 102 | + } |
| 103 | + |
| 104 | + |
| 105 | +@router.get("/{article_id}/vinted-progress") |
| 106 | +async def vinted_progress_stream( |
| 107 | + article_id: int, |
| 108 | + _: Annotated[int, Depends(get_user_id_introspected)], |
| 109 | +) -> StreamingResponse: |
| 110 | + async def generate(): |
| 111 | + async for ev in vinted_progress_hub.event_stream(article_id): |
| 112 | + yield f"data: {json.dumps(ev, default=str)}\n\n" |
| 113 | + |
| 114 | + return StreamingResponse( |
| 115 | + generate(), |
| 116 | + media_type="text/event-stream", |
| 117 | + headers={ |
| 118 | + "Cache-Control": "no-cache", |
| 119 | + "Connection": "keep-alive", |
| 120 | + "X-Accel-Buffering": "no", |
| 121 | + }, |
| 122 | + ) |
| 123 | + |
| 124 | + |
| 125 | +@router.get("/vinted-batch/active") |
| 126 | +async def vinted_batch_active( |
| 127 | + user_id: Annotated[int, Depends(get_user_id_introspected)], |
| 128 | +) -> dict[str, object]: |
| 129 | + jid = vinted_batch_hub.get_active_job_id(user_id) |
| 130 | + return { |
| 131 | + "job_id": jid, |
| 132 | + "stream_path": f"/articles/vinted-batch/{jid}/stream" if jid else None, |
| 133 | + } |
| 134 | + |
| 135 | + |
| 136 | +@router.get("/vinted-batch/{job_id}/stream") |
| 137 | +async def vinted_batch_stream( |
| 138 | + job_id: str, |
| 139 | + user_id: Annotated[int, Depends(get_user_id_introspected)], |
| 140 | +) -> StreamingResponse: |
| 141 | + owner = vinted_batch_hub.get_job_user_id(job_id) |
| 142 | + if owner is None: |
| 143 | + raise HTTPException(status_code=404, detail="Job introuvable ou expiré.") |
| 144 | + if owner != user_id: |
| 145 | + raise HTTPException(status_code=403, detail="Accès refusé à ce job.") |
| 146 | + |
| 147 | + async def generate(): |
| 148 | + async for ev in vinted_batch_hub.event_stream(job_id): |
| 149 | + yield f"data: {json.dumps(ev, default=str)}\n\n" |
| 150 | + |
| 151 | + return StreamingResponse( |
| 152 | + generate(), |
| 153 | + media_type="text/event-stream", |
| 154 | + headers={ |
| 155 | + "Cache-Control": "no-cache", |
| 156 | + "Connection": "keep-alive", |
| 157 | + "X-Accel-Buffering": "no", |
| 158 | + }, |
| 159 | + ) |
| 160 | + |
| 161 | + |
| 162 | +@router.post("/vinted-batch", status_code=status.HTTP_202_ACCEPTED) |
| 163 | +async def start_vinted_batch( |
| 164 | + body: VintedBatchStartBody, |
| 165 | + user_id: Annotated[int, Depends(get_user_id_introspected)], |
| 166 | + raw_token: Annotated[str, Depends(get_bearer_or_query_token)], |
| 167 | + remote: Annotated[str, Depends(get_remote_base_flexible)], |
| 168 | +) -> dict[str, object]: |
| 169 | + unique_ids = list(dict.fromkeys(body.article_ids)) |
| 170 | + job_id = str(uuid.uuid4()) |
| 171 | + if not vinted_batch_hub.try_register_job(job_id, user_id): |
| 172 | + raise HTTPException( |
| 173 | + status_code=409, |
| 174 | + detail="Une publication Vinted groupée est déjà en cours pour ce compte.", |
| 175 | + ) |
| 176 | + asyncio.create_task( |
| 177 | + run_desktop_vinted_batch_job(job_id, user_id, unique_ids, raw_token, remote), |
| 178 | + ) |
| 179 | + return { |
| 180 | + "job_id": job_id, |
| 181 | + "stream_path": f"/articles/vinted-batch/{job_id}/stream", |
| 182 | + } |
| 183 | + |
| 184 | + |
| 185 | +app = FastAPI(title="GoupixDex Vinted local", version="1.0.0") |
| 186 | +app.add_middleware( |
| 187 | + CORSMiddleware, |
| 188 | + allow_origins=["*"], |
| 189 | + allow_credentials=True, |
| 190 | + allow_methods=["*"], |
| 191 | + allow_headers=["*"], |
| 192 | +) |
| 193 | +app.include_router(router) |
| 194 | + |
| 195 | + |
| 196 | +@app.get("/health") |
| 197 | +def health() -> dict[str, str]: |
| 198 | + return {"status": "ok", "service": "goupixdex-vinted-local"} |
| 199 | + |
| 200 | + |
| 201 | +if __name__ == "__main__": |
| 202 | + from core.nodriver_uvicorn_loop import UVICORN_WINDOWS_NODRIVER_LOOP |
| 203 | + |
| 204 | + port = int(os.environ.get("GOUPIX_VINTED_LOCAL_PORT", "18766")) |
| 205 | + loop = UVICORN_WINDOWS_NODRIVER_LOOP if sys.platform == "win32" else "auto" |
| 206 | + uvicorn.run(app, host="127.0.0.1", port=port, loop=loop, log_level="info") |
0 commit comments