Files
gsfdc/server/app/services/association_education.py
T

50 lines
1.6 KiB
Python

"""协会教育只配置两个外链,不承载学习业务。"""
import json
from urllib.parse import urlsplit
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.models.content import SiteSetting
SETTING_KEY = "association_education"
def validate_url(value: str) -> str:
text = value.strip()
if not text:
return ""
try:
parsed = urlsplit(text)
valid = (
len(text) <= 2048
and parsed.scheme.lower() in {"http", "https"}
and bool(parsed.hostname)
and parsed.username is None
and parsed.password is None
and "\\" not in text
and not any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in text)
and (parsed.port is None or 1 <= parsed.port <= 65535)
)
except ValueError:
valid = False
if not valid:
raise ValueError("请填写完整的 http:// 或 https:// 网址,不包含账号密码")
return text
def read_links(db: Session) -> dict[str, str]:
row = db.scalar(select(SiteSetting).where(SiteSetting.key == SETTING_KEY))
stored = json.loads(row.value) if row else {}
return {key: stored.get(key, "") for key in ("webUrl", "mobileUrl")}
def save_links(db: Session, web_url: str, mobile_url: str) -> None:
value = json.dumps({"webUrl": validate_url(web_url), "mobileUrl": validate_url(mobile_url)})
row = db.scalar(select(SiteSetting).where(SiteSetting.key == SETTING_KEY))
if row is None:
db.add(SiteSetting(key=SETTING_KEY, value=value))
else:
row.value = value
db.commit()