2022-12-21 14:53:50 +00:00
|
|
|
from urllib import parse
|
|
|
|
from requests import RequestException, Session, post
|
2022-12-21 15:14:43 +00:00
|
|
|
from .config import CLOUDPROXY_ENDPOINT, REQUESTS_TIMEOUT
|
2022-12-21 14:53:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
class FlareRequests(Session):
|
2022-12-21 15:23:06 +00:00
|
|
|
def request(self, method, url, params=None, timeout=REQUESTS_TIMEOUT, **kwargs):
|
2022-12-21 14:53:50 +00:00
|
|
|
if not CLOUDPROXY_ENDPOINT:
|
2022-12-21 15:14:43 +00:00
|
|
|
return super().request(method, url, params, timeout=timeout, **kwargs)
|
2022-12-21 14:53:50 +00:00
|
|
|
|
|
|
|
sessions = post(CLOUDPROXY_ENDPOINT, json={"cmd": "sessions.list"}).json()
|
|
|
|
|
|
|
|
if "sessions" in sessions and len(sessions["sessions"]) > 0:
|
|
|
|
FLARESESSION = sessions["sessions"][0]
|
|
|
|
else:
|
|
|
|
response = post(CLOUDPROXY_ENDPOINT, json={"cmd": "sessions.create"})
|
|
|
|
session = response.json()
|
|
|
|
|
|
|
|
if "session" in session:
|
|
|
|
FLARESESSION = session["session"]
|
|
|
|
else:
|
|
|
|
raise RequestException(response)
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = post(
|
|
|
|
CLOUDPROXY_ENDPOINT,
|
|
|
|
json={
|
|
|
|
"cmd": f"request.{method.lower()}",
|
|
|
|
"session": FLARESESSION,
|
|
|
|
"url": url,
|
2022-12-21 15:31:05 +00:00
|
|
|
"postData": parse.urlencode(params) if params else "",
|
2022-12-21 15:40:10 +00:00
|
|
|
"maxTimeout": timeout * 1000,
|
2022-12-21 14:53:50 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
solution = response.json()
|
|
|
|
|
|
|
|
if "solution" in solution:
|
2022-12-21 15:56:04 +00:00
|
|
|
response.status_code = solution["solution"]["status"]
|
2022-12-21 14:53:50 +00:00
|
|
|
response.headers = solution["solution"]["headers"]
|
2022-12-21 15:56:04 +00:00
|
|
|
response.raw = solution["solution"]["response"]
|
|
|
|
response.url = url
|
|
|
|
response.cookies = solution["solution"]["cookies"]
|
2022-12-21 14:53:50 +00:00
|
|
|
|
|
|
|
return response
|
|
|
|
|
|
|
|
raise RequestException(response)
|
|
|
|
except RequestException:
|
|
|
|
session = post(
|
2022-12-21 15:14:43 +00:00
|
|
|
CLOUDPROXY_ENDPOINT,
|
2022-12-21 15:41:50 +00:00
|
|
|
json={"cmd": "sessions.destroy", "session": FLARESESSION},
|
2022-12-21 14:53:50 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
raise RequestException(solution)
|