This repository has been archived on 2023-10-01. You can view files and clone it, but cannot push or open issues or pull requests.
PyNyaaTa/pynyaata/flarerequests.py

52 lines
1.6 KiB
Python
Raw Normal View History

2022-12-21 18:12:20 +00:00
from io import BytesIO
2022-12-21 14:53:50 +00:00
from urllib import parse
2023-01-05 14:19:04 +00:00
from requests import 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-24 14:22:33 +00:00
def request(self, method, url, params=None, data=None, **kwargs):
2022-12-21 14:53:50 +00:00
if not CLOUDPROXY_ENDPOINT:
2022-12-24 14:22:33 +00:00
return super().request(method, url, params, data, **kwargs)
2022-12-21 14:53:50 +00:00
2022-12-24 14:22:33 +00:00
if params:
url += "&" if len(url.split("?")) > 1 else "?"
url = f"{url}{parse.urlencode(params)}"
2022-12-21 17:20:16 +00:00
post_data = {
"cmd": f"request.{method.lower()}",
2022-12-21 17:49:01 +00:00
"url": url,
2022-12-21 17:20:16 +00:00
}
2022-12-24 14:22:33 +00:00
if data:
post_data["postData"] = parse.urlencode(data)
2022-12-21 17:20:16 +00:00
2023-01-05 14:19:04 +00:00
response = post(
CLOUDPROXY_ENDPOINT,
json=post_data,
)
solution = response.json()
if "solution" in solution:
2023-01-05 19:50:17 +00:00
encoding = None
2023-01-05 14:19:04 +00:00
headers = solution["solution"]["headers"]
if "content-type" in headers:
content_type = headers["content-type"].split(";")
if len(content_type) > 1:
charset = content_type[1].split("=")
if len(charset) > 1:
encoding = charset[1]
resolved = Response()
resolved.status_code = solution["solution"]["status"]
resolved.headers = headers
resolved.raw = BytesIO(solution["solution"]["response"].encode())
resolved.url = url
2023-01-05 19:50:17 +00:00
resolved.encoding = encoding
2023-01-05 14:19:04 +00:00
resolved.reason = solution["status"]
resolved.cookies = solution["solution"]["cookies"]
return resolved