Skip to content

Commit

Permalink
Refactor language handling in webapi routers
Browse files Browse the repository at this point in the history
  • Loading branch information
lichifeng committed Apr 28, 2024
1 parent 827f2f7 commit 2c28499
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 15 deletions.
2 changes: 1 addition & 1 deletion mgxhub/db/operation/add_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def add_game(session: Session, d: dict, t: str | None = None, source: str = "")
population=d.get('population'),
speed=d.get('speedEn'),
matchup=d.get('matchup'),
map_name=d.get('map', {}).get('nameEn'),
map_name=d.get('map', {}).get('nameEn', d.get('map', {}).get('name')),
map_size=d.get('map', {}).get('sizeEn'),
version_code=d.get('version', {}).get('code'),
version_log=d.get('version', {}).get('logVer'),
Expand Down
13 changes: 9 additions & 4 deletions mgxhub/db/operation/get_player_recent_games.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
'''Get recent games of a player.'''

import gettext

from sqlalchemy import desc
from sqlalchemy.orm import Session

from mgxhub.model.orm import Game, Player


def get_player_recent_games(db: Session, name_hash: str, limit: int = 50, offset: int = 0) -> list:
def get_player_recent_games(db: Session, name_hash: str, limit: int = 50, offset: int = 0, lang: str = 'en') -> list:
'''Get recent games of a player.
Args:
Expand All @@ -25,10 +27,13 @@ def get_player_recent_games(db: Session, name_hash: str, limit: int = 50, offset
.limit(limit)\
.all()

return [(g.game_guid, g.version_code, g.map_name, g.matchup, g.duration, g.game_time, p) for g, p in recent_games]
t = gettext.translation(lang, localedir='translations', languages=["en"], fallback=True)
_ = t.gettext

return [(g.game_guid, g.version_code, _(g.map_name), g.matchup, g.duration, g.game_time, p) for g, p in recent_games]


async def async_get_player_recent_games(db: Session, name_hash: str, limit: int = 50, offset: int = 0) -> list:
async def async_get_player_recent_games(db: Session, name_hash: str, limit: int = 50, offset: int = 0, lang: str = 'en') -> list:
'''Async version of fetch_player_recent_games()'''

return get_player_recent_games(db, name_hash, limit, offset)
return get_player_recent_games(db, name_hash, limit, offset, lang)
14 changes: 9 additions & 5 deletions mgxhub/db/operation/search_games.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'''Search games in the database'''

import gettext
from datetime import datetime

from sqlalchemy import desc
Expand All @@ -9,7 +10,7 @@
from mgxhub.model.searchcriteria import SearchCriteria


def search_games(session: Session, criteria: SearchCriteria) -> dict:
def search_games(session: Session, criteria: SearchCriteria, lang: str = 'en') -> dict:
'''Search games.
Args:
Expand Down Expand Up @@ -70,19 +71,22 @@ def search_games(session: Session, criteria: SearchCriteria) -> dict:

query = query.order_by(order_by).limit(criteria.page_size).offset((criteria.page - 1) * criteria.page_size)

t = gettext.translation(lang, localedir='translations', languages=["en"], fallback=True)
_ = t.gettext

games = [{
'game_guid': game.game_guid,
'version_code': game.version_code,
'map_name': game.map_name,
'map_name': _(game.map_name),
'matchup': game.matchup,
'duration': game.duration,
'game_time': game.game_time,
'population': game.population,
'include_ai': game.include_ai,
'is_multiplayer': game.is_multiplayer,
'speed': game.speed,
'victory_type': game.victory_type,
'map_size': game.map_size,
'speed': _(game.speed),
'victory_type': _(game.victory_type),
'map_size': _(game.map_size),
'instruction': game.instruction,
'players': [(player.slot, player.name, player.civ_name, player.type, player.name_hash) for player in game.players]
} for game in query.all()]
Expand Down
4 changes: 4 additions & 0 deletions mgxhub/model/webapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class GameDetail(BaseModel):
duration: int | None
players: dict[int, PlayerInGame] | None
chats: list[ChatEntry] | None
files: list[list] | None
biggest_file: tuple[str, int] | None

