[boardgames] Modularize the Lichess imports

This commit is contained in:
2025-02-25 11:09:29 -05:00
parent 3f9cdcac65
commit baa8dbee46

View File

@ -8,13 +8,12 @@ from scrobbles.utils import send_notifications_for_scrobble
User = get_user_model()
def import_chess_games_for_all_users():
def import_chess_games_for_user_id(user_id: int, commit: bool = False) -> dict:
user = User.objects.get(id=user_id)
client = berserk.Client(
session=berserk.TokenSession(settings.LICHESS_API_KEY)
)
scrobbles_to_create = []
for user in User.objects.filter(profile__lichess_username__isnull=False):
games = client.games.export_by_player(user.profile.lichess_username)
for game_dict in games:
chess, created = BoardGame.objects.get_or_create(title="Chess")
@ -63,9 +62,9 @@ def import_chess_games_for_all_users():
white_player.get("aiLevel", "")
)
else:
other_player["name_str"] = white_player.get(
"user", {}
).get("name", "")
other_player["name_str"] = white_player.get("user", {}).get(
"name", ""
)
other_player["lichess_username"] = other_player["name_str"]
other_player["color"] = "white"
@ -83,9 +82,9 @@ def import_chess_games_for_all_users():
black_player.get("aiLevel", "")
)
else:
other_player["name_str"] = black_player.get(
"user", {}
).get("name", "")
other_player["name_str"] = black_player.get("user", {}).get(
"name", ""
)
other_player["lichess_username"] = other_player["name_str"]
other_player["color"] = "black"
if winner == "white":
@ -111,6 +110,15 @@ def import_chess_games_for_all_users():
"timezone": user.profile.timezone,
"log": log_data,
}
if commit:
Scrobble.objects.create(**scrobble_dict)
return scrobble_dict
def import_chess_games_for_all_users():
scrobbles_to_create = []
for user in User.objects.filter(profile__lichess_username__isnull=False):
scrobble_dict = import_chess_games_for_user_id(user.id)
scrobbles_to_create.append(Scrobble(**scrobble_dict))
if scrobbles_to_create: