2023-09-26 01:52:29 +03:00
|
|
|
from __future__ import annotations
|
|
|
|
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
from urllib.parse import urlparse
|
|
|
|
from typing import Iterator
|
|
|
|
from http.cookies import Morsel
|
2024-01-26 09:54:13 +03:00
|
|
|
try:
|
2024-03-12 04:06:06 +03:00
|
|
|
from curl_cffi.requests import Session, Response
|
2024-03-15 16:55:53 +03:00
|
|
|
from .curl_cffi import StreamResponse, StreamSession, FormData
|
2024-01-26 09:54:13 +03:00
|
|
|
has_curl_cffi = True
|
|
|
|
except ImportError:
|
2024-03-12 04:06:06 +03:00
|
|
|
from typing import Type as Session, Type as Response
|
2024-03-15 16:55:53 +03:00
|
|
|
from .aiohttp import StreamResponse, StreamSession, FormData
|
2024-01-26 09:54:13 +03:00
|
|
|
has_curl_cffi = False
|
2024-03-15 13:46:06 +03:00
|
|
|
try:
|
|
|
|
import webview
|
|
|
|
import asyncio
|
|
|
|
has_webview = True
|
|
|
|
except ImportError:
|
|
|
|
has_webview = False
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
try:
|
|
|
|
import nodriver
|
|
|
|
from nodriver.cdp.network import CookieParam
|
2024-11-19 22:45:25 +03:00
|
|
|
from nodriver import Browser
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
has_nodriver = True
|
|
|
|
except ImportError:
|
|
|
|
has_nodriver = False
|
2024-11-19 22:45:25 +03:00
|
|
|
try:
|
|
|
|
from platformdirs import user_config_dir
|
|
|
|
has_platformdirs = True
|
|
|
|
except ImportError:
|
|
|
|
has_platformdirs = False
|
2024-01-14 09:45:41 +03:00
|
|
|
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
from .. import debug
|
2024-03-15 16:55:53 +03:00
|
|
|
from .raise_for_status import raise_for_status
|
2024-03-12 04:06:06 +03:00
|
|
|
from ..webdriver import WebDriver, WebDriverSession
|
2024-03-12 20:45:22 +03:00
|
|
|
from ..webdriver import bypass_cloudflare, get_driver_cookies
|
2024-03-15 16:55:53 +03:00
|
|
|
from ..errors import MissingRequirementsError
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
from ..typing import Cookies
|
2024-03-15 13:46:06 +03:00
|
|
|
from .defaults import DEFAULT_HEADERS, WEBVIEW_HAEDERS
|
|
|
|
|
2024-03-15 16:55:53 +03:00
|
|
|
async def get_args_from_webview(url: str) -> dict:
|
2024-03-15 13:46:06 +03:00
|
|
|
if not has_webview:
|
|
|
|
raise MissingRequirementsError('Install "webview" package')
|
|
|
|
window = webview.create_window("", url, hidden=True)
|
|
|
|
await asyncio.sleep(2)
|
|
|
|
body = None
|
|
|
|
while body is None:
|
|
|
|
try:
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
body = window.dom.get_element("body:not(.no-js)")
|
|
|
|
except:
|
|
|
|
...
|
|
|
|
headers = {
|
|
|
|
**WEBVIEW_HAEDERS,
|
|
|
|
"User-Agent": window.evaluate_js("this.navigator.userAgent"),
|
|
|
|
"Accept-Language": window.evaluate_js("this.navigator.language"),
|
|
|
|
"Referer": window.real_url
|
|
|
|
}
|
|
|
|
cookies = [list(*cookie.items()) for cookie in window.get_cookies()]
|
2024-05-06 00:38:31 +03:00
|
|
|
cookies = {name: cookie.value for name, cookie in cookies}
|
2024-03-15 13:46:06 +03:00
|
|
|
window.destroy()
|
|
|
|
return {"headers": headers, "cookies": cookies}
|
2024-01-26 09:54:13 +03:00
|
|
|
|
2024-02-23 13:33:38 +03:00
|
|
|
def get_args_from_browser(
|
|
|
|
url: str,
|
|
|
|
webdriver: WebDriver = None,
|
|
|
|
proxy: str = None,
|
|
|
|
timeout: int = 120,
|
2024-03-12 04:06:06 +03:00
|
|
|
do_bypass_cloudflare: bool = True,
|
|
|
|
virtual_display: bool = False
|
2024-02-23 13:33:38 +03:00
|
|
|
) -> dict:
|
2024-01-14 09:45:41 +03:00
|
|
|
"""
|
|
|
|
Create a Session object using a WebDriver to handle cookies and headers.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
url (str): The URL to navigate to using the WebDriver.
|
|
|
|
webdriver (WebDriver, optional): The WebDriver instance to use.
|
|
|
|
proxy (str, optional): Proxy server to use for the Session.
|
|
|
|
timeout (int, optional): Timeout in seconds for the WebDriver.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Session: A Session object configured with cookies and headers from the WebDriver.
|
|
|
|
"""
|
2024-03-12 20:45:22 +03:00
|
|
|
with WebDriverSession(webdriver, "", proxy=proxy, virtual_display=virtual_display) as driver:
|
2024-02-23 13:33:38 +03:00
|
|
|
if do_bypass_cloudflare:
|
|
|
|
bypass_cloudflare(driver, url, timeout)
|
2024-03-12 04:06:06 +03:00
|
|
|
headers = {
|
|
|
|
**DEFAULT_HEADERS,
|
|
|
|
'referer': url,
|
|
|
|
}
|
2024-03-12 20:45:22 +03:00
|
|
|
if not hasattr(driver, "requests"):
|
|
|
|
headers["user-agent"] = driver.execute_script("return navigator.userAgent")
|
|
|
|
else:
|
2024-03-12 04:06:06 +03:00
|
|
|
for request in driver.requests:
|
|
|
|
if request.url.startswith(url):
|
|
|
|
for key, value in request.headers.items():
|
|
|
|
if key in (
|
|
|
|
"accept-encoding",
|
|
|
|
"accept-language",
|
|
|
|
"user-agent",
|
|
|
|
"sec-ch-ua",
|
|
|
|
"sec-ch-ua-platform",
|
|
|
|
"sec-ch-ua-arch",
|
|
|
|
"sec-ch-ua-full-version",
|
|
|
|
"sec-ch-ua-platform-version",
|
|
|
|
"sec-ch-ua-bitness"
|
|
|
|
):
|
|
|
|
headers[key] = value
|
|
|
|
break
|
|
|
|
cookies = get_driver_cookies(driver)
|
2024-01-27 04:00:44 +03:00
|
|
|
return {
|
|
|
|
'cookies': cookies,
|
2024-03-12 04:06:06 +03:00
|
|
|
'headers': headers,
|
2024-01-27 04:00:44 +03:00
|
|
|
}
|
2024-01-29 20:14:46 +03:00
|
|
|
|
2024-01-27 04:00:44 +03:00
|
|
|
def get_session_from_browser(url: str, webdriver: WebDriver = None, proxy: str = None, timeout: int = 120) -> Session:
|
|
|
|
if not has_curl_cffi:
|
2024-11-18 17:41:45 +03:00
|
|
|
raise MissingRequirementsError('Install "curl_cffi" package | pip install -U curl_cffi')
|
2024-01-27 04:00:44 +03:00
|
|
|
args = get_args_from_browser(url, webdriver, proxy, timeout)
|
|
|
|
return Session(
|
|
|
|
**args,
|
2023-12-02 07:40:07 +03:00
|
|
|
proxies={"https": proxy, "http": proxy},
|
|
|
|
timeout=timeout,
|
2024-03-12 04:06:06 +03:00
|
|
|
impersonate="chrome"
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
)
|
2024-11-26 18:36:45 +03:00
|
|
|
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
def get_cookie_params_from_dict(cookies: Cookies, url: str = None, domain: str = None) -> list[CookieParam]:
|
|
|
|
[CookieParam.from_json({
|
|
|
|
"name": key,
|
|
|
|
"value": value,
|
|
|
|
"url": url,
|
|
|
|
"domain": domain
|
|
|
|
}) for key, value in cookies.items()]
|
|
|
|
|
|
|
|
async def get_args_from_nodriver(
|
|
|
|
url: str,
|
|
|
|
proxy: str = None,
|
|
|
|
timeout: int = 120,
|
|
|
|
cookies: Cookies = None
|
|
|
|
) -> dict:
|
|
|
|
if not has_nodriver:
|
|
|
|
raise MissingRequirementsError('Install "nodriver" package | pip install -U nodriver')
|
|
|
|
if debug.logging:
|
|
|
|
print(f"Open nodriver with url: {url}")
|
|
|
|
browser = await nodriver.start(
|
|
|
|
browser_args=None if proxy is None else [f"--proxy-server={proxy}"],
|
|
|
|
)
|
|
|
|
domain = urlparse(url).netloc
|
|
|
|
if cookies is None:
|
|
|
|
cookies = {}
|
|
|
|
else:
|
|
|
|
await browser.cookies.set_all(get_cookie_params_from_dict(cookies, url=url, domain=domain))
|
|
|
|
page = await browser.get(url)
|
2024-12-16 21:07:41 +03:00
|
|
|
for c in await page.send(nodriver.cdp.network.get_cookies([url])):
|
|
|
|
cookies[c.name] = c.value
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
user_agent = await page.evaluate("window.navigator.userAgent")
|
|
|
|
await page.wait_for("body:not(.no-js)", timeout=timeout)
|
|
|
|
await page.close()
|
|
|
|
browser.stop()
|
|
|
|
return {
|
2024-12-16 21:07:41 +03:00
|
|
|
"impersonate": "chrome",
|
Fix api streaming, fix AsyncClient (#2357)
* Fix api streaming, fix AsyncClient, Improve Client class, Some providers fixes, Update models list, Fix some tests, Update model list in Airforce provid
er, Add OpenAi image generation url to api, Fix reload and debug in api arguments, Fix websearch in gui
* Fix Cloadflare and Pi and AmigoChat provider
* Fix conversation support in DDG provider, Add cloudflare bypass with nodriver
* Fix unittests without curl_cffi
2024-11-16 15:19:51 +03:00
|
|
|
"cookies": cookies,
|
|
|
|
"headers": {
|
|
|
|
**DEFAULT_HEADERS,
|
|
|
|
"user-agent": user_agent,
|
|
|
|
"referer": url,
|
|
|
|
},
|
|
|
|
"proxy": proxy
|
|
|
|
}
|
|
|
|
|
|
|
|
def merge_cookies(cookies: Iterator[Morsel], response: Response) -> Cookies:
|
|
|
|
if cookies is None:
|
|
|
|
cookies = {}
|
|
|
|
for cookie in response.cookies.jar:
|
2024-11-19 22:45:25 +03:00
|
|
|
cookies[cookie.name] = cookie.value
|
2024-11-26 18:36:45 +03:00
|
|
|
|
2024-12-07 21:38:04 +03:00
|
|
|
async def get_nodriver(proxy: str = None, user_data_dir = "nodriver", **kwargs)-> Browser:
|
2024-11-19 22:45:25 +03:00
|
|
|
if not has_nodriver:
|
|
|
|
raise MissingRequirementsError('Install "nodriver" package | pip install -U nodriver')
|
2024-12-07 21:38:04 +03:00
|
|
|
user_data_dir = user_config_dir(f"g4f-{user_data_dir}") if has_platformdirs else None
|
2024-11-26 18:36:45 +03:00
|
|
|
debug.log(f"Open nodriver with user_dir: {user_data_dir}")
|
2024-11-19 22:45:25 +03:00
|
|
|
return await nodriver.start(
|
|
|
|
user_data_dir=user_data_dir,
|
|
|
|
browser_args=None if proxy is None else [f"--proxy-server={proxy}"],
|
|
|
|
**kwargs
|
|
|
|
)
|