Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd0bcc2516 | ||
|
|
d5cf278073 | ||
|
|
16e649633b |
No files matched your search
@@ -0,0 +1,121 @@
|
||||
# it-tools-relay
|
||||
|
||||
IT-Tools 的自建后端中继服务(Python 标准库 `http.server`,**监听 8091**,无第三方框架依赖)。为 IT-Tools 前端提供:
|
||||
|
||||
- **翻译代理** `GET /translate` —— 转发 Google Translate(走 `HTTPS_PROXY` 出网,解决国内不通)
|
||||
- **授权校验** `GET /check` —— 供 nginx `auth_request` 调用,卡密授权 / 试用窗口判定(网络故障 fail-open,不锁死付费用户)
|
||||
- **卡密激活** `POST /activate` —— 代理 CardAuth 验卡,`CARD_AUTH_KEY` 只留在容器内
|
||||
- **授权中心 hub** `GET /hub/announcements`(拉项目公告,服务端双保险过滤 `project_id`)+ `POST /hub/report`(安装登记 + 心跳在线统计,`X-Api-Key`/`X-Project-Id=6` 只存在服务端;**先心跳后 check-update**——实测 CardAuth heartbeat 会清空 `client_version/device_info`,check-update 放最后保证版本号落库)
|
||||
- 另有大量 AI 对话/生图、TTS/ASR、视频、格式转换、网速测速、IP 查询等接口(`server.py`,约 3700 行)
|
||||
|
||||
Docker 镜像内置:calibre(`ebook-convert`)、ffmpeg、Piper(本地 TTS)、faster-whisper(本地 ASR)、rembg(抠图)、waifu2x(无损放大)、中文回退字体。模型文件(`hf-cache/`、`piper-models/`、`ai-models/`、`waifu2x/`)已预下载到构建上下文,**构建不需要联网**。
|
||||
|
||||
镜像也可直接拉取:`192.168.68.19:3200/jinghui/it-tools-relay:latest`(Gitea Container Registry,免登录)。
|
||||
|
||||
## 环境变量(`.env`)
|
||||
|
||||
```bash
|
||||
cat > .env <<'EOF'
|
||||
# CardAuth 授权中心(/check、/activate 用)
|
||||
CARD_AUTH_KEY=your-cardauth-project-key
|
||||
AUTH_BASE=https://auth.88531.cn/api
|
||||
AUTH_USER=admin
|
||||
AUTH_PASS=your-auth-pass
|
||||
PROJECT_NAME=IT-Tools
|
||||
PROJECT_ID=6
|
||||
PROJECT_ALIASES=IT-Tools,IT-TOOLS-PRO
|
||||
|
||||
# IT-Tools 前端接入的中继地址(前端调用方填,非本容器变量)
|
||||
# 中继监听 8091
|
||||
|
||||
# 管理员 / 人机验证
|
||||
DEFAULT_ADMIN_USER=admin
|
||||
DEFAULT_ADMIN_PW=change-me
|
||||
ADMIN_TOKEN=
|
||||
TURNSTILE_SECRET=
|
||||
|
||||
# AI 网关(可选,/ai/* 接口用)
|
||||
NEWAPI_URL=https://your-newapi-host/v1/chat/completions
|
||||
NEWAPI_KEY=sk-xxx
|
||||
NEWAPI_MODEL=qwen3.8-flash
|
||||
|
||||
# 出网代理(翻译等走 Google 的接口用,可选)
|
||||
HTTPS_PROXY=http://host.docker.internal:7890
|
||||
RELAY_TIMEOUT=25
|
||||
|
||||
# 上传限制(MB)
|
||||
MAX_UPLOAD_MB=50
|
||||
EOF
|
||||
```
|
||||
|
||||
## 方式一:docker run
|
||||
|
||||
```bash
|
||||
docker build -t it-tools-relay .
|
||||
docker run -d --name it-tools-relay --restart always \
|
||||
-p 8091:8091 --env-file .env \
|
||||
-v relay-data:/app/data \
|
||||
it-tools-relay
|
||||
```
|
||||
|
||||
已有镜像时可省去构建:`docker run ... 192.168.68.19:3200/jinghui/it-tools-relay:latest`。
|
||||
|
||||
数据(试用记录、用量库、用户库)持久化在卷 `relay-data:/app/data`。要被 IT-Tools 的 nginx 按容器名反代,需加 `--network ittools-net`(`docker network create ittools-net`)。
|
||||
|
||||
## 方式二:Docker Compose 部署
|
||||
|
||||
本仓库根目录 `docker-compose.yml`(含全部参数):
|
||||
|
||||
```yaml
|
||||
services:
|
||||
it-tools-relay:
|
||||
build: .
|
||||
image: 192.168.68.19:3200/jinghui/it-tools-relay:latest
|
||||
container_name: it-tools-relay
|
||||
restart: always
|
||||
ports:
|
||||
- "8091:8091"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
# 常用项也可直接写在这里,优先级高于 .env
|
||||
- RELAY_TIMEOUT=25
|
||||
- MAX_UPLOAD_MB=50
|
||||
- HF_HOME=/root/.cache/huggingface
|
||||
volumes:
|
||||
# 试用记录 / 用量库 / 用户库 持久化
|
||||
- relay-data:/app/data
|
||||
# 可选:代理宿主机目录,供 /hostfs、文件转换类接口使用
|
||||
# - ./data:/app/data
|
||||
extra_hosts:
|
||||
# 容器内访问宿机代理 / 服务时用 host.docker.internal
|
||||
- "host.docker.internal:host-gateway"
|
||||
networks:
|
||||
- ittools-net
|
||||
|
||||
volumes:
|
||||
relay-data:
|
||||
|
||||
networks:
|
||||
ittools-net:
|
||||
driver: bridge
|
||||
```
|
||||
|
||||
```bash
|
||||
git clone http://192.168.68.19:3200/jinghui/it-tools-relay.git
|
||||
cd it-tools-relay
|
||||
cat > .env # 按上表内容创建 .env
|
||||
docker compose up -d --build
|
||||
docker compose ps # it-tools-relay 为 running 即就绪
|
||||
curl -s http://127.0.0.1:8091/auth-status # 返回 JSON 即服务正常
|
||||
```
|
||||
|
||||
只重建代码(模型目录已缓存):`docker compose up -d --build it-tools-relay`。
|
||||
|
||||
## 其他镜像变体
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| `Dockerfile` | 主镜像(完整模型 + AI 接口) |
|
||||
| `Dockerfile.patch` | `FROM it-tools-relay:latest`,只覆盖 `server.py` / `video_ops.py` / `audio_ops.py` 的热更镜像(构建秒级) |
|
||||
| `Dockerfile.lt` | `FROM it-tools-relay:se-patch`,LibreTranslate 相关补丁,需 `docker/lt` 目录的翻译栈配合(见 it-tools-pro 仓库) |
|
||||
@@ -1196,6 +1196,28 @@ def admin_api(method: str, sub: str, payload: dict, handler):
|
||||
_save_reco(clean)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
# ---------- 站内留言反馈(管理端查看/改状态/删除) ----------
|
||||
if method == "GET" and sub == "/feedback":
|
||||
items = sorted(_load_feedback(), key=lambda x: float(x.get("ts") or 0), reverse=True)
|
||||
return 200, {"code": 200, "message": "ok", "data": items}
|
||||
|
||||
if method == "POST" and sub == "/feedback":
|
||||
fid = str(payload.get("id") or "")
|
||||
if not fid:
|
||||
return 400, {"code": 400, "message": "缺少留言 id"}
|
||||
with FEEDBACK_LOCK:
|
||||
items = _load_feedback()
|
||||
hit = next((it for it in items if it.get("id") == fid), None)
|
||||
if not hit:
|
||||
return 404, {"code": 404, "message": "留言不存在"}
|
||||
if str(payload.get("action") or "") == "delete":
|
||||
items = [it for it in items if it.get("id") != fid]
|
||||
else:
|
||||
status = str(payload.get("status") or "new")
|
||||
hit["status"] = status if status in ("new", "replied", "done") else "new"
|
||||
_save_feedback(items)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
if method == "GET" and sub == "/storage":
|
||||
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
|
||||
for extra in ("users.db", "usage.db", "trials.json"):
|
||||
@@ -1294,11 +1316,282 @@ def _req_machine(handler):
|
||||
return handler.headers.get("X-Machine-Id", "") if handler else ""
|
||||
|
||||
|
||||
# ---- 本地图片验证码(替代 Cloudflare Turnstile:不依赖外网,服务端出图) ----
|
||||
try:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
_HAS_PIL = True
|
||||
except Exception: # pragma: no cover
|
||||
_HAS_PIL = False
|
||||
|
||||
CAPTCHA_TTL = 300 # 验证码有效期(秒)
|
||||
_CAPTCHA_MAX = 5000 # 内存上限(防撑爆)
|
||||
_CAPTCHAS = {} # id -> (code, expire_ts),单次核销
|
||||
_CAPTCHA_LOCK = threading.Lock()
|
||||
_CAPTCHA_CHARS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # 去掉易混字符 0/O/1/I/L
|
||||
|
||||
|
||||
def _gen_captcha():
|
||||
"""返回 (captcha_id, png_base64)。4 位干扰码,5 分钟过期,取用即销毁。"""
|
||||
import base64
|
||||
import random
|
||||
import uuid
|
||||
|
||||
code = "".join(random.choice(_CAPTCHA_CHARS) for _ in range(4))
|
||||
cid = uuid.uuid4().hex
|
||||
w, h = 148, 52
|
||||
img = Image.new("RGB", (w, h), (247, 248, 251))
|
||||
d = ImageDraw.Draw(img)
|
||||
try:
|
||||
font = ImageFont.load_default(size=36)
|
||||
except TypeError: # pragma: no cover
|
||||
font = ImageFont.load_default()
|
||||
# 干扰线 + 噪点
|
||||
for _ in range(7):
|
||||
d.line([random.randrange(w), random.randrange(h),
|
||||
random.randrange(w), random.randrange(h)],
|
||||
fill=(random.randint(160, 210), random.randint(160, 210), random.randint(160, 210)),
|
||||
width=1)
|
||||
for _ in range(60):
|
||||
d.point((random.randrange(w), random.randrange(h)),
|
||||
fill=(random.randint(150, 220), random.randint(150, 220), random.randint(150, 220)))
|
||||
# 逐字带抖动绘制
|
||||
x = 14
|
||||
for ch in code:
|
||||
d.text((x, 6 + random.randint(-4, 4)), ch, font=font,
|
||||
fill=(random.randint(10, 90), random.randint(10, 90), random.randint(10, 90)))
|
||||
x += 33
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
now = time.time()
|
||||
with _CAPTCHA_LOCK:
|
||||
for k in [k for k, v in _CAPTCHAS.items() if v[1] < now]:
|
||||
_CAPTCHAS.pop(k, None)
|
||||
while len(_CAPTCHAS) >= _CAPTCHA_MAX:
|
||||
_CAPTCHAS.pop(next(iter(_CAPTCHAS)), None)
|
||||
_CAPTCHAS[cid] = (code, now + CAPTCHA_TTL)
|
||||
return cid, base64.b64encode(buf.getvalue()).decode()
|
||||
|
||||
|
||||
def verify_captcha(payload) -> bool:
|
||||
"""核销 captcha_id + captcha_code(单次有效,大小写不敏感)。"""
|
||||
cid = str(payload.get("captcha_id") or "")
|
||||
got = str(payload.get("captcha_code") or "").strip().upper()
|
||||
if not cid or not got:
|
||||
return False
|
||||
with _CAPTCHA_LOCK:
|
||||
entry = _CAPTCHAS.pop(cid, None) # 无论对错都销毁,防爆破
|
||||
if not entry:
|
||||
return False
|
||||
stored, exp = entry
|
||||
if time.time() > exp:
|
||||
return False
|
||||
import secrets as _secrets
|
||||
return _secrets.compare_digest(stored, got)
|
||||
|
||||
|
||||
# ============ 站内留言反馈(独立于卡密/授权系统,任何人可用) ============
|
||||
# ---- CardAuth hub 接入(项目 6):在线统计上报 + 公告推送,失败开放(不可达不影响站点) ----
|
||||
HUB_TIMEOUT = 8
|
||||
|
||||
|
||||
def hub_announcements(limit: int = 20) -> tuple[int, dict]:
|
||||
"""GET /hub/announcements — 服务端拉本项目公告,双保险过滤 project_id。"""
|
||||
try:
|
||||
res = _get_json(
|
||||
f"/public/announcements?target=client&project_id={PROJECT_ID}&limit={max(1, min(int(limit), 50))}",
|
||||
{}, timeout=HUB_TIMEOUT)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"[hub] announcements failed: {exc}", flush=True)
|
||||
return 503, {"code": 503, "message": "公告服务暂不可用",
|
||||
"data": {"list": [], "popup": []}}
|
||||
data = (res or {}).get("data") or {}
|
||||
|
||||
def mine(arr) -> list:
|
||||
out = []
|
||||
for a in arr or []:
|
||||
if not isinstance(a, dict):
|
||||
continue
|
||||
pid = a.get("project_id")
|
||||
if pid in (None, "", 0) or str(pid) == str(PROJECT_ID):
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
return 200, {"code": 200, "message": "ok",
|
||||
"data": {"list": mine(data.get("list")), "popup": mine(data.get("popup"))}}
|
||||
|
||||
|
||||
def hub_report(payload: dict) -> tuple[int, dict]:
|
||||
"""POST /hub/report {machine_id, client_version, device_info}
|
||||
— 安装登记(安装统计)+ 心跳(在线统计),顺带返回版本推送信息。"""
|
||||
machine = str(payload.get("machine_id") or "")
|
||||
version = str(payload.get("client_version") or "0")[:40]
|
||||
device = str(payload.get("device_info") or "")[:200] or "web"
|
||||
if not MACHINE_RE.match(machine):
|
||||
return 400, {"code": 400, "message": "机器码格式错误"}
|
||||
if not (CARD_AUTH_KEY and PROJECT_ID):
|
||||
return 503, {"code": 503, "message": "授权中心未配置"}
|
||||
hdr = {"X-Api-Key": CARD_AUTH_KEY, "X-Project-Id": str(PROJECT_ID)}
|
||||
out: dict = {"install_id": None, "latest_version": "",
|
||||
"update_available": False, "update_required": False,
|
||||
"download_url": None, "changelog": None, "online": False}
|
||||
# 心跳必须在 check-update 之前:实测 CardAuth heartbeat 会把
|
||||
# client_version/device_info 清空,check-update 放最后确保版本号落库
|
||||
try:
|
||||
hb = _post_json("/public/installations/heartbeat", {"machine_id": machine},
|
||||
hdr, timeout=HUB_TIMEOUT)
|
||||
out["online"] = (hb or {}).get("code") == 200
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"[hub] heartbeat failed: {exc}", flush=True)
|
||||
try:
|
||||
res = _post_json("/public/installations/check-update",
|
||||
{"machine_id": machine, "client_version": version,
|
||||
"device_info": device}, hdr, timeout=HUB_TIMEOUT)
|
||||
d = (res or {}).get("data") or {}
|
||||
out.update({
|
||||
"install_id": d.get("install_id"),
|
||||
"latest_version": d.get("latest_version") or "",
|
||||
"update_available": bool(d.get("update_available")),
|
||||
"update_required": bool(d.get("update_required")),
|
||||
"download_url": d.get("download_url"),
|
||||
"changelog": d.get("changelog"),
|
||||
})
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"[hub] check-update failed: {exc}", flush=True)
|
||||
return 503, {"code": 503, "message": "授权中心暂不可用", "data": out}
|
||||
return 200, {"code": 200, "message": "ok", "data": out}
|
||||
|
||||
|
||||
# GET /feedback/captcha 图形验证码
|
||||
# POST /feedback {type,content,contact,captcha_id,captcha_code}
|
||||
FEEDBACK_FILE = os.path.join(DATA_DIR, "feedback.json")
|
||||
FEEDBACK_TYPES = ("功能建议", "意见反馈")
|
||||
FEEDBACK_WINDOW = 3600 # 同一 IP 两次提交的最小间隔(秒,1 小时)
|
||||
FEEDBACK_MAX = 2000 # 存档上限,超出丢弃最旧
|
||||
FEEDBACK_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _load_feedback() -> list:
|
||||
try:
|
||||
with open(FEEDBACK_FILE, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
return data if isinstance(data, list) else []
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
|
||||
|
||||
def _save_feedback(items: list) -> None:
|
||||
tmp = FEEDBACK_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as fh:
|
||||
json.dump(items, fh, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, FEEDBACK_FILE)
|
||||
|
||||
|
||||
def _ip_is_public(value: str) -> bool:
|
||||
try:
|
||||
import ipaddress
|
||||
ip = ipaddress.ip_address(value)
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
return not (
|
||||
ip.is_private or ip.is_loopback or ip.is_link_local
|
||||
or ip.is_reserved or ip.is_multicast
|
||||
)
|
||||
|
||||
|
||||
def _real_client_ip(handler) -> str:
|
||||
"""取真实客户端 IP(限频用)。
|
||||
|
||||
链路:浏览器 → nps/frp 隧道(注入真实 IP 的 X-Forwarded-For)
|
||||
→ nginx(再追加 $remote_addr = 隧道/内网地址)→ relay。
|
||||
因此 XFF 从右往左取第一个公网地址:先跳过隧道与内网地址,
|
||||
客户端在链路最左侧伪造的头也不会被采信。
|
||||
"""
|
||||
raw = handler.headers.get("X-Forwarded-For") or handler.headers.get("X-Real-IP") or ""
|
||||
parts = [p.strip() for p in raw.split(",") if p.strip()]
|
||||
for part in reversed(parts):
|
||||
if _ip_is_public(part):
|
||||
return part
|
||||
if parts:
|
||||
return parts[0]
|
||||
try:
|
||||
return handler.client_address[0] or "unknown"
|
||||
except Exception: # noqa: BLE001
|
||||
return "unknown"
|
||||
|
||||
|
||||
def feedback_api(method: str, payload: dict, handler) -> tuple:
|
||||
"""公开留言接口:GET 出图形验证码,POST 提交留言。"""
|
||||
if method == "GET":
|
||||
if not _HAS_PIL:
|
||||
return 503, {"code": 503, "message": "验证码组件未就绪,请稍后再试"}
|
||||
cid, img_b64 = _gen_captcha()
|
||||
return 200, {"code": 200, "message": "ok", "data": {"id": cid, "img": img_b64}}
|
||||
|
||||
# POST:先人机验证,再业务校验,最后同 IP 1 小时限频
|
||||
if not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
|
||||
ftype = str(payload.get("type") or "").strip()
|
||||
if ftype not in FEEDBACK_TYPES:
|
||||
return 400, {"code": 400, "message": "请选择留言类型:功能建议 / 意见反馈"}
|
||||
|
||||
content = str(payload.get("content") or "").replace("\r\n", "\n").strip()
|
||||
if not content:
|
||||
return 400, {"code": 400, "message": "请填写留言内容"}
|
||||
if len(content) > 1000:
|
||||
return 400, {"code": 400, "message": "留言内容最多 1000 字"}
|
||||
|
||||
contact = str(payload.get("contact") or "").strip()
|
||||
if len(contact) > 64:
|
||||
return 400, {"code": 400, "message": "联系方式最多 64 字"}
|
||||
if any(ord(c) < 32 for c in contact):
|
||||
return 400, {"code": 400, "message": "联系方式含非法字符"}
|
||||
|
||||
ip = _real_client_ip(handler)
|
||||
now = time.time()
|
||||
|
||||
with FEEDBACK_LOCK:
|
||||
items = _load_feedback()
|
||||
last_ts = 0.0
|
||||
for it in reversed(items):
|
||||
if it.get("ip") == ip:
|
||||
try:
|
||||
last_ts = float(it.get("ts") or 0)
|
||||
except Exception: # noqa: BLE001
|
||||
last_ts = 0.0
|
||||
break
|
||||
if now - last_ts < FEEDBACK_WINDOW:
|
||||
wait_min = max(int((FEEDBACK_WINDOW - (now - last_ts)) / 60), 1)
|
||||
return 429, {"code": 429, "message": f"同一 IP 一小时内只能提交一次,请 {wait_min} 分钟后再试"}
|
||||
|
||||
items.append({
|
||||
"id": f"{int(now)}-{secrets.token_hex(4)}",
|
||||
"ts": int(now),
|
||||
"ip": ip,
|
||||
"type": ftype,
|
||||
"content": content,
|
||||
"contact": contact,
|
||||
"status": "new",
|
||||
})
|
||||
if len(items) > FEEDBACK_MAX:
|
||||
items = items[-FEEDBACK_MAX:]
|
||||
_save_feedback(items)
|
||||
|
||||
print(f"[feedback] new from {ip} [{ftype}] {len(content)} chars", flush=True)
|
||||
return 200, {"code": 200, "message": "ok"}
|
||||
|
||||
|
||||
def user_api(method, sub, payload, handler):
|
||||
"""returns (status, body_dict)"""
|
||||
if method == "GET" and sub == "/captcha":
|
||||
if not _HAS_PIL:
|
||||
return 503, {"code": 503, "message": "验证码组件未就绪"}
|
||||
cid, img_b64 = _gen_captcha()
|
||||
return 200, {"code": 200, "message": "ok", "data": {"id": cid, "img": img_b64}}
|
||||
|
||||
if method == "POST" and sub == "/register":
|
||||
if not verify_turnstile(str(payload.get("cf_token") or "")):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"}
|
||||
if not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
if not USER_NAME_RE.match(username):
|
||||
@@ -1321,10 +1614,10 @@ def user_api(method, sub, payload, handler):
|
||||
if method == "POST" and sub == "/login":
|
||||
username = str(payload.get("username") or "").strip()
|
||||
password = str(payload.get("password") or "")
|
||||
# admin accounts skip the human check (admin panel login has no Turnstile widget)
|
||||
# admin accounts skip the human check (admin panel login has no captcha widget)
|
||||
role, _disabled = _user_attr(username)
|
||||
if role != "admin" and not verify_turnstile(str(payload.get("cf_token") or "")):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请完成验证后重试"}
|
||||
if role != "admin" and not verify_captcha(payload):
|
||||
return 403, {"code": 403, "message": "人机验证失败,请刷新验证码后重试"}
|
||||
conn = _db()
|
||||
row = conn.execute("SELECT salt, pw_hash FROM users WHERE username=?", (username,)).fetchone()
|
||||
conn.close()
|
||||
@@ -1591,6 +1884,21 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/feedback/captcha":
|
||||
status, body = feedback_api("GET", {}, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/hub/announcements":
|
||||
qs = parse.parse_qs(parsed.query or "")
|
||||
try:
|
||||
limit = int((qs.get("limit") or ["20"])[0] or 20)
|
||||
except ValueError:
|
||||
limit = 20
|
||||
status, body = hub_announcements(limit)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
if parsed.path == "/reco":
|
||||
items = [x for x in _load_reco() if x.get("enabled")][:24]
|
||||
body = json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8")
|
||||
@@ -1677,6 +1985,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
# ---- 代理/VPN 判定(/ip-check?ip= 浏览器侧自己的公网 IP)----
|
||||
if parsed.path == "/ip-check":
|
||||
ipq = (parse.parse_qs(parsed.query or "").get("ip") or [""])[0].strip()
|
||||
if not ipq or not _ip_valid(ipq):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "缺少或非法 ip 参数"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
data = _ip_check(ipq)
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
|
||||
self._reply(404, b"not found")
|
||||
|
||||
# ---------- POST ----------
|
||||
@@ -2465,6 +2783,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/speed":
|
||||
self._handle_speed_post()
|
||||
return
|
||||
if parsed.path == "/feedback":
|
||||
payload = self._read_payload()
|
||||
status, body = feedback_api("POST", payload, self)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/hub/report":
|
||||
payload = self._read_payload() or {}
|
||||
status, body = hub_report(payload)
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path.startswith("/admin"):
|
||||
self._handle_admin("POST")
|
||||
return
|
||||
@@ -3476,6 +3804,47 @@ def _ip_info(ip):
|
||||
return info
|
||||
|
||||
|
||||
# ---------- 代理/VPN 判定(proxycheck.io 免 key,内存缓存) ----------
|
||||
_IPCHECK_CACHE = {}
|
||||
|
||||
|
||||
def _ip_check(ip):
|
||||
"""出口 IP 代理/VPN/数据中心判定:proxycheck.io + 内存缓存;内网地址不外查。
|
||||
返回 {ip, lan, proxy(bool|None), type, provider, hostname, asn};
|
||||
查询失败 proxy=None(前端降级为“无法判定”)。"""
|
||||
ip = (ip or "").strip()
|
||||
if not ip or not _ip_valid(ip):
|
||||
return None
|
||||
import ipaddress
|
||||
addr = ipaddress.ip_address(ip)
|
||||
lan = bool(addr.is_private or addr.is_loopback or addr.is_link_local)
|
||||
cached = _IPCHECK_CACHE.get(ip)
|
||||
if cached is not None:
|
||||
return cached
|
||||
out = {"ip": ip, "lan": lan, "proxy": None, "type": "", "provider": "", "hostname": "", "asn": ""}
|
||||
if not lan:
|
||||
try:
|
||||
url = "http://proxycheck.io/v2/%s?vpn=1&asn=1" % ip
|
||||
with request.urlopen(url, timeout=8) as resp:
|
||||
d = json.loads(resp.read().decode("utf-8", "ignore"))
|
||||
if d.get("status") == "ok":
|
||||
rec = d.get(ip) or {}
|
||||
out = {
|
||||
"ip": ip, "lan": False,
|
||||
"proxy": str(rec.get("proxy") or "").lower() == "yes",
|
||||
"type": rec.get("type") or "",
|
||||
"provider": rec.get("provider") or rec.get("organisation") or "",
|
||||
"hostname": rec.get("hostname") or "",
|
||||
"asn": rec.get("asn") or "",
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
if len(_IPCHECK_CACHE) > 1500:
|
||||
_IPCHECK_CACHE.clear()
|
||||
_IPCHECK_CACHE[ip] = out
|
||||
return out
|
||||
|
||||
|
||||
def _tr_chunks(text: str, limit: int = 1200):
|
||||
"""按行/长度切块,保留换行结构;返回 [(块文本, 块后是否接换行)]"""
|
||||
lines = text.split("\n")
|
||||
|
||||
Reference in new issue
Block a user