mirror of
https://github.com/xtekky/gpt4free.git
synced 2025-10-19 22:54:43 +08:00
Fix stop_browser, update secret validation
This commit is contained in:
@@ -87,12 +87,12 @@ class Backend_Api(Api):
|
|||||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||||
)
|
)
|
||||||
|
|
||||||
def decrypt_data(encrypted_data: str):
|
def decrypt_data(encrypted_data: str) -> str:
|
||||||
decrypted = private_key_obj.decrypt(
|
decrypted = private_key_obj.decrypt(
|
||||||
base64.b64decode(encrypted_data),
|
base64.b64decode(encrypted_data),
|
||||||
padding.PKCS1v15()
|
padding.PKCS1v15()
|
||||||
)
|
)
|
||||||
return decrypted.decode('utf-8')
|
return decrypted.decode()
|
||||||
|
|
||||||
def validate_secret(secret: str) -> bool:
|
def validate_secret(secret: str) -> bool:
|
||||||
"""
|
"""
|
||||||
@@ -105,7 +105,7 @@ class Backend_Api(Api):
|
|||||||
bool: True if the secret is valid, False otherwise.
|
bool: True if the secret is valid, False otherwise.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
decrypted_secret = decrypt_data(secret)
|
decrypted_secret = base64.b64decode(decrypt_data(secret).encode()).decode()
|
||||||
return int(decrypted_secret) >= time.time() - 2
|
return int(decrypted_secret) >= time.time() - 2
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Secret validation failed: {e}")
|
logger.error(f"Secret validation failed: {e}")
|
||||||
@@ -114,7 +114,10 @@ class Backend_Api(Api):
|
|||||||
@app.route('/backend-api/v2/public-key', methods=['GET'])
|
@app.route('/backend-api/v2/public-key', methods=['GET'])
|
||||||
def get_public_key():
|
def get_public_key():
|
||||||
# Send the public key to the client for encryption
|
# Send the public key to the client for encryption
|
||||||
return jsonify({"public_key": public_key_pem.decode('utf-8'), "data": str(int(time.time()))})
|
return jsonify({
|
||||||
|
"public_key": public_key_pem.decode(),
|
||||||
|
"data": base64.b64encode(str(int(time.time())).encode()).decode()
|
||||||
|
})
|
||||||
|
|
||||||
@app.route('/backend-api/v2/models', methods=['GET'])
|
@app.route('/backend-api/v2/models', methods=['GET'])
|
||||||
def jsonify_models(**kwargs):
|
def jsonify_models(**kwargs):
|
||||||
@@ -282,7 +285,7 @@ class Backend_Api(Api):
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@app.route('/backend-api/v2/create', methods=['GET', 'POST'])
|
@app.route('/backend-api/v2/create', methods=['GET'])
|
||||||
def create():
|
def create():
|
||||||
try:
|
try:
|
||||||
tool_calls = []
|
tool_calls = []
|
||||||
@@ -394,7 +397,7 @@ class Backend_Api(Api):
|
|||||||
delete_files = request.args.get('delete_files', True)
|
delete_files = request.args.get('delete_files', True)
|
||||||
refine_chunks_with_spacy = request.args.get('refine_chunks_with_spacy', False)
|
refine_chunks_with_spacy = request.args.get('refine_chunks_with_spacy', False)
|
||||||
event_stream = 'text/event-stream' in request.headers.get('Accept', '')
|
event_stream = 'text/event-stream' in request.headers.get('Accept', '')
|
||||||
mimetype = "text/event-stream" if event_stream else "text/plain";
|
mimetype = "text/event-stream" if event_stream else "text/plain"
|
||||||
return Response(get_streaming(bucket_dir, delete_files, refine_chunks_with_spacy, event_stream), mimetype=mimetype)
|
return Response(get_streaming(bucket_dir, delete_files, refine_chunks_with_spacy, event_stream), mimetype=mimetype)
|
||||||
|
|
||||||
@self.app.route('/backend-api/v2/files/<bucket_id>', methods=['POST'])
|
@self.app.route('/backend-api/v2/files/<bucket_id>', methods=['POST'])
|
||||||
@@ -413,7 +416,7 @@ class Backend_Api(Api):
|
|||||||
suffix = os.path.splitext(filename)[1].lower()
|
suffix = os.path.splitext(filename)[1].lower()
|
||||||
copyfile = get_tempfile(file, suffix)
|
copyfile = get_tempfile(file, suffix)
|
||||||
result = None
|
result = None
|
||||||
if has_markitdown and not filename.endswith((".md", ".json")):
|
if has_markitdown and not filename.endswith((".md", ".json", ".zip")):
|
||||||
try:
|
try:
|
||||||
language = request.headers.get("x-recognition-language")
|
language = request.headers.get("x-recognition-language")
|
||||||
md = MarkItDown()
|
md = MarkItDown()
|
||||||
|
@@ -45,7 +45,9 @@ from ..typing import Cookies
|
|||||||
from ..cookies import get_cookies_dir
|
from ..cookies import get_cookies_dir
|
||||||
from .defaults import DEFAULT_HEADERS, WEBVIEW_HAEDERS
|
from .defaults import DEFAULT_HEADERS, WEBVIEW_HAEDERS
|
||||||
|
|
||||||
BROWSER_EXECUTABLE_PATH = None
|
class BrowserConfig:
|
||||||
|
stop_browser = lambda: None
|
||||||
|
browser_executable_path: str = None
|
||||||
|
|
||||||
if not has_curl_cffi:
|
if not has_curl_cffi:
|
||||||
class Session:
|
class Session:
|
||||||
@@ -141,7 +143,7 @@ def merge_cookies(cookies: Iterator[Morsel], response: Response) -> Cookies:
|
|||||||
return cookies
|
return cookies
|
||||||
|
|
||||||
def set_browser_executable_path(browser_executable_path: str):
|
def set_browser_executable_path(browser_executable_path: str):
|
||||||
BROWSER_EXECUTABLE_PATH = browser_executable_path
|
BrowserConfig.browser_executable_path = browser_executable_path
|
||||||
|
|
||||||
async def get_nodriver(
|
async def get_nodriver(
|
||||||
proxy: str = None,
|
proxy: str = None,
|
||||||
@@ -154,7 +156,7 @@ async def get_nodriver(
|
|||||||
raise MissingRequirementsError('Install "nodriver" and "platformdirs" package | pip install -U nodriver platformdirs')
|
raise MissingRequirementsError('Install "nodriver" and "platformdirs" package | pip install -U nodriver platformdirs')
|
||||||
user_data_dir = user_config_dir(f"g4f-{user_data_dir}") if has_platformdirs else None
|
user_data_dir = user_config_dir(f"g4f-{user_data_dir}") if has_platformdirs else None
|
||||||
if browser_executable_path is None:
|
if browser_executable_path is None:
|
||||||
browser_executable_path = BROWSER_EXECUTABLE_PATH
|
browser_executable_path = BrowserConfig.browser_executable_path
|
||||||
if browser_executable_path is None:
|
if browser_executable_path is None:
|
||||||
try:
|
try:
|
||||||
browser_executable_path = find_chrome_executable()
|
browser_executable_path = find_chrome_executable()
|
||||||
@@ -173,11 +175,18 @@ async def get_nodriver(
|
|||||||
if timeout * 2 > time_open:
|
if timeout * 2 > time_open:
|
||||||
debug.log(f"Nodriver: Browser is already in use since {time_open} secs.")
|
debug.log(f"Nodriver: Browser is already in use since {time_open} secs.")
|
||||||
debug.log("Lock file:", lock_file)
|
debug.log("Lock file:", lock_file)
|
||||||
for _ in range(timeout):
|
for idx in range(timeout):
|
||||||
if lock_file.exists():
|
if lock_file.exists():
|
||||||
await asyncio.sleep(1)
|
await asyncio.sleep(1)
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
if idx == timeout - 1:
|
||||||
|
debug.log("Timeout reached, nodriver is still in use.")
|
||||||
|
raise TimeoutError("Nodriver is already in use, please try again later.")
|
||||||
|
else:
|
||||||
|
debug.log(f"Nodriver: Browser was opened {time_open} secs ago, closing it.")
|
||||||
|
BrowserConfig.stop_browser()
|
||||||
|
lock_file.unlink(missing_ok=True)
|
||||||
lock_file.write_text(str(time.time()))
|
lock_file.write_text(str(time.time()))
|
||||||
debug.log(f"Open nodriver with user_dir: {user_data_dir}")
|
debug.log(f"Open nodriver with user_dir: {user_data_dir}")
|
||||||
try:
|
try:
|
||||||
@@ -200,6 +209,7 @@ async def get_nodriver(
|
|||||||
browser.stop()
|
browser.stop()
|
||||||
finally:
|
finally:
|
||||||
lock_file.unlink(missing_ok=True)
|
lock_file.unlink(missing_ok=True)
|
||||||
|
BrowserConfig.stop_browser = on_stop
|
||||||
return browser, on_stop
|
return browser, on_stop
|
||||||
|
|
||||||
async def see_stream(iter_lines: Iterator[bytes]) -> AsyncIterator[dict]:
|
async def see_stream(iter_lines: Iterator[bytes]) -> AsyncIterator[dict]:
|
||||||
|
Reference in New Issue
Block a user