EnkaNetwork.py/enkanetwork/client.py

126 lines
3.6 KiB
Python
Raw Normal View History

from __future__ import annotations
import os
import json
import logging
2022-08-10 07:18:26 +00:00
from time import time
from .http import HTTPClient
2022-06-22 06:14:31 +00:00
from .model import EnkaNetworkResponse
2022-07-16 19:35:08 +00:00
from .assets import Assets
2022-07-18 08:54:24 +00:00
from .enum import Language
2022-08-02 17:37:24 +00:00
from .cache import Cache
2022-07-12 19:55:54 +00:00
from typing import Union, Optional, Type, TYPE_CHECKING
if TYPE_CHECKING:
from typing_extensions import Self
from types import TracebackType
__all__ = ("EnkaNetworkAPI",)
2022-07-29 04:31:21 +00:00
2022-06-22 06:14:31 +00:00
class EnkaNetworkAPI:
2022-07-05 08:46:47 +00:00
LOGGER = logging.getLogger(__name__)
2022-08-10 07:18:26 +00:00
def __init__(self, lang: str = "en", *, debug: bool = False, key: str = "", cache: bool = True, agent: str = "", timeout: int = 10) -> None: # noqa: E501
2022-07-05 08:46:47 +00:00
# Logging
logging.basicConfig()
2022-07-29 04:31:21 +00:00
logging.getLogger("enkanetwork").setLevel(logging.DEBUG if debug else logging.ERROR) # noqa: E501
2022-06-22 06:14:31 +00:00
# Set language and load config
2022-07-16 19:35:08 +00:00
self.assets = Assets(lang)
2022-07-12 19:55:54 +00:00
2022-08-02 17:37:24 +00:00
# Cache
self._enable_cache = cache
self.cache = Cache(1024, 60 * 3)
# http client
2022-08-10 07:18:26 +00:00
self.__http = HTTPClient(key=key, agent=agent, timeout=timeout)
self._closed = False
2022-08-03 07:50:43 +00:00
async def __aenter__(self) -> Self:
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
self._close = True
if self._close:
await self.__http.close()
def is_closed(self) -> bool:
return self._closed
2022-06-22 06:14:31 +00:00
2022-08-22 09:39:55 +00:00
@property
def http(self) -> HTTPClient:
return self.__http
@http.setter
def http(self, http: HTTPClient) -> None:
self.__http = http
2022-07-18 08:54:24 +00:00
@property
def lang(self) -> Language:
return self.assets.LANGS
@lang.setter
def lang(self, lang: Language) -> None:
self.assets._set_language(lang)
2022-08-02 17:37:24 +00:00
def set_cache(self, cache: Cache) -> None:
self.cache = cache
2022-07-18 08:54:24 +00:00
async def set_language(self, lang: Language) -> None:
self.lang = lang
async def fetch_user(self, uid: Union[str, int]) -> EnkaNetworkResponse:
2022-07-05 08:46:47 +00:00
self.LOGGER.debug(f"Validating with UID {uid}...")
2022-08-02 17:37:24 +00:00
if self._enable_cache:
self.LOGGER.warning("Getting data from cache...")
2022-08-05 01:41:21 +00:00
data = await self.cache.get(uid)
2022-08-02 17:37:24 +00:00
if data is not None:
# Return data
self.LOGGER.debug("Parsing data...")
return EnkaNetworkResponse.parse_obj(data)
2022-08-02 17:40:30 +00:00
2022-08-05 01:41:21 +00:00
user = await self.__http.fetch_user(uid)
data = user["content"]
2022-08-15 20:17:34 +00:00
data = json.loads(data)
2022-08-05 01:41:21 +00:00
self.LOGGER.debug(f"Fetching user with UID {uid}...")
if self._enable_cache:
self.LOGGER.debug("Caching data...")
await self.cache.set(uid, data)
2022-07-12 19:55:54 +00:00
# Return data
self.LOGGER.debug("Parsing data...")
return EnkaNetworkResponse.parse_obj(data)
2022-06-22 06:14:31 +00:00
async def update_assets(self) -> None:
print("Updating assets...")
2022-07-12 19:55:54 +00:00
self.LOGGER.debug("Downloading new content...")
path = Assets._get_path_assets()
for folder in path:
for filename in os.listdir(path[folder]):
self.LOGGER.debug(f"Downloading {folder} file {filename}...")
2022-08-05 02:21:21 +00:00
data = await self.__http.fetch_asset(folder, filename)
self.LOGGER.debug(f"Writing {folder} file {filename}...")
# dumps to json file
with open(os.path.join(path[folder], filename), "w", encoding="utf-8") as f:
2022-08-15 20:17:34 +00:00
json.dump(json.loads(data["content"]), f, ensure_ascii=False, indent=4)
2022-06-22 06:14:31 +00:00
# Reload config
2022-07-29 04:31:21 +00:00
self.assets.reload_assets()