mirror of
				https://github.com/xtekky/gpt4free.git
				synced 2025-10-31 03:26:22 +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 | ||||
|             ) | ||||
|  | ||||
|             def decrypt_data(encrypted_data: str): | ||||
|             def decrypt_data(encrypted_data: str) -> str: | ||||
|                 decrypted = private_key_obj.decrypt( | ||||
|                     base64.b64decode(encrypted_data), | ||||
|                     padding.PKCS1v15() | ||||
|                 ) | ||||
|                 return decrypted.decode('utf-8') | ||||
|                 return decrypted.decode() | ||||
|  | ||||
|             def validate_secret(secret: str) -> bool: | ||||
|                 """ | ||||
| @@ -105,7 +105,7 @@ class Backend_Api(Api): | ||||
|                     bool: True if the secret is valid, False otherwise. | ||||
|                 """ | ||||
|                 try: | ||||
|                     decrypted_secret = decrypt_data(secret) | ||||
|                     decrypted_secret = base64.b64decode(decrypt_data(secret).encode()).decode() | ||||
|                     return int(decrypted_secret) >= time.time() - 2 | ||||
|                 except Exception as 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']) | ||||
|             def get_public_key(): | ||||
|                 # 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']) | ||||
|         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(): | ||||
|             try: | ||||
|                 tool_calls = [] | ||||
| @@ -335,7 +338,7 @@ class Backend_Api(Api): | ||||
|                                 if chunk: | ||||
|                                     yield chunk | ||||
|                     return iter_response() | ||||
|                  | ||||
|  | ||||
|                 if cache_id: | ||||
|                     cache_id = sha256(cache_id.encode() + json.dumps(parameters, sort_keys=True).encode()).hexdigest() | ||||
|                     cache_dir = Path(get_cookies_dir()) / ".scrape_cache" / "create" | ||||
| @@ -394,7 +397,7 @@ class Backend_Api(Api): | ||||
|             delete_files = request.args.get('delete_files', True) | ||||
|             refine_chunks_with_spacy = request.args.get('refine_chunks_with_spacy', False) | ||||
|             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) | ||||
|  | ||||
|         @self.app.route('/backend-api/v2/files/<bucket_id>', methods=['POST']) | ||||
| @@ -413,14 +416,14 @@ class Backend_Api(Api): | ||||
|                 suffix = os.path.splitext(filename)[1].lower() | ||||
|                 copyfile = get_tempfile(file, suffix) | ||||
|                 result = None | ||||
|                 if has_markitdown and not filename.endswith((".md", ".json")): | ||||
|                 if has_markitdown and not filename.endswith((".md", ".json", ".zip")): | ||||
|                     try: | ||||
|                         language = request.headers.get("x-recognition-language") | ||||
|                         md = MarkItDown() | ||||
|                         result = md.convert(copyfile, stream_info=StreamInfo( | ||||
|                             extension=suffix, | ||||
|                             mimetype=file.mimetype, | ||||
|                         ),recognition_language=language).text_content | ||||
|                         ), recognition_language=language).text_content | ||||
|                     except Exception as e: | ||||
|                         logger.exception(e) | ||||
|                 is_media = is_allowed_extension(filename) | ||||
|   | ||||
| @@ -45,7 +45,9 @@ from ..typing import Cookies | ||||
| from ..cookies import get_cookies_dir | ||||
| 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: | ||||
|     class Session: | ||||
| @@ -141,7 +143,7 @@ def merge_cookies(cookies: Iterator[Morsel], response: Response) -> Cookies: | ||||
|     return cookies | ||||
|  | ||||
| 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( | ||||
|     proxy: str = None, | ||||
| @@ -154,7 +156,7 @@ async def get_nodriver( | ||||
|         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 | ||||
|     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: | ||||
|         try: | ||||
|             browser_executable_path = find_chrome_executable() | ||||
| @@ -173,11 +175,18 @@ async def get_nodriver( | ||||
|         if timeout * 2 > time_open: | ||||
|             debug.log(f"Nodriver: Browser is already in use since {time_open} secs.") | ||||
|             debug.log("Lock file:", lock_file) | ||||
|             for _ in range(timeout): | ||||
|             for idx in range(timeout): | ||||
|                 if lock_file.exists(): | ||||
|                     await asyncio.sleep(1) | ||||
|                 else: | ||||
|                     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())) | ||||
|     debug.log(f"Open nodriver with user_dir: {user_data_dir}") | ||||
|     try: | ||||
| @@ -200,6 +209,7 @@ async def get_nodriver( | ||||
|                 browser.stop() | ||||
|         finally: | ||||
|             lock_file.unlink(missing_ok=True) | ||||
|     BrowserConfig.stop_browser = on_stop | ||||
|     return browser, on_stop | ||||
|  | ||||
| async def see_stream(iter_lines: Iterator[bytes]) -> AsyncIterator[dict]: | ||||
|   | ||||
		Reference in New Issue
	
	Block a user
	 hlohaus
					hlohaus