-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
438 lines (350 loc) · 15.1 KB
/
app.py
File metadata and controls
438 lines (350 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# ph-editor/app.py
import logging
import platform
import random
import string
import os,time
import traceback
import unicodedata
from wsgiref.simple_server import WSGIRequestHandler
from flask import (
Flask,
flash,
jsonify,
redirect,
render_template,
request,
send_from_directory,
session,
url_for,
)
from waitress import serve
from werkzeug.routing import IntegerConverter
from api.character_bp import api_characters_bp
from api.profile import api_profile_bp
from api.scenario_bp import api_scenario_bp
from api.ui_config import api_ui_config_bp
from config.logging_setup import setup_logging
from utils.exceptions import APIError
from werkzeug.exceptions import HTTPException
# 從 shared_data 模組引入相關函式
from core.shared_data import (
add_or_update_character_with_path,
clear_characters_db,
process_tag_info,
initialize_extra_data,
get_general_data,
get_wish_list,
add_wish,
delete_wish as delete_wish_service,
)
from core.user_config_manager import UserConfigManager
from web.arrange_bp import arrange_bp
from web.ccm_bp import ccm_bp
from web.compare_bp import compare_bp
from web.edit_bp import edit_bp
from web.epoch_bp import epoch_bp
from web.general_bp import general_bp
# 初始化時確保所有目錄存在
UserConfigManager.ensure_dir()
# app = Flask(__name__)
# 建立 Flask 應用程式實例,並只設定變數的分隔符號
app = Flask(__name__, template_folder='templates')
app.secret_key = 'gohome!Is1very3Handome'
# 讓 url <int:number> 支援負數
app.url_map.converters['int'] = type('SignedInt', (IntegerConverter,), {'regex': r'-?\d+'})
app.json.sort_keys = False
# json setting.
#app.config['JSON_AS_ASCII'] = False # 讓中文正常顯示,不噴 \uXXXX
#app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True # 讓瀏覽器直接看就有縮排
WSGIRequestHandler.protocol_version = "HTTP/1.1"
# 換 jinja delimeters
app.jinja_env.variable_start_string = '[['
app.jinja_env.variable_end_string = ']]'
app.jinja_env.block_start_string = '[%'
app.jinja_env.block_end_string = '%]'
app.register_blueprint(arrange_bp)
app.register_blueprint(ccm_bp)
app.register_blueprint(compare_bp)
app.register_blueprint(edit_bp)
app.register_blueprint(epoch_bp)
app.register_blueprint(general_bp)
app.register_blueprint(api_characters_bp)
app.register_blueprint(api_profile_bp)
app.register_blueprint(api_scenario_bp)
app.register_blueprint(api_ui_config_bp)
# error handler.
@app.errorhandler(APIError)
def handle_custom_api_error(e):
"""處理主動拋出的 APIError (符合 RESTful 規範)"""
# 如果是 204,直接回傳空回應
if e.status_code == 204:
return '', 204
return jsonify({
"error": e.message,
"code": e.__class__.__name__, # 多帶一個錯誤類型方便前端判斷
}), e.status_code
@app.errorhandler(HTTPException)
def handle_standard_http_error(e):
"""處理 Flask 內建錯誤 (例如 404 Not Found 或 405 Method Not Allowed)"""
return jsonify({"error": e.description}), e.code
@app.errorhandler(Exception)
def handle_unexpected_error(e):
"""處理程式 Bug (例如除以零、KeyError),確保前端不崩潰"""
# 這裡可以加入 log 紀錄真正的錯誤原因
error_details = traceback.format_exc()
app.logger.error(f"Unhandled Exception: {error_details}")
return jsonify({"error": "Internal Server Error"}), 500
# 設定快取路徑
CACHE_DIR = UserConfigManager.get_cache_dir()
# 設定掃描路徑
scan_path = UserConfigManager.load_scan_path()
app.config["SCAN_PATH"] = scan_path if scan_path else ""
# 在應用程式啟動時,先設定日誌
setup_logging()
# 取得這個模組的日誌器
logger = logging.getLogger(__name__)
# ✅ 新增:在應用程式啟動時載入 general.json 資料
#logger.info("應用程式啟動,正在載入全域 general 資料...")
initialize_extra_data()
#logger.info("全域 general 資料載入完成。")
'''
def clean_old_thumbnails(cache_dir, max_remove=3):
if not os.path.exists(cache_dir):
return
files = [
(f, os.path.getmtime(os.path.join(cache_dir, f)))
for f in os.listdir(cache_dir)
if f.lower().endswith((".png", ".jpg"))
]
files.sort(key=lambda x: x[1]) # sort by oldest
for f, _ in files[:max_remove]:
try:
os.remove(os.path.join(cache_dir, f))
print(f"刪除快取縮圖: {f}")
except Exception as e:
print(f"刪除失敗: {f}, {e}")
'''
def smart_clean_thumbnails(cache_dir, threshold=500, days=3):
if not os.path.exists(cache_dir):
return
all_files = [f for f in os.listdir(cache_dir) if f.lower().endswith((".png", ".jpg"))]
if len(all_files) < threshold:
logger.debug(f"目前檔案數 {len(all_files)},未達標,繼續裝死...")
return
logger.debug(f"檔案數 {len(all_files)} 已超過門檻 {threshold},開始清理 3 天前的舊檔...")
expiry_threshold = time.time() - (days * 24 * 60 * 60)
count = 0
for f in all_files:
file_path = os.path.join(cache_dir, f)
try:
mtime = os.path.getmtime(file_path)
# 只要超過三天就幹掉
if mtime < expiry_threshold:
os.remove(file_path)
count += 1
except Exception as e:
logger.error(f"處理 {f} 出錯: {e}")
if count > 0:
logger.info(f"大掃除完畢,共清掉了 {count} 個過期檔案。")
else:
logger.debug("雖然達到了 500 張,但目前沒有超過 3 天的舊檔,先放它們一馬。")
smart_clean_thumbnails(CACHE_DIR) # 應用啟動時執行清理
UserConfigManager.cleanup_plain_backups() # 應用啟動時執行清理
@app.before_request
def check_auth():
# 只要不是訪問登入頁或靜態檔案,沒登入就踢走
if request.endpoint not in ['login', 'static'] and not session.get('is_admin'):
return redirect('/login')
@app.after_request
def add_header(response):
# 禁止快取敏感內容
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if request.form.get('password') == 'geobess':
session['is_admin'] = True
return redirect('/')
else:
# 密碼錯誤,顯示隨機數字(符合你的需求)
flash(str(random.randint(100000, 999999)))
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
return redirect('https://www.google.com')
@app.route("/")
def index():
return render_template("index.html")
@app.route("/cache/<path:filename>")
def serve_cache(filename):
return send_from_directory(CACHE_DIR, filename)
@app.route("/get_scan_path", methods=["GET"])
def get_scan_path():
path = UserConfigManager.load_scan_path()
return jsonify({"scanPath": path or ""})
@app.route("/scan", methods=["POST"])
def scan_folder():
folder_path = request.json.get("path")
# 偵測是否為 Mac 環境
is_mac = platform.system() == "Darwin"
if not folder_path:
return jsonify({"error": "缺少資料夾路徑"}), 400
if not os.path.isdir(folder_path):
return jsonify({"error": "無效的資料夾路徑"}), 400
app.config["SCAN_PATH"] = folder_path # 更新應用程式配置中的掃描路徑
UserConfigManager.save_scan_path(folder_path) # ✅ 改用此處理
# 清空現有的數據庫,以便重新掃描
clear_characters_db()
thumbnails = [] # 儲存生成或更新的縮圖檔案名
loaded_character_count = 0
character_list = [] # 儲存 thumbnail, file_id, profile_name
logger.debug(f"開始掃描資料夾 '{folder_path}'...")
for root, _, files in os.walk(folder_path):
for file_name_with_ext in files:
# --- 關鍵修正:處理 Mac 的 NFD 檔名 ---
if is_mac:
# 將 Mac 拆散的 NFD 檔名「黏回去」變成 NFC
file_name_with_ext = unicodedata.normalize('NFC', file_name_with_ext)
# -----------------------------------
if file_name_with_ext.lower().endswith(".png"):
file_path = os.path.join(root, file_name_with_ext)
file_id = os.path.splitext(file_name_with_ext)[0]
#logger.debug(f"處理 {file_id}")
# --- 縮圖生成邏輯 ---
thumbnail_name = f"thumb_{file_id}.jpg"
'''
thumbnail_path = os.path.join(CACHE_DIR, thumbnail_name)
try:
original_mtime = os.path.getmtime(file_path)
if os.path.exists(thumbnail_path):
cache_mtime = os.path.getmtime(thumbnail_path)
if original_mtime <= cache_mtime:
thumbnails.append(thumbnail_name)
# print(f" [縮圖] 快取未過期,跳過: {file_name_with_ext}")
pass # 不跳過,因為還要處理角色數據
except Exception as e:
print(
f" [縮圖] 處理 '{file_name_with_ext}' 縮圖快取時發生錯誤: {e}"
)
# 不阻礙後續的 CharacterData 載入,但會嘗試重新生成縮圖
# 嘗試生成/更新縮圖
try:
# 如果縮圖不存在或已過期,則重新生成
if not os.path.exists(
thumbnail_path
) or original_mtime > os.path.getmtime(thumbnail_path):
with Image.open(file_path) as img:
img = img.convert("RGB")
# img.thumbnail((189, 264)) # 等比縮圖,寬不超過189,高不超過264
img.save(thumbnail_path, format="JPEG", quality=85)
# print(f" [縮圖] 生成/更新縮圖: {file_name_with_ext}")
# if thumbnail_name not in thumbnails: # 避免重複添加,如果之前快取判斷沒有跳過
# thumbnails.append(thumbnail_name)
except Exception as e:
print(f" [錯誤] 生成縮圖 '{file_name_with_ext}' 失敗: {e}")
# 縮圖失敗不影響角色數據載入,繼續
# --- 縮圖生成邏輯結束 ---
# '''
# --- 角色數據載入邏輯 ---
try:
character_file_obj = (
add_or_update_character_with_path(folder_path, file_id)
)
loaded_character_count += 1
except Exception as e:
logger.error(
f" [錯誤] 載入或解析檔案 '{file_name_with_ext}' 的角色數據時發生錯誤: {e}"
)
continue # 繼續處理下一個檔案
character_list.append(
character_file_obj.to_dict(process_tag_info)
)
# 1. 掃描完成後, 才有確定的 tag 資料
global_data = get_general_data()
# dump 全域資料
#logger.debug("全域資料:")
#logger.debug(json.dumps(global_data, ensure_ascii=False, indent=2))
# 2. 整理 tag type 的樣式資料
tag_styles = global_data.get("tag_styles", {})
tag_styles_data = {}
for tag_type, style in tag_styles.items():
tag_styles_data[tag_type] = {
"color": style.get("color", "#000"),
"bg_color": style.get("background", "#fff"),
}
logger.debug(
f"掃描完成。總計處理 {len(thumbnails)} 個檔案,成功載入 {loaded_character_count} 個角色數據。"
)
# 排序
#character_list.sort(key=lambda item: item["id"].lower())
return jsonify(
{
"images": character_list,
"tag_styles": tag_styles_data,
"message": f"成功掃描 {len(thumbnails)} 個檔案並載入 {loaded_character_count} 個角色數據。",
}
)
@app.route("/reload_file/<file_id>", methods=["GET"])
def reload_file(file_id):
"""
處理重新載入單個角色檔案的請求,從設定的路徑讀取數據並返回。
"""
# 檢查 file_id 是否存在,這是 URL 路由參數
if not file_id:
logger.warning("reload_file 請求缺少檔案 ID。")
return jsonify({"error": "缺少檔案 ID"}), 400
try:
# 1. 取得掃描路徑並嘗試更新檔案
scan_path = app.config.get("SCAN_PATH")
if not scan_path:
logger.error("未設定 SCAN_PATH,無法重新載入角色檔案。")
return jsonify({"error": "系統設定錯誤:找不到掃描路徑"}), 500
# 嘗試重新載入或更新指定的檔案
character_file_obj = add_or_update_character_with_path(scan_path, file_id)
# 2. 檢查檔案物件是否成功返回
if not character_file_obj:
logger.warning(f"重新載入檔案 '{file_id}' 失敗,可能找不到該檔案。")
return jsonify({"error": "找不到指定的檔案或處理失敗"}), 404
# 3. 從檔案物件中提取並整理所需資料
data_to_return = {
"thumb": f"thumb_{file_id}.jpg",
"id": file_id,
"profile_name": character_file_obj.get_profile_name(),
"scenario_scene": character_file_obj.get_scenario_scene(),
"remark": character_file_obj.get_remark(),
"status": character_file_obj.get_status(),
}
# 4. 處理標籤資訊,這個函式也可能出錯
tag_style, tag_name = process_tag_info(file_id)
data_to_return["tag_style"] = tag_style
data_to_return["tag_name"] = tag_name
# 5. 返回整理好的 JSON 數據
return jsonify(data_to_return)
except Exception as e:
# 6. 統一處理所有未預期的錯誤
logger.exception(f"處理檔案 '{file_id}' 時發生內部錯誤。")
return jsonify({"error": f"處理檔案時發生內部錯誤: {str(e)}"}), 500
@app.route('/wishes', methods=['GET', 'POST'])
def handle_wishes():
if request.method == 'POST':
new_wish = request.json # 預期:{type, content}
saved_wish = add_wish(new_wish)
return jsonify(saved_wish)
#logger.debug("準備寫入全域資料了!!")
#logger.debug(json.dumps(wishes, ensure_ascii = False, indent = 4))
wishes = get_wish_list()
return jsonify(wishes)
@app.route('/wishes/<int:wish_id>', methods=['DELETE'])
def delete_wish(wish_id):
delete_wish_service(wish_id)
return jsonify({"status": "ok"})
if __name__ == "__main__":
# app.run(host="0.0.0.0", port=5000, debug = True, threaded = False) #單執行緒
# 因為 mac 鎖死了 5000 -> Air Playpy
app.run(host="0.0.0.0", port=5050, debug = True, threaded = True) #單執行緒
# serve(app, host="0.0.0.0", port=5000)