def __init__(self, g: Game, p: list[Player], f: list[File], c: list[Chat], lang: str = 'en'):
Expand Down Expand Up @@ -125,6 +126,7 @@ def __init__(self, g: Game, p: list[Player], f: list[File], c: list[Chat], lang:
duration=g.duration,
players={},
chats=[],
files=[],
biggest_file=('', 0)
)

Expand Down Expand Up @@ -153,6 +155,8 @@ def __init__(self, g: Game, p: list[Player], f: list[File], c: list[Chat], lang:
)

for file in f:
self.files.append([file.created, file.md5, file.realsize, file.raw_filename,
file.recorder_slot, self.players[file.recorder_slot].name, self.players[file.recorder_slot].name_hash])
if file.recorder_slot in self.players:
if isinstance(file.realsize, int):
if file.realsize > self.biggest_file[1]:
Expand Down
2 changes: 1 addition & 1 deletion webapi/routers/game_detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async def get_game(guid: str, lang: str = 'en', db: Session = Depends(db_dep)) -
raise HTTPException(status_code=404, detail=f"Game profile [{guid}] not found")

player_data = db.query(Player).filter(Player.game_guid == guid).all()
file_data = db.query(File).filter(File.game_guid == guid).limit(10).all()
file_data = db.query(File).filter(File.game_guid == guid).limit(20).all()
chat_data = db.query(Chat.chat_time, Chat.chat_content)\
.filter(Chat.game_guid == guid)\
.group_by(Chat.chat_time, Chat.chat_content)\
Expand Down
8 changes: 6 additions & 2 deletions webapi/routers/game_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@


@app.post("/game/search", tags=['game'])
async def search_games(criteria: SearchCriteria = Body(...), session: Session = Depends(db_dep)) -> dict:
async def search_games(
criteria: SearchCriteria = Body(...),
session: Session = Depends(db_dep),
lang: str = 'en'
) -> dict:
'''Search games by some criteria
Args:
Expand All @@ -26,6 +30,6 @@ async def search_games(criteria: SearchCriteria = Body(...), session: Session =

logger.info(criteria.model_dump())

result = search_games_in_db(session, criteria)
result = search_games_in_db(session, criteria, lang)

return result
3 changes: 2 additions & 1 deletion webapi/routers/player_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ async def get_player_comprehensive(
player_hash: str,
recent_limit: int = Query(50, gt=0),
friend_limit: int = Query(50, gt=0),
lang: str = 'en',
db: Session = Depends(db_dep)
) -> dict:
'''Fetch comprehensive information of a player
Expand All @@ -40,7 +41,7 @@ async def get_player_comprehensive(
result = await asyncio.gather(
async_get_player_totals(db, player_hash),
async_get_player_rating_stats(db, player_hash),
async_get_player_recent_games(db, player_hash, recent_limit),
async_get_player_recent_games(db, player_hash, recent_limit, 0, lang),
async_get_close_friends(db, player_hash, friend_limit),
hash2name(db, player_hash)
)
Expand Down
3 changes: 2 additions & 1 deletion webapi/routers/player_recent_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ async def get_player_games(
player_hash: str,
page: int = Query(1, ge=1),
page_size: int = Query(50, ge=1),
lang: str = 'en',
db: Session = Depends(db_dep)
) -> dict:
'''Get recent games of a player
Expand All @@ -27,7 +28,7 @@ async def get_player_games(
Defined in: `webapi/routers/player_recent_game.py`
'''

games = get_player_recent_games(db, player_hash, page_size, (page - 1) * page_size)
games = get_player_recent_games(db, player_hash, page_size, (page - 1) * page_size, lang)

current_time = datetime.now().isoformat()

Expand Down

0 comments on commit 2c28499

Please sign in to comment.