2024-12-09 02:22:28 +00:00
|
|
|
import asyncio
|
2024-12-01 07:42:35 +00:00
|
|
|
from typing import Dict, List
|
2024-12-02 12:58:16 +00:00
|
|
|
|
2024-11-30 11:27:32 +00:00
|
|
|
import aiohttp
|
|
|
|
|
2024-12-02 12:58:16 +00:00
|
|
|
from token_bot.token_database.exceptions import *
|
|
|
|
from token_bot.token_database.flavor import Flavor
|
2024-11-30 11:27:32 +00:00
|
|
|
from token_bot.token_database.region import Region
|
|
|
|
|
|
|
|
|
|
|
|
class Database:
|
|
|
|
def __init__(self, session: aiohttp.ClientSession):
|
|
|
|
self.data_url = "https://data.wowtoken.app/v2/"
|
|
|
|
self.session = session
|
|
|
|
|
|
|
|
async def _get_data(self, endpoint: str) -> Dict | List:
|
|
|
|
url = f"{self.data_url}{endpoint}"
|
|
|
|
|
|
|
|
success = False
|
|
|
|
tries = 0
|
2024-12-09 02:22:28 +00:00
|
|
|
backoff = 0.1
|
2024-11-30 11:27:32 +00:00
|
|
|
|
2024-12-09 02:22:28 +00:00
|
|
|
while not success and tries <= 5:
|
|
|
|
if tries > 1:
|
|
|
|
await asyncio.sleep(backoff * tries)
|
2024-11-30 11:27:32 +00:00
|
|
|
try:
|
|
|
|
return await self._external_call(url)
|
|
|
|
except TokenHttpException:
|
|
|
|
tries += 1
|
2024-12-09 02:22:28 +00:00
|
|
|
raise TokenHttpException
|
2024-11-30 11:27:32 +00:00
|
|
|
|
|
|
|
async def _external_call(self, url) -> Dict | List:
|
|
|
|
async with self.session.get(url) as resp:
|
|
|
|
await resp.text()
|
|
|
|
if resp.ok:
|
|
|
|
return await resp.json()
|
|
|
|
else:
|
|
|
|
raise TokenHttpException(resp.status)
|
|
|
|
|
|
|
|
async def current(self, flavor: Flavor) -> dict:
|
2024-12-09 01:07:26 +00:00
|
|
|
return await self._get_data(f"current/{flavor.name.lower()}.json")
|
2024-11-30 11:27:32 +00:00
|
|
|
|
2024-12-09 01:07:26 +00:00
|
|
|
async def history(self, flavor: Flavor, region: Region, relative_time: str = "all"):
|
|
|
|
return await self._get_data(
|
|
|
|
f"relative/{flavor.name.lower()}/{region.value.lower()}/{relative_time}.json"
|
|
|
|
)
|