From 398fa9059d3f14900721678934ad546a76061481 Mon Sep 17 00:00:00 2001 From: SoulGateKey Date: Fri, 11 Oct 2024 16:09:53 +0000 Subject: [PATCH] Update mai2/base.py using the ORM --- titles/mai2/base.py | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/titles/mai2/base.py b/titles/mai2/base.py index 2d0b686..d498fcf 100644 --- a/titles/mai2/base.py +++ b/titles/mai2/base.py @@ -77,40 +77,33 @@ class Mai2Base: } async def handle_get_game_ranking_api_request(self, data: Dict) -> Dict: - conn = pymysql.connect( - host=self.core_config.database.host, - port=self.core_config.database.port, - user=self.core_config.database.username, - password=self.core_config.database.password, - database=self.core_config.database.name, - charset='utf8mb4' - ) try: - cursor = conn.cursor() + playlogs = await self.data.score.get_playlogs(user_id=None) + ranking_list = [] - query = """ - SELECT musicid AS id, COUNT(*) AS point - FROM mai2_playlog - GROUP BY musicid - ORDER BY point DESC - LIMIT 100 - """ - cursor.execute(query) + if not playlogs: + self.logger.warning("No playlogs found.") + return {"length": 0, "gameRankingList": []} - results = cursor.fetchall() - ranking_list = [{"id": row[0], "point": row[1], "userName": ""} for row in results] - output = { + music_count = {} + for log in playlogs: + music_id = log.musicId + music_count[music_id] = music_count.get(music_id, 0) + 1 + + sorted_music = sorted(music_count.items(), key=lambda item: item[1], reverse=True) + + for music_id, count in sorted_music[:100]: + ranking_list.append({"id": music_id, "point": count, "userName": ""}) + + return { "type": 1, "gameRankingList": ranking_list, "gameRankingInstantList": None } - cursor.close() - conn.close() - return output - except Exception as e: - return {'length': 0, 'gameRankingList': []} + self.logger.error(f"Error while getting game ranking: {e}") + return {"length": 0, "gameRankingList": []} async def handle_get_game_tournament_info_api_request(self, data: Dict) -> Dict: # TODO: Tournament support