2023-05-14 10:40:47 +02:00
|
|
|
import alive_progress
|
2023-05-13 23:07:10 +02:00
|
|
|
from typing import Dict, Optional
|
|
|
|
|
2023-05-14 10:22:06 +02:00
|
|
|
import psycopg2.errors
|
2023-07-05 18:47:09 +02:00
|
|
|
import platformdirs
|
2023-05-14 10:22:06 +02:00
|
|
|
|
2023-07-04 20:06:06 +02:00
|
|
|
from hanabi import hanab_game
|
2023-07-05 18:47:09 +02:00
|
|
|
from hanabi import constants
|
|
|
|
from hanabi import logger
|
2023-07-04 20:06:06 +02:00
|
|
|
from hanabi.database import database
|
|
|
|
from hanabi.live import site_api
|
|
|
|
from hanabi.live import compress
|
|
|
|
from hanabi.live import variants
|
|
|
|
from hanabi.live import hanab_live
|
2023-03-02 13:27:26 +01:00
|
|
|
|
2023-05-14 14:03:42 +02:00
|
|
|
|
2023-05-06 17:42:27 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
class GameExportError(ValueError):
|
|
|
|
def __init__(self, game_id, msg):
|
|
|
|
super().__init__("When exporting game {}: {}".format(game_id, msg))
|
2023-07-05 16:31:10 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class GameExportNoResponseFromSiteError(GameExportError):
|
|
|
|
def __init__(self, game_id):
|
|
|
|
super().__init__(game_id, "No response from site")
|
|
|
|
|
|
|
|
|
|
|
|
class GameExportInvalidResponseTypeError(GameExportError):
|
|
|
|
def __init__(self, game_id, response_type):
|
|
|
|
super().__init__(game_id, "Invalid response type (expected json, got {})".format(
|
|
|
|
response_type, game_id
|
|
|
|
))
|
2023-07-05 16:31:10 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class GameExportInvalidFormatError(GameExportError):
|
|
|
|
def __init__(self, game_id, msg):
|
2023-07-05 16:31:10 +02:00
|
|
|
super().__init__(game_id, "Invalid response format: {}".format(msg))
|
2023-07-05 09:00:03 +02:00
|
|
|
|
|
|
|
|
|
|
|
class GameExportInvalidNumberOfPlayersError(GameExportInvalidFormatError):
|
|
|
|
def __init__(self, game_id, expected, received):
|
2023-07-05 16:44:22 +02:00
|
|
|
super().__init__(
|
|
|
|
game_id,
|
|
|
|
"Received invalid list of players: Expected {} many, got {}".format(expected, received)
|
|
|
|
)
|
2023-07-05 09:00:03 +02:00
|
|
|
|
|
|
|
|
2023-05-13 23:07:10 +02:00
|
|
|
#
|
2023-07-05 09:00:03 +02:00
|
|
|
def detailed_export_game(
|
2023-07-05 16:31:10 +02:00
|
|
|
game_id: int
|
|
|
|
, score: Optional[int] = None
|
|
|
|
, var_id: Optional[int] = None
|
|
|
|
, seed_exists: bool = False
|
|
|
|
) -> None:
|
2023-05-13 23:07:10 +02:00
|
|
|
"""
|
2023-07-05 09:00:03 +02:00
|
|
|
Downloads full details of game from hanab.live, inserts seed and game into DB
|
2023-05-13 23:07:10 +02:00
|
|
|
If seed is already present, it is left as is
|
|
|
|
If game is already present, game details will be updated
|
|
|
|
|
2023-07-05 16:44:22 +02:00
|
|
|
:param game_id: id of game to export
|
2023-05-13 23:07:10 +02:00
|
|
|
:param score: If given, this will be inserted as score of the game. If not given, score is calculated
|
2023-07-05 09:00:03 +02:00
|
|
|
:param var_id: If given, this will be inserted as variant id of the game. If not given, this is looked up
|
2023-05-13 23:07:10 +02:00
|
|
|
:param seed_exists: If specified and true, assumes that the seed is already present in database.
|
|
|
|
If this is not the case, call will raise a DB insertion error
|
2023-07-05 09:00:03 +02:00
|
|
|
|
|
|
|
:raises GameExportError and its child classes
|
2023-05-13 23:07:10 +02:00
|
|
|
"""
|
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
logger.debug("Importing game {}".format(game_id))
|
2023-05-14 14:03:42 +02:00
|
|
|
|
2023-07-04 20:06:06 +02:00
|
|
|
game_json = site_api.get("export/{}".format(game_id))
|
2023-07-05 09:00:03 +02:00
|
|
|
if game_json is None:
|
2023-07-05 18:47:09 +02:00
|
|
|
raise GameExportNoResponseFromSiteError(game_id)
|
2023-07-05 09:00:03 +02:00
|
|
|
if type(game_json) != dict:
|
|
|
|
raise GameExportInvalidResponseTypeError(game_id, type(game_json))
|
|
|
|
|
|
|
|
if game_json.get('id', None) != game_id:
|
|
|
|
raise GameExportInvalidFormatError(game_id, "Unexpected game_id {} received, expected {}".format(
|
|
|
|
game_json.get('id'), game_id
|
|
|
|
))
|
2023-05-13 23:07:10 +02:00
|
|
|
|
|
|
|
players = game_json.get('players', [])
|
|
|
|
num_players = len(players)
|
2023-07-05 09:00:03 +02:00
|
|
|
if num_players < 2:
|
|
|
|
raise GameExportInvalidNumberOfPlayersError(game_id, "≥2", num_players)
|
|
|
|
|
2023-05-13 23:07:10 +02:00
|
|
|
seed = game_json.get('seed', None)
|
2023-07-05 09:00:03 +02:00
|
|
|
if type(seed) != str:
|
|
|
|
raise GameExportInvalidFormatError(game_id, "Unexpected seed, expected string, got {}".format(seed))
|
|
|
|
|
2023-05-13 23:07:10 +02:00
|
|
|
options = game_json.get('options', {})
|
2023-07-04 20:06:06 +02:00
|
|
|
var_id = var_id or variants.variant_id(options.get('variant', 'No Variant'))
|
2023-05-13 23:07:10 +02:00
|
|
|
deck_plays = options.get('deckPlays', False)
|
|
|
|
one_extra_card = options.get('oneExtraCard', False)
|
|
|
|
one_less_card = options.get('oneLessCard', False)
|
|
|
|
all_or_nothing = options.get('allOrNothing', False)
|
2023-06-24 17:23:05 +02:00
|
|
|
starting_player = options.get('startingPlayer', 0)
|
2023-05-13 23:07:10 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
try:
|
|
|
|
actions = [hanab_game.Action.from_json(action) for action in game_json.get('actions', [])]
|
|
|
|
except hanab_game.ParseError as e:
|
|
|
|
raise GameExportInvalidFormatError(game_id, "Failed to parse actions") from e
|
|
|
|
|
|
|
|
try:
|
|
|
|
deck = [hanab_game.DeckCard.from_json(card) for card in game_json.get('deck', None)]
|
|
|
|
except hanab_game.ParseError as e:
|
|
|
|
raise GameExportInvalidFormatError(game_id, "Failed to parse deck") from e
|
2023-05-13 23:07:10 +02:00
|
|
|
|
|
|
|
if score is None:
|
2023-05-06 17:42:27 +02:00
|
|
|
# need to play through the game once to find out its score
|
2023-07-04 20:06:06 +02:00
|
|
|
game = hanab_live.HanabLiveGameState(
|
|
|
|
hanab_live.HanabLiveInstance(
|
2023-06-24 17:23:05 +02:00
|
|
|
deck, num_players, var_id,
|
|
|
|
deck_plays=deck_plays,
|
|
|
|
one_less_card=one_less_card,
|
|
|
|
one_extra_card=one_extra_card,
|
|
|
|
all_or_nothing=all_or_nothing
|
|
|
|
),
|
|
|
|
starting_player
|
|
|
|
)
|
|
|
|
print(game.instance.hand_size, game.instance.num_players)
|
2023-05-06 17:42:27 +02:00
|
|
|
for action in actions:
|
|
|
|
game.make_action(action)
|
2023-05-13 23:07:10 +02:00
|
|
|
score = game.score
|
|
|
|
|
|
|
|
try:
|
2023-07-04 20:06:06 +02:00
|
|
|
compressed_deck = compress.compress_deck(deck)
|
2023-07-05 09:00:03 +02:00
|
|
|
except compress.InvalidFormatError as e:
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.error("Failed to compress deck while exporting game {}: {}".format(game_id, deck))
|
2023-07-05 09:00:03 +02:00
|
|
|
raise GameExportInvalidFormatError(game_id, "Failed to compress deck") from e
|
|
|
|
|
2023-05-13 23:07:10 +02:00
|
|
|
try:
|
2023-07-04 20:06:06 +02:00
|
|
|
compressed_actions = compress.compress_actions(actions)
|
2023-07-05 09:00:03 +02:00
|
|
|
except compress.InvalidFormatError as e:
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.error("Failed to compress actions while exporting game {}".format(game_id))
|
2023-07-05 09:00:03 +02:00
|
|
|
raise GameExportInvalidFormatError(game_id, "Failed to compress actions") from e
|
2023-05-13 23:07:10 +02:00
|
|
|
|
|
|
|
if not seed_exists:
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute(
|
2023-05-13 23:07:10 +02:00
|
|
|
"INSERT INTO seeds (seed, num_players, variant_id, deck)"
|
|
|
|
"VALUES (%s, %s, %s, %s)"
|
|
|
|
"ON CONFLICT (seed) DO NOTHING",
|
|
|
|
(seed, num_players, var_id, compressed_deck)
|
|
|
|
)
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.debug("New seed {} imported.".format(seed))
|
2023-05-13 23:07:10 +02:00
|
|
|
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute(
|
2023-05-13 23:07:10 +02:00
|
|
|
"INSERT INTO games ("
|
2023-06-24 18:35:15 +02:00
|
|
|
"id, num_players, starting_player, score, seed, variant_id, deck_plays, one_extra_card, one_less_card,"
|
2023-05-13 23:07:10 +02:00
|
|
|
"all_or_nothing, actions"
|
|
|
|
")"
|
2023-06-24 18:35:15 +02:00
|
|
|
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
|
2023-05-13 23:07:10 +02:00
|
|
|
"ON CONFLICT (id) DO UPDATE SET ("
|
|
|
|
"deck_plays, one_extra_card, one_less_card, all_or_nothing, actions"
|
|
|
|
") = ("
|
|
|
|
"EXCLUDED.deck_plays, EXCLUDED.one_extra_card, EXCLUDED.one_less_card, EXCLUDED.all_or_nothing,"
|
|
|
|
"EXCLUDED.actions"
|
|
|
|
")",
|
|
|
|
(
|
2023-06-24 18:35:15 +02:00
|
|
|
game_id, num_players, starting_player, score, seed, var_id, deck_plays, one_extra_card, one_less_card,
|
2023-05-13 23:07:10 +02:00
|
|
|
all_or_nothing, compressed_actions
|
|
|
|
)
|
|
|
|
)
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.debug("Imported game {}".format(game_id))
|
2023-05-13 23:07:10 +02:00
|
|
|
|
|
|
|
|
2023-07-05 16:31:10 +02:00
|
|
|
def _process_game_row(game: Dict, var_id, export_all_games: bool = False):
|
2023-05-13 23:07:10 +02:00
|
|
|
game_id = game.get('id', None)
|
|
|
|
seed = game.get('seed', None)
|
|
|
|
num_players = game.get('num_players', None)
|
2023-07-05 16:44:22 +02:00
|
|
|
users = game.get('users', "").split(", ")
|
2023-05-13 23:07:10 +02:00
|
|
|
score = game.get('score', None)
|
|
|
|
|
|
|
|
if any(v is None for v in [game_id, seed, num_players, score]):
|
|
|
|
raise ValueError("Unknown response format on hanab.live")
|
|
|
|
|
2023-07-05 16:44:22 +02:00
|
|
|
if len(users) != num_players:
|
2023-07-05 18:47:09 +02:00
|
|
|
logger.error("Invalid number of players reported when processing row {}".format(game))
|
|
|
|
f = platformdirs.user_data_dir(constants.APP_NAME, ensure_exists=True) + '/invalid_game_ids.txt'
|
|
|
|
with open(f, "a+") as invalid_games_file:
|
|
|
|
invalid_games_file.writelines(
|
|
|
|
"{}, {}, {}\n".format(game_id, num_players, ", ".join(users))
|
|
|
|
)
|
|
|
|
return
|
|
|
|
# raise GameExportInvalidNumberOfPlayersError(game_id, num_players, users)
|
2023-07-05 16:44:22 +02:00
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
if export_all_games:
|
2023-07-05 16:44:22 +02:00
|
|
|
detailed_export_game(game_id, score=score, var_id=var_id)
|
2023-07-05 09:00:03 +02:00
|
|
|
logger.debug("Imported game {}".format(game_id))
|
|
|
|
return
|
|
|
|
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute("SAVEPOINT seed_insert")
|
2023-05-14 10:22:06 +02:00
|
|
|
try:
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute(
|
2023-05-13 23:07:10 +02:00
|
|
|
"INSERT INTO games (id, seed, num_players, score, variant_id)"
|
|
|
|
"VALUES"
|
|
|
|
"(%s, %s ,%s ,%s ,%s)"
|
|
|
|
"ON CONFLICT (id) DO NOTHING",
|
|
|
|
(game_id, seed, num_players, score, var_id)
|
|
|
|
)
|
2023-05-14 10:22:06 +02:00
|
|
|
except psycopg2.errors.ForeignKeyViolation:
|
2023-07-05 09:00:03 +02:00
|
|
|
# Sometimes, seed is not present in the database yet, then we will have to query the full game details
|
|
|
|
# (including the seed) to export it accordingly
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute("ROLLBACK TO seed_insert")
|
2023-07-05 16:44:22 +02:00
|
|
|
detailed_export_game(game_id, score=score, var_id=var_id)
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute("RELEASE seed_insert")
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.debug("Imported game {}".format(game_id))
|
2023-05-13 23:07:10 +02:00
|
|
|
|
|
|
|
|
2023-07-05 09:00:03 +02:00
|
|
|
def download_games(var_id, export_all_games: bool = False):
|
2023-07-04 20:06:06 +02:00
|
|
|
name = variants.variant_name(var_id)
|
2023-05-13 23:07:10 +02:00
|
|
|
page_size = 100
|
|
|
|
if name is None:
|
|
|
|
raise ValueError("{} is not a known variant_id.".format(var_id))
|
|
|
|
|
|
|
|
url = "variants/{}".format(var_id)
|
2023-07-04 20:06:06 +02:00
|
|
|
r = site_api.api(url, refresh=True)
|
2023-05-13 23:07:10 +02:00
|
|
|
if not r:
|
|
|
|
raise RuntimeError("Failed to download request from hanab.live")
|
|
|
|
|
|
|
|
num_entries = r.get('total_rows', None)
|
|
|
|
if num_entries is None:
|
|
|
|
raise ValueError("Unknown response format on hanab.live")
|
|
|
|
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute(
|
2023-05-13 23:07:10 +02:00
|
|
|
"SELECT COUNT(*) FROM games WHERE variant_id = %s AND id <= "
|
|
|
|
"(SELECT COALESCE (last_game_id, 0) FROM variant_game_downloads WHERE variant_id = %s)",
|
|
|
|
(var_id, var_id)
|
|
|
|
)
|
2023-07-04 20:06:06 +02:00
|
|
|
num_already_downloaded_games = database.cur.fetchone()[0]
|
2023-05-14 14:03:42 +02:00
|
|
|
assert num_already_downloaded_games <= num_entries, "Database inconsistent, too many games present."
|
2023-05-13 23:07:10 +02:00
|
|
|
next_page = num_already_downloaded_games // page_size
|
|
|
|
last_page = (num_entries - 1) // page_size
|
|
|
|
|
|
|
|
if num_already_downloaded_games == num_entries:
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.info("Already downloaded all games ({} many) for variant {} [{}]".format(num_entries, var_id, name))
|
2023-05-13 23:07:10 +02:00
|
|
|
return
|
2023-05-14 23:53:20 +02:00
|
|
|
logger.info(
|
2023-05-13 23:07:10 +02:00
|
|
|
"Downloading remaining {} (total {}) entries for variant {} [{}]".format(
|
|
|
|
num_entries - num_already_downloaded_games, num_entries, var_id, name
|
|
|
|
)
|
|
|
|
)
|
2023-05-06 17:42:27 +02:00
|
|
|
|
2023-05-14 10:40:47 +02:00
|
|
|
with alive_progress.alive_bar(
|
|
|
|
total=num_entries - num_already_downloaded_games,
|
2023-05-14 14:03:42 +02:00
|
|
|
title='Downloading games for variant id {} [{}]'.format(var_id, name),
|
|
|
|
enrich_print=False
|
2023-05-14 10:40:47 +02:00
|
|
|
) as bar:
|
|
|
|
for page in range(next_page, last_page + 1):
|
2023-07-04 20:06:06 +02:00
|
|
|
r = site_api.api(url + "?col[0]=0&page={}".format(page), refresh=page == last_page)
|
2023-05-14 10:40:47 +02:00
|
|
|
rows = r.get('rows', [])
|
2023-05-14 14:03:42 +02:00
|
|
|
if page == next_page:
|
|
|
|
rows = rows[num_already_downloaded_games % 100:]
|
2023-05-14 10:40:47 +02:00
|
|
|
if not (page == last_page or len(rows) == page_size):
|
2023-05-14 14:03:42 +02:00
|
|
|
logger.warn('WARN: received unexpected row count ({}) on page {}'.format(len(rows), page))
|
2023-05-14 10:40:47 +02:00
|
|
|
for row in rows:
|
2023-07-05 16:31:10 +02:00
|
|
|
_process_game_row(row, var_id, export_all_games)
|
2023-05-14 10:40:47 +02:00
|
|
|
bar()
|
2023-07-04 20:06:06 +02:00
|
|
|
database.cur.execute(
|
2023-05-14 10:40:47 +02:00
|
|
|
"INSERT INTO variant_game_downloads (variant_id, last_game_id) VALUES"
|
|
|
|
"(%s, %s)"
|
|
|
|
"ON CONFLICT (variant_id) DO UPDATE SET last_game_id = EXCLUDED.last_game_id",
|
|
|
|
(var_id, r['rows'][-1]['id'])
|
|
|
|
)
|
2023-07-04 20:06:06 +02:00
|
|
|
database.conn.commit()
|