2023-06-24 11:30:54 +00:00
|
|
|
from http.cookiejar import CookieJar
|
|
|
|
from http.cookies import SimpleCookie
|
2023-05-01 09:30:57 +00:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from httpx import Cookies as _Cookies
|
|
|
|
|
2023-06-24 11:30:54 +00:00
|
|
|
from simnet.utils.types import CookieTypes
|
|
|
|
|
2023-05-05 12:04:41 +00:00
|
|
|
__all__ = ("Cookies",)
|
|
|
|
|
2023-05-01 09:30:57 +00:00
|
|
|
|
|
|
|
class Cookies(_Cookies):
|
2023-06-24 11:30:54 +00:00
|
|
|
"""A wrapper around `httpx.Cookies` that provides additional functionality."""
|
|
|
|
|
|
|
|
def __init__(self, cookies: Optional[CookieTypes] = None): # skipcq: PYL-W0231
|
|
|
|
if cookies is None or isinstance(cookies, dict):
|
|
|
|
self.jar = CookieJar()
|
|
|
|
if isinstance(cookies, dict):
|
|
|
|
for key, value in cookies.items():
|
|
|
|
if isinstance(value, str):
|
|
|
|
self.set(key, value)
|
|
|
|
else:
|
|
|
|
self.set(key, str(value))
|
|
|
|
elif isinstance(cookies, list):
|
|
|
|
self.jar = CookieJar()
|
|
|
|
for key, value in cookies:
|
|
|
|
self.set(key, value)
|
|
|
|
elif isinstance(cookies, Cookies):
|
|
|
|
self.jar = CookieJar()
|
|
|
|
for cookie in cookies.jar:
|
|
|
|
self.jar.set_cookie(cookie)
|
|
|
|
elif isinstance(cookies, str):
|
2023-07-17 05:14:40 +00:00
|
|
|
self.jar = CookieJar()
|
2023-06-24 11:30:54 +00:00
|
|
|
cookie = SimpleCookie(cookies)
|
|
|
|
for key, value in cookie.items():
|
|
|
|
self.set(key, value.value)
|
|
|
|
else:
|
|
|
|
self.jar = cookies
|
2023-05-01 09:30:57 +00:00
|
|
|
|
2023-05-09 07:19:36 +00:00
|
|
|
COOKIE_USER_ID_NAMES = ("ltuid", "account_id", "stuid", "ltuid_v2", "account_id_v2")
|
2023-05-01 09:30:57 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def account_id(self) -> Optional[int]:
|
|
|
|
"""Return the user account ID if present in the cookies.
|
|
|
|
|
|
|
|
If one of the user ID cookies exists in the cookies, return its integer value.
|
|
|
|
Otherwise, return `None`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Optional[int]: The user account ID, or `None` if it is not present in the cookies.
|
|
|
|
"""
|
|
|
|
for name in self.COOKIE_USER_ID_NAMES:
|
|
|
|
value = self.get(name)
|
|
|
|
if value is not None:
|
|
|
|
return int(value)
|
|
|
|
return None
|