fix(platform): 持久化并完善斗鱼兑换结果图片
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
"""履约任务保存兑换结果图片。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "20261121_0105"
|
||||
down_revision = "20261121_0104"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _column_exists(column: str) -> bool:
|
||||
return bool(
|
||||
op.get_bind()
|
||||
.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'platform_fulfillment_tasks'
|
||||
AND column_name = :column
|
||||
"""
|
||||
),
|
||||
{"column": column},
|
||||
)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists("exchange_result_image_key"):
|
||||
op.add_column(
|
||||
"platform_fulfillment_tasks",
|
||||
sa.Column(
|
||||
"exchange_result_image_key",
|
||||
sa.String(length=512),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
if not _column_exists("exchange_result_image_saved_at"):
|
||||
op.add_column(
|
||||
"platform_fulfillment_tasks",
|
||||
sa.Column(
|
||||
"exchange_result_image_saved_at",
|
||||
sa.DateTime(),
|
||||
nullable=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _column_exists("exchange_result_image_saved_at"):
|
||||
op.drop_column("platform_fulfillment_tasks", "exchange_result_image_saved_at")
|
||||
if _column_exists("exchange_result_image_key"):
|
||||
op.drop_column("platform_fulfillment_tasks", "exchange_result_image_key")
|
||||
@@ -2043,6 +2043,12 @@ class PlatformFulfillmentTask(Base):
|
||||
exchange_task_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("douyu_tasks.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
exchange_result_image_key: Mapped[str] = mapped_column(
|
||||
String(512), nullable=False, default="", server_default=""
|
||||
)
|
||||
exchange_result_image_saved_at: Mapped[datetime | None] = mapped_column(
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
binding_status: Mapped[str] = mapped_column(
|
||||
String(24), nullable=False, default="not_started", server_default="not_started"
|
||||
)
|
||||
|
||||
@@ -10,9 +10,11 @@ from weakref import WeakKeyDictionary
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
File,
|
||||
HTTPException,
|
||||
Query,
|
||||
Request,
|
||||
UploadFile,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
)
|
||||
@@ -47,6 +49,7 @@ from ..schemas import (
|
||||
CookieReloginRequest,
|
||||
DouyuConfigOut,
|
||||
DouyuConfigUpdate,
|
||||
DouyuExchangeResultImageOut,
|
||||
DouyuGoodsOut,
|
||||
DouyuTaskAccountOut,
|
||||
DouyuTaskBatchRequest,
|
||||
@@ -63,6 +66,10 @@ from ..services.douyu_batch_launcher import (
|
||||
DOUYU_MAX_ACTIVE_BATCHES,
|
||||
start_douyu_batch,
|
||||
)
|
||||
from ..services.douyu_exchange_result_image import (
|
||||
ExchangeResultImageError,
|
||||
save_exchange_result_image,
|
||||
)
|
||||
from ..services.douyu_goods_service import serialize_goods
|
||||
from ..services.douyu_runner import DouyuBatchRunner, douyu_batch_registry
|
||||
from ..services.douyu_service import (
|
||||
@@ -80,6 +87,8 @@ from ..services.douyu_service import (
|
||||
douyu_task_payload,
|
||||
ensure_douyu_config,
|
||||
)
|
||||
from ..services.file_service import FileUploadError
|
||||
from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes
|
||||
from ..services.platform_fulfillment import service as platform_fulfillment_service
|
||||
|
||||
router = APIRouter(prefix="/api/douyu", tags=["斗鱼活动"])
|
||||
@@ -1241,6 +1250,70 @@ def cleanup_orphan_tasks(
|
||||
}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/tasks/{task_id}/exchange-result-image",
|
||||
response_model=DouyuExchangeResultImageOut,
|
||||
)
|
||||
def upload_exchange_result_image(
|
||||
task_id: int,
|
||||
file: UploadFile = File(...),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("douyu:task")),
|
||||
) -> DouyuExchangeResultImageOut:
|
||||
"""保存兑换结果 PNG,并绑定到对应履约任务供后续查看。"""
|
||||
task = _visible_tasks_query(db, current).filter(DouyuTask.id == task_id).first()
|
||||
if task is None:
|
||||
raise HTTPException(status_code=404, detail="任务不存在")
|
||||
platform_task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.id == int(task.platform_task_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
if task.platform_task_id
|
||||
else None
|
||||
)
|
||||
|
||||
limit = max_upload_size_bytes()
|
||||
data = file.file.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"文件不能超过 {limit // (1024 * 1024)}MB",
|
||||
)
|
||||
try:
|
||||
saved = save_exchange_result_image(
|
||||
db,
|
||||
task,
|
||||
data=data,
|
||||
filename=(file.filename or "").strip(),
|
||||
uploader_id=int(current.id),
|
||||
platform_task=platform_task,
|
||||
)
|
||||
except ExchangeResultImageError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except FileUploadError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
|
||||
except StorageUnavailableError as exc:
|
||||
raise HTTPException(status_code=503, detail="文件存储暂时不可用") from exc
|
||||
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
action="douyu:task:exchange_result_image",
|
||||
target=f"douyu_task:{task.id}",
|
||||
detail={
|
||||
"platform_task_id": task.platform_task_id,
|
||||
"object_key": saved["objectKey"],
|
||||
},
|
||||
)
|
||||
db.commit()
|
||||
return DouyuExchangeResultImageOut(
|
||||
object_key=str(saved["objectKey"]),
|
||||
url=str(saved["url"]),
|
||||
saved_at=cast(datetime, saved["savedAt"]),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}", response_model=DouyuTaskOut)
|
||||
def get_task(
|
||||
task_id: int,
|
||||
|
||||
@@ -1672,6 +1672,12 @@ class DouyuTaskOut(BaseModel):
|
||||
}
|
||||
|
||||
|
||||
class DouyuExchangeResultImageOut(BaseModel):
|
||||
object_key: str
|
||||
url: str
|
||||
saved_at: datetime
|
||||
|
||||
|
||||
class DouyuGoodsOut(BaseModel):
|
||||
id: int
|
||||
commodity_id: str
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""保存斗鱼兑换结果图片,供履约任务长期查看、复制和下载。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import DouyuTask, PlatformFulfillmentTask
|
||||
from .file_service import build_file_url, sniff_content_type, upload_file_asset
|
||||
|
||||
EXCHANGE_RESULT_TASK_TYPES = frozenset(
|
||||
{
|
||||
"exchange_goods",
|
||||
"pay_locked_order",
|
||||
"exchange_esports_goods",
|
||||
"exchange_xpd_goods",
|
||||
}
|
||||
)
|
||||
EXCHANGE_RESULT_SCENE = "exchange-result"
|
||||
|
||||
|
||||
class ExchangeResultImageError(ValueError):
|
||||
"""兑换结果图片不符合任务状态或文件契约。"""
|
||||
|
||||
|
||||
def _result_image(task: DouyuTask) -> dict[str, Any]:
|
||||
result = task.result if isinstance(task.result, dict) else {}
|
||||
image = result.get("exchange_result_image")
|
||||
return image if isinstance(image, dict) else {}
|
||||
|
||||
|
||||
def exchange_result_image_payload(
|
||||
task: DouyuTask,
|
||||
platform_task: PlatformFulfillmentTask | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""返回任务已保存图片的稳定代理地址;没有保存时返回 ``None``。"""
|
||||
image = _result_image(task)
|
||||
object_key = str(
|
||||
(platform_task.exchange_result_image_key if platform_task else "")
|
||||
or image.get("object_key")
|
||||
or ""
|
||||
).strip()
|
||||
if not object_key:
|
||||
return None
|
||||
saved_at = (
|
||||
platform_task.exchange_result_image_saved_at
|
||||
if platform_task
|
||||
else None
|
||||
)
|
||||
if saved_at is None:
|
||||
raw_saved_at = image.get("saved_at")
|
||||
if isinstance(raw_saved_at, str):
|
||||
try:
|
||||
saved_at = datetime.fromisoformat(raw_saved_at)
|
||||
except ValueError:
|
||||
saved_at = None
|
||||
return {
|
||||
"objectKey": object_key,
|
||||
"url": build_file_url(object_key),
|
||||
"savedAt": saved_at,
|
||||
}
|
||||
|
||||
|
||||
def save_exchange_result_image(
|
||||
db: Session,
|
||||
task: DouyuTask,
|
||||
*,
|
||||
data: bytes,
|
||||
filename: str = "",
|
||||
uploader_id: int,
|
||||
platform_task: PlatformFulfillmentTask | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""保存 PNG 并把对象 key 同时写回斗鱼任务和履约任务。
|
||||
|
||||
重复调用是幂等的:已有图片直接返回,不再产生第二份对象。
|
||||
"""
|
||||
if task.task_type not in EXCHANGE_RESULT_TASK_TYPES:
|
||||
raise ExchangeResultImageError("当前任务不是兑换任务")
|
||||
if task.status != "success":
|
||||
raise ExchangeResultImageError("只有兑换成功的任务可以保存结果图片")
|
||||
if sniff_content_type(data) != "image/png":
|
||||
raise ExchangeResultImageError("兑换结果图片必须是 PNG")
|
||||
|
||||
existing = exchange_result_image_payload(task, platform_task)
|
||||
if existing is not None:
|
||||
if platform_task and not platform_task.exchange_result_image_key:
|
||||
platform_task.exchange_result_image_key = str(existing["objectKey"])
|
||||
platform_task.exchange_result_image_saved_at = (
|
||||
existing["savedAt"] or datetime.now(UTC).replace(microsecond=0)
|
||||
)
|
||||
db.commit()
|
||||
return existing
|
||||
|
||||
uploaded = upload_file_asset(
|
||||
db,
|
||||
data=data,
|
||||
filename=filename or f"douyu-exchange-result-{task.id}.png",
|
||||
content_type="image/png",
|
||||
scene=EXCHANGE_RESULT_SCENE,
|
||||
uploader_type="user",
|
||||
uploader_id=str(uploader_id),
|
||||
)
|
||||
saved_at = datetime.now(UTC).replace(microsecond=0)
|
||||
result = dict(task.result or {})
|
||||
result["exchange_result_image"] = {
|
||||
"object_key": uploaded.object_key,
|
||||
"content_type": uploaded.content_type,
|
||||
"size": uploaded.size,
|
||||
"saved_at": saved_at.isoformat(),
|
||||
}
|
||||
task.result = result
|
||||
if platform_task is not None:
|
||||
platform_task.exchange_task_id = int(task.id)
|
||||
platform_task.exchange_result_image_key = uploaded.object_key
|
||||
platform_task.exchange_result_image_saved_at = saved_at
|
||||
db.commit()
|
||||
return {
|
||||
"objectKey": uploaded.object_key,
|
||||
"url": uploaded.url,
|
||||
"savedAt": saved_at,
|
||||
}
|
||||
@@ -56,6 +56,7 @@ from ..external_order_source import (
|
||||
list_pending_manual_fulfillments,
|
||||
lookup_pending_manual_fulfillment,
|
||||
)
|
||||
from ..file_service import build_file_url
|
||||
from .account_selector import (
|
||||
AccountCandidate,
|
||||
capability_candidate_accounts,
|
||||
@@ -662,6 +663,8 @@ def record_douyu_operation_started(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""记录履约上下文发起的斗鱼操作,账号任务结果由执行器补写。"""
|
||||
if task_type == "exchange_goods" and len(douyu_task_ids) == 1:
|
||||
task.exchange_task_id = int(douyu_task_ids[0])
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
@@ -1056,6 +1059,7 @@ def _task_out(
|
||||
task: PlatformFulfillmentTask,
|
||||
*,
|
||||
include_qr: bool = False,
|
||||
include_exchange_task: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
account = (
|
||||
db.query(Account).filter(Account.id == task.account_id).first()
|
||||
@@ -1078,6 +1082,18 @@ def _task_out(
|
||||
.first()
|
||||
)
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
exchange_task_id = task.exchange_task_id
|
||||
if exchange_task_id is None and include_exchange_task:
|
||||
exchange_task_id = (
|
||||
db.query(DouyuTask.id)
|
||||
.filter(
|
||||
DouyuTask.platform_task_id == task.id,
|
||||
DouyuTask.task_type == "exchange_goods",
|
||||
)
|
||||
.order_by(DouyuTask.id.desc())
|
||||
.limit(1)
|
||||
.scalar()
|
||||
)
|
||||
# 外层只消费共享绑定规则,不再自己比较角色名或 bindAct。
|
||||
pending_role = pending_binding_role_from_result(bind_result)
|
||||
return {
|
||||
@@ -1163,6 +1179,16 @@ def _task_out(
|
||||
if bind_task
|
||||
else None
|
||||
),
|
||||
"exchangeTaskId": exchange_task_id,
|
||||
"exchangeResultImage": (
|
||||
{
|
||||
"objectKey": task.exchange_result_image_key,
|
||||
"url": build_file_url(task.exchange_result_image_key),
|
||||
"savedAt": task.exchange_result_image_saved_at,
|
||||
}
|
||||
if task.exchange_result_image_key
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -1189,7 +1215,7 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
else {}
|
||||
)
|
||||
return {
|
||||
"task": _task_out(db, task, include_qr=True),
|
||||
"task": _task_out(db, task, include_qr=True, include_exchange_task=True),
|
||||
"events": [
|
||||
{
|
||||
"id": event.id,
|
||||
|
||||
Reference in New Issue
Block a user