EnkaNetwork.py/enkanetwork/client.py

76 lines
2.6 KiB
Python
Raw Normal View History

2022-07-05 08:46:47 +00:00
import logging
2022-07-12 19:55:54 +00:00
import os
import json
2022-06-22 06:14:31 +00:00
from typing import Union
2022-06-22 06:14:31 +00:00
from .model import EnkaNetworkResponse
from .exception import VaildateUIDError, UIDNotFounded
from .json import Config
2022-07-12 19:55:54 +00:00
from .utils import create_path, validate_uid, request
2022-06-22 06:14:31 +00:00
class EnkaNetworkAPI:
2022-07-05 08:46:47 +00:00
LOGGER = logging.getLogger(__name__)
2022-07-12 19:55:54 +00:00
# JSON Data & Language
RAWDATA = "https://raw.githubusercontent.com/mrwan200/enkanetwork.py-data/{PATH}"
def __init__(self, lang: str = "en", debug: bool = False, key: str = "") -> None:
2022-07-05 08:46:47 +00:00
# Logging
logging.basicConfig()
logging.getLogger("enkanetwork").setLevel(logging.DEBUG if debug else logging.ERROR)
2022-06-22 06:14:31 +00:00
# Set language and load config
2022-07-12 19:55:54 +00:00
self.__load_config(lang)
# Key
self.__key = key
def __load_config(self, lang) -> None:
Config.set_languege(lang)
2022-07-05 08:46:47 +00:00
Config.load_json_data()
Config.load_json_lang()
2022-06-22 06:14:31 +00:00
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}...")
if not validate_uid(str(uid)):
2022-06-22 06:14:31 +00:00
raise VaildateUIDError("Validate UID failed. Please check your UID.")
2022-07-05 08:46:47 +00:00
self.LOGGER.debug(f"Fetching user with UID {uid}...")
2022-07-12 19:55:54 +00:00
resp = await request(url=create_path(f"u/{uid}/__data.json" + ("?key={key}" if self.__key else "")))
# Check if status code is not 200 (Ex. 500)
if resp["status"] != 200:
raise UIDNotFounded(f"UID {uid} not found.")
2022-06-22 06:14:31 +00:00
2022-07-12 19:55:54 +00:00
# Parse JSON data
data = resp["content"]
2022-07-12 19:55:54 +00:00
if not data:
raise UIDNotFounded(f"UID {uid} not found.")
self.LOGGER.debug("Got data from EnkaNetwork.")
self.LOGGER.debug(f"Raw data: {data}")
# Return data
self.LOGGER.debug("Parsing data...")
return EnkaNetworkResponse.parse_obj(data)
2022-06-22 06:14:31 +00:00
2022-07-12 19:55:54 +00:00
async def download_data(self) -> None:
self.LOGGER.debug("Downloading new content...")
_PATH = Config.get_path_json()
for folder in _PATH:
for filename in os.listdir(_PATH[folder]):
self.LOGGER.debug(f"Downloading {folder} file {filename}...")
_json = await request(
url=self.RAWDATA.format(PATH=f"master/exports/{folder}/{filename}")
)
2022-07-05 08:46:47 +00:00
2022-07-12 19:55:54 +00:00
self.LOGGER.debug(f"Writing {folder} file {filename}...")
with open(os.path.join(_PATH[folder], filename), "w", encoding="utf-8") as f:
json.dump(_json["content"], f, ensure_ascii=False, indent=4)
2022-06-22 06:14:31 +00:00
2022-07-12 19:55:54 +00:00
# Load config
self.__load_config(Config.LANGS)