2022-12-21 17:57:37 +00:00
|
|
|
from io import StringIO
|
2022-12-21 14:53:50 +00:00
|
|
|
from urllib import parse
|
2022-12-21 16:46:50 +00:00
|
|
|
from requests import RequestException, Response, Session, post
|
2022-12-21 17:49:01 +00:00
|
|
|
from .config import CLOUDPROXY_ENDPOINT
|
2022-12-21 14:53:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
class FlareRequests(Session):
|
2022-12-21 17:48:31 +00:00
|
|
|
def request(self, method, url, params=None, **kwargs):
|
2022-12-21 14:53:50 +00:00
|
|
|
if not CLOUDPROXY_ENDPOINT:
|
2022-12-21 17:48:31 +00:00
|
|
|
return super().request(method, url, params, **kwargs)
|
2022-12-21 14:53:50 +00:00
|
|
|
|
2022-12-21 17:37:27 +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)
|
|
|
|
|
2022-12-21 17:20:16 +00:00
|
|
|
post_data = {
|
|
|
|
"cmd": f"request.{method.lower()}",
|
2022-12-21 17:37:27 +00:00
|
|
|
"session": FLARESESSION,
|
2022-12-21 17:49:01 +00:00
|
|
|
"url": url,
|
2022-12-21 17:20:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if params:
|
|
|
|
post_data["postData"] = parse.urlencode(params)
|
|
|
|
|
2022-12-21 17:37:27 +00:00
|
|
|
try:
|
|
|
|
response = post(
|
|
|
|
CLOUDPROXY_ENDPOINT,
|
|
|
|
json=post_data,
|
|
|
|
)
|
|
|
|
|
|
|
|
solution = response.json()
|
2022-12-21 17:20:16 +00:00
|
|
|
|
2022-12-21 17:37:27 +00:00
|
|
|
if "solution" in solution:
|
|
|
|
resolved = Response()
|
2022-12-21 17:12:18 +00:00
|
|
|
|
2022-12-21 18:06:03 +00:00
|
|
|
resolved.raw = StringIO(solution["solution"]["response"].encode())
|
2022-12-21 17:37:27 +00:00
|
|
|
resolved.status_code = solution["solution"]["status"]
|
|
|
|
resolved.headers = solution["solution"]["headers"]
|
|
|
|
resolved.url = url
|
|
|
|
resolved.reason = solution["status"]
|
|
|
|
resolved.cookies = solution["solution"]["cookies"]
|
2022-12-21 17:12:18 +00:00
|
|
|
|
2022-12-21 17:37:27 +00:00
|
|
|
return resolved
|
2022-12-21 17:12:18 +00:00
|
|
|
|
2022-12-21 17:37:27 +00:00
|
|
|
raise RequestException(response)
|
|
|
|
except RequestException:
|
|
|
|
session = post(
|
|
|
|
CLOUDPROXY_ENDPOINT,
|
|
|
|
json={"cmd": "sessions.destroy", "session": FLARESESSION},
|
|
|
|
)
|
2022-12-21 17:12:18 +00:00
|
|
|
|
2022-12-21 17:37:27 +00:00
|
|
|
raise RequestException(solution)
|