Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

授权函

增瑞 田ad2e09325f0e
diff --git a/backend/app/marketplace/authorization.py b/backend/app/marketplace/authorization.py
index fa2318e..107a90c 100644
--- a/backend/app/marketplace/authorization.py
+++ b/backend/app/marketplace/authorization.py
@@ -1,12 +1,13 @@
"""本平台作品账号授权;仅作用于下游,不自动转让或授予买家权利。"""
import asyncio
import hashlib
+import logging
from pathlib import Path
import tempfile
from typing import Annotated, Literal
import uuid
-from fastapi import APIRouter, Depends, Request
+from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import Field, model_validator
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
@@ -18,6 +19,8 @@ from .models import Authorization
from .schemas import Input
from .service import data, event, fail, now
+logger = logging.getLogger("marketplace.authorization")
+
VERSION = "printfilm-marketplace-2026-10-v1"
TITLE = "PrintFilm 生成作品展示与撮合授权函"
BODY = """一、适用作品:本人以本账号提交至数字资产市场并声明为 PrintFilm 生成的作品。本授权函可被本账号后续作品引用,但每件作品的来源、权属、素材及授权范围仍由平台逐件核验。
@@ -80,21 +83,28 @@ def _wrap(text: str, font_name: str, size: float, width: float) -> list[str]:
return lines
def render_and_store(body: SignInput, signed_at: str, owner_id: int) -> str:
- """把条款和手写签名直接写成 PDF,再存入私有 OSS。"""
- from reportlab.pdfgen import canvas
+ """把条款和手写签名直接写成 PDF,再存入私有 OSS。生成失败不伪装成存储未配置。"""
try:
font_name = _pdf_font(resolve_cjk_font())
- except (OSError, FileNotFoundError):
- fail("服务器未找到可用的中文字体,暂时无法生成授权函。请安装 Noto CJK 或文泉驿字体后重试。", 503)
- prefix = f"marketplace/authorizations/u{owner_id}/{uuid.uuid4().hex}"
- key = f"{prefix}/letter.pdf"
- with tempfile.TemporaryDirectory(prefix="printfilm-authorization-") as folder:
- path = Path(folder) / "letter.pdf"
- _write_letter(path, font_name, body, signed_at, owner_id)
- storage.upload(key, path, "application/pdf")
- return key
+ prefix = f"marketplace/authorizations/u{owner_id}/{uuid.uuid4().hex}"
+ key = f"{prefix}/letter.pdf"
+ with tempfile.TemporaryDirectory(prefix="printfilm-authorization-") as folder:
+ path = Path(folder) / "letter.pdf"
+ _write_letter(path, font_name, body, signed_at, owner_id)
+ storage.upload(key, path, "application/pdf")
+ return key
+ except HTTPException:
+ raise
+ except (OSError, FileNotFoundError) as exc:
+ logger.warning("授权函字体不可用:%s", type(exc).__name__)
+ fail("服务器未找到可用的中文字体,暂时无法生成授权函。", 503)
+ except ImportError:
+ logger.exception("授权函组件未安装")
+ fail("服务器未安装生成授权函所需组件,请安装 requirements-marketplace.txt 后重启。", 503)
+ except Exception:
+ logger.exception("授权函生成失败")
+ fail("授权函生成失败,请稍后重试。", 503)
def _write_letter(path: Path, font_name: str, body: SignInput, signed_at: str, owner_id: int) -> None:
diff --git a/backend/app/marketplace/storage.py b/backend/app/marketplace/storage.py
index 5fdbc02..ee0d232 100644
--- a/backend/app/marketplace/storage.py
+++ b/backend/app/marketplace/storage.py
@@ -1,6 +1,7 @@
"""共用后台 OSS 配置,独立私有对象;不复用公开上传函数。"""
from functools import lru_cache, wraps
import json
+import logging
from pathlib import Path
import time
@@ -9,6 +10,8 @@ from app.config import get_settings
from .config import get_marketplace_settings
+logger = logging.getLogger("marketplace.storage")
+
# 已核验客户端及核验时刻;一分钟后重新检查 Bucket 权限。
_verified_at: float = 0
_verified_client = None
@@ -34,6 +37,7 @@ def transport(operation):
except HTTPException:
raise
except Exception as exc:
+ logger.warning("市场文件操作失败:%s", getattr(exc, "code", None) or type(exc).__name__)
raise unavailable() from exc
return guarded
@@ -63,7 +67,9 @@ def bucket():
try:
client = _client()
if client is not _verified_client or time.monotonic() - _verified_at > 60:
- if client.get_bucket_acl().acl != "private":
+ acl = client.get_bucket_acl().acl
+ if acl != "private":
+ logger.warning("市场存储不可用:Bucket ACL 为 %s,需要 private", acl)
raise unavailable()
try:
policy = json.loads(client.get_bucket_policy().policy)
@@ -76,6 +82,7 @@ def bucket():
principal = statement.get("Principal", "")
# 下游不接受任何匿名授权策略,避免条件或资源规则被误判。
if "*" in json.dumps(principal):
+ logger.warning("市场存储不可用:Bucket Policy 允许匿名访问")
raise unavailable()
except Exception as exc:
# Aliyun returns 404/NoSuchBucketPolicy when no optional bucket
@@ -92,6 +99,7 @@ def bucket():
except HTTPException:
raise
except Exception as exc:
+ logger.warning("市场存储不可用:%s", getattr(exc, "code", None) or type(exc).__name__)
raise unavailable() from exc
diff --git a/backend/tests/test_marketplace.py b/backend/tests/test_marketplace.py
index 6308d5e..34e6557 100644
--- a/backend/tests/test_marketplace.py
+++ b/backend/tests/test_marketplace.py
@@ -426,6 +426,21 @@ def test_bundled_cjk_font_is_used_when_configured_path_missing(monkeypatch):
TTFont("BundledCJKTest", found, subfontIndex=0)
+def test_authorization_generation_error_is_not_storage(monkeypatch):
+ """生成授权函失败时不要报成文件服务未配置。"""
+ from app.marketplace.authorization import SignInput, render_and_store
+
+ def missing_component(path):
+ raise ImportError("reportlab")
+
+ body = SignInput.model_validate(signing_body())
+ monkeypatch.setattr("app.marketplace.authorization._pdf_font", missing_component)
+ with pytest.raises(HTTPException) as error:
+ render_and_store(body, "2026-10-26T00:00:00+00:00", 1)
+ assert error.value.status_code == 503
+ assert error.value.detail == "服务器未安装生成授权函所需组件,请安装 requirements-marketplace.txt 后重启。"
+
+
def test_letter_font_falls_back_when_configured_path_missing(monkeypatch):
"""配置路径和系统字体都不存在时,明确报缺少字体。"""
from app.marketplace.config import resolve_cjk_font