Upload 2 files
Browse files- Dockerfile +25 -0
- app/run.py +607 -0
Dockerfile
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
| 2 |
+
|
| 3 |
+
ARG BUILD_SHA
|
| 4 |
+
ARG BUILD_TAG
|
| 5 |
+
|
| 6 |
+
ENV BUILD_SHA=${BUILD_SHA}
|
| 7 |
+
ENV BUILD_TAG=${BUILD_TAG}
|
| 8 |
+
ENV TZ=Asia/Shanghai
|
| 9 |
+
ENV PYTHONUNBUFFERED=1
|
| 10 |
+
ENV HOST=0.0.0.0
|
| 11 |
+
ENV PORT=7860
|
| 12 |
+
ENV CONFIG_PATH=/app/config/quark_config.json
|
| 13 |
+
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
|
| 16 |
+
COPY . /app
|
| 17 |
+
|
| 18 |
+
RUN pip install --no-cache-dir -r requirements.txt && \
|
| 19 |
+
echo "{\"BUILD_SHA\":\"$BUILD_SHA\", \"BUILD_TAG\":\"$BUILD_TAG\"}" > build.json && \
|
| 20 |
+
python ./app/_clean_plugins.py && \
|
| 21 |
+
rm ./app/_clean_plugins.py
|
| 22 |
+
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
CMD ["python", "./app/run.py"]
|
app/run.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# !/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
from flask import (
|
| 4 |
+
json,
|
| 5 |
+
Flask,
|
| 6 |
+
url_for,
|
| 7 |
+
session,
|
| 8 |
+
jsonify,
|
| 9 |
+
request,
|
| 10 |
+
redirect,
|
| 11 |
+
Response,
|
| 12 |
+
render_template,
|
| 13 |
+
send_from_directory,
|
| 14 |
+
stream_with_context,
|
| 15 |
+
)
|
| 16 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 17 |
+
from apscheduler.triggers.cron import CronTrigger
|
| 18 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 19 |
+
from sdk.cloudsaver import CloudSaver
|
| 20 |
+
from sdk.pansou import PanSou
|
| 21 |
+
from datetime import timedelta
|
| 22 |
+
import subprocess
|
| 23 |
+
import requests
|
| 24 |
+
import hashlib
|
| 25 |
+
import logging
|
| 26 |
+
import traceback
|
| 27 |
+
import base64
|
| 28 |
+
import sys
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
|
| 32 |
+
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
| 33 |
+
sys.path.insert(0, parent_dir)
|
| 34 |
+
from quark_auto_save import Quark, Config, MagicRename
|
| 35 |
+
|
| 36 |
+
print(
|
| 37 |
+
r"""
|
| 38 |
+
____ ___ _____
|
| 39 |
+
/ __ \ / | / ___/
|
| 40 |
+
/ / / / / /| | \__ \
|
| 41 |
+
/ /_/ / / ___ |___/ /
|
| 42 |
+
\___\_\/_/ |_/____/
|
| 43 |
+
|
| 44 |
+
-- Quark-Auto-Save --
|
| 45 |
+
"""
|
| 46 |
+
)
|
| 47 |
+
sys.stdout.flush()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_app_ver():
|
| 51 |
+
"""获取应用版本"""
|
| 52 |
+
try:
|
| 53 |
+
with open("build.json", "r") as f:
|
| 54 |
+
build_info = json.loads(f.read())
|
| 55 |
+
BUILD_SHA = build_info["BUILD_SHA"]
|
| 56 |
+
BUILD_TAG = build_info["BUILD_TAG"]
|
| 57 |
+
except Exception as e:
|
| 58 |
+
BUILD_SHA = os.getenv("BUILD_SHA", "")
|
| 59 |
+
BUILD_TAG = os.getenv("BUILD_TAG", "")
|
| 60 |
+
if BUILD_TAG[:1] == "v":
|
| 61 |
+
return BUILD_TAG
|
| 62 |
+
elif BUILD_SHA:
|
| 63 |
+
return f"{BUILD_TAG}({BUILD_SHA[:7]})"
|
| 64 |
+
else:
|
| 65 |
+
return "dev"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# 文件路径
|
| 69 |
+
PYTHON_PATH = "python3" if os.path.exists("/usr/bin/python3") else "python"
|
| 70 |
+
SCRIPT_PATH = os.environ.get("SCRIPT_PATH", "./quark_auto_save.py")
|
| 71 |
+
CONFIG_PATH = os.environ.get("CONFIG_PATH", "./config/quark_config.json")
|
| 72 |
+
PLUGIN_FLAGS = os.environ.get("PLUGIN_FLAGS", "")
|
| 73 |
+
DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
|
| 74 |
+
HOST = os.environ.get("HOST", "0.0.0.0")
|
| 75 |
+
PORT = int(os.environ.get("PORT", 7860))
|
| 76 |
+
TASK_TIMEOUT = int(os.environ.get("TASK_TIMEOUT", 1800))
|
| 77 |
+
|
| 78 |
+
config_data = {}
|
| 79 |
+
task_plugins_config_default = {}
|
| 80 |
+
|
| 81 |
+
app = Flask(__name__)
|
| 82 |
+
app.config["APP_VERSION"] = get_app_ver()
|
| 83 |
+
app.secret_key = os.environ.get("SECRET_KEY", "change-me-in-production")
|
| 84 |
+
app.config["SESSION_COOKIE_NAME"] = "QUARK_AUTO_SAVE_SESSION"
|
| 85 |
+
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=31)
|
| 86 |
+
app.json.ensure_ascii = False
|
| 87 |
+
app.json.sort_keys = False
|
| 88 |
+
app.jinja_env.variable_start_string = "[["
|
| 89 |
+
app.jinja_env.variable_end_string = "]]"
|
| 90 |
+
|
| 91 |
+
scheduler = BackgroundScheduler()
|
| 92 |
+
logging.basicConfig(
|
| 93 |
+
level=logging.DEBUG if DEBUG else logging.INFO,
|
| 94 |
+
format="[%(asctime)s][%(levelname)s] %(message)s",
|
| 95 |
+
datefmt="%m-%d %H:%M:%S",
|
| 96 |
+
)
|
| 97 |
+
# 过滤werkzeug日志输出
|
| 98 |
+
if not DEBUG:
|
| 99 |
+
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
| 100 |
+
logging.getLogger("apscheduler").setLevel(logging.ERROR)
|
| 101 |
+
sys.modules["flask.cli"].show_server_banner = lambda *x: None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def gen_md5(string):
|
| 105 |
+
md5 = hashlib.md5()
|
| 106 |
+
md5.update(string.encode("utf-8"))
|
| 107 |
+
return md5.hexdigest()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_login_token():
|
| 111 |
+
username = config_data["webui"]["username"]
|
| 112 |
+
password = config_data["webui"]["password"]
|
| 113 |
+
return gen_md5(f"token{username}{password}+-*/")[8:24]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def is_login():
|
| 117 |
+
login_token = get_login_token()
|
| 118 |
+
if session.get("token") == login_token or request.args.get("token") == login_token:
|
| 119 |
+
return True
|
| 120 |
+
else:
|
| 121 |
+
return False
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# 设置icon
|
| 125 |
+
@app.route("/favicon.ico")
|
| 126 |
+
def favicon():
|
| 127 |
+
return send_from_directory(
|
| 128 |
+
os.path.join(app.root_path, "static"),
|
| 129 |
+
"favicon.ico",
|
| 130 |
+
mimetype="image/vnd.microsoft.icon",
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# 登录页面
|
| 135 |
+
@app.route("/login", methods=["GET", "POST"])
|
| 136 |
+
def login():
|
| 137 |
+
if request.method == "POST":
|
| 138 |
+
username = config_data["webui"]["username"]
|
| 139 |
+
password = config_data["webui"]["password"]
|
| 140 |
+
# 验证用户名和密码
|
| 141 |
+
if (username == request.form.get("username")) and (
|
| 142 |
+
password == request.form.get("password")
|
| 143 |
+
):
|
| 144 |
+
logging.info(f">>> 用户 {username} 登录成功")
|
| 145 |
+
session.permanent = True
|
| 146 |
+
session["token"] = get_login_token()
|
| 147 |
+
return redirect(url_for("index"))
|
| 148 |
+
else:
|
| 149 |
+
logging.info(f">>> 用户 {username} 登录失败")
|
| 150 |
+
return render_template("login.html", message="登录失败")
|
| 151 |
+
|
| 152 |
+
if is_login():
|
| 153 |
+
return redirect(url_for("index"))
|
| 154 |
+
return render_template("login.html", error=None)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# 退出登录
|
| 158 |
+
@app.route("/logout")
|
| 159 |
+
def logout():
|
| 160 |
+
session.pop("token", None)
|
| 161 |
+
return redirect(url_for("login"))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# 管理页面
|
| 165 |
+
@app.route("/")
|
| 166 |
+
def index():
|
| 167 |
+
if not is_login():
|
| 168 |
+
return redirect(url_for("login"))
|
| 169 |
+
return render_template(
|
| 170 |
+
"index.html", version=app.config["APP_VERSION"], plugin_flags=PLUGIN_FLAGS
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# 获取配置数据
|
| 175 |
+
@app.route("/data")
|
| 176 |
+
def get_data():
|
| 177 |
+
if not is_login():
|
| 178 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 179 |
+
data = Config.read_json(CONFIG_PATH)
|
| 180 |
+
del data["webui"]
|
| 181 |
+
data["api_token"] = get_login_token()
|
| 182 |
+
data["task_plugins_config_default"] = task_plugins_config_default
|
| 183 |
+
return jsonify({"success": True, "data": data})
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# 更新数据
|
| 187 |
+
@app.route("/update", methods=["POST"])
|
| 188 |
+
def update():
|
| 189 |
+
global config_data
|
| 190 |
+
if not is_login():
|
| 191 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 192 |
+
dont_save_keys = ["task_plugins_config_default", "api_token"]
|
| 193 |
+
for key, value in request.json.items():
|
| 194 |
+
if key not in dont_save_keys:
|
| 195 |
+
config_data.update({key: value})
|
| 196 |
+
Config.write_json(CONFIG_PATH, config_data)
|
| 197 |
+
# 重新加载任务
|
| 198 |
+
if reload_tasks():
|
| 199 |
+
logging.info(f">>> 配置更新成功")
|
| 200 |
+
return jsonify({"success": True, "message": "配置更新成功"})
|
| 201 |
+
else:
|
| 202 |
+
logging.info(f">>> 配置更新失败")
|
| 203 |
+
return jsonify({"success": False, "message": "配置更新失败"})
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# 处理运行脚本请求
|
| 207 |
+
@app.route("/run_script_now", methods=["POST"])
|
| 208 |
+
def run_script_now():
|
| 209 |
+
if not is_login():
|
| 210 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 211 |
+
tasklist = request.json.get("tasklist", [])
|
| 212 |
+
command = [PYTHON_PATH, "-u", SCRIPT_PATH, CONFIG_PATH]
|
| 213 |
+
logging.info(
|
| 214 |
+
f">>> 手动运行任务 [{tasklist[0].get('taskname') if len(tasklist)>0 else 'ALL'}] 开始执行..."
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
def generate_output():
|
| 218 |
+
# 设置环境变量
|
| 219 |
+
process_env = os.environ.copy()
|
| 220 |
+
process_env["PYTHONIOENCODING"] = "utf-8"
|
| 221 |
+
if request.json.get("quark_test"):
|
| 222 |
+
process_env["QUARK_TEST"] = "true"
|
| 223 |
+
process_env["COOKIE"] = json.dumps(
|
| 224 |
+
request.json.get("cookie", []), ensure_ascii=False
|
| 225 |
+
)
|
| 226 |
+
process_env["PUSH_CONFIG"] = json.dumps(
|
| 227 |
+
request.json.get("push_config", {}), ensure_ascii=False
|
| 228 |
+
)
|
| 229 |
+
if tasklist:
|
| 230 |
+
process_env["TASKLIST"] = json.dumps(tasklist, ensure_ascii=False)
|
| 231 |
+
process = subprocess.Popen(
|
| 232 |
+
command,
|
| 233 |
+
stdout=subprocess.PIPE,
|
| 234 |
+
stderr=subprocess.STDOUT,
|
| 235 |
+
universal_newlines=True,
|
| 236 |
+
encoding="utf-8",
|
| 237 |
+
errors="replace",
|
| 238 |
+
bufsize=1,
|
| 239 |
+
env=process_env,
|
| 240 |
+
)
|
| 241 |
+
try:
|
| 242 |
+
for line in iter(process.stdout.readline, ""):
|
| 243 |
+
logging.info(line.strip())
|
| 244 |
+
yield f"data: {line}\n\n"
|
| 245 |
+
yield "data: [DONE]\n\n"
|
| 246 |
+
finally:
|
| 247 |
+
process.stdout.close()
|
| 248 |
+
process.wait()
|
| 249 |
+
|
| 250 |
+
return Response(
|
| 251 |
+
stream_with_context(generate_output()),
|
| 252 |
+
content_type="text/event-stream;charset=utf-8",
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@app.route("/task_suggestions")
|
| 257 |
+
def get_task_suggestions():
|
| 258 |
+
if not is_login():
|
| 259 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 260 |
+
query = request.args.get("q", "").lower()
|
| 261 |
+
deep = request.args.get("d", "").lower()
|
| 262 |
+
net_data = config_data.get("source", {}).get("net", {})
|
| 263 |
+
cs_data = config_data.get("source", {}).get("cloudsaver", {})
|
| 264 |
+
ps_data = config_data.get("source", {}).get("pansou", {})
|
| 265 |
+
|
| 266 |
+
def net_search():
|
| 267 |
+
if str(net_data.get("enable", "true")).lower() != "false":
|
| 268 |
+
base_url = base64.b64decode("aHR0cHM6Ly9zLjkxNzc4OC54eXo=").decode()
|
| 269 |
+
url = f"{base_url}/task_suggestions?q={query}&d={deep}"
|
| 270 |
+
response = requests.get(url)
|
| 271 |
+
return response.json()
|
| 272 |
+
return []
|
| 273 |
+
|
| 274 |
+
def cs_search():
|
| 275 |
+
if (
|
| 276 |
+
cs_data.get("server")
|
| 277 |
+
and cs_data.get("username")
|
| 278 |
+
and cs_data.get("password")
|
| 279 |
+
):
|
| 280 |
+
cs = CloudSaver(cs_data.get("server"))
|
| 281 |
+
cs.set_auth(
|
| 282 |
+
cs_data.get("username", ""),
|
| 283 |
+
cs_data.get("password", ""),
|
| 284 |
+
cs_data.get("token", ""),
|
| 285 |
+
)
|
| 286 |
+
search = cs.auto_login_search(query)
|
| 287 |
+
if search.get("success"):
|
| 288 |
+
if search.get("new_token"):
|
| 289 |
+
cs_data["token"] = search.get("new_token")
|
| 290 |
+
Config.write_json(CONFIG_PATH, config_data)
|
| 291 |
+
search_results = cs.clean_search_results(search.get("data"))
|
| 292 |
+
return search_results
|
| 293 |
+
return []
|
| 294 |
+
|
| 295 |
+
def ps_search():
|
| 296 |
+
if ps_data.get("server"):
|
| 297 |
+
ps = PanSou(ps_data.get("server"))
|
| 298 |
+
return ps.search(query, deep == "1")
|
| 299 |
+
return []
|
| 300 |
+
|
| 301 |
+
try:
|
| 302 |
+
search_results = []
|
| 303 |
+
with ThreadPoolExecutor(max_workers=3) as executor:
|
| 304 |
+
features = []
|
| 305 |
+
features.append(executor.submit(net_search))
|
| 306 |
+
features.append(executor.submit(cs_search))
|
| 307 |
+
features.append(executor.submit(ps_search))
|
| 308 |
+
for future in as_completed(features):
|
| 309 |
+
result = future.result()
|
| 310 |
+
search_results.extend(result)
|
| 311 |
+
|
| 312 |
+
# 按时间排序并去重
|
| 313 |
+
results = []
|
| 314 |
+
link_array = []
|
| 315 |
+
search_results.sort(key=lambda x: x.get("datetime", ""), reverse=True)
|
| 316 |
+
for item in search_results:
|
| 317 |
+
url = item.get("shareurl", "")
|
| 318 |
+
if url != "" and url not in link_array:
|
| 319 |
+
link_array.append(url)
|
| 320 |
+
results.append(item)
|
| 321 |
+
|
| 322 |
+
return jsonify({"success": True, "data": results})
|
| 323 |
+
except Exception as e:
|
| 324 |
+
return jsonify({"success": True, "message": f"error: {str(e)}"})
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@app.route("/get_share_detail", methods=["POST"])
|
| 328 |
+
def get_share_detail():
|
| 329 |
+
if not is_login():
|
| 330 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 331 |
+
shareurl = request.json.get("shareurl", "")
|
| 332 |
+
stoken = request.json.get("stoken", "")
|
| 333 |
+
account = Quark()
|
| 334 |
+
pwd_id, passcode, pdir_fid, paths = account.extract_url(shareurl)
|
| 335 |
+
if not stoken:
|
| 336 |
+
get_stoken = account.get_stoken(pwd_id, passcode)
|
| 337 |
+
if get_stoken.get("status") == 200:
|
| 338 |
+
stoken = get_stoken["data"]["stoken"]
|
| 339 |
+
else:
|
| 340 |
+
return jsonify(
|
| 341 |
+
{"success": False, "data": {"error": get_stoken.get("message")}}
|
| 342 |
+
)
|
| 343 |
+
share_detail = account.get_detail(
|
| 344 |
+
pwd_id, stoken, pdir_fid, _fetch_share=1, fetch_share_full_path=1
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if share_detail.get("code") != 0:
|
| 348 |
+
return jsonify(
|
| 349 |
+
{"success": False, "data": {"error": share_detail.get("message")}}
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
data = share_detail["data"]
|
| 353 |
+
data["paths"] = [
|
| 354 |
+
{"fid": i["fid"], "name": i["file_name"]}
|
| 355 |
+
for i in share_detail["data"].get("full_path", [])
|
| 356 |
+
] or paths
|
| 357 |
+
data["stoken"] = stoken
|
| 358 |
+
|
| 359 |
+
# 正则处理预览
|
| 360 |
+
def preview_regex(data):
|
| 361 |
+
task = request.json.get("task", {})
|
| 362 |
+
magic_regex = request.json.get("magic_regex", {})
|
| 363 |
+
mr = MagicRename(magic_regex)
|
| 364 |
+
mr.set_taskname(task.get("taskname", ""))
|
| 365 |
+
account = Quark(config_data["cookie"][0])
|
| 366 |
+
get_fids = account.get_fids([task.get("savepath", "")])
|
| 367 |
+
if get_fids:
|
| 368 |
+
dir_file_list = account.ls_dir(get_fids[0]["fid"])["data"]["list"]
|
| 369 |
+
dir_filename_list = [dir_file["file_name"] for dir_file in dir_file_list]
|
| 370 |
+
else:
|
| 371 |
+
dir_file_list = []
|
| 372 |
+
dir_filename_list = []
|
| 373 |
+
|
| 374 |
+
pattern, replace = mr.magic_regex_conv(
|
| 375 |
+
task.get("pattern", ""), task.get("replace", "")
|
| 376 |
+
)
|
| 377 |
+
for share_file in data["list"]:
|
| 378 |
+
search_pattern = (
|
| 379 |
+
task["update_subdir"]
|
| 380 |
+
if share_file["dir"] and task.get("update_subdir")
|
| 381 |
+
else pattern
|
| 382 |
+
)
|
| 383 |
+
if re.search(search_pattern, share_file["file_name"]):
|
| 384 |
+
# 文件名重命名,目录不重命名
|
| 385 |
+
file_name_re = (
|
| 386 |
+
share_file["file_name"]
|
| 387 |
+
if share_file["dir"]
|
| 388 |
+
else mr.sub(pattern, replace, share_file["file_name"])
|
| 389 |
+
)
|
| 390 |
+
if file_name_saved := mr.is_exists(
|
| 391 |
+
file_name_re,
|
| 392 |
+
dir_filename_list,
|
| 393 |
+
(task.get("ignore_extension") and not share_file["dir"]),
|
| 394 |
+
):
|
| 395 |
+
share_file["file_name_saved"] = file_name_saved
|
| 396 |
+
else:
|
| 397 |
+
share_file["file_name_re"] = file_name_re
|
| 398 |
+
|
| 399 |
+
# 文件列表排序
|
| 400 |
+
if re.search(r"\{I+\}", replace):
|
| 401 |
+
mr.set_dir_file_list(dir_file_list, replace)
|
| 402 |
+
mr.sort_file_list(data["list"])
|
| 403 |
+
|
| 404 |
+
if request.json.get("task"):
|
| 405 |
+
preview_regex(data)
|
| 406 |
+
|
| 407 |
+
return jsonify({"success": True, "data": data})
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@app.route("/get_savepath_detail")
|
| 411 |
+
def get_savepath_detail():
|
| 412 |
+
if not is_login():
|
| 413 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 414 |
+
account = Quark(config_data["cookie"][0])
|
| 415 |
+
paths = []
|
| 416 |
+
if path := request.args.get("path"):
|
| 417 |
+
path = re.sub(r"/+", "/", path)
|
| 418 |
+
if path == "/":
|
| 419 |
+
fid = 0
|
| 420 |
+
else:
|
| 421 |
+
dir_names = path.split("/")
|
| 422 |
+
if dir_names[0] == "":
|
| 423 |
+
dir_names.pop(0)
|
| 424 |
+
path_fids = []
|
| 425 |
+
current_path = ""
|
| 426 |
+
for dir_name in dir_names:
|
| 427 |
+
current_path += "/" + dir_name
|
| 428 |
+
path_fids.append(current_path)
|
| 429 |
+
if get_fids := account.get_fids(path_fids):
|
| 430 |
+
fid = get_fids[-1]["fid"]
|
| 431 |
+
paths = [
|
| 432 |
+
{"fid": get_fid["fid"], "name": dir_name}
|
| 433 |
+
for get_fid, dir_name in zip(get_fids, dir_names)
|
| 434 |
+
]
|
| 435 |
+
else:
|
| 436 |
+
return jsonify({"success": False, "data": {"error": "获取fid失败"}})
|
| 437 |
+
else:
|
| 438 |
+
fid = request.args.get("fid", "0")
|
| 439 |
+
file_list = {
|
| 440 |
+
"list": account.ls_dir(fid)["data"]["list"],
|
| 441 |
+
"paths": paths,
|
| 442 |
+
}
|
| 443 |
+
return jsonify({"success": True, "data": file_list})
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@app.route("/delete_file", methods=["POST"])
|
| 447 |
+
def delete_file():
|
| 448 |
+
if not is_login():
|
| 449 |
+
return jsonify({"success": False, "message": "未登录"})
|
| 450 |
+
account = Quark(config_data["cookie"][0])
|
| 451 |
+
if fid := request.json.get("fid"):
|
| 452 |
+
response = account.delete([fid])
|
| 453 |
+
else:
|
| 454 |
+
response = {"success": False, "message": "缺失必要字段: fid"}
|
| 455 |
+
return jsonify(response)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
# 添加任务接口
|
| 459 |
+
@app.route("/api/add_task", methods=["POST"])
|
| 460 |
+
def add_task():
|
| 461 |
+
global config_data
|
| 462 |
+
# 验证token
|
| 463 |
+
if not is_login():
|
| 464 |
+
return jsonify({"success": False, "code": 1, "message": "未登录"}), 401
|
| 465 |
+
# 必选字段
|
| 466 |
+
request_data = request.json
|
| 467 |
+
required_fields = ["taskname", "shareurl", "savepath"]
|
| 468 |
+
for field in required_fields:
|
| 469 |
+
if field not in request_data or not request_data[field]:
|
| 470 |
+
return (
|
| 471 |
+
jsonify(
|
| 472 |
+
{"success": False, "code": 2, "message": f"缺少必要字段: {field}"}
|
| 473 |
+
),
|
| 474 |
+
400,
|
| 475 |
+
)
|
| 476 |
+
if not request_data.get("addition"):
|
| 477 |
+
request_data["addition"] = task_plugins_config_default
|
| 478 |
+
# 添加任务
|
| 479 |
+
config_data["tasklist"].append(request_data)
|
| 480 |
+
Config.write_json(CONFIG_PATH, config_data)
|
| 481 |
+
logging.info(f">>> 通过API添加任务: {request_data['taskname']}")
|
| 482 |
+
return jsonify(
|
| 483 |
+
{"success": True, "code": 0, "message": "任务添加成功", "data": request_data}
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# 定时任务执行的函数
|
| 488 |
+
def run_python(args):
|
| 489 |
+
logging.info(f">>> 定时运行任务")
|
| 490 |
+
try:
|
| 491 |
+
result = subprocess.run(
|
| 492 |
+
f"{PYTHON_PATH} {args}",
|
| 493 |
+
shell=True,
|
| 494 |
+
timeout=TASK_TIMEOUT,
|
| 495 |
+
capture_output=True,
|
| 496 |
+
text=True,
|
| 497 |
+
encoding="utf-8",
|
| 498 |
+
errors="replace",
|
| 499 |
+
)
|
| 500 |
+
# 输出执行日志
|
| 501 |
+
if result.stdout:
|
| 502 |
+
for line in result.stdout.strip().split("\n"):
|
| 503 |
+
if line.strip():
|
| 504 |
+
logging.info(line)
|
| 505 |
+
|
| 506 |
+
if result.returncode == 0:
|
| 507 |
+
logging.info(f">>> 任务执行成功")
|
| 508 |
+
else:
|
| 509 |
+
logging.error(f">>> 任务执行失败,返回码: {result.returncode}")
|
| 510 |
+
if result.stderr:
|
| 511 |
+
logging.error(f"错误信息: {result.stderr[:500]}")
|
| 512 |
+
except subprocess.TimeoutExpired as e:
|
| 513 |
+
logging.error(f">>> 任务执行超时(>{TASK_TIMEOUT}s),强制终止")
|
| 514 |
+
except Exception as e:
|
| 515 |
+
logging.error(f">>> 任务执行异常: {str(e)}")
|
| 516 |
+
logging.error(traceback.format_exc())
|
| 517 |
+
finally:
|
| 518 |
+
# 确保函数能够正常返回
|
| 519 |
+
logging.debug(f">>> run_python 函数执行完成")
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
# 重新加载任务
|
| 523 |
+
def reload_tasks():
|
| 524 |
+
# 读取定时规则
|
| 525 |
+
if crontab := config_data.get("crontab"):
|
| 526 |
+
if scheduler.state == 1:
|
| 527 |
+
scheduler.pause() # 暂停调度器
|
| 528 |
+
trigger = CronTrigger.from_crontab(crontab)
|
| 529 |
+
scheduler.remove_all_jobs()
|
| 530 |
+
scheduler.add_job(
|
| 531 |
+
run_python,
|
| 532 |
+
trigger=trigger,
|
| 533 |
+
args=[f"{SCRIPT_PATH} {CONFIG_PATH}"],
|
| 534 |
+
id=SCRIPT_PATH,
|
| 535 |
+
max_instances=1, # 最多允许1个实例运行
|
| 536 |
+
coalesce=True, # 合并错过的任务,避免堆积
|
| 537 |
+
misfire_grace_time=300, # 错过任务的宽限期(秒),超过则跳过
|
| 538 |
+
replace_existing=True, # 替换已存在的同ID任务
|
| 539 |
+
)
|
| 540 |
+
if scheduler.state == 0:
|
| 541 |
+
scheduler.start()
|
| 542 |
+
elif scheduler.state == 2:
|
| 543 |
+
scheduler.resume()
|
| 544 |
+
scheduler_state_map = {0: "停止", 1: "运行", 2: "暂停"}
|
| 545 |
+
logging.info(">>> 重载调度器")
|
| 546 |
+
logging.info(f"调度状态: {scheduler_state_map[scheduler.state]}")
|
| 547 |
+
logging.info(f"定时规则: {crontab}")
|
| 548 |
+
logging.info(f"现有任务: {scheduler.get_jobs()}")
|
| 549 |
+
return True
|
| 550 |
+
else:
|
| 551 |
+
logging.info(">>> no crontab")
|
| 552 |
+
return False
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def init():
|
| 556 |
+
global config_data, task_plugins_config_default
|
| 557 |
+
logging.info(">>> 初始化配置")
|
| 558 |
+
# 检查配置文件是否存在
|
| 559 |
+
if not os.path.exists(CONFIG_PATH):
|
| 560 |
+
if not os.path.exists(os.path.dirname(CONFIG_PATH)):
|
| 561 |
+
os.makedirs(os.path.dirname(CONFIG_PATH))
|
| 562 |
+
with open("quark_config.json", "rb") as src, open(CONFIG_PATH, "wb") as dest:
|
| 563 |
+
dest.write(src.read())
|
| 564 |
+
|
| 565 |
+
# 读取配置
|
| 566 |
+
config_data = Config.read_json(CONFIG_PATH)
|
| 567 |
+
Config.breaking_change_update(config_data)
|
| 568 |
+
if not config_data.get("magic_regex"):
|
| 569 |
+
config_data["magic_regex"] = MagicRename().magic_regex
|
| 570 |
+
|
| 571 |
+
# 默认管理账号
|
| 572 |
+
config_data["webui"] = {
|
| 573 |
+
"username": os.environ.get("WEBUI_USERNAME")
|
| 574 |
+
or config_data.get("webui", {}).get("username", "admin"),
|
| 575 |
+
"password": os.environ.get("WEBUI_PASSWORD")
|
| 576 |
+
or config_data.get("webui", {}).get("password", "admin123"),
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
# 默认定时规则
|
| 580 |
+
if not config_data.get("crontab"):
|
| 581 |
+
config_data["crontab"] = "0 8,18,20 * * *"
|
| 582 |
+
|
| 583 |
+
# 初始化插件配置
|
| 584 |
+
_, plugins_config_default, task_plugins_config_default = Config.load_plugins()
|
| 585 |
+
for name, config in plugins_config_default.items():
|
| 586 |
+
for key, value in config.items():
|
| 587 |
+
config[key] = (
|
| 588 |
+
config_data.setdefault("plugins", {})
|
| 589 |
+
.setdefault(name, {})
|
| 590 |
+
.get(key, value)
|
| 591 |
+
)
|
| 592 |
+
config_data["plugins"] = plugins_config_default
|
| 593 |
+
|
| 594 |
+
# 更新配置
|
| 595 |
+
Config.write_json(CONFIG_PATH, config_data)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
if __name__ == "__main__":
|
| 599 |
+
init()
|
| 600 |
+
reload_tasks()
|
| 601 |
+
logging.info(">>> 启动Web服务")
|
| 602 |
+
logging.info(f"运行在: http://{HOST}:{PORT}")
|
| 603 |
+
app.run(
|
| 604 |
+
debug=DEBUG,
|
| 605 |
+
host=HOST,
|
| 606 |
+
port=PORT,
|
| 607 |
+
)
|