From b63a2264ceb91d846869fb7750e5c64881f68688 Mon Sep 17 00:00:00 2001 From: zanllp Date: Sat, 27 May 2023 03:33:55 +0800 Subject: [PATCH] Add support for configuring server language through .env file --- .env.example | 6 +++++- scripts/api.py | 22 +++++----------------- scripts/tool.py | 46 +++++++++++++++++++--------------------------- 3 files changed, 29 insertions(+), 45 deletions(-) diff --git a/.env.example b/.env.example index b050cac..18976f1 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,5 @@ -IIB_SECRET_KEY= \ No newline at end of file +IIB_SECRET_KEY= +# Configuring the server-side language for this extension, +# including the tab title and most of the server-side error messages returned. Options are 'zh', 'en', or 'auto'. +# If you want to configure the language for the front-end pages, please set it on the extension's global settings page. +IIB_SERVER_LANG=auto \ No newline at end of file diff --git a/scripts/api.py b/scripts/api.py index 11d5aba..a21fdc1 100644 --- a/scripts/api.py +++ b/scripts/api.py @@ -16,17 +16,17 @@ from scripts.tool import ( get_valid_img_dirs, get_created_date, open_folder, + secret_key ) from fastapi import FastAPI, HTTPException from fastapi.staticfiles import StaticFiles import asyncio -from typing import Any, List, Literal, Optional +from typing import Any, List, Optional from pydantic import BaseModel -from fastapi.responses import FileResponse, RedirectResponse +from fastapi.responses import FileResponse from PIL import Image from fastapi import Depends, FastAPI, HTTPException, Request import hashlib -from urllib.parse import urlencode from scripts.db.datamodel import ( DataBase, Image as DbImg, @@ -41,31 +41,19 @@ from scripts.logger import logger send_img_path = {"value": ""} - -options = {"IIB_SECRET_KEY": ""} mem = { "IIB_SECRET_KEY_HASH" : None } -try: - from dotenv import load_dotenv - load_dotenv(os.path.join(cwd, ".env")) - secret_key = os.getenv("IIB_SECRET_KEY") - if secret_key: - options["IIB_SECRET_KEY"] = secret_key - print(f"Secret key loaded successfully. ") -except BaseException as e: - print(e) async def get_token(request: Request): - secert = options["IIB_SECRET_KEY"] - if not secert: + if not secret_key: return token = request.cookies.get("IIB_S") if not token: raise HTTPException(status_code=401, detail="Unauthorized") if not mem["IIB_SECRET_KEY_HASH"]: - mem["IIB_SECRET_KEY_HASH"] = hashlib.sha256((secert+"_ciallo").encode("utf-8")).hexdigest() + mem["IIB_SECRET_KEY_HASH"] = hashlib.sha256((secret_key+"_ciallo").encode("utf-8")).hexdigest() if mem["IIB_SECRET_KEY_HASH"] != token: raise HTTPException(status_code=401, detail="Unauthorized") diff --git a/scripts/tool.py b/scripts/tool.py index c14c510..4a666dd 100644 --- a/scripts/tool.py +++ b/scripts/tool.py @@ -21,6 +21,22 @@ sd_img_dirs = [ ] +is_dev = os.getenv("APP_ENV") == "dev" +cwd = os.path.normpath(os.path.join(__file__, "../../")) +is_win = platform.system().lower().find("windows") != -1 + + +try: + from dotenv import load_dotenv + load_dotenv(os.path.join(cwd, ".env")) +except BaseException as e: + print(e) +secret_key = os.getenv("IIB_SECRET_KEY") +if secret_key: + print(f"Secret key loaded successfully. ") + + + def get_sd_webui_conf(**kwargs): try: from modules.shared import opts @@ -107,29 +123,6 @@ def convert_to_bytes(file_size_str): raise ValueError(f"Invalid file size string '{file_size_str}'") -import asyncio - - -def debounce(delay): - """用于优化高频事件的装饰器""" - - def decorator(func): - from typing import Union - - task: Union[None, asyncio.Task] = None - - async def debounced(*args, **kwargs): - nonlocal task - if task: - task.cancel() - task = asyncio.create_task(asyncio.sleep(delay)) - await task - return await func(*args, **kwargs) - - return debounced - - return decorator - def is_valid_image_path(path): """ @@ -145,9 +138,6 @@ def is_valid_image_path(path): return True -is_dev = "APP_ENV" in os.environ and os.environ["APP_ENV"] == "dev" -cwd = os.path.normpath(os.path.join(__file__, "../../")) -is_win = platform.system().lower().find("windows") != -1 def get_temp_path(): @@ -183,7 +173,9 @@ temp_path = get_temp_path() def get_locale(): import locale - + env_lang = os.getenv("IIB_SERVER_LANG") + if env_lang in ['zh', 'en']: + return env_lang lang, _ = locale.getdefaultlocale() return "zh" if lang and lang.startswith("zh") else "en"