2023-03-02 13:11:06 +01:00
|
|
|
import json
|
2023-07-05 09:00:03 +02:00
|
|
|
from typing import Optional, Dict
|
2023-07-04 22:02:25 +02:00
|
|
|
|
2023-03-02 13:11:06 +01:00
|
|
|
import requests_cache
|
2023-07-04 22:02:25 +02:00
|
|
|
import platformdirs
|
2023-03-02 13:11:06 +01:00
|
|
|
|
2023-07-04 22:02:25 +02:00
|
|
|
from hanabi import logger
|
|
|
|
from hanabi import constants
|
2023-03-02 13:11:06 +01:00
|
|
|
|
2023-05-13 23:25:15 +02:00
|
|
|
# Cache all requests to site to reduce traffic and latency
|
2023-07-05 18:48:19 +02:00
|
|
|
session = requests_cache.CachedSession(
|
|
|
|
platformdirs.user_cache_dir(constants.APP_NAME) + '/hanab.live',
|
|
|
|
urls_expire_after={
|
|
|
|
'hanab.live/export/*': requests_cache.NEVER_EXPIRE
|
|
|
|
}
|
|
|
|
)
|
2023-03-02 13:11:06 +01:00
|
|
|
|
2023-05-13 23:25:15 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
def get(url, refresh=False) -> Optional[Dict | str]:
|
2023-05-13 23:25:15 +02:00
|
|
|
# print("sending request for " + url)
|
|
|
|
query = "https://hanab.live/" + url
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.debug("GET {} (force_refresh={})".format(query, refresh))
|
2023-05-14 14:04:57 +02:00
|
|
|
response = session.get(query, force_refresh=refresh)
|
2023-05-13 23:25:15 +02:00
|
|
|
if not response:
|
2023-07-07 14:19:57 +02:00
|
|
|
logger.debug("Failed to get request {} from hanab.live".format(query))
|
2023-05-14 14:04:57 +02:00
|
|
|
return None
|
2023-03-02 13:11:06 +01:00
|
|
|
if not response.status_code == 200:
|
2023-07-07 14:19:57 +02:00
|
|
|
logger.debug("Request {} from hanab.live produced status code {}".format(query, response.status_code))
|
2023-03-02 13:11:06 +01:00
|
|
|
return None
|
|
|
|
if "application/json" in response.headers['content-type']:
|
|
|
|
return json.loads(response.text)
|
2023-07-05 09:00:03 +02:00
|
|
|
return response.text
|
2023-03-02 13:11:06 +01:00
|
|
|
|
2023-05-14 14:04:57 +02:00
|
|
|
|
|
|
|
def api(url, refresh=False):
|
2023-03-02 13:11:06 +01:00
|
|
|
link = "api/v1/" + url
|
|
|
|
if "?" in url:
|
|
|
|
link += "&"
|
|
|
|
else:
|
|
|
|
link += "?"
|
|
|
|
link += "size=100"
|
2023-05-14 14:04:57 +02:00
|
|
|
return get(link, refresh)
|
|
|
|
|
2023-03-02 13:11:06 +01:00
|
|
|
|
|
|
|
def replay(seed):
|
|
|
|
r = api("seed/" + str(seed))
|
|
|
|
try:
|
|
|
|
game_id = r['rows'][0]['id']
|
|
|
|
except TypeError:
|
|
|
|
return None
|
|
|
|
return get("export/" + str(game_id))
|