Add support for configuring server language through .env file

pull/191/head
zanllp 2023-05-27 03:33:55 +08:00
parent 7c92848699
commit b63a2264ce
3 changed files with 29 additions and 45 deletions

View File

@ -1 +1,5 @@
IIB_SECRET_KEY=
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

View File

@ -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")

View File

@ -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"