feat(fileserver): 新增内网文件服务器服务与管理页面
新增 FastAPI 文件服务器核心模块(配置、鉴权、存储、心跳上报),新增 HTTP 路由接口(健康检查、文件上传/下载/删除、管理登录/密码修改/统计),新增 Vue3 管理页面源码;新增 MySQL 元数据存储支持,新增 PyMySQL 依赖;新增 .gitignore 忽略 IDE 与备份文件;新增文件服务器工具脚本;删除旧的 build/ 脚本与 exe 构建产物,优化 Electron 平台登录逻辑为纯接口模式,新增平台账号环境变量注入,优化试用期异常检查逻辑,拆分服务岗转正流程为独立脚本。
This commit is contained in:
@@ -374,21 +374,13 @@ def _init_db() -> None:
|
||||
|
||||
|
||||
def _seed() -> None:
|
||||
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
|
||||
"""首次启动写入默认管理员(puddy)。
|
||||
|
||||
不再种子 demo 普通账号(alice/bob 曾带弱口令入生产库),普通账号一律由管理员建号。
|
||||
曾有的 seal_check 占位插件种子已移除(demo 遗留,会随服务重启复活,对真实插件清单造成干扰)。
|
||||
"""
|
||||
config.PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO plugins(id, name, latest_version) VALUES (%s, %s, %s)",
|
||||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (%s, %s, %s, %s)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,密码随机生成并记入日志(不再硬编码 123456,P0 安全债)。
|
||||
# 已有库不重跑本种子(INSERT IGNORE 幂等);生产环境建号后应立即改密。
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
@@ -399,9 +391,6 @@ def _seed() -> None:
|
||||
"VALUES (%s, %s, %s, %s, %s)", (_acc, _hex, _salt, 1, _dept))
|
||||
_LOGGER.warning("首次引导:初始管理员 %s 初始密码为 %s(请立即登录修改)", _acc, _pwd)
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
pkg.write_bytes(b"# placeholder controlplane package v1.0.0\n")
|
||||
|
||||
|
||||
def _audit(account: str, action: str, target: str = "", detail: str = "") -> None:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -236,10 +236,11 @@ npm run pack # → dist-app/setup-37du-shell-<version>.exe(NSIS 静
|
||||
- 每个人的 HR/OA 账号密码由本人在「个人中心 → 平台账号」填写(AES-256-GCM 本机加密,
|
||||
存 `%LOCALAPPDATA%\37duAutomation\platform-creds\creds.json`),顶栏不再显示设备级平台徽章
|
||||
- 平台会话 cookies 按账号隔离:`.sessions/<账号>/hr_cookies.json`、`oa_cookies.json`;
|
||||
Python 共享模块(hr_login / oa_login / seal_data_export / roster_export_api / org_export /
|
||||
Python 共享模块(hr_login_api / oa_login_api / seal_data_export / roster_export_api / org_export /
|
||||
core.auth)通过 `PLATFORM_ACCOUNT` 环境变量解析各自的会话目录,未设置时沿用共享目录(兼容旧逻辑)
|
||||
- 登录/登出:壳端 `platform-auth` 拉起 Python 登录子进程时注入 `PLATFORM_ACCOUNT`
|
||||
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env)
|
||||
与账号的 `hr_login_username/password`(个人账号密码优先,未配置回退共享 .env);
|
||||
登录为纯 requests 接口版(HR 含滑块接口破解),全程无浏览器
|
||||
- 插件执行:runner 子进程同样注入 `PLATFORM_ACCOUNT`,插件内数据导出按当前登录账号的身份执行;
|
||||
同平台并发闸键改为(账号, 平台)
|
||||
- 接口:`GET /api/meta` 平台在线按当前账号返回;`GET /api/platforms/status` 返回当前账号
|
||||
|
||||
@@ -63,8 +63,10 @@ if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on("second-instance", () => {
|
||||
if (mainWindow) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
// 收托盘走的是 hide():隐藏窗口不是 minimized,focus() 也唤不回,必须先 show()
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 平台登录态(HR/OA):真实登录/登出/在线校验。
|
||||
// 保持 Python 子进程执行登录自动化(壳内置 python/webhost/backend/shared 下的
|
||||
// hr_login、oa_login,DrissionPage 滑块;自包含 vendor,不依赖老 webhost 底座),
|
||||
// Node 壳只负责拉起子进程与解析结果。
|
||||
// 保持 Python 子进程执行登录(壳内置 python/webhost/backend/shared 下的
|
||||
// hr_login_api、oa_login_api,纯 requests 接口登录无浏览器;自包含 vendor,
|
||||
// 不依赖老 webhost 底座),Node 壳只负责拉起子进程与解析结果。
|
||||
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
|
||||
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
|
||||
"use strict";
|
||||
@@ -182,7 +182,7 @@ async function isOnline(pid, account) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// 真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
// 真实登录:cookies 有效则复用(不弹浏览器),失效则纯接口登录(无浏览器)。
|
||||
// account:当前登录账号;其个人 HR/OA 账号密码通过环境变量注入登录子进程。
|
||||
async function login(pid, account) {
|
||||
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
|
||||
@@ -199,8 +199,8 @@ async function login(pid, account) {
|
||||
try {
|
||||
const snippet =
|
||||
pid === "hr"
|
||||
? `from webhost.backend.shared import hr_login; import json; print(json.dumps(hr_login.main({"force": False}), ensure_ascii=False))`
|
||||
: `from webhost.backend.shared import oa_login; import json; print(json.dumps(oa_login.main(force=False), ensure_ascii=False))`;
|
||||
? `from webhost.backend.shared import hr_login_api; import json; print(json.dumps(hr_login_api.main({"force": False}), ensure_ascii=False))`
|
||||
: `from webhost.backend.shared import oa_login_api; import json; print(json.dumps(oa_login_api.main(force=False), ensure_ascii=False))`;
|
||||
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
|
||||
const result = extractJson(out) || {};
|
||||
const ok = !!result.success;
|
||||
|
||||
@@ -94,6 +94,9 @@ function pluginSchema(pluginId) {
|
||||
uses_month: !!manifest.uses_month,
|
||||
ui: !!manifest.ui,
|
||||
platform: manifest.platform || "", // hr / oa / ""(前端平台徽章 + 运行并发闸按(账号,平台)隔离)
|
||||
platforms: Array.isArray(manifest.platforms) && manifest.platforms.length
|
||||
? manifest.platforms // 插件声明的全部平台依赖(运行前登录态预检按此逐个检查)
|
||||
: manifest.platform ? [manifest.platform] : [], // 缺省回退单 platform 字段
|
||||
min_runtime_version: manifest.minRuntimeVersion || "", // 版本兼容校验声明(安装时强校验,此处透传前端展示)
|
||||
capabilities: manifest.capabilities || [],
|
||||
permissions: manifest.permissions || {},
|
||||
|
||||
@@ -14,6 +14,7 @@ const scheduler = require("./scheduler");
|
||||
const licensing = require("./licensing");
|
||||
const runHistory = require("./run-history");
|
||||
const platformAuth = require("./platform-auth");
|
||||
const platformCreds = require("./platform-creds");
|
||||
const { HUB } = require("./hub");
|
||||
const { makeLogger } = require("./logger");
|
||||
|
||||
@@ -67,26 +68,33 @@ function nsKey(account, platform) {
|
||||
return `${account || "anon"}:${platform || "local"}`;
|
||||
}
|
||||
|
||||
// 平台登录态预检(HR/OA):插件执行前检测该账号的平台登录态,
|
||||
// 失效时自动拉起自动登录(platform-auth.login,Python 子进程滑块自动化;
|
||||
// cookies 实际有效时不会弹浏览器)。登录成功继续执行,失败则本次运行报错,
|
||||
// 提示用户去个人中心手动登录(手动登录入口保留,不冲突)。
|
||||
// 在(账号, 平台)命名空间锁内调用,天然避免并发双开登录浏览器。
|
||||
// 平台登录态预检(HR/OA):点击执行后、拉起插件前,按插件声明(plugin.json 的 platforms
|
||||
// 数组,缺省回退 platform 单字段)逐个校验登录态(真实轻量 API 探测),失效时自动调
|
||||
// platform-auth.login 纯接口补登(无浏览器,凭据来自平台账号配置)。任一平台补登失败
|
||||
// 则本次运行直接报错中止,不进入插件执行。在(账号, 平台)命名空间锁内调用,天然避免
|
||||
// 并发双开登录。
|
||||
const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" };
|
||||
function pluginPlatforms(plugin) {
|
||||
if (Array.isArray(plugin.platforms) && plugin.platforms.length) {
|
||||
return plugin.platforms.filter((p) => PLATFORM_LABELS[p]);
|
||||
}
|
||||
const pid = plugin.platform;
|
||||
return pid && PLATFORM_LABELS[pid] ? [pid] : [];
|
||||
}
|
||||
async function ensurePlatformSession(plugin, runId, account) {
|
||||
const pid = plugin.platform;
|
||||
if (!pid || !PLATFORM_LABELS[pid]) return; // 无平台要求(或未知平台)直接执行
|
||||
if (await platformAuth.isOnline(pid, account)) return; // 登录态有效,直接执行
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
|
||||
const label = PLATFORM_LABELS[pid];
|
||||
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…(如需人工介入请观察弹出的浏览器窗口)`);
|
||||
const r = await platformAuth.login(pid, account);
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
|
||||
if (!r || !r.online) {
|
||||
const msg = (r && r.message) || "登录未生效";
|
||||
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」手动登录后重试`);
|
||||
for (const pid of pluginPlatforms(plugin)) {
|
||||
if (await platformAuth.isOnline(pid, account)) continue; // 登录态有效,无需处理
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
|
||||
const label = PLATFORM_LABELS[pid];
|
||||
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…`);
|
||||
const r = await platformAuth.login(pid, account);
|
||||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
|
||||
if (!r || !r.online) {
|
||||
const msg = (r && r.message) || "登录未生效";
|
||||
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」检查账号密码配置后重试`);
|
||||
}
|
||||
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
|
||||
}
|
||||
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
|
||||
}
|
||||
|
||||
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
|
||||
@@ -287,6 +295,10 @@ function startChild(plugin, fields, runId, account) {
|
||||
PYTHONIOENCODING: "utf-8",
|
||||
PYTHONUTF8: "1",
|
||||
PLATFORM_ACCOUNT: account || "",
|
||||
// 平台凭据:供插件内登录态失效时自动补登录(未配置的平台/账号不注入,
|
||||
// 此时登录模块回退读共享 .env)
|
||||
...(platformCreds.envFor(account, "hr") || {}),
|
||||
...(platformCreds.envFor(account, "oa") || {}),
|
||||
// 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害)
|
||||
PLUGINS_ROOT: config.pluginRoot(),
|
||||
},
|
||||
|
||||
@@ -693,7 +693,8 @@ async function refreshShellStatus() {
|
||||
shellUpdate.value = s
|
||||
const st = s.dl?.status || ''
|
||||
if (lastDlStatus === 'downloading' && st === 'downloaded') {
|
||||
updDlg.value = false // 弹窗开着时自动收起,顶部提示条转为「重启更新」
|
||||
// 内网直链下载很快(80MB 秒下),延迟收窗让人看清 100% 完成态,再转顶部「重启更新」条
|
||||
setTimeout(() => { updDlg.value = false }, 1500)
|
||||
ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`)
|
||||
log('INFO', `客户端新版本 v${s.new} 已就绪,可重启更新`)
|
||||
} else if (lastDlStatus === 'downloading' && st === 'failed') {
|
||||
@@ -701,7 +702,7 @@ async function refreshShellStatus() {
|
||||
}
|
||||
lastDlStatus = st
|
||||
} catch (_) {}
|
||||
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 1200 : 15000)
|
||||
shellPollTimer = setTimeout(refreshShellStatus, updDl.value.status === 'downloading' ? 400 : 15000)
|
||||
}
|
||||
function startShellPoll() {
|
||||
if (shellPollTimer) return
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "37du-electron-shell",
|
||||
"productName": "37du 自动化工作台",
|
||||
"version": "1.0.6",
|
||||
"version": "1.0.9",
|
||||
"description": "37du 执行机 Node/Electron 客户端(替代 Python webhost 底座,插件保持 Python 子进程执行)",
|
||||
"main": "electron/main.js",
|
||||
"private": true,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则纯接口登录,无浏览器)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
@@ -16,8 +16,8 @@ import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import hr_login_api as _hr
|
||||
from webhost.backend.shared import oa_login_api as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
@@ -62,7 +62,7 @@ def is_online(pid: str) -> bool:
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则纯接口登录(无浏览器)。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login_api.py
|
||||
@Description: HR 纯接口登录(无浏览器版),webhost 宿主壳平台登录模块。
|
||||
与 webhost/backend/shared/hr_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json
|
||||
(PLATFORM_ACCOUNT 存在时按账号隔离到 .sessions/<账号>/);
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录(含滑块验证),不打开浏览器、无拖拽拟人。
|
||||
|
||||
登录链路(从登录页前端 JS 逆向 + 2025-10 实测验证):
|
||||
1. GET /RedseaPlatform/ 建立 Session 基础 cookie(routeEhr/JSESSIONID);
|
||||
2. GET /RedseaPlatform/captcha/get/verification/image.mob 取滑块图,返回
|
||||
result = {shadeImage(带缺口背景 jpg b64), originImage(原始背景 jpg b64),
|
||||
cutoutImage(55x55 拼图块 png b64), y(拼图块 top), x(恒 0)};
|
||||
前端 CSS 固定 340x171 容器、background 原尺寸绘制 => 浏览器只显示原图
|
||||
左上角 min(w,340) x min(h,171) 的窗口,坐标系 1:1,匹配前需先裁切到该窗口;
|
||||
3. 定位缺口 x:
|
||||
a) 首选 diff 法:|shadeImage - originImage| 最大连通域左边界 = 缺口 x
|
||||
(两图同源成对,diff 定位最准,且天然免疫整图变换);
|
||||
b) 兜底模板匹配法(与 hr_login.py 浏览器截图版同源算法);
|
||||
两者互验:diff 可信用 diff,diff 缺失用模板,分歧过大判定本图不可信换图重取;
|
||||
4. POST /RedseaPlatform/captcha/check/verification/result.mob?x=&y= 校验滑块(返回 true/false);
|
||||
5. POST /RedseaPlatform/j_red_security_check/PW 提交登录:
|
||||
form: MENU_TYPE=classic & sysCode=RedseaP & j_username & j_password=<AES密文> & x & y
|
||||
header: Csrf-Token: RP(前端写死常量);
|
||||
密码加密:AES-128-ECB + PKCS7,key='ps_uer_!@#BGYUJN'(前端硬编码),输出 base64;
|
||||
成功判定:state != "0";失败 state == "0" 且 meg 为错误信息;
|
||||
6. GET getCurUserInfo 校验会话有效后,cookies 落盘 hr_cookies.json。
|
||||
|
||||
配置(与 hr_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
hr_login_username=用户名
|
||||
hr_login_password=密码
|
||||
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
|
||||
全局变量(影刀环境可用,webhost 宿主下静默跳过):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖:
|
||||
pip install requests python-dotenv opencv-python-headless numpy pycryptodome
|
||||
|
||||
入口:
|
||||
main(args) 平台登录调用入口(platform-auth.js / core.auth),args 传
|
||||
{"force": true|false},返回 JSON 安全 dict
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
import base64
|
||||
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 hr_login.py 统一,按账号隔离) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://hr.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/RedseaPlatform/'
|
||||
CAPTCHA_GET_URL = BASE_URL + '/RedseaPlatform/captcha/get/verification/image.mob'
|
||||
CAPTCHA_CHECK_URL = BASE_URL + '/RedseaPlatform/captcha/check/verification/result.mob'
|
||||
LOGIN_POST_URL = BASE_URL + '/RedseaPlatform/j_red_security_check/PW'
|
||||
GET_CUR_USER_INFO_URL = BASE_URL + '/RedseaPlatform/PtUsers.mc?method=getCurUserInfo'
|
||||
|
||||
# 前端登录页硬编码:AES 密钥与 CSRF 常量
|
||||
AES_KEY = b'ps_uer_!@#BGYUJN'
|
||||
CSRF_TOKEN = 'RP'
|
||||
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# 浏览器可见窗口(登录页 CSS:.imgBg 340x171 固定、background 原尺寸绘制)
|
||||
VIEW_W = 340
|
||||
VIEW_H = 171
|
||||
|
||||
RETRY_MAX = 5 # 单轮滑块重试次数(与浏览器版一致)
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 hr_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 hr_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(与 hr_login.py 同款) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(前端 pubAesEncrypt 等价实现) ==================
|
||||
def aes_encrypt_password(password):
|
||||
"""AES-128-ECB + PKCS7,key 前端硬编码,输出 base64(与 CryptoJS encrypted.toString() 一致)。"""
|
||||
cipher = AES.new(AES_KEY, AES.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 16))).decode('ascii')
|
||||
|
||||
|
||||
# ================== 滑块图获取与裁切 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(routeEhr/JSESSIONID),验证码/登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Referer": LOGIN_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def _b64_to_img(b64str, flag):
|
||||
"""base64 -> cv2 图像(失败返回 None)。"""
|
||||
if not b64str:
|
||||
return None
|
||||
try:
|
||||
buf = base64.b64decode(b64str)
|
||||
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _crop_view(img):
|
||||
"""裁切到浏览器可见窗口(左上角 min(w,340) x min(h,171)),坐标系与浏览器 1:1。"""
|
||||
if img is None:
|
||||
return None
|
||||
h, w = img.shape[:2]
|
||||
return img[:min(h, VIEW_H), :min(w, VIEW_W)]
|
||||
|
||||
|
||||
def get_captcha(session):
|
||||
"""取滑块图,返回 dict(shade, origin, cutout, y);y 为拼图块 top(服务端给定)。"""
|
||||
resp = session.get(CAPTCHA_GET_URL, timeout=TIMEOUT)
|
||||
data = resp.json()
|
||||
res = data.get("result") or {}
|
||||
shade = _crop_view(_b64_to_img(res.get("shadeImage"), cv2.IMREAD_COLOR))
|
||||
origin = _crop_view(_b64_to_img(res.get("originImage"), cv2.IMREAD_COLOR))
|
||||
cutout = _b64_to_img(res.get("cutoutImage"), cv2.IMREAD_UNCHANGED)
|
||||
y = int(res.get("y") or 0)
|
||||
return {"shade": shade, "origin": origin, "cutout": cutout, "y": y}
|
||||
|
||||
|
||||
# ================== 缺口定位 ==================
|
||||
def locate_by_diff(shade, origin):
|
||||
"""diff 法:shade/origin 同源成对,逐像素差异的最大连通域左边界 = 缺口 x。
|
||||
返回 (x, 可信度说明);不可信返回 (None, 原因)。"""
|
||||
if shade is None or origin is None or shade.shape != origin.shape:
|
||||
return None, "图片缺失或尺寸不一致"
|
||||
diff = cv2.absdiff(shade, origin).max(axis=2)
|
||||
mask = (diff > 30).astype(np.uint8) * 255
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
||||
n, _, stats, _ = cv2.connectedComponentsWithStats(mask)
|
||||
if n <= 1:
|
||||
return None, "无差异区域"
|
||||
best = max(range(1, n), key=lambda i: stats[i, cv2.CC_STAT_AREA])
|
||||
area = int(stats[best, cv2.CC_STAT_AREA])
|
||||
x = int(stats[best, cv2.CC_STAT_LEFT])
|
||||
# 缺口约 55x55(面积 ~3000),过大/过小视为 jpg 噪声或异常
|
||||
if area < 300 or area > 12000:
|
||||
return None, f"差异区域面积异常({area})"
|
||||
return x, f"diff(area={area})"
|
||||
|
||||
|
||||
def match_slider_dual(bg_img, slider_color):
|
||||
"""模板匹配滑块缺口,返回物理距离 px。
|
||||
算法与 hr_login.py 浏览器截图版同源(边缘 Canny + TM_CCOEFF_NORMED + 白区加权)。"""
|
||||
if bg_img is None or slider_color is None:
|
||||
return None
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset = 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, _ = x_min, np.min(ys)
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
|
||||
return None
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_loc = scored[0][2]
|
||||
else:
|
||||
best_loc = candidates[0][1]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
def solve_distance(cap):
|
||||
"""定位缺口并输出应提交的 x(= 滑块从 0 到缺口的距离,即缺口左边界 - 拼图透明边)。
|
||||
返回 (x, 说明);本图不可信返回 (None, 原因)。
|
||||
|
||||
几何说明(与浏览器画面一致):
|
||||
- 原图宽 >= 340:浏览器只显示左上 340x171 裁切窗口;
|
||||
- 原图宽 < 340:.imgBg 的 background 默认 repeat 会把原图复制拼接到右侧,
|
||||
画面上缺口可能出现副本(x_g 与 x_g+原图宽),但服务端记录的是原图缺口
|
||||
坐标 x_g,提交 x_g 即可通过;
|
||||
因此匹配始终在原图(裁切后)上进行——拼接成画面等价图反而会让 diff 出双峰
|
||||
(副本也带缺口)——越界过滤上限用实际图宽。
|
||||
"""
|
||||
shade = cap["shade"]
|
||||
cutout = cap["cutout"]
|
||||
s_w = cutout.shape[1] if cutout is not None else 55
|
||||
view_w = shade.shape[1] if shade is not None else VIEW_W
|
||||
x_diff, info = locate_by_diff(cap["shade"], cap["origin"])
|
||||
x_tpl = match_slider_dual(cap["shade"], cutout)
|
||||
print(f" 缺口定位:{info} diff_x={x_diff} tpl_x={x_tpl}")
|
||||
|
||||
x, how = None, "无法定位"
|
||||
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
|
||||
x, how = x_diff, "diff+tpl 一致"
|
||||
elif x_diff is not None:
|
||||
x, how = x_diff, "仅 diff(与模板分歧)"
|
||||
elif x_tpl is not None:
|
||||
x, how = x_tpl, "仅模板"
|
||||
if x is None:
|
||||
return None, how
|
||||
# 合理性校验:缺口不会贴最左/最右(贴边缺口可能是平铺坐标映射产物,直接换图)
|
||||
if x <= s_w or x > view_w - s_w:
|
||||
return None, f"缺口位置越界({x}, 图宽{view_w})"
|
||||
return x, how
|
||||
|
||||
|
||||
# ================== 滑块校验与登录提交 ==================
|
||||
def check_slider(session, x, y):
|
||||
"""提交滑块校验,返回 True/False。"""
|
||||
resp = session.post(CAPTCHA_CHECK_URL, params={"x": int(round(x)), "y": int(y)}, timeout=TIMEOUT)
|
||||
try:
|
||||
return bool(resp.json())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def submit_login(session, username, password, x, y):
|
||||
"""提交登录,返回 (ok, message)。"""
|
||||
form = {
|
||||
"MENU_TYPE": "classic",
|
||||
"sysCode": "RedseaP",
|
||||
"j_username": username,
|
||||
"j_password": aes_encrypt_password(password),
|
||||
"x": int(round(x)),
|
||||
"y": int(y),
|
||||
}
|
||||
headers = {"Csrf-Token": CSRF_TOKEN}
|
||||
resp = session.post(LOGIN_POST_URL, data=form, headers=headers, timeout=TIMEOUT)
|
||||
try:
|
||||
result = resp.json()
|
||||
except Exception:
|
||||
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
|
||||
if result.get("state") == "0":
|
||||
return False, str(result.get("meg") or "登录失败")
|
||||
return True, "登录成功"
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:滑块校验(带重试)+ 提交登录。成功返回 True。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
for attempt in range(RETRY_MAX):
|
||||
print(f"--- 第 {attempt + 1} 次尝试验证 ---")
|
||||
try:
|
||||
cap = get_captcha(session)
|
||||
except Exception as e:
|
||||
print(f"取验证码图异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
shade = cap["shade"]
|
||||
y = cap["y"]
|
||||
# y 用实际图高校验(裁切窗口高 = min(图高, 171),小图场景更严谨)
|
||||
if shade is None or not (0 <= y <= shade.shape[0] - 55):
|
||||
print(f"验证码图异常(shade={None if shade is None else shade.shape}, y={y})")
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
x, info = solve_distance(cap)
|
||||
if x is None:
|
||||
time.sleep(random.uniform(0.3, 0.8))
|
||||
continue
|
||||
|
||||
print(f" 提交滑块校验 x={x} y={y}({info})")
|
||||
if check_slider(session, x, y):
|
||||
print(" 滑块校验通过")
|
||||
ok, msg = submit_login(session, username, password, x, y)
|
||||
if ok:
|
||||
save_session_cookies(session)
|
||||
return True
|
||||
print(f"登录失败:{msg}")
|
||||
return False # 账号密码类错误,重试无意义
|
||||
else:
|
||||
print(" 滑块校验未通过,换图重试")
|
||||
time.sleep(random.uniform(0.5, 1.2))
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主入口(与 hr_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次会话有效性,确保落盘的 cookies 可用
|
||||
if _is_hr_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过或接口异常)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 调用入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
平台登录调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,326 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login_api.py
|
||||
@Description: OA 纯接口登录(无浏览器版),webhost 宿主壳平台登录模块。
|
||||
与 webhost/backend/shared/oa_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json
|
||||
(PLATFORM_ACCOUNT 存在时按账号隔离到 .sessions/<账号>/);
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 配置读取一致(共享 .env 的 oa_login_username / oa_login_password);
|
||||
- 对外入口 main(force) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录,不打开浏览器。
|
||||
|
||||
登录链路(蓝凌 EKP security.js 逆向 + 2026-10 实测验证):
|
||||
1. GET /login.jsp 建立 Session 基础 cookie(SESSION/sl-session);
|
||||
2. GET /resource/js/session.jsp?_=时间戳 服务端按会话下发密钥串:
|
||||
window.getSessionId = function(){ return "<36位UUID>"; }
|
||||
同一会话内固定,登录 POST 必须与本次取密钥同会话;
|
||||
3. 密码加密(复刻 security.js desEncrypt 的 des 分支,浏览器默认走 sm2 分支,
|
||||
但密文前缀带算法标记、服务端按标记选算法解密,des 同样受支持):
|
||||
a) 密钥串不足 16 位补 "abcdefghijklmnopqrstuvwxyz",再 toUpperCase;
|
||||
b) key = 前 8 字符 toHexString、iv = 第 8~16 字符 toHexString
|
||||
(toHexString = 逐字符 charCode 转 16 进制拼接,ASCII 即 .encode().hex());
|
||||
c) DES-CBC + PKCS7 加密密码,输出 base64;
|
||||
d) j_password = 标记前缀 "\\u4445\\u5320\\u4d45" + base64 密文;
|
||||
4. POST /j_acegi_security_check form: j_username & j_password & j_redirectto(空)
|
||||
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
|
||||
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
|
||||
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
|
||||
|
||||
配置(与 oa_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)OA 会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(影刀环境可用,webhost 宿主下静默跳过):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖:
|
||||
pip install requests python-dotenv pycryptodome
|
||||
|
||||
入口:
|
||||
main(force) 平台登录调用入口(platform-auth.js / core.auth),force 传 True/False,
|
||||
返回 JSON 安全 dict
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import base64
|
||||
|
||||
import requests
|
||||
from Crypto.Cipher import DES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 oa_login.py 统一,按账号隔离) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/login.jsp'
|
||||
SESSION_KEY_URL = BASE_URL + '/resource/js/session.jsp'
|
||||
LOGIN_POST_URL = BASE_URL + '/j_acegi_security_check'
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = BASE_URL + "/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# security.js 密码加密常量(逆向自 /resource/js/security.js,Dean Edwards packer 混淆已还原)
|
||||
DES_MARKER = "\u4445\u5320\u4d45" # des 分支密文标记前缀(服务端按标记选算法)
|
||||
DES_PADDING = "abcdefghijklmnopqrstuvwxyz" # 密钥串不足 16 位时的补齐串
|
||||
SESSION_KEY_RE = re.compile(
|
||||
r'getSessionId\s*=\s*function\s*\(\s*\)\s*\{\s*return\s*"([^"]*)"')
|
||||
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 oa_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 oa_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== 会话校验(与 oa_login.py 同款逻辑) ==================
|
||||
def _is_todo_count_json(resp):
|
||||
"""sumTodoCount 响应判定:200 且返回 JSON 视为登录态有效。"""
|
||||
try:
|
||||
return (resp.status_code == 200 and bool(resp.text)
|
||||
and resp.text.lstrip().startswith(("{", "[")))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
与 oa_login.py 及业务脚本使用同一套接口与校验逻辑。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_session_alive(session):
|
||||
"""用当前登录会话直接校验(登录后、落盘前使用)。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"会话校验异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(复刻 security.js desEncrypt 的 des 分支) ==================
|
||||
def to_hex_str(text):
|
||||
"""复刻 security.js 的 toHexString:逐字符 charCode 转 16 进制(小写、无补零)拼接。"""
|
||||
return ''.join(format(ord(ch), 'x') for ch in text)
|
||||
|
||||
|
||||
def fetch_session_key(session):
|
||||
"""GET session.jsp 取服务端按会话下发的密钥串(同会话固定)。"""
|
||||
url = f"{SESSION_KEY_URL}?_={int(time.time() * 1000)}"
|
||||
resp = session.get(url, timeout=TIMEOUT)
|
||||
m = SESSION_KEY_RE.search(resp.text)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def des_encrypt_password(session, password):
|
||||
"""返回可直接提交的 j_password:标记前缀 + DES-CBC-PKCS7 base64 密文。
|
||||
密钥派生:密钥串不足 16 位补齐 -> 大写 -> key/iv 各取 8 字符 toHexString。"""
|
||||
sid = fetch_session_key(session)
|
||||
if not sid:
|
||||
raise RuntimeError("session.jsp 未返回 getSessionId 密钥串")
|
||||
b = sid
|
||||
if len(b) < 16:
|
||||
b += DES_PADDING
|
||||
b = b.upper()
|
||||
key = bytes.fromhex(to_hex_str(b[:8]))
|
||||
iv = bytes.fromhex(to_hex_str(b[8:16]))
|
||||
cipher = DES.new(key, DES.MODE_CBC, iv)
|
||||
ct = base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 8))).decode('ascii')
|
||||
return DES_MARKER + ct
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(SESSION/sl-session),取密钥与登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:取密钥 -> DES 加密 -> 表单提交 -> 会话校验。返回 (ok, message)。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
j_password = des_encrypt_password(session, password)
|
||||
except Exception as e:
|
||||
print(f"获取会话密钥/加密异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = session.post(
|
||||
LOGIN_POST_URL,
|
||||
data={"j_username": username, "j_password": j_password, "j_redirectto": ""},
|
||||
headers={"Referer": LOGIN_URL, "Origin": BASE_URL},
|
||||
timeout=TIMEOUT, allow_redirects=True)
|
||||
except Exception as e:
|
||||
print(f"提交登录异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
final_url = str(resp.url)
|
||||
if "login.jsp" in final_url:
|
||||
# Acegi 拒绝(凭据错误/解密失败)会重定向回登录页,重试无意义
|
||||
return False, f"登录被拒绝(用户名或密码错误?):{final_url}"
|
||||
if check_session_alive(session):
|
||||
save_session_cookies(session)
|
||||
return True, "登录成功"
|
||||
print(f"登录后会话校验未通过,最终URL:{final_url}")
|
||||
time.sleep(1)
|
||||
return False, "登录失败(重试耗尽或接口异常)"
|
||||
|
||||
|
||||
# ================== 登录主入口(与 oa_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok, msg = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次落盘 cookies 可用性,确保业务脚本拿到的登录态真实有效
|
||||
if _is_oa_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "message": msg, "relogin": False}
|
||||
|
||||
|
||||
# ================== 调用入口(与 oa_login.py 契约一致) ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
平台登录调用入口。
|
||||
force: bool 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
@@ -24,7 +24,9 @@
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
运行前置:无需预先登录——无共享登录态或登录态失效时,宿主(webhost)环境会
|
||||
自动调用内置接口版登录(hr_login_api,无浏览器)补登录;影刀环境需先运行
|
||||
「37duHR登录(接口版)」指令。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@@ -160,12 +162,26 @@ def _load_shared_hr_cookies():
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _force_relogin():
|
||||
"""登录态缺失/失效时自动补登录:调用宿主内置接口版登录(无浏览器,凭据来自
|
||||
执行机注入的环境变量或共享 .env)。影刀等无宿主环境时抛出带指引的 RuntimeError。"""
|
||||
try:
|
||||
from webhost.backend.shared import hr_login_api
|
||||
except ImportError:
|
||||
raise RuntimeError(
|
||||
"HR 登录态缺失或已失效,且当前环境无内置接口登录模块。\n"
|
||||
"请先调用「37duHR登录(接口版)」指令完成登录,再运行本模块")
|
||||
result = hr_login_api.ensure_login(force=True)
|
||||
if not result.get("success"):
|
||||
raise RuntimeError(f"HR 自动补登录失败:{result.get('message')}")
|
||||
logger.info("HR 自动补登录成功")
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
_force_relogin()
|
||||
return True
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
@@ -213,8 +229,8 @@ def fetch_cur_user_info(session):
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
"""登录态失效后:强制补登录 → 重建会话 → 重新获取 userId。"""
|
||||
_force_relogin()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
@@ -361,9 +377,14 @@ def export_seal_data(month: str = None) -> List[dict]:
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量);缓存 cookies 失效时自动补登录重试
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
try:
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
except HRSessionExpiredError:
|
||||
_force_relogin()
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Build portable Python + environment package (python-env-<version>.zip)
|
||||
# Build portable Python + environment package (python-env-<version>.zip)
|
||||
# ============================================================================
|
||||
# Purpose: give the packaged Electron client a self-contained Python runtime so
|
||||
# plugins and platform-login no longer depend on an external Python install.
|
||||
@@ -41,7 +41,7 @@ $PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.ed
|
||||
|
||||
# All dependencies (top-level + key transitive), pinned to .venv-validated versions
|
||||
$Pinned = @(
|
||||
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1",
|
||||
"requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1", "pycryptodome==3.24.0",
|
||||
"pandas==3.0.5", "numpy==2.3.5", "openpyxl==3.1.5",
|
||||
"python-dateutil==2.9.0.post0", "tzdata==2026.3", "et-xmlfile",
|
||||
"websocket-client==1.9.0",
|
||||
@@ -191,7 +191,7 @@ Get-ChildItem -Path (Join-Path $Wb "shared") -Filter "*.py" | ForEach-Object {
|
||||
# ---------- 4. smoke test ----------
|
||||
Write-Host "=== smoke test ===" -ForegroundColor Cyan
|
||||
& $PyExe -c "import sys; print(' python:', sys.version.split()[0])" | Out-Host
|
||||
& $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography; print(' core deps ok')" | Out-Host
|
||||
& $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography,Crypto,cv2; print(' core deps ok')" | Out-Host
|
||||
if ($LASTEXITCODE -ne 0) { throw "core deps import failed" }
|
||||
& $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host
|
||||
& $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# fileserver(37du 内网文件服务器)管理页 + 服务
|
||||
|
||||
文件服务器(FastAPI,端口 8802):存放大文件(壳子包/Chrome 包等),执行机内网直连下载。
|
||||
配套 Vue3 管理页面(经 Nginx,端口 **8899**):查看/上传/下载/删除,展示上传时间、上传人、下载次数。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
fileserver/
|
||||
├── main.py # 入口(组装路由 + lifespan)
|
||||
├── launch.py # PyInstaller 打包入口
|
||||
├── requirements.txt # fastapi / uvicorn / python-multipart / PyMySQL
|
||||
├── .env # 配置(各环境各自维护)
|
||||
├── core/
|
||||
│ ├── config.py # 配置加载(.env,环境变量优先)
|
||||
│ ├── auth.py # 鉴权:X-API-Token(中心机) + 管理会话(HMAC)
|
||||
│ ├── store.py # 存储:文件落盘 + MySQL 元数据(未配库时 JSON 兜底)
|
||||
│ └── heartbeat.py # 中心机心跳上报(daemon 线程)
|
||||
├── apis/
|
||||
│ ├── meta.py # GET /(健康检查)
|
||||
│ ├── files.py # 上传/列表/删除/下载
|
||||
│ └── admin.py # 登录/改密码/统计
|
||||
└── frontend/ # Vue3 管理页源码(部署到服务器 /opt/37du/fileserver-admin/)
|
||||
├── index.html
|
||||
├── app.js
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
执行机(内网直连下载) ──▶ fileserver :8802(下载开放)
|
||||
中心机/自动化 ─────────▶ fileserver :8802(X-API-Token:上传/删除/列表)
|
||||
浏览器(管理页) ──▶ Nginx :8899 ──/fs-api/──▶ fileserver :8802(登录后 Bearer Token)
|
||||
文件本体 ──▶ FILESERVER_DATA_DIR(磁盘)
|
||||
元数据 ──▶ MySQL 37du_fileserver.fs_files(fid/filename/sha256/size/created/uploader/downloads)
|
||||
```
|
||||
|
||||
- 管理接口(上传/删除/列表/统计)需**页面内登录**:`POST /api/admin/login`(账号密码在 `FILESERVER_ADMIN_USER/PASSWORD`),签发 HMAC 会话 Token(默认 12h),前端存 localStorage、以 `Authorization: Bearer` 携带
|
||||
- **默认账号**:`puddy / 123456`(登录后请尽快在页面「改密码」)
|
||||
- 前端不接触 X-API-Token(中心机直连 8802 时用)
|
||||
- 下载 `/files/{fid}` 开放(执行机内网直连),并累计下载次数
|
||||
|
||||
## 部署位置(服务器 172.30.30.243)
|
||||
|
||||
- 代码/venv:`/opt/37du/fileserver/`、`/opt/37du/venv`
|
||||
- 数据目录:`/opt/37du/fileserver/data/`
|
||||
- 管理页静态文件:`/opt/37du/fileserver-admin/`
|
||||
- Nginx 站点:`/etc/nginx/sites-available/37du-fileserver-admin`(监听 **8899**)
|
||||
- 服务:`systemctl status/restart 37du-fileserver`,日志 `journalctl -u 37du-fileserver -f`
|
||||
|
||||
## 常用维护
|
||||
|
||||
```bash
|
||||
# 改管理密码(页面内改,或改 .env 后重启)
|
||||
sed -i 's/^FILESERVER_ADMIN_PASSWORD=.*/FILESERVER_ADMIN_PASSWORD=新密码/' /opt/37du/fileserver/.env
|
||||
systemctl restart 37du-fileserver
|
||||
|
||||
# 查 MySQL 元数据
|
||||
mysql -h 127.0.0.1 -u fs -p 37du_fileserver -e "SELECT fid,filename,size,created,uploader,downloads FROM fs_files ORDER BY created DESC LIMIT 20;"
|
||||
|
||||
# 防火墙
|
||||
ufw status verbose # 放行 22/8899/3306/8802
|
||||
```
|
||||
|
||||
## 端口规划(不给 80 占位)
|
||||
|
||||
| 端口 | 用途 |
|
||||
|------|------|
|
||||
| 22 | SSH |
|
||||
| 8802 | 文件服务器(执行机直连下载) |
|
||||
| 8899 | 管理页面(Nginx) |
|
||||
| 3306 | MySQL |
|
||||
| 80 | 预留后续其他项目 |
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""fileserver.apis 包:HTTP 路由(meta / files / admin)。"""
|
||||
@@ -0,0 +1,53 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""管理接口:登录 / 修改密码 / 统计。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from fileserver.core import auth, config, store
|
||||
|
||||
router = APIRouter(tags=["admin"])
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
|
||||
|
||||
class _ChangePwdIn(BaseModel):
|
||||
old_password: str = ""
|
||||
new_password: str = ""
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def api_login(d: _LoginIn) -> dict:
|
||||
"""管理页面登录:校验账号密码,签发管理会话 token(HMAC 签名 + 有效期)。"""
|
||||
if not auth.verify_login(d.username, d.password):
|
||||
time.sleep(0.5) # 失败延迟,降低爆破速度
|
||||
raise HTTPException(401, "用户名或密码错误")
|
||||
return {"ok": True, "token": auth.sign_admin_token(d.username),
|
||||
"expires_in": config.ADMIN_TOKEN_TTL, "user": d.username}
|
||||
|
||||
|
||||
@router.post("/api/admin/change-password")
|
||||
def api_change_password(d: _ChangePwdIn,
|
||||
_: str = Depends(auth.check_admin)) -> dict:
|
||||
"""修改管理密码:需旧密码正确;成功后旧会话全部失效(重新登录)。"""
|
||||
if not config.ADMIN_PASSWORD:
|
||||
raise HTTPException(400, "当前未配置管理密码")
|
||||
if not hmac.compare_digest(d.old_password, config.ADMIN_PASSWORD):
|
||||
raise HTTPException(400, "旧密码不正确")
|
||||
if len(d.new_password) < 6:
|
||||
raise HTTPException(400, "新密码至少 6 位")
|
||||
config.update_admin_password(d.new_password)
|
||||
return {"ok": True, "message": "密码已修改,请重新登录"}
|
||||
|
||||
|
||||
@router.get("/api/admin/stats")
|
||||
def api_stats(_: str = Depends(auth.check_admin)) -> dict:
|
||||
"""汇总统计:文件数 / 总大小 / 总下载次数。"""
|
||||
return {"ok": True, **store.stats()}
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""文件接口:上传 / 列表 / 删除 / 下载。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from fileserver.core import auth, store
|
||||
|
||||
router = APIRouter(tags=["files"])
|
||||
|
||||
|
||||
@router.post("/api/upload")
|
||||
async def api_upload(upload: UploadFile, who: str = Depends(auth.check_admin)) -> dict:
|
||||
"""上传文件:存唯一 id,返回 {id, filename, sha256, size, url}。"""
|
||||
raw = await upload.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
m = store.save(raw, upload.filename or "", uploader=who)
|
||||
return {"ok": True, "id": m["fid"], "fid": m["fid"],
|
||||
"filename": m["filename"], "sha256": m["sha256"], "size": m["size"],
|
||||
"created": m["created"], "uploader": m["uploader"],
|
||||
"url": store.file_url(m["fid"], m["filename"])}
|
||||
|
||||
|
||||
@router.get("/api/files")
|
||||
def api_files(_: str = Depends(auth.check_admin)) -> dict:
|
||||
"""列表已上传文件(管理)。"""
|
||||
items = []
|
||||
for m in store.list_files():
|
||||
m = dict(m)
|
||||
m["url"] = store.file_url(m["fid"], m["filename"])
|
||||
items.append(m)
|
||||
return {"files": items}
|
||||
|
||||
|
||||
@router.delete("/api/files/{fid}")
|
||||
def api_delete(fid: str, _: str = Depends(auth.check_admin)) -> dict:
|
||||
"""删除文件与元数据(管理)。"""
|
||||
try:
|
||||
removed = store.remove(fid)
|
||||
except ValueError:
|
||||
raise HTTPException(400, "非法的文件 id")
|
||||
return {"ok": True, "removed": removed, "id": fid}
|
||||
|
||||
|
||||
@router.get("/files/{fid}")
|
||||
def api_download(fid: str, dl: str = ""):
|
||||
"""开放下载(内网直链);?dl=文件名 时以该名 attachment 落盘;统计下载次数。"""
|
||||
p = store.path_of(fid)
|
||||
if p is None:
|
||||
raise HTTPException(404, "文件不存在")
|
||||
store.increment_downloads(fid)
|
||||
m = store.meta(fid)
|
||||
default_name = m.get("filename") or fid
|
||||
return FileResponse(p, filename=dl or default_name,
|
||||
media_type="application/octet-stream")
|
||||
@@ -0,0 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础接口:健康检查。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from fileserver.core import config, store
|
||||
|
||||
router = APIRouter(tags=["meta"])
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def index() -> dict:
|
||||
"""健康检查(无鉴权)。"""
|
||||
return {"ok": True, "service": "37du内网文件服务器",
|
||||
"version": config.VERSION,
|
||||
"files": len(store.list_files())}
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,128 +0,0 @@
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
|
||||
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
|
||||
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
|
||||
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
|
||||
missing module named 'rich.table' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.syntax' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.progress' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.markup' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.console' - imported by httpx._main (top-level)
|
||||
missing module named 'pygments.util' - imported by httpx._main (top-level)
|
||||
missing module named pygments - imported by httpx._main (top-level)
|
||||
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named zstandard - imported by httpx._decoders (optional)
|
||||
missing module named brotlicffi - imported by httpx._decoders (optional)
|
||||
missing module named brotli - imported by httpx._decoders (optional)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
excluded module named win32con - imported by win32evtlogutil (top-level)
|
||||
excluded module named win32api - imported by win32evtlogutil (top-level)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""fileserver.core 包:配置 / 鉴权 / 存储 / 心跳。"""
|
||||
@@ -0,0 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""鉴权层:中心机 X-API-Token 与 管理页面会话 token(HMAC 签名)双通道。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from fileserver.core import config
|
||||
|
||||
|
||||
def sign_admin_token(user: str) -> str:
|
||||
"""签发管理会话 token:base64("{user}|{exp}|{hmac}"),默认 12h 有效。"""
|
||||
exp = int(time.time()) + config.ADMIN_TOKEN_TTL
|
||||
payload = f"{user}|{exp}"
|
||||
sig = hmac.new(config.ADMIN_SECRET.encode("utf-8"),
|
||||
payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return base64.urlsafe_b64encode(f"{payload}|{sig}".encode("utf-8")).decode("utf-8")
|
||||
|
||||
|
||||
def verify_admin_token(token: str) -> bool:
|
||||
"""校验管理会话 Bearer token(HMAC 签名 + 过期时间)。"""
|
||||
return bool(_decode_admin(token))
|
||||
|
||||
|
||||
def _decode_admin(token: str) -> str:
|
||||
"""解析管理会话,返回登录用户名;无效/过期返回空串。"""
|
||||
if not token:
|
||||
return ""
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token.encode("utf-8")).decode("utf-8")
|
||||
user, exp, sig = raw.rsplit("|", 2)
|
||||
expect = hmac.new(config.ADMIN_SECRET.encode("utf-8"),
|
||||
f"{user}|{exp}".encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(sig, expect):
|
||||
return ""
|
||||
if int(exp) <= time.time():
|
||||
return ""
|
||||
return user
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def admin_identity(x_api_token: str, authorization: str) -> str:
|
||||
"""解析当前调用方身份:X-API-Token → "center";管理会话 → 登录用户名;否则空串。"""
|
||||
if config.TOKEN and x_api_token.strip() == config.TOKEN:
|
||||
return "center"
|
||||
if authorization.startswith("Bearer "):
|
||||
user = _decode_admin(authorization[7:].strip())
|
||||
if user:
|
||||
return user
|
||||
return ""
|
||||
|
||||
|
||||
def check_admin(x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
authorization: str = Header(default="", alias="Authorization")) -> str:
|
||||
"""FastAPI 依赖:X-API-Token(中心机/自动化)或管理会话 Bearer(管理页面)二选一通过。
|
||||
返回调用方身份("center" 或登录用户名),供记录上传人等审计字段。"""
|
||||
who = admin_identity(x_api_token, authorization)
|
||||
if not who:
|
||||
raise HTTPException(401, "无效的文件服务器令牌")
|
||||
return who
|
||||
|
||||
|
||||
def verify_login(username: str, password: str) -> bool:
|
||||
"""校验管理页面账号密码(常量时间比较)。"""
|
||||
if not (config.ADMIN_USER and config.ADMIN_PASSWORD):
|
||||
return False
|
||||
return (hmac.compare_digest(username, config.ADMIN_USER)
|
||||
and hmac.compare_digest(password, config.ADMIN_PASSWORD))
|
||||
@@ -1,68 +1,97 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
||||
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
||||
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 心跳上报间隔(秒)
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
return TOKEN or secrets.token_urlsafe(24)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录(源码与 PyInstaller 打包两种形态)。"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ===== 基础服务 =====
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
# 中心机/自动化管理 token(X-API-Token);未配置时管理接口仅允许登录会话
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
# 落盘目录:.env 未配时默认 应用目录/data
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP:端口
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
VERSION = "37du-fileserver/2.0"
|
||||
|
||||
# ===== 中心机心跳上报 =====
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
# ===== 管理页面登录(内置管理会话,替代 nginx Basic Auth)=====
|
||||
ADMIN_USER = os.getenv("FILESERVER_ADMIN_USER", "").strip()
|
||||
ADMIN_PASSWORD = os.getenv("FILESERVER_ADMIN_PASSWORD", "")
|
||||
# 管理会话有效期(秒,默认 12h)
|
||||
ADMIN_TOKEN_TTL = int(os.getenv("FILESERVER_ADMIN_TOKEN_TTL", "43200") or "43200")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""管理会话签名密钥:优先 .env 的 FILESERVER_ADMIN_SECRET;未配则由 ADMIN_PASSWORD
|
||||
派生(固定盐,保证重启后已签发 token 仍然有效)。密码变更后密钥随之变化,
|
||||
已签发 token 全部失效(需重新登录)。"""
|
||||
_s = os.getenv("FILESERVER_ADMIN_SECRET", "").strip()
|
||||
if _s:
|
||||
return _s
|
||||
import hashlib
|
||||
return hashlib.sha256(f"{ADMIN_PASSWORD}|37du-fs-admin".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
ADMIN_SECRET = _admin_secret()
|
||||
|
||||
# ===== MySQL 元数据存储(文件本体仍在磁盘,元数据/统计入库)=====
|
||||
DB_HOST = os.getenv("FILESERVER_DB_HOST", "").strip()
|
||||
DB_PORT = int(os.getenv("FILESERVER_DB_PORT", "3306") or "3306")
|
||||
DB_USER = os.getenv("FILESERVER_DB_USER", "").strip()
|
||||
DB_PASSWORD = os.getenv("FILESERVER_DB_PASSWORD", "")
|
||||
DB_NAME = os.getenv("FILESERVER_DB_NAME", "37du_fileserver").strip()
|
||||
DB_ENABLED = bool(DB_HOST and DB_USER)
|
||||
|
||||
|
||||
def update_admin_password(new_password: str) -> None:
|
||||
"""更新管理密码并持久化到 .env(管理页面「修改密码」用)。"""
|
||||
global ADMIN_PASSWORD, ADMIN_SECRET
|
||||
ADMIN_PASSWORD = new_password
|
||||
ADMIN_SECRET = _admin_secret()
|
||||
env_path = APP_DIR / ".env"
|
||||
lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
|
||||
out, hit = [], False
|
||||
for ln in lines:
|
||||
if ln.strip().startswith("FILESERVER_ADMIN_PASSWORD="):
|
||||
out.append(f"FILESERVER_ADMIN_PASSWORD={new_password}")
|
||||
hit = True
|
||||
else:
|
||||
out.append(ln)
|
||||
if not hit:
|
||||
out.append(f"FILESERVER_ADMIN_PASSWORD={new_password}")
|
||||
env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""心跳上报:后台线程周期向中心机上报本机状态,供中心机监控在线/离线并钉钉告警。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
from fileserver.core import config
|
||||
from fileserver.core import store
|
||||
|
||||
log = logging.getLogger("fileserver.heartbeat")
|
||||
_START_TS = time.time()
|
||||
|
||||
|
||||
def _server_status() -> dict:
|
||||
"""收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。"""
|
||||
metas = store.list_files()
|
||||
total = sum(int(m.get("size") or 0) for m in metas)
|
||||
hostname = socket.gethostname()
|
||||
try:
|
||||
ip = socket.gethostbyname(hostname)
|
||||
except OSError: # noqa: BLE001
|
||||
ip = ""
|
||||
return {
|
||||
"host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根)
|
||||
"base_url": config.BASE_URL,
|
||||
"hostname": hostname,
|
||||
"ip": ip,
|
||||
"port": config.PORT,
|
||||
"file_count": len(metas),
|
||||
"total_size": total,
|
||||
"version": config.VERSION,
|
||||
"uptime_sec": int(time.time() - _START_TS),
|
||||
}
|
||||
|
||||
|
||||
def _post_heartbeat() -> bool:
|
||||
"""单次上报心跳到中心机;成功返回 True。"""
|
||||
payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat",
|
||||
data=payload, method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status < 400
|
||||
except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理
|
||||
log.warning("心跳上报失败:%s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _loop() -> None:
|
||||
"""周期上报;每次最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
log.info("未配置 CONTROLPLANE_URL,跳过心跳上报")
|
||||
return
|
||||
while True:
|
||||
try:
|
||||
ok = False
|
||||
for _i in range(3):
|
||||
if _post_heartbeat():
|
||||
ok = True
|
||||
break
|
||||
if not ok:
|
||||
log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL)
|
||||
except Exception: # noqa: BLE001
|
||||
log.exception("心跳上报线程异常")
|
||||
time.sleep(max(5, config.HEARTBEAT_INTERVAL))
|
||||
|
||||
|
||||
def start() -> None:
|
||||
"""启动心跳上报线程(daemon)。"""
|
||||
threading.Thread(target=_loop, daemon=True,
|
||||
name="fileserver-heartbeat").start()
|
||||
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""存储层:文件本体落盘 + 元数据入库(MySQL 优先,未配置时 JSON 兜底)。
|
||||
|
||||
元数据字段:fid / filename / sha256 / size / created / uploader / downloads / note。
|
||||
文件本体保存在 DATA_DIR(大文件不放数据库),元数据与统计进 MySQL。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fileserver.core import config
|
||||
|
||||
_DATA_DIR = config.DATA_DIR
|
||||
_STATUS_DIR = _DATA_DIR / ".meta"
|
||||
_FID_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS fs_files (
|
||||
fid VARCHAR(64) NOT NULL PRIMARY KEY,
|
||||
filename VARCHAR(200) NOT NULL,
|
||||
sha256 CHAR(64) NOT NULL,
|
||||
size BIGINT NOT NULL DEFAULT 0,
|
||||
created DOUBLE NOT NULL,
|
||||
uploader VARCHAR(64) NOT NULL DEFAULT '',
|
||||
downloads BIGINT NOT NULL DEFAULT 0,
|
||||
note VARCHAR(255) NOT NULL DEFAULT '',
|
||||
KEY idx_created (created),
|
||||
KEY idx_filename (filename)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
"""
|
||||
|
||||
|
||||
def _db_conn():
|
||||
"""建立 PyMySQL 连接(每操作短连接,轻量文件服务够用)。"""
|
||||
import pymysql
|
||||
return pymysql.connect(
|
||||
host=config.DB_HOST, port=config.DB_PORT, user=config.DB_USER,
|
||||
password=config.DB_PASSWORD, database=config.DB_NAME,
|
||||
charset="utf8mb4", autocommit=False)
|
||||
|
||||
|
||||
def _db_exec(sql: str, args=()) -> int:
|
||||
"""执行写操作,返回 rowcount。"""
|
||||
conn = _db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
n = cur.execute(sql, args)
|
||||
conn.commit()
|
||||
return n
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _db_fetch(sql: str, args=()) -> list[dict]:
|
||||
"""查询并返回 dict 列表。"""
|
||||
conn = _db_conn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql, args)
|
||||
cols = [d[0] for d in cur.description] if cur.description else []
|
||||
rows = [dict(zip(cols, r)) for r in cur.fetchall()]
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ==================== 初始化 ====================
|
||||
def init() -> None:
|
||||
"""确保数据目录与元数据目录就绪;DB 模式下自动建表。"""
|
||||
_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_STATUS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
if config.DB_ENABLED:
|
||||
_db_exec(_SCHEMA)
|
||||
|
||||
|
||||
def _using_db() -> bool:
|
||||
return config.DB_ENABLED
|
||||
|
||||
|
||||
# ==================== 工具 ====================
|
||||
def safe_name(name: str) -> str:
|
||||
"""清洗文件名:仅保留安全 basename,去除路径与危险字符。"""
|
||||
return re.sub(r"[^\w.\-]", "_", Path(name or "").name)[:200]
|
||||
|
||||
|
||||
def _row_to_meta(row: dict) -> dict:
|
||||
return {
|
||||
"fid": row["fid"], "filename": row["filename"],
|
||||
"sha256": row["sha256"], "size": int(row["size"] or 0),
|
||||
"created": float(row["created"]),
|
||||
"uploader": row.get("uploader") or "",
|
||||
"downloads": int(row.get("downloads") or 0),
|
||||
"note": row.get("note") or "",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 写 ====================
|
||||
def save(raw: bytes, filename: str, uploader: str = "", note: str = "") -> dict:
|
||||
"""保存文件:唯一 id 落盘 + 元数据入库,返回 meta。"""
|
||||
fid = secrets.token_urlsafe(12)
|
||||
origin = safe_name(filename)
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
created = time.time()
|
||||
(_DATA_DIR / fid).write_bytes(raw)
|
||||
if _using_db():
|
||||
_db_exec(
|
||||
"INSERT INTO fs_files (fid, filename, sha256, size, created, uploader, note) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
(fid, origin, sha, len(raw), created, uploader, note))
|
||||
else:
|
||||
m = {"fid": fid, "filename": origin, "sha256": sha, "size": len(raw),
|
||||
"created": created, "uploader": uploader, "downloads": 0, "note": note}
|
||||
(_STATUS_DIR / f"{fid}.json").write_text(
|
||||
json.dumps(m, ensure_ascii=False), encoding="utf-8")
|
||||
return meta(fid)
|
||||
|
||||
|
||||
def increment_downloads(fid: str) -> None:
|
||||
"""下载计数 +1(仅统计,不影响下载)。"""
|
||||
if _using_db():
|
||||
_db_exec("UPDATE fs_files SET downloads = downloads + 1 WHERE fid = %s", (fid,))
|
||||
else:
|
||||
mf = _STATUS_DIR / f"{fid}.json"
|
||||
if mf.is_file():
|
||||
try:
|
||||
m = json.loads(mf.read_text(encoding="utf-8"))
|
||||
m["downloads"] = int(m.get("downloads") or 0) + 1
|
||||
mf.write_text(json.dumps(m, ensure_ascii=False), encoding="utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 读 ====================
|
||||
def meta(fid: str) -> dict:
|
||||
"""读元数据;不存在返回空 dict。"""
|
||||
if _using_db():
|
||||
rows = _db_fetch("SELECT * FROM fs_files WHERE fid = %s", (fid,))
|
||||
return _row_to_meta(rows[0]) if rows else {}
|
||||
mf = _STATUS_DIR / f"{fid}.json"
|
||||
if not mf.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(mf.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def list_files() -> list[dict]:
|
||||
"""列出全部文件元数据(按上传时间倒序)。"""
|
||||
if _using_db():
|
||||
rows = _db_fetch("SELECT * FROM fs_files ORDER BY created DESC")
|
||||
return [_row_to_meta(r) for r in rows]
|
||||
items = []
|
||||
for mf in sorted(_STATUS_DIR.glob("*.json")):
|
||||
m = meta(mf.stem)
|
||||
if m:
|
||||
items.append(m)
|
||||
items.sort(key=lambda m: m.get("created") or 0, reverse=True)
|
||||
return items
|
||||
|
||||
|
||||
def path_of(fid: str) -> Path | None:
|
||||
"""返回文件落盘路径;不存在/非法 id 返回 None。"""
|
||||
if not _FID_RE.fullmatch(fid):
|
||||
return None
|
||||
p = _DATA_DIR / fid
|
||||
return p if p.is_file() else None
|
||||
|
||||
|
||||
def remove(fid: str) -> bool:
|
||||
"""删除文件与元数据;非法 id 抛 ValueError。"""
|
||||
if not _FID_RE.fullmatch(fid):
|
||||
raise ValueError("非法文件 id")
|
||||
removed = False
|
||||
p = _DATA_DIR / fid
|
||||
if p.is_file():
|
||||
p.unlink(missing_ok=True)
|
||||
removed = True
|
||||
if _using_db():
|
||||
_db_exec("DELETE FROM fs_files WHERE fid = %s", (fid,))
|
||||
else:
|
||||
(_STATUS_DIR / f"{fid}.json").unlink(missing_ok=True)
|
||||
return removed
|
||||
|
||||
|
||||
def file_url(fid: str, filename: str = "") -> str:
|
||||
"""对外下载直链。"""
|
||||
return f"{config.BASE_URL}/files/{fid}?dl={filename or fid}"
|
||||
|
||||
|
||||
def stats() -> dict:
|
||||
"""汇总统计:文件数 / 总大小 / 总下载。"""
|
||||
if _using_db():
|
||||
rows = _db_fetch(
|
||||
"SELECT COUNT(*) AS c, COALESCE(SUM(size),0) AS s, COALESCE(SUM(downloads),0) AS d "
|
||||
"FROM fs_files")
|
||||
return {"count": int(rows[0]["c"]), "total_size": int(rows[0]["s"]),
|
||||
"total_downloads": int(rows[0]["d"])}
|
||||
metas = list_files()
|
||||
return {"count": len(metas),
|
||||
"total_size": sum(int(m.get("size") or 0) for m in metas),
|
||||
"total_downloads": sum(int(m.get("downloads") or 0) for m in metas)}
|
||||
Binary file not shown.
@@ -0,0 +1,47 @@
|
||||
# fileserver 管理页面(Vue 3)
|
||||
|
||||
文件服务器(8802)的 Web 管理界面:查看文件列表、上传时间、大小、SHA256,支持上传/下载/删除。
|
||||
|
||||
## 文件说明
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `index.html` | 页面骨架 + 样式 |
|
||||
| `app.js` | Vue 3 应用逻辑(列表/上传/删除/搜索) |
|
||||
| `vue.global.prod.js` | Vue 运行时(本地托管,离线可用,部署在服务器 `/opt/37du/fileserver-admin/`) |
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
浏览器 → Nginx(:80)
|
||||
├── 页面静态文件(/opt/37du/fileserver-admin/)
|
||||
└── /fs-api/* → 反代到 127.0.0.1:8802
|
||||
```
|
||||
- 管理接口(列表/上传/删除)需**页面内登录**:`POST /api/admin/login`(账号密码在 fileserver/.env 的 `FILESERVER_ADMIN_USER/PASSWORD`),签发 HMAC 会话 Token(默认 12h),前端存 localStorage、以 `Authorization: Bearer` 携带
|
||||
- 前端**不接触** X-API-Token(中心机/自动化直连 8802 时用)
|
||||
- 下载 `/files/{fid}` 保持开放(执行机内网直连)
|
||||
- Nginx `client_max_body_size 0` 支持大文件上传
|
||||
|
||||
## 部署位置(服务器 172.30.30.243)
|
||||
|
||||
- 站点配置:`/etc/nginx/sites-available/37du-fileserver-admin`
|
||||
- 页面文件:`/opt/37du/fileserver-admin/`
|
||||
- 认证文件:`/etc/nginx/.htpasswd`
|
||||
|
||||
## 修改管理密码
|
||||
|
||||
```bash
|
||||
# 修改 /opt/37du/fileserver/.env 中的 FILESERVER_ADMIN_PASSWORD,然后重启服务:
|
||||
systemctl restart 37du-fileserver
|
||||
```
|
||||
|
||||
## 更新页面
|
||||
|
||||
1. 本地修改 `desktop/fileserver/frontend/` 下文件
|
||||
2. 上传覆盖 `/opt/37du/fileserver-admin/` 同名文件
|
||||
3. `systemctl reload nginx`
|
||||
|
||||
## 防火墙(ufw)
|
||||
|
||||
已启用:默认拒绝入站,放行 `22/tcp`(limit)、`80/tcp`、`3306/tcp`、`8802/tcp`。
|
||||
管理:`ufw status verbose` / `ufw allow <port>/tcp` / `ufw delete allow <port>/tcp`
|
||||
@@ -0,0 +1,316 @@
|
||||
// 37du 文件服务器管理页面 v2.0 - Vue 3 应用逻辑
|
||||
// API 走同源 /fs-api 反代;管理接口用登录后的会话 Bearer Token 鉴权。
|
||||
"use strict";
|
||||
|
||||
const API_BASE = "/fs-api";
|
||||
const TOKEN_KEY = "fs_admin_token";
|
||||
|
||||
const { createApp } = Vue;
|
||||
|
||||
createApp({
|
||||
data() {
|
||||
return {
|
||||
files: [],
|
||||
loading: false,
|
||||
keyword: "",
|
||||
sortKey: "created",
|
||||
sortDir: -1, // -1 降序 1 升序
|
||||
uploading: false,
|
||||
uploadIdx: 0,
|
||||
uploadTotal: 0,
|
||||
uploadPercent: 0,
|
||||
statusMsg: "",
|
||||
statusClass: "",
|
||||
baseUrl: location.origin,
|
||||
// 登录态
|
||||
token: localStorage.getItem(TOKEN_KEY) || "",
|
||||
username: "",
|
||||
password: "",
|
||||
showPwd: false,
|
||||
loginMsg: "",
|
||||
loggingIn: false,
|
||||
// 改密码
|
||||
showPwdModal: false,
|
||||
oldPwd: "",
|
||||
newPwd: "",
|
||||
newPwd2: "",
|
||||
pwdMsg: "",
|
||||
savingPwd: false,
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
loggedIn() {
|
||||
return !!this.token;
|
||||
},
|
||||
tokenUser() {
|
||||
try {
|
||||
const raw = atob(this.token.split(".")[0]);
|
||||
return raw.split("|")[0] || "?";
|
||||
} catch (e) {
|
||||
return "?";
|
||||
}
|
||||
},
|
||||
sortedFiles() {
|
||||
const k = this.keyword.trim().toLowerCase();
|
||||
let list = this.files;
|
||||
if (k) list = list.filter((f) => (f.filename || "").toLowerCase().includes(k));
|
||||
const dir = this.sortDir;
|
||||
const key = this.sortKey;
|
||||
return list.slice().sort((a, b) => {
|
||||
let r = 0;
|
||||
if (key === "filename") r = (a.filename || "").localeCompare(b.filename || "", "zh");
|
||||
else if (key === "size") r = (Number(a.size) || 0) - (Number(b.size) || 0);
|
||||
else if (key === "created") r = (a.created || 0) - (b.created || 0);
|
||||
else if (key === "downloads") r = (Number(a.downloads) || 0) - (Number(b.downloads) || 0);
|
||||
return r * dir;
|
||||
});
|
||||
},
|
||||
totalCount() {
|
||||
return this.files.length;
|
||||
},
|
||||
totalSizeText() {
|
||||
return this.fmtSize(this.files.reduce((s, f) => s + (Number(f.size) || 0), 0));
|
||||
},
|
||||
totalDownloads() {
|
||||
return this.files.reduce((s, f) => s + (Number(f.downloads) || 0), 0);
|
||||
},
|
||||
lastUploadText() {
|
||||
if (!this.files.length) return "-";
|
||||
const t = Math.max(...this.files.map((f) => Number(f.created) || 0));
|
||||
return this.fmtTime(t);
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
authHeaders() {
|
||||
return { Authorization: "Bearer " + this.token };
|
||||
},
|
||||
flash(msg, ok) {
|
||||
this.statusMsg = msg;
|
||||
this.statusClass = ok ? "ok" : "err";
|
||||
clearTimeout(this._t);
|
||||
this._t = setTimeout(() => {
|
||||
this.statusMsg = "";
|
||||
this.statusClass = "";
|
||||
}, 3000);
|
||||
},
|
||||
sortBy(key) {
|
||||
if (this.sortKey === key) {
|
||||
this.sortDir = -this.sortDir;
|
||||
} else {
|
||||
this.sortKey = key;
|
||||
this.sortDir = key === "filename" ? 1 : -1;
|
||||
}
|
||||
},
|
||||
// ===== 登录 =====
|
||||
async login() {
|
||||
this.loggingIn = true;
|
||||
this.loginMsg = "";
|
||||
try {
|
||||
const r = await fetch(`${API_BASE}/api/admin/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: this.username, password: this.password }),
|
||||
});
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) {
|
||||
this.loginMsg = j.detail || ("登录失败 HTTP " + r.status);
|
||||
return;
|
||||
}
|
||||
this.token = j.token;
|
||||
localStorage.setItem(TOKEN_KEY, j.token);
|
||||
this.password = "";
|
||||
this.load();
|
||||
} catch (e) {
|
||||
this.loginMsg = "网络错误:" + e.message;
|
||||
} finally {
|
||||
this.loggingIn = false;
|
||||
}
|
||||
},
|
||||
logout() {
|
||||
this.token = "";
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
this.files = [];
|
||||
this.loginMsg = "";
|
||||
this.keyword = "";
|
||||
},
|
||||
// ===== 数据 =====
|
||||
async load() {
|
||||
this.loading = true;
|
||||
try {
|
||||
const r = await fetch(`${API_BASE}/api/files`, { headers: this.authHeaders() });
|
||||
if (r.status === 401) {
|
||||
this.logout();
|
||||
this.loginMsg = "登录已过期,请重新登录";
|
||||
return;
|
||||
}
|
||||
if (!r.ok) throw new Error("HTTP " + r.status);
|
||||
const j = await r.json();
|
||||
this.files = j.files || [];
|
||||
this.flash("已刷新,共 " + this.files.length + " 个文件", true);
|
||||
} catch (e) {
|
||||
this.flash("加载文件列表失败:" + e.message, false);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
// ===== 上传(支持多文件)=====
|
||||
async onFilesPicked(ev) {
|
||||
const files = Array.from(ev.target.files || []);
|
||||
ev.target.value = "";
|
||||
if (!files.length) return;
|
||||
this.uploading = true;
|
||||
this.uploadTotal = files.length;
|
||||
let okCount = 0;
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
this.uploadIdx = i + 1;
|
||||
this.uploadPercent = 0;
|
||||
if (await this.uploadOne(files[i])) okCount++;
|
||||
}
|
||||
this.uploading = false;
|
||||
this.flash(`上传完成:成功 ${okCount}/${files.length} 个`, okCount > 0);
|
||||
this.load();
|
||||
},
|
||||
uploadOne(file) {
|
||||
return new Promise((resolve) => {
|
||||
const fd = new FormData();
|
||||
fd.append("upload", file);
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", `${API_BASE}/api/upload`);
|
||||
xhr.setRequestHeader("Authorization", "Bearer " + this.token);
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) this.uploadPercent = Math.round((e.loaded / e.total) * 100);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
if (xhr.status === 401) {
|
||||
this.logout();
|
||||
this.loginMsg = "登录已过期,请重新登录";
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
if (xhr.status < 300) resolve(true);
|
||||
else {
|
||||
this.flash(`上传 ${file.name} 失败:HTTP ${xhr.status}`, false);
|
||||
resolve(false);
|
||||
}
|
||||
};
|
||||
xhr.onerror = () => {
|
||||
this.flash(`上传 ${file.name} 失败:网络错误`, false);
|
||||
resolve(false);
|
||||
};
|
||||
xhr.send(fd);
|
||||
});
|
||||
},
|
||||
// ===== 删除 =====
|
||||
async remove(f) {
|
||||
if (!confirm(`确定删除文件「${f.filename}」?此操作不可恢复。`)) return;
|
||||
try {
|
||||
const r = await fetch(`${API_BASE}/api/files/${f.fid}`, {
|
||||
method: "DELETE",
|
||||
headers: this.authHeaders(),
|
||||
});
|
||||
if (r.status === 401) {
|
||||
this.logout();
|
||||
this.loginMsg = "登录已过期,请重新登录";
|
||||
return;
|
||||
}
|
||||
if (!r.ok) throw new Error("HTTP " + r.status);
|
||||
const j = await r.json();
|
||||
if (j.ok) {
|
||||
this.files = this.files.filter((x) => x.fid !== f.fid);
|
||||
this.flash("已删除:" + f.filename, true);
|
||||
} else {
|
||||
this.flash("删除失败", false);
|
||||
}
|
||||
} catch (e) {
|
||||
this.flash("删除失败:" + e.message, false);
|
||||
}
|
||||
},
|
||||
// ===== 链接复制 =====
|
||||
async copyLink(f) {
|
||||
const url = this.downloadUrl(f);
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
this.flash("下载链接已复制", true);
|
||||
} catch (e) {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = url;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand("copy");
|
||||
ta.remove();
|
||||
this.flash("下载链接已复制", true);
|
||||
}
|
||||
},
|
||||
// ===== 修改密码 =====
|
||||
openPwdModal() {
|
||||
this.oldPwd = this.newPwd = this.newPwd2 = "";
|
||||
this.pwdMsg = "";
|
||||
this.showPwdModal = true;
|
||||
},
|
||||
closePwdModal() {
|
||||
this.showPwdModal = false;
|
||||
},
|
||||
async changePwd() {
|
||||
this.pwdMsg = "";
|
||||
if (this.newPwd !== this.newPwd2) {
|
||||
this.pwdMsg = "两次输入的新密码不一致";
|
||||
return;
|
||||
}
|
||||
if (this.newPwd.length < 6) {
|
||||
this.pwdMsg = "新密码至少 6 位";
|
||||
return;
|
||||
}
|
||||
this.savingPwd = true;
|
||||
try {
|
||||
const r = await fetch(`${API_BASE}/api/admin/change-password`, {
|
||||
method: "POST",
|
||||
headers: Object.assign({ "Content-Type": "application/json" }, this.authHeaders()),
|
||||
body: JSON.stringify({ old_password: this.oldPwd, new_password: this.newPwd }),
|
||||
});
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) {
|
||||
this.pwdMsg = j.detail || ("修改失败 HTTP " + r.status);
|
||||
return;
|
||||
}
|
||||
this.showPwdModal = false;
|
||||
this.logout();
|
||||
this.loginMsg = "密码已修改,请用新密码重新登录";
|
||||
} catch (e) {
|
||||
this.pwdMsg = "网络错误:" + e.message;
|
||||
} finally {
|
||||
this.savingPwd = false;
|
||||
}
|
||||
},
|
||||
// ===== 工具 =====
|
||||
downloadUrl(f) {
|
||||
return `${API_BASE}/files/${f.fid}?dl=${encodeURIComponent(f.filename || f.fid)}`;
|
||||
},
|
||||
extOf(name) {
|
||||
const m = /\.([A-Za-z0-9]+)$/.exec(name || "");
|
||||
return m ? m[1].toUpperCase().slice(0, 6) : "FILE";
|
||||
},
|
||||
whoLabel(who) {
|
||||
if (!who) return "-";
|
||||
return who === "center" ? "中心机" : who;
|
||||
},
|
||||
fmtSize(bytes) {
|
||||
const b = Number(bytes) || 0;
|
||||
if (b < 1024) return b + " B";
|
||||
if (b < 1024 * 1024) return (b / 1024).toFixed(1) + " KB";
|
||||
if (b < 1024 * 1024 * 1024) return (b / 1024 / 1024).toFixed(1) + " MB";
|
||||
return (b / 1024 / 1024 / 1024).toFixed(2) + " GB";
|
||||
},
|
||||
fmtTime(ts) {
|
||||
if (!ts) return "-";
|
||||
const d = new Date(Number(ts) * 1000);
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
},
|
||||
shortSha(s) {
|
||||
return (s || "").slice(0, 12) + "…";
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
if (this.token) this.load();
|
||||
},
|
||||
}).mount("#app");
|
||||
@@ -0,0 +1,424 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>37du 文件服务器管理</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: "Comic Sans MS", "Comic Neue", "Segoe Print", "Marker Felt", "Bradley Hand", cursive;
|
||||
background-color: #fffdf3;
|
||||
background-image:
|
||||
repeating-linear-gradient(transparent 0 31px, rgba(120, 150, 210, .15) 31px 32px),
|
||||
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix type='saturate' values='0'/></filter><rect width='120' height='120' filter='url(%23n)' opacity='0.035'/></svg>");
|
||||
color: #2b2b2b; font-size: 15px; min-height: 100vh;
|
||||
}
|
||||
::selection { background: #ffe066; color: #2b2b2b; }
|
||||
|
||||
/* ===== 手绘通用 ===== */
|
||||
.hand { border: 2.5px solid #2b2b2b; border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px; }
|
||||
.squiggle {
|
||||
display: inline-block; height: 7px; margin-top: 3px;
|
||||
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='140' height='7'><path d='M0 3 Q 10 0, 20 3 T 40 3 T 60 3 T 80 3 T 100 3 T 120 3 T 140 3' stroke='%23e8590c' stroke-width='2.6' fill='none' stroke-linecap='round'/></svg>");
|
||||
background-repeat: no-repeat; background-size: 100% 100%;
|
||||
}
|
||||
.pin { position: absolute; font-size: 20px; line-height: 1; filter: drop-shadow(0 2px 2px rgba(0,0,0,.25)); }
|
||||
.tape {
|
||||
position: absolute; width: 92px; height: 26px; z-index: 2;
|
||||
background: rgba(255, 224, 130, .62);
|
||||
border-left: 2px dashed rgba(0,0,0,.18);
|
||||
border-right: 2px dashed rgba(0,0,0,.18);
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,.12);
|
||||
}
|
||||
|
||||
/* ===== 登录页 ===== */
|
||||
.login-wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; }
|
||||
.login-card {
|
||||
position: relative; width: 410px; background: #fffef8;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
|
||||
box-shadow: 5px 7px 0 rgba(0,0,0,.12);
|
||||
padding: 44px 38px 36px; transform: rotate(-.6deg);
|
||||
}
|
||||
.login-card .tape { top: -14px; left: 50%; margin-left: -46px; transform: rotate(-3deg); }
|
||||
.login-card .pin { top: -12px; right: 22px; transform: rotate(12deg); }
|
||||
.login-card .emblem {
|
||||
width: 58px; height: 58px; border-radius: 50%;
|
||||
background: #fff; border: 3px solid #2b2b2b;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 800; font-size: 24px; color: #e8590c;
|
||||
transform: rotate(-7deg); box-shadow: 2px 3px 0 rgba(0,0,0,.14);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.login-card h2 { font-size: 27px; font-weight: 800; letter-spacing: .5px; }
|
||||
.login-card .login-sub { font-size: 13px; color: #868e96; font-weight: 700; margin: 4px 0 20px; }
|
||||
.login-field { position: relative; margin-bottom: 13px; }
|
||||
.login-field input {
|
||||
width: 100%; padding: 11px 44px 11px 14px;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
font-family: inherit; font-size: 15px; font-weight: 600; outline: none;
|
||||
background: #fff;
|
||||
}
|
||||
.login-field input:focus { background: #fff9db; }
|
||||
.eye { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); cursor: pointer; font-size: 17px; user-select: none; }
|
||||
.login-card .btn { width: 100%; padding: 12px; font-size: 16px; margin-top: 4px; }
|
||||
.login-hint { margin-top: 14px; font-size: 12.5px; color: #868e96; font-weight: 700; }
|
||||
.login-msg {
|
||||
margin-top: 12px; background: #ffe3e3; color: #c92a2a;
|
||||
padding: 10px 12px; font-weight: 700; font-size: 13px;
|
||||
border: 2.5px dashed #c92a2a; border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
|
||||
}
|
||||
|
||||
/* ===== 顶栏(便签条)===== */
|
||||
.header {
|
||||
position: relative; background: #ffe066;
|
||||
border-bottom: 3px solid #2b2b2b;
|
||||
padding: 16px 30px;
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 16px;
|
||||
transform: rotate(-.35deg); margin: 0 -4px;
|
||||
}
|
||||
.header .pin.l { top: 6px; left: 14px; transform: rotate(-14deg); }
|
||||
.header .pin.r { top: 6px; right: 200px; transform: rotate(10deg); }
|
||||
.header .brand { display: flex; align-items: center; gap: 14px; }
|
||||
.header .emblem {
|
||||
width: 48px; height: 48px; border-radius: 50%;
|
||||
background: #fff; border: 3px solid #2b2b2b;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 800; font-size: 21px; color: #e8590c;
|
||||
transform: rotate(-6deg); box-shadow: 2px 3px 0 rgba(0,0,0,.14);
|
||||
}
|
||||
.header h1 { font-size: 23px; font-weight: 800; line-height: 1.1; }
|
||||
.header h1 .squiggle { width: 150px; }
|
||||
.header .sub { font-size: 12.5px; color: #5c5c5c; font-weight: 700; margin-top: 2px; }
|
||||
.header .actions { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
/* ===== 统计条 ===== */
|
||||
.stats {
|
||||
display: grid; grid-template-columns: repeat(4, 1fr); gap: 18px;
|
||||
padding: 22px 30px 18px;
|
||||
}
|
||||
.stat {
|
||||
position: relative; background: #fffef8; padding: 12px 16px 13px;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
box-shadow: 3px 5px 0 rgba(0,0,0,.1);
|
||||
transition: transform .18s ease, box-shadow .18s ease;
|
||||
}
|
||||
.stat:nth-child(odd) { transform: rotate(-1.2deg); }
|
||||
.stat:nth-child(even) { transform: rotate(1deg); }
|
||||
.stat:hover { transform: rotate(0) translateY(-3px); box-shadow: 5px 8px 0 rgba(0,0,0,.14); }
|
||||
.stat .tape { top: -11px; left: 50%; margin-left: -46px; transform: rotate(-2deg); width: 74px; height: 22px; }
|
||||
.stat .k { font-size: 12.5px; font-weight: 700; color: #868e96; letter-spacing: .5px; }
|
||||
.stat .v { font-size: 23px; font-weight: 800; margin-top: 3px; color: #2b2b2b; }
|
||||
.stat:nth-child(1) .v { color: #e8590c; }
|
||||
.stat:nth-child(2) .v { color: #1971c2; }
|
||||
.stat:nth-child(3) .v { color: #2f9e44; }
|
||||
.stat:nth-child(4) .v { color: #9c36b5; }
|
||||
|
||||
/* ===== 工具栏 ===== */
|
||||
.toolbar {
|
||||
display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
|
||||
padding: 8px 30px 18px;
|
||||
}
|
||||
.toolbar input[type="text"] {
|
||||
padding: 9px 14px; border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
font-family: inherit; font-size: 14px; font-weight: 600; outline: none;
|
||||
width: 280px; background: #fff;
|
||||
}
|
||||
.toolbar input[type="text"]:focus { background: #fff9db; }
|
||||
.toolbar .hint { color: #868e96; font-size: 12.5px; font-weight: 700; }
|
||||
|
||||
/* ===== 按钮(标记笔)===== */
|
||||
.btn {
|
||||
font-family: inherit; font-weight: 700; font-size: 14.5px;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
background: #fff; color: #2b2b2b;
|
||||
padding: 9px 18px; cursor: pointer;
|
||||
box-shadow: 2px 3px 0 rgba(0,0,0,.14);
|
||||
transition: transform .12s ease, background .12s ease;
|
||||
user-select: none;
|
||||
}
|
||||
.btn:hover { transform: rotate(-1.6deg) scale(1.04); }
|
||||
.btn:active { transform: rotate(0) translateY(2px); box-shadow: 0 1px 0 rgba(0,0,0,.14); }
|
||||
.btn-primary { background: #ffe066; }
|
||||
.btn-primary:hover { background: #ffd43b; }
|
||||
.btn-success { background: #b2f2bb; }
|
||||
.btn-success:hover { background: #8ce99a; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.upload-btn input[type="file"] { display: none; }
|
||||
.tag {
|
||||
display: inline-block; padding: 6px 12px;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
font-size: 13px; font-weight: 700; background: #ffd8a8; color: #2b2b2b;
|
||||
transform: rotate(-1deg); box-shadow: 2px 3px 0 rgba(0,0,0,.1);
|
||||
}
|
||||
|
||||
/* ===== 状态条(标记笔高亮)===== */
|
||||
.status-bar { display: none; padding: 11px 30px; font-weight: 700; font-size: 14px; }
|
||||
.status-bar.ok { display: block; background: #fff3bf; color: #2b2b2b; border-bottom: 2.5px dashed #f59f00; }
|
||||
.status-bar.err { display: block; background: #ffe3e3; color: #c92a2a; border-bottom: 2.5px dashed #e03131; }
|
||||
|
||||
.main { padding: 8px 30px 30px; }
|
||||
|
||||
/* ===== 主卡片(纸页 + 折角)===== */
|
||||
.card {
|
||||
position: relative; background: #fffef8;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
|
||||
box-shadow: 5px 7px 0 rgba(0,0,0,.1);
|
||||
transform: rotate(.2deg);
|
||||
}
|
||||
.card > .tape { top: -13px; left: 50%; margin-left: -46px; transform: rotate(-3deg); }
|
||||
.card::after {
|
||||
content: ""; position: absolute; top: 0; right: 0;
|
||||
width: 0; height: 0;
|
||||
border-style: solid;
|
||||
border-width: 0 0 30px 30px;
|
||||
border-color: transparent transparent #ffe066 transparent;
|
||||
filter: drop-shadow(-2px 2px 1px rgba(0,0,0,.08));
|
||||
}
|
||||
|
||||
/* ===== 加载中(翻本子)===== */
|
||||
.loading {
|
||||
padding: 70px; text-align: center; font-weight: 800; font-size: 18px; color: #495057;
|
||||
}
|
||||
.loading .pen { display: inline-block; animation: pen 1.1s ease-in-out infinite; }
|
||||
@keyframes pen {
|
||||
0%, 100% { transform: rotate(-8deg) translateY(0); }
|
||||
50% { transform: rotate(10deg) translateY(-6px); }
|
||||
}
|
||||
|
||||
/* ===== 表格 ===== */
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th {
|
||||
background: #fff3bf; color: #2b2b2b; text-align: left; cursor: pointer; user-select: none;
|
||||
padding: 11px 14px; font-weight: 800; letter-spacing: .3px;
|
||||
border-bottom: 3px solid #2b2b2b; font-size: 14px; white-space: nowrap;
|
||||
}
|
||||
th .arrow { color: #e8590c; margin-left: 3px; }
|
||||
td { padding: 11px 14px; border-bottom: 2px dashed #ced4da; font-weight: 600; vertical-align: middle; }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
tbody tr:hover td { background: #ffecb3; }
|
||||
.fname-cell { display: flex; flex-direction: column; gap: 4px; min-width: 200px; }
|
||||
.filename { font-weight: 800; word-break: break-all; }
|
||||
.fname-meta { display: flex; gap: 8px; align-items: center; }
|
||||
.ext {
|
||||
display: inline-block; padding: 1px 8px;
|
||||
border: 2px solid #2b2b2b; border-radius: 50%;
|
||||
background: #d0ebff; font-size: 10px; font-weight: 800; color: #1971c2;
|
||||
transform: rotate(-4deg);
|
||||
}
|
||||
.sha { font-family: "Courier New", Consolas, monospace; color: #868e96; font-size: 11.5px; cursor: help; font-weight: 700; }
|
||||
tbody tr:hover .sha { color: #2b2b2b; }
|
||||
.empty { padding: 46px 20px; text-align: center; font-weight: 700; font-size: 15px; color: #2b2b2b; }
|
||||
.empty svg { margin-bottom: 14px; }
|
||||
.empty .et { display: inline-block; border: 2.5px dashed #adb5bd;
|
||||
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
|
||||
padding: 10px 26px; background: #fffdf3; }
|
||||
a.dl, a.cp, a.rm { text-decoration: none; font-weight: 800; font-size: 13.5px; padding: 0 3px; margin-right: 6px; }
|
||||
a.dl { color: #1971c2; background: linear-gradient(transparent 62%, #a5d8ff 62%); }
|
||||
a.dl:hover { background: #a5d8ff; }
|
||||
a.cp { color: #2f9e44; background: linear-gradient(transparent 62%, #b2f2bb 62%); }
|
||||
a.cp:hover { background: #b2f2bb; }
|
||||
a.rm { color: #e03131; background: linear-gradient(transparent 62%, #ffc9c9 62%); }
|
||||
a.rm:hover { background: #ffc9c9; }
|
||||
.who { font-weight: 800; }
|
||||
.who.center { color: #1971c2; }
|
||||
|
||||
.footer {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
padding: 12px 18px; border-top: 2.5px dashed #adb5bd;
|
||||
font-weight: 700; font-size: 12.5px; color: #495057;
|
||||
}
|
||||
.footer .dot { color: #e8590c; }
|
||||
|
||||
/* ===== 修改密码弹窗(便签)===== */
|
||||
.mask {
|
||||
position: fixed; inset: 0; background: rgba(43,43,43,.45);
|
||||
display: flex; align-items: center; justify-content: center; z-index: 99; padding: 24px;
|
||||
}
|
||||
.modal {
|
||||
position: relative; width: 410px; background: #fffef8;
|
||||
border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
box-shadow: 6px 8px 0 rgba(0,0,0,.16); padding: 36px 34px 30px;
|
||||
transform: rotate(.5deg);
|
||||
}
|
||||
.modal .tape { top: -13px; left: 50%; margin-left: -46px; transform: rotate(2deg); }
|
||||
.modal h3 { font-size: 21px; font-weight: 800; }
|
||||
.modal .msub { font-size: 12.5px; color: #868e96; font-weight: 700; margin: 3px 0 16px; }
|
||||
.modal input {
|
||||
width: 100%; padding: 10px 14px; border: 2.5px solid #2b2b2b;
|
||||
border-radius: 255px 15px 225px 15px / 15px 225px 15px 255px;
|
||||
font-family: inherit; font-size: 14px; font-weight: 600; outline: none;
|
||||
margin-bottom: 12px; background: #fff;
|
||||
}
|
||||
.modal input:focus { background: #fff9db; }
|
||||
.modal .mrow { display: flex; gap: 10px; justify-content: flex-end; margin-top: 8px; }
|
||||
.modal .pwd-msg {
|
||||
margin-bottom: 12px; background: #ffe3e3; color: #c92a2a;
|
||||
padding: 9px 12px; font-weight: 700; font-size: 12.5px;
|
||||
border: 2.5px dashed #c92a2a;
|
||||
border-radius: 15px 255px 15px 255px / 255px 15px 255px 15px;
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.stats { grid-template-columns: repeat(2, 1fr); }
|
||||
th:nth-child(4), td:nth-child(4), th:nth-child(5), td:nth-child(5) { display: none; }
|
||||
.header .pin.r { display: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<!-- 登录界面 -->
|
||||
<div class="login-wrap" v-if="!loggedIn">
|
||||
<div class="login-card">
|
||||
<span class="tape"></span>
|
||||
<span class="pin">📌</span>
|
||||
<div class="emblem">37</div>
|
||||
<h2>文件服务器管理</h2>
|
||||
<div class="login-sub">37DU 内网文件服务器 · 管理台</div>
|
||||
<div class="login-field">
|
||||
<input type="text" v-model="username" placeholder="账号" @keyup.enter="login">
|
||||
</div>
|
||||
<div class="login-field">
|
||||
<input :type="showPwd ? 'text' : 'password'" v-model="password" placeholder="密码" @keyup.enter="login">
|
||||
<span class="eye" @click="showPwd = !showPwd">{{ showPwd ? '🙈' : '👁' }}</span>
|
||||
</div>
|
||||
<button class="btn btn-primary" @click="login" :disabled="loggingIn">{{ loggingIn ? "登录中…" : "登 录" }}</button>
|
||||
<div class="login-hint">初始账号 puddy / 123456,登录后请尽快修改密码</div>
|
||||
<div class="login-msg" v-if="loginMsg">{{ loginMsg }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主界面 -->
|
||||
<template v-else>
|
||||
<div class="header">
|
||||
<span class="pin l">📌</span>
|
||||
<span class="pin r">📌</span>
|
||||
<div class="brand">
|
||||
<div class="emblem">37</div>
|
||||
<div>
|
||||
<h1>文件服务器管理 <span class="squiggle"></span></h1>
|
||||
<div class="sub">{{ baseUrl }} · 登录用户:{{ tokenUser }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="btn" @click="openPwdModal">改密码</button>
|
||||
<button class="btn" @click="logout">退出</button>
|
||||
<button class="btn btn-primary" @click="load">↻ 刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat"><span class="tape"></span><div class="k">文件数</div><div class="v">{{ totalCount }}</div></div>
|
||||
<div class="stat"><span class="tape"></span><div class="k">总大小</div><div class="v">{{ totalSizeText }}</div></div>
|
||||
<div class="stat"><span class="tape"></span><div class="k">总下载</div><div class="v">{{ totalDownloads }}</div></div>
|
||||
<div class="stat"><span class="tape"></span><div class="k">最近上传</div><div class="v" style="font-size:15px;line-height:1.4">{{ lastUploadText }}</div></div>
|
||||
</div>
|
||||
|
||||
<div class="toolbar">
|
||||
<input type="text" v-model="keyword" placeholder="搜索文件名…">
|
||||
<label class="btn btn-success upload-btn">
|
||||
⬆ 上传文件
|
||||
<input type="file" multiple @change="onFilesPicked">
|
||||
</label>
|
||||
<span v-if="uploading" class="tag">上传 {{ uploadIdx }}/{{ uploadTotal }} {{ uploadPercent }}%</span>
|
||||
<span class="hint" style="flex:1"></span>
|
||||
<span class="hint">点击表头排序 · 元数据存 MySQL</span>
|
||||
</div>
|
||||
|
||||
<div class="status-bar" :class="statusClass">{{ statusMsg }}</div>
|
||||
|
||||
<div class="main">
|
||||
<div class="loading" v-if="loading"><span class="pen">✏️</span> 翻本子中…</div>
|
||||
<div class="card" v-else>
|
||||
<span class="tape"></span>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:42px">#</th>
|
||||
<th @click="sortBy('filename')">文件名<span class="arrow" v-if="sortKey==='filename'">{{ sortDir===1?'▲':'▼' }}</span></th>
|
||||
<th style="width:90px" @click="sortBy('size')">大小<span class="arrow" v-if="sortKey==='size'">{{ sortDir===1?'▲':'▼' }}</span></th>
|
||||
<th style="width:160px" @click="sortBy('created')">上传时间<span class="arrow" v-if="sortKey==='created'">{{ sortDir===1?'▲':'▼' }}</span></th>
|
||||
<th style="width:90px">上传人</th>
|
||||
<th style="width:70px" @click="sortBy('downloads')">下载<span class="arrow" v-if="sortKey==='downloads'">{{ sortDir===1?'▲':'▼' }}</span></th>
|
||||
<th style="width:190px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody v-if="sortedFiles.length">
|
||||
<tr v-for="(f, i) in sortedFiles" :key="f.fid">
|
||||
<td style="color:#adb5bd;font-weight:800">{{ i + 1 }}</td>
|
||||
<td>
|
||||
<div class="fname-cell">
|
||||
<span class="filename">{{ f.filename }}</span>
|
||||
<span class="fname-meta">
|
||||
<span class="ext">{{ extOf(f.filename) }}</span>
|
||||
<span class="sha" :title="f.sha256">{{ shortSha(f.sha256) }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>{{ fmtSize(f.size) }}</td>
|
||||
<td>{{ fmtTime(f.created) }}</td>
|
||||
<td><span class="who" :class="f.uploader==='center'?'center':''">{{ whoLabel(f.uploader) }}</span></td>
|
||||
<td>{{ f.downloads || 0 }}</td>
|
||||
<td>
|
||||
<a class="dl" :href="downloadUrl(f)" target="_blank" rel="noopener">下载</a>
|
||||
<a class="cp" href="javascript:;" @click="copyLink(f)">复制</a>
|
||||
<a class="rm" href="javascript:;" @click="remove(f)">删除</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tbody v-else>
|
||||
<tr><td colspan="7">
|
||||
<div class="empty">
|
||||
<svg width="150" height="120" viewBox="0 0 150 120" fill="none" stroke="#2b2b2b" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 36 Q22 31 27 31 L56 31 L67 41 L129 41"/>
|
||||
<path d="M15 41 L135 41 Q139 42 139 46 L139 96 Q139 101 134 101 L16 101 Q11 101 11 96 L11 46 Q11 42 15 41 Z"/>
|
||||
<path d="M18 51 L132 51" stroke="#ffd43b" stroke-width="5" opacity=".65"/>
|
||||
<path d="M96 22 L110 13"/>
|
||||
<path d="M112 28 L128 20"/>
|
||||
<path d="M86 14 L92 4"/>
|
||||
<path d="M102 8 l13 8 -6 10 -13 -8 z" transform="rotate(-12 108 17)"/>
|
||||
<path d="M82 4 l10 6 -5 8 -10 -6 z" transform="rotate(-30 87 11)"/>
|
||||
</svg>
|
||||
<div class="et">📭 暂无文件{{ keyword ? '(与搜索条件匹配)' : '' }}</div>
|
||||
</div>
|
||||
</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="footer">
|
||||
<span>37DU <span class="dot">✏️</span> 内网文件服务器</span>
|
||||
<span>DOODLE ADMIN v2.2</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改密码弹窗 -->
|
||||
<div class="mask" v-if="showPwdModal">
|
||||
<div class="modal">
|
||||
<span class="tape"></span>
|
||||
<h3>修改密码</h3>
|
||||
<div class="msub">修改后需重新登录</div>
|
||||
<div class="pwd-msg" v-if="pwdMsg">{{ pwdMsg }}</div>
|
||||
<input type="password" v-model="oldPwd" placeholder="旧密码">
|
||||
<input type="password" v-model="newPwd" placeholder="新密码(至少 6 位)">
|
||||
<input type="password" v-model="newPwd2" placeholder="确认新密码">
|
||||
<div class="mrow">
|
||||
<button class="btn" @click="closePwdModal">取消</button>
|
||||
<button class="btn btn-primary" @click="changePwd" :disabled="savingPwd">{{ savingPwd ? "保存中…" : "保存" }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<script src="/vue.global.prod.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+20
-204
@@ -1,224 +1,40 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器(独立 FastAPI,端口 8802)。
|
||||
"""内网文件服务器入口(组装层)。
|
||||
|
||||
职责:存放大型文件(壳子更新包、Chrome 安装包等),供执行机内网直连下载。
|
||||
设计:中心机只存本服务器返回的内网直链,不转发大包。
|
||||
职责:lifespan 初始化存储(自动建表)+ 启动心跳上报,装配各领域路由。
|
||||
- core/config.py 配置(.env)
|
||||
- core/auth.py 鉴权(X-API-Token / 管理会话)
|
||||
- core/store.py 存储(文件落盘 + MySQL 元数据,未配库时 JSON 兜底)
|
||||
- core/heartbeat.py 中心机心跳上报
|
||||
- apis/ 路由子包(meta / files / admin)
|
||||
|
||||
接口鉴权:
|
||||
- 上传 / 删除 / 列表需 HTTP 头 `X-API-Token`(值 = FILESERVER_TOKEN)
|
||||
- 下载开放(内网环境,客户端拿到链接直接下)
|
||||
|
||||
运行(桌面端,cwd = desktop/):python -m fileserver.main
|
||||
运行(cwd = desktop/,模块搜索根 = desktop/):
|
||||
python -m fileserver.main
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, Header, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi import FastAPI
|
||||
|
||||
from fileserver.core import config
|
||||
|
||||
log = logging.getLogger("fileserver.heartbeat")
|
||||
|
||||
_DATA_DIR = config.DATA_DIR
|
||||
_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
_STATUS_DIR = _DATA_DIR / ".meta"
|
||||
_STATUS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 进程启动时间(心跳上报 uptime 用)
|
||||
_START_TS = time.time()
|
||||
|
||||
|
||||
def _require_token(x_api_token: str = "") -> None:
|
||||
"""校验管理 token;未配置 token 时放行(纯开发模式)。"""
|
||||
if not config.TOKEN:
|
||||
return
|
||||
if x_api_token.strip() != config.TOKEN:
|
||||
raise HTTPException(401, "无效的文件服务器令牌")
|
||||
|
||||
|
||||
def _safe_link_name(name: str) -> str:
|
||||
"""下载文件名清洗:仅保留安全 basename,去除路径与危险字符。"""
|
||||
name = Path(name or "").name
|
||||
return re.sub(r"[^\w.\-]", "_", name)[:200]
|
||||
|
||||
|
||||
def _store_path(fid: str) -> Path:
|
||||
return _DATA_DIR / fid
|
||||
|
||||
|
||||
def _file_meta(fid: str) -> dict:
|
||||
"""读 .meta/{fid}.json;缺失返回空 dict。"""
|
||||
mf = _STATUS_DIR / f"{fid}.json"
|
||||
if not mf.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(mf.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
# ==================== 中心机心跳上报(主动上报状态,供中心机监控在线/离线) ====================
|
||||
def _server_status() -> dict:
|
||||
"""收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。"""
|
||||
meta_files = list(_STATUS_DIR.glob("*.json"))
|
||||
total = 0
|
||||
for mf in meta_files:
|
||||
try:
|
||||
m = json.loads(mf.read_text(encoding="utf-8"))
|
||||
total += int(m.get("size") or 0)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
hostname = socket.gethostname()
|
||||
ip = ""
|
||||
try:
|
||||
ip = socket.gethostbyname(hostname)
|
||||
except OSError: # noqa: BLE001
|
||||
pass
|
||||
return {
|
||||
"host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根)
|
||||
"base_url": config.BASE_URL,
|
||||
"hostname": hostname,
|
||||
"ip": ip,
|
||||
"port": config.PORT,
|
||||
"file_count": len(meta_files),
|
||||
"total_size": total,
|
||||
"version": "37du-fileserver",
|
||||
"uptime_sec": int(time.time() - _START_TS),
|
||||
}
|
||||
|
||||
|
||||
def _post_heartbeat() -> bool:
|
||||
"""单次上报心跳到中心机;成功返回 True。"""
|
||||
payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat",
|
||||
data=payload, method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status < 400
|
||||
except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理
|
||||
log.warning("心跳上报失败:%s", exc)
|
||||
return False
|
||||
|
||||
|
||||
def _heartbeat_loop() -> None:
|
||||
"""后台线程:周期向中心机上报心跳。未配置 CONTROLPLANE_URL 则直接退出。
|
||||
|
||||
每次上报最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
log.info("未配置 CONTROLPLANE_URL,跳过心跳上报")
|
||||
return
|
||||
while True:
|
||||
try:
|
||||
ok = False
|
||||
for _i in range(3):
|
||||
if _post_heartbeat():
|
||||
ok = True
|
||||
break
|
||||
if not ok:
|
||||
log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL)
|
||||
except Exception: # noqa: BLE001 上报异常不拖垮文件服务
|
||||
log.exception("心跳上报线程异常")
|
||||
time.sleep(max(5, config.HEARTBEAT_INTERVAL))
|
||||
from fileserver.core import config, store
|
||||
from fileserver.core.heartbeat import start as start_heartbeat
|
||||
from fileserver.apis import admin, files, meta
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _lifespan(_app: FastAPI):
|
||||
threading.Thread(target=_heartbeat_loop, daemon=True,
|
||||
name="fileserver-heartbeat").start()
|
||||
store.init() # 建数据目录 + DB 模式自动建表
|
||||
start_heartbeat() # 中心机心跳上报(daemon 线程)
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du 内网文件服务器", lifespan=_lifespan)
|
||||
|
||||
|
||||
@app.post("/api/upload")
|
||||
async def api_upload(upload: UploadFile,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传文件:存唯一 id,返回 {id, filename, sha256, size, url}。"""
|
||||
_require_token(x_api_token)
|
||||
raw = await upload.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
fid = secrets.token_urlsafe(12)
|
||||
origin = _safe_link_name(upload.filename or "")
|
||||
size = len(raw)
|
||||
sha = hashlib.sha256(raw).hexdigest()
|
||||
(_DATA_DIR / fid).write_bytes(raw)
|
||||
(_STATUS_DIR / f"{fid}.json").write_text(
|
||||
json.dumps({"fid": fid, "filename": origin, "sha256": sha, "size": size,
|
||||
"created": time.time()},
|
||||
ensure_ascii=False), encoding="utf-8")
|
||||
url = f"{config.BASE_URL}/files/{fid}?dl={origin}"
|
||||
return {"ok": True, "id": fid, "filename": origin, "sha256": sha,
|
||||
"size": size, "url": url}
|
||||
|
||||
|
||||
@app.get("/api/files")
|
||||
def api_files(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""列表已上传文件(管理)。"""
|
||||
_require_token(x_api_token)
|
||||
items = []
|
||||
for mf in sorted(_STATUS_DIR.glob("*.json")):
|
||||
m = _file_meta(mf.stem)
|
||||
if m:
|
||||
m["url"] = f"{config.BASE_URL}/files/{m['fid']}?dl={m['filename']}"
|
||||
items.append(m)
|
||||
return {"files": items}
|
||||
|
||||
|
||||
@app.delete("/api/files/{fid}")
|
||||
def api_delete(fid: str, x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除文件与元数据(管理)。"""
|
||||
_require_token(x_api_token)
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", fid):
|
||||
raise HTTPException(400, "非法的文件 id")
|
||||
removed = False
|
||||
p = _store_path(fid)
|
||||
if p.is_file():
|
||||
p.unlink(missing_ok=True)
|
||||
removed = True
|
||||
(_STATUS_DIR / f"{fid}.json").unlink(missing_ok=True)
|
||||
return {"ok": True, "removed": removed, "id": fid}
|
||||
|
||||
|
||||
@app.get("/files/{fid}")
|
||||
def api_download(fid: str):
|
||||
"""开放下载(内网直链);?dl=文件名 时以该名 attachment 落盘。"""
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", fid):
|
||||
raise HTTPException(404, "文件不存在")
|
||||
p = _store_path(fid)
|
||||
if not p.is_file():
|
||||
raise HTTPException(404, "文件不存在")
|
||||
m = _file_meta(fid)
|
||||
default_name = m.get("filename") or fid
|
||||
return FileResponse(p, filename=default_name, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index() -> dict:
|
||||
"""健康检查(无鉴权)。"""
|
||||
return {"ok": True, "service": "37du内网文件服务器",
|
||||
"files": len(list(_STATUS_DIR.glob("*.json")))}
|
||||
app = FastAPI(title="37du 内网文件服务器", version=config.VERSION, lifespan=_lifespan)
|
||||
app.include_router(meta.router)
|
||||
app.include_router(files.router)
|
||||
app.include_router(admin.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.PORT)
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.PORT)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
python-multipart>=0.0.9
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
python-multipart>=0.0.9
|
||||
PyMySQL>=1.1
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
@echo off
|
||||
REM ===== 37du intranet file server build script (run on Windows) =====
|
||||
REM prereq: desktop/.venv with fastapi uvicorn python-multipart pyinstaller
|
||||
REM usage: run inside desktop\ directory with project .venv
|
||||
|
||||
setlocal
|
||||
cd /d %~dp0\..\..
|
||||
set PY=..\.venv\Scripts\python.exe
|
||||
if not exist %PY% (
|
||||
echo [err] PYTHON NOT FOUND: %PY% - run from desktop\ and ensure .venv exists
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo [1/3] building exe ...
|
||||
%PY% -m PyInstaller fileserver\tools\37du-fileserver.spec ^
|
||||
--distpath fileserver\dist-exe ^
|
||||
--workpath fileserver\build-exe ^
|
||||
--noconfirm
|
||||
if errorlevel 1 (echo [err] BUILD FAILED & pause & exit /b 1)
|
||||
|
||||
echo [2/3] assembling deploy dir ...
|
||||
set DEP=fileserver\dist-exe\fileserver
|
||||
if not exist %DEP% mkdir %DEP%
|
||||
REM copy .env next to exe (contains FILESERVER_BASE_URL pointing to intranet)
|
||||
copy /y fileserver\.env %DEP%\.env >nul
|
||||
move /y fileserver\dist-exe\37du-fileserver.exe %DEP%\37du-fileserver.exe >nul
|
||||
|
||||
echo [3/3] done.
|
||||
echo deploy dir: %DEP%
|
||||
echo deploy to 172.30.35.135: adjust FILESERVER_BASE_URL/TOKEN in .env, then run install_autostart.bat
|
||||
pause
|
||||
@@ -1,47 +0,0 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 一键配置:开放端口 + 安装开机自启 =====
|
||||
REM 用法:在文件服务器部署目录(含 37du-fileserver.exe、start_server.bat、.env)内
|
||||
REM 以管理员身份双击运行一次(放行防火墙需管理员权限)
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist "%~dp037du-fileserver.exe" (
|
||||
echo [err] 未找到 37du-fileserver.exe,请把本脚本拷贝到 exe 同目录再运行
|
||||
pause & exit /b 1
|
||||
)
|
||||
if not exist "%~dp0start_server.bat" (
|
||||
echo [err] 未找到 start_server.bat,请与 exe 放在同一目录
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo ============================================
|
||||
echo [1/2] 开放防火墙端口 8802(TCP)...
|
||||
echo ============================================
|
||||
netsh advfirewall firewall show rule name="37du-FileServer-8802" >nul 2>&1
|
||||
if not errorlevel 1 (
|
||||
echo 规则已存在,跳过创建。
|
||||
) else (
|
||||
netsh advfirewall firewall add rule name="37du-FileServer-8802" ^
|
||||
dir=in action=allow protocol=TCP localport=8802 profile=any >nul
|
||||
if errorlevel 1 (
|
||||
echo [err] 放行端口失败(请以管理员身份运行本脚本)
|
||||
pause & exit /b 1
|
||||
) else (
|
||||
echo [ok] TCP 8802 已放行(内网 172.30.35.135:8802 可访问)。
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo ============================================
|
||||
echo [2/2] 安装开机自启计划任务...
|
||||
echo ============================================
|
||||
schtasks /create /tn "37du-FileServer" /tr "\"%~dp0start_server.bat\"" ^
|
||||
/sc onlogon /rl limited /f >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [err] 自启安装失败(可能被安全软件拦截)
|
||||
pause & exit /b 1
|
||||
)
|
||||
|
||||
echo [ok] 完成:端口已放行,登录 Windows 自动启动内网文件服务器。
|
||||
echo 验证:http://127.0.0.1:8802 (返回 ok 即服务在线)
|
||||
pause
|
||||
@@ -1,17 +0,0 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 启动脚本 =====
|
||||
REM 由计划任务(开机自启)调用:先启动本机内网文件服务器,并记录启动日志
|
||||
REM 请确保本脚本与 37du-fileserver.exe、.env 位于同一目录
|
||||
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
REM 若已在运行则跳过(避免自启+手动重复起)
|
||||
tasklist /fi "imagename eq 37du-fileserver.exe" 2>nul | find /i "37du-fileserver.exe" >nul && (
|
||||
echo [%date% %time%] 已运行,跳过 >> fileserver.start.log
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
echo [%date% %time%] starting >> fileserver.start.log
|
||||
start "" "%~dp037du-fileserver.exe"
|
||||
exit /b 0
|
||||
@@ -1,7 +0,0 @@
|
||||
@echo off
|
||||
REM ===== 37du 内网文件服务器 卸载开机自启 =====
|
||||
setlocal
|
||||
echo 正在删除 37du-FileServer 计划任务 ...
|
||||
schtasks /delete /tn "37du-FileServer" /f >nul 2>&1
|
||||
echo [ok] 已卸载开机自启(服务文件未删除,可手动运行 exe 启动)。
|
||||
pause
|
||||
Reference in New Issue
Block a user