From f6a9aa69fd95b1cdb3b505b0c5da4b4900dda418 Mon Sep 17 00:00:00 2001 From: Jennifer Taylor Date: Tue, 2 Jan 2024 02:46:24 +0000 Subject: [PATCH] Make black do 120 character lines instead of 80. --- bemani/api/app.py | 4 +- bemani/api/objects/base.py | 8 +- bemani/api/objects/catalog.py | 13 +- bemani/api/objects/profile.py | 12 +- bemani/api/objects/records.py | 12 +- bemani/api/objects/statistics.py | 63 +- bemani/backend/base.py | 55 +- bemani/backend/bishi/bishi.py | 28 +- bemani/backend/core/cardmng.py | 9 +- bemani/backend/core/core.py | 24 +- bemani/backend/core/eacoin.py | 58 +- bemani/backend/ddr/base.py | 12 +- bemani/backend/ddr/common.py | 44 +- bemani/backend/ddr/ddr2013.py | 42 +- bemani/backend/ddr/ddr2014.py | 58 +- bemani/backend/ddr/ddrace.py | 200 ++-- bemani/backend/ddr/ddrx2.py | 93 +- bemani/backend/ddr/ddrx3.py | 54 +- bemani/backend/dispatch.py | 16 +- bemani/backend/iidx/base.py | 126 +-- bemani/backend/iidx/cannonballers.py | 396 ++------ bemani/backend/iidx/copula.py | 350 ++----- bemani/backend/iidx/course.py | 8 +- bemani/backend/iidx/pendual.py | 346 ++----- bemani/backend/iidx/rootage.py | 534 +++-------- bemani/backend/iidx/sinobuz.py | 326 ++----- bemani/backend/iidx/spada.py | 158 +--- bemani/backend/iidx/tricoro.py | 126 +-- bemani/backend/jubeat/base.py | 33 +- bemani/backend/jubeat/clan.py | 243 ++--- bemani/backend/jubeat/festo.py | 374 ++------ bemani/backend/jubeat/prop.py | 254 ++---- bemani/backend/jubeat/qubell.py | 265 ++---- bemani/backend/jubeat/saucer.py | 135 +-- bemani/backend/jubeat/saucerfulfill.py | 189 +--- bemani/backend/mga/mga.py | 75 +- bemani/backend/museca/base.py | 33 +- bemani/backend/museca/common.py | 16 +- bemani/backend/museca/museca1.py | 44 +- bemani/backend/museca/museca1plus.py | 44 +- bemani/backend/popn/base.py | 40 +- bemani/backend/popn/common.py | 315 ++----- bemani/backend/popn/eclale.py | 137 +-- bemani/backend/popn/fantasia.py | 226 ++--- bemani/backend/popn/kaimei.py | 34 +- bemani/backend/popn/lapistoria.py | 105 +-- bemani/backend/popn/sunnypark.py | 344 ++----- bemani/backend/popn/tunestreet.py | 96 +- bemani/backend/reflec/base.py | 37 +- bemani/backend/reflec/colette.py | 150 +-- bemani/backend/reflec/groovin.py | 310 ++----- bemani/backend/reflec/limelight.py | 156 +--- bemani/backend/reflec/reflecbeat.py | 46 +- bemani/backend/reflec/volzza.py | 262 ++---- bemani/backend/reflec/volzza2.py | 403 ++------ bemani/backend/reflec/volzzabase.py | 59 +- bemani/backend/sdvx/base.py | 29 +- bemani/backend/sdvx/booth.py | 25 +- bemani/backend/sdvx/gravitywars.py | 26 +- bemani/backend/sdvx/gravitywars_s1.py | 70 +- bemani/backend/sdvx/gravitywars_s2.py | 102 +-- bemani/backend/sdvx/heavenlyhaven.py | 125 +-- bemani/backend/sdvx/infiniteinfection.py | 59 +- bemani/client/base.py | 44 +- bemani/client/bishi/bishi.py | 20 +- bemani/client/ddr/ddr2013.py | 44 +- bemani/client/ddr/ddr2014.py | 32 +- bemani/client/ddr/ddrace.py | 85 +- bemani/client/ddr/ddrx2.py | 44 +- bemani/client/ddr/ddrx3.py | 52 +- bemani/client/iidx/cannonballers.py | 80 +- bemani/client/iidx/copula.py | 72 +- bemani/client/iidx/pendual.py | 72 +- bemani/client/iidx/rootage.py | 68 +- bemani/client/iidx/sinobuz.py | 72 +- bemani/client/iidx/spada.py | 60 +- bemani/client/iidx/tricoro.py | 44 +- bemani/client/jubeat/clan.py | 108 +-- bemani/client/jubeat/festo.py | 48 +- bemani/client/jubeat/prop.py | 96 +- bemani/client/jubeat/qubell.py | 60 +- bemani/client/jubeat/saucer.py | 24 +- bemani/client/jubeat/saucerfulfill.py | 32 +- bemani/client/mga/mga.py | 20 +- bemani/client/museca/museca1.py | 61 +- bemani/client/museca/museca1plus.py | 61 +- bemani/client/popn/eclale.py | 44 +- bemani/client/popn/fantasia.py | 45 +- bemani/client/popn/kaimei.py | 68 +- bemani/client/popn/lapistoria.py | 28 +- bemani/client/popn/peace.py | 68 +- bemani/client/popn/sunnypark.py | 45 +- bemani/client/popn/tunestreet.py | 44 +- bemani/client/popn/usaneko.py | 68 +- bemani/client/reflec/colette.py | 45 +- bemani/client/reflec/groovin.py | 55 +- bemani/client/reflec/limelight.py | 53 +- bemani/client/reflec/reflec.py | 49 +- bemani/client/reflec/volzza.py | 55 +- bemani/client/reflec/volzza2.py | 59 +- bemani/client/sdvx/booth.py | 57 +- bemani/client/sdvx/gravitywars_s1.py | 81 +- bemani/client/sdvx/gravitywars_s2.py | 85 +- bemani/client/sdvx/heavenlyhaven.py | 85 +- bemani/client/sdvx/infiniteinfection.py | 77 +- bemani/common/aes.py | 4 +- bemani/common/http.py | 16 +- bemani/common/id.py | 3 +- bemani/common/model.py | 4 +- bemani/common/parallel.py | 21 +- bemani/common/pe.py | 120 +-- bemani/common/time.py | 8 +- bemani/common/validateddict.py | 24 +- bemani/data/api/base.py | 5 +- bemani/data/api/client.py | 44 +- bemani/data/api/game.py | 4 +- bemani/data/api/music.py | 172 +--- bemani/data/api/user.py | 33 +- bemani/data/config.py | 28 +- bemani/data/data.py | 28 +- bemani/data/mysql/base.py | 17 +- bemani/data/mysql/game.py | 36 +- bemani/data/mysql/lobby.py | 24 +- bemani/data/mysql/machine.py | 4 +- bemani/data/mysql/music.py | 68 +- bemani/data/mysql/network.py | 32 +- bemani/data/mysql/user.py | 100 +- bemani/data/triggers.py | 16 +- bemani/data/types.py | 8 +- bemani/format/afp/blend/blend.py | 61 +- bemani/format/afp/container.py | 207 ++--- bemani/format/afp/decompile.py | 1061 ++++++---------------- bemani/format/afp/geo.py | 38 +- bemani/format/afp/render.py | 314 ++----- bemani/format/afp/swf.py | 807 ++++------------ bemani/format/afp/types/ap2.py | 8 +- bemani/format/afp/types/expression.py | 15 +- bemani/format/afp/types/generic.py | 97 +- bemani/format/afp/types/statement.py | 70 +- bemani/format/afp/util.py | 8 +- bemani/format/arc.py | 8 +- bemani/format/dxt.py | 27 +- bemani/format/ifs.py | 29 +- bemani/format/iidxchart.py | 4 +- bemani/format/iidxmusicdb.py | 4 +- bemani/format/tdxt.py | 4 +- bemani/format/twodx.py | 4 +- bemani/frontend/account/account.py | 6 +- bemani/frontend/admin/admin.py | 207 +---- bemani/frontend/app.py | 27 +- bemani/frontend/arcade/arcade.py | 109 +-- bemani/frontend/base.py | 69 +- bemani/frontend/bishi/bishi.py | 4 +- bemani/frontend/bishi/endpoints.py | 8 +- bemani/frontend/ddr/ddr.py | 12 +- bemani/frontend/ddr/endpoints.py | 28 +- bemani/frontend/gamesettings.py | 8 +- bemani/frontend/iidx/endpoints.py | 60 +- bemani/frontend/iidx/iidx.py | 9 +- bemani/frontend/jubeat/endpoints.py | 44 +- bemani/frontend/jubeat/jubeat.py | 44 +- bemani/frontend/mga/endpoints.py | 8 +- bemani/frontend/mga/mga.py | 4 +- bemani/frontend/museca/endpoints.py | 12 +- bemani/frontend/museca/museca.py | 4 +- bemani/frontend/popn/endpoints.py | 20 +- bemani/frontend/popn/popn.py | 4 +- bemani/frontend/reflec/endpoints.py | 20 +- bemani/frontend/reflec/reflec.py | 16 +- bemani/frontend/sdvx/endpoints.py | 16 +- bemani/frontend/sdvx/sdvx.py | 4 +- bemani/protocol/binary.py | 100 +- bemani/protocol/lz77.py | 36 +- bemani/protocol/node.py | 32 +- bemani/protocol/protocol.py | 9 +- bemani/protocol/xml.py | 38 +- bemani/sniff/sniff.py | 31 +- bemani/tests/helpers.py | 4 +- bemani/tests/test_AES.py | 4 +- bemani/tests/test_APIClient.py | 4 +- bemani/tests/test_CardCipher.py | 16 +- bemani/tests/test_GameData.py | 7 +- bemani/tests/test_NetworkData.py | 24 +- bemani/tests/test_PlayStats.py | 20 +- bemani/tests/test_ValidatedDict.py | 24 +- bemani/tests/test_XmlDecoder.py | 4 +- bemani/tests/test_afp_decompile.py | 284 ++---- bemani/tests/test_protocol.py | 8 +- bemani/utils/afputils.py | 88 +- bemani/utils/api.py | 4 +- bemani/utils/assetparse.py | 24 +- bemani/utils/bemanishark.py | 20 +- bemani/utils/binutils.py | 4 +- bemani/utils/cardconvert.py | 4 +- bemani/utils/dbutils.py | 4 +- bemani/utils/frontend.py | 8 +- bemani/utils/iidxutils.py | 8 +- bemani/utils/jsx.py | 4 +- bemani/utils/proxy.py | 20 +- bemani/utils/psmap.py | 20 +- bemani/utils/read.py | 580 +++--------- bemani/utils/replay.py | 8 +- bemani/utils/responsegen.py | 12 +- bemani/utils/sampleclient.py | 42 +- bemani/utils/scheduler.py | 4 +- bemani/utils/services.py | 8 +- bemani/utils/struct.py | 32 +- bemani/utils/tdxtutils.py | 12 +- bemani/utils/trafficgen.py | 16 +- bemani/utils/twodxutils.py | 8 +- formatfiles | 2 +- 211 files changed, 3914 insertions(+), 12437 deletions(-) diff --git a/bemani/api/app.py b/bemani/api/app.py index 59d4368..25f37fd 100644 --- a/bemani/api/app.py +++ b/bemani/api/app.py @@ -91,9 +91,7 @@ def jsonify(func: Callable) -> Callable: @app.errorhandler(Exception) def server_exception(exception: Any) -> Response: - stack = "".join( - traceback.format_exception(type(exception), exception, exception.__traceback__) - ) + stack = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__)) print(stack) try: g.data.local.network.put_event( diff --git a/bemani/api/objects/base.py b/bemani/api/objects/base.py index 385f652..d0f7cbd 100644 --- a/bemani/api/objects/base.py +++ b/bemani/api/objects/base.py @@ -14,15 +14,11 @@ class BaseObject: various fetch versions. """ - def __init__( - self, data: Data, game: GameConstants, version: int, omnimix: bool - ) -> None: + def __init__(self, data: Data, game: GameConstants, version: int, omnimix: bool) -> None: self.data = data self.game = game self.version = version self.omnimix = omnimix - def fetch_v1( - self, idtype: APIConstants, ids: List[str], params: Dict[str, Any] - ) -> Any: + def fetch_v1(self, idtype: APIConstants, ids: List[str], params: Dict[str, Any]) -> Any: raise APIException("Object fetch not supported for this version!") diff --git a/bemani/api/objects/catalog.py b/bemani/api/objects/catalog.py index e32f90d..06c9734 100644 --- a/bemani/api/objects/catalog.py +++ b/bemani/api/objects/catalog.py @@ -65,9 +65,7 @@ class CatalogObject(BaseObject): } return { "difficulty": song.data.get_int("difficulty"), - "category": categorymapping.get( - song.data.get_int("version", defaultcategory), "1" - ), + "category": categorymapping.get(song.data.get_int("version", defaultcategory), "1"), "bpm_min": song.data.get_int("bpm_min"), "bpm_max": song.data.get_int("bpm_max"), } @@ -228,9 +226,7 @@ class CatalogObject(BaseObject): else: return self.version - def fetch_v1( - self, idtype: APIConstants, ids: List[str], params: Dict[str, Any] - ) -> Dict[str, List[Dict[str, Any]]]: + def fetch_v1(self, idtype: APIConstants, ids: List[str], params: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]: # Verify IDs if idtype != APIConstants.ID_TYPE_SERVER: raise APIException( @@ -240,10 +236,7 @@ class CatalogObject(BaseObject): # Fetch the songs songs = self.data.local.music.get_all_songs(self.game, self.music_version) - if ( - self.game == GameConstants.JUBEAT - and self.version == VersionConstants.JUBEAT_CLAN - ): + if self.game == GameConstants.JUBEAT and self.version == VersionConstants.JUBEAT_CLAN: # There's always a special case. We don't store all music IDs since those in # the range of 80000301-80000347 are actually the same song, but copy-pasted # for different prefectures and slightly different charts. So, we need to copy diff --git a/bemani/api/objects/profile.py b/bemani/api/objects/profile.py index 1e38f35..11527c3 100644 --- a/bemani/api/objects/profile.py +++ b/bemani/api/objects/profile.py @@ -74,15 +74,11 @@ class ProfileObject(BaseObject): return base - def fetch_v1( - self, idtype: APIConstants, ids: List[str], params: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def fetch_v1(self, idtype: APIConstants, ids: List[str], params: Dict[str, Any]) -> List[Dict[str, Any]]: # Fetch the profiles profiles: List[Tuple[UserID, Profile]] = [] if idtype == APIConstants.ID_TYPE_SERVER: - profiles.extend( - self.data.local.user.get_all_profiles(self.game, self.version) - ) + profiles.extend(self.data.local.user.get_all_profiles(self.game, self.version)) elif idtype == APIConstants.ID_TYPE_SONG: raise APIException( "Unsupported ID for lookup!", @@ -108,9 +104,7 @@ class ProfileObject(BaseObject): # in the case that we returned scores for a user that doesn't have a # profile on a particular version. We allow that on this network, so in # order to not break remote networks, try our best to return any profile. - profile = self.data.local.user.get_any_profile( - self.game, self.version, userid - ) + profile = self.data.local.user.get_any_profile(self.game, self.version, userid) if profile is not None: profiles.append((userid, profile)) else: diff --git a/bemani/api/objects/records.py b/bemani/api/objects/records.py index 57369f8..a98c939 100644 --- a/bemani/api/objects/records.py +++ b/bemani/api/objects/records.py @@ -235,9 +235,7 @@ class RecordsObject(BaseObject): else: return self.version - def fetch_v1( - self, idtype: APIConstants, ids: List[str], params: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def fetch_v1(self, idtype: APIConstants, ids: List[str], params: Dict[str, Any]) -> List[Dict[str, Any]]: since = params.get("since") until = params.get("until") @@ -247,9 +245,7 @@ class RecordsObject(BaseObject): # Because of the way this query works, we can't apply since/until to it directly. # If we did, it would miss higher scores earned before since or after until, and # incorrectly report records. - records.extend( - self.data.local.music.get_all_records(self.game, self.music_version) - ) + records.extend(self.data.local.music.get_all_records(self.game, self.music_version)) elif idtype == APIConstants.ID_TYPE_SONG: if len(ids) == 1: songid = int(ids[0]) @@ -273,9 +269,7 @@ class RecordsObject(BaseObject): cardid = ids[2] userid = self.data.local.user.from_cardid(cardid) if userid is not None: - score = self.data.local.music.get_score( - self.game, self.music_version, userid, songid, chart - ) + score = self.data.local.music.get_score(self.game, self.music_version, userid, songid, chart) if score is not None: records.append((userid, score)) elif idtype == APIConstants.ID_TYPE_CARD: diff --git a/bemani/api/objects/statistics.py b/bemani/api/objects/statistics.py index 417ce95..39bf6e2 100644 --- a/bemani/api/objects/statistics.py +++ b/bemani/api/objects/statistics.py @@ -17,9 +17,7 @@ class StatisticsObject(BaseObject): "combos": stats.get("combos", -1), } - def __format_user_statistics( - self, cardids: List[str], stats: Dict[str, Any] - ) -> Dict[str, Any]: + def __format_user_statistics(self, cardids: List[str], stats: Dict[str, Any]) -> Dict[str, Any]: base = self.__format_statistics(stats) base["cards"] = cardids return base @@ -48,20 +46,11 @@ class StatisticsObject(BaseObject): }: return True if self.game == GameConstants.IIDX: - return ( - attempt.data.get_int("clear_status") - != DBConstants.IIDX_CLEAR_STATUS_NO_PLAY - ) + return attempt.data.get_int("clear_status") != DBConstants.IIDX_CLEAR_STATUS_NO_PLAY if self.game == GameConstants.REFLEC_BEAT: - return ( - attempt.data.get_int("clear_type") - != DBConstants.REFLEC_BEAT_CLEAR_TYPE_NO_PLAY - ) + return attempt.data.get_int("clear_type") != DBConstants.REFLEC_BEAT_CLEAR_TYPE_NO_PLAY if self.game == GameConstants.SDVX: - return ( - attempt.data.get_int("clear_type") - != DBConstants.SDVX_CLEAR_TYPE_NO_PLAY - ) + return attempt.data.get_int("clear_type") != DBConstants.SDVX_CLEAR_TYPE_NO_PLAY return False @@ -72,17 +61,11 @@ class StatisticsObject(BaseObject): if self.game == GameConstants.DDR: return attempt.data.get_int("rank") != DBConstants.DDR_RANK_E if self.game == GameConstants.IIDX: - return ( - attempt.data.get_int("clear_status") - != DBConstants.IIDX_CLEAR_STATUS_FAILED - ) + return attempt.data.get_int("clear_status") != DBConstants.IIDX_CLEAR_STATUS_FAILED if self.game == GameConstants.JUBEAT: return attempt.data.get_int("medal") != DBConstants.JUBEAT_PLAY_MEDAL_FAILED if self.game == GameConstants.MUSECA: - return ( - attempt.data.get_int("clear_type") - != DBConstants.MUSECA_CLEAR_TYPE_FAILED - ) + return attempt.data.get_int("clear_type") != DBConstants.MUSECA_CLEAR_TYPE_FAILED if self.game == GameConstants.POPN_MUSIC: return attempt.data.get_int("medal") not in [ DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FAILED, @@ -90,14 +73,9 @@ class StatisticsObject(BaseObject): DBConstants.POPN_MUSIC_PLAY_MEDAL_STAR_FAILED, ] if self.game == GameConstants.REFLEC_BEAT: - return ( - attempt.data.get_int("clear_type") - != DBConstants.REFLEC_BEAT_CLEAR_TYPE_FAILED - ) + return attempt.data.get_int("clear_type") != DBConstants.REFLEC_BEAT_CLEAR_TYPE_FAILED if self.game == GameConstants.SDVX: - return attempt.data.get_int( - "grade" - ) != DBConstants.SDVX_GRADE_NO_PLAY and attempt.data.get_int( + return attempt.data.get_int("grade") != DBConstants.SDVX_GRADE_NO_PLAY and attempt.data.get_int( "clear_type" ) not in [ DBConstants.SDVX_CLEAR_TYPE_NO_PLAY, @@ -113,10 +91,7 @@ class StatisticsObject(BaseObject): if self.game == GameConstants.DDR: return attempt.data.get_int("halo") != DBConstants.DDR_HALO_NONE if self.game == GameConstants.IIDX: - return ( - attempt.data.get_int("clear_status") - == DBConstants.IIDX_CLEAR_STATUS_FULL_COMBO - ) + return attempt.data.get_int("clear_status") == DBConstants.IIDX_CLEAR_STATUS_FULL_COMBO if self.game == GameConstants.JUBEAT: return attempt.data.get_int("medal") in [ DBConstants.JUBEAT_PLAY_MEDAL_FULL_COMBO, @@ -124,10 +99,7 @@ class StatisticsObject(BaseObject): DBConstants.JUBEAT_PLAY_MEDAL_EXCELLENT, ] if self.game == GameConstants.MUSECA: - return ( - attempt.data.get_int("clear_type") - == DBConstants.MUSECA_CLEAR_TYPE_FULL_COMBO - ) + return attempt.data.get_int("clear_type") == DBConstants.MUSECA_CLEAR_TYPE_FULL_COMBO if self.game == GameConstants.POPN_MUSIC: return attempt.data.get_int("medal") in [ DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FULL_COMBO, @@ -213,20 +185,13 @@ class StatisticsObject(BaseObject): return retval - def fetch_v1( - self, idtype: APIConstants, ids: List[str], params: Dict[str, Any] - ) -> List[Dict[str, Any]]: + def fetch_v1(self, idtype: APIConstants, ids: List[str], params: Dict[str, Any]) -> List[Dict[str, Any]]: retval: List[Dict[str, Any]] = [] # Fetch the attempts if idtype == APIConstants.ID_TYPE_SERVER: retval = self.__aggregate_global( - [ - attempt[1] - for attempt in self.data.local.music.get_all_attempts( - self.game, self.music_version - ) - ] + [attempt[1] for attempt in self.data.local.music.get_all_attempts(self.game, self.music_version)] ) elif idtype == APIConstants.ID_TYPE_SONG: if len(ids) == 1: @@ -272,9 +237,7 @@ class StatisticsObject(BaseObject): id_to_cards[userid] = self.data.local.user.get_cards(userid) attempts.extend( - self.data.local.music.get_all_attempts( - self.game, self.music_version, userid=userid - ) + self.data.local.music.get_all_attempts(self.game, self.music_version, userid=userid) ) retval = self.__aggregate_local(id_to_cards, attempts) else: diff --git a/bemani/backend/base.py b/bemani/backend/base.py index ff50548..2d08c7d 100644 --- a/bemani/backend/base.py +++ b/bemani/backend/base.py @@ -226,9 +226,7 @@ class Base(ABC): return Base(data, config, model) else: # Return the registered module providing this game - return cls.__registered_games[model.gamecode].create( - data, config, model, parentmodel=parentmodel - ) + return cls.__registered_games[model.gamecode].create(data, config, model, parentmodel=parentmodel) @classmethod def register(cls, gamecode: str, handler: Type[Factory]) -> None: @@ -244,9 +242,7 @@ class Base(ABC): cls.__registered_handlers.add(handler) @classmethod - def run_scheduled_work( - cls, data: Data, config: Config - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Config) -> List[Tuple[str, Dict[str, Any]]]: """ Run any out-of-band scheduled work that is applicable to this game. """ @@ -297,10 +293,7 @@ class Base(ABC): Returns: True if the profile exists, False if not. """ - return ( - self.data.local.user.get_profile(self.game, self.version, userid) - is not None - ) + return self.data.local.user.get_profile(self.game, self.version, userid) is not None def get_profile(self, userid: UserID) -> Optional[Profile]: """ @@ -354,15 +347,11 @@ class Base(ABC): or an empty dictionary if nothing was found. """ userids = list(set(userids)) - profiles = self.data.remote.user.get_any_profiles( - self.game, self.version, userids - ) + profiles = self.data.remote.user.get_any_profiles(self.game, self.version, userids) return [ ( userid, - profile - if profile is not None - else Profile(self.game, self.version, "", 0), + profile if profile is not None else Profile(self.game, self.version, "", 0), ) for (userid, profile) in profiles ] @@ -379,9 +368,7 @@ class Base(ABC): raise Exception("Trying to save a remote profile locally!") self.data.local.user.put_profile(self.game, self.version, userid, profile) - def update_play_statistics( - self, userid: UserID, stats: Optional[PlayStatistics] = None - ) -> None: + def update_play_statistics(self, userid: UserID, stats: Optional[PlayStatistics] = None) -> None: """ Given a user ID, calculate new play statistics. @@ -397,9 +384,7 @@ class Base(ABC): # We store the play statistics in a series-wide settings blob so its available # across all game versions, since it isn't game-specific. - settings = self.data.local.game.get_settings( - self.game, userid - ) or ValidatedDict({}) + settings = self.data.local.game.get_settings(self.game, userid) or ValidatedDict({}) if stats is not None: for key in stats: @@ -418,9 +403,7 @@ class Base(ABC): settings[key] = stats[key] settings.replace_int("total_plays", settings.get_int("total_plays") + 1) - settings.replace_int( - "first_play_timestamp", settings.get_int("first_play_timestamp", Time.now()) - ) + settings.replace_int("first_play_timestamp", settings.get_int("first_play_timestamp", Time.now())) settings.replace_int("last_play_timestamp", Time.now()) last_play_date = settings.get_int_array("last_play_date", 3) @@ -445,9 +428,7 @@ class Base(ABC): and last_play_date[2] == yesterday_play_date[2] ): # We played yesterday, add one to consecutive days - settings.replace_int( - "consecutive_days", settings.get_int("consecutive_days") + 1 - ) + settings.replace_int("consecutive_days", settings.get_int("consecutive_days") + 1) else: # We haven't played yesterday, so we have only one consecutive day. settings.replace_int("consecutive_days", 1) @@ -490,13 +471,9 @@ class Base(ABC): def get_machine_region(self) -> int: arcade = self.get_arcade() if arcade is None: - return RegionConstants.db_to_game_region( - self.requires_extended_regions, self.config.server.region - ) + return RegionConstants.db_to_game_region(self.requires_extended_regions, self.config.server.region) else: - return RegionConstants.db_to_game_region( - self.requires_extended_regions, arcade.region - ) + return RegionConstants.db_to_game_region(self.requires_extended_regions, arcade.region) def get_game_config(self) -> ValidatedDict: machine = self.data.local.machine.get_machine(self.config.machine.pcbid) @@ -504,9 +481,7 @@ class Base(ABC): # If this machine belongs to an arcade, use its settings. If the settings aren't present, # default to the game's defaults. if machine.arcade is not None: - settings = self.data.local.machine.get_settings( - machine.arcade, self.game, self.version, "game_config" - ) + settings = self.data.local.machine.get_settings(machine.arcade, self.game, self.version, "game_config") if settings is None: settings = ValidatedDict() return settings @@ -582,11 +557,7 @@ class Base(ABC): total_days = settings.get_int("total_days", 1) consecutive_days = settings.get_int("consecutive_days", 1) else: - if ( - last_play_date[0] != 0 - and last_play_date[1] != 0 - and last_play_date[2] != 0 - ): + if last_play_date[0] != 0 and last_play_date[1] != 0 and last_play_date[2] != 0: # We've played before but not today, so the total days is # the stored count plus today. total_days = settings.get_int("total_days") + 1 diff --git a/bemani/backend/bishi/bishi.py b/bemani/backend/bishi/bishi.py index c573d62..5858911 100644 --- a/bemani/backend/bishi/bishi.py +++ b/bemani/backend/bishi/bishi.py @@ -98,9 +98,7 @@ class TheStarBishiBashi( data = data.replace(";", "#;") return data - def __generate_setting( - self, key: str, values: Union[int, str, Sequence[int], Sequence[str]] - ) -> str: + def __generate_setting(self, key: str, values: Union[int, str, Sequence[int], Sequence[str]]) -> str: if isinstance(values, Iterable) and not isinstance(values, str): values = ",".join(self.__escape_string(x) for x in values) else: @@ -184,9 +182,7 @@ class TheStarBishiBashi( enable_dlc_levels = game_config.get_bool("enable_dlc_levels") if enable_dlc_levels: settings["MAL"] = 1 - force_unlock_characters = game_config.get_bool( - "force_unlock_eamuse_characters" - ) + force_unlock_characters = game_config.get_bool("force_unlock_eamuse_characters") if force_unlock_characters: settings["ALL"] = 1 scrolling_message = game_config.get_str("big_announcement") @@ -197,9 +193,7 @@ class TheStarBishiBashi( settings["IM"] = bb_message # Generate system message - settings_str = ";".join( - self.__generate_setting(key, vals) for key, vals in settings.items() - ) + settings_str = ";".join(self.__generate_setting(key, vals) for key, vals in settings.items()) # Send it to the client, making sure to inform the client that it was valid. root.add_child( @@ -223,9 +217,7 @@ class TheStarBishiBashi( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is None: root = Node.void("playerdata") - root.add_child( - Node.s32("result", 1) - ) # Unclear if this is the right thing to do here. + root.add_child(Node.s32("result", 1)) # Unclear if this is the right thing to do here. return root # Extract new profile info from old profile @@ -258,14 +250,10 @@ class TheStarBishiBashi( return self.format_profile(userid, profiletype, profile) else: root = Node.void("playerdata") - root.add_child( - Node.s32("result", 1) - ) # Unclear if this is the right thing to do here. + root.add_child(Node.s32("result", 1)) # Unclear if this is the right thing to do here. return root - def format_profile( - self, userid: UserID, profiletype: str, profile: Profile - ) -> Node: + def format_profile(self, userid: UserID, profiletype: str, profile: Profile) -> Node: root = Node.void("playerdata") root.add_child(Node.s32("result", 0)) player = Node.void("player") @@ -342,9 +330,7 @@ class TheStarBishiBashi( player.add_child(Node.u32("record_num", records)) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile, is_new: bool - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile, is_new: bool) -> Profile: # Profile save request, data values are base64 encoded. # d is a CSV, and bin1 is binary data. newprofile = oldprofile.clone() diff --git a/bemani/backend/core/cardmng.py b/bemani/backend/core/cardmng.py index dd0ba06..d6ebe4d 100644 --- a/bemani/backend/core/cardmng.py +++ b/bemani/backend/core/cardmng.py @@ -43,10 +43,7 @@ class CardManagerHandler(Base): refid = self.data.local.user.get_refid(self.game, self.version, userid) paseli_enabled = self.supports_paseli and self.config.paseli.enabled - newflag = ( - self.data.remote.user.get_any_profile(self.game, self.version, userid) - is None - ) + newflag = self.data.remote.user.get_any_profile(self.game, self.version, userid) is None root = Node.void("cardmng") root.set_attribute("refid", refid) @@ -81,9 +78,7 @@ class CardManagerHandler(Base): else: valid = False root = Node.void("cardmng") - root.set_attribute( - "status", str(Status.SUCCESS if valid else Status.INVALID_PIN) - ) + root.set_attribute("status", str(Status.SUCCESS if valid else Status.INVALID_PIN)) return root def handle_cardmng_getrefid_request(self, request: Node) -> Node: diff --git a/bemani/backend/core/core.py b/bemani/backend/core/core.py index 669f6e5..882b158 100644 --- a/bemani/backend/core/core.py +++ b/bemani/backend/core/core.py @@ -177,9 +177,7 @@ class CoreHandler(Base): root = Node.void("facility") root.set_attribute("expire", "600") location = Node.void("location") - location.add_child( - Node.string("id", ID.format_machine_id(machine.id, region=country)) - ) + location.add_child(Node.string("id", ID.format_machine_id(machine.id, region=country))) location.add_child(Node.string("country", country)) location.add_child(Node.string("region", regionstr)) location.add_child(Node.string("name", machine.name)) @@ -213,21 +211,11 @@ class CoreHandler(Base): eapass.add_child(Node.u16("valid", 365)) url = Node.void("url") - url.add_child( - Node.string("eapass", self.config.server.uri or "www.ea-pass.konami.net") - ) - url.add_child( - Node.string("arcadefan", self.config.server.uri or "www.konami.jp/am") - ) - url.add_child( - Node.string("konaminetdx", self.config.server.uri or "http://am.573.jp") - ) - url.add_child( - Node.string("konamiid", self.config.server.uri or "https://id.konami.net") - ) - url.add_child( - Node.string("eagate", self.config.server.uri or "http://eagate.573.jp") - ) + url.add_child(Node.string("eapass", self.config.server.uri or "www.ea-pass.konami.net")) + url.add_child(Node.string("arcadefan", self.config.server.uri or "www.konami.jp/am")) + url.add_child(Node.string("konaminetdx", self.config.server.uri or "http://am.573.jp")) + url.add_child(Node.string("konamiid", self.config.server.uri or "https://id.konami.net")) + url.add_child(Node.string("eagate", self.config.server.uri or "http://eagate.573.jp")) share.add_child(eacoin) share.add_child(url) diff --git a/bemani/backend/core/eacoin.py b/bemani/backend/core/eacoin.py index dc9411d..3fedede 100644 --- a/bemani/backend/core/eacoin.py +++ b/bemani/backend/core/eacoin.py @@ -65,9 +65,7 @@ class PASELIHandler(Base): # enabled, so there's no way to find a balance. balance = 0 else: - balance = self.data.local.user.get_balance( - userid, self.config.machine.arcade - ) + balance = self.data.local.user.get_balance(userid, self.config.machine.arcade) root.add_child(Node.s16("sequence", 0)) root.add_child(Node.u8("acstatus", 0)) @@ -158,17 +156,13 @@ class PASELIHandler(Base): else: # Look up the new balance based on this delta. If there isn't enough, # we will end up returning None here and exit without performing. - balance = self.data.local.user.update_balance( - userid, self.config.machine.arcade, -payment - ) + balance = self.data.local.user.update_balance(userid, self.config.machine.arcade, -payment) if balance is None: print("Not enough balance for eacoin consume request") return make_resp( 1, - self.data.local.user.get_balance( - userid, self.config.machine.arcade - ), + self.data.local.user.get_balance(userid, self.config.machine.arcade), ) else: self.data.local.network.put_event( @@ -253,16 +247,13 @@ class PASELIHandler(Base): end_of_week = beginning_of_today beginning_of_week = end_of_week - Time.SECONDS_IN_WEEK - topic.add_child( - Node.string("sumfrom", Time.format(beginning_of_week, date_format)) - ) + topic.add_child(Node.string("sumfrom", Time.format(beginning_of_week, date_format))) topic.add_child(Node.string("sumto", Time.format(end_of_week, date_format))) today_total = sum( [ -event.data.get_int("delta") for event in events - if event.timestamp >= beginning_of_today - and event.timestamp < end_of_today + if event.timestamp >= beginning_of_today and event.timestamp < end_of_today ] ) @@ -270,15 +261,13 @@ class PASELIHandler(Base): [ -event.data.get_int("delta") for event in events - if event.timestamp >= beginning_of_today - and event.timestamp < end_of_today + if event.timestamp >= beginning_of_today and event.timestamp < end_of_today ] ) week_txns = [ -event.data.get_int("delta") for event in events - if event.timestamp >= beginning_of_week - and event.timestamp < end_of_week + if event.timestamp >= beginning_of_week and event.timestamp < end_of_week ] week_total = sum(week_txns) if len(week_txns) > 0: @@ -298,8 +287,7 @@ class PASELIHandler(Base): [ -event.data.get_int("delta") for event in events - if event.timestamp >= start_of_day - and event.timestamp < end_of_day + if event.timestamp >= start_of_day and event.timestamp < end_of_day ] ) ) @@ -317,14 +305,10 @@ class PASELIHandler(Base): topic.add_child( Node.string( "sumfrom", - Time.format( - end_of_52_weeks - (52 * Time.SECONDS_IN_WEEK), date_format - ), + Time.format(end_of_52_weeks - (52 * Time.SECONDS_IN_WEEK), date_format), ) ) - topic.add_child( - Node.string("sumto", Time.format(end_of_52_weeks, date_format)) - ) + topic.add_child(Node.string("sumto", Time.format(end_of_52_weeks, date_format))) # We index backwards, where index 0 = the first week back, 1 = the next week back after that, etc... items = [] @@ -337,8 +321,7 @@ class PASELIHandler(Base): [ -event.data.get_int("delta") for event in events - if event.timestamp >= beginning_of_range - and event.timestamp < end_of_range + if event.timestamp >= beginning_of_range and event.timestamp < end_of_range ] ) ) @@ -366,9 +349,7 @@ class PASELIHandler(Base): hours = [0] * 24 for event in events: - event_hour = int( - (event.timestamp % Time.SECONDS_IN_DAY) / Time.SECONDS_IN_HOUR - ) + event_hour = int((event.timestamp % Time.SECONDS_IN_DAY) / Time.SECONDS_IN_HOUR) hours[event_hour] = hours[event_hour] - event.data.get_int("delta") if event.timestamp < start_ts: start_ts = event.timestamp @@ -399,15 +380,11 @@ class PASELIHandler(Base): item = Node.void("item") history.add_child(item) - item.add_child( - Node.string("date", Time.format(event.timestamp, time_format)) - ) + item.add_child(Node.string("date", Time.format(event.timestamp, time_format))) item.add_child(Node.s32("consume", -event.data.get_int("delta"))) item.add_child(Node.s32("service", -event.data.get_int("service"))) item.add_child(Node.string("cardtype", "")) - item.add_child( - Node.string("cardno", " " * self.paseli_padding + card_no) - ) + item.add_child(Node.string("cardno", " " * self.paseli_padding + card_no)) item.add_child(Node.string("title", "")) item.add_child(Node.string("systemid", "")) @@ -417,9 +394,7 @@ class PASELIHandler(Base): last_month = Time.timestamp_from_date(year, month - 1) month_before = Time.timestamp_from_date(year, month - 2) - topic.add_child( - Node.string("sumfrom", Time.format(month_before, date_format)) - ) + topic.add_child(Node.string("sumfrom", Time.format(month_before, date_format))) topic.add_child(Node.string("sumto", Time.format(this_month, date_format))) for start, end in [(month_before, last_month), (last_month, this_month)]: @@ -439,8 +414,7 @@ class PASELIHandler(Base): [ -event.data.get_int("delta") for event in events - if event.timestamp >= begin_ts - and event.timestamp < end_ts + if event.timestamp >= begin_ts and event.timestamp < end_ts ] ) ) diff --git a/bemani/backend/ddr/base.py b/bemani/backend/ddr/base.py index 4e252d0..5a587e2 100644 --- a/bemani/backend/ddr/base.py +++ b/bemani/backend/ddr/base.py @@ -127,18 +127,14 @@ class DDRBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("game") - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: """ Base handler for a score list. Given a userid, profile and a score list, return a Node representing a score list. Should be overridden. """ return Node.void("game") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -164,9 +160,7 @@ class DDRBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Now, return it return self.format_profile(userid, profile) - def new_profile_by_refid( - self, refid: Optional[str], name: Optional[str], area: Optional[int] - ) -> None: + def new_profile_by_refid(self, refid: Optional[str], name: Optional[str], area: Optional[int]) -> None: """ Given a RefID and a name/area, create a new profile. """ diff --git a/bemani/backend/ddr/common.py b/bemani/backend/ddr/common.py index 4cbffc2..d6b5769 100644 --- a/bemani/backend/ddr/common.py +++ b/bemani/backend/ddr/common.py @@ -63,10 +63,7 @@ class DDRGameHiscoreHandler(DDRBase): sortedrecords[score.id] = {} sortedrecords[score.id][score.chart] = (userid, score) missing_profiles.append(userid) - users = { - userid: profile - for (userid, profile) in self.get_any_profiles(missing_profiles) - } + users = {userid: profile for (userid, profile) in self.get_any_profiles(missing_profiles)} game = Node.void("game") for song in sortedrecords: @@ -90,11 +87,7 @@ class DDRGameHiscoreHandler(DDRBase): typenode.add_child(Node.string("name", users[userid].get_str("name"))) typenode.add_child(Node.u32("score", score.points)) - typenode.add_child( - Node.u16( - "area", users[userid].get_int("area", self.get_machine_region()) - ) - ) + typenode.add_child(Node.u16("area", users[userid].get_int("area", self.get_machine_region()))) typenode.add_child(Node.u8("rank", gamerank)) typenode.add_child(Node.u8("combo_type", combo_type)) typenode.add_child(Node.u32("code", users[userid].extid)) @@ -109,16 +102,12 @@ class DDRGameAreaHiscoreHandler(DDRBase): # First, get all users that are in the current shop's area area_users = { uid: prof - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) + for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version) if prof.get_int("area", self.get_machine_region()) == shop_area } # Second, look up records belonging only to those users - records = self.data.local.music.get_all_records( - self.game, self.music_version, userlist=list(area_users.keys()) - ) + records = self.data.local.music.get_all_records(self.game, self.music_version, userlist=list(area_users.keys())) # Now, do the same lazy thing as 'hiscore' because I don't want # to think about how to change this knowing that we only pulled @@ -137,10 +126,7 @@ class DDRGameAreaHiscoreHandler(DDRBase): for chart in area_records[song]: userid, score = area_records[song][chart] - if ( - area_users[userid].get_int("area", self.get_machine_region()) - != shop_area - ): + if area_users[userid].get_int("area", self.get_machine_region()) != shop_area: # Don't return this, this user isn't in this area continue try: @@ -155,9 +141,7 @@ class DDRGameAreaHiscoreHandler(DDRBase): music.add_child(typenode) typenode.set_attribute("diff", str(gamechart)) - typenode.add_child( - Node.string("name", area_users[userid].get_str("name")) - ) + typenode.add_child(Node.string("name", area_users[userid].get_str("name"))) typenode.add_child(Node.u32("score", score.points)) typenode.add_child( Node.u16( @@ -309,9 +293,7 @@ class DDRGameOldHandler(DDRBase): oldprofile = previous_version.get_profile(userid) if oldprofile is not None: game.set_attribute("name", oldprofile.get_str("name")) - game.set_attribute( - "area", str(oldprofile.get_int("area", self.get_machine_region())) - ) + game.set_attribute("area", str(oldprofile.get_int("area", self.get_machine_region()))) return game @@ -361,9 +343,7 @@ class DDRGameFriendHandler(DDRBase): game.set_attribute("data", "1") game.add_child(Node.u32("code", friend.extid)) game.add_child(Node.string("name", friend.get_str("name"))) - game.add_child( - Node.u8("area", friend.get_int("area", self.get_machine_region())) - ) + game.add_child(Node.u8("area", friend.get_int("area", self.get_machine_region()))) game.add_child(Node.u32("exp", play_stats.get_int("exp"))) game.add_child(Node.u32("star", friend.get_int("star"))) @@ -421,9 +401,7 @@ class DDRGameLoadCourseHandler(DDRBase): coursedata = [0] * 3200 if userid is not None: - for course in self.data.local.user.get_achievements( - self.game, self.version, userid - ): + for course in self.data.local.user.get_achievements(self.game, self.version, userid): if course.type != "course": continue @@ -438,9 +416,7 @@ class DDRGameLoadCourseHandler(DDRBase): coursedata[index + 0] = int(course.data.get_int("score") / 10000) coursedata[index + 1] = course.data.get_int("score") % 10000 coursedata[index + 2] = course.data.get_int("combo") - coursedata[index + 3] = self.db_to_game_rank( - course.data.get_int("rank") - ) + coursedata[index + 3] = self.db_to_game_rank(course.data.get_int("rank")) coursedata[index + 5] = course.data.get_int("stage") coursedata[index + 6] = course.data.get_int("combo_type") diff --git a/bemani/backend/ddr/ddr2013.py b/bemani/backend/ddr/ddr2013.py index ff85a74..1cd00f8 100644 --- a/bemani/backend/ddr/ddr2013.py +++ b/bemani/backend/ddr/ddr2013.py @@ -171,9 +171,7 @@ class DDR2013( flag.set_attribute("area", str(self.get_machine_region())) flag.set_attribute("is_final", "1") - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -194,9 +192,7 @@ class DDR2013( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -284,14 +280,10 @@ class DDR2013( root.add_child(Node.string("seq", "")) root.add_child(Node.u32("code", profile.extid)) root.add_child(Node.string("name", profile.get_str("name"))) - root.add_child( - Node.u8("area", profile.get_int("area", self.get_machine_region())) - ) + root.add_child(Node.u8("area", profile.get_int("area", self.get_machine_region()))) root.add_child(Node.u32("cnt_s", play_stats.get_int("single_plays"))) root.add_child(Node.u32("cnt_d", play_stats.get_int("double_plays"))) - root.add_child( - Node.u32("cnt_b", play_stats.get_int("battle_plays")) - ) # This could be wrong, its a guess + root.add_child(Node.u32("cnt_b", play_stats.get_int("battle_plays"))) # This could be wrong, its a guess root.add_child(Node.u32("cnt_m0", play_stats.get_int("cnt_m0"))) root.add_child(Node.u32("cnt_m1", play_stats.get_int("cnt_m1"))) root.add_child(Node.u32("cnt_m2", play_stats.get_int("cnt_m2"))) @@ -309,11 +301,7 @@ class DDR2013( chara = Node.void("chara") root.add_child(chara) chara.set_attribute("my", str(profile.get_int("chara", 30))) - root.add_child( - Node.u16_array( - "chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96) - ) - ) + root.add_child(Node.u16_array("chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96))) # Drill rankings if "title_gr" in profile: @@ -361,9 +349,7 @@ class DDR2013( last.set_attribute("rival1", str(lastdict.get_int("rival1", -1))) last.set_attribute("rival2", str(lastdict.get_int("rival2", -1))) last.set_attribute("rival3", str(lastdict.get_int("rival3", -1))) - last.set_attribute( - "fri", str(lastdict.get_int("rival1", -1)) - ) # This literally goes to the same memory in 2013 + last.set_attribute("fri", str(lastdict.get_int("rival1", -1))) # This literally goes to the same memory in 2013 last.set_attribute("style", str(lastdict.get_int("style"))) last.set_attribute("mode", str(lastdict.get_int("mode"))) last.set_attribute("cate", str(lastdict.get_int("cate"))) @@ -407,9 +393,7 @@ class DDR2013( root.add_child(Node.s16_array("opt_ex", profile.get_int_array("opt_ex", 16))) # Unlock flags - root.add_child( - Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256)) - ) + root.add_child(Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256))) # Ranking display? root.add_child(Node.u16_array("rank", profile.get_int_array("rank", 100))) @@ -431,9 +415,7 @@ class DDR2013( friendnode.set_attribute("up", "0") friendnode.add_child(Node.u32("code", friend.extid)) friendnode.add_child(Node.string("name", friend.get_str("name"))) - friendnode.add_child( - Node.u8("area", friend.get_int("area", self.get_machine_region())) - ) + friendnode.add_child(Node.u8("area", friend.get_int("area", self.get_machine_region()))) friendnode.add_child(Node.u32("exp", play_stats.get_int("exp"))) friendnode.add_child(Node.u32("star", friend.get_int("star"))) @@ -484,9 +466,7 @@ class DDR2013( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -691,9 +671,7 @@ class DDR2013( newfriends[pos] = None else: # Try looking up the userid - newfriends[pos] = self.data.remote.user.from_extid( - self.game, self.version, code - ) + newfriends[pos] = self.data.remote.user.from_extid(self.game, self.version, code) # Diff the set of links to determine updates for i in range(10): diff --git a/bemani/backend/ddr/ddr2014.py b/bemani/backend/ddr/ddr2014.py index 5742419..19500c1 100644 --- a/bemani/backend/ddr/ddr2014.py +++ b/bemani/backend/ddr/ddr2014.py @@ -166,9 +166,7 @@ class DDR2014( flag.set_attribute("is_final", "0") # Last month's hit chart - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS, 30 - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS, 30) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -176,9 +174,7 @@ class DDR2014( game.add_child(Node.u32_array("cnt_music_monthly", counts_by_reflink)) # Last week's hit chart - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS, 7 - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS, 7) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -186,9 +182,7 @@ class DDR2014( game.add_child(Node.u32_array("cnt_music_weekly", counts_by_reflink)) # Last day's hit chart - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS, 1 - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS, 1) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -209,9 +203,7 @@ class DDR2014( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -338,14 +330,10 @@ class DDR2014( root.add_child(Node.string("seq", "")) root.add_child(Node.u32("code", profile.extid)) root.add_child(Node.string("name", profile.get_str("name"))) - root.add_child( - Node.u8("area", profile.get_int("area", self.get_machine_region())) - ) + root.add_child(Node.u8("area", profile.get_int("area", self.get_machine_region()))) root.add_child(Node.u32("cnt_s", play_stats.get_int("single_plays"))) root.add_child(Node.u32("cnt_d", play_stats.get_int("double_plays"))) - root.add_child( - Node.u32("cnt_b", play_stats.get_int("battle_plays")) - ) # This could be wrong, its a guess + root.add_child(Node.u32("cnt_b", play_stats.get_int("battle_plays"))) # This could be wrong, its a guess root.add_child(Node.u32("cnt_m0", play_stats.get_int("cnt_m0"))) root.add_child(Node.u32("cnt_m1", play_stats.get_int("cnt_m1"))) root.add_child(Node.u32("cnt_m2", play_stats.get_int("cnt_m2"))) @@ -363,11 +351,7 @@ class DDR2014( chara = Node.void("chara") root.add_child(chara) chara.set_attribute("my", str(profile.get_int("chara", 30))) - root.add_child( - Node.u16_array( - "chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96) - ) - ) + root.add_child(Node.u16_array("chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96))) # Drill rankings if "title_gr" in profile: @@ -420,9 +404,7 @@ class DDR2014( last.set_attribute("rival1", str(lastdict.get_int("rival1", -1))) last.set_attribute("rival2", str(lastdict.get_int("rival2", -1))) last.set_attribute("rival3", str(lastdict.get_int("rival3", -1))) - last.set_attribute( - "fri", str(lastdict.get_int("rival1", -1)) - ) # This literally goes to the same memory in 2014 + last.set_attribute("fri", str(lastdict.get_int("rival1", -1))) # This literally goes to the same memory in 2014 last.set_attribute("style", str(lastdict.get_int("style"))) last.set_attribute("mode", str(lastdict.get_int("mode"))) last.set_attribute("cate", str(lastdict.get_int("cate"))) @@ -462,17 +444,11 @@ class DDR2014( root.add_child(option_ver) option_ver.set_attribute("ver", str(profile.get_int("option_ver", 2))) if "option_02" in profile: - root.add_child( - Node.s16_array("option_02", profile.get_int_array("option_02", 24)) - ) + root.add_child(Node.s16_array("option_02", profile.get_int_array("option_02", 24))) # Unlock flags - root.add_child( - Node.u8_array("flag", profile.get_int_array("flag", 512, [1] * 512)[:256]) - ) - root.add_child( - Node.u8_array("flag_ex", profile.get_int_array("flag", 512, [1] * 512)) - ) + root.add_child(Node.u8_array("flag", profile.get_int_array("flag", 512, [1] * 512)[:256])) + root.add_child(Node.u8_array("flag_ex", profile.get_int_array("flag", 512, [1] * 512))) # Ranking display? root.add_child(Node.u16_array("rank", profile.get_int_array("rank", 100))) @@ -494,9 +470,7 @@ class DDR2014( friendnode.set_attribute("up", "0") friendnode.add_child(Node.u32("code", friend.extid)) friendnode.add_child(Node.string("name", friend.get_str("name"))) - friendnode.add_child( - Node.u8("area", friend.get_int("area", self.get_machine_region())) - ) + friendnode.add_child(Node.u8("area", friend.get_int("area", self.get_machine_region()))) friendnode.add_child(Node.u32("exp", play_stats.get_int("exp"))) friendnode.add_child(Node.u32("star", friend.get_int("star"))) @@ -553,9 +527,7 @@ class DDR2014( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -760,9 +732,7 @@ class DDR2014( newfriends[pos] = None else: # Try looking up the userid - newfriends[pos] = self.data.remote.user.from_extid( - self.game, self.version, code - ) + newfriends[pos] = self.data.remote.user.from_extid(self.game, self.version, code) # Diff the set of links to determine updates for i in range(10): diff --git a/bemani/backend/ddr/ddrace.py b/bemani/backend/ddr/ddrace.py index bce2799..7eab353 100644 --- a/bemani/backend/ddr/ddrace.py +++ b/bemani/backend/ddr/ddrace.py @@ -113,9 +113,7 @@ class DDRAce( return DDR2014(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: # DDR Ace has a weird bug where it sends a profile save for a blank # profile before reading it back when creating a new profile. If there # is no profile on read-back, it errors out, and it also uses the name @@ -134,10 +132,7 @@ class DDRAce( events = [] for userid, profile in profiles: - if ( - profile.get_str("name") == "" - and profile.get_int("write_time") < several_minutes_ago - ): + if profile.get_str("name") == "" and profile.get_int("write_time") < several_minutes_ago: data.local.user.delete_profile(cls.game, cls.version, userid) events.append( ( @@ -255,21 +250,15 @@ class DDRAce( tax.add_child(Node.s32("phase", 0)) return tax - def __handle_userload( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_userload(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: has_profile: bool = False achievements: List[Achievement] = [] scores: List[Score] = [] if userid is not None: has_profile = self.has_profile(userid) - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Place scores into an arrangement for easier distribution to Ace. scores_by_mcode: Dict[int, List[Optional[Score]]] = {} @@ -304,11 +293,7 @@ class DDRAce( note.add_child(Node.s32("ghostid", 0)) else: note.add_child(Node.u16("count", score.plays)) - note.add_child( - Node.u8( - "rank", self.db_to_game_rank(score.data.get_int("rank")) - ) - ) + note.add_child(Node.u8("rank", self.db_to_game_rank(score.data.get_int("rank")))) note.add_child( Node.u8( "clearkind", @@ -401,9 +386,7 @@ class DDRAce( eventdata.add_child(Node.u32("eventno", 0)) eventdata.add_child(Node.s64("condition", 0)) eventdata.add_child(Node.u32("reward", 0)) - eventdata.add_child( - Node.s32("comptime", 1 if playerstats.get_bool("completed") else 0) - ) + eventdata.add_child(Node.s32("comptime", 1 if playerstats.get_bool("completed") else 0)) eventdata.add_child(Node.s64("savedata", 0)) for evtprogress in progress: @@ -414,21 +397,11 @@ class DDRAce( eventdata.add_child(Node.s32("eventtype", int(evtprogress.type))) eventdata.add_child(Node.u32("eventno", 0)) eventdata.add_child(Node.s64("condition", 0)) - eventdata.add_child( - Node.u32( - "reward", rewards.get(evtprogress.type, {}).get(evtprogress.id) - ) - ) - eventdata.add_child( - Node.s32("comptime", 1 if evtprogress.data.get_bool("completed") else 0) - ) - eventdata.add_child( - Node.s64("savedata", evtprogress.data.get_int("progress")) - ) + eventdata.add_child(Node.u32("reward", rewards.get(evtprogress.type, {}).get(evtprogress.id))) + eventdata.add_child(Node.s32("comptime", 1 if evtprogress.data.get_bool("completed") else 0)) + eventdata.add_child(Node.s64("savedata", evtprogress.data.get_int("progress"))) - def __handle_usersave( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_usersave(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: if userid is None: # the game sends us empty user ID strings when a guest is playing. # Return early so it doesn't wait a minute and a half to show the @@ -537,9 +510,7 @@ class DDRAce( ghost=ghost, ) - def __handle_rivalload( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_rivalload(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: data = Node.void("data") response.add_child(data) data.add_child(Node.s32("recordtype", requestdata.child_value("loadflag"))) @@ -567,9 +538,7 @@ class DDRAce( if loadkind == self.GAME_RIVAL_TYPE_WORLD: # Just load all scores for this network - scores = self.data.remote.music.get_all_records( - self.game, self.music_version - ) + scores = self.data.remote.music.get_all_records(self.game, self.music_version) elif loadkind == self.GAME_RIVAL_TYPE_AREA: if thismachine.arcade is not None: match_arcade = thismachine.arcade @@ -595,14 +564,10 @@ class DDRAce( userids.append(userid) # Load all scores for users in the area - scores = self.data.local.music.get_all_records( - self.game, self.music_version, userlist=userids - ) + scores = self.data.local.music.get_all_records(self.game, self.music_version, userlist=userids) elif loadkind == self.GAME_RIVAL_TYPE_MACHINE: # Load up all scores and filter them by those earned at this location - scores = self.data.local.music.get_all_records( - self.game, self.music_version, locationlist=[thismachine.id] - ) + scores = self.data.local.music.get_all_records(self.game, self.music_version, locationlist=[thismachine.id]) elif loadkind in [ self.GAME_RIVAL_TYPE_RIVAL1, self.GAME_RIVAL_TYPE_RIVAL2, @@ -611,17 +576,13 @@ class DDRAce( # Load up this user's highscores, format the way the below code expects it extid = requestdata.child_value("ddrcode") otherid = self.data.remote.user.from_extid(self.game, self.version, extid) - userscores = self.data.remote.music.get_scores( - self.game, self.music_version, otherid - ) + userscores = self.data.remote.music.get_scores(self.game, self.music_version, otherid) scores = [(otherid, score) for score in userscores] else: # Nothing here scores = [] - missing_users = [ - userid for (userid, _) in scores if userid not in profiles_by_userid - ] + missing_users = [userid for (userid, _) in scores if userid not in profiles_by_userid] for userid, profile in self.get_any_profiles(missing_users): profiles_by_userid[userid] = profile @@ -634,12 +595,8 @@ class DDRAce( data.add_child(record) record.add_child(Node.u32("mcode", score.id)) record.add_child(Node.u8("notetype", self.db_to_game_chart(score.chart))) - record.add_child( - Node.u8("rank", self.db_to_game_rank(score.data.get_int("rank"))) - ) - record.add_child( - Node.u8("clearkind", self.db_to_game_halo(score.data.get_int("halo"))) - ) + record.add_child(Node.u8("rank", self.db_to_game_rank(score.data.get_int("rank")))) + record.add_child(Node.u8("clearkind", self.db_to_game_halo(score.data.get_int("halo")))) record.add_child(Node.u8("flagdata", 0)) record.add_child(Node.string("name", profiledata.get_str("name"))) record.add_child(Node.s32("area", profiledata.get_int("area", 58))) @@ -647,9 +604,7 @@ class DDRAce( record.add_child(Node.s32("score", score.points)) record.add_child(Node.s32("ghostid", score.key)) - def __handle_usernew( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_usernew(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: if userid is None: raise Exception("Expecting valid UserID to create new profile!") @@ -669,26 +624,18 @@ class DDRAce( response.add_child(Node.s32("code", profile.extid)) response.add_child(Node.string("shoparea", "")) - def __handle_inheritance( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_inheritance(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: if userid is not None: previous_version = self.previous_version() profile = previous_version.get_profile(userid) else: profile = None - response.add_child( - Node.s32("InheritanceStatus", 1 if profile is not None else 0) - ) + response.add_child(Node.s32("InheritanceStatus", 1 if profile is not None else 0)) - def __handle_ghostload( - self, userid: Optional[UserID], requestdata: Node, response: Node - ) -> None: + def __handle_ghostload(self, userid: Optional[UserID], requestdata: Node, response: Node) -> None: ghostid = requestdata.child_value("ghostid") - ghost = self.data.local.music.get_score_by_key( - self.game, self.music_version, ghostid - ) + ghost = self.data.local.music.get_score_by_key(self.game, self.music_version, ghostid) if ghost is None: return @@ -708,9 +655,7 @@ class DDRAce( ghostdata.add_child(Node.s32("ghostsize", len(score.data["ghost"]))) ghostdata.add_child(Node.string("ghost", score.data["ghost"])) - def handle_playerdata_usergamedata_advanced_request( - self, request: Node - ) -> Optional[Node]: + def handle_playerdata_usergamedata_advanced_request(self, request: Node) -> Optional[Node]: playerdata = Node.void("playerdata") # DDR Ace decides to be difficult and have a third level of packet switching @@ -748,9 +693,7 @@ class DDRAce( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - profile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + profile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) usergamedata = profile.get_dict("usergamedata") for record in request.child("data/record").children: @@ -781,30 +724,19 @@ class DDRAce( profile.replace_bool( "workout_mode", int( - strdatalist[self.GAME_COMMON_WEIGHT_DISPLAY_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_COMMON_WEIGHT_DISPLAY_OFFSET].decode("ascii"), 16, ) != 0, ) profile.replace_int( "weight", - int( - float( - strdatalist[self.GAME_COMMON_WEIGHT_OFFSET].decode( - "ascii" - ) - ) - * 10 - ), + int(float(strdatalist[self.GAME_COMMON_WEIGHT_OFFSET].decode("ascii")) * 10), ) profile.replace_int( "character", int( - strdatalist[self.GAME_COMMON_CHARACTER_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_COMMON_CHARACTER_OFFSET].decode("ascii"), 16, ), ) @@ -812,36 +744,28 @@ class DDRAce( profile.replace_int( "combo", int( - strdatalist[self.GAME_OPTION_COMBO_POSITION_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_OPTION_COMBO_POSITION_OFFSET].decode("ascii"), 16, ), ) profile.replace_int( "early_late", int( - strdatalist[self.GAME_OPTION_FAST_SLOW_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_OPTION_FAST_SLOW_OFFSET].decode("ascii"), 16, ), ) profile.replace_int( "arrowskin", int( - strdatalist[self.GAME_OPTION_ARROW_SKIN_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_OPTION_ARROW_SKIN_OFFSET].decode("ascii"), 16, ), ) profile.replace_int( "guidelines", int( - strdatalist[self.GAME_OPTION_GUIDELINE_OFFSET].decode( - "ascii" - ), + strdatalist[self.GAME_OPTION_GUIDELINE_OFFSET].decode("ascii"), 16, ), ) @@ -907,45 +831,39 @@ class DDRAce( old_profile = previous_version.get_profile(userid) if old_profile is not None: name = old_profile.get_str("name") - area = old_profile.get_int( - "area", self.get_machine_region() - ) + area = old_profile.get_int("area", self.get_machine_region()) else: area = self.get_machine_region() common = usergamedata[ptype]["strdata"].split(b",") common[self.GAME_COMMON_NAME_OFFSET] = name.encode("ascii") - common[self.GAME_COMMON_AREA_OFFSET] = acehex(area).encode( - "ascii" - ) + common[self.GAME_COMMON_AREA_OFFSET] = acehex(area).encode("ascii") common[self.GAME_COMMON_WEIGHT_DISPLAY_OFFSET] = ( b"1" if profile.get_bool("workout_mode") else b"0" ) common[self.GAME_COMMON_WEIGHT_OFFSET] = str( float(profile.get_int("weight")) / 10.0 ).encode("ascii") - common[self.GAME_COMMON_CHARACTER_OFFSET] = acehex( - profile.get_int("character") - ).encode("ascii") + common[self.GAME_COMMON_CHARACTER_OFFSET] = acehex(profile.get_int("character")).encode( + "ascii" + ) usergamedata[ptype]["strdata"] = b",".join(common) if ptype == "OPTION": # Return user settings for frontend option = usergamedata[ptype]["strdata"].split(b",") - option[self.GAME_OPTION_FAST_SLOW_OFFSET] = acehex( - profile.get_int("early_late") - ).encode("ascii") - option[self.GAME_OPTION_COMBO_POSITION_OFFSET] = acehex( - profile.get_int("combo") - ).encode("ascii") - option[self.GAME_OPTION_ARROW_SKIN_OFFSET] = acehex( - profile.get_int("arrowskin") - ).encode("ascii") - option[self.GAME_OPTION_GUIDELINE_OFFSET] = acehex( - profile.get_int("guidelines") - ).encode("ascii") - option[self.GAME_OPTION_FILTER_OFFSET] = acehex( - profile.get_int("filter") - ).encode("ascii") + option[self.GAME_OPTION_FAST_SLOW_OFFSET] = acehex(profile.get_int("early_late")).encode( + "ascii" + ) + option[self.GAME_OPTION_COMBO_POSITION_OFFSET] = acehex(profile.get_int("combo")).encode( + "ascii" + ) + option[self.GAME_OPTION_ARROW_SKIN_OFFSET] = acehex(profile.get_int("arrowskin")).encode( + "ascii" + ) + option[self.GAME_OPTION_GUIDELINE_OFFSET] = acehex(profile.get_int("guidelines")).encode( + "ascii" + ) + option[self.GAME_OPTION_FILTER_OFFSET] = acehex(profile.get_int("filter")).encode("ascii") usergamedata[ptype]["strdata"] = b",".join(option) if ptype == "LAST": # Return the number of calories expended in the last day @@ -959,9 +877,7 @@ class DDRAce( total = sum([w.data.get_int("calories") for w in workouts]) last = usergamedata[ptype]["strdata"].split(b",") - last[self.GAME_LAST_CALORIES_OFFSET] = acehex(total).encode( - "ascii" - ) + last[self.GAME_LAST_CALORIES_OFFSET] = acehex(total).encode("ascii") usergamedata[ptype]["strdata"] = b",".join(last) if ptype == "RIVAL": # Fill in the DDR code and active status of the three active @@ -1003,24 +919,18 @@ class DDRAce( }[rivalno] rival[activeslot] = acehex(rivalno).encode("ascii") - rival[ddrcodeslot] = acehex(friendprofile.extid).encode( - "ascii" - ) + rival[ddrcodeslot] = acehex(friendprofile.extid).encode("ascii") usergamedata[ptype]["strdata"] = b",".join(rival) dnode = Node.string( "d", - base64.b64encode(usergamedata[ptype]["strdata"]).decode( - "ascii" - ), + base64.b64encode(usergamedata[ptype]["strdata"]).decode("ascii"), ) dnode.add_child( Node.string( "bin1", - base64.b64encode(usergamedata[ptype]["bindata"]).decode( - "ascii" - ), + base64.b64encode(usergamedata[ptype]["bindata"]).decode("ascii"), ) ) record.add_child(dnode) diff --git a/bemani/backend/ddr/ddrx2.py b/bemani/backend/ddr/ddrx2.py index a66a241..9b461e7 100644 --- a/bemani/backend/ddr/ddrx2.py +++ b/bemani/backend/ddr/ddrx2.py @@ -156,9 +156,7 @@ class DDRX2( flag.set_attribute("s1", "0") flag.set_attribute("t", "0") - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -180,10 +178,7 @@ class DDRX2( sortedrecords[score.id] = {} sortedrecords[score.id][score.chart] = (userid, score) missing_profiles.append(userid) - users = { - userid: profile - for (userid, profile) in self.get_any_profiles(missing_profiles) - } + users = {userid: profile for (userid, profile) in self.get_any_profiles(missing_profiles)} game = Node.void("game") for song in sortedrecords: @@ -207,11 +202,7 @@ class DDRX2( typenode.add_child(Node.string("name", users[userid].get_str("name"))) typenode.add_child(Node.u32("score", score.points)) - typenode.add_child( - Node.u16( - "area", users[userid].get_int("area", self.get_machine_region()) - ) - ) + typenode.add_child(Node.u16("area", users[userid].get_int("area", self.get_machine_region()))) typenode.add_child(Node.u8("rank", gamerank)) typenode.add_child(Node.u8("combo_type", combo_type)) @@ -229,9 +220,7 @@ class DDRX2( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -317,14 +306,10 @@ class DDRX2( root.add_child(Node.string("seq", "")) root.add_child(Node.u32("code", profile.extid)) root.add_child(Node.string("name", profile.get_str("name"))) - root.add_child( - Node.u8("area", profile.get_int("area", self.get_machine_region())) - ) + root.add_child(Node.u8("area", profile.get_int("area", self.get_machine_region()))) root.add_child(Node.u32("cnt_s", play_stats.get_int("single_plays"))) root.add_child(Node.u32("cnt_d", play_stats.get_int("double_plays"))) - root.add_child( - Node.u32("cnt_b", play_stats.get_int("battle_plays")) - ) # This could be wrong, its a guess + root.add_child(Node.u32("cnt_b", play_stats.get_int("battle_plays"))) # This could be wrong, its a guess root.add_child(Node.u32("cnt_m0", play_stats.get_int("cnt_m0"))) root.add_child(Node.u32("cnt_m1", play_stats.get_int("cnt_m1"))) root.add_child(Node.u32("cnt_m2", play_stats.get_int("cnt_m2"))) @@ -342,9 +327,7 @@ class DDRX2( if "chara" in profile: chara.set_attribute("my", str(profile.get_int("chara"))) - root.add_child( - Node.u8_array("chara_opt", profile.get_int_array("chara_opt", 96)) - ) + root.add_child(Node.u8_array("chara_opt", profile.get_int_array("chara_opt", 96))) # Drill rankings if "title" in profile: @@ -387,53 +370,31 @@ class DDRX2( e_panel_dict = profile.get_dict("e_panel") if "play_id" in e_panel_dict: e_panel.set_attribute("play_id", str(e_panel_dict.get_int("play_id"))) - e_panel.add_child( - Node.u8_array("cell", e_panel_dict.get_int_array("cell", 24)) - ) - e_panel.add_child( - Node.u8_array( - "panel_state", e_panel_dict.get_int_array("panel_state", 6) - ) - ) + e_panel.add_child(Node.u8_array("cell", e_panel_dict.get_int_array("cell", 24))) + e_panel.add_child(Node.u8_array("panel_state", e_panel_dict.get_int_array("panel_state", 6))) if "e_pix" in profile: e_pix = Node.void("e_pix") root.add_child(e_pix) e_pix_dict = profile.get_dict("e_pix") if "max_distance" in e_pix_dict: - e_pix.set_attribute( - "max_distance", str(e_pix_dict.get_int("max_distance")) - ) + e_pix.set_attribute("max_distance", str(e_pix_dict.get_int("max_distance"))) if "max_planet" in e_pix_dict: e_pix.set_attribute("max_planet", str(e_pix_dict.get_int("max_planet"))) if "total_distance" in e_pix_dict: - e_pix.set_attribute( - "total_distance", str(e_pix_dict.get_int("total_distance")) - ) + e_pix.set_attribute("total_distance", str(e_pix_dict.get_int("total_distance"))) if "total_planet" in e_pix_dict: - e_pix.set_attribute( - "total_planet", str(e_pix_dict.get_int("total_planet")) - ) + e_pix.set_attribute("total_planet", str(e_pix_dict.get_int("total_planet"))) if "border_character" in e_pix_dict: - e_pix.set_attribute( - "border_character", str(e_pix_dict.get_int("border_character")) - ) + e_pix.set_attribute("border_character", str(e_pix_dict.get_int("border_character"))) if "border_balloon" in e_pix_dict: - e_pix.set_attribute( - "border_balloon", str(e_pix_dict.get_int("border_balloon")) - ) + e_pix.set_attribute("border_balloon", str(e_pix_dict.get_int("border_balloon"))) if "border_music_aftr" in e_pix_dict: - e_pix.set_attribute( - "border_music_aftr", str(e_pix_dict.get_int("border_music_aftr")) - ) + e_pix.set_attribute("border_music_aftr", str(e_pix_dict.get_int("border_music_aftr"))) if "border_music_meii" in e_pix_dict: - e_pix.set_attribute( - "border_music_meii", str(e_pix_dict.get_int("border_music_meii")) - ) + e_pix.set_attribute("border_music_meii", str(e_pix_dict.get_int("border_music_meii"))) if "border_music_dirt" in e_pix_dict: - e_pix.set_attribute( - "border_music_dirt", str(e_pix_dict.get_int("border_music_dirt")) - ) + e_pix.set_attribute("border_music_dirt", str(e_pix_dict.get_int("border_music_dirt"))) if "flags" in e_pix_dict: e_pix.set_attribute("flags", str(e_pix_dict.get_int("flags"))) @@ -488,9 +449,7 @@ class DDRX2( root.add_child(Node.s16_array("opt_ex", profile.get_int_array("opt_ex", 16))) # Unlock flags - root.add_child( - Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256)) - ) + root.add_child(Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256))) # Ranking display? root.add_child(Node.u16_array("rank", profile.get_int_array("rank", 100))) @@ -512,9 +471,7 @@ class DDRX2( friendnode.set_attribute("up", "0") friendnode.add_child(Node.u32("code", friend.extid)) friendnode.add_child(Node.string("name", friend.get_str("name"))) - friendnode.add_child( - Node.u8("area", friend.get_int("area", self.get_machine_region())) - ) + friendnode.add_child(Node.u8("area", friend.get_int("area", self.get_machine_region()))) friendnode.add_child(Node.u32("exp", play_stats.get_int("exp"))) friendnode.add_child(Node.u32("star", friend.get_int("star"))) @@ -558,9 +515,7 @@ class DDRX2( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -656,9 +611,7 @@ class DDRX2( e_panel_dict = newprofile.get_dict("e_panel") e_panel_dict.replace_int("play_id", intish(e_panel.attribute("play_id"))) e_panel_dict.replace_int_array("cell", 24, e_panel.child_value("cell")) - e_panel_dict.replace_int_array( - "panel_state", 6, e_panel.child_value("panel_state") - ) + e_panel_dict.replace_int_array("panel_state", 6, e_panel.child_value("panel_state")) newprofile.replace_dict("e_panel", e_panel_dict) e_pix = request.child("e_pix") @@ -777,9 +730,7 @@ class DDRX2( newfriends[pos] = None else: # Try looking up the userid - newfriends[pos] = self.data.remote.user.from_extid( - self.game, self.version, code - ) + newfriends[pos] = self.data.remote.user.from_extid(self.game, self.version, code) # Diff the set of links to determine updates for i in range(10): diff --git a/bemani/backend/ddr/ddrx3.py b/bemani/backend/ddr/ddrx3.py index 9d2554c..e64efb9 100644 --- a/bemani/backend/ddr/ddrx3.py +++ b/bemani/backend/ddr/ddrx3.py @@ -165,9 +165,7 @@ class DDRX3( flag.set_attribute("s1", "0") flag.set_attribute("t", "0") - hit_chart = self.data.local.music.get_hit_chart( - self.game, self.music_version, self.GAME_MAX_SONGS - ) + hit_chart = self.data.local.music.get_hit_chart(self.game, self.music_version, self.GAME_MAX_SONGS) counts_by_reflink = [0] * self.GAME_MAX_SONGS for reflink, plays in hit_chart: if reflink >= 0 and reflink < self.GAME_MAX_SONGS: @@ -188,14 +186,10 @@ class DDRX3( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) old_scores = [ score - for score in self.data.local.user.get_achievements( - self.game, self.music_version, userid - ) + for score in self.data.local.user.get_achievements(self.game, self.music_version, userid) if score.type == "2ndmix" ] else: @@ -236,12 +230,8 @@ class DDRX3( if "score" in scoredict: # We played the normal version of this song - gamerank = self.db_to_game_rank( - scoredict["score"].data.get_int("rank") - ) - combo_type = self.db_to_game_halo( - scoredict["score"].data.get_int("halo") - ) + gamerank = self.db_to_game_rank(scoredict["score"].data.get_int("rank")) + combo_type = self.db_to_game_halo(scoredict["score"].data.get_int("halo")) points = scoredict["score"].points # type: ignore plays = scoredict["score"].plays # type: ignore else: @@ -366,14 +356,10 @@ class DDRX3( root.add_child(Node.string("seq", "")) root.add_child(Node.u32("code", profile.extid)) root.add_child(Node.string("name", profile.get_str("name"))) - root.add_child( - Node.u8("area", profile.get_int("area", self.get_machine_region())) - ) + root.add_child(Node.u8("area", profile.get_int("area", self.get_machine_region()))) root.add_child(Node.u32("cnt_s", play_stats.get_int("single_plays"))) root.add_child(Node.u32("cnt_d", play_stats.get_int("double_plays"))) - root.add_child( - Node.u32("cnt_b", play_stats.get_int("battle_plays")) - ) # This could be wrong, its a guess + root.add_child(Node.u32("cnt_b", play_stats.get_int("battle_plays"))) # This could be wrong, its a guess root.add_child(Node.u32("cnt_m0", play_stats.get_int("cnt_m0"))) root.add_child(Node.u32("cnt_m1", play_stats.get_int("cnt_m1"))) root.add_child(Node.u32("cnt_m2", play_stats.get_int("cnt_m2"))) @@ -391,11 +377,7 @@ class DDRX3( chara = Node.void("chara") root.add_child(chara) chara.set_attribute("my", str(profile.get_int("chara", 30))) - root.add_child( - Node.u16_array( - "chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96) - ) - ) + root.add_child(Node.u16_array("chara_opt", profile.get_int_array("chara_opt", 96, [208] * 96))) # Drill rankings if "title_gr" in profile: @@ -443,9 +425,7 @@ class DDRX3( last.set_attribute("rival1", str(lastdict.get_int("rival1", -1))) last.set_attribute("rival2", str(lastdict.get_int("rival2", -1))) last.set_attribute("rival3", str(lastdict.get_int("rival3", -1))) - last.set_attribute( - "fri", str(lastdict.get_int("rival1", -1)) - ) # This literally goes to the same memory in X3 + last.set_attribute("fri", str(lastdict.get_int("rival1", -1))) # This literally goes to the same memory in X3 last.set_attribute("style", str(lastdict.get_int("style"))) last.set_attribute("mode", str(lastdict.get_int("mode"))) last.set_attribute("cate", str(lastdict.get_int("cate"))) @@ -489,9 +469,7 @@ class DDRX3( root.add_child(Node.s16_array("opt_ex", profile.get_int_array("opt_ex", 16))) # Unlock flags - root.add_child( - Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256)) - ) + root.add_child(Node.u8_array("flag", profile.get_int_array("flag", 256, [1] * 256))) # Ranking display? root.add_child(Node.u16_array("rank", profile.get_int_array("rank", 100))) @@ -513,9 +491,7 @@ class DDRX3( friendnode.set_attribute("up", "0") friendnode.add_child(Node.u32("code", friend.extid)) friendnode.add_child(Node.string("name", friend.get_str("name"))) - friendnode.add_child( - Node.u8("area", friend.get_int("area", self.get_machine_region())) - ) + friendnode.add_child(Node.u8("area", friend.get_int("area", self.get_machine_region()))) friendnode.add_child(Node.u32("exp", play_stats.get_int("exp"))) friendnode.add_child(Node.u32("star", friend.get_int("star"))) @@ -566,9 +542,7 @@ class DDRX3( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -773,9 +747,7 @@ class DDRX3( newfriends[pos] = None else: # Try looking up the userid - newfriends[pos] = self.data.remote.user.from_extid( - self.game, self.version, code - ) + newfriends[pos] = self.data.remote.user.from_extid(self.game, self.version, code) # Diff the set of links to determine updates for i in range(10): diff --git a/bemani/backend/dispatch.py b/bemani/backend/dispatch.py index 08cedf7..b024d47 100644 --- a/bemani/backend/dispatch.py +++ b/bemani/backend/dispatch.py @@ -79,9 +79,7 @@ class Dispatch: pcb = self.__data.local.machine.get_machine(pcbid) if self.__config.server.enforce_pcbid and pcb is None: self.log("Unrecognized PCBID {}", pcbid) - raise UnrecognizedPCBIDException( - pcbid, modelstring, self.__config.client.address - ) + raise UnrecognizedPCBIDException(pcbid, modelstring, self.__config.client.address) # If we don't have a Machine, but we aren't enforcing, we must create it if pcb is None: @@ -120,9 +118,7 @@ class Dispatch: pcb.game, game.game, ) - raise UnrecognizedPCBIDException( - pcbid, modelstring, config.client.address - ) + raise UnrecognizedPCBIDException(pcbid, modelstring, config.client.address) if pcb.version is not None: if pcb.version > 0 and pcb.version != game.version: self.log( @@ -133,9 +129,7 @@ class Dispatch: game.game, game.version, ) - raise UnrecognizedPCBIDException( - pcbid, modelstring, config.client.address - ) + raise UnrecognizedPCBIDException(pcbid, modelstring, config.client.address) if pcb.version < 0 and (-pcb.version) < game.version: self.log( "PCBID {} assigned to game {} maximum version {}, but connected from game {} version {}", @@ -145,9 +139,7 @@ class Dispatch: game.game, game.version, ) - raise UnrecognizedPCBIDException( - pcbid, modelstring, config.client.address - ) + raise UnrecognizedPCBIDException(pcbid, modelstring, config.client.address) # First, try to handle with specific service/method function try: diff --git a/bemani/backend/iidx/base.py b/bemani/backend/iidx/base.py index 2b5bac8..0f54b38 100644 --- a/bemani/backend/iidx/base.py +++ b/bemani/backend/iidx/base.py @@ -115,9 +115,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("pc") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -145,9 +143,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): return None return self.format_profile(userid, profile) - def new_profile_by_refid( - self, refid: Optional[str], name: Optional[str], pid: Optional[int] - ) -> Profile: + def new_profile_by_refid(self, refid: Optional[str], name: Optional[str], pid: Optional[int]) -> Profile: """ Given a RefID and an optional name, create a profile and then return that newly created profile. @@ -169,9 +165,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): { "name": name, "pid": pid, - "settings": { - "flags": 223 # Default to turning on all optional folders - }, + "settings": {"flags": 223}, # Default to turning on all optional folders }, ) self.put_profile(userid, profile) @@ -253,27 +247,18 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): } # We saw an attempt, keep the total attempts in sync. - attempts[attempt.id][attempt.chart]["total"] = ( - attempts[attempt.id][attempt.chart]["total"] + 1 - ) + attempts[attempt.id][attempt.chart]["total"] = attempts[attempt.id][attempt.chart]["total"] + 1 - if ( - attempt.data.get_int("clear_status", self.CLEAR_STATUS_FAILED) - == self.CLEAR_STATUS_FAILED - ): + if attempt.data.get_int("clear_status", self.CLEAR_STATUS_FAILED) == self.CLEAR_STATUS_FAILED: # This attempt was a failure, so don't count it against clears of full combos continue # It was at least a clear - attempts[attempt.id][attempt.chart]["clears"] = ( - attempts[attempt.id][attempt.chart]["clears"] + 1 - ) + attempts[attempt.id][attempt.chart]["clears"] = attempts[attempt.id][attempt.chart]["clears"] + 1 if attempt.data.get_int("clear_status") == self.CLEAR_STATUS_FULL_COMBO: # This was a full combo clear, so it also counts here - attempts[attempt.id][attempt.chart]["fcs"] = ( - attempts[attempt.id][attempt.chart]["fcs"] + 1 - ) + attempts[attempt.id][attempt.chart]["fcs"] = attempts[attempt.id][attempt.chart]["fcs"] + 1 # Merge in remote attempts for songid in remote_attempts: @@ -288,15 +273,9 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): "fcs": 0, } - attempts[songid][songchart]["total"] += remote_attempts[songid][ - songchart - ]["plays"] - attempts[songid][songchart]["clears"] += remote_attempts[songid][ - songchart - ]["clears"] - attempts[songid][songchart]["fcs"] += remote_attempts[songid][ - songchart - ]["combos"] + attempts[songid][songchart]["total"] += remote_attempts[songid][songchart]["plays"] + attempts[songid][songchart]["clears"] += remote_attempts[songid][songchart]["clears"] + attempts[songid][songchart]["fcs"] += remote_attempts[songid][songchart]["combos"] # If requesting a specific song/chart, make sure its in the dict if songid is not None: @@ -399,16 +378,12 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): highscore = ex_score >= oldscore.points ex_score = max(ex_score, oldscore.points) scoredata = oldscore.data - scoredata.replace_int( - "clear_status", max(scoredata.get_int("clear_status"), clear_status) - ) + scoredata.replace_int("clear_status", max(scoredata.get_int("clear_status"), clear_status)) if miss_count != -1: if scoredata.get_int("miss_count", -1) == -1: scoredata.replace_int("miss_count", miss_count) else: - scoredata.replace_int( - "miss_count", min(scoredata.get_int("miss_count"), miss_count) - ) + scoredata.replace_int("miss_count", min(scoredata.get_int("miss_count"), miss_count)) if raised: scoredata.replace_int("pgreats", pgreats) scoredata.replace_int("greats", greats) @@ -514,12 +489,8 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): if dan_score is None: dan_score = ValidatedDict() dan_score.replace_int("percent", max(percent, dan_score.get_int("percent"))) - dan_score.replace_int( - "stages_cleared", max(stages_cleared, dan_score.get_int("stages_cleared")) - ) - self.data.local.user.put_achievement( - self.game, self.version, userid, rank, dantype, dan_score - ) + dan_score.replace_int("stages_cleared", max(stages_cleared, dan_score.get_int("stages_cleared"))) + self.data.local.user.put_achievement(self.game, self.version, userid, rank, dantype, dan_score) def db_to_game_status(self, db_status: int) -> int: """ @@ -545,9 +516,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ raise Exception("Implement in sub-class!") - def make_score_struct( - self, scores: List[Score], cltype: int, index: int - ) -> List[List[int]]: + def make_score_struct(self, scores: List[Score], cltype: int, index: int) -> List[List[int]]: scorestruct: Dict[int, List[int]] = {} for score in scores: @@ -595,9 +564,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): -1, # Miss count another, ] - scorestruct[musicid][chartindex + 2] = self.db_to_game_status( - score.data.get_int("clear_status") - ) + scorestruct[musicid][chartindex + 2] = self.db_to_game_status(score.data.get_int("clear_status")) scorestruct[musicid][chartindex + 5] = score.points scorestruct[musicid][chartindex + 8] = score.data.get_int("miss_count", -1) @@ -698,9 +665,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): if ghost_type == self.GHOST_TYPE_RIVAL: rival_extid = int(parameter) - rival_userid = self.data.remote.user.from_extid( - self.game, self.version, rival_extid - ) + rival_userid = self.data.remote.user.from_extid(self.game, self.version, rival_extid) if rival_userid is not None: rival_profile = self.get_profile(rival_userid) rival_score = self.data.remote.music.get_score( @@ -720,10 +685,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): or ghost_type == self.GHOST_TYPE_GLOBAL_AVERAGE or ghost_type == self.GHOST_TYPE_LOCAL_AVERAGE ): - if ( - ghost_type == self.GHOST_TYPE_LOCAL_TOP - or ghost_type == self.GHOST_TYPE_LOCAL_AVERAGE - ): + if ghost_type == self.GHOST_TYPE_LOCAL_TOP or ghost_type == self.GHOST_TYPE_LOCAL_AVERAGE: all_scores = sorted( self.data.local.music.get_all_scores( game=self.game, @@ -756,9 +718,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): all_scores = [ score for score in all_scores - if self.user_joined_arcade( - machine, self.get_any_profile(score[0]) - ) + if self.user_joined_arcade(machine, self.get_any_profile(score[0])) ] else: # Not joined an arcade, so nobody matches our scores @@ -775,10 +735,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): reverse=True, ) - if ( - ghost_type == self.GHOST_TYPE_GLOBAL_TOP - or ghost_type == self.GHOST_TYPE_LOCAL_TOP - ): + if ghost_type == self.GHOST_TYPE_GLOBAL_TOP or ghost_type == self.GHOST_TYPE_LOCAL_TOP: for potential_top in all_scores: top_userid = potential_top[0] top_score = potential_top[1] @@ -793,23 +750,15 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): } break - if ( - ghost_type == self.GHOST_TYPE_GLOBAL_AVERAGE - or ghost_type == self.GHOST_TYPE_LOCAL_AVERAGE - ): - average_score, delta_ghost = self.delta_score( - [score[1] for score in all_scores], ghost_length - ) + if ghost_type == self.GHOST_TYPE_GLOBAL_AVERAGE or ghost_type == self.GHOST_TYPE_LOCAL_AVERAGE: + average_score, delta_ghost = self.delta_score([score[1] for score in all_scores], ghost_length) if average_score is not None and delta_ghost is not None: ghost_score = { "score": average_score, "ghost": bytes([0] * ghost_length), } - if ( - ghost_type == self.GHOST_TYPE_DAN_TOP - or ghost_type == self.GHOST_TYPE_DAN_AVERAGE - ): + if ghost_type == self.GHOST_TYPE_DAN_TOP or ghost_type == self.GHOST_TYPE_DAN_AVERAGE: is_dp = chart not in [ self.CHART_TYPE_N7, self.CHART_TYPE_H7, @@ -839,20 +788,13 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): key=lambda s: s[1].points, reverse=True, ) - all_profiles = self.data.local.user.get_all_profiles( - self.game, self.version - ) + all_profiles = self.data.local.user.get_all_profiles(self.game, self.version) relevant_userids = { profile[0] for profile in all_profiles - if profile[1].get_int( - self.DAN_RANKING_DOUBLE if is_dp else self.DAN_RANKING_SINGLE - ) - == dan_rank + if profile[1].get_int(self.DAN_RANKING_DOUBLE if is_dp else self.DAN_RANKING_SINGLE) == dan_rank } - relevant_scores = [ - score for score in all_scores if score[0] in relevant_userids - ] + relevant_scores = [score for score in all_scores if score[0] in relevant_userids] if ghost_type == self.GHOST_TYPE_DAN_TOP: for potential_top in relevant_scores: top_userid = potential_top[0] @@ -869,23 +811,17 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): break if ghost_type == self.GHOST_TYPE_DAN_AVERAGE: - average_score, delta_ghost = self.delta_score( - [score[1] for score in relevant_scores], ghost_length - ) + average_score, delta_ghost = self.delta_score([score[1] for score in relevant_scores], ghost_length) if average_score is not None and delta_ghost is not None: ghost_score = { "score": average_score, "ghost": bytes([0] * ghost_length), } - if ( - ghost_type == self.GHOST_TYPE_RIVAL_TOP - or ghost_type == self.GHOST_TYPE_RIVAL_AVERAGE - ): + if ghost_type == self.GHOST_TYPE_RIVAL_TOP or ghost_type == self.GHOST_TYPE_RIVAL_AVERAGE: rival_extids = [int(e[1:-1]) for e in parameter.split(",")] rival_userids = [ - self.data.remote.user.from_extid(self.game, self.version, rival_extid) - for rival_extid in rival_extids + self.data.remote.user.from_extid(self.game, self.version, rival_extid) for rival_extid in rival_extids ] all_scores = sorted( @@ -918,9 +854,7 @@ class IIDXBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): break if ghost_type == self.GHOST_TYPE_RIVAL_AVERAGE: - average_score, delta_ghost = self.delta_score( - [score[1] for score in all_scores], ghost_length - ) + average_score, delta_ghost = self.delta_score([score[1] for score in all_scores], ghost_length) if average_score is not None and delta_ghost is not None: ghost_score = { "score": average_score, diff --git a/bemani/backend/iidx/cannonballers.py b/bemani/backend/iidx/cannonballers.py index 3f244f4..9f40e0d 100644 --- a/bemani/backend/iidx/cannonballers.py +++ b/bemani/backend/iidx/cannonballers.py @@ -107,28 +107,15 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): return IIDXSinobuz(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -152,9 +139,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -389,9 +374,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): root = Node.void("IIDX25shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -414,9 +397,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return Node.void("IIDX25shop") @@ -436,9 +417,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -575,16 +554,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): root = Node.void("IIDX25music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -628,16 +598,12 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -645,10 +611,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -675,9 +638,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -768,18 +729,11 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} shop_id = ID.parse_machine_id(request.attribute("location_id")) if not global_scores: - all_scores = [ - score - for score in all_scores - if (score[0] == userid or score[1].location == shop_id) - ] + all_scores = [score for score in all_scores if (score[0] == userid or score[1].location == shop_id)] # Find our actual index oldindex = None @@ -830,9 +784,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -853,11 +805,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): all_players[uid] = prof if not global_scores: - all_scores = [ - score - for score in all_scores - if (score[0] == userid or score[1].location == shop_id) - ] + all_scores = [score for score in all_scores if (score[0] == userid or score[1].location == shop_id)] # Find our actual index ourindex = None @@ -990,13 +938,9 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): } for item in request.children: if item.name == "music_list": - music_list[int(item.child_value("index"))] = int( - item.child_value("total_notes") - ) + music_list[int(item.child_value("index"))] = int(item.child_value("total_notes")) if item.name == "cpu_list": - cpu_list[int(item.child_value("index"))] = int( - item.child_value("grade_id") - ) + cpu_list[int(item.child_value("index"))] = int(item.child_value("grade_id")) for index in range(4): cpu_score_list = Node.void("cpu_score_list") cpu_score_list.add_child(Node.s32("index", index)) @@ -1099,9 +1043,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): root.add_child(event1_phase) event1_phase.set_attribute("phase", str(event1)) - extra_boss_event = Node.void( - "extra_boss_event" - ) # Always enable IIDX AIR RACE 5 + extra_boss_event = Node.void("extra_boss_event") # Always enable IIDX AIR RACE 5 root.add_child(extra_boss_event) extra_boss_event.set_attribute("phase", "4") @@ -1270,9 +1212,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): used_secret_ids: List[int] = [] for c in secret_courses: if c["id"] in used_secret_ids: - raise Exception( - "Cannot have multiple secret courses with the same ID!" - ) + raise Exception("Cannot have multiple secret courses with the same ID!") elif c["id"] < 0 or c["id"] >= 20: raise Exception("Secret course ID is out of bounds!") else: @@ -1483,25 +1423,15 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): root.add_child(arena_cpu_define) arena_cpu_define.add_child(Node.s32("play_style", playstyle)) arena_cpu_define.add_child(Node.s32("arena_class", arena_class)) - arena_cpu_define.add_child( - Node.s32("grade_id", cpu_grades[arena_class]) - ) - arena_cpu_define.add_child( - Node.s32("low_music_difficult", cpu_low_diff[arena_class]) - ) - arena_cpu_define.add_child( - Node.s32("high_music_difficult", cpu_high_diff[arena_class]) - ) - arena_cpu_define.add_child( - Node.bool("is_leggendaria", arena_class >= 13) - ) + arena_cpu_define.add_child(Node.s32("grade_id", cpu_grades[arena_class])) + arena_cpu_define.add_child(Node.s32("low_music_difficult", cpu_low_diff[arena_class])) + arena_cpu_define.add_child(Node.s32("high_music_difficult", cpu_high_diff[arena_class])) + arena_cpu_define.add_child(Node.bool("is_leggendaria", arena_class >= 13)) for matching_class in range(21): matching_class_range = Node.void("matching_class_range") root.add_child(matching_class_range) matching_class_range.add_child(Node.s32("play_style", playstyle)) - matching_class_range.add_child( - Node.s32("matching_class", matching_class) - ) + matching_class_range.add_child(Node.s32("matching_class", matching_class)) matching_class_range.add_child(Node.s32("low_arena_class", 1)) matching_class_range.add_child(Node.s32("high_arena_class", 20)) return root @@ -1551,9 +1481,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1678,15 +1606,9 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3))) # Favorites for folder in ["favorite1", "favorite2", "favorite3"]: @@ -1748,9 +1670,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): ) ), ) - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in achievements: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1822,21 +1742,11 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): qpro_secrete_dict = profile.get_dict("qpro_secret") qpro_secret = Node.void("qpro_secret") root.add_child(qpro_secret) - qpro_secret.add_child( - Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5)) - ) - qpro_secret.add_child( - Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5)) - ) - qpro_secret.add_child( - Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5)) - ) + qpro_secret.add_child(Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5))) + qpro_secret.add_child(Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5))) + qpro_secret.add_child(Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5))) + qpro_secret.add_child(Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5))) + qpro_secret.add_child(Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5))) # Rivals rlist = Node.void("rlist") @@ -1908,9 +1818,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): [ courseid, # course ID coursechart, # course chart - self.db_to_game_status( - course.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(course.data.get_int("clear_status")), # course clear status course.data.get_int("pgnum"), # flashing great count course.data.get_int("gnum"), # great count ], @@ -1928,9 +1836,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): [ courseid, # course ID coursechart, # course chart - self.db_to_game_status( - course.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(course.data.get_int("clear_status")), # course clear status course.data.get_int("pgnum"), # flashing great count course.data.get_int("gnum"), # great count ], @@ -1965,12 +1871,8 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): dj_rank_node = Node.void("dj_rank") root.add_child(dj_rank_node) dj_rank_node.set_attribute("style", str(dj_rank.id)) - dj_rank_node.add_child( - Node.s32_array("rank", dj_rank.data.get_int_array("rank", 15)) - ) - dj_rank_node.add_child( - Node.s32_array("point", dj_rank.data.get_int_array("point", 15)) - ) + dj_rank_node.add_child(Node.s32_array("rank", dj_rank.data.get_int_array("rank", 15))) + dj_rank_node.add_child(Node.s32_array("point", dj_rank.data.get_int_array("point", 15))) for i in range(2): for j in range(15): @@ -1997,24 +1899,12 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): event1 = Node.void("event1") root.add_child(event1) event1.set_attribute("tuneup_point", str(event1_dict.get_int("tuneup_point"))) - event1.set_attribute( - "body_parts_list", str(event1_dict.get_int("body_parts_list")) - ) - event1.set_attribute( - "engine_parts_list", str(event1_dict.get_int("engine_parts_list")) - ) - event1.set_attribute( - "tire_parts_list", str(event1_dict.get_int("tire_parts_list")) - ) - event1.set_attribute( - "body_equip_parts", str(event1_dict.get_int("body_equip_parts")) - ) - event1.set_attribute( - "engine_equip_parts", str(event1_dict.get_int("engine_equip_parts")) - ) - event1.set_attribute( - "tire_equip_parts", str(event1_dict.get_int("tire_equip_parts")) - ) + event1.set_attribute("body_parts_list", str(event1_dict.get_int("body_parts_list"))) + event1.set_attribute("engine_parts_list", str(event1_dict.get_int("engine_parts_list"))) + event1.set_attribute("tire_parts_list", str(event1_dict.get_int("tire_parts_list"))) + event1.set_attribute("body_equip_parts", str(event1_dict.get_int("body_equip_parts"))) + event1.set_attribute("engine_equip_parts", str(event1_dict.get_int("engine_equip_parts"))) + event1.set_attribute("tire_equip_parts", str(event1_dict.get_int("tire_equip_parts"))) event1.set_attribute("gift_point", str(event1_dict.get_int("play_gift"))) for map_data in achievements: @@ -2023,59 +1913,29 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): map_data_node = Node.void("map_data") event1.add_child(map_data_node) map_data_node.set_attribute("map_id", str(map_data.id)) - map_data_node.set_attribute( - "play_num", str(map_data.data.get_int("play_num")) - ) - map_data_node.set_attribute( - "progress", str(map_data.data.get_int("progress")) - ) - map_data_node.set_attribute( - "boost_fuel", str(map_data.data.get_int("boost_fuel")) - ) - map_data_node.set_attribute( - "is_clear", str(map_data.data.get_int("is_clear")) - ) - map_data_node.set_attribute( - "rare_defeat_list", str(map_data.data.get_int("rare_defeat_list")) - ) - map_data_node.set_attribute( - "rare1_appearance", str(map_data.data.get_int("rare1_appearance")) - ) - map_data_node.set_attribute( - "rare2_appearance", str(map_data.data.get_int("rare2_appearance")) - ) - map_data_node.set_attribute( - "rare3_appearance", str(map_data.data.get_int("rare3_appearance")) - ) - map_data_node.set_attribute( - "rare4_appearance", str(map_data.data.get_int("rare4_appearance")) - ) - map_data_node.set_attribute( - "rare5_appearance", str(map_data.data.get_int("rare5_appearance")) - ) - map_data_node.set_attribute( - "rare6_appearance", str(map_data.data.get_int("rare6_appearance")) - ) + map_data_node.set_attribute("play_num", str(map_data.data.get_int("play_num"))) + map_data_node.set_attribute("progress", str(map_data.data.get_int("progress"))) + map_data_node.set_attribute("boost_fuel", str(map_data.data.get_int("boost_fuel"))) + map_data_node.set_attribute("is_clear", str(map_data.data.get_int("is_clear"))) + map_data_node.set_attribute("rare_defeat_list", str(map_data.data.get_int("rare_defeat_list"))) + map_data_node.set_attribute("rare1_appearance", str(map_data.data.get_int("rare1_appearance"))) + map_data_node.set_attribute("rare2_appearance", str(map_data.data.get_int("rare2_appearance"))) + map_data_node.set_attribute("rare3_appearance", str(map_data.data.get_int("rare3_appearance"))) + map_data_node.set_attribute("rare4_appearance", str(map_data.data.get_int("rare4_appearance"))) + map_data_node.set_attribute("rare5_appearance", str(map_data.data.get_int("rare5_appearance"))) + map_data_node.set_attribute("rare6_appearance", str(map_data.data.get_int("rare6_appearance"))) # OMES Data omes_dict = profile.get_dict("omes") onemore_data = Node.void("onemore_event") root.add_child(onemore_data) for i in range(6): - onemore_data.set_attribute( - f"defeat_{i}", str(omes_dict.get_int(f"defeat_{i}")) - ) + onemore_data.set_attribute(f"defeat_{i}", str(omes_dict.get_int(f"defeat_{i}"))) for i in range(3): i = i + 1 - onemore_data.set_attribute( - f"challenge_num_{i}_n", str(omes_dict.get_int(f"challenge_num_{i}_n")) - ) - onemore_data.set_attribute( - f"challenge_num_{i}_h", str(omes_dict.get_int(f"challenge_num_{i}_h")) - ) - onemore_data.set_attribute( - f"challenge_num_{i}_a", str(omes_dict.get_int(f"challenge_num_{i}_a")) - ) + onemore_data.set_attribute(f"challenge_num_{i}_n", str(omes_dict.get_int(f"challenge_num_{i}_n"))) + onemore_data.set_attribute(f"challenge_num_{i}_h", str(omes_dict.get_int(f"challenge_num_{i}_h"))) + onemore_data.set_attribute(f"challenge_num_{i}_a", str(omes_dict.get_int(f"challenge_num_{i}_a"))) # Step up mode step_dict = profile.get_dict("step") @@ -2084,18 +1944,14 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): step.set_attribute("enemy_damage", str(step_dict.get_int("enemy_damage"))) step.set_attribute("progress", str(step_dict.get_int("progress"))) step.set_attribute("point", str(step_dict.get_int("point"))) - step.set_attribute( - "enemy_defeat_flg", str(step_dict.get_int("enemy_defeat_flg")) - ) + step.set_attribute("enemy_defeat_flg", str(step_dict.get_int("enemy_defeat_flg"))) step.set_attribute("sp_level", str(step_dict.get_int("sp_level"))) step.set_attribute("dp_level", str(step_dict.get_int("dp_level"))) step.set_attribute("sp_mplay", str(step_dict.get_int("sp_mplay"))) step.set_attribute("dp_mplay", str(step_dict.get_int("dp_mplay"))) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -2118,36 +1974,24 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): achievement_node.set_attribute("pack", "0") achievement_node.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() - achievement_node.set_attribute( - "pack", str(daily_played.get_int("pack_flg")) - ) - achievement_node.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievement_node.set_attribute("pack", str(daily_played.get_int("pack_flg"))) + achievement_node.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies - achievement_node.set_attribute( - "last_weekly", str(profile.get_int("last_weekly")) - ) + achievement_node.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) achievement_node.set_attribute("weekly_num", str(profile.get_int("weekly_num"))) # Prefecture visit flag achievement_node.set_attribute("visit_flg", str(profile.get_int("visit_flg"))) # Number of rivals beaten - achievement_node.set_attribute( - "rival_crush", str(profile.get_int("rival_crush")) - ) + achievement_node.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievement_node.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 20)) - ) + achievement_node.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 20))) # Track deller deller = Node.void("deller") @@ -2170,9 +2014,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): detail.set_attribute("course_id", str(rank.id)) detail.set_attribute("n_point", str(rank.data.get_int("normal_points"))) detail.set_attribute("h_point", str(rank.data.get_int("hyper_points"))) - detail.set_attribute( - "a_point", str(rank.data.get_int("another_points")) - ) + detail.set_attribute("a_point", str(rank.data.get_int("another_points"))) nostalgia = Node.void("nostalgia_open") root.add_child(nostalgia) @@ -2185,9 +2027,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): pay_per_use.set_attribute("item_num", "99") return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -2239,12 +2079,8 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): newprofile.replace_int("d_gauge_disp", int(request.attribute("d_gauge_disp"))) newprofile.replace_int("s_lane_brignt", int(request.attribute("s_lane_brignt"))) newprofile.replace_int("d_lane_brignt", int(request.attribute("d_lane_brignt"))) - newprofile.replace_int( - "s_camera_layout", int(request.attribute("s_camera_layout")) - ) - newprofile.replace_int( - "d_camera_layout", int(request.attribute("d_camera_layout")) - ) + newprofile.replace_int("s_camera_layout", int(request.attribute("s_camera_layout"))) + newprofile.replace_int("d_camera_layout", int(request.attribute("d_camera_layout"))) newprofile.replace_int("s_lift", int(request.attribute("s_lift"))) newprofile.replace_int("d_lift", int(request.attribute("d_lift"))) newprofile.replace_int("mode", int(request.attribute("mode"))) @@ -2272,15 +2108,9 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -2304,9 +2134,7 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Secret course expert point saving expert_point = request.child("expert_point") @@ -2370,22 +2198,14 @@ class IIDXCannonBallers(IIDXCourse, IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -149,9 +136,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -357,9 +342,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): root = Node.void("IIDX23shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -383,9 +366,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return root @@ -410,9 +391,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -527,16 +506,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): root = Node.void("IIDX23music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -580,16 +550,12 @@ class IIDXCopula(IIDXCourse, IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -597,10 +563,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -643,19 +606,13 @@ class IIDXCopula(IIDXCourse, IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} if not global_scores: all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -707,9 +664,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -733,10 +688,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -884,9 +836,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -1318,9 +1268,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): used_secret_ids: List[int] = [] for c in secret_courses: if c["id"] in used_secret_ids: - raise Exception( - "Cannot have multiple secret courses with the same ID!" - ) + raise Exception("Cannot have multiple secret courses with the same ID!") elif c["id"] < 0 or c["id"] >= 20: raise Exception("Secret course ID is out of bounds!") else: @@ -1497,9 +1445,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1609,15 +1555,9 @@ class IIDXCopula(IIDXCourse, IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1, -1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1, -1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 4)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 4)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 4)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 4))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 4))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 4))) # Favorites for folder in ["favorite1", "favorite2", "favorite3"]: @@ -1679,9 +1619,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): ) ), ) - rankings = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + rankings = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in rankings: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1822,9 +1760,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): [ int(rank.id / 6), # course ID rank.id % 6, # course chart - self.db_to_game_status( - rank.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(rank.data.get_int("clear_status")), # course clear status rank.data.get_int("pgnum"), # flashing great count rank.data.get_int("gnum"), # great count ], @@ -1841,9 +1777,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): [ int(rank.id / 6), # course ID rank.id % 6, # course chart - self.db_to_game_status( - rank.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(rank.data.get_int("clear_status")), # course clear status rank.data.get_int("pgnum"), # flashing great count rank.data.get_int("gnum"), # great count ], @@ -1881,16 +1815,12 @@ class IIDXCopula(IIDXCourse, IIDXBase): step.add_child( Node.binary( "tokimeki", - step_dict.get_bytes( - "tokimeki", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - ), + step_dict.get_bytes("tokimeki", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), ) ) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -1913,15 +1843,11 @@ class IIDXCopula(IIDXCourse, IIDXBase): achievements.set_attribute("pack", "0") achievements.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() achievements.set_attribute("pack", str(daily_played.get_int("pack_flg"))) - achievements.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievements.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies achievements.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) @@ -1934,9 +1860,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): achievements.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievements.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 10)) - ) + achievements.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 10))) # Track deller deller = Node.void("deller") @@ -1959,9 +1883,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): detail.set_attribute("course_id", str(rank.id)) detail.set_attribute("n_point", str(rank.data.get_int("normal_points"))) detail.set_attribute("h_point", str(rank.data.get_int("hyper_points"))) - detail.set_attribute( - "a_point", str(rank.data.get_int("another_points")) - ) + detail.set_attribute("a_point", str(rank.data.get_int("another_points"))) # Tokotoko Line Event if "event1" in profile: @@ -1969,31 +1891,15 @@ class IIDXCopula(IIDXCourse, IIDXBase): event1_dict = profile.get_dict("event1") event1_data = Node.void("event1_data") root.add_child(event1_data) - event1_data.set_attribute( - "point_map_0", str(event1_dict.get_int("point_map_0")) - ) - event1_data.set_attribute( - "point_map_1", str(event1_dict.get_int("point_map_1")) - ) - event1_data.set_attribute( - "point_map_2", str(event1_dict.get_int("point_map_2")) - ) - event1_data.set_attribute( - "point_map_3", str(event1_dict.get_int("point_map_3")) - ) - event1_data.set_attribute( - "point_map_4", str(event1_dict.get_int("point_map_4")) - ) - event1_data.set_attribute( - "hold_point", str(event1_dict.get_int("hold_point")) - ) + event1_data.set_attribute("point_map_0", str(event1_dict.get_int("point_map_0"))) + event1_data.set_attribute("point_map_1", str(event1_dict.get_int("point_map_1"))) + event1_data.set_attribute("point_map_2", str(event1_dict.get_int("point_map_2"))) + event1_data.set_attribute("point_map_3", str(event1_dict.get_int("point_map_3"))) + event1_data.set_attribute("point_map_4", str(event1_dict.get_int("point_map_4"))) + event1_data.set_attribute("hold_point", str(event1_dict.get_int("hold_point"))) event1_data.set_attribute("last_map", str(event1_dict.get_int("last_map"))) - event1_data.set_attribute( - "rank_point", str(event1_dict.get_int("rank_point")) - ) - event1_data.set_attribute( - "tips_list", str(event1_dict.get_int("tips_list")) - ) + event1_data.set_attribute("rank_point", str(event1_dict.get_int("rank_point"))) + event1_data.set_attribute("tips_list", str(event1_dict.get_int("tips_list"))) event1_data.set_attribute("gift_point", "0") # Mystery Line Event @@ -2004,16 +1910,10 @@ class IIDXCopula(IIDXCourse, IIDXBase): root.add_child(event2_data) event2_data.set_attribute("play_num", str(event2_dict.get_int("play_num"))) event2_data.set_attribute("now_area", str(event2_dict.get_int("now_area"))) - event2_data.set_attribute( - "now_note_grade", str(event2_dict.get_int("now_note_grade")) - ) - event2_data.set_attribute( - "stop_area_time", str(event2_dict.get_int("stop_area_time")) - ) + event2_data.set_attribute("now_note_grade", str(event2_dict.get_int("now_note_grade"))) + event2_data.set_attribute("stop_area_time", str(event2_dict.get_int("stop_area_time"))) - areas = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + areas = self.data.local.user.get_achievements(self.game, self.version, userid) for area in areas: if area.type != "event2_area_data": continue @@ -2021,18 +1921,10 @@ class IIDXCopula(IIDXCourse, IIDXBase): event2_area_data = Node.void("event2_area_data") event2_data.add_child(event2_area_data) event2_area_data.set_attribute("area_no", str(area.id)) - event2_area_data.set_attribute( - "area_play", str(area.data.get_int("play_num")) - ) - event2_area_data.set_attribute( - "normal_point", str(area.data.get_int("normal_point")) - ) - event2_area_data.set_attribute( - "hyper_point", str(area.data.get_int("hyper_point")) - ) - event2_area_data.set_attribute( - "another_point", str(area.data.get_int("another_point")) - ) + event2_area_data.set_attribute("area_play", str(area.data.get_int("play_num"))) + event2_area_data.set_attribute("normal_point", str(area.data.get_int("normal_point"))) + event2_area_data.set_attribute("hyper_point", str(area.data.get_int("hyper_point"))) + event2_area_data.set_attribute("another_point", str(area.data.get_int("another_point"))) # One More Event if "onemore" in profile: @@ -2040,42 +1932,22 @@ class IIDXCopula(IIDXCourse, IIDXBase): onemore_dict = profile.get_dict("onemore") onemore_data = Node.void("onemore_data") root.add_child(onemore_data) - onemore_data.set_attribute( - "defeat_0", str(onemore_dict.get_int("defeat_0")) - ) - onemore_data.set_attribute( - "defeat_1", str(onemore_dict.get_int("defeat_1")) - ) - onemore_data.set_attribute( - "defeat_2", str(onemore_dict.get_int("defeat_2")) - ) - onemore_data.set_attribute( - "defeat_3", str(onemore_dict.get_int("defeat_3")) - ) - onemore_data.set_attribute( - "defeat_4", str(onemore_dict.get_int("defeat_4")) - ) - onemore_data.set_attribute( - "defeat_5", str(onemore_dict.get_int("defeat_5")) - ) - onemore_data.set_attribute( - "challenge_num_n", str(onemore_dict.get_int("challenge_num_n")) - ) - onemore_data.set_attribute( - "challenge_num_h", str(onemore_dict.get_int("challenge_num_h")) - ) - onemore_data.set_attribute( - "challenge_num_a", str(onemore_dict.get_int("challenge_num_a")) - ) + onemore_data.set_attribute("defeat_0", str(onemore_dict.get_int("defeat_0"))) + onemore_data.set_attribute("defeat_1", str(onemore_dict.get_int("defeat_1"))) + onemore_data.set_attribute("defeat_2", str(onemore_dict.get_int("defeat_2"))) + onemore_data.set_attribute("defeat_3", str(onemore_dict.get_int("defeat_3"))) + onemore_data.set_attribute("defeat_4", str(onemore_dict.get_int("defeat_4"))) + onemore_data.set_attribute("defeat_5", str(onemore_dict.get_int("defeat_5"))) + onemore_data.set_attribute("challenge_num_n", str(onemore_dict.get_int("challenge_num_n"))) + onemore_data.set_attribute("challenge_num_h", str(onemore_dict.get_int("challenge_num_h"))) + onemore_data.set_attribute("challenge_num_a", str(onemore_dict.get_int("challenge_num_a"))) # Ea app features if self.data.triggers.has_broadcast_destination(self.game): root.add_child(Node.void("bind_eaappli")) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -2151,15 +2023,9 @@ class IIDXCopula(IIDXCourse, IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -2183,9 +2049,7 @@ class IIDXCopula(IIDXCourse, IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Secret course expert point saving expert_point = request.child("expert_point") @@ -2249,22 +2113,14 @@ class IIDXCopula(IIDXCourse, IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -146,9 +133,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -243,9 +228,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): root = Node.void("IIDX22shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -269,9 +252,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return root @@ -291,9 +272,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -530,16 +509,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): root = Node.void("IIDX22music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -583,16 +553,12 @@ class IIDXPendual(IIDXCourse, IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -600,10 +566,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -646,19 +609,13 @@ class IIDXPendual(IIDXCourse, IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} if not global_scores: all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -710,9 +667,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -736,10 +691,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -887,9 +839,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -1240,9 +1190,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): used_secret_ids: List[int] = [] for c in secret_courses: if c["id"] in used_secret_ids: - raise Exception( - "Cannot have multiple secret courses with the same ID!" - ) + raise Exception("Cannot have multiple secret courses with the same ID!") elif c["id"] < 0 or c["id"] >= 10: raise Exception("Secret course ID is out of bounds!") else: @@ -1272,13 +1220,9 @@ class IIDXPendual(IIDXCourse, IIDXBase): common_timeshift_phase = Node.void("common_timeshift_phase") root.add_child(common_timeshift_phase) if timeshift_override == 0: - common_timeshift_phase.set_attribute( - "phase", "1" if (days_since_epoch % 2) == 0 else "2" - ) + common_timeshift_phase.set_attribute("phase", "1" if (days_since_epoch % 2) == 0 else "2") elif timeshift_override == 1: - common_timeshift_phase.set_attribute( - "phase", "2" if (days_since_epoch % 2) == 0 else "1" - ) + common_timeshift_phase.set_attribute("phase", "2" if (days_since_epoch % 2) == 0 else "1") elif timeshift_override == 2: common_timeshift_phase.set_attribute("phase", "1") elif timeshift_override == 3: @@ -1306,9 +1250,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): # Ranking details in title screen rankingcharts = [] - for mid, _plays in self.data.local.music.get_hit_chart( - self.game, self.music_version, 20 - ): + for mid, _plays in self.data.local.music.get_hit_chart(self.game, self.music_version, 20): rankingcharts.append(mid) root.add_child(Node.u16_array("monthly_mranking", rankingcharts)) root.add_child(Node.u16_array("total_mranking", rankingcharts)) @@ -1467,9 +1409,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1578,9 +1518,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): join_shop.set_attribute("join_name", machine.name) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -1611,15 +1549,9 @@ class IIDXPendual(IIDXCourse, IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3))) # Tran medals and shit achievements = Node.void("achievements") @@ -1630,15 +1562,11 @@ class IIDXPendual(IIDXCourse, IIDXBase): achievements.set_attribute("pack", "0") achievements.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() achievements.set_attribute("pack", str(daily_played.get_int("pack_flg"))) - achievements.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievements.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies achievements.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) @@ -1651,9 +1579,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): achievements.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievements.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 10)) - ) + achievements.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 10))) # User settings settings_dict = profile.get_dict("settings") @@ -1699,9 +1625,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): ) ), ) - rankings = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + rankings = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in rankings: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1739,9 +1663,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): [ int(rank.id / 6), # course ID rank.id % 6, # course chart - self.db_to_game_status( - rank.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(rank.data.get_int("clear_status")), # course clear status rank.data.get_int("pgnum"), # flashing great count rank.data.get_int("gnum"), # great count ], @@ -1758,9 +1680,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): [ int(rank.id / 6), # course ID rank.id % 6, # course chart - self.db_to_game_status( - rank.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(rank.data.get_int("clear_status")), # course clear status rank.data.get_int("pgnum"), # flashing great count rank.data.get_int("gnum"), # great count ], @@ -1776,9 +1696,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): detail.set_attribute("course_id", str(rank.id)) detail.set_attribute("n_point", str(rank.data.get_int("normal_points"))) detail.set_attribute("h_point", str(rank.data.get_int("hyper_points"))) - detail.set_attribute( - "a_point", str(rank.data.get_int("another_points")) - ) + detail.set_attribute("a_point", str(rank.data.get_int("another_points"))) # Qpro data qpro_dict = profile.get_dict("qpro") @@ -1880,9 +1798,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): step.add_child( Node.binary( "album", - step_dict.get_bytes( - "album", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - ), + step_dict.get_bytes("album", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), ) ) @@ -1962,9 +1878,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): present_time_sandglass.set_attribute("item_num", "99") # TODO: Same as above. - pointsdict = profile.get_dict( - "point_events" - ) # used for summer, dcat, and pyramid + pointsdict = profile.get_dict("point_events") # used for summer, dcat, and pyramid # destiny event dcat = Node.void("destiny_catharsis") root.add_child(dcat) @@ -1980,46 +1894,20 @@ class IIDXPendual(IIDXCourse, IIDXBase): cdive = Node.void("chrono_diver") root.add_child(cdive) cdive.set_attribute("play_count", str(diverdict.get_int("play_count", 0))) - cdive.set_attribute( - "present_unlock", str(diverdict.get_int("present_unlock", 0)) - ) + cdive.set_attribute("present_unlock", str(diverdict.get_int("present_unlock", 0))) cdive.set_attribute("future_unlock", str(diverdict.get_int("future_unlock", 0))) - cdive.set_attribute( - "success_count_0_n", str(diverdict.get_int("success_count_0_n", 0)) - ) - cdive.set_attribute( - "success_count_0_h", str(diverdict.get_int("success_count_0_h", 0)) - ) - cdive.set_attribute( - "success_count_0_a", str(diverdict.get_int("success_count_0_a", 0)) - ) - cdive.set_attribute( - "success_count_1_n", str(diverdict.get_int("success_count_1_n", 0)) - ) - cdive.set_attribute( - "success_count_1_h", str(diverdict.get_int("success_count_1_h", 0)) - ) - cdive.set_attribute( - "success_count_1_a", str(diverdict.get_int("success_count_1_a", 0)) - ) - cdive.set_attribute( - "success_count_2_n", str(diverdict.get_int("success_count_2_n", 0)) - ) - cdive.set_attribute( - "success_count_2_h", str(diverdict.get_int("success_count_2_h", 0)) - ) - cdive.set_attribute( - "success_count_2_a", str(diverdict.get_int("success_count_2_a", 0)) - ) - cdive.set_attribute( - "success_count_3_n", str(diverdict.get_int("success_count_3_n", 0)) - ) - cdive.set_attribute( - "success_count_3_h", str(diverdict.get_int("success_count_3_h", 0)) - ) - cdive.set_attribute( - "success_count_3_a", str(diverdict.get_int("success_count_3_a", 0)) - ) + cdive.set_attribute("success_count_0_n", str(diverdict.get_int("success_count_0_n", 0))) + cdive.set_attribute("success_count_0_h", str(diverdict.get_int("success_count_0_h", 0))) + cdive.set_attribute("success_count_0_a", str(diverdict.get_int("success_count_0_a", 0))) + cdive.set_attribute("success_count_1_n", str(diverdict.get_int("success_count_1_n", 0))) + cdive.set_attribute("success_count_1_h", str(diverdict.get_int("success_count_1_h", 0))) + cdive.set_attribute("success_count_1_a", str(diverdict.get_int("success_count_1_a", 0))) + cdive.set_attribute("success_count_2_n", str(diverdict.get_int("success_count_2_n", 0))) + cdive.set_attribute("success_count_2_h", str(diverdict.get_int("success_count_2_h", 0))) + cdive.set_attribute("success_count_2_a", str(diverdict.get_int("success_count_2_a", 0))) + cdive.set_attribute("success_count_3_n", str(diverdict.get_int("success_count_3_n", 0))) + cdive.set_attribute("success_count_3_h", str(diverdict.get_int("success_count_3_h", 0))) + cdive.set_attribute("success_count_3_a", str(diverdict.get_int("success_count_3_a", 0))) cdive.set_attribute("story_list", str(diverdict.get_int("story_list", 0))) # reflec beat collaboration @@ -2048,9 +1936,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -2126,15 +2012,9 @@ class IIDXPendual(IIDXCourse, IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -2158,9 +2038,7 @@ class IIDXPendual(IIDXCourse, IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Secret course expert point saving expert_point = request.child("expert_point") @@ -2212,17 +2090,13 @@ class IIDXPendual(IIDXCourse, IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -152,9 +139,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -390,9 +375,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): root = Node.void("IIDX26shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -415,9 +398,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return Node.void("IIDX26shop") @@ -429,16 +410,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): root = Node.void("IIDX26music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -482,16 +454,12 @@ class IIDXRootage(IIDXCourse, IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -499,10 +467,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -529,9 +494,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -622,18 +585,11 @@ class IIDXRootage(IIDXCourse, IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} shop_id = ID.parse_machine_id(request.attribute("location_id")) if not global_scores: - all_scores = [ - score - for score in all_scores - if (score[0] == userid or score[1].location == shop_id) - ] + all_scores = [score for score in all_scores if (score[0] == userid or score[1].location == shop_id)] # Find our actual index oldindex = None @@ -684,9 +640,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -707,11 +661,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): all_players[uid] = prof if not global_scores: - all_scores = [ - score - for score in all_scores - if (score[0] == userid or score[1].location == shop_id) - ] + all_scores = [score for score in all_scores if (score[0] == userid or score[1].location == shop_id)] # Find our actual index ourindex = None @@ -844,13 +794,9 @@ class IIDXRootage(IIDXCourse, IIDXBase): } for item in request.children: if item.name == "music_list": - music_list[int(item.child_value("index"))] = int( - item.child_value("total_notes") - ) + music_list[int(item.child_value("index"))] = int(item.child_value("total_notes")) if item.name == "cpu_list": - cpu_list[int(item.child_value("index"))] = int( - item.child_value("grade_id") - ) + cpu_list[int(item.child_value("index"))] = int(item.child_value("grade_id")) for index in range(4): cpu_score_list = Node.void("cpu_score_list") cpu_score_list.add_child(Node.s32("index", index)) @@ -991,9 +937,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): root.set_attribute("pflg", "0") return root - def handle_IIDX26pc_shopregister_request( - self, request: Node - ) -> Node: # Not used anymore???? + def handle_IIDX26pc_shopregister_request(self, request: Node) -> Node: # Not used anymore???? root = Node.void("IIDX26pc") return root @@ -1115,9 +1059,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1239,25 +1181,15 @@ class IIDXRootage(IIDXCourse, IIDXBase): root.add_child(arena_cpu_define) arena_cpu_define.add_child(Node.s32("play_style", playstyle)) arena_cpu_define.add_child(Node.s32("arena_class", arena_class)) - arena_cpu_define.add_child( - Node.s32("grade_id", cpu_grades[arena_class]) - ) - arena_cpu_define.add_child( - Node.s32("low_music_difficult", cpu_low_diff[arena_class]) - ) - arena_cpu_define.add_child( - Node.s32("high_music_difficult", cpu_high_diff[arena_class]) - ) - arena_cpu_define.add_child( - Node.bool("is_leggendaria", arena_class >= 13) - ) + arena_cpu_define.add_child(Node.s32("grade_id", cpu_grades[arena_class])) + arena_cpu_define.add_child(Node.s32("low_music_difficult", cpu_low_diff[arena_class])) + arena_cpu_define.add_child(Node.s32("high_music_difficult", cpu_high_diff[arena_class])) + arena_cpu_define.add_child(Node.bool("is_leggendaria", arena_class >= 13)) for matching_class in range(21): matching_class_range = Node.void("matching_class_range") root.add_child(matching_class_range) matching_class_range.add_child(Node.s32("play_style", playstyle)) - matching_class_range.add_child( - Node.s32("matching_class", matching_class) - ) + matching_class_range.add_child(Node.s32("matching_class", matching_class)) matching_class_range.add_child(Node.s32("low_arena_class", 1)) matching_class_range.add_child(Node.s32("high_arena_class", 20)) return root @@ -1330,12 +1262,8 @@ class IIDXRootage(IIDXCourse, IIDXBase): pcdata.set_attribute("d_camera_layout", str(profile.get_int("d_camera_layout"))) pcdata.set_attribute("s_ghost_score", str(profile.get_int("s_ghost_score"))) pcdata.set_attribute("d_ghost_score", str(profile.get_int("d_ghost_score"))) - pcdata.set_attribute( - "s_tsujigiri_disp", str(profile.get_int("s_tsujigiri_disp")) - ) - pcdata.set_attribute( - "d_tsujigiri_disp", str(profile.get_int("d_tsujigiri_disp")) - ) + pcdata.set_attribute("s_tsujigiri_disp", str(profile.get_int("s_tsujigiri_disp"))) + pcdata.set_attribute("d_tsujigiri_disp", str(profile.get_int("d_tsujigiri_disp"))) # KAC stuff # kac_entry_info = Node.void('kac_entry_info') @@ -1363,15 +1291,9 @@ class IIDXRootage(IIDXCourse, IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3))) # Favorites for folder in ["favorite1", "favorite2", "favorite3"]: @@ -1420,21 +1342,11 @@ class IIDXRootage(IIDXCourse, IIDXBase): qpro_secrete_dict = profile.get_dict("qpro_secret") qpro_secret = Node.void("qpro_secret") root.add_child(qpro_secret) - qpro_secret.add_child( - Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5)) - ) - qpro_secret.add_child( - Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5)) - ) - qpro_secret.add_child( - Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5)) - ) + qpro_secret.add_child(Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5))) + qpro_secret.add_child(Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5))) + qpro_secret.add_child(Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5))) + qpro_secret.add_child(Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5))) + qpro_secret.add_child(Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5))) # DAN rankings grade = Node.void("grade") @@ -1457,9 +1369,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): ) ), ) - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in achievements: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1604,12 +1514,8 @@ class IIDXRootage(IIDXCourse, IIDXBase): dj_rank_node = Node.void("dj_rank") root.add_child(dj_rank_node) dj_rank_node.set_attribute("style", str(dj_rank.id)) - dj_rank_node.add_child( - Node.s32_array("rank", dj_rank.data.get_int_array("rank", 15)) - ) - dj_rank_node.add_child( - Node.s32_array("point", dj_rank.data.get_int_array("point", 15)) - ) + dj_rank_node.add_child(Node.s32_array("rank", dj_rank.data.get_int_array("rank", 15))) + dj_rank_node.add_child(Node.s32_array("point", dj_rank.data.get_int_array("point", 15))) dj_rank_ranking_node = Node.void("dj_rank_ranking") root.add_child(dj_rank_ranking_node) @@ -1655,25 +1561,13 @@ class IIDXRootage(IIDXCourse, IIDXBase): event1_dict = profile.get_dict("event1") event1 = Node.void("event1") root.add_child(event1) - event1.set_attribute( - "event_play_num", str(event1_dict.get_int("event_play_num")) - ) + event1.set_attribute("event_play_num", str(event1_dict.get_int("event_play_num"))) event1.set_attribute("fragment_num", str(event1_dict.get_int("fragment_num"))) - event1.set_attribute( - "last_select_map_id", str(event1_dict.get_int("last_select_map")) - ) - event1.set_attribute( - "read_tips_list", str(event1_dict.get_int("read_tips_list")) - ) - event1.set_attribute( - "continuous_correct", str(event1_dict.get_int("continuous_correct")) - ) - event1.set_attribute( - "bookshelf_release_num", str(event1_dict.get_int("bookshelf_release_num")) - ) - event1.add_child( - Node.binary("quiz_control_list", event1_dict.get_bytes("quiz_control_list")) - ) + event1.set_attribute("last_select_map_id", str(event1_dict.get_int("last_select_map"))) + event1.set_attribute("read_tips_list", str(event1_dict.get_int("read_tips_list"))) + event1.set_attribute("continuous_correct", str(event1_dict.get_int("continuous_correct"))) + event1.set_attribute("bookshelf_release_num", str(event1_dict.get_int("bookshelf_release_num"))) + event1.add_child(Node.binary("quiz_control_list", event1_dict.get_bytes("quiz_control_list"))) for map_data in achievements: if map_data.type != "map_data": continue @@ -1681,9 +1575,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): map_data_node = Node.void("map_data") event1.add_child(map_data_node) map_data_node.set_attribute("map_id", str(map_data.id)) - map_data_node.set_attribute( - "play_num", str(map_data.data.get_int("play_num")) - ) + map_data_node.set_attribute("play_num", str(map_data.data.get_int("play_num"))) map_data_node.set_attribute( "last_select_route_id", str(map_data.data.get_int("last_select_route_id")), @@ -1692,14 +1584,8 @@ class IIDXRootage(IIDXCourse, IIDXBase): "bookshelf_release_num", str(map_data.data.get_int("bookshelf_release_num")), ) - map_data_node.add_child( - Node.bool("is_clear", map_data.data.get_bool("is_clear")) - ) - map_data_node.add_child( - Node.binary( - "map_route_damage", map_data.data.get_bytes("map_route_damage") - ) - ) + map_data_node.add_child(Node.bool("is_clear", map_data.data.get_bool("is_clear"))) + map_data_node.add_child(Node.binary("map_route_damage", map_data.data.get_bytes("map_route_damage"))) # DELABITY LABORATORY event event2_dict = profile.get_dict("event2") @@ -1707,27 +1593,13 @@ class IIDXRootage(IIDXCourse, IIDXBase): root.add_child(event2) event2.set_attribute("play_num", str(event2_dict.get_int("play_num"))) event2.set_attribute("delabity", str(event2_dict.get_int("delabity"))) - event2.set_attribute( - "floor_0_last_area", str(event2_dict.get_int("floor_0_last_area")) - ) - event2.set_attribute( - "floor_1_last_area", str(event2_dict.get_int("floor_1_last_area")) - ) - event2.set_attribute( - "floor_2_last_area", str(event2_dict.get_int("floor_2_last_area")) - ) - event2.set_attribute( - "floor_3_last_area", str(event2_dict.get_int("floor_3_last_area")) - ) - event2.set_attribute( - "floor_4_last_area", str(event2_dict.get_int("floor_4_last_area")) - ) - event2.set_attribute( - "floor_clear_flg_list", str(event2_dict.get_int("floor_clear_flg_list")) - ) - event2.set_attribute( - "last_select_floor", str(event2_dict.get_int("last_select_floor")) - ) + event2.set_attribute("floor_0_last_area", str(event2_dict.get_int("floor_0_last_area"))) + event2.set_attribute("floor_1_last_area", str(event2_dict.get_int("floor_1_last_area"))) + event2.set_attribute("floor_2_last_area", str(event2_dict.get_int("floor_2_last_area"))) + event2.set_attribute("floor_3_last_area", str(event2_dict.get_int("floor_3_last_area"))) + event2.set_attribute("floor_4_last_area", str(event2_dict.get_int("floor_4_last_area"))) + event2.set_attribute("floor_clear_flg_list", str(event2_dict.get_int("floor_clear_flg_list"))) + event2.set_attribute("last_select_floor", str(event2_dict.get_int("last_select_floor"))) event2.set_attribute("tips_list", str(event2_dict.get_int("tips_list"))) areas = self.data.local.user.get_achievements(self.game, self.version, userid) @@ -1738,45 +1610,25 @@ class IIDXRootage(IIDXCourse, IIDXBase): event2.add_child(area_data) area_data.set_attribute("area_id", str(area.id)) area_data.set_attribute("floor_id", str(area.data.get_int("floor_id"))) - area_data.set_attribute( - "last_select_note", str(area.data.get_int("last_select_note")) - ) - area_data.set_attribute( - "normal_play_num", str(area.data.get_int("normal_play_num")) - ) - area_data.set_attribute( - "hyper_play_num", str(area.data.get_int("hyper_play_num")) - ) - area_data.set_attribute( - "another_play_num", str(area.data.get_int("another_play_num")) - ) - area_data.set_attribute( - "area_clear_flg_list", str(area.data.get_int("area_clear_flg_list")) - ) - area_data.set_attribute( - "normal_grade_point", str(area.data.get_int("normal_grade_point")) - ) - area_data.set_attribute( - "hyper_grade_point", str(area.data.get_int("hyper_grade_point")) - ) - area_data.set_attribute( - "another_grade_point", str(area.data.get_int("another_grade_point")) - ) + area_data.set_attribute("last_select_note", str(area.data.get_int("last_select_note"))) + area_data.set_attribute("normal_play_num", str(area.data.get_int("normal_play_num"))) + area_data.set_attribute("hyper_play_num", str(area.data.get_int("hyper_play_num"))) + area_data.set_attribute("another_play_num", str(area.data.get_int("another_play_num"))) + area_data.set_attribute("area_clear_flg_list", str(area.data.get_int("area_clear_flg_list"))) + area_data.set_attribute("normal_grade_point", str(area.data.get_int("normal_grade_point"))) + area_data.set_attribute("hyper_grade_point", str(area.data.get_int("hyper_grade_point"))) + area_data.set_attribute("another_grade_point", str(area.data.get_int("another_grade_point"))) tonyutsu = Node.void("tonyutsu") tonyutsu_dict = profile.get_dict("tonyutsu") - tonyutsu.set_attribute( - "platinum_pass", str(tonyutsu_dict.get_int("platiunum_pass")) - ) + tonyutsu.set_attribute("platinum_pass", str(tonyutsu_dict.get_int("platiunum_pass"))) tonyutsu.set_attribute("black_pass", str(tonyutsu_dict.get_int("black_pass"))) extra_boss_event_dict = profile.get_dict("extra_boss_event") extra_boss_event = Node.void("extra_boss_event") root.add_child(extra_boss_event) for i in range(9): - extra_boss_event.set_attribute( - f"orb_{i}", str(extra_boss_event_dict.get_int(f"orb_{i}")) - ) + extra_boss_event.set_attribute(f"orb_{i}", str(extra_boss_event_dict.get_int(f"orb_{i}"))) # Step up mode step_dict = profile.get_dict("step") @@ -1784,49 +1636,25 @@ class IIDXRootage(IIDXCourse, IIDXBase): root.add_child(step) step.set_attribute("enemy_damage", str(step_dict.get_int("enemy_damage"))) step.set_attribute("progress", str(step_dict.get_int("progress"))) - step.add_child( - Node.bool("is_track_ticket", step_dict.get_bool("is_track_ticket")) - ) + step.add_child(Node.bool("is_track_ticket", step_dict.get_bool("is_track_ticket"))) step.set_attribute("sp_level", str(step_dict.get_int("sp_level"))) step.set_attribute("dp_level", str(step_dict.get_int("dp_level"))) - step.set_attribute( - "sp_mission_point", str(step_dict.get_int("sp_mission_point")) - ) - step.set_attribute( - "dp_mission_point", str(step_dict.get_int("dp_mission_point")) - ) - step.set_attribute( - "sp_dj_mission_level", str(step_dict.get_int("sp_dj_mission_level@")) - ) - step.set_attribute( - "dp_dj_mission_level", str(step_dict.get_int("dp_dj_mission_level@")) - ) - step.set_attribute( - "sp_clear_mission_level", str(step_dict.get_int("sp_clear_mission_level")) - ) - step.set_attribute( - "dp_clear_mission_level", str(step_dict.get_int("dp_clear_mission_level")) - ) - step.set_attribute( - "sp_dj_mission_clear", str(step_dict.get_int("sp_dj_mission_clear")) - ) - step.set_attribute( - "dp_dj_mission_clear", str(step_dict.get_int("dp_dj_mission_clear")) - ) - step.set_attribute( - "sp_clear_mission_clear", str(step_dict.get_int("sp_clear_mission_clear")) - ) - step.set_attribute( - "dp_clear_mission_clear", str(step_dict.get_int("dp_clear_mission_clear")) - ) + step.set_attribute("sp_mission_point", str(step_dict.get_int("sp_mission_point"))) + step.set_attribute("dp_mission_point", str(step_dict.get_int("dp_mission_point"))) + step.set_attribute("sp_dj_mission_level", str(step_dict.get_int("sp_dj_mission_level@"))) + step.set_attribute("dp_dj_mission_level", str(step_dict.get_int("dp_dj_mission_level@"))) + step.set_attribute("sp_clear_mission_level", str(step_dict.get_int("sp_clear_mission_level"))) + step.set_attribute("dp_clear_mission_level", str(step_dict.get_int("dp_clear_mission_level"))) + step.set_attribute("sp_dj_mission_clear", str(step_dict.get_int("sp_dj_mission_clear"))) + step.set_attribute("dp_dj_mission_clear", str(step_dict.get_int("dp_dj_mission_clear"))) + step.set_attribute("sp_clear_mission_clear", str(step_dict.get_int("sp_clear_mission_clear"))) + step.set_attribute("dp_clear_mission_clear", str(step_dict.get_int("dp_clear_mission_clear"))) step.set_attribute("sp_mplay", str(step_dict.get_int("sp_mplay"))) step.set_attribute("dp_mplay", str(step_dict.get_int("dp_mplay"))) step.set_attribute("tips_read_list", str(step_dict.get_int("tips_read_list"))) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -1849,36 +1677,24 @@ class IIDXRootage(IIDXCourse, IIDXBase): achievement_node.set_attribute("pack", "0") achievement_node.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() - achievement_node.set_attribute( - "pack", str(daily_played.get_int("pack_flg")) - ) - achievement_node.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievement_node.set_attribute("pack", str(daily_played.get_int("pack_flg"))) + achievement_node.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies - achievement_node.set_attribute( - "last_weekly", str(profile.get_int("last_weekly")) - ) + achievement_node.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) achievement_node.set_attribute("weekly_num", str(profile.get_int("weekly_num"))) # Prefecture visit flag achievement_node.set_attribute("visit_flg", str(profile.get_int("visit_flg"))) # Number of rivals beaten - achievement_node.set_attribute( - "rival_crush", str(profile.get_int("rival_crush")) - ) + achievement_node.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievement_node.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 20)) - ) + achievement_node.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 20))) # Track deller deller = Node.void("deller") @@ -1902,9 +1718,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): detail.set_attribute("course_id", str(rank.id)) detail.set_attribute("n_point", str(rank.data.get_int("normal_points"))) detail.set_attribute("h_point", str(rank.data.get_int("hyper_points"))) - detail.set_attribute( - "a_point", str(rank.data.get_int("another_points")) - ) + detail.set_attribute("a_point", str(rank.data.get_int("another_points"))) nostalgia = Node.void("nostalgia_open") root.add_child(nostalgia) @@ -1918,9 +1732,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -1972,20 +1784,12 @@ class IIDXRootage(IIDXCourse, IIDXBase): newprofile.replace_int("d_gauge_disp", int(request.attribute("d_gauge_disp"))) newprofile.replace_int("s_lane_brignt", int(request.attribute("s_lane_brignt"))) newprofile.replace_int("d_lane_brignt", int(request.attribute("d_lane_brignt"))) - newprofile.replace_int( - "s_camera_layout", int(request.attribute("s_camera_layout")) - ) - newprofile.replace_int( - "d_camera_layout", int(request.attribute("d_camera_layout")) - ) + newprofile.replace_int("s_camera_layout", int(request.attribute("s_camera_layout"))) + newprofile.replace_int("d_camera_layout", int(request.attribute("d_camera_layout"))) newprofile.replace_int("s_ghost_score", int(request.attribute("s_ghost_score"))) newprofile.replace_int("d_ghost_score", int(request.attribute("d_ghost_score"))) - newprofile.replace_int( - "s_tsujigiri_disp", int(request.attribute("s_tsujigiri_disp")) - ) - newprofile.replace_int( - "d_tsujigiri_disp", int(request.attribute("d_tsujigiri_disp")) - ) + newprofile.replace_int("s_tsujigiri_disp", int(request.attribute("s_tsujigiri_disp"))) + newprofile.replace_int("d_tsujigiri_disp", int(request.attribute("d_tsujigiri_disp"))) newprofile.replace_int("s_lift", int(request.attribute("s_lift"))) newprofile.replace_int("d_lift", int(request.attribute("d_lift"))) newprofile.replace_int("mode", int(request.attribute("mode"))) @@ -2014,15 +1818,9 @@ class IIDXRootage(IIDXCourse, IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -2046,9 +1844,7 @@ class IIDXRootage(IIDXCourse, IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Secret course expert point saving expert_point = request.child("expert_point") @@ -2112,22 +1908,14 @@ class IIDXRootage(IIDXCourse, IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -150,9 +137,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -387,9 +372,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): root = Node.void("IIDX24shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -412,9 +395,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return Node.void("IIDX24shop") @@ -434,9 +415,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -574,16 +553,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): root = Node.void("IIDX24music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -627,16 +597,12 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -644,10 +610,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -674,9 +637,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -767,19 +728,13 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} if not global_scores: all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -831,9 +786,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -857,10 +810,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -1324,9 +1274,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): used_secret_ids: List[int] = [] for c in secret_courses: if c["id"] in used_secret_ids: - raise Exception( - "Cannot have multiple secret courses with the same ID!" - ) + raise Exception("Cannot have multiple secret courses with the same ID!") elif c["id"] < 0 or c["id"] >= 20: raise Exception("Secret course ID is out of bounds!") else: @@ -1503,9 +1451,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1622,15 +1568,9 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 3))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 3))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 3))) # Favorites for folder in ["favorite1", "favorite2", "favorite3"]: @@ -1692,9 +1632,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): ) ), ) - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in achievements: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1766,21 +1704,11 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): qpro_secrete_dict = profile.get_dict("qpro_secret") qpro_secret = Node.void("qpro_secret") root.add_child(qpro_secret) - qpro_secret.add_child( - Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5)) - ) - qpro_secret.add_child( - Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5)) - ) - qpro_secret.add_child( - Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5)) - ) - qpro_secret.add_child( - Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5)) - ) + qpro_secret.add_child(Node.s64_array("head", qpro_secrete_dict.get_int_array("head", 5))) + qpro_secret.add_child(Node.s64_array("hair", qpro_secrete_dict.get_int_array("hair", 5))) + qpro_secret.add_child(Node.s64_array("face", qpro_secrete_dict.get_int_array("face", 5))) + qpro_secret.add_child(Node.s64_array("body", qpro_secrete_dict.get_int_array("body", 5))) + qpro_secret.add_child(Node.s64_array("hand", qpro_secrete_dict.get_int_array("hand", 5))) # Rivals rlist = Node.void("rlist") @@ -1861,9 +1789,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): [ courseid, # course ID coursechart, # course chart - self.db_to_game_status( - course.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(course.data.get_int("clear_status")), # course clear status course.data.get_int("pgnum"), # flashing great count course.data.get_int("gnum"), # great count ], @@ -1881,9 +1807,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): [ courseid, # course ID coursechart, # course chart - self.db_to_game_status( - course.data.get_int("clear_status") - ), # course clear status + self.db_to_game_status(course.data.get_int("clear_status")), # course clear status course.data.get_int("pgnum"), # flashing great count course.data.get_int("gnum"), # great count ], @@ -1918,20 +1842,14 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): ninja_rank_node = Node.void("ninja_rank") root.add_child(ninja_rank_node) ninja_rank_node.set_attribute("style", str(ninja_rank.id)) - ninja_rank_node.add_child( - Node.s32_array("rank", ninja_rank.data.get_int_array("rank", 13)) - ) - ninja_rank_node.add_child( - Node.s32_array("point", ninja_rank.data.get_int_array("point", 13)) - ) + ninja_rank_node.add_child(Node.s32_array("rank", ninja_rank.data.get_int_array("rank", 13))) + ninja_rank_node.add_child(Node.s32_array("point", ninja_rank.data.get_int_array("point", 13))) # SINOBUZ Den event event1_dict = profile.get_dict("event1") event1 = Node.void("event1") root.add_child(event1) - event1.set_attribute( - "last_select_map", str(event1_dict.get_int("last_select_map")) - ) + event1.set_attribute("last_select_map", str(event1_dict.get_int("last_select_map"))) event1.set_attribute("hold_rice", str(event1_dict.get_int("hold_rice"))) event1.set_attribute("tax_rice", str(event1_dict.get_int("tax_rice"))) event1.set_attribute("tips_list", str(event1_dict.get_int("tips_list"))) @@ -1943,32 +1861,14 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): map_data_node = Node.void("map_data") event1.add_child(map_data_node) map_data_node.set_attribute("map_id", str(map_data.id)) - map_data_node.set_attribute( - "play_num", str(map_data.data.get_int("play_num")) - ) - map_data_node.set_attribute( - "progress", str(map_data.data.get_int("progress")) - ) - map_data_node.set_attribute( - "battle_point", str(map_data.data.get_int("battle_point")) - ) - map_data_node.set_attribute( - "rice_point", str(map_data.data.get_int("rice_point")) - ) - map_data_node.set_attribute( - "is_clear", "1" if map_data.data.get_bool("is_clear") else "0" - ) - map_data_node.add_child( - Node.binary("ninjyutsu", map_data.data.get_bytes("ninjyutsu")) - ) - map_data_node.add_child( - Node.binary( - "map_card_damage", map_data.data.get_bytes("map_card_damage") - ) - ) - map_data_node.add_child( - Node.binary("map_card_clear", map_data.data.get_bytes("map_card_clear")) - ) + map_data_node.set_attribute("play_num", str(map_data.data.get_int("play_num"))) + map_data_node.set_attribute("progress", str(map_data.data.get_int("progress"))) + map_data_node.set_attribute("battle_point", str(map_data.data.get_int("battle_point"))) + map_data_node.set_attribute("rice_point", str(map_data.data.get_int("rice_point"))) + map_data_node.set_attribute("is_clear", "1" if map_data.data.get_bool("is_clear") else "0") + map_data_node.add_child(Node.binary("ninjyutsu", map_data.data.get_bytes("ninjyutsu"))) + map_data_node.add_child(Node.binary("map_card_damage", map_data.data.get_bytes("map_card_damage"))) + map_data_node.add_child(Node.binary("map_card_clear", map_data.data.get_bytes("map_card_clear"))) # Shichikenden event event2_dict = profile.get_dict("event2") @@ -1976,20 +1876,14 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): root.add_child(event2) event2.set_attribute("play_num", str(event2_dict.get_int("play_num"))) event2.set_attribute("chakra_point", str(event2_dict.get_int("chakra_point"))) - event2.set_attribute( - "last_select_ryuha", str(event2_dict.get_int("last_select_ryuha")) - ) + event2.set_attribute("last_select_ryuha", str(event2_dict.get_int("last_select_ryuha"))) event2.add_child( Node.binary( "last_select_dojo", event2_dict.get_bytes("last_select_dojo", b"\0" * 12), ) ) - event2.add_child( - Node.binary( - "enemy_damage", event2_dict.get_bytes("enemy_damage", b"\0" * 532) - ) - ) + event2.add_child(Node.binary("enemy_damage", event2_dict.get_bytes("enemy_damage", b"\0" * 532))) # OMES Data omes_dict = profile.get_dict("omes") @@ -2002,15 +1896,9 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): onemore_data.set_attribute("defeat_4", str(omes_dict.get_int("defeat_4"))) onemore_data.set_attribute("defeat_5", str(omes_dict.get_int("defeat_5"))) onemore_data.set_attribute("defeat_6", str(omes_dict.get_int("defeat_6"))) - onemore_data.set_attribute( - "challenge_num_n", str(omes_dict.get_int("challenge_num_n")) - ) - onemore_data.set_attribute( - "challenge_num_h", str(omes_dict.get_int("challenge_num_h")) - ) - onemore_data.set_attribute( - "challenge_num_a", str(omes_dict.get_int("challenge_num_a")) - ) + onemore_data.set_attribute("challenge_num_n", str(omes_dict.get_int("challenge_num_n"))) + onemore_data.set_attribute("challenge_num_h", str(omes_dict.get_int("challenge_num_h"))) + onemore_data.set_attribute("challenge_num_a", str(omes_dict.get_int("challenge_num_a"))) # If the user joined a particular shop, let the game know. if "shop_location" in profile: @@ -2030,18 +1918,14 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): root.add_child(step) step.set_attribute("enemy_damage", str(step_dict.get_int("enemy_damage"))) step.set_attribute("progress", str(step_dict.get_int("progress"))) - step.set_attribute( - "enemy_defeat_flg", str(step_dict.get_int("enemy_defeat_flg")) - ) + step.set_attribute("enemy_defeat_flg", str(step_dict.get_int("enemy_defeat_flg"))) step.set_attribute("sp_level", str(step_dict.get_int("sp_level"))) step.set_attribute("dp_level", str(step_dict.get_int("dp_level"))) step.set_attribute("sp_mplay", str(step_dict.get_int("sp_mplay"))) step.set_attribute("dp_mplay", str(step_dict.get_int("dp_mplay"))) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -2064,36 +1948,24 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): achievement_node.set_attribute("pack", "0") achievement_node.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() - achievement_node.set_attribute( - "pack", str(daily_played.get_int("pack_flg")) - ) - achievement_node.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievement_node.set_attribute("pack", str(daily_played.get_int("pack_flg"))) + achievement_node.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies - achievement_node.set_attribute( - "last_weekly", str(profile.get_int("last_weekly")) - ) + achievement_node.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) achievement_node.set_attribute("weekly_num", str(profile.get_int("weekly_num"))) # Prefecture visit flag achievement_node.set_attribute("visit_flg", str(profile.get_int("visit_flg"))) # Number of rivals beaten - achievement_node.set_attribute( - "rival_crush", str(profile.get_int("rival_crush")) - ) + achievement_node.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievement_node.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 10)) - ) + achievement_node.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 10))) # Track deller deller = Node.void("deller") @@ -2116,9 +1988,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): detail.set_attribute("course_id", str(rank.id)) detail.set_attribute("n_point", str(rank.data.get_int("normal_points"))) detail.set_attribute("h_point", str(rank.data.get_int("hyper_points"))) - detail.set_attribute( - "a_point", str(rank.data.get_int("another_points")) - ) + detail.set_attribute("a_point", str(rank.data.get_int("another_points"))) nostalgia = Node.void("nostalgia_open") root.add_child(nostalgia) @@ -2128,9 +1998,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): root.add_child(Node.void("bind_eaappli")) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -2206,15 +2074,9 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -2238,9 +2100,7 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Secret course expert point saving expert_point = request.child("expert_point") @@ -2304,22 +2164,14 @@ class IIDXSinobuz(IIDXCourse, IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -145,9 +132,7 @@ class IIDXSpada(IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -345,9 +330,7 @@ class IIDXSpada(IIDXBase): root = Node.void("IIDX21shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -371,9 +354,7 @@ class IIDXSpada(IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return root @@ -393,9 +374,7 @@ class IIDXSpada(IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -474,16 +453,7 @@ class IIDXSpada(IIDXBase): root = Node.void("IIDX21music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -527,16 +497,12 @@ class IIDXSpada(IIDXBase): continue userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -544,10 +510,7 @@ class IIDXSpada(IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -590,19 +553,13 @@ class IIDXSpada(IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} if not global_scores: all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -654,9 +611,7 @@ class IIDXSpada(IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -680,10 +635,7 @@ class IIDXSpada(IIDXBase): all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -831,9 +783,7 @@ class IIDXSpada(IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -1128,9 +1078,7 @@ class IIDXSpada(IIDXBase): best_clear_string = clear_map.get(best_clear, "NO PLAY") now_clear_string = clear_map.get(now_clear, "NO PLAY") # let's get the song info first - song = self.data.local.music.get_song( - self.game, self.music_version, music_id, self.game_to_db_chart(class_id) - ) + song = self.data.local.music.get_song(self.game, self.music_version, music_id, self.game_to_db_chart(class_id)) notecount = song.data.get("notecount", 0) # Construct the dictionary for the broadcast card_data = { @@ -1235,9 +1183,7 @@ class IIDXSpada(IIDXBase): join_shop.set_attribute("join_name", machine.name) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -1268,15 +1214,9 @@ class IIDXSpada(IIDXBase): secret.add_child(Node.s64_array("flg2", [-1, -1])) secret.add_child(Node.s64_array("flg3", [-1, -1])) else: - secret.add_child( - Node.s64_array("flg1", secret_dict.get_int_array("flg1", 2)) - ) - secret.add_child( - Node.s64_array("flg2", secret_dict.get_int_array("flg2", 2)) - ) - secret.add_child( - Node.s64_array("flg3", secret_dict.get_int_array("flg3", 2)) - ) + secret.add_child(Node.s64_array("flg1", secret_dict.get_int_array("flg1", 2))) + secret.add_child(Node.s64_array("flg2", secret_dict.get_int_array("flg2", 2))) + secret.add_child(Node.s64_array("flg3", secret_dict.get_int_array("flg3", 2))) # Tran medals and shit achievements = Node.void("achievements") @@ -1287,15 +1227,11 @@ class IIDXSpada(IIDXBase): achievements.set_attribute("pack", "0") achievements.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() achievements.set_attribute("pack", str(daily_played.get_int("pack_flg"))) - achievements.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievements.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies achievements.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) @@ -1308,9 +1244,7 @@ class IIDXSpada(IIDXBase): achievements.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievements.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 10)) - ) + achievements.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 10))) # User settings settings_dict = profile.get_dict("settings") @@ -1356,9 +1290,7 @@ class IIDXSpada(IIDXBase): ) ), ) - rankings = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + rankings = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in rankings: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1483,9 +1415,7 @@ class IIDXSpada(IIDXBase): step.add_child( Node.binary( "album", - step_dict.get_bytes( - "album", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - ), + step_dict.get_bytes("album", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), ) ) @@ -1614,13 +1544,9 @@ class IIDXSpada(IIDXBase): "boss6_damage", ]: boss1.set_attribute(attr, str(boss1_dict.get_int(attr))) - boss1.add_child( - Node.s32_array("level", boss1_dict.get_int_array("level", 7)) - ) + boss1.add_child(Node.s32_array("level", boss1_dict.get_int_array("level", 7))) if "durability" in boss1_dict: - boss1.add_child( - Node.binary("durability", boss1_dict.get_bytes("durability")) - ) + boss1.add_child(Node.binary("durability", boss1_dict.get_bytes("durability"))) # Events copied from Tricoro, but might still allow unlocks in this version? gakuen = Node.void("gakuen") @@ -1646,9 +1572,7 @@ class IIDXSpada(IIDXBase): root.add_child(Node.void("bind_eaappli")) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -1720,15 +1644,9 @@ class IIDXSpada(IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: @@ -1752,9 +1670,7 @@ class IIDXSpada(IIDXBase): # Deller saving deller = request.child("deller") if deller is not None: - newprofile.replace_int( - "deller", newprofile.get_int("deller") + int(deller.attribute("deller")) - ) + newprofile.replace_int("deller", newprofile.get_int("deller") + int(deller.attribute("deller"))) # Favorites saving favorite = request.child("favorite") @@ -1769,17 +1685,13 @@ class IIDXSpada(IIDXBase): for i in range(self.FAVORITE_LIST_LENGTH): singles.append( { - "id": struct.unpack( - " List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert dailies into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "daily_charts", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "daily_charts", "daily"): # Generate a new list of three dailies. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = list( - set( - [ - song.id - for song in data.local.music.get_all_songs( - cls.game, cls.version - ) - ] - ) - ) + all_songs = list(set([song.id for song in data.local.music.get_all_songs(cls.game, cls.version)])) if len(all_songs) >= 3: daily_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -137,9 +124,7 @@ class IIDXTricoro(IIDXBase): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "daily_charts", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "daily_charts", "daily") return events @classmethod @@ -324,9 +309,7 @@ class IIDXTricoro(IIDXBase): root = Node.void("shop") machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -350,9 +333,7 @@ class IIDXTricoro(IIDXBase): course.replace_int("music_2", request.child_value("music_2")) course.replace_int("music_3", request.child_value("music_3")) course.replace_bool("valid", request.child_value("valid")) - self.data.local.machine.put_settings( - machine.arcade, self.game, self.music_version, "shop_course", course - ) + self.data.local.machine.put_settings(machine.arcade, self.game, self.music_version, "shop_course", course) return root @@ -372,9 +353,7 @@ class IIDXTricoro(IIDXBase): machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - course = self.data.local.machine.get_settings( - machine.arcade, self.game, self.music_version, "shop_course" - ) + course = self.data.local.machine.get_settings(machine.arcade, self.game, self.music_version, "shop_course") else: course = None @@ -453,16 +432,7 @@ class IIDXTricoro(IIDXBase): root = Node.void("music") attempts = self.get_clear_rates() - all_songs = list( - set( - [ - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - ] - ) - ) + all_songs = list(set([song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)])) for song in all_songs: clears = [] fcs = [] @@ -507,16 +477,12 @@ class IIDXTricoro(IIDXBase): userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) # Grab score data for user/rival scoredata = self.make_score_struct( scores, - self.CLEAR_TYPE_SINGLE - if cltype == self.GAME_CLTYPE_SINGLE - else self.CLEAR_TYPE_DOUBLE, + self.CLEAR_TYPE_SINGLE if cltype == self.GAME_CLTYPE_SINGLE else self.CLEAR_TYPE_DOUBLE, rivalid, ) for s in scoredata: @@ -524,10 +490,7 @@ class IIDXTricoro(IIDXBase): # Grab most played for user/rival most_played = [ - play[0] - for play in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) + play[0] for play in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20) ] if len(most_played) < 20: most_played.extend([0] * (20 - len(most_played))) @@ -570,19 +533,13 @@ class IIDXTricoro(IIDXBase): key=lambda s: (s[1].points, s[1].timestamp), reverse=True, ) - all_players = { - uid: prof - for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores]) - } + all_players = {uid: prof for (uid, prof) in self.get_any_profiles([s[0] for s in all_scores])} if not global_scores: all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -633,9 +590,7 @@ class IIDXTricoro(IIDXBase): # Shop ranking shopdata = Node.void("shopdata") root.add_child(shopdata) - shopdata.set_attribute( - "rank", "-1" if oldindex is None else str(oldindex + 1) - ) + shopdata.set_attribute("rank", "-1" if oldindex is None else str(oldindex + 1)) # Grab the rank of some other players on this song ranklist = Node.void("ranklist") @@ -659,10 +614,7 @@ class IIDXTricoro(IIDXBase): all_scores = [ score for score in all_scores - if ( - score[0] == userid - or self.user_joined_arcade(machine, all_players[score[0]]) - ) + if (score[0] == userid or self.user_joined_arcade(machine, all_players[score[0]])) ] # Find our actual index @@ -809,9 +761,7 @@ class IIDXTricoro(IIDXBase): if userid is not None: # Try to look up previous ghost for user - my_score = self.data.remote.music.get_score( - self.game, self.music_version, userid, musicid, chart - ) + my_score = self.data.remote.music.get_score(self.game, self.music_version, userid, musicid, chart) if my_score is not None: mydata = Node.binary("mydata", my_score.data.get_bytes("ghost")) mydata.set_attribute("score", str(my_score.points)) @@ -1114,9 +1064,7 @@ class IIDXTricoro(IIDXBase): ) ), ) - rankings = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + rankings = self.data.local.user.get_achievements(self.game, self.version, userid) for rank in rankings: if rank.type == self.DAN_RANKING_SINGLE: grade.add_child( @@ -1274,18 +1222,12 @@ class IIDXTricoro(IIDXBase): step.set_attribute("dp_mplay", str(step_dict.get_int("dp_mplay"))) step.set_attribute("review", str(step_dict.get_int("review"))) if "stamp" in step_dict: - step.add_child( - Node.binary("stamp", step_dict.get_bytes("stamp", bytes([0] * 36))) - ) + step.add_child(Node.binary("stamp", step_dict.get_bytes("stamp", bytes([0] * 36)))) if "help" in step_dict: - step.add_child( - Node.binary("help", step_dict.get_bytes("help", bytes([0] * 6))) - ) + step.add_child(Node.binary("help", step_dict.get_bytes("help", bytes([0] * 6)))) # Daily recommendations - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "dailies" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "dailies") if entry is not None: packinfo = Node.void("packinfo") root.add_child(packinfo) @@ -1328,15 +1270,11 @@ class IIDXTricoro(IIDXBase): achievements.set_attribute("pack", "0") achievements.set_attribute("pack_comp", "0") else: - daily_played = self.data.local.user.get_achievement( - self.game, self.version, userid, pack_id, "daily" - ) + daily_played = self.data.local.user.get_achievement(self.game, self.version, userid, pack_id, "daily") if daily_played is None: daily_played = ValidatedDict() achievements.set_attribute("pack", str(daily_played.get_int("pack_flg"))) - achievements.set_attribute( - "pack_comp", str(daily_played.get_int("pack_comp")) - ) + achievements.set_attribute("pack_comp", str(daily_played.get_int("pack_comp"))) # Weeklies achievements.set_attribute("last_weekly", str(profile.get_int("last_weekly"))) @@ -1349,9 +1287,7 @@ class IIDXTricoro(IIDXBase): achievements.set_attribute("rival_crush", str(profile.get_int("rival_crush"))) # Tran medals - achievements.add_child( - Node.s64_array("trophy", profile.get_int_array("trophy", 10)) - ) + achievements.add_child(Node.s64_array("trophy", profile.get_int_array("trophy", 10))) # Link5 data if "link5" in profile: @@ -1403,9 +1339,7 @@ class IIDXTricoro(IIDXBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() play_stats = self.get_play_statistics(userid) @@ -1459,15 +1393,9 @@ class IIDXTricoro(IIDXBase): # Basic achievements achievements = request.child("achievements") if achievements is not None: - newprofile.replace_int( - "visit_flg", int(achievements.attribute("visit_flg")) - ) - newprofile.replace_int( - "last_weekly", int(achievements.attribute("last_weekly")) - ) - newprofile.replace_int( - "weekly_num", int(achievements.attribute("weekly_num")) - ) + newprofile.replace_int("visit_flg", int(achievements.attribute("visit_flg"))) + newprofile.replace_int("last_weekly", int(achievements.attribute("last_weekly"))) + newprofile.replace_int("weekly_num", int(achievements.attribute("weekly_num"))) pack_id = int(achievements.attribute("pack_id")) if pack_id > 0: diff --git a/bemani/backend/jubeat/base.py b/bemani/backend/jubeat/base.py index 49f6ba7..1f17cb4 100644 --- a/bemani/backend/jubeat/base.py +++ b/bemani/backend/jubeat/base.py @@ -30,13 +30,9 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): PLAY_MEDAL_FAILED: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_FAILED PLAY_MEDAL_CLEARED: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_CLEARED - PLAY_MEDAL_NEARLY_FULL_COMBO: Final[ - int - ] = DBConstants.JUBEAT_PLAY_MEDAL_NEARLY_FULL_COMBO + PLAY_MEDAL_NEARLY_FULL_COMBO: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_NEARLY_FULL_COMBO PLAY_MEDAL_FULL_COMBO: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_FULL_COMBO - PLAY_MEDAL_NEARLY_EXCELLENT: Final[ - int - ] = DBConstants.JUBEAT_PLAY_MEDAL_NEARLY_EXCELLENT + PLAY_MEDAL_NEARLY_EXCELLENT: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_NEARLY_EXCELLENT PLAY_MEDAL_EXCELLENT: Final[int] = DBConstants.JUBEAT_PLAY_MEDAL_EXCELLENT CHART_TYPE_BASIC: Final[int] = 0 @@ -86,18 +82,14 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("gametop") - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: """ Base handler for a score list. Given a userid, profile and a score list, return a Node representing a score list. Should be overridden. """ return Node.void("gametop") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -159,9 +151,7 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): return self.format_profile(userid, profile) - def get_scores_by_extid( - self, extid: Optional[int], partition: int, total_partitions: int - ) -> Optional[Node]: + def get_scores_by_extid(self, extid: Optional[int], partition: int, total_partitions: int) -> Optional[Node]: """ Given an ExtID, return a formatted score node. Similar rationale to get_profile_by_refid. Note that this takes into account the game's @@ -183,9 +173,7 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # We fetch all scores on the first partition and then divy up # the scores across total_partitions fetches. If it is small # enough, we don't bother. - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: # We will want to fetch the remaining scores that were in our # cache. @@ -205,9 +193,7 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # last iteration. if partition == total_partitions: if rest: - raise Exception( - "Logic error, should not have gotten additional scores to cache on last iteration!" - ) + raise Exception("Logic error, should not have gotten additional scores to cache on last iteration!") self.cache.delete(cache_key) else: self.cache.set(cache_key, rest, timeout=60) @@ -339,10 +325,7 @@ class JubeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): for gameitem in gameitems: if gameitem.type == "emblem": - if ( - gameitem.data.get_int("layer") == 2 - and gameitem.data.get_int("rarity") == 1 - ): + if gameitem.data.get_int("layer") == 2 and gameitem.data.get_int("rarity") == 1: default_main.add(gameitem.id) return default_main diff --git a/bemani/backend/jubeat/clan.py b/bemani/backend/jubeat/clan.py index 4163d41..284695f 100644 --- a/bemani/backend/jubeat/clan.py +++ b/bemani/backend/jubeat/clan.py @@ -83,16 +83,12 @@ class JubeatClan( return JubeatQubell(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert daily FC challenges into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. Skip a particular song range since these are all a single song ID. # Jubeat Clan has an unlock event where you have to play different charts for the same song, and the charts are # loaded in based on the cabinet's prefecture. So, no matter where you are, you will only see one song within this @@ -129,9 +125,7 @@ class JubeatClan( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") return events @classmethod @@ -1098,36 +1092,21 @@ class JubeatClan( valid_courses: Set[int] = set() for course in self.__get_course_list(): if course["id"] < 1: - raise Exception( - f"Invalid course ID {course['id']} found in course list!" - ) + raise Exception(f"Invalid course ID {course['id']} found in course list!") if course["id"] in valid_courses: raise Exception(f"Duplicate ID {course['id']} found in course list!") - if ( - course["clear_type"] == self.COURSE_CLEAR_HAZARD - and "hazard_type" not in course - ): + if course["clear_type"] == self.COURSE_CLEAR_HAZARD and "hazard_type" not in course: raise Exception(f"Need 'hazard_type' set in course {course['id']}!") - if ( - course["course_type"] == self.COURSE_TYPE_TIME_BASED - and "end_time" not in course - ): + if course["course_type"] == self.COURSE_TYPE_TIME_BASED and "end_time" not in course: raise Exception(f"Need 'end_time' set in course {course['id']}!") if ( - course["clear_type"] - in [self.COURSE_CLEAR_SCORE, self.COURSE_CLEAR_COMBINED_SCORE] + course["clear_type"] in [self.COURSE_CLEAR_SCORE, self.COURSE_CLEAR_COMBINED_SCORE] and "score" not in course ): raise Exception(f"Need 'score' set in course {course['id']}!") - if ( - course["clear_type"] == self.COURSE_CLEAR_SCORE - and course["score"] > 1000000 - ): + if course["clear_type"] == self.COURSE_CLEAR_SCORE and course["score"] > 1000000: raise Exception(f"Invalid per-coure score in course {course['id']}!") - if ( - course["clear_type"] == self.COURSE_CLEAR_COMBINED_SCORE - and course["score"] <= 1000000 - ): + if course["clear_type"] == self.COURSE_CLEAR_COMBINED_SCORE and course["score"] <= 1000000: raise Exception(f"Invalid combined score in course {course['id']}!") valid_courses.add(course["id"]) @@ -1139,11 +1118,7 @@ class JubeatClan( clan_course.set_attribute("id", str(course["id"])) clan_course.set_attribute("course_type", str(course["course_type"])) clan_course.add_child(Node.s32("difficulty", course["difficulty"])) - clan_course.add_child( - Node.u64( - "etime", (course["end_time"] if "end_time" in course else 0) * 1000 - ) - ) + clan_course.add_child(Node.u64("etime", (course["end_time"] if "end_time" in course else 0) * 1000)) clan_course.add_child(Node.string("name", course["name"])) # List of included songs @@ -1169,9 +1144,7 @@ class JubeatClan( clan_course.add_child(clear) ex_option = Node.void("ex_option") clear.add_child(ex_option) - ex_option.add_child( - Node.bool("is_hard", course["hard"] if "hard" in course else False) - ) + ex_option.add_child(Node.bool("is_hard", course["hard"] if "hard" in course else False)) ex_option.add_child( Node.s32( "hazard_type", @@ -1179,9 +1152,7 @@ class JubeatClan( ) ) clear.set_attribute("type", str(course["clear_type"])) - clear.add_child( - Node.s32("score", course["score"] if "score" in course else 0) - ) + clear.add_child(Node.s32("score", course["score"] if "score" in course else 0)) reward_list = Node.void("reward_list") clear.add_child(reward_list) @@ -1404,9 +1375,7 @@ class JubeatClan( # Grab unlock progress item = player.child("item") if item is not None: - owned_emblems = self.calculate_owned_items( - item.child_value("emblem_list") - ) + owned_emblems = self.calculate_owned_items(item.child_value("emblem_list")) for index in owned_emblems: self.data.local.user.put_achievement( self.game, @@ -1443,9 +1412,7 @@ class JubeatClan( return Node.void("gameend") - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -1518,24 +1485,12 @@ class JubeatClan( playdata.add_child(musicdata) musicdata.set_attribute("music_id", scoreid) - musicdata.add_child( - Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("score", scoredata.get_int_array("points", 3)) - ) - musicdata.add_child( - Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3)) - ) + musicdata.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3))) + musicdata.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3))) + musicdata.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3))) + musicdata.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3))) + musicdata.add_child(Node.s32_array("score", scoredata.get_int_array("points", 3))) + musicdata.add_child(Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3))) for i, ghost in enumerate(scoredata.get("ghost", [None, None, None])): if ghost is None: @@ -1557,9 +1512,7 @@ class JubeatClan( force_unlock = game_config.get_bool("force_song_unlock") # Calculate all of our achievement-backed entities. - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() event_completion: Dict[int, bool] = {} @@ -1567,9 +1520,7 @@ class JubeatClan( owned_emblems: Set[int] = set() for achievement in achievements: if achievement.type == "event": - event_completion[achievement.id] = achievement.data.get_bool( - "is_completed" - ) + event_completion[achievement.id] = achievement.data.get_bool("is_completed") elif achievement.type == "course": course_completion[achievement.id] = achievement.data elif achievement.type == "emblem": @@ -1610,12 +1561,8 @@ class JubeatClan( info.add_child(Node.s32("match_cnt", profile.get_int("match_cnt"))) info.add_child(Node.s32("beat_cnt", profile.get_int("beat_cnt"))) info.add_child(Node.s32("mynews_cnt", profile.get_int("mynews_cnt"))) - info.add_child( - Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points")) - ) - info.add_child( - Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played")) - ) + info.add_child(Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points"))) + info.add_child(Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -1665,68 +1612,30 @@ class JubeatClan( # Secret unlocks item = Node.void("item") player.add_child(item) - item.add_child( - Node.s32_array( - "music_list", profile.get_int_array("music_list", 64, [-1] * 64) - ) - ) + item.add_child(Node.s32_array("music_list", profile.get_int_array("music_list", 64, [-1] * 64))) item.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_songs, 64), - ) - ) - item.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "title_list", profile.get_int_array("title_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96)) - ) - item.add_child( - Node.s32_array( - "commu_list", profile.get_int_array("commu_list", 16, [-1] * 16) + ([-1] * 64) if force_unlock else self.create_owned_items(owned_songs, 64), ) ) + item.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("title_list", profile.get_int_array("title_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96))) + item.add_child(Node.s32_array("commu_list", profile.get_int_array("commu_list", 16, [-1] * 16))) new = Node.void("new") item.add_child(new) new.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_secrets, 64), - ) - ) - new.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16) - ) - ) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16) + ([-1] * 64) if force_unlock else self.create_owned_items(owned_secrets, 64), ) ) + new.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16))) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16))) # Add rivals to profile. rivallist = Node.void("rivallist") @@ -1765,9 +1674,7 @@ class JubeatClan( lab_edit_seq.set_attribute("count", "0") # Full combo challenge - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -1826,11 +1733,7 @@ class JubeatClan( state = 0x0 state |= self.EVENT_STATUS_OPEN if eventdata["enabled"] else 0 - state |= ( - self.EVENT_STATUS_COMPLETE - if event_completion.get(eventid, False) - else 0 - ) + state |= self.EVENT_STATUS_COMPLETE if event_completion.get(eventid, False) else 0 event.add_child(Node.u8("state", state)) # JBox stuff @@ -1900,9 +1803,7 @@ class JubeatClan( bestentry.replace_int("songid", achievement.id) bestentry.replace_int("chart", chart) jubeat_entries.append(bestentry) - jubeat_entries = sorted( - jubeat_entries, key=lambda entry: entry.get_int("value"), reverse=True - ) + jubeat_entries = sorted(jubeat_entries, key=lambda entry: entry.get_int("value"), reverse=True) # Now, give the game the list. for i, entry in enumerate(jubeat_entries): @@ -1916,9 +1817,7 @@ class JubeatClan( target_music.add_child(Node.s8("seq", entry.get_int("chart"))) target_music.add_child(Node.s32("score", entry.get_int("score"))) target_music.add_child(Node.s32("value", entry.get_int("value"))) - target_music.add_child( - Node.bool("is_hard_mode", entry.get_bool("hard_mode")) - ) + target_music.add_child(Node.bool("is_hard_mode", entry.get_bool("hard_mode"))) # Team stuff team = Node.void("team") @@ -1964,9 +1863,7 @@ class JubeatClan( status = 0 status |= self.COURSE_STATUS_SEEN if status_dict.get_bool("seen") else 0 status |= self.COURSE_STATUS_PLAYED if status_dict.get_bool("played") else 0 - status |= ( - self.COURSE_STATUS_CLEARED if status_dict.get_bool("cleared") else 0 - ) + status |= self.COURSE_STATUS_CLEARED if status_dict.get_bool("cleared") else 0 clan_course = Node.void("clan_course") clan_course_list.add_child(clan_course) @@ -2051,9 +1948,7 @@ class JubeatClan( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -2092,12 +1987,8 @@ class JubeatClan( newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) - newprofile.replace_int( - "bonus_tune_points", info.child_value("bonus_tune_points") - ) - newprofile.replace_bool( - "is_bonus_tune_played", info.child_value("is_bonus_tune_played") - ) + newprofile.replace_int("bonus_tune_points", info.child_value("bonus_tune_points")) + newprofile.replace_bool("is_bonus_tune_played", info.child_value("is_bonus_tune_played")) # Grab last settings lastnode = player.child("last") @@ -2122,30 +2013,16 @@ class JubeatClan( # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "music_list", 64, item.child_value("music_list") - ) - newprofile.replace_int_array( - "theme_list", 16, item.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list", 16, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "title_list", 160, item.child_value("title_list") - ) - newprofile.replace_int_array( - "parts_list", 160, item.child_value("parts_list") - ) - newprofile.replace_int_array( - "commu_list", 16, item.child_value("commu_list") - ) + newprofile.replace_int_array("music_list", 64, item.child_value("music_list")) + newprofile.replace_int_array("theme_list", 16, item.child_value("theme_list")) + newprofile.replace_int_array("marker_list", 16, item.child_value("marker_list")) + newprofile.replace_int_array("title_list", 160, item.child_value("title_list")) + newprofile.replace_int_array("parts_list", 160, item.child_value("parts_list")) + newprofile.replace_int_array("commu_list", 16, item.child_value("commu_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -2169,18 +2046,12 @@ class JubeatClan( newitem = item.child("new") if newitem is not None: - newprofile.replace_int_array( - "theme_list_new", 16, newitem.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list_new", 16, newitem.child_value("marker_list") - ) + newprofile.replace_int_array("theme_list_new", 16, newitem.child_value("theme_list")) + newprofile.replace_int_array("marker_list_new", 16, newitem.child_value("marker_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_secrets = self.calculate_owned_items( - newitem.child_value("secret_list") - ) + owned_secrets = self.calculate_owned_items(newitem.child_value("secret_list")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -2375,9 +2246,7 @@ class JubeatClan( if flags & bit > 0: medal = max(medal, mapping[bit]) - self.update_score( - userid, timestamp, songid, chart, points, medal, combo, ghost, stats - ) + self.update_score(userid, timestamp, songid, chart, points, medal, combo, ghost, stats) # Born stuff born = player.child("born") @@ -2458,9 +2327,7 @@ class JubeatClan( oldcourse = ValidatedDict() oldcourse.replace_bool("seen", oldcourse.get_bool("seen") or is_seen) - oldcourse.replace_bool( - "played", oldcourse.get_bool("played") or is_played - ) + oldcourse.replace_bool("played", oldcourse.get_bool("played") or is_played) # Save it as an achievement self.data.local.user.put_achievement( diff --git a/bemani/backend/jubeat/festo.py b/bemani/backend/jubeat/festo.py index 5753171..ed76e38 100644 --- a/bemani/backend/jubeat/festo.py +++ b/bemani/backend/jubeat/festo.py @@ -143,22 +143,15 @@ class JubeatFesto( }[db_chart] @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert daily FC challenges into the DB. """ events: List[Tuple[str, Dict[str, Any]]] = [] - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if len(all_songs) >= 2: daily_songs = random.sample(all_songs, 2) data.local.game.put_time_sensitive_settings( @@ -184,12 +177,8 @@ class JubeatFesto( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) - if data.local.network.should_schedule( - cls.game, cls.version, "random_course", "daily" - ): + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") + if data.local.network.should_schedule(cls.game, cls.version, "random_course", "daily"): # Generate a new list of three random songs for random course mode. start_time, end_time = data.local.network.get_schedule_duration("daily") @@ -216,11 +205,7 @@ class JubeatFesto( cls.CHART_TYPE_HARD_EXTREME: cls.CHART_TYPE_EXTREME, }[chart] - all_tens = [ - song - for song in data.local.music.get_all_songs(cls.game, cls.version) - if is_ten(song) - ] + all_tens = [song for song in data.local.music.get_all_songs(cls.game, cls.version) if is_ten(song)] if len(all_tens) >= 3: course_songs = random.sample(all_tens, 3) data.local.game.put_time_sensitive_settings( @@ -266,9 +251,7 @@ class JubeatFesto( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "random_course", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "random_course", "daily") return events @classmethod @@ -324,9 +307,7 @@ class JubeatFesto( # If it is available, then grab the random course. If we haven't generated that course, then # just don't bother trying to create it. - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "random_course" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "random_course") random_course: List[Dict[str, Any]] = [] if entry is not None: @@ -521,9 +502,7 @@ class JubeatFesto( "music": [ [ ( - 70000057 - if dataver < 2019062100 - else (90000079 if dataver < 2022021600 else 20000031), + 70000057 if dataver < 2019062100 else (90000079 if dataver < 2022021600 else 20000031), 0, ), (60000100, 0), @@ -543,9 +522,7 @@ class JubeatFesto( "music": [ [ ( - 80000020 - if dataver < 2019062100 - else (90000082 if dataver < 2022021600 else 60000092), + 80000020 if dataver < 2019062100 else (90000082 if dataver < 2022021600 else 60000092), 0, ), (90000031, 0), @@ -556,9 +533,7 @@ class JubeatFesto( 80000034 if dataver < 2020062900 else ( - 30000108 - if dataver < 2020091300 - else (40000107 if dataver < 2021020100 else 30000004) + 30000108 if dataver < 2020091300 else (40000107 if dataver < 2021020100 else 30000004) ), 0, ), @@ -579,9 +554,7 @@ class JubeatFesto( "music": [ [ ( - 70000148 - if dataver < 2020021900 - else (90000040 if dataver < 2021081600 else 80000097), + 70000148 if dataver < 2020021900 else (90000040 if dataver < 2021081600 else 80000097), 0, ), (50000296 if dataver < 2021081600 else 90000029, 0), @@ -665,9 +638,7 @@ class JubeatFesto( [ (50000242, 0), ( - 80000034 - if dataver < 2020063000 - else (90000079 if dataver < 2022021600 else 50000277), + 80000034 if dataver < 2020063000 else (90000079 if dataver < 2022021600 else 50000277), 1, ), (90000037 if dataver < 2021081600 else 50000294, 1), @@ -675,9 +646,7 @@ class JubeatFesto( [(50000260, 1), (50000261, 1)], [ ( - 70000085 - if dataver < 2019062100 - else (90000081 if dataver < 2022021600 else 90000143), + 70000085 if dataver < 2019062100 else (90000081 if dataver < 2022021600 else 90000143), 1, ), ], @@ -695,9 +664,7 @@ class JubeatFesto( (20000111 if dataver < 2019062100 else 90000034, 1), (90000037 if dataver < 2021081600 else 90000107, 1), ( - 70000131 - if dataver < 2019111800 - else (90000042 if dataver < 2021081600 else 90000140), + 70000131 if dataver < 2019111800 else (90000042 if dataver < 2021081600 else 90000140), 1, ), ], @@ -1753,9 +1720,7 @@ class JubeatFesto( game_config = self.get_game_config() konami_logo_50th = Node.void("konami_logo_50th") info.add_child(konami_logo_50th) - konami_logo_50th.add_child( - Node.bool("is_available", game_config.get_bool("50th_anniversary")) - ) + konami_logo_50th.add_child(Node.bool("is_available", game_config.get_bool("50th_anniversary"))) expert_option = Node.void("expert_option") info.add_child(expert_option) @@ -1780,36 +1745,21 @@ class JubeatFesto( dataver = self.model.version or 2022052400 for course in self.__get_course_list(): if course["id"] < 1: - raise Exception( - f"Invalid course ID {course['id']} found in course list!" - ) + raise Exception(f"Invalid course ID {course['id']} found in course list!") if course["id"] in valid_courses: raise Exception(f"Duplicate ID {course['id']} found in course list!") - if ( - course["clear_type"] == self.COURSE_CLEAR_HAZARD - and "hazard_type" not in course - ): + if course["clear_type"] == self.COURSE_CLEAR_HAZARD and "hazard_type" not in course: raise Exception(f"Need 'hazard_type' set in course {course['id']}!") - if ( - course["course_type"] == self.COURSE_TYPE_TIME_BASED - and "end_time" not in course - ): + if course["course_type"] == self.COURSE_TYPE_TIME_BASED and "end_time" not in course: raise Exception(f"Need 'end_time' set in course {course['id']}!") if ( - course["clear_type"] - in [self.COURSE_CLEAR_SCORE, self.COURSE_CLEAR_COMBINED_SCORE] + course["clear_type"] in [self.COURSE_CLEAR_SCORE, self.COURSE_CLEAR_COMBINED_SCORE] and "score" not in course ): raise Exception(f"Need 'score' set in course {course['id']}!") - if ( - course["clear_type"] == self.COURSE_CLEAR_SCORE - and course["score"] > 1000000 - ): + if course["clear_type"] == self.COURSE_CLEAR_SCORE and course["score"] > 1000000: raise Exception(f"Invalid per-coure score in course {course['id']}!") - if ( - course["clear_type"] == self.COURSE_CLEAR_COMBINED_SCORE - and course["score"] <= 1000000 - ): + if course["clear_type"] == self.COURSE_CLEAR_COMBINED_SCORE and course["score"] <= 1000000: raise Exception(f"Invalid combined score in course {course['id']}!") valid_courses.add(course["id"]) @@ -1821,11 +1771,7 @@ class JubeatFesto( clan_course.set_attribute("id", str(course["id"])) clan_course.set_attribute("course_type", str(course["course_type"])) clan_course.add_child(Node.s32("difficulty", course["difficulty"])) - clan_course.add_child( - Node.u64( - "etime", (course["end_time"] if "end_time" in course else 0) * 1000 - ) - ) + clan_course.add_child(Node.u64("etime", (course["end_time"] if "end_time" in course else 0) * 1000)) clan_course.add_child(Node.string("name", course["name"])) # List of included songs @@ -1851,9 +1797,7 @@ class JubeatFesto( clan_course.add_child(clear) ex_option = Node.void("ex_option") clear.add_child(ex_option) - ex_option.add_child( - Node.bool("is_hard", course["hard"] if "hard" in course else False) - ) + ex_option.add_child(Node.bool("is_hard", course["hard"] if "hard" in course else False)) ex_option.add_child( Node.s32( "hazard_type", @@ -1861,9 +1805,7 @@ class JubeatFesto( ) ) clear.set_attribute("type", str(course["clear_type"])) - clear.add_child( - Node.s32("score", course["score"] if "score" in course else 0) - ) + clear.add_child(Node.s32("score", course["score"] if "score" in course else 0)) reward_list = Node.void("reward_list") clear.add_child(reward_list) @@ -1965,9 +1907,7 @@ class JubeatFesto( if game_config.get_bool("festo_dungeon"): festo_dungeon = Node.void("festo_dungeon") info.add_child(festo_dungeon) - festo_dungeon.add_child( - Node.u64("etime", (Time.now() + Time.SECONDS_IN_WEEK) * 1000) - ) + festo_dungeon.add_child(Node.u64("etime", (Time.now() + Time.SECONDS_IN_WEEK) * 1000)) # Unsupported team_battle nodes. info.add_child(Node.void("team_battle")) @@ -2205,9 +2145,7 @@ class JubeatFesto( # Grab unlock progress item = player.child("item") if item is not None: - owned_emblems = self.calculate_owned_items( - item.child_value("emblem_list") - ) + owned_emblems = self.calculate_owned_items(item.child_value("emblem_list")) for index in owned_emblems: self.data.local.user.put_achievement( self.game, @@ -2244,9 +2182,7 @@ class JubeatFesto( return Node.void("gameend") - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -2324,43 +2260,15 @@ class JubeatFesto( normalnode = Node.void("normal") musicdata.add_child(normalnode) - normalnode.add_child( - Node.s32_array( - "play_cnt", scoredata.get_int_array("normal_play_cnt", 3) - ) - ) - normalnode.add_child( - Node.s32_array( - "clear_cnt", scoredata.get_int_array("normal_clear_cnt", 3) - ) - ) - normalnode.add_child( - Node.s32_array( - "fc_cnt", scoredata.get_int_array("normal_fc_cnt", 3) - ) - ) - normalnode.add_child( - Node.s32_array( - "ex_cnt", scoredata.get_int_array("normal_ex_cnt", 3) - ) - ) - normalnode.add_child( - Node.s32_array("score", scoredata.get_int_array("normal_points", 3)) - ) - normalnode.add_child( - Node.s8_array( - "clear", scoredata.get_int_array("normal_clear_flags", 3) - ) - ) - normalnode.add_child( - Node.s32_array( - "music_rate", scoredata.get_int_array("normal_music_rate", 3) - ) - ) + normalnode.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("normal_play_cnt", 3))) + normalnode.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("normal_clear_cnt", 3))) + normalnode.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("normal_fc_cnt", 3))) + normalnode.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("normal_ex_cnt", 3))) + normalnode.add_child(Node.s32_array("score", scoredata.get_int_array("normal_points", 3))) + normalnode.add_child(Node.s8_array("clear", scoredata.get_int_array("normal_clear_flags", 3))) + normalnode.add_child(Node.s32_array("music_rate", scoredata.get_int_array("normal_music_rate", 3))) - for i, ghost in enumerate( - scoredata.get("normal_ghost", [None, None, None]) - ): + for i, ghost in enumerate(scoredata.get("normal_ghost", [None, None, None])): if ghost is None: continue @@ -2372,39 +2280,15 @@ class JubeatFesto( hardnode = Node.void("hard") musicdata.add_child(hardnode) - hardnode.add_child( - Node.s32_array( - "play_cnt", scoredata.get_int_array("hard_play_cnt", 3) - ) - ) - hardnode.add_child( - Node.s32_array( - "clear_cnt", scoredata.get_int_array("hard_clear_cnt", 3) - ) - ) - hardnode.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("hard_fc_cnt", 3)) - ) - hardnode.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("hard_ex_cnt", 3)) - ) - hardnode.add_child( - Node.s32_array("score", scoredata.get_int_array("hard_points", 3)) - ) - hardnode.add_child( - Node.s8_array( - "clear", scoredata.get_int_array("hard_clear_flags", 3) - ) - ) - hardnode.add_child( - Node.s32_array( - "music_rate", scoredata.get_int_array("hard_music_rate", 3) - ) - ) + hardnode.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("hard_play_cnt", 3))) + hardnode.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("hard_clear_cnt", 3))) + hardnode.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("hard_fc_cnt", 3))) + hardnode.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("hard_ex_cnt", 3))) + hardnode.add_child(Node.s32_array("score", scoredata.get_int_array("hard_points", 3))) + hardnode.add_child(Node.s8_array("clear", scoredata.get_int_array("hard_clear_flags", 3))) + hardnode.add_child(Node.s32_array("music_rate", scoredata.get_int_array("hard_music_rate", 3))) - for i, ghost in enumerate( - scoredata.get("hard_ghost", [None, None, None]) - ): + for i, ghost in enumerate(scoredata.get("hard_ghost", [None, None, None])): if ghost is None: continue @@ -2424,9 +2308,7 @@ class JubeatFesto( force_unlock = game_config.get_bool("force_song_unlock") # Calculate all of our achievement-backed entities. - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() owned_emblems: Set[int] = set() @@ -2434,9 +2316,7 @@ class JubeatFesto( course_completion: Dict[int, ValidatedDict] = {} for achievement in achievements: if achievement.type == "event": - event_completion[achievement.id] = achievement.data.get_bool( - "is_completed" - ) + event_completion[achievement.id] = achievement.data.get_bool("is_completed") elif achievement.type == "course": course_completion[achievement.id] = achievement.data elif achievement.type == "emblem": @@ -2480,12 +2360,8 @@ class JubeatFesto( info.add_child(Node.s32("mtg_entry_cnt", profile.get_int("mtg_entry_cnt"))) info.add_child(Node.s32("mtg_hold_cnt", profile.get_int("mtg_hold_cnt"))) info.add_child(Node.u8("mtg_result", profile.get_int("mtg_result"))) - info.add_child( - Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points")) - ) - info.add_child( - Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played")) - ) + info.add_child(Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points"))) + info.add_child(Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -2532,55 +2408,27 @@ class JubeatFesto( # Default music availability, I think? The game doesn't seem to make much use of this, so I think # we can safely set it to all 1's much like we do the open_music_list bitfield in global settings. - item.add_child( - Node.s32_array( - "music_list", profile.get_int_array("music_list", 64, [-1] * 64) - ) - ) + item.add_child(Node.s32_array("music_list", profile.get_int_array("music_list", 64, [-1] * 64))) # Song unlocks, force everything on if force unlocked, otherwise default to what the game granted. item.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_songs, 64), + ([-1] * 64) if force_unlock else self.create_owned_items(owned_songs, 64), ) ) # We force unlock all themes, markers, titles, and parts, regardless of what the client ended up earning. - item.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "title_list", profile.get_int_array("title_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 160, [-1] * 160) - ) - ) + item.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("title_list", profile.get_int_array("title_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 160, [-1] * 160))) # These get earned by unlocking them through JBOX. - item.add_child( - Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96)) - ) + item.add_child(Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96))) # I got no idea wtf this is, so I'm defaulting it to all on like the above ones. - item.add_child( - Node.s32_array( - "commu_list", profile.get_int_array("commu_list", 16, [-1] * 16) - ) - ) + item.add_child(Node.s32_array("commu_list", profile.get_int_array("commu_list", 16, [-1] * 16))) # I have no idea what these are for. I figured it was for the server to grant songs/themes/markers # outside of gameplay, but the game doesn't seem to react to setting values here. So, lets set them @@ -2592,21 +2440,11 @@ class JubeatFesto( new.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_secrets, 64), - ) - ) - new.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16) - ) - ) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16) + ([-1] * 64) if force_unlock else self.create_owned_items(owned_secrets, 64), ) ) + new.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16))) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16))) # Add rivals to profile. rivallist = Node.void("rivallist") @@ -2643,9 +2481,7 @@ class JubeatFesto( lab_edit_seq.set_attribute("count", "0") # Full combo challenge - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -2705,11 +2541,7 @@ class JubeatFesto( state = 0x0 state |= self.EVENT_STATUS_OPEN if eventdata["enabled"] else 0 - state |= ( - self.EVENT_STATUS_COMPLETE - if event_completion.get(eventid, False) - else 0 - ) + state |= self.EVENT_STATUS_COMPLETE if event_completion.get(eventid, False) else 0 event.add_child(Node.u8("state", state)) # JBox stuff @@ -2776,9 +2608,7 @@ class JubeatFesto( status = 0 status |= self.COURSE_STATUS_SEEN if status_dict.get_bool("seen") else 0 status |= self.COURSE_STATUS_PLAYED if status_dict.get_bool("played") else 0 - status |= ( - self.COURSE_STATUS_CLEARED if status_dict.get_bool("cleared") else 0 - ) + status |= self.COURSE_STATUS_CLEARED if status_dict.get_bool("cleared") else 0 coursenode = Node.void("course") course_list.add_child(coursenode) @@ -2871,20 +2701,14 @@ class JubeatFesto( # Festo dungeon festo_dungeon = Node.void("festo_dungeon") player.add_child(festo_dungeon) - festo_dungeon.add_child( - Node.s32("phase", profile.get_int("festo_dungeon_phase")) - ) - festo_dungeon.add_child( - Node.s32("clear_flag", profile.get_int("festo_dungeon_clear_flag")) - ) + festo_dungeon.add_child(Node.s32("phase", profile.get_int("festo_dungeon_phase"))) + festo_dungeon.add_child(Node.s32("clear_flag", profile.get_int("festo_dungeon_clear_flag"))) # Missing travel event, which I do not want to implement. return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -2923,12 +2747,8 @@ class JubeatFesto( newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) - newprofile.replace_int( - "bonus_tune_points", info.child_value("bonus_tune_points") - ) - newprofile.replace_bool( - "is_bonus_tune_played", info.child_value("is_bonus_tune_played") - ) + newprofile.replace_int("bonus_tune_points", info.child_value("bonus_tune_points")) + newprofile.replace_bool("is_bonus_tune_played", info.child_value("is_bonus_tune_played")) # Grab last settings lastnode = player.child("last") @@ -2953,30 +2773,16 @@ class JubeatFesto( # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "music_list", 64, item.child_value("music_list") - ) - newprofile.replace_int_array( - "theme_list", 16, item.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list", 16, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "title_list", 160, item.child_value("title_list") - ) - newprofile.replace_int_array( - "parts_list", 160, item.child_value("parts_list") - ) - newprofile.replace_int_array( - "commu_list", 16, item.child_value("commu_list") - ) + newprofile.replace_int_array("music_list", 64, item.child_value("music_list")) + newprofile.replace_int_array("theme_list", 16, item.child_value("theme_list")) + newprofile.replace_int_array("marker_list", 16, item.child_value("marker_list")) + newprofile.replace_int_array("title_list", 160, item.child_value("title_list")) + newprofile.replace_int_array("parts_list", 160, item.child_value("parts_list")) + newprofile.replace_int_array("commu_list", 16, item.child_value("commu_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -3000,18 +2806,12 @@ class JubeatFesto( newitem = item.child("new") if newitem is not None: - newprofile.replace_int_array( - "theme_list_new", 16, newitem.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list_new", 16, newitem.child_value("marker_list") - ) + newprofile.replace_int_array("theme_list_new", 16, newitem.child_value("theme_list")) + newprofile.replace_int_array("marker_list_new", 16, newitem.child_value("marker_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_secrets = self.calculate_owned_items( - newitem.child_value("secret_list") - ) + owned_secrets = self.calculate_owned_items(newitem.child_value("secret_list")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -3226,9 +3026,7 @@ class JubeatFesto( # Save it back newprofile.replace_dict("pick_up_chart", pick_up_chart) - newprofile.replace_float( - "pick_up_jubility", float(hot_music_list.attribute("param")) / 10 - ) + newprofile.replace_float("pick_up_jubility", float(hot_music_list.attribute("param")) / 10) # Common jubility stuff other_music_list = target_music.child("other_music_list") @@ -3251,9 +3049,7 @@ class JubeatFesto( # Save it back newprofile.replace_dict("common_chart", common_chart) - newprofile.replace_float( - "common_jubility", float(other_music_list.attribute("param")) / 10 - ) + newprofile.replace_float("common_jubility", float(other_music_list.attribute("param")) / 10) # Clan course saving clan_course_list = player.child("course_list") @@ -3281,9 +3077,7 @@ class JubeatFesto( oldcourse = ValidatedDict() oldcourse.replace_bool("seen", oldcourse.get_bool("seen") or is_seen) - oldcourse.replace_bool( - "played", oldcourse.get_bool("played") or is_played - ) + oldcourse.replace_bool("played", oldcourse.get_bool("played") or is_played) # Save it as an achievement self.data.local.user.put_achievement( @@ -3335,12 +3129,8 @@ class JubeatFesto( festo_dungeon = player.child("festo_dungeon") if festo_dungeon is not None: - newprofile.replace_int( - "festo_dungeon_phase", festo_dungeon.child_value("phase") - ) - newprofile.replace_int( - "festo_dungeon_clear_flag", festo_dungeon.child_value("clear_flag") - ) + newprofile.replace_int("festo_dungeon_phase", festo_dungeon.child_value("phase")) + newprofile.replace_int("festo_dungeon_clear_flag", festo_dungeon.child_value("clear_flag")) # Keep track of play statistics self.update_play_statistics(userid) diff --git a/bemani/backend/jubeat/prop.py b/bemani/backend/jubeat/prop.py index ffe9ec4..a35e729 100644 --- a/bemani/backend/jubeat/prop.py +++ b/bemani/backend/jubeat/prop.py @@ -199,9 +199,7 @@ class JubeatProp( return cls.__rank_to_class(cls.__class_to_rank(cur_class, cur_subclass) - 1) @classmethod - def _get_league_buckets( - cls, scores: List[Tuple[UserID, int]] - ) -> Tuple[List[UserID], List[UserID], List[UserID]]: + def _get_league_buckets(cls, scores: List[Tuple[UserID, int]]) -> Tuple[List[UserID], List[UserID], List[UserID]]: """ Given a list of userid, score tuples, return a tuple containing three lists. The first list is the top 30% scorer IDs, the next list is the middle 40% @@ -253,9 +251,7 @@ class JubeatProp( scores.append( ( userid, - league_score["score"][0] - + league_score["score"][1] - + league_score["score"][2], + league_score["score"][0] + league_score["score"][1] + league_score["score"][2], ) ) else: @@ -264,9 +260,7 @@ class JubeatProp( return scores, absentees @classmethod - def _get_league_absentees( - cls, data: Data, current_id: int, absentees: List[UserID] - ) -> List[UserID]: + def _get_league_absentees(cls, data: Data, current_id: int, absentees: List[UserID]) -> List[UserID]: """ Given a list of user IDs that didn't play for some number of weeks, return a subset of those IDs that have been absent enough weeks to get a demotion. @@ -333,22 +327,15 @@ class JubeatProp( data.local.user.put_profile(cls.game, cls.version, userid, profile) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Once a week, insert a new league course. Every day, insert new FC challenge courses. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "league_course", "weekly" - ): + if data.local.network.should_schedule(cls.game, cls.version, "league_course", "weekly"): # Generate a new league course list, save it to the DB. start_time, end_time = data.local.network.get_schedule_duration("weekly") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if len(all_songs) >= 3: league_songs = random.sample(all_songs, 3) data.local.game.put_time_sensitive_settings( @@ -390,19 +377,12 @@ class JubeatProp( cls._modify_profile(data, userid, "demote") # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "league_course", "weekly" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "league_course", "weekly") - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if len(all_songs) >= 2: daily_songs = random.sample(all_songs, 2) data.local.game.put_time_sensitive_settings( @@ -428,9 +408,7 @@ class JubeatProp( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") return events @@ -466,9 +444,7 @@ class JubeatProp( info.add_child(only_now_music) # Full combo challenge? - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -803,11 +779,7 @@ class JubeatProp( result.add_child(Node.s32_array("score", scores)) # Last course ID - data.add_child( - Node.s32( - "last_course_id", profile.get_dict("last").get_int("last_course_id", -1) - ) - ) + data.add_child(Node.s32("last_course_id", profile.get_dict("last").get_int("last_course_id", -1))) return gametop @@ -830,9 +802,7 @@ class JubeatProp( data.add_child(league_list) # Look up the current league charts in the DB - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "league" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "league") if entry is not None: # Just get the week number, use that as the ID leagueid = int(entry["start_time"] / 604800) @@ -870,27 +840,15 @@ class JubeatProp( result = Node.void("result") player.add_child(result) - league_score = self.data.local.user.get_achievement( - self.game, self.version, userid, leagueid, "league" - ) + league_score = self.data.local.user.get_achievement(self.game, self.version, userid, leagueid, "league") if league_score is None: league_score = ValidatedDict() - result.add_child( - Node.s32_array("score", league_score.get_int_array("score", 3, [0] * 3)) - ) - result.add_child( - Node.s8_array("clear", league_score.get_int_array("clear", 3, [0] * 3)) - ) + result.add_child(Node.s32_array("score", league_score.get_int_array("score", 3, [0] * 3))) + result.add_child(Node.s8_array("clear", league_score.get_int_array("clear", 3, [0] * 3))) - data.add_child( - Node.s32("last_class", profile.get_dict("last").get_int("league_class", 1)) - ) - data.add_child( - Node.s32( - "last_subclass", profile.get_dict("last").get_int("league_subclass", 5) - ) - ) + data.add_child(Node.s32("last_class", profile.get_dict("last").get_int("league_class", 1))) + data.add_child(Node.s32("last_subclass", profile.get_dict("last").get_int("league_subclass", 5))) data.add_child(Node.bool("is_checked", profile.get_bool("league_is_checked"))) return gametop @@ -905,9 +863,7 @@ class JubeatProp( force_unlock = game_config.get_bool("force_song_unlock") # Allow figuring out owned emblems. - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() owned_emblems: Set[int] = set() @@ -953,12 +909,8 @@ class JubeatProp( info.add_child(Node.s32("match_cnt", profile.get_int("match_cnt"))) info.add_child(Node.s32("beat_cnt", profile.get_int("beat_cnt"))) info.add_child(Node.s32("mynews_cnt", profile.get_int("mynews_cnt"))) - info.add_child( - Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points")) - ) - info.add_child( - Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played")) - ) + info.add_child(Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points"))) + info.add_child(Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -1008,55 +960,29 @@ class JubeatProp( # Secret unlocks item = Node.void("item") player.add_child(item) - item.add_child( - Node.s32_array( - "music_list", profile.get_int_array("music_list", 32, [-1] * 32) - ) - ) + item.add_child(Node.s32_array("music_list", profile.get_int_array("music_list", 32, [-1] * 32))) item.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_songs, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_songs, 32), ) ) item.add_child(Node.s16("theme_list", profile.get_int("theme_list", -1))) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 2, [-1] * 2) - ) - ) - item.add_child( - Node.s32_array( - "title_list", profile.get_int_array("title_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96)) - ) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 2, [-1] * 2))) + item.add_child(Node.s32_array("title_list", profile.get_int_array("title_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96))) new = Node.void("new") item.add_child(new) new.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_secrets, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_secrets, 32), ) ) new.add_child(Node.s16("theme_list", profile.get_int("theme_list_new", -1))) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2) - ) - ) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2))) # Sane defaults for unknown/who cares nodes history = Node.void("history") @@ -1070,9 +996,7 @@ class JubeatProp( cabinet_survey.add_child(Node.u32("read_flag", 0)) kaitou_bisco = Node.void("kaitou_bisco") player.add_child(kaitou_bisco) - kaitou_bisco.add_child( - Node.u32("read_flag", profile.get_int("kaitou_bisco_read_flag")) - ) + kaitou_bisco.add_child(Node.u32("read_flag", profile.get_int("kaitou_bisco_read_flag"))) navi = Node.void("navi") player.add_child(navi) navi.add_child(Node.u32("flag", profile.get_int("navi_flag"))) @@ -1089,15 +1013,11 @@ class JubeatProp( event.set_attribute("type", str(achievement.id)) state = 0x0 - state = ( - state + 0x2 if achievement.data.get_bool("is_completed") else 0x0 - ) + state = state + 0x2 if achievement.data.get_bool("is_completed") else 0x0 event.add_child(Node.u8("state", state)) # Full combo challenge - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -1161,15 +1081,9 @@ class JubeatProp( league = Node.void("league") rival.add_child(league) - league.add_child( - Node.bool( - "is_first_play", rprofile.get_bool("league_is_first_play", True) - ) - ) + league.add_child(Node.bool("is_first_play", rprofile.get_bool("league_is_first_play", True))) league.add_child(Node.s32("class", rprofile.get_int("league_class", 1))) - league.add_child( - Node.s32("subclass", rprofile.get_int("league_subclass", 5)) - ) + league.add_child(Node.s32("subclass", rprofile.get_int("league_subclass", 5))) # Lazy way of keeping track of rivals, since we can only have 3 # or the game with throw up. @@ -1214,17 +1128,13 @@ class JubeatProp( player.add_child(career) career.add_child(Node.s16("level", careerdict.get_int("level", 1))) career.add_child(Node.s32("point", careerdict.get_int("point"))) - career.add_child( - Node.s32_array("param", careerdict.get_int_array("param", 10, [-1] * 10)) - ) + career.add_child(Node.s32_array("param", careerdict.get_int_array("param", 10, [-1] * 10))) career.add_child(Node.bool("is_unlocked", careerdict.get_bool("is_unlocked"))) # League stuff league = Node.void("league") player.add_child(league) - league.add_child( - Node.bool("is_first_play", profile.get_bool("league_is_first_play", True)) - ) + league.add_child(Node.bool("is_first_play", profile.get_bool("league_is_first_play", True))) league.add_child(Node.s32("class", profile.get_int("league_class", 1))) league.add_child(Node.s32("subclass", profile.get_int("league_subclass", 5))) @@ -1276,9 +1186,7 @@ class JubeatProp( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -1318,17 +1226,11 @@ class JubeatProp( newprofile.replace_int("clear_cnt", info.child_value("clear_cnt")) newprofile.replace_int("match_cnt", info.child_value("match_cnt")) newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) - newprofile.replace_int( - "total_best_score", info.child_value("total_best_score") - ) + newprofile.replace_int("total_best_score", info.child_value("total_best_score")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) - newprofile.replace_int( - "bonus_tune_points", info.child_value("bonus_tune_points") - ) - newprofile.replace_bool( - "is_bonus_tune_played", info.child_value("is_bonus_tune_played") - ) + newprofile.replace_int("bonus_tune_points", info.child_value("bonus_tune_points")) + newprofile.replace_bool("is_bonus_tune_played", info.child_value("is_bonus_tune_played")) # Grab last settings (finally mostly in its own node!) lastnode = player.child("last") @@ -1353,25 +1255,15 @@ class JubeatProp( # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "title_list", 160, item.child_value("title_list") - ) + newprofile.replace_int_array("title_list", 160, item.child_value("title_list")) newprofile.replace_int("theme_list", item.child_value("theme_list")) - newprofile.replace_int_array( - "marker_list", 2, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "parts_list", 160, item.child_value("parts_list") - ) - newprofile.replace_int_array( - "music_list", 32, item.child_value("music_list") - ) + newprofile.replace_int_array("marker_list", 2, item.child_value("marker_list")) + newprofile.replace_int_array("parts_list", 160, item.child_value("parts_list")) + newprofile.replace_int_array("music_list", 32, item.child_value("music_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -1395,18 +1287,12 @@ class JubeatProp( newitem = item.child("new") if newitem is not None: - newprofile.replace_int( - "theme_list_new", newitem.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list_new", 2, newitem.child_value("marker_list") - ) + newprofile.replace_int("theme_list_new", newitem.child_value("theme_list")) + newprofile.replace_int_array("marker_list_new", 2, newitem.child_value("marker_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_secrets = self.calculate_owned_items( - newitem.child_value("secret_list") - ) + owned_secrets = self.calculate_owned_items(newitem.child_value("secret_list")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -1478,9 +1364,7 @@ class JubeatProp( # A whole bunch of miscelaneous shit newprofile.replace_int("navi_flag", player.child_value("navi/flag")) - newprofile.replace_int( - "kaitou_bisco_read_flag", player.child_value("kaitou_bisco/read_flag") - ) + newprofile.replace_int("kaitou_bisco_read_flag", player.child_value("kaitou_bisco/read_flag")) # Get timestamps for played songs timestamps: Dict[int, int] = {} @@ -1527,9 +1411,7 @@ class JubeatProp( if flags & bit > 0: medal = max(medal, mapping[bit]) - self.update_score( - userid, timestamp, songid, chart, points, medal, combo, ghost - ) + self.update_score(userid, timestamp, songid, chart, points, medal, combo, ghost) # If this was a course save, grab and save that info too course = player.child("course") @@ -1558,12 +1440,8 @@ class JubeatProp( league = player.child("league") if league is not None: leagueid = league.child_value("league_id") - newprofile.replace_bool( - "league_is_checked", league.child_value("is_checked") - ) - newprofile.replace_bool( - "league_is_first_play", league.child_value("is_first_play") - ) + newprofile.replace_bool("league_is_checked", league.child_value("is_checked")) + newprofile.replace_bool("league_is_first_play", league.child_value("is_first_play")) # Extract scores score = [0] * 3 @@ -1605,9 +1483,7 @@ class JubeatProp( return newprofile - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -1673,24 +1549,12 @@ class JubeatProp( playdata.add_child(musicdata) musicdata.set_attribute("music_id", scoreid) - musicdata.add_child( - Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("score", scoredata.get_int_array("points", 3)) - ) - musicdata.add_child( - Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3)) - ) + musicdata.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3))) + musicdata.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3))) + musicdata.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3))) + musicdata.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3))) + musicdata.add_child(Node.s32_array("score", scoredata.get_int_array("points", 3))) + musicdata.add_child(Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3))) ghosts = scoredata.get("ghost", [None, None, None]) for i in range(len(ghosts)): diff --git a/bemani/backend/jubeat/qubell.py b/bemani/backend/jubeat/qubell.py index 84943ca..cf99d91 100644 --- a/bemani/backend/jubeat/qubell.py +++ b/bemani/backend/jubeat/qubell.py @@ -56,22 +56,15 @@ class JubeatQubell( return JubeatProp(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert daily FC challenges into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if len(all_songs) >= 2: daily_songs = random.sample(all_songs, 2) data.local.game.put_time_sensitive_settings( @@ -97,9 +90,7 @@ class JubeatQubell( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") return events @classmethod @@ -674,9 +665,7 @@ class JubeatQubell( # Grab unlock progress item = player.child("item") if item is not None: - owned_emblems = self.calculate_owned_items( - item.child_value("emblem_list") - ) + owned_emblems = self.calculate_owned_items(item.child_value("emblem_list")) for index in owned_emblems: self.data.local.user.put_achievement( self.game, @@ -722,9 +711,7 @@ class JubeatQubell( game_config = self.get_game_config() force_unlock = game_config.get_bool("force_song_unlock") - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() owned_emblems: Set[int] = set() @@ -773,12 +760,8 @@ class JubeatQubell( info.add_child(Node.s32("match_cnt", profile.get_int("match_cnt"))) info.add_child(Node.s32("beat_cnt", profile.get_int("beat_cnt"))) info.add_child(Node.s32("mynews_cnt", profile.get_int("mynews_cnt"))) - info.add_child( - Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points")) - ) - info.add_child( - Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played")) - ) + info.add_child(Node.s32("bonus_tune_points", profile.get_int("bonus_tune_points"))) + info.add_child(Node.bool("is_bonus_tune_played", profile.get_bool("is_bonus_tune_played"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -829,63 +812,29 @@ class JubeatQubell( # Secret unlocks item = Node.void("item") player.add_child(item) - item.add_child( - Node.s32_array( - "music_list", profile.get_int_array("music_list", 64, [-1] * 64) - ) - ) + item.add_child(Node.s32_array("music_list", profile.get_int_array("music_list", 64, [-1] * 64))) item.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_songs, 64), + ([-1] * 64) if force_unlock else self.create_owned_items(owned_songs, 64), ) ) - item.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 16, [-1] * 16) - ) - ) - item.add_child( - Node.s32_array( - "title_list", profile.get_int_array("title_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 160, [-1] * 160) - ) - ) - item.add_child( - Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96)) - ) + item.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 16, [-1] * 16))) + item.add_child(Node.s32_array("title_list", profile.get_int_array("title_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 160, [-1] * 160))) + item.add_child(Node.s32_array("emblem_list", self.create_owned_items(owned_emblems, 96))) new = Node.void("new") item.add_child(new) new.add_child( Node.s32_array( "secret_list", - ([-1] * 64) - if force_unlock - else self.create_owned_items(owned_secrets, 64), - ) - ) - new.add_child( - Node.s32_array( - "theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16) - ) - ) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16) + ([-1] * 64) if force_unlock else self.create_owned_items(owned_secrets, 64), ) ) + new.add_child(Node.s32_array("theme_list", profile.get_int_array("theme_list_new", 16, [-1] * 16))) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 16, [-1] * 16))) # Add rivals to profile. rivallist = Node.void("rivallist") @@ -924,9 +873,7 @@ class JubeatQubell( lab_edit_seq.set_attribute("count", "0") # Full combo challenge - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -987,9 +934,7 @@ class JubeatQubell( event.set_attribute("type", str(achievement.id)) state = 0x0 - state = ( - state + 0x2 if achievement.data.get_bool("is_completed") else 0x0 - ) + state = state + 0x2 if achievement.data.get_bool("is_completed") else 0x0 event.add_child(Node.u8("state", state)) # JBox stuff @@ -1025,9 +970,7 @@ class JubeatQubell( main.add_child(stage) stage.set_attribute("number", str(digdigdict.get_int("stage_number", 1))) stage.add_child(Node.s32("point", digdigdict.get_int("point"))) - stage.add_child( - Node.s32_array("param", digdigdict.get_int_array("param", 12, [0] * 12)) - ) + stage.add_child(Node.s32_array("param", digdigdict.get_int_array("param", 12, [0] * 12))) # Emerald eternal stages eternal = Node.void("eternal") @@ -1035,42 +978,20 @@ class JubeatQubell( eternal.add_child(Node.s32("ratio", 1)) eternal.add_child(Node.s64("used_point", eternaldict.get_int("used_point"))) eternal.add_child(Node.s64("point", eternaldict.get_int("point"))) - eternal.add_child( - Node.s64("excavated_point", eternaldict.get_int("excavated_point")) - ) + eternal.add_child(Node.s64("excavated_point", eternaldict.get_int("excavated_point"))) cube = Node.void("cube") eternal.add_child(cube) - cube.add_child( - Node.s8_array("state", eternaldict.get_int_array("state", 12, [0] * 12)) - ) + cube.add_child(Node.s8_array("state", eternaldict.get_int_array("state", 12, [0] * 12))) item = Node.void("item") cube.add_child(item) - item.add_child( - Node.s32_array("kind", eternaldict.get_int_array("item_kind", 12, [0] * 12)) - ) - item.add_child( - Node.s32_array( - "value", eternaldict.get_int_array("item_value", 12, [0] * 12) - ) - ) + item.add_child(Node.s32_array("kind", eternaldict.get_int_array("item_kind", 12, [0] * 12))) + item.add_child(Node.s32_array("value", eternaldict.get_int_array("item_value", 12, [0] * 12))) norma = Node.void("norma") cube.add_child(norma) norma.add_child(Node.s64_array("till_time", [0] * 12)) - norma.add_child( - Node.s32_array( - "kind", eternaldict.get_int_array("norma_kind", 12, [0] * 12) - ) - ) - norma.add_child( - Node.s32_array( - "value", eternaldict.get_int_array("norma_value", 12, [0] * 12) - ) - ) - norma.add_child( - Node.s32_array( - "param", eternaldict.get_int_array("norma_param", 12, [0] * 12) - ) - ) + norma.add_child(Node.s32_array("kind", eternaldict.get_int_array("norma_kind", 12, [0] * 12))) + norma.add_child(Node.s32_array("value", eternaldict.get_int_array("norma_value", 12, [0] * 12))) + norma.add_child(Node.s32_array("param", eternaldict.get_int_array("norma_param", 12, [0] * 12))) if self.ENABLE_GARNET: # Garnet @@ -1084,14 +1005,8 @@ class JubeatQubell( olddict.get_int_array("excavated_point", 5, [0] * 5), ) ) - old.add_child( - Node.s32_array( - "excavated", olddict.get_int_array("excavated", 5, [0] * 5) - ) - ) - old.add_child( - Node.s32_array("param", olddict.get_int_array("param", 5, [0] * 5)) - ) + old.add_child(Node.s32_array("excavated", olddict.get_int_array("excavated", 5, [0] * 5))) + old.add_child(Node.s32_array("param", olddict.get_int_array("param", 5, [0] * 5))) # This should have a bunch of sub-nodes with the following format. Note that only # the first ten nodes are saved even if more are read. Presumably this is the list # of old songs we are allowing the player to unlock? Doesn't matter, we're disabling @@ -1110,9 +1025,7 @@ class JubeatQubell( main.add_child(stage_list) # Stage numbers are between 1 and 13 inclusive. for i in range(1, 14): - stage_flags = self.data.local.user.get_achievement( - self.game, self.version, userid, i, "stage" - ) + stage_flags = self.data.local.user.get_achievement(self.game, self.version, userid, i, "stage") if stage_flags is None: stage_flags = ValidatedDict() @@ -1167,9 +1080,7 @@ class JubeatQubell( return root - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -1235,24 +1146,12 @@ class JubeatQubell( playdata.add_child(musicdata) musicdata.set_attribute("music_id", scoreid) - musicdata.add_child( - Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("score", scoredata.get_int_array("points", 3)) - ) - musicdata.add_child( - Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3)) - ) + musicdata.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3))) + musicdata.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3))) + musicdata.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3))) + musicdata.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3))) + musicdata.add_child(Node.s32_array("score", scoredata.get_int_array("points", 3))) + musicdata.add_child(Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3))) ghosts = scoredata.get("ghost", [None, None, None]) for i in range(len(ghosts)): @@ -1266,9 +1165,7 @@ class JubeatQubell( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -1309,12 +1206,8 @@ class JubeatQubell( newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) - newprofile.replace_int( - "bonus_tune_points", info.child_value("bonus_tune_points") - ) - newprofile.replace_bool( - "is_bonus_tune_played", info.child_value("is_bonus_tune_played") - ) + newprofile.replace_int("bonus_tune_points", info.child_value("bonus_tune_points")) + newprofile.replace_bool("is_bonus_tune_played", info.child_value("is_bonus_tune_played")) # Grab last settings lastnode = player.child("last") @@ -1340,27 +1233,15 @@ class JubeatQubell( # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "music_list", 64, item.child_value("music_list") - ) - newprofile.replace_int_array( - "theme_list", 16, item.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list", 16, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "title_list", 160, item.child_value("title_list") - ) - newprofile.replace_int_array( - "parts_list", 160, item.child_value("parts_list") - ) + newprofile.replace_int_array("music_list", 64, item.child_value("music_list")) + newprofile.replace_int_array("theme_list", 16, item.child_value("theme_list")) + newprofile.replace_int_array("marker_list", 16, item.child_value("marker_list")) + newprofile.replace_int_array("title_list", 160, item.child_value("title_list")) + newprofile.replace_int_array("parts_list", 160, item.child_value("parts_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -1384,18 +1265,12 @@ class JubeatQubell( newitem = item.child("new") if newitem is not None: - newprofile.replace_int_array( - "theme_list_new", 16, newitem.child_value("theme_list") - ) - newprofile.replace_int_array( - "marker_list_new", 16, newitem.child_value("marker_list") - ) + newprofile.replace_int_array("theme_list_new", 16, newitem.child_value("theme_list")) + newprofile.replace_int_array("marker_list_new", 16, newitem.child_value("marker_list")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_secrets = self.calculate_owned_items( - newitem.child_value("secret_list") - ) + owned_secrets = self.calculate_owned_items(newitem.child_value("secret_list")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -1492,27 +1367,13 @@ class JubeatQubell( if eternal is not None: eternaldict.replace_int("used_point", eternal.child_value("used_point")) eternaldict.replace_int("point", eternal.child_value("point")) - eternaldict.replace_int( - "excavated_point", eternal.child_value("excavated_point") - ) - eternaldict.replace_int_array( - "state", 12, eternal.child_value("cube/state") - ) - eternaldict.replace_int_array( - "item_kind", 12, eternal.child_value("cube/item/kind") - ) - eternaldict.replace_int_array( - "item_value", 12, eternal.child_value("cube/item/value") - ) - eternaldict.replace_int_array( - "norma_kind", 12, eternal.child_value("cube/norma/kind") - ) - eternaldict.replace_int_array( - "norma_value", 12, eternal.child_value("cube/norma/value") - ) - eternaldict.replace_int_array( - "norma_param", 12, eternal.child_value("cube/norma/param") - ) + eternaldict.replace_int("excavated_point", eternal.child_value("excavated_point")) + eternaldict.replace_int_array("state", 12, eternal.child_value("cube/state")) + eternaldict.replace_int_array("item_kind", 12, eternal.child_value("cube/item/kind")) + eternaldict.replace_int_array("item_value", 12, eternal.child_value("cube/item/value")) + eternaldict.replace_int_array("norma_kind", 12, eternal.child_value("cube/norma/kind")) + eternaldict.replace_int_array("norma_value", 12, eternal.child_value("cube/norma/value")) + eternaldict.replace_int_array("norma_param", 12, eternal.child_value("cube/norma/param")) digdigdict.replace_dict("eternal", eternaldict) if self.ENABLE_GARNET: @@ -1521,12 +1382,8 @@ class JubeatQubell( if old is not None: olddict.replace_int("need_point", old.child_value("need_point")) olddict.replace_int("point", old.child_value("point")) - olddict.replace_int_array( - "excavated_point", 5, old.child_value("excavated_point") - ) - olddict.replace_int_array( - "excavated", 5, old.child_value("excavated") - ) + olddict.replace_int_array("excavated_point", 5, old.child_value("excavated_point")) + olddict.replace_int_array("excavated", 5, old.child_value("excavated")) olddict.replace_int_array("param", 5, old.child_value("param")) digdigdict.replace_dict("old", olddict) @@ -1599,9 +1456,7 @@ class JubeatQubell( if flags & bit > 0: medal = max(medal, mapping[bit]) - self.update_score( - userid, timestamp, songid, chart, points, medal, combo, ghost, stats - ) + self.update_score(userid, timestamp, songid, chart, points, medal, combo, ghost, stats) # Born stuff born = player.child("born") diff --git a/bemani/backend/jubeat/saucer.py b/bemani/backend/jubeat/saucer.py index a960715..85d99b3 100644 --- a/bemani/backend/jubeat/saucer.py +++ b/bemani/backend/jubeat/saucer.py @@ -34,22 +34,15 @@ class JubeatSaucer( return JubeatCopiousAppend(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert daily FC challenges into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if all_songs: today_song = random.sample(all_songs, 1)[0] data.local.game.put_time_sensitive_settings( @@ -73,9 +66,7 @@ class JubeatSaucer( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") return events @classmethod @@ -215,9 +206,7 @@ class JubeatSaucer( force_unlock = game_config.get_bool("force_song_unlock") # Allow figuring out owned songs. - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() for achievement in achievements: @@ -242,9 +231,7 @@ class JubeatSaucer( info.add_child(Node.s32("beat_cnt", profile.get_int("beat_cnt"))) info.add_child(Node.s32("mynews_cnt", profile.get_int("mynews_cnt"))) if "total_best_score" in profile: - info.add_child( - Node.s32("total_best_score", profile.get_int("total_best_score")) - ) + info.add_child(Node.s32("total_best_score", profile.get_int("total_best_score"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -266,9 +253,7 @@ class JubeatSaucer( item.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_songs, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_songs, 32), ) ) item.add_child( @@ -282,25 +267,15 @@ class JubeatSaucer( ) ) item.add_child(Node.s16("theme_list", profile.get_int("theme_list", -1))) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 2, [-1] * 2) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 96, [-1] * 96) - ) - ) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 2, [-1] * 2))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 96, [-1] * 96))) new = Node.void("new") item.add_child(new) new.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_secrets, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_secrets, 32), ) ) new.add_child( @@ -314,11 +289,7 @@ class JubeatSaucer( ) ) new.add_child(Node.s16("theme_list", profile.get_int("theme_list_new", -1))) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2) - ) - ) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2))) # Last played data, for showing cursor and such lastdict = profile.get_dict("last") @@ -393,9 +364,7 @@ class JubeatSaucer( collabo.add_child(Node.bool("completed", False)) # Daily FC challenge. - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -510,9 +479,7 @@ class JubeatSaucer( music.add_child(Node.s32("price_s32", routedata["price"])) # Look up any updated satisfaction stored by the game - routesaved = self.data.local.user.get_achievement( - self.game, self.version, userid, route_no + 1, "route" - ) + routesaved = self.data.local.user.get_achievement(self.game, self.version, userid, route_no + 1, "route") if routesaved is None: routesaved = ValidatedDict() satisfaction = routesaved.get_int("satisfaction", routedata["satisfaction"]) @@ -697,9 +664,7 @@ class JubeatSaucer( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -727,44 +692,28 @@ class JubeatSaucer( newprofile.replace_int("save_cnt", info.child_value("save_cnt")) newprofile.replace_int("saved_cnt", info.child_value("saved_cnt")) newprofile.replace_int("fc_cnt", info.child_value("fc_cnt")) - newprofile.replace_int( - "ex_cnt", info.child_value("exc_cnt") - ) # Not a mistake, Jubeat is weird + newprofile.replace_int("ex_cnt", info.child_value("exc_cnt")) # Not a mistake, Jubeat is weird newprofile.replace_int("pf_cnt", info.child_value("pf_cnt")) newprofile.replace_int("clear_cnt", info.child_value("clear_cnt")) newprofile.replace_int("match_cnt", info.child_value("match_cnt")) newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) - newprofile.replace_int( - "total_best_score", info.child_value("total_best_score") - ) + newprofile.replace_int("total_best_score", info.child_value("total_best_score")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "title_list", 96, item.child_value("title_list") - ) + newprofile.replace_int_array("title_list", 96, item.child_value("title_list")) newprofile.replace_int("theme_list", item.child_value("theme_list")) - newprofile.replace_int_array( - "marker_list", 2, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "parts_list", 96, item.child_value("parts_list") - ) - newprofile.replace_int_array( - "title_list_new", 96, item.child_value("title_new") - ) + newprofile.replace_int_array("marker_list", 2, item.child_value("marker_list")) + newprofile.replace_int_array("parts_list", 96, item.child_value("parts_list")) + newprofile.replace_int_array("title_list_new", 96, item.child_value("title_new")) newprofile.replace_int("theme_list_new", item.child_value("theme_new")) - newprofile.replace_int_array( - "marker_list_new", 2, item.child_value("marker_new") - ) + newprofile.replace_int_array("marker_list_new", 2, item.child_value("marker_new")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -775,9 +724,7 @@ class JubeatSaucer( {}, ) - owned_secrets = self.calculate_owned_items( - item.child_value("secret_new") - ) + owned_secrets = self.calculate_owned_items(item.child_value("secret_new")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -791,9 +738,7 @@ class JubeatSaucer( # Grab bistro progress bistro = player.child("bistro") if bistro is not None: - newprofile.replace_int( - "bistro_carry_over", bistro.child_value("carry_over") - ) + newprofile.replace_int("bistro_carry_over", bistro.child_value("carry_over")) chefdata = newprofile.get_dict("chef") chef = bistro.child("chef") @@ -877,9 +822,7 @@ class JubeatSaucer( if flags & bit > 0: medal = max(medal, mapping[bit]) - self.update_score( - userid, timestamp, songid, chart, points, medal, combo, ghost - ) + self.update_score(userid, timestamp, songid, chart, points, medal, combo, ghost) # Save back last information gleaned from results newprofile.replace_dict("last", last) @@ -889,9 +832,7 @@ class JubeatSaucer( return newprofile - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -958,24 +899,12 @@ class JubeatSaucer( playdata.add_child(musicdata) musicdata.set_attribute("music_id", scoreid) - musicdata.add_child( - Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("score", scoredata.get_int_array("points", 3)) - ) - musicdata.add_child( - Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3)) - ) + musicdata.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3))) + musicdata.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3))) + musicdata.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3))) + musicdata.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3))) + musicdata.add_child(Node.s32_array("score", scoredata.get_int_array("points", 3))) + musicdata.add_child(Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3))) ghosts = scoredata.get("ghost", [None, None, None]) for i in range(len(ghosts)): diff --git a/bemani/backend/jubeat/saucerfulfill.py b/bemani/backend/jubeat/saucerfulfill.py index 34b60f3..2160736 100644 --- a/bemani/backend/jubeat/saucerfulfill.py +++ b/bemani/backend/jubeat/saucerfulfill.py @@ -46,22 +46,15 @@ class JubeatSaucerFulfill( return JubeatSaucer(self.data, self.config, self.model) @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Insert daily FC challenges into the DB. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "fc_challenge", "daily" - ): + if data.local.network.should_schedule(cls.game, cls.version, "fc_challenge", "daily"): # Generate a new list of two FC challenge songs. start_time, end_time = data.local.network.get_schedule_duration("daily") - all_songs = set( - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ) + all_songs = set(song.id for song in data.local.music.get_all_songs(cls.game, cls.version)) if len(all_songs) >= 2: daily_songs = random.sample(all_songs, 2) data.local.game.put_time_sensitive_settings( @@ -87,9 +80,7 @@ class JubeatSaucerFulfill( ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "fc_challenge", "daily" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "fc_challenge", "daily") return events @classmethod @@ -289,9 +280,7 @@ class JubeatSaucerFulfill( result.add_child(Node.s32_array("score", scores)) # Last course ID - last_course_id = Node.s32( - "last_course_id", profile.get_dict("last").get_int("last_course_id", -1) - ) + last_course_id = Node.s32("last_course_id", profile.get_dict("last").get_int("last_course_id", -1)) data.add_child(last_course_id) return gametop @@ -350,9 +339,7 @@ class JubeatSaucerFulfill( force_unlock = game_config.get_bool("force_song_unlock") # Allow figuring out owned songs. - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) owned_songs: Set[int] = set() owned_secrets: Set[int] = set() for achievement in achievements: @@ -377,13 +364,9 @@ class JubeatSaucerFulfill( info.add_child(Node.s32("beat_cnt", profile.get_int("beat_cnt"))) info.add_child(Node.s32("mynews_cnt", profile.get_int("mynews_cnt"))) info.add_child(Node.s32("extra_point", profile.get_int("extra_point"))) - info.add_child( - Node.bool("is_extra_played", profile.get_bool("is_extra_played")) - ) + info.add_child(Node.bool("is_extra_played", profile.get_bool("is_extra_played"))) if "total_best_score" in profile: - info.add_child( - Node.s32("total_best_score", profile.get_int("total_best_score")) - ) + info.add_child(Node.s32("total_best_score", profile.get_int("total_best_score"))) # Looks to be set to true when there's an old profile, stops tutorial from # happening on first load. @@ -412,9 +395,7 @@ class JubeatSaucerFulfill( item.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_songs, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_songs, 32), ) ) item.add_child( @@ -428,25 +409,15 @@ class JubeatSaucerFulfill( ) ) item.add_child(Node.s16("theme_list", profile.get_int("theme_list", -1))) - item.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list", 2, [-1] * 2) - ) - ) - item.add_child( - Node.s32_array( - "parts_list", profile.get_int_array("parts_list", 96, [-1] * 96) - ) - ) + item.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list", 2, [-1] * 2))) + item.add_child(Node.s32_array("parts_list", profile.get_int_array("parts_list", 96, [-1] * 96))) new = Node.void("new") item.add_child(new) new.add_child( Node.s32_array( "secret_list", - ([-1] * 32) - if force_unlock - else self.create_owned_items(owned_secrets, 32), + ([-1] * 32) if force_unlock else self.create_owned_items(owned_secrets, 32), ) ) new.add_child( @@ -460,11 +431,7 @@ class JubeatSaucerFulfill( ) ) new.add_child(Node.s16("theme_list", profile.get_int("theme_list_new", -1))) - new.add_child( - Node.s32_array( - "marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2) - ) - ) + new.add_child(Node.s32_array("marker_list", profile.get_int_array("marker_list_new", 2, [-1] * 2))) # Last played data, for showing cursor and such lastdict = profile.get_dict("last") @@ -498,37 +465,23 @@ class JubeatSaucerFulfill( player.add_child(macchiato) macchiato.add_child(Node.s32("pack_id", macchiatodict.get_int("pack_id"))) macchiato.add_child(Node.u16("bean_num", macchiatodict.get_int("bean_num"))) - macchiato.add_child( - Node.s32("daily_milk_num", macchiatodict.get_int("daily_milk_num")) - ) + macchiato.add_child(Node.s32("daily_milk_num", macchiatodict.get_int("daily_milk_num"))) macchiato.add_child( Node.bool( "is_received_daily_milk", macchiatodict.get_bool("is_received_daily_milk"), ) ) - macchiato.add_child( - Node.s32("today_tune_cnt", macchiatodict.get_int("today_tune_cnt")) - ) + macchiato.add_child(Node.s32("today_tune_cnt", macchiatodict.get_int("today_tune_cnt"))) macchiato.add_child( Node.s32_array( "daily_milk_bonus", - macchiatodict.get_int_array( - "daily_milk_bonus", 9, [-1, -1, -1, -1, -1, -1, -1, -1, -1] - ), + macchiatodict.get_int_array("daily_milk_bonus", 9, [-1, -1, -1, -1, -1, -1, -1, -1, -1]), ) ) - macchiato.add_child( - Node.s32("daily_play_burst", macchiatodict.get_int("daily_play_burst")) - ) - macchiato.add_child( - Node.bool( - "sub_menu_is_completed", macchiatodict.get_bool("sub_menu_is_completed") - ) - ) - macchiato.add_child( - Node.s32("compensation_milk", macchiatodict.get_int("compensation_milk")) - ) + macchiato.add_child(Node.s32("daily_play_burst", macchiatodict.get_int("daily_play_burst"))) + macchiato.add_child(Node.bool("sub_menu_is_completed", macchiatodict.get_bool("sub_menu_is_completed"))) + macchiato.add_child(Node.s32("compensation_milk", macchiatodict.get_int("compensation_milk"))) macchiato.add_child(Node.s32("match_cnt", macchiatodict.get_int("match_cnt"))) # Probably never will support this @@ -593,9 +546,7 @@ class JubeatSaucerFulfill( rivallist.set_attribute("count", str(rivalcount)) # Full combo daily challenge. - entry = self.data.local.game.get_time_sensitive_settings( - self.game, self.version, "fc_challenge" - ) + entry = self.data.local.game.get_time_sensitive_settings(self.game, self.version, "fc_challenge") if entry is None: entry = ValidatedDict() @@ -779,9 +730,7 @@ class JubeatSaucerFulfill( return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_bool("saved", True) data = request.child("data") @@ -809,21 +758,15 @@ class JubeatSaucerFulfill( newprofile.replace_int("save_cnt", info.child_value("save_cnt")) newprofile.replace_int("saved_cnt", info.child_value("saved_cnt")) newprofile.replace_int("fc_cnt", info.child_value("fc_cnt")) - newprofile.replace_int( - "ex_cnt", info.child_value("exc_cnt") - ) # Not a mistake, Jubeat is weird + newprofile.replace_int("ex_cnt", info.child_value("exc_cnt")) # Not a mistake, Jubeat is weird newprofile.replace_int("pf_cnt", info.child_value("pf_cnt")) newprofile.replace_int("clear_cnt", info.child_value("clear_cnt")) newprofile.replace_int("match_cnt", info.child_value("match_cnt")) newprofile.replace_int("beat_cnt", info.child_value("beat_cnt")) - newprofile.replace_int( - "total_best_score", info.child_value("total_best_score") - ) + newprofile.replace_int("total_best_score", info.child_value("total_best_score")) newprofile.replace_int("mynews_cnt", info.child_value("mynews_cnt")) newprofile.replace_int("extra_point", info.child_value("extra_point")) - newprofile.replace_bool( - "is_extra_played", info.child_value("is_extra_played") - ) + newprofile.replace_bool("is_extra_played", info.child_value("is_extra_played")) last.replace_int("expert_option", info.child_value("expert_option")) last.replace_int("matching", info.child_value("matching")) @@ -833,29 +776,17 @@ class JubeatSaucerFulfill( # Grab unlock progress item = player.child("item") if item is not None: - newprofile.replace_int_array( - "title_list", 96, item.child_value("title_list") - ) + newprofile.replace_int_array("title_list", 96, item.child_value("title_list")) newprofile.replace_int("theme_list", item.child_value("theme_list")) - newprofile.replace_int_array( - "marker_list", 2, item.child_value("marker_list") - ) - newprofile.replace_int_array( - "parts_list", 96, item.child_value("parts_list") - ) - newprofile.replace_int_array( - "title_list_new", 96, item.child_value("title_new") - ) + newprofile.replace_int_array("marker_list", 2, item.child_value("marker_list")) + newprofile.replace_int_array("parts_list", 96, item.child_value("parts_list")) + newprofile.replace_int_array("title_list_new", 96, item.child_value("title_new")) newprofile.replace_int("theme_list_new", item.child_value("theme_new")) - newprofile.replace_int_array( - "marker_list_new", 2, item.child_value("marker_new") - ) + newprofile.replace_int_array("marker_list_new", 2, item.child_value("marker_new")) if not force_unlock: # Don't persist if we're force-unlocked, this data will be bogus. - owned_songs = self.calculate_owned_items( - item.child_value("secret_list") - ) + owned_songs = self.calculate_owned_items(item.child_value("secret_list")) for index in owned_songs: self.data.local.user.put_achievement( self.game, @@ -866,9 +797,7 @@ class JubeatSaucerFulfill( {}, ) - owned_secrets = self.calculate_owned_items( - item.child_value("secret_new") - ) + owned_secrets = self.calculate_owned_items(item.child_value("secret_new")) for index in owned_secrets: self.data.local.user.put_achievement( self.game, @@ -885,31 +814,19 @@ class JubeatSaucerFulfill( if macchiato is not None: macchiatodict.replace_int("pack_id", macchiato.child_value("pack_id")) macchiatodict.replace_int("bean_num", macchiato.child_value("bean_num")) - macchiatodict.replace_int( - "daily_milk_num", macchiato.child_value("daily_milk_num") - ) + macchiatodict.replace_int("daily_milk_num", macchiato.child_value("daily_milk_num")) macchiatodict.replace_bool( "is_received_daily_milk", macchiato.child_value("is_received_daily_milk"), ) - macchiatodict.replace_bool( - "sub_menu_is_completed", macchiato.child_value("sub_menu_is_completed") - ) - macchiatodict.replace_int( - "today_tune_cnt", macchiato.child_value("today_tune_cnt") - ) - macchiatodict.replace_int_array( - "daily_milk_bonus", 9, macchiato.child_value("daily_milk_bonus") - ) - macchiatodict.replace_int( - "compensation_milk", macchiato.child_value("compensation_milk") - ) + macchiatodict.replace_bool("sub_menu_is_completed", macchiato.child_value("sub_menu_is_completed")) + macchiatodict.replace_int("today_tune_cnt", macchiato.child_value("today_tune_cnt")) + macchiatodict.replace_int_array("daily_milk_bonus", 9, macchiato.child_value("daily_milk_bonus")) + macchiatodict.replace_int("compensation_milk", macchiato.child_value("compensation_milk")) macchiatodict.replace_int("match_cnt", macchiato.child_value("match_cnt")) macchiatodict.replace_int("used_bean", macchiato.child_value("used_bean")) macchiatodict.replace_int("used_milk", macchiato.child_value("used_milk")) - macchiatodict.replace_int( - "daily_play_burst", macchiato.child_value("daily_play_burst") - ) + macchiatodict.replace_int("daily_play_burst", macchiato.child_value("daily_play_burst")) newprofile.replace_dict("macchiato", macchiatodict) # Get timestamps for played songs @@ -967,9 +884,7 @@ class JubeatSaucerFulfill( if flags & bit > 0: medal = max(medal, mapping[bit]) - self.update_score( - userid, timestamp, songid, chart, points, medal, combo, ghost - ) + self.update_score(userid, timestamp, songid, chart, points, medal, combo, ghost) # Grab the course results as well course = data.child("course") @@ -1002,9 +917,7 @@ class JubeatSaucerFulfill( return newprofile - def format_scores( - self, userid: UserID, profile: Profile, scores: List[Score] - ) -> Node: + def format_scores(self, userid: UserID, profile: Profile, scores: List[Score]) -> Node: root = Node.void("gametop") datanode = Node.void("data") root.add_child(datanode) @@ -1071,24 +984,12 @@ class JubeatSaucerFulfill( playdata.add_child(musicdata) musicdata.set_attribute("music_id", scoreid) - musicdata.add_child( - Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3)) - ) - musicdata.add_child( - Node.s32_array("score", scoredata.get_int_array("points", 3)) - ) - musicdata.add_child( - Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3)) - ) + musicdata.add_child(Node.s32_array("play_cnt", scoredata.get_int_array("play_cnt", 3))) + musicdata.add_child(Node.s32_array("clear_cnt", scoredata.get_int_array("clear_cnt", 3))) + musicdata.add_child(Node.s32_array("fc_cnt", scoredata.get_int_array("fc_cnt", 3))) + musicdata.add_child(Node.s32_array("ex_cnt", scoredata.get_int_array("ex_cnt", 3))) + musicdata.add_child(Node.s32_array("score", scoredata.get_int_array("points", 3))) + musicdata.add_child(Node.s8_array("clear", scoredata.get_int_array("clear_flags", 3))) ghosts = scoredata.get("ghost", [None, None, None]) for i in range(len(ghosts)): diff --git a/bemani/backend/mga/mga.py b/bemani/backend/mga/mga.py index 34f416a..3ed5911 100644 --- a/bemani/backend/mga/mga.py +++ b/bemani/backend/mga/mga.py @@ -52,7 +52,9 @@ class MetalGearArcade( if reqtype == "S_SRVMSG" and reqkey == "INFO": # Generate system message - settings1_str = "2011081000:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1" + settings1_str = ( + "2011081000:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1" + ) settings2_str = "1,1,1,1,1,1,1,1,1,1,1,1,1,1" # Send it to the client, making sure to inform the client that it was valid. @@ -82,9 +84,7 @@ class MetalGearArcade( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is None: root = Node.void("playerdata") - root.add_child( - Node.s32("result", 1) - ) # Unclear if this is the right thing to do here. + root.add_child(Node.s32("result", 1)) # Unclear if this is the right thing to do here. return root # Extract new profile info from old profile @@ -117,9 +117,7 @@ class MetalGearArcade( return self.format_profile(userid, profiletypes, profile) else: root = Node.void("playerdata") - root.add_child( - Node.s32("result", 1) - ) # Unclear if this is the right thing to do here. + root.add_child(Node.s32("result", 1)) # Unclear if this is the right thing to do here. return root def handle_playerdata_usergamedata_scorerank_request(self, request: Node) -> Node: @@ -151,9 +149,7 @@ class MetalGearArcade( userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is None: root = Node.void("matching") - root.add_child( - Node.s32("result", -1) - ) # Set to error so matching doesn't happen. + root.add_child(Node.s32("result", -1)) # Set to error so matching doesn't happen. return root # Game sends how long it intends to wait, so we should use that. @@ -162,21 +158,13 @@ class MetalGearArcade( # Look up active lobbies, see if there was a previous one for us. # Matchmaking takes at most 60 seconds, so assume any lobbies older # than this are dead. - lobbies = self.data.local.lobby.get_all_lobbies( - self.game, self.version, max_age=wait_time - ) + lobbies = self.data.local.lobby.get_all_lobbies(self.game, self.version, max_age=wait_time) previous_hosted_lobbies = [True for uid, _ in lobbies if uid == userid] - previous_joined_lobbies = [ - (uid, lobby) for uid, lobby in lobbies if userid in lobby["participants"] - ] + previous_joined_lobbies = [(uid, lobby) for uid, lobby in lobbies if userid in lobby["participants"]] # See if there's a random lobby we can be slotted into. Don't choose potentially # our old one, since it will be overwritten by a new entry, if we were ever a host. - nonfull_lobbies = [ - (uid, lobby) - for uid, lobby in lobbies - if len(lobby["participants"]) < lobby["lobbysize"] - ] + nonfull_lobbies = [(uid, lobby) for uid, lobby in lobbies if len(lobby["participants"]) < lobby["lobbysize"]] # Make sure to put our session information somewhere that we can find again. self.data.local.lobby.put_play_session_info( @@ -225,18 +213,10 @@ class MetalGearArcade( Node.s32("result", 1) ) # Setting this to 1 makes the client consider itself a guest and join a host. root.add_child(Node.s64("hostid", lobby.get_int("id"))) - root.add_child( - Node.string("hostip_g", host_play_session_info.get_str("joinip")) - ) - root.add_child( - Node.s32("hostport_g", host_play_session_info.get_int("joinport")) - ) - root.add_child( - Node.string("hostip_l", host_play_session_info.get_str("localip")) - ) - root.add_child( - Node.s32("hostport_l", host_play_session_info.get_int("localport")) - ) + root.add_child(Node.string("hostip_g", host_play_session_info.get_str("joinip"))) + root.add_child(Node.s32("hostport_g", host_play_session_info.get_int("joinport"))) + root.add_child(Node.string("hostip_l", host_play_session_info.get_str("localip"))) + root.add_child(Node.s32("hostport_l", host_play_session_info.get_int("localport"))) return root # The game does weird things if you let it wait as long as its own countdown, @@ -281,16 +261,11 @@ class MetalGearArcade( # List all lobbies out, find the one that we're either a host or a guest of. lobbies = self.data.local.lobby.get_all_lobbies(self.game, self.version) info_by_uid = { - uid: data - for uid, data in self.data.local.lobby.get_all_play_session_infos( - self.game, self.version - ) + uid: data for uid, data in self.data.local.lobby.get_all_play_session_infos(self.game, self.version) } # We should be able to filter by host_id that the game gave us. - joined_lobby = [ - (uid, lobby) for uid, lobby in lobbies if lobby.get_int("id") == host_id - ] + joined_lobby = [(uid, lobby) for uid, lobby in lobbies if lobby.get_int("id") == host_id] if len(joined_lobby) != 1: # This shouldn't happen. root = Node.void("matching") @@ -299,14 +274,10 @@ class MetalGearArcade( # Calculate creation time, figure out when to join the match after that. host_uid, lobby = joined_lobby[0] - time_left = max( - lobby.get_int("waittime") - (Time.now() - lobby.get_int("createtime")), 0 - ) + time_left = max(lobby.get_int("waittime") - (Time.now() - lobby.get_int("createtime")), 0) root = Node.void("matching") - root.add_child( - Node.s32("result", 0 if time_left > 0 else 1) - ) # We send 1 to start the match. + root.add_child(Node.s32("result", 0 if time_left > 0 else 1)) # We send 1 to start the match. root.add_child(Node.s32("prwtime", time_left)) matchlist = Node.void("matchlist") root.add_child(matchlist) @@ -339,9 +310,7 @@ class MetalGearArcade( return root - def format_profile( - self, userid: UserID, profiletypes: List[str], profile: Profile - ) -> Node: + def format_profile(self, userid: UserID, profiletypes: List[str], profile: Profile) -> Node: root = Node.void("playerdata") root.add_child(Node.s32("result", 0)) player = Node.void("player") @@ -371,9 +340,7 @@ class MetalGearArcade( strdata = b",".join(csvs[2:]) d = Node.string("d", base64.b64encode(strdata).decode("ascii")) record.add_child(d) - d.add_child( - Node.string("bin1", base64.b64encode(bindata).decode("ascii")) - ) + d.add_child(Node.string("bin1", base64.b64encode(bindata).decode("ascii"))) # Remember that we had this record records = records + 1 @@ -381,9 +348,7 @@ class MetalGearArcade( player.add_child(Node.u32("record_num", records)) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile, is_new: bool - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile, is_new: bool) -> Profile: # Profile save request, data values are base64 encoded. # d is a CSV, and bin1 is binary data. newprofile = oldprofile.clone() diff --git a/bemani/backend/museca/base.py b/bemani/backend/museca/base.py index cc3b96a..0b71dcf 100644 --- a/bemani/backend/museca/base.py +++ b/bemani/backend/museca/base.py @@ -95,9 +95,7 @@ class MusecaBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Now, return it return self.format_profile(userid, profile) - def new_profile_by_refid( - self, refid: Optional[str], name: Optional[str], locid: Optional[int] - ) -> Node: + def new_profile_by_refid(self, refid: Optional[str], name: Optional[str], locid: Optional[int]) -> Node: """ Given a RefID and an optional name, create a profile and then return a formatted profile node. Similar rationale to get_profile_by_refid. @@ -130,9 +128,7 @@ class MusecaBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("game") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -177,21 +173,14 @@ class MusecaBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): } # We saw an attempt, keep the total attempts in sync. - attempts[attempt.id][attempt.chart]["total"] = ( - attempts[attempt.id][attempt.chart]["total"] + 1 - ) + attempts[attempt.id][attempt.chart]["total"] = attempts[attempt.id][attempt.chart]["total"] + 1 - if ( - attempt.data.get_int("clear_type", self.CLEAR_TYPE_FAILED) - != self.CLEAR_TYPE_FAILED - ): + if attempt.data.get_int("clear_type", self.CLEAR_TYPE_FAILED) != self.CLEAR_TYPE_FAILED: # This attempt was a failure, so don't count it against clears of full combos continue # It was at least a clear - attempts[attempt.id][attempt.chart]["clears"] = ( - attempts[attempt.id][attempt.chart]["clears"] + 1 - ) + attempts[attempt.id][attempt.chart]["clears"] = attempts[attempt.id][attempt.chart]["clears"] + 1 # Merge in remote attempts for songid in remote_attempts: @@ -205,12 +194,8 @@ class MusecaBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): "clears": 0, } - attempts[songid][songchart]["total"] += remote_attempts[songid][ - songchart - ]["plays"] - attempts[songid][songchart]["clears"] += remote_attempts[songid][ - songchart - ]["clears"] + attempts[songid][songchart]["total"] += remote_attempts[songid][songchart]["plays"] + attempts[songid][songchart]["clears"] += remote_attempts[songid][songchart]["clears"] return attempts @@ -280,9 +265,7 @@ class MusecaBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): scoredata = oldscore.data # Replace grade and clear type - scoredata.replace_int( - "clear_type", max(scoredata.get_int("clear_type"), clear_type) - ) + scoredata.replace_int("clear_type", max(scoredata.get_int("clear_type"), clear_type)) history.replace_int("clear_type", clear_type) scoredata.replace_int("grade", max(scoredata.get_int("grade"), grade)) history.replace_int("grade", grade) diff --git a/bemani/backend/museca/common.py b/bemani/backend/museca/common.py index 1b9325e..e172f44 100644 --- a/bemani/backend/museca/common.py +++ b/bemani/backend/museca/common.py @@ -34,9 +34,7 @@ class MusecaGameHiscoreHandler(MusecaBase): # Now, grab user records records = self.data.remote.music.get_all_records(self.game, self.version) - users = { - uid: prof for (uid, prof) in self.get_any_profiles([r[0] for r in records]) - } + users = {uid: prof for (uid, prof) in self.get_any_profiles([r[0] for r in records])} hiscore_allover = Node.void("hiscore_allover") game.add_child(hiscore_allover) @@ -61,14 +59,10 @@ class MusecaGameHiscoreHandler(MusecaBase): # Now, grab local records area_users = [ uid - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) + for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version) if prof.get_int("loc", -1) == locid ] - records = self.data.local.music.get_all_records( - self.game, self.version, userlist=area_users - ) + records = self.data.local.music.get_all_records(self.game, self.version, userlist=area_users) missing_players = [uid for (uid, _) in records if uid not in users] for uid, prof in self.get_any_profiles(missing_players): users[uid] = prof @@ -101,9 +95,7 @@ class MusecaGameHiscoreHandler(MusecaBase): for songid in clears: for chart in clears[songid]: if clears[songid][chart]["total"] > 0: - rate = float(clears[songid][chart]["clears"]) / float( - clears[songid][chart]["total"] - ) + rate = float(clears[songid][chart]["clears"]) / float(clears[songid][chart]["total"]) dnode = Node.void("d") clear_rate.add_child(dnode) dnode.add_child(Node.u32("id", songid)) diff --git a/bemani/backend/museca/museca1.py b/bemani/backend/museca/museca1.py index b9fd059..653f1f1 100644 --- a/bemani/backend/museca/museca1.py +++ b/bemani/backend/museca/museca1.py @@ -177,9 +177,7 @@ class Museca1( userid = None if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -201,11 +199,7 @@ class Museca1( self.db_to_game_clear_type(score.data.get_int("clear_type")), ) ) - music.add_child( - Node.u32( - "score_grade", self.db_to_game_grade(score.data.get_int("grade")) - ) - ) + music.add_child(Node.u32("score_grade", self.db_to_game_grade(score.data.get_int("grade")))) stats = score.data.get_dict("stats") music.add_child(Node.u32("btn_rate", stats.get_int("btn_rate"))) music.add_child(Node.u32("long_rate", stats.get_int("long_rate"))) @@ -222,9 +216,7 @@ class Museca1( game.add_child(Node.u32("gamecoin_packet", profile.get_int("packet"))) game.add_child(Node.u32("gamecoin_block", profile.get_int("block"))) game.add_child(Node.s16("skill_name_id", profile.get_int("skill_name_id", -1))) - game.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20)) - ) + game.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20))) game.add_child(Node.u32("blaster_energy", profile.get_int("blaster_energy"))) game.add_child(Node.u32("blaster_count", profile.get_int("blaster_count"))) @@ -253,19 +245,14 @@ class Museca1( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": continue itemtype = int(item.type[5:]) - if ( - game_config.get_bool("force_unlock_songs") - and itemtype == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and itemtype == self.GAME_CATALOG_TYPE_SONG: # Don't echo unlocked songs, we will add all of them later continue @@ -299,22 +286,16 @@ class Museca1( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -325,9 +306,7 @@ class Museca1( # Miscelaneous stuff newprofile.replace_int("blaster_count", request.child_value("blaster_count")) newprofile.replace_int("skill_name_id", request.child_value("skill_name_id")) - newprofile.replace_int_array( - "hidden_param", 20, request.child_value("hidden_param") - ) + newprofile.replace_int_array("hidden_param", 20, request.child_value("hidden_param")) # Update user's unlock status if we aren't force unlocked game_config = self.get_game_config() @@ -342,10 +321,7 @@ class Museca1( param = child.child_value("param") diff_param = child.child_value("diff_param") - if ( - game_config.get_bool("force_unlock_songs") - and item_type == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and item_type == self.GAME_CATALOG_TYPE_SONG: # Don't save back songs, because they were force unlocked continue diff --git a/bemani/backend/museca/museca1plus.py b/bemani/backend/museca/museca1plus.py index 080c30b..f7dc418 100644 --- a/bemani/backend/museca/museca1plus.py +++ b/bemani/backend/museca/museca1plus.py @@ -309,9 +309,7 @@ class Museca1Plus( userid = None if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -334,11 +332,7 @@ class Museca1Plus( self.db_to_game_clear_type(score.data.get_int("clear_type")), ) ) - music.add_child( - Node.u32( - "score_grade", self.db_to_game_grade(score.data.get_int("grade")) - ) - ) + music.add_child(Node.u32("score_grade", self.db_to_game_grade(score.data.get_int("grade")))) stats = score.data.get_dict("stats") music.add_child(Node.u32("btn_rate", stats.get_int("btn_rate"))) music.add_child(Node.u32("long_rate", stats.get_int("long_rate"))) @@ -355,9 +349,7 @@ class Museca1Plus( game.add_child(Node.u32("gamecoin_packet", profile.get_int("packet"))) game.add_child(Node.u32("gamecoin_block", profile.get_int("block"))) game.add_child(Node.s16("skill_name_id", profile.get_int("skill_name_id", -1))) - game.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20)) - ) + game.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20))) game.add_child(Node.u32("blaster_energy", profile.get_int("blaster_energy"))) game.add_child(Node.u32("blaster_count", profile.get_int("blaster_count"))) @@ -391,19 +383,14 @@ class Museca1Plus( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": continue itemtype = int(item.type[5:]) - if ( - game_config.get_bool("force_unlock_songs") - and itemtype == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and itemtype == self.GAME_CATALOG_TYPE_SONG: # Don't echo unlocked songs, we will add all of them later continue @@ -437,22 +424,16 @@ class Museca1Plus( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -463,9 +444,7 @@ class Museca1Plus( # Miscelaneous stuff newprofile.replace_int("blaster_count", request.child_value("blaster_count")) newprofile.replace_int("skill_name_id", request.child_value("skill_name_id")) - newprofile.replace_int_array( - "hidden_param", 20, request.child_value("hidden_param") - ) + newprofile.replace_int_array("hidden_param", 20, request.child_value("hidden_param")) # Update user's unlock status if we aren't force unlocked game_config = self.get_game_config() @@ -480,10 +459,7 @@ class Museca1Plus( param = child.child_value("param") diff_param = child.child_value("diff_param") - if ( - game_config.get_bool("force_unlock_songs") - and item_type == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and item_type == self.GAME_CATALOG_TYPE_SONG: # Don't save back songs, because they were force unlocked continue diff --git a/bemani/backend/popn/base.py b/bemani/backend/popn/base.py index 01397ea..5876106 100644 --- a/bemani/backend/popn/base.py +++ b/bemani/backend/popn/base.py @@ -28,30 +28,16 @@ class PopnMusicBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Play medals, as saved into/loaded from the DB PLAY_MEDAL_NO_PLAY: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_NO_PLAY - PLAY_MEDAL_CIRCLE_FAILED: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FAILED - PLAY_MEDAL_DIAMOND_FAILED: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_FAILED + PLAY_MEDAL_CIRCLE_FAILED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FAILED + PLAY_MEDAL_DIAMOND_FAILED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_FAILED PLAY_MEDAL_STAR_FAILED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_STAR_FAILED PLAY_MEDAL_EASY_CLEAR: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_EASY_CLEAR - PLAY_MEDAL_CIRCLE_CLEARED: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_CLEARED - PLAY_MEDAL_DIAMOND_CLEARED: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_CLEARED + PLAY_MEDAL_CIRCLE_CLEARED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_CLEARED + PLAY_MEDAL_DIAMOND_CLEARED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_CLEARED PLAY_MEDAL_STAR_CLEARED: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_STAR_CLEARED - PLAY_MEDAL_CIRCLE_FULL_COMBO: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FULL_COMBO - PLAY_MEDAL_DIAMOND_FULL_COMBO: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_FULL_COMBO - PLAY_MEDAL_STAR_FULL_COMBO: Final[ - int - ] = DBConstants.POPN_MUSIC_PLAY_MEDAL_STAR_FULL_COMBO + PLAY_MEDAL_CIRCLE_FULL_COMBO: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FULL_COMBO + PLAY_MEDAL_DIAMOND_FULL_COMBO: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_FULL_COMBO + PLAY_MEDAL_STAR_FULL_COMBO: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_STAR_FULL_COMBO PLAY_MEDAL_PERFECT: Final[int] = DBConstants.POPN_MUSIC_PLAY_MEDAL_PERFECT # Chart type, as saved into/loaded from the DB, and returned to game @@ -107,9 +93,7 @@ class PopnMusicBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("playerdata") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -117,9 +101,7 @@ class PopnMusicBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return oldprofile - def get_profile_by_refid( - self, refid: Optional[str], load_mode: int - ) -> Optional[Node]: + def get_profile_by_refid(self, refid: Optional[str], load_mode: int) -> Optional[Node]: """ Given a RefID, return a formatted profile node. Basically every game needs a profile lookup, even if it handles where that happens in @@ -341,9 +323,7 @@ class PopnMusicBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): ) -> None: # Generate scorecard profile = self.get_profile(userid) - song = self.data.local.music.get_song( - self.game, self.music_version, songid, chart - ) + song = self.data.local.music.get_song(self.game, self.music_version, songid, chart) card_medal = { self.PLAY_MEDAL_CIRCLE_FAILED: "Failed", diff --git a/bemani/backend/popn/common.py b/bemani/backend/popn/common.py index ee5f94c..6d7a6b6 100644 --- a/bemani/backend/popn/common.py +++ b/bemani/backend/popn/common.py @@ -55,22 +55,15 @@ class PopnMusicModernBase(PopnMusicBase, ABC): ] @classmethod - def run_scheduled_work( - cls, data: Data, config: Dict[str, Any] - ) -> List[Tuple[str, Dict[str, Any]]]: + def run_scheduled_work(cls, data: Data, config: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any]]]: """ Once a week, insert a new course. """ events = [] - if data.local.network.should_schedule( - cls.game, cls.version, "course", "weekly" - ): + if data.local.network.should_schedule(cls.game, cls.version, "course", "weekly"): # Generate a new course list, save it to the DB. start_time, end_time = data.local.network.get_schedule_duration("weekly") - all_songs = [ - song.id - for song in data.local.music.get_all_songs(cls.game, cls.version) - ] + all_songs = [song.id for song in data.local.music.get_all_songs(cls.game, cls.version)] if all_songs: course_song = random.choice(all_songs) data.local.game.put_time_sensitive_settings( @@ -94,9 +87,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): ) # Mark that we did some actual work here. - data.local.network.mark_scheduled( - cls.game, cls.version, "course", "weekly" - ) + data.local.network.mark_scheduled(cls.game, cls.version, "course", "weekly") return events def __score_to_rank(self, score: int) -> int: @@ -152,12 +143,8 @@ class PopnMusicModernBase(PopnMusicBase, ABC): # Gather course information and course ranking for users. course_infos, achievements, profiles = Parallel.execute( [ - lambda: self.data.local.game.get_all_time_sensitive_settings( - self.game, self.version, "course" - ), - lambda: self.data.local.user.get_all_achievements( - self.game, self.version - ), + lambda: self.data.local.game.get_all_time_sensitive_settings(self.game, self.version, "course"), + lambda: self.data.local.user.get_all_achievements(self.game, self.version), lambda: self.data.local.user.get_all_profiles(self.game, self.version), ] ) @@ -168,9 +155,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): reverse=True, ) # Sort achievements within course ID from best to worst ranking. - achievements_by_course_id: Dict[ - int, Dict[str, List[Tuple[UserID, Achievement]]] - ] = {} + achievements_by_course_id: Dict[int, Dict[str, List[Tuple[UserID, Achievement]]]] = {} type_to_chart_lut: Dict[str, str] = { f"course_{self.GAME_CHART_TYPE_EASY}": "loc_ranking_e", f"course_{self.GAME_CHART_TYPE_NORMAL}": "loc_ranking_n", @@ -187,9 +172,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): "loc_ranking_h": [], "loc_ranking_ex": [], } - achievements_by_course_id[ach.id][type_to_chart_lut[ach.type]].append( - (uid, ach) - ) + achievements_by_course_id[ach.id][type_to_chart_lut[ach.type]].append((uid, ach)) for courseid in achievements_by_course_id: for chart in [ "loc_ranking_e", @@ -204,9 +187,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): ) # Cache of userID to profile - userid_to_profile: Dict[UserID, Profile] = { - uid: profile for (uid, profile) in profiles - } + userid_to_profile: Dict[UserID, Profile] = {uid: profile for (uid, profile) in profiles} # Course ranking info for the last 256 courses for course_info in course_infos[:256]: @@ -216,9 +197,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): ranking_info = Node.void("ranking_info") root.add_child(ranking_info) ranking_info.add_child(Node.s16("course_id", course_id)) - ranking_info.add_child( - Node.u64("start_date", course_info["start_time"] * 1000) - ) + ranking_info.add_child(Node.u64("start_date", course_info["start_time"] * 1000)) ranking_info.add_child(Node.u64("end_date", course_info["end_time"] * 1000)) ranking_info.add_child(Node.s32("music_id", course_info["music"])) @@ -232,26 +211,16 @@ class PopnMusicModernBase(PopnMusicBase, ABC): chart_rankings = course_rankings.get(name, []) for pos, (uid, ach) in enumerate(chart_rankings[:20]): - profile = userid_to_profile.get( - uid, Profile(self.game, self.version, "", 0) - ) + profile = userid_to_profile.get(uid, Profile(self.game, self.version, "", 0)) subnode = Node.void(name) ranking_info.add_child(subnode) subnode.add_child(Node.s16("rank", pos + 1)) subnode.add_child(Node.string("name", profile.get_str("name"))) - subnode.add_child( - Node.s16("chara_num", profile.get_int("chara", -1)) - ) - subnode.add_child( - Node.s32("total_score", ach.data.get_int("score")) - ) - subnode.add_child( - Node.u8("clear_type", ach.data.get_int("clear_type")) - ) - subnode.add_child( - Node.u8("clear_rank", ach.data.get_int("clear_rank")) - ) + subnode.add_child(Node.s16("chara_num", profile.get_int("chara", -1))) + subnode.add_child(Node.s32("total_score", ach.data.get_int("score"))) + subnode.add_child(Node.u8("clear_type", ach.data.get_int("clear_type"))) + subnode.add_child(Node.u8("clear_rank", ach.data.get_int("clear_rank"))) if send_areas: for area_id in range(1, 16): @@ -327,9 +296,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): popular.add_child(Node.s16("chara_num", charaid)) # Top 500 Popular music - for songid, _plays in self.data.local.music.get_hit_chart( - self.game, self.music_version, 500 - ): + for songid, _plays in self.data.local.music.get_hit_chart(self.game, self.music_version, 500): popular_music = Node.void("popular_music") root.add_child(popular_music) popular_music.add_child(Node.s16("music_num", songid)) @@ -418,9 +385,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): userid = None if userid is not None: - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: @@ -480,34 +445,23 @@ class PopnMusicModernBase(PopnMusicBase, ABC): # Handle fetching all scores uids_and_courses, profile = Parallel.execute( [ - lambda: self.data.local.user.get_all_achievements( - self.game, self.version - ), - lambda: self.get_profile(userid) - or Profile(self.game, self.version, "", 0), + lambda: self.data.local.user.get_all_achievements(self.game, self.version), + lambda: self.get_profile(userid) or Profile(self.game, self.version, "", 0), ] ) # Grab a sorted list of all scores for this course and chart global_uids_and_courses = sorted( - [ - (uid, ach) - for (uid, ach) in uids_and_courses - if ach.type == course_type and ach.id == course_id - ], + [(uid, ach) for (uid, ach) in uids_and_courses if ach.type == course_type and ach.id == course_id], key=lambda uid_and_course: uid_and_course[1].data.get_int("score"), reverse=True, ) # Grab smaller lists that contain only sorted for our prefecture/location pref_uids_and_courses = [ - (uid, ach) - for (uid, ach) in global_uids_and_courses - if ach.data.get_int("pref") == prefecture + (uid, ach) for (uid, ach) in global_uids_and_courses if ach.data.get_int("pref") == prefecture ] loc_uids_and_courses = [ - (uid, ach) - for (uid, ach) in global_uids_and_courses - if ach.data.get_int("lid") == loc_id + (uid, ach) for (uid, ach) in global_uids_and_courses if ach.data.get_int("lid") == loc_id ] def _get_rank(uac: List[Tuple[UserID, Achievement]]) -> Optional[int]: @@ -575,17 +529,13 @@ class PopnMusicModernBase(PopnMusicBase, ABC): return root rivalid = links[no].other_userid rivalprofile = profiles[rivalid] - scores = self.data.remote.music.get_scores( - self.game, self.music_version, rivalid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, rivalid) # First, output general profile info. friend = Node.void("friend") root.add_child(friend) friend.add_child(Node.s16("no", no)) - friend.add_child( - Node.string("g_pm_id", self.format_extid(rivalprofile.extid)) - ) # UsaNeko formats on its own + friend.add_child(Node.string("g_pm_id", self.format_extid(rivalprofile.extid))) # UsaNeko formats on its own friend.add_child(Node.string("name", rivalprofile.get_str("name", "なし"))) friend.add_child(Node.s16("chara_num", rivalprofile.get_int("chara", -1))) # This might be for having non-active or non-confirmed friends, but setting to 0 makes the @@ -642,9 +592,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): ), ) - achievements = self.data.local.user.get_achievements( - self.game, self.version, rivalid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, rivalid) for achievement in achievements: if achievement.type[:7] == "course_": sheet = int(achievement.type[7:]) @@ -652,18 +600,10 @@ class PopnMusicModernBase(PopnMusicBase, ABC): course_data = Node.void("course_data") root.add_child(course_data) course_data.add_child(Node.s16("course_id", achievement.id)) - course_data.add_child( - Node.u8("clear_type", achievement.data.get_int("clear_type")) - ) - course_data.add_child( - Node.u8("clear_rank", achievement.data.get_int("clear_rank")) - ) - course_data.add_child( - Node.s32("total_score", achievement.data.get_int("score")) - ) - course_data.add_child( - Node.s32("update_count", achievement.data.get_int("count")) - ) + course_data.add_child(Node.u8("clear_type", achievement.data.get_int("clear_type"))) + course_data.add_child(Node.u8("clear_rank", achievement.data.get_int("clear_rank"))) + course_data.add_child(Node.s32("total_score", achievement.data.get_int("score"))) + course_data.add_child(Node.s32("update_count", achievement.data.get_int("count"))) course_data.add_child(Node.u8("sheet_num", sheet)) return root @@ -675,9 +615,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): return Node.void("player24") root = Node.void("player24") - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: # Skip any scores for chart types we don't support if score.chart not in [ @@ -768,9 +706,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): self.GAME_PLAY_MEDAL_STAR_FULL_COMBO: self.PLAY_MEDAL_STAR_FULL_COMBO, self.GAME_PLAY_MEDAL_PERFECT: self.PLAY_MEDAL_PERFECT, }[medal] - self.update_score( - userid, songid, chart, points, medal, combo=combo, stats=stats - ) + self.update_score(userid, songid, chart, points, medal, combo=combo, stats=stats) if request.child_value("is_image_store") == 1: self.broadcast_score(userid, songid, chart, medal, points, combo, stats) @@ -804,9 +740,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): if lumina >= price: # Update player lumina balance - profile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + profile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) profile.replace_int("player_point", lumina - price) self.put_profile(userid, profile) @@ -833,9 +767,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): root.add_child(Node.s8("result", 1)) # Scores - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: # Skip any scores for chart types we don't support if score.chart not in [ @@ -905,57 +837,31 @@ class PopnMusicModernBase(PopnMusicBase, ABC): account.add_child(Node.s16("area_id", profile.get_int("area_id"))) account.add_child(Node.s16("use_navi", profile.get_int("use_navi"))) account.add_child(Node.s16("read_news", profile.get_int("read_news"))) - account.add_child( - Node.s16_array("nice", profile.get_int_array("nice", 30, [-1] * 30)) - ) - account.add_child( - Node.s16_array( - "favorite_chara", profile.get_int_array("favorite_chara", 20, [-1] * 20) - ) - ) - account.add_child( - Node.s16_array( - "special_area", profile.get_int_array("special_area", 8, [-1] * 8) - ) - ) + account.add_child(Node.s16_array("nice", profile.get_int_array("nice", 30, [-1] * 30))) + account.add_child(Node.s16_array("favorite_chara", profile.get_int_array("favorite_chara", 20, [-1] * 20))) + account.add_child(Node.s16_array("special_area", profile.get_int_array("special_area", 8, [-1] * 8))) account.add_child( Node.s16_array( "chocolate_charalist", profile.get_int_array("chocolate_charalist", 5, [-1] * 5), ) ) - account.add_child( - Node.s32("chocolate_sp_chara", profile.get_int("chocolate_sp_chara", -1)) - ) - account.add_child( - Node.s32("chocolate_pass_cnt", profile.get_int("chocolate_pass_cnt")) - ) - account.add_child( - Node.s32("chocolate_hon_cnt", profile.get_int("chocolate_hon_cnt")) - ) + account.add_child(Node.s32("chocolate_sp_chara", profile.get_int("chocolate_sp_chara", -1))) + account.add_child(Node.s32("chocolate_pass_cnt", profile.get_int("chocolate_pass_cnt"))) + account.add_child(Node.s32("chocolate_hon_cnt", profile.get_int("chocolate_hon_cnt"))) account.add_child( Node.s16_array( "teacher_setting", profile.get_int_array("teacher_setting", 10, [-1] * 10), ) ) - account.add_child( - Node.bool("welcom_pack", False) - ) # Set to true to grant extra stage no matter what. + account.add_child(Node.bool("welcom_pack", False)) # Set to true to grant extra stage no matter what. account.add_child(Node.s32("ranking_node", profile.get_int("ranking_node"))) - account.add_child( - Node.s32("chara_ranking_kind_id", profile.get_int("chara_ranking_kind_id")) - ) - account.add_child( - Node.s8("navi_evolution_flg", profile.get_int("navi_evolution_flg")) - ) - account.add_child( - Node.s32("ranking_news_last_no", profile.get_int("ranking_news_last_no")) - ) + account.add_child(Node.s32("chara_ranking_kind_id", profile.get_int("chara_ranking_kind_id"))) + account.add_child(Node.s8("navi_evolution_flg", profile.get_int("navi_evolution_flg"))) + account.add_child(Node.s32("ranking_news_last_no", profile.get_int("ranking_news_last_no"))) account.add_child(Node.s32("power_point", profile.get_int("power_point"))) - account.add_child( - Node.s32("player_point", profile.get_int("player_point", 300)) - ) + account.add_child(Node.s32("player_point", profile.get_int("player_point", 300))) account.add_child( Node.s32_array( "power_point_list", @@ -1039,18 +945,8 @@ class PopnMusicModernBase(PopnMusicBase, ABC): account.add_child(Node.s16_array("license_data", [-1] * 20)) # Song statistics - last_played = [ - x[0] - for x in self.data.local.music.get_last_played( - self.game, self.music_version, userid, 10 - ) - ] - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) - ] + last_played = [x[0] for x in self.data.local.music.get_last_played(self.game, self.music_version, userid, 10)] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20)] while len(last_played) < 10: last_played.append(-1) while len(most_played) < 20: @@ -1104,14 +1000,10 @@ class PopnMusicModernBase(PopnMusicBase, ABC): config.add_child(Node.u8("sheet", profile.get_int("sheet"))) config.add_child(Node.s8("category", profile.get_int("category", -1))) config.add_child(Node.s8("sub_category", profile.get_int("sub_category", -1))) - config.add_child( - Node.s8("chara_category", profile.get_int("chara_category", -1)) - ) + config.add_child(Node.s8("chara_category", profile.get_int("chara_category", -1))) config.add_child(Node.s16("course_id", profile.get_int("course_id", -1))) config.add_child(Node.s8("course_folder", profile.get_int("course_folder", -1))) - config.add_child( - Node.s8("ms_banner_disp", profile.get_int("ms_banner_disp", -1)) - ) + config.add_child(Node.s8("ms_banner_disp", profile.get_int("ms_banner_disp", -1))) config.add_child(Node.s8("ms_down_info", profile.get_int("ms_down_info", -1))) config.add_child(Node.s8("ms_side_info", profile.get_int("ms_side_info", -1))) config.add_child(Node.s8("ms_raise_type", profile.get_int("ms_raise_type", -1))) @@ -1134,9 +1026,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): option.add_child(Node.u8("ojama_1", option_dict.get_int("ojama_1"))) option.add_child(Node.bool("forever_0", option_dict.get_bool("forever_0"))) option.add_child(Node.bool("forever_1", option_dict.get_bool("forever_1"))) - option.add_child( - Node.bool("full_setting", option_dict.get_bool("full_setting")) - ) + option.add_child(Node.bool("full_setting", option_dict.get_bool("full_setting"))) option.add_child(Node.u8("judge", option_dict.get_int("judge"))) option.add_child(Node.s8("guide_se", option_dict.get_int("guide_se"))) @@ -1155,18 +1045,11 @@ class PopnMusicModernBase(PopnMusicBase, ABC): navi_data = Node.void("navi_data") root.add_child(navi_data) if "navi_points" in profile: - navi_data.add_child( - Node.s32_array("raisePoint", profile.get_int_array("navi_points", 5)) - ) + navi_data.add_child(Node.s32_array("raisePoint", profile.get_int_array("navi_points", 5))) game_config = self.get_game_config() if game_config.get_bool("force_unlock_songs"): - songs = { - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - } + songs = {song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)} for song in songs: item = Node.void("item") root.add_child(item) @@ -1177,9 +1060,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): item.add_child(Node.u64("get_time", 0)) # Set up achievements - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for achievement in achievements: if achievement.type[:5] == "item_": itemtype = int(achievement.type[5:]) @@ -1243,18 +1124,10 @@ class PopnMusicModernBase(PopnMusicBase, ABC): course_data = Node.void("course_data") root.add_child(course_data) course_data.add_child(Node.s16("course_id", achievement.id)) - course_data.add_child( - Node.u8("clear_type", achievement.data.get_int("clear_type")) - ) - course_data.add_child( - Node.u8("clear_rank", achievement.data.get_int("clear_rank")) - ) - course_data.add_child( - Node.s32("total_score", achievement.data.get_int("score")) - ) - course_data.add_child( - Node.s32("update_count", achievement.data.get_int("count")) - ) + course_data.add_child(Node.u8("clear_type", achievement.data.get_int("clear_type"))) + course_data.add_child(Node.u8("clear_rank", achievement.data.get_int("clear_rank"))) + course_data.add_child(Node.s32("total_score", achievement.data.get_int("score"))) + course_data.add_child(Node.s32("update_count", achievement.data.get_int("count"))) course_data.add_child(Node.u8("sheet_num", sheet)) elif achievement.type == "fes": @@ -1340,9 +1213,7 @@ class PopnMusicModernBase(PopnMusicBase, ABC): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() account = request.child("account") @@ -1352,49 +1223,23 @@ class PopnMusicModernBase(PopnMusicBase, ABC): newprofile.replace_int("area_id", account.child_value("area_id")) newprofile.replace_int("use_navi", account.child_value("use_navi")) newprofile.replace_int("ranking_node", account.child_value("ranking_node")) - newprofile.replace_int( - "chara_ranking_kind_id", account.child_value("chara_ranking_kind_id") - ) - newprofile.replace_int( - "navi_evolution_flg", account.child_value("navi_evolution_flg") - ) - newprofile.replace_int( - "ranking_news_last_no", account.child_value("ranking_news_last_no") - ) + newprofile.replace_int("chara_ranking_kind_id", account.child_value("chara_ranking_kind_id")) + newprofile.replace_int("navi_evolution_flg", account.child_value("navi_evolution_flg")) + newprofile.replace_int("ranking_news_last_no", account.child_value("ranking_news_last_no")) newprofile.replace_int("power_point", account.child_value("power_point")) newprofile.replace_int("player_point", account.child_value("player_point")) newprofile.replace_int_array("nice", 30, account.child_value("nice")) - newprofile.replace_int_array( - "favorite_chara", 20, account.child_value("favorite_chara") - ) - newprofile.replace_int_array( - "special_area", 8, account.child_value("special_area") - ) - newprofile.replace_int_array( - "chocolate_charalist", 5, account.child_value("chocolate_charalist") - ) - newprofile.replace_int( - "chocolate_sp_chara", account.child_value("chocolate_sp_chara") - ) - newprofile.replace_int( - "chocolate_pass_cnt", account.child_value("chocolate_pass_cnt") - ) - newprofile.replace_int( - "chocolate_hon_cnt", account.child_value("chocolate_hon_cnt") - ) - newprofile.replace_int( - "chocolate_giri_cnt", account.child_value("chocolate_giri_cnt") - ) - newprofile.replace_int( - "chocolate_kokyu_cnt", account.child_value("chocolate_kokyu_cnt") - ) - newprofile.replace_int_array( - "teacher_setting", 10, account.child_value("teacher_setting") - ) - newprofile.replace_int_array( - "power_point_list", 20, account.child_value("power_point_list") - ) + newprofile.replace_int_array("favorite_chara", 20, account.child_value("favorite_chara")) + newprofile.replace_int_array("special_area", 8, account.child_value("special_area")) + newprofile.replace_int_array("chocolate_charalist", 5, account.child_value("chocolate_charalist")) + newprofile.replace_int("chocolate_sp_chara", account.child_value("chocolate_sp_chara")) + newprofile.replace_int("chocolate_pass_cnt", account.child_value("chocolate_pass_cnt")) + newprofile.replace_int("chocolate_hon_cnt", account.child_value("chocolate_hon_cnt")) + newprofile.replace_int("chocolate_giri_cnt", account.child_value("chocolate_giri_cnt")) + newprofile.replace_int("chocolate_kokyu_cnt", account.child_value("chocolate_kokyu_cnt")) + newprofile.replace_int_array("teacher_setting", 10, account.child_value("teacher_setting")) + newprofile.replace_int_array("power_point_list", 20, account.child_value("power_point_list")) info = request.child("info") if info is not None: @@ -1413,14 +1258,10 @@ class PopnMusicModernBase(PopnMusicBase, ABC): newprofile.replace_int("sheet", config.child_value("sheet")) newprofile.replace_int("category", config.child_value("category")) newprofile.replace_int("sub_category", config.child_value("sub_category")) - newprofile.replace_int( - "chara_category", config.child_value("chara_category") - ) + newprofile.replace_int("chara_category", config.child_value("chara_category")) newprofile.replace_int("course_id", config.child_value("course_id")) newprofile.replace_int("course_folder", config.child_value("course_folder")) - newprofile.replace_int( - "ms_banner_disp", config.child_value("ms_banner_disp") - ) + newprofile.replace_int("ms_banner_disp", config.child_value("ms_banner_disp")) newprofile.replace_int("ms_down_info", config.child_value("ms_down_info")) newprofile.replace_int("ms_side_info", config.child_value("ms_side_info")) newprofile.replace_int("ms_raise_type", config.child_value("ms_raise_type")) @@ -1450,21 +1291,15 @@ class PopnMusicModernBase(PopnMusicBase, ABC): customize = request.child("customize") if customize is not None: newprofile.replace_int("effect_left", customize.child_value("effect_left")) - newprofile.replace_int( - "effect_center", customize.child_value("effect_center") - ) - newprofile.replace_int( - "effect_right", customize.child_value("effect_right") - ) + newprofile.replace_int("effect_center", customize.child_value("effect_center")) + newprofile.replace_int("effect_right", customize.child_value("effect_right")) newprofile.replace_int("hukidashi", customize.child_value("hukidashi")) newprofile.replace_int("comment_1", customize.child_value("comment_1")) newprofile.replace_int("comment_2", customize.child_value("comment_2")) navi_data = request.child("navi_data") if navi_data is not None: - newprofile.replace_int_array( - "navi_points", 5, navi_data.child_value("raisePoint") - ) + newprofile.replace_int_array("navi_points", 5, navi_data.child_value("raisePoint")) # Extract navi achievements for node in navi_data.children: diff --git a/bemani/backend/popn/eclale.py b/bemani/backend/popn/eclale.py index 58a75e8..3529186 100644 --- a/bemani/backend/popn/eclale.py +++ b/bemani/backend/popn/eclale.py @@ -209,9 +209,7 @@ class PopnMusicEclale(PopnMusicBase): rank = rank + 1 # Output the hit chart - for songid, _plays in self.data.local.music.get_hit_chart( - self.game, self.music_version, 500 - ): + for songid, _plays in self.data.local.music.get_hit_chart(self.game, self.music_version, 500): popular_music = Node.void("popular_music") root.add_child(popular_music) popular_music.add_child(Node.s16("music_num", songid)) @@ -285,9 +283,7 @@ class PopnMusicEclale(PopnMusicBase): userid = None if userid is not None: - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: @@ -332,9 +328,7 @@ class PopnMusicEclale(PopnMusicBase): if lumina >= price: # Update player lumina balance - profile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + profile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) profile.replace_int("lumina", lumina - price) self.put_profile(userid, profile) @@ -360,9 +354,7 @@ class PopnMusicEclale(PopnMusicBase): userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) else: scores = [] @@ -453,17 +445,13 @@ class PopnMusicEclale(PopnMusicBase): return root rivalid = links[no].other_userid rivalprofile = profiles[rivalid] - scores = self.data.remote.music.get_scores( - self.game, self.music_version, rivalid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, rivalid) # First, output general profile info. friend = Node.void("friend") root.add_child(friend) friend.add_child(Node.s16("no", no)) - friend.add_child( - Node.string("g_pm_id", self.format_extid(rivalprofile.extid)) - ) # Eclale formats on its own + friend.add_child(Node.string("g_pm_id", self.format_extid(rivalprofile.extid))) # Eclale formats on its own friend.add_child(Node.string("name", rivalprofile.get_str("name", "なし"))) friend.add_child(Node.s16("chara_num", rivalprofile.get_int("chara", -1))) # This might be for having non-active or non-confirmed friends, but setting to 0 makes the @@ -561,9 +549,7 @@ class PopnMusicEclale(PopnMusicBase): self.GAME_PLAY_MEDAL_STAR_FULL_COMBO: self.PLAY_MEDAL_STAR_FULL_COMBO, self.GAME_PLAY_MEDAL_PERFECT: self.PLAY_MEDAL_PERFECT, }[medal] - self.update_score( - userid, songid, chart, points, medal, combo=combo, stats=stats - ) + self.update_score(userid, songid, chart, points, medal, combo=combo, stats=stats) if request.child_value("is_image_store") == 1: self.broadcast_score(userid, songid, chart, medal, points, combo, stats) @@ -577,9 +563,7 @@ class PopnMusicEclale(PopnMusicBase): root.add_child(Node.s8("result", 1)) # Scores - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: # Skip any scores for chart types we don't support if score.chart not in [ @@ -649,34 +633,18 @@ class PopnMusicEclale(PopnMusicBase): account.add_child(Node.s16("area_id", profile.get_int("area_id"))) account.add_child(Node.s16("lumina", profile.get_int("lumina", 300))) account.add_child(Node.s16("read_news", profile.get_int("read_news"))) - account.add_child( - Node.bool("welcom_pack", False) - ) # Set this to true to grant extra stage no matter what. - account.add_child( - Node.s16_array("medal_set", profile.get_int_array("medal_set", 4)) - ) - account.add_child( - Node.s16_array("nice", profile.get_int_array("nice", 30, [-1] * 30)) - ) - account.add_child( - Node.s16_array( - "favorite_chara", profile.get_int_array("favorite_chara", 20, [-1] * 20) - ) - ) - account.add_child( - Node.s16_array("special_area", profile.get_int_array("special_area", 8)) - ) + account.add_child(Node.bool("welcom_pack", False)) # Set this to true to grant extra stage no matter what. + account.add_child(Node.s16_array("medal_set", profile.get_int_array("medal_set", 4))) + account.add_child(Node.s16_array("nice", profile.get_int_array("nice", 30, [-1] * 30))) + account.add_child(Node.s16_array("favorite_chara", profile.get_int_array("favorite_chara", 20, [-1] * 20))) + account.add_child(Node.s16_array("special_area", profile.get_int_array("special_area", 8))) account.add_child( Node.s16_array( "chocolate_charalist", profile.get_int_array("chocolate_charalist", 5, [-1] * 5), ) ) - account.add_child( - Node.s16_array( - "teacher_setting", profile.get_int_array("teacher_setting", 10) - ) - ) + account.add_child(Node.s16_array("teacher_setting", profile.get_int_array("teacher_setting", 10))) # Stuff we never change account.add_child(Node.s8("staff", 0)) @@ -687,18 +655,8 @@ class PopnMusicEclale(PopnMusicBase): account.add_child(Node.s16_array("license_data", [-1] * 20)) # Add statistics section - last_played = [ - x[0] - for x in self.data.local.music.get_last_played( - self.game, self.music_version, userid, 5 - ) - ] - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 10 - ) - ] + last_played = [x[0] for x in self.data.local.music.get_last_played(self.game, self.music_version, userid, 5)] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 10)] while len(last_played) < 5: last_played.append(-1) while len(most_played) < 10: @@ -753,9 +711,7 @@ class PopnMusicEclale(PopnMusicBase): config.add_child(Node.u8("sheet", profile.get_int("sheet"))) config.add_child(Node.s8("category", profile.get_int("category", -1))) config.add_child(Node.s8("sub_category", profile.get_int("sub_category", -1))) - config.add_child( - Node.s8("chara_category", profile.get_int("chara_category", -1)) - ) + config.add_child(Node.s8("chara_category", profile.get_int("chara_category", -1))) config.add_child(Node.s16("course_id", profile.get_int("course_id", -1))) config.add_child(Node.s8("course_folder", profile.get_int("course_folder", -1))) config.add_child(Node.s8("ms_banner_disp", profile.get_int("ms_banner_disp"))) @@ -780,9 +736,7 @@ class PopnMusicEclale(PopnMusicBase): option.add_child(Node.u8("ojama_1", option_dict.get_int("ojama_1"))) option.add_child(Node.bool("forever_0", option_dict.get_bool("forever_0"))) option.add_child(Node.bool("forever_1", option_dict.get_bool("forever_1"))) - option.add_child( - Node.bool("full_setting", option_dict.get_bool("full_setting")) - ) + option.add_child(Node.bool("full_setting", option_dict.get_bool("full_setting"))) option.add_child(Node.u8("judge", option_dict.get_int("judge"))) # Unknown custom category stuff? @@ -798,12 +752,7 @@ class PopnMusicEclale(PopnMusicBase): game_config = self.get_game_config() if game_config.get_bool("force_unlock_songs"): - songs = { - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - } + songs = {song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)} for song in songs: item = Node.void("item") root.add_child(item) @@ -813,9 +762,7 @@ class PopnMusicEclale(PopnMusicBase): item.add_child(Node.bool("is_new", False)) # Set up achievements - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for achievement in achievements: if achievement.type[:5] == "item_": itemtype = int(achievement.type[5:]) @@ -898,9 +845,7 @@ class PopnMusicEclale(PopnMusicBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() account = request.child("account") @@ -909,22 +854,12 @@ class PopnMusicEclale(PopnMusicBase): newprofile.replace_int("read_news", account.child_value("read_news")) newprofile.replace_int("area_id", account.child_value("area_id")) newprofile.replace_int("lumina", account.child_value("lumina")) - newprofile.replace_int_array( - "medal_set", 4, account.child_value("medal_set") - ) + newprofile.replace_int_array("medal_set", 4, account.child_value("medal_set")) newprofile.replace_int_array("nice", 30, account.child_value("nice")) - newprofile.replace_int_array( - "favorite_chara", 20, account.child_value("favorite_chara") - ) - newprofile.replace_int_array( - "special_area", 8, account.child_value("special_area") - ) - newprofile.replace_int_array( - "chocolate_charalist", 5, account.child_value("chocolate_charalist") - ) - newprofile.replace_int_array( - "teacher_setting", 10, account.child_value("teacher_setting") - ) + newprofile.replace_int_array("favorite_chara", 20, account.child_value("favorite_chara")) + newprofile.replace_int_array("special_area", 8, account.child_value("special_area")) + newprofile.replace_int_array("chocolate_charalist", 5, account.child_value("chocolate_charalist")) + newprofile.replace_int_array("teacher_setting", 10, account.child_value("teacher_setting")) info = request.child("info") if info is not None: @@ -938,14 +873,10 @@ class PopnMusicEclale(PopnMusicBase): newprofile.replace_int("sheet", config.child_value("sheet")) newprofile.replace_int("category", config.child_value("category")) newprofile.replace_int("sub_category", config.child_value("sub_category")) - newprofile.replace_int( - "chara_category", config.child_value("chara_category") - ) + newprofile.replace_int("chara_category", config.child_value("chara_category")) newprofile.replace_int("course_id", config.child_value("course_id")) newprofile.replace_int("course_folder", config.child_value("course_folder")) - newprofile.replace_int( - "ms_banner_disp", config.child_value("ms_banner_disp") - ) + newprofile.replace_int("ms_banner_disp", config.child_value("ms_banner_disp")) newprofile.replace_int("ms_down_info", config.child_value("ms_down_info")) newprofile.replace_int("ms_side_info", config.child_value("ms_side_info")) newprofile.replace_int("ms_raise_type", config.child_value("ms_raise_type")) @@ -973,21 +904,15 @@ class PopnMusicEclale(PopnMusicBase): customize = request.child("customize") if customize is not None: newprofile.replace_int("effect_left", customize.child_value("effect_left")) - newprofile.replace_int( - "effect_center", customize.child_value("effect_center") - ) - newprofile.replace_int( - "effect_right", customize.child_value("effect_right") - ) + newprofile.replace_int("effect_center", customize.child_value("effect_center")) + newprofile.replace_int("effect_right", customize.child_value("effect_right")) newprofile.replace_int("hukidashi", customize.child_value("hukidashi")) newprofile.replace_int("comment_1", customize.child_value("comment_1")) newprofile.replace_int("comment_2", customize.child_value("comment_2")) event = request.child("event") if event is not None: - newprofile.replace_int( - "event_enemy_medal", event.child_value("enemy_medal") - ) + newprofile.replace_int("event_enemy_medal", event.child_value("enemy_medal")) newprofile.replace_int("event_hp", event.child_value("hp")) stamp = request.child("stamp") diff --git a/bemani/backend/popn/fantasia.py b/bemani/backend/popn/fantasia.py index 8e649a1..9ad1aa3 100644 --- a/bemani/backend/popn/fantasia.py +++ b/bemani/backend/popn/fantasia.py @@ -113,9 +113,7 @@ class PopnMusicFantasia(PopnMusicBase): base.add_child(Node.u8("mode", profile.get_int("mode", 0))) base.add_child(Node.s8("button", profile.get_int("button", 0))) base.add_child(Node.s8("last_play_flag", profile.get_int("last_play_flag", -1))) - base.add_child( - Node.u8("medal_and_friend", profile.get_int("medal_and_friend", 0)) - ) + base.add_child(Node.u8("medal_and_friend", profile.get_int("medal_and_friend", 0))) base.add_child(Node.s8("category", profile.get_int("category", -1))) base.add_child(Node.s8("sub_category", profile.get_int("sub_category", -1))) base.add_child(Node.s16("chara", profile.get_int("chara", -1))) @@ -128,58 +126,32 @@ class PopnMusicFantasia(PopnMusicBase): base.add_child(Node.s32("option", profile.get_int("option", 0))) base.add_child(Node.s16("music", profile.get_int("music", -1))) base.add_child(Node.u16("ep", profile.get_int("ep", 0))) - base.add_child( - Node.s32_array("sp_color_flg", profile.get_int_array("sp_color_flg", 2)) - ) + base.add_child(Node.s32_array("sp_color_flg", profile.get_int_array("sp_color_flg", 2))) base.add_child(Node.s32("read_news", profile.get_int("read_news", 0))) - base.add_child( - Node.s16( - "consecutive_days_coupon", profile.get_int("consecutive_days_coupon", 0) - ) - ) + base.add_child(Node.s16("consecutive_days_coupon", profile.get_int("consecutive_days_coupon", 0))) base.add_child(Node.s8("staff", 0)) # Player card section player_card_dict = profile.get_dict("player_card") player_card = Node.void("player_card") root.add_child(player_card) - player_card.add_child( - Node.u8_array("title", player_card_dict.get_int_array("title", 2, [0, 1])) - ) + player_card.add_child(Node.u8_array("title", player_card_dict.get_int_array("title", 2, [0, 1]))) player_card.add_child(Node.u8("frame", player_card_dict.get_int("frame"))) player_card.add_child(Node.u8("base", player_card_dict.get_int("base"))) - player_card.add_child( - Node.u8_array("seal", player_card_dict.get_int_array("seal", 2)) - ) - player_card.add_child( - Node.s32_array("get_title", player_card_dict.get_int_array("get_title", 4)) - ) - player_card.add_child( - Node.s32("get_frame", player_card_dict.get_int("get_frame")) - ) - player_card.add_child( - Node.s32("get_base", player_card_dict.get_int("get_base")) - ) - player_card.add_child( - Node.s32_array("get_seal", player_card_dict.get_int_array("get_seal", 2)) - ) + player_card.add_child(Node.u8_array("seal", player_card_dict.get_int_array("seal", 2))) + player_card.add_child(Node.s32_array("get_title", player_card_dict.get_int_array("get_title", 4))) + player_card.add_child(Node.s32("get_frame", player_card_dict.get_int("get_frame"))) + player_card.add_child(Node.s32("get_base", player_card_dict.get_int("get_base"))) + player_card.add_child(Node.s32_array("get_seal", player_card_dict.get_int_array("get_seal", 2))) player_card.add_child(Node.s8("is_open", 1)) # Player card EX section player_card_ex = Node.void("player_card_ex") root.add_child(player_card_ex) - player_card_ex.add_child( - Node.s32("get_title_ex", player_card_dict.get_int("get_title_ex")) - ) - player_card_ex.add_child( - Node.s32("get_frame_ex", player_card_dict.get_int("get_frame_ex")) - ) - player_card_ex.add_child( - Node.s32("get_base_ex", player_card_dict.get_int("get_base_ex")) - ) - player_card_ex.add_child( - Node.s32("get_seal_ex", player_card_dict.get_int("get_seal_ex")) - ) + player_card_ex.add_child(Node.s32("get_title_ex", player_card_dict.get_int("get_title_ex"))) + player_card_ex.add_child(Node.s32("get_frame_ex", player_card_dict.get_int("get_frame_ex"))) + player_card_ex.add_child(Node.s32("get_base_ex", player_card_dict.get_int("get_base_ex"))) + player_card_ex.add_child(Node.s32("get_seal_ex", player_card_dict.get_int("get_seal_ex"))) # Statistics section and scores section statistics = self.get_play_statistics(userid) @@ -201,18 +173,8 @@ class PopnMusicFantasia(PopnMusicBase): rivalcount += 1 base.add_child(Node.u8("active_fr_num", rivalcount)) - last_played = [ - x[0] - for x in self.data.local.music.get_last_played( - self.game, self.music_version, userid, 3 - ) - ] - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) - ] + last_played = [x[0] for x in self.data.local.music.get_last_played(self.game, self.music_version, userid, 3)] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20)] while len(last_played) < 3: last_played.append(-1) while len(most_played) < 20: @@ -222,9 +184,7 @@ class PopnMusicFantasia(PopnMusicBase): clear_medal = [0] * self.GAME_MAX_MUSIC_ID clear_medal_sub = [0] * self.GAME_MAX_MUSIC_ID - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue @@ -240,9 +200,7 @@ class PopnMusicFantasia(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) hiscore_index = (score.id * 4) + { self.CHART_TYPE_EASY: self.GAME_CHART_TYPE_EASY_POSITION, self.CHART_TYPE_NORMAL: self.GAME_CHART_TYPE_NORMAL_POSITION, @@ -252,15 +210,9 @@ class PopnMusicFantasia(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF - ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ((hiscore_value >> 8) & 0xFF) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ((hiscore_value >> 16) & 0xFF) hiscore = bytes(hiscore_array) @@ -294,9 +246,7 @@ class PopnMusicFantasia(PopnMusicBase): reflec_data = Node.void("reflec_data") root.add_child(reflec_data) - reflec_data.add_child( - Node.s8_array("reflec", profile.get_int_array("reflec", 2)) - ) + reflec_data.add_child(Node.s8_array("reflec", profile.get_int_array("reflec", 2))) # Navigate section for i in range(3): @@ -307,14 +257,10 @@ class PopnMusicFantasia(PopnMusicBase): navigate.add_child(Node.s8("image", navigate_dict.get_int("image", -1))) navigate.add_child(Node.s8("level", navigate_dict.get_int("level", -1))) navigate.add_child(Node.s8("ojama", navigate_dict.get_int("ojama", -1))) - navigate.add_child( - Node.s16("limit_num", navigate_dict.get_int("limit_num", -1)) - ) + navigate.add_child(Node.s16("limit_num", navigate_dict.get_int("limit_num", -1))) navigate.add_child(Node.s8("button", navigate_dict.get_int("button", -1))) navigate.add_child(Node.s8("life", navigate_dict.get_int("life", -1))) - navigate.add_child( - Node.s16("progress", navigate_dict.get_int("progress", -1)) - ) + navigate.add_child(Node.s16("progress", navigate_dict.get_int("progress", -1))) return root @@ -331,9 +277,7 @@ class PopnMusicFantasia(PopnMusicBase): clear_medal = [0] * self.GAME_MAX_MUSIC_ID hiscore_array = [0] * int((((self.GAME_MAX_MUSIC_ID * 4) * 17) + 7) / 8) - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue @@ -349,9 +293,7 @@ class PopnMusicFantasia(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) hiscore_index = (score.id * 4) + { self.CHART_TYPE_EASY: self.GAME_CHART_TYPE_EASY_POSITION, self.CHART_TYPE_NORMAL: self.GAME_CHART_TYPE_NORMAL_POSITION, @@ -361,24 +303,16 @@ class PopnMusicFantasia(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF - ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ((hiscore_value >> 8) & 0xFF) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ((hiscore_value >> 16) & 0xFF) root.add_child(Node.u16_array("clear_medal", clear_medal)) root.add_child(Node.binary("hiscore", bytes(hiscore_array))) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: # For some reason, Pop'n 20 sends us two profile saves, one with 'not done yet' # so we only want to process the done yet node. The 'not gameover' save has # jubeat collabo stuff set in it, but we don't use that so it doesn't matter. @@ -396,17 +330,11 @@ class PopnMusicFantasia(PopnMusicBase): newprofile.replace_int("category", request.child_value("category")) newprofile.replace_int("sub_category", request.child_value("sub_category")) newprofile.replace_int("chara_category", request.child_value("chara_category")) - newprofile.replace_int( - "medal_and_friend", request.child_value("medal_and_friend") - ) + newprofile.replace_int("medal_and_friend", request.child_value("medal_and_friend")) newprofile.replace_int("ep", request.child_value("ep")) - newprofile.replace_int_array( - "sp_color_flg", 2, request.child_value("sp_color_flg") - ) + newprofile.replace_int_array("sp_color_flg", 2, request.child_value("sp_color_flg")) newprofile.replace_int("read_news", request.child_value("read_news")) - newprofile.replace_int( - "consecutive_days_coupon", request.child_value("consecutive_days_coupon") - ) + newprofile.replace_int("consecutive_days_coupon", request.child_value("consecutive_days_coupon")) newprofile.replace_int("tutorial", request.child_value("tutorial")) newprofile.replace_int("music_open_pt", request.child_value("music_open_pt")) newprofile.replace_int("collabo", request.child_value("collabo")) @@ -428,29 +356,17 @@ class PopnMusicFantasia(PopnMusicBase): player_card_dict.replace_int("frame", request.child_value("frame")) player_card_dict.replace_int("base", request.child_value("base")) player_card_dict.replace_int_array("seal", 2, request.child_value("seal")) - player_card_dict.replace_int_array( - "get_title", 4, request.child_value("get_title") - ) + player_card_dict.replace_int_array("get_title", 4, request.child_value("get_title")) player_card_dict.replace_int("get_frame", request.child_value("get_frame")) player_card_dict.replace_int("get_base", request.child_value("get_base")) - player_card_dict.replace_int_array( - "get_seal", 2, request.child_value("get_seal") - ) + player_card_dict.replace_int_array("get_seal", 2, request.child_value("get_seal")) player_card_ex = request.child("player_card_ex") if player_card_ex is not None: - player_card_dict.replace_int( - "get_title_ex", player_card_ex.child_value("get_title_ex") - ) - player_card_dict.replace_int( - "get_frame_ex", player_card_ex.child_value("get_frame_ex") - ) - player_card_dict.replace_int( - "get_base_ex", player_card_ex.child_value("get_base_ex") - ) - player_card_dict.replace_int( - "get_seal_ex", player_card_ex.child_value("get_seal_ex") - ) + player_card_dict.replace_int("get_title_ex", player_card_ex.child_value("get_title_ex")) + player_card_dict.replace_int("get_frame_ex", player_card_ex.child_value("get_frame_ex")) + player_card_dict.replace_int("get_base_ex", player_card_ex.child_value("get_base_ex")) + player_card_dict.replace_int("get_seal_ex", player_card_ex.child_value("get_seal_ex")) newprofile.replace_dict("player_card", player_card_dict) # Extract navigate stuff @@ -462,9 +378,7 @@ class PopnMusicFantasia(PopnMusicBase): navigate_dict.replace_int("image", navigate.child_value("image")) navigate_dict.replace_int("level", navigate.child_value("level")) navigate_dict.replace_int("ojama", navigate.child_value("ojama")) - navigate_dict.replace_int( - "limit_num", navigate.child_value("limit_num") - ) + navigate_dict.replace_int("limit_num", navigate.child_value("limit_num")) navigate_dict.replace_int("button", navigate.child_value("button")) navigate_dict.replace_int("life", navigate.child_value("life")) navigate_dict.replace_int("progress", navigate.child_value("progress")) @@ -549,9 +463,7 @@ class PopnMusicFantasia(PopnMusicBase): machine = self.get_machine() root = Node.void("playerdata") - root.add_child( - Node.s8("pref", machine.data.get_int("pref", self.get_machine_region())) - ) + root.add_child(Node.s8("pref", machine.data.get_int("pref", self.get_machine_region()))) if refid is None: root.add_child(Node.string("name", "")) @@ -584,9 +496,7 @@ class PopnMusicFantasia(PopnMusicBase): root.add_child(Node.string("message", "")) return root - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: @@ -597,22 +507,10 @@ class PopnMusicFantasia(PopnMusicBase): root.add_child(Node.s16("chara", newprofile.get_int("chara", -1))) root.add_child(Node.u8("frame", player_card_dict.get_int("frame"))) root.add_child(Node.u8("base", player_card_dict.get_int("base"))) - root.add_child( - Node.u8("seal_1", player_card_dict.get_int_array("seal", 2)[0]) - ) - root.add_child( - Node.u8("seal_2", player_card_dict.get_int_array("seal", 2)[1]) - ) - root.add_child( - Node.u8( - "title_1", player_card_dict.get_int_array("title", 2, [0, 1])[0] - ) - ) - root.add_child( - Node.u8( - "title_2", player_card_dict.get_int_array("title", 2, [0, 1])[1] - ) - ) + root.add_child(Node.u8("seal_1", player_card_dict.get_int_array("seal", 2)[0])) + root.add_child(Node.u8("seal_2", player_card_dict.get_int_array("seal", 2)[1])) + root.add_child(Node.u8("title_1", player_card_dict.get_int_array("title", 2, [0, 1])[0])) + root.add_child(Node.u8("title_2", player_card_dict.get_int_array("title", 2, [0, 1])[1])) root.add_child(Node.s16("recommend_1", -1)) root.add_child(Node.s16("recommend_2", -1)) root.add_child(Node.s16("recommend_3", -1)) @@ -647,9 +545,7 @@ class PopnMusicFantasia(PopnMusicBase): for rival in links[:2]: rivalid = rival.other_userid rivalprofile = profiles[rivalid] - scores = self.data.remote.music.get_scores( - self.game, self.music_version, rivalid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, rivalid) # First, output general profile info. friend = Node.void("friend") @@ -661,9 +557,7 @@ class PopnMusicFantasia(PopnMusicBase): # Set up some sane defaults. friend.add_child(Node.string("name", rivalprofile.get_str("name", "なし"))) - friend.add_child( - Node.string("g_pm_id", ID.format_extid(rivalprofile.extid)) - ) + friend.add_child(Node.string("g_pm_id", ID.format_extid(rivalprofile.extid))) friend.add_child(Node.s16("chara", rivalprofile.get_int("chara", -1))) # Perform hiscore/medal conversion. @@ -684,9 +578,7 @@ class PopnMusicFantasia(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) hiscore_index = (score.id * 4) + { self.CHART_TYPE_EASY: self.GAME_CHART_TYPE_EASY_POSITION, self.CHART_TYPE_NORMAL: self.GAME_CHART_TYPE_NORMAL_POSITION, @@ -696,15 +588,13 @@ class PopnMusicFantasia(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ( + (hiscore_value >> 8) & 0xFF + ) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ( + (hiscore_value >> 16) & 0xFF ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) hiscore = bytes(hiscore_array) friend.add_child(Node.u16_array("clear_medal", clear_medal)) @@ -726,14 +616,10 @@ class PopnMusicFantasia(PopnMusicBase): root.add_child(Node.s32("game_phase", game_phase)) root.add_child(Node.s32("ir_phase", 0)) root.add_child(Node.s32("event_phase", event_phase)) - root.add_child( - Node.s32("netvs_phase", 0) - ) # Net taisen mode, we don't support lobbies. + root.add_child(Node.s32("netvs_phase", 0)) # Net taisen mode, we don't support lobbies. root.add_child(Node.s32("card_phase", 6)) root.add_child(Node.s32("illust_phase", 2)) - root.add_child( - Node.s32("psp_phase", 5) - ) # Unlock songs from Pop'n Music Portable. + root.add_child(Node.s32("psp_phase", 5)) # Unlock songs from Pop'n Music Portable. root.add_child(Node.s32("other_phase", 1)) root.add_child(Node.s32("jubeat_phase", 1)) root.add_child(Node.s32("public_phase", 3)) diff --git a/bemani/backend/popn/kaimei.py b/bemani/backend/popn/kaimei.py index dc94afc..a756fc2 100644 --- a/bemani/backend/popn/kaimei.py +++ b/bemani/backend/popn/kaimei.py @@ -384,9 +384,7 @@ class PopnMusicKaimei(PopnMusicModernBase): root = super().format_profile(userid, profile) account = root.child("account") - account.add_child( - Node.s16("card_again_count", profile.get_int("card_again_count")) - ) + account.add_child(Node.s16("card_again_count", profile.get_int("card_again_count"))) account.add_child(Node.s16("sp_riddles_id", profile.get_int("sp_riddles_id"))) # Kaimei riddles events @@ -394,11 +392,7 @@ class PopnMusicKaimei(PopnMusicModernBase): root.add_child(event2021) event2021.add_child(Node.u32("point", profile.get_int("point"))) event2021.add_child(Node.u8("step", profile.get_int("step"))) - event2021.add_child( - Node.u32_array( - "quest_point", profile.get_int_array("quest_point", 8, [0] * 8) - ) - ) + event2021.add_child(Node.u32_array("quest_point", profile.get_int_array("quest_point", 8, [0] * 8))) event2021.add_child(Node.u8("step_nos", profile.get_int("step_nos"))) event2021.add_child( Node.u32_array( @@ -428,9 +422,7 @@ class PopnMusicKaimei(PopnMusicModernBase): sh_riddles.add_child(Node.u32("sh_riddles_id", riddle)) # Set up kaimei riddles achievements - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for achievement in achievements: if achievement.type == "riddle": kaimei_gauge = achievement.data.get_int("kaimei_gauge") @@ -449,32 +441,22 @@ class PopnMusicKaimei(PopnMusicModernBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = super().unformat_profile(userid, request, oldprofile) account = request.child("account") if account is not None: - newprofile.replace_int( - "card_again_count", account.child_value("card_again_count") - ) - newprofile.replace_int( - "sp_riddles_id", account.child_value("sp_riddles_id") - ) + newprofile.replace_int("card_again_count", account.child_value("card_again_count")) + newprofile.replace_int("sp_riddles_id", account.child_value("sp_riddles_id")) # Kaimei riddles events event2021 = request.child("event2021") if event2021 is not None: newprofile.replace_int("point", event2021.child_value("point")) newprofile.replace_int("step", event2021.child_value("step")) - newprofile.replace_int_array( - "quest_point", 8, event2021.child_value("quest_point") - ) + newprofile.replace_int_array("quest_point", 8, event2021.child_value("quest_point")) newprofile.replace_int("step_nos", event2021.child_value("step_nos")) - newprofile.replace_int_array( - "quest_point_nos", 13, event2021.child_value("quest_point_nos") - ) + newprofile.replace_int_array("quest_point_nos", 13, event2021.child_value("quest_point_nos")) # Extract kaimei riddles achievements for node in request.children: diff --git a/bemani/backend/popn/lapistoria.py b/bemani/backend/popn/lapistoria.py index fa88703..4d779a7 100644 --- a/bemani/backend/popn/lapistoria.py +++ b/bemani/backend/popn/lapistoria.py @@ -289,9 +289,7 @@ class PopnMusicLapistoria(PopnMusicBase): if userid is None: return root - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: @@ -334,12 +332,8 @@ class PopnMusicLapistoria(PopnMusicBase): return root rivalid = links[no].other_userid rivalprofile = profiles[rivalid] - scores = self.data.remote.music.get_scores( - self.game, self.music_version, rivalid - ) - achievements = self.data.local.user.get_achievements( - self.game, self.version, rivalid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, rivalid) + achievements = self.data.local.user.get_achievements(self.game, self.version, rivalid) # First, output general profile info. friend = Node.void("friend") @@ -474,9 +468,7 @@ class PopnMusicLapistoria(PopnMusicBase): self.GAME_PLAY_MEDAL_STAR_FULL_COMBO: self.PLAY_MEDAL_STAR_FULL_COMBO, self.GAME_PLAY_MEDAL_PERFECT: self.PLAY_MEDAL_PERFECT, }[medal] - self.update_score( - userid, songid, chart, points, medal, combo=combo, stats=stats - ) + self.update_score(userid, songid, chart, points, medal, combo=combo, stats=stats) return root def handle_player22_write_course_request(self, request: Node) -> Node: @@ -496,9 +488,7 @@ class PopnMusicLapistoria(PopnMusicBase): if course_id is not None: machine = self.data.local.machine.get_machine(self.config.machine.pcbid) pref = request.child_value("pref") or self.get_machine_region() - profile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + profile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) course = self.data.local.user.get_achievement( self.game, @@ -569,12 +559,8 @@ class PopnMusicLapistoria(PopnMusicBase): key=lambda entry: entry[1].data.get_int("total_score"), reverse=True, ) - pref_ranking = [ - c for c in global_ranking if c[1].data.get_int("pref") == pref - ] - local_ranking = [ - c for c in global_ranking if c[1].data.get_int("lid") == machine.arcade - ] + pref_ranking = [c for c in global_ranking if c[1].data.get_int("pref") == pref] + local_ranking = [c for c in global_ranking if c[1].data.get_int("lid") == machine.arcade] global_rank = len(global_ranking) pref_rank = len(pref_ranking) @@ -630,9 +616,7 @@ class PopnMusicLapistoria(PopnMusicBase): account.add_child(Node.s8("is_conv", 0)) account.add_child(Node.s16("item_type", 0)) account.add_child(Node.s16("item_id", 0)) - account.add_child( - Node.s16_array("license_data", [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]) - ) + account.add_child(Node.s16_array("license_data", [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1])) # Statistics section and scores section statistics = self.get_play_statistics(userid) @@ -657,18 +641,8 @@ class PopnMusicLapistoria(PopnMusicBase): account.add_child(Node.u8("active_fr_num", rivalcount)) # Add scores section - last_played = [ - x[0] - for x in self.data.local.music.get_last_played( - self.game, self.music_version, userid, 5 - ) - ] - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 10 - ) - ] + last_played = [x[0] for x in self.data.local.music.get_last_played(self.game, self.music_version, userid, 5)] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 10)] while len(last_played) < 5: last_played.append(-1) while len(most_played) < 10: @@ -677,9 +651,7 @@ class PopnMusicLapistoria(PopnMusicBase): account.add_child(Node.s16_array("my_best", most_played)) account.add_child(Node.s16_array("latest_music", last_played)) - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: # Skip any scores for chart types we don't support if score.chart not in [ @@ -754,9 +726,7 @@ class PopnMusicLapistoria(PopnMusicBase): config.add_child(Node.u8("sheet", profile.get_int("sheet", 0))) config.add_child(Node.s8("category", profile.get_int("category", 1))) config.add_child(Node.s8("sub_category", profile.get_int("sub_category", -1))) - config.add_child( - Node.s8("chara_category", profile.get_int("chara_category", -1)) - ) + config.add_child(Node.s8("chara_category", profile.get_int("chara_category", -1))) config.add_child(Node.s16("story_id", profile.get_int("story_id", -1))) config.add_child(Node.s16("course_id", profile.get_int("course_id", -1))) config.add_child(Node.s8("course_folder", profile.get_int("course_folder", -1))) @@ -774,26 +744,16 @@ class PopnMusicLapistoria(PopnMusicBase): option.add_child(Node.s16("hispeed", option_dict.get_int("hispeed", 10))) option.add_child(Node.u8("popkun", option_dict.get_int("popkun", 0))) option.add_child(Node.bool("hidden", option_dict.get_bool("hidden", False))) - option.add_child( - Node.s16("hidden_rate", option_dict.get_int("hidden_rate", -1)) - ) + option.add_child(Node.s16("hidden_rate", option_dict.get_int("hidden_rate", -1))) option.add_child(Node.bool("sudden", option_dict.get_bool("sudden", False))) - option.add_child( - Node.s16("sudden_rate", option_dict.get_int("sudden_rate", -1)) - ) + option.add_child(Node.s16("sudden_rate", option_dict.get_int("sudden_rate", -1))) option.add_child(Node.s8("randmir", option_dict.get_int("randmir", 0))) option.add_child(Node.s8("gauge_type", option_dict.get_int("gauge_type", 0))) option.add_child(Node.u8("ojama_0", option_dict.get_int("ojama_0", 0))) option.add_child(Node.u8("ojama_1", option_dict.get_int("ojama_1", 0))) - option.add_child( - Node.bool("forever_0", option_dict.get_bool("forever_0", False)) - ) - option.add_child( - Node.bool("forever_1", option_dict.get_bool("forever_1", False)) - ) - option.add_child( - Node.bool("full_setting", option_dict.get_bool("full_setting", False)) - ) + option.add_child(Node.bool("forever_0", option_dict.get_bool("forever_0", False))) + option.add_child(Node.bool("forever_1", option_dict.get_bool("forever_1", False))) + option.add_child(Node.bool("full_setting", option_dict.get_bool("full_setting", False))) # Set up info info = Node.void("info") @@ -824,12 +784,7 @@ class PopnMusicLapistoria(PopnMusicBase): game_config = self.get_game_config() if game_config.get_bool("force_unlock_songs"): - songs = { - song.id - for song in self.data.local.music.get_all_songs( - self.game, self.music_version - ) - } + songs = {song.id for song in self.data.local.music.get_all_songs(self.game, self.music_version)} for song in songs: item = Node.void("item") root.add_child(item) @@ -839,9 +794,7 @@ class PopnMusicLapistoria(PopnMusicBase): item.add_child(Node.bool("is_new", False)) # Set up achievements - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for achievement in achievements: if achievement.type == "item": itemtype = achievement.data.get_int("type") @@ -919,9 +872,7 @@ class PopnMusicLapistoria(PopnMusicBase): course.add_child(Node.s32("stage3_score", stage3_score)) course.add_child(Node.s32("stage4_score", stage4_score)) course.add_child(Node.s32("total_score", total_score)) - course.add_child( - Node.s16("max_cmbo", max_combo) - ) # Yes, it is misspelled. + course.add_child(Node.s16("max_cmbo", max_combo)) # Yes, it is misspelled. course.add_child(Node.s16("play_cnt", play_cnt)) course.add_child(Node.s16("all_rank", 1)) # Unclear what this does. @@ -930,9 +881,7 @@ class PopnMusicLapistoria(PopnMusicBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() account = request.child("account") @@ -953,16 +902,12 @@ class PopnMusicLapistoria(PopnMusicBase): newprofile.replace_int("sheet", config.child_value("sheet")) newprofile.replace_int("category", config.child_value("category")) newprofile.replace_int("sub_category", config.child_value("sub_category")) - newprofile.replace_int( - "chara_category", config.child_value("chara_category") - ) + newprofile.replace_int("chara_category", config.child_value("chara_category")) newprofile.replace_int("story_id", config.child_value("story_id")) newprofile.replace_int("course_id", config.child_value("course_id")) newprofile.replace_int("course_folder", config.child_value("course_folder")) newprofile.replace_int("story_folder", config.child_value("story_folder")) - newprofile.replace_int( - "ms_banner_disp", config.child_value("ms_banner_disp") - ) + newprofile.replace_int("ms_banner_disp", config.child_value("ms_banner_disp")) newprofile.replace_int("ms_down_info", config.child_value("ms_down_info")) newprofile.replace_int("ms_side_info", config.child_value("ms_side_info")) newprofile.replace_int("ms_raise_type", config.child_value("ms_raise_type")) @@ -1088,9 +1033,7 @@ class PopnMusicLapistoria(PopnMusicBase): root.add_child(Node.s32("option", profile.get_int("option", 0))) root.add_child(Node.s8("result", 1)) - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue diff --git a/bemani/backend/popn/sunnypark.py b/bemani/backend/popn/sunnypark.py index e7d566e..27a4018 100644 --- a/bemani/backend/popn/sunnypark.py +++ b/bemani/backend/popn/sunnypark.py @@ -126,9 +126,7 @@ class PopnMusicSunnyPark(PopnMusicBase): base.add_child(Node.u8("mode", profile.get_int("mode", 0))) base.add_child(Node.s8("button", profile.get_int("button", 0))) base.add_child(Node.s8("last_play_flag", profile.get_int("last_play_flag", -1))) - base.add_child( - Node.u8("medal_and_friend", profile.get_int("medal_and_friend", 0)) - ) + base.add_child(Node.u8("medal_and_friend", profile.get_int("medal_and_friend", 0))) base.add_child(Node.s8("category", profile.get_int("category", -1))) base.add_child(Node.s8("sub_category", profile.get_int("sub_category", -1))) base.add_child(Node.s16("chara", profile.get_int("chara", -1))) @@ -141,15 +139,9 @@ class PopnMusicSunnyPark(PopnMusicBase): base.add_child(Node.s32("option", profile.get_int("option", 0))) base.add_child(Node.s16("music", profile.get_int("music", -1))) base.add_child(Node.u16("ep", profile.get_int("ep", 0))) - base.add_child( - Node.s32_array("sp_color_flg", profile.get_int_array("sp_color_flg", 2)) - ) + base.add_child(Node.s32_array("sp_color_flg", profile.get_int_array("sp_color_flg", 2))) base.add_child(Node.s32("read_news", profile.get_int("read_news", 0))) - base.add_child( - Node.s16( - "consecutive_days_coupon", profile.get_int("consecutive_days_coupon", 0) - ) - ) + base.add_child(Node.s16("consecutive_days_coupon", profile.get_int("consecutive_days_coupon", 0))) base.add_child(Node.s8("staff", 0)) # These are probably from an old event, but if they aren't present and defaulted, # then different songs show up in the Zoo event. @@ -159,9 +151,7 @@ class PopnMusicSunnyPark(PopnMusicBase): profile.get_int_array("gitadora_point", 3, [2000, 2000, 2000]), ) ) - base.add_child( - Node.u8("gitadora_select", profile.get_int("gitadora_select", 2)) - ) + base.add_child(Node.u8("gitadora_select", profile.get_int("gitadora_select", 2))) # Statistics section and scores section statistics = self.get_play_statistics(userid) @@ -183,18 +173,8 @@ class PopnMusicSunnyPark(PopnMusicBase): rivalcount += 1 base.add_child(Node.u8("active_fr_num", rivalcount)) - last_played = [ - x[0] - for x in self.data.local.music.get_last_played( - self.game, self.music_version, userid, 3 - ) - ] - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) - ] + last_played = [x[0] for x in self.data.local.music.get_last_played(self.game, self.music_version, userid, 3)] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20)] while len(last_played) < 3: last_played.append(-1) while len(most_played) < 20: @@ -204,9 +184,7 @@ class PopnMusicSunnyPark(PopnMusicBase): clear_medal = [0] * self.GAME_MAX_MUSIC_ID clear_medal_sub = [0] * self.GAME_MAX_MUSIC_ID - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue @@ -222,9 +200,7 @@ class PopnMusicSunnyPark(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) hiscore_index = (score.id * 4) + { self.CHART_TYPE_EASY: self.GAME_CHART_TYPE_EASY_POSITION, self.CHART_TYPE_NORMAL: self.GAME_CHART_TYPE_NORMAL_POSITION, @@ -234,15 +210,9 @@ class PopnMusicSunnyPark(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF - ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ((hiscore_value >> 8) & 0xFF) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ((hiscore_value >> 16) & 0xFF) hiscore = bytes(hiscore_array) @@ -263,85 +233,37 @@ class PopnMusicSunnyPark(PopnMusicBase): avatar.add_child(Node.u8("body", avatar_dict.get_int("body", 0))) avatar.add_child(Node.u8("effect", avatar_dict.get_int("effect", 0))) avatar.add_child(Node.u8("object", avatar_dict.get_int("object", 0))) - avatar.add_child( - Node.u8_array("comment", avatar_dict.get_int_array("comment", 2)) - ) - avatar.add_child( - Node.s32_array("get_hair", avatar_dict.get_int_array("get_hair", 2)) - ) - avatar.add_child( - Node.s32_array("get_face", avatar_dict.get_int_array("get_face", 2)) - ) - avatar.add_child( - Node.s32_array("get_body", avatar_dict.get_int_array("get_body", 2)) - ) - avatar.add_child( - Node.s32_array("get_effect", avatar_dict.get_int_array("get_effect", 2)) - ) - avatar.add_child( - Node.s32_array("get_object", avatar_dict.get_int_array("get_object", 2)) - ) - avatar.add_child( - Node.s32_array( - "get_comment_over", avatar_dict.get_int_array("get_comment_over", 3) - ) - ) - avatar.add_child( - Node.s32_array( - "get_comment_under", avatar_dict.get_int_array("get_comment_under", 3) - ) - ) + avatar.add_child(Node.u8_array("comment", avatar_dict.get_int_array("comment", 2))) + avatar.add_child(Node.s32_array("get_hair", avatar_dict.get_int_array("get_hair", 2))) + avatar.add_child(Node.s32_array("get_face", avatar_dict.get_int_array("get_face", 2))) + avatar.add_child(Node.s32_array("get_body", avatar_dict.get_int_array("get_body", 2))) + avatar.add_child(Node.s32_array("get_effect", avatar_dict.get_int_array("get_effect", 2))) + avatar.add_child(Node.s32_array("get_object", avatar_dict.get_int_array("get_object", 2))) + avatar.add_child(Node.s32_array("get_comment_over", avatar_dict.get_int_array("get_comment_over", 3))) + avatar.add_child(Node.s32_array("get_comment_under", avatar_dict.get_int_array("get_comment_under", 3))) # Avatar add section avatar_add_dict = profile.get_dict("avatar_add") avatar_add = Node.void("avatar_add") root.add_child(avatar_add) - avatar_add.add_child( - Node.s32_array("get_hair", avatar_add_dict.get_int_array("get_hair", 2)) - ) - avatar_add.add_child( - Node.s32_array("get_face", avatar_add_dict.get_int_array("get_face", 2)) - ) - avatar_add.add_child( - Node.s32_array("get_body", avatar_add_dict.get_int_array("get_body", 2)) - ) - avatar_add.add_child( - Node.s32_array("get_effect", avatar_add_dict.get_int_array("get_effect", 2)) - ) - avatar_add.add_child( - Node.s32_array("get_object", avatar_add_dict.get_int_array("get_object", 2)) - ) - avatar_add.add_child( - Node.s32_array( - "get_comment_over", avatar_add_dict.get_int_array("get_comment_over", 2) - ) - ) + avatar_add.add_child(Node.s32_array("get_hair", avatar_add_dict.get_int_array("get_hair", 2))) + avatar_add.add_child(Node.s32_array("get_face", avatar_add_dict.get_int_array("get_face", 2))) + avatar_add.add_child(Node.s32_array("get_body", avatar_add_dict.get_int_array("get_body", 2))) + avatar_add.add_child(Node.s32_array("get_effect", avatar_add_dict.get_int_array("get_effect", 2))) + avatar_add.add_child(Node.s32_array("get_object", avatar_add_dict.get_int_array("get_object", 2))) + avatar_add.add_child(Node.s32_array("get_comment_over", avatar_add_dict.get_int_array("get_comment_over", 2))) avatar_add.add_child( Node.s32_array( "get_comment_under", avatar_add_dict.get_int_array("get_comment_under", 2), ) ) - avatar_add.add_child( - Node.s32_array("new_hair", avatar_add_dict.get_int_array("new_hair", 2)) - ) - avatar_add.add_child( - Node.s32_array("new_face", avatar_add_dict.get_int_array("new_face", 2)) - ) - avatar_add.add_child( - Node.s32_array("new_body", avatar_add_dict.get_int_array("new_body", 2)) - ) - avatar_add.add_child( - Node.s32_array("new_effect", avatar_add_dict.get_int_array("new_effect", 2)) - ) - avatar_add.add_child( - Node.s32_array("new_object", avatar_add_dict.get_int_array("new_object", 2)) - ) - avatar_add.add_child( - Node.s32_array( - "new_comment_over", avatar_add_dict.get_int_array("new_comment_over", 2) - ) - ) + avatar_add.add_child(Node.s32_array("new_hair", avatar_add_dict.get_int_array("new_hair", 2))) + avatar_add.add_child(Node.s32_array("new_face", avatar_add_dict.get_int_array("new_face", 2))) + avatar_add.add_child(Node.s32_array("new_body", avatar_add_dict.get_int_array("new_body", 2))) + avatar_add.add_child(Node.s32_array("new_effect", avatar_add_dict.get_int_array("new_effect", 2))) + avatar_add.add_child(Node.s32_array("new_object", avatar_add_dict.get_int_array("new_object", 2))) + avatar_add.add_child(Node.s32_array("new_comment_over", avatar_add_dict.get_int_array("new_comment_over", 2))) avatar_add.add_child( Node.s32_array( "new_comment_under", @@ -383,35 +305,17 @@ class PopnMusicSunnyPark(PopnMusicBase): zoo = Node.void("zoo") root.add_child(zoo) zoo.add_child(Node.u16_array("point", zoo_dict.get_int_array("point", 5))) - zoo.add_child( - Node.s32_array("music_list", zoo_dict.get_int_array("music_list", 2)) - ) - zoo.add_child( - Node.s8_array( - "today_play_flag", zoo_dict.get_int_array("today_play_flag", 4) - ) - ) + zoo.add_child(Node.s32_array("music_list", zoo_dict.get_int_array("music_list", 2))) + zoo.add_child(Node.s8_array("today_play_flag", zoo_dict.get_int_array("today_play_flag", 4))) # Pop'n Walker event personal_event_dict = profile.get_dict("personal_event") personal_event = Node.void("personal_event") root.add_child(personal_event) - personal_event.add_child( - Node.s16_array("pos", personal_event_dict.get_int_array("pos", 2)) - ) - personal_event.add_child( - Node.s16("point", personal_event_dict.get_int("point")) - ) - personal_event.add_child( - Node.u32_array( - "walk_data", personal_event_dict.get_int_array("walk_data", 128) - ) - ) - personal_event.add_child( - Node.u32_array( - "event_data", personal_event_dict.get_int_array("event_data", 4) - ) - ) + personal_event.add_child(Node.s16_array("pos", personal_event_dict.get_int_array("pos", 2))) + personal_event.add_child(Node.s16("point", personal_event_dict.get_int("point"))) + personal_event.add_child(Node.u32_array("walk_data", personal_event_dict.get_int_array("walk_data", 128))) + personal_event.add_child(Node.u32_array("event_data", personal_event_dict.get_int_array("event_data", 4))) # We don't support triple journey, so this is stubbed out. triple = Node.void("triple_journey") @@ -465,9 +369,7 @@ class PopnMusicSunnyPark(PopnMusicBase): clear_medal = [0] * self.GAME_MAX_MUSIC_ID - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue @@ -483,17 +385,13 @@ class PopnMusicSunnyPark(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) root.add_child(Node.u16_array("clear_medal", clear_medal)) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() newprofile.replace_int("option", request.child_value("option")) newprofile.replace_int("chara", request.child_value("chara")) @@ -505,25 +403,15 @@ class PopnMusicSunnyPark(PopnMusicBase): newprofile.replace_int("category", request.child_value("category")) newprofile.replace_int("sub_category", request.child_value("sub_category")) newprofile.replace_int("chara_category", request.child_value("chara_category")) - newprofile.replace_int( - "medal_and_friend", request.child_value("medal_and_friend") - ) + newprofile.replace_int("medal_and_friend", request.child_value("medal_and_friend")) newprofile.replace_int("ep", request.child_value("ep")) - newprofile.replace_int_array( - "sp_color_flg", 2, request.child_value("sp_color_flg") - ) + newprofile.replace_int_array("sp_color_flg", 2, request.child_value("sp_color_flg")) newprofile.replace_int("read_news", request.child_value("read_news")) - newprofile.replace_int( - "consecutive_days_coupon", request.child_value("consecutive_days_coupon") - ) + newprofile.replace_int("consecutive_days_coupon", request.child_value("consecutive_days_coupon")) newprofile.replace_int("tutorial", request.child_value("tutorial")) newprofile.replace_int("music_open_pt", request.child_value("music_open_pt")) - newprofile.replace_int_array( - "gitadora_point", 3, request.child_value("gitadora_point") - ) - newprofile.replace_int( - "gitadora_select", request.child_value("gitadora_select") - ) + newprofile.replace_int_array("gitadora_point", 3, request.child_value("gitadora_point")) + newprofile.replace_int("gitadora_select", request.child_value("gitadora_select")) sp_node = request.child("sp_data") if sp_node is not None: @@ -533,29 +421,17 @@ class PopnMusicSunnyPark(PopnMusicBase): zoo_node = request.child("zoo") if zoo_node is not None: zoo_dict.replace_int_array("point", 5, zoo_node.child_value("point")) - zoo_dict.replace_int_array( - "music_list", 2, zoo_node.child_value("music_list") - ) - zoo_dict.replace_int_array( - "today_play_flag", 4, zoo_node.child_value("today_play_flag") - ) + zoo_dict.replace_int_array("music_list", 2, zoo_node.child_value("music_list")) + zoo_dict.replace_int_array("today_play_flag", 4, zoo_node.child_value("today_play_flag")) newprofile.replace_dict("zoo", zoo_dict) personal_event_dict = newprofile.get_dict("personal_event") personal_event_node = request.child("personal_event") if personal_event_node is not None: - personal_event_dict.replace_int_array( - "pos", 2, personal_event_node.child_value("pos") - ) - personal_event_dict.replace_int( - "point", personal_event_node.child_value("point") - ) - personal_event_dict.replace_int_array( - "walk_data", 128, personal_event_node.child_value("walk_data") - ) - personal_event_dict.replace_int_array( - "event_data", 4, personal_event_node.child_value("event_data") - ) + personal_event_dict.replace_int_array("pos", 2, personal_event_node.child_value("pos")) + personal_event_dict.replace_int("point", personal_event_node.child_value("point")) + personal_event_dict.replace_int_array("walk_data", 128, personal_event_node.child_value("walk_data")) + personal_event_dict.replace_int_array("event_data", 4, personal_event_node.child_value("event_data")) newprofile.replace_dict("personal_event", personal_event_dict) avatar_dict = newprofile.get_dict("avatar") @@ -568,65 +444,29 @@ class PopnMusicSunnyPark(PopnMusicBase): avatar_dict.replace_int_array("get_hair", 2, request.child_value("get_hair")) avatar_dict.replace_int_array("get_face", 2, request.child_value("get_face")) avatar_dict.replace_int_array("get_body", 2, request.child_value("get_body")) - avatar_dict.replace_int_array( - "get_effect", 2, request.child_value("get_effect") - ) - avatar_dict.replace_int_array( - "get_object", 2, request.child_value("get_object") - ) - avatar_dict.replace_int_array( - "get_comment_over", 3, request.child_value("get_comment_over") - ) - avatar_dict.replace_int_array( - "get_comment_under", 3, request.child_value("get_comment_under") - ) + avatar_dict.replace_int_array("get_effect", 2, request.child_value("get_effect")) + avatar_dict.replace_int_array("get_object", 2, request.child_value("get_object")) + avatar_dict.replace_int_array("get_comment_over", 3, request.child_value("get_comment_over")) + avatar_dict.replace_int_array("get_comment_under", 3, request.child_value("get_comment_under")) newprofile.replace_dict("avatar", avatar_dict) avatar_add_dict = newprofile.get_dict("avatar_add") avatar_add_node = request.child("avatar_add") if avatar_add_node is not None: - avatar_add_dict.replace_int_array( - "get_hair", 2, avatar_add_node.child_value("get_hair") - ) - avatar_add_dict.replace_int_array( - "get_face", 2, avatar_add_node.child_value("get_face") - ) - avatar_add_dict.replace_int_array( - "get_body", 2, avatar_add_node.child_value("get_body") - ) - avatar_add_dict.replace_int_array( - "get_effect", 2, avatar_add_node.child_value("get_effect") - ) - avatar_add_dict.replace_int_array( - "get_object", 2, avatar_add_node.child_value("get_object") - ) - avatar_add_dict.replace_int_array( - "get_comment_over", 2, avatar_add_node.child_value("get_comment_over") - ) - avatar_add_dict.replace_int_array( - "get_comment_under", 2, avatar_add_node.child_value("get_comment_under") - ) - avatar_add_dict.replace_int_array( - "new_hair", 2, avatar_add_node.child_value("new_hair") - ) - avatar_add_dict.replace_int_array( - "new_face", 2, avatar_add_node.child_value("new_face") - ) - avatar_add_dict.replace_int_array( - "new_body", 2, avatar_add_node.child_value("new_body") - ) - avatar_add_dict.replace_int_array( - "new_effect", 2, avatar_add_node.child_value("new_effect") - ) - avatar_add_dict.replace_int_array( - "new_object", 2, avatar_add_node.child_value("new_object") - ) - avatar_add_dict.replace_int_array( - "new_comment_over", 2, avatar_add_node.child_value("new_comment_over") - ) - avatar_add_dict.replace_int_array( - "new_comment_under", 2, avatar_add_node.child_value("new_comment_under") - ) + avatar_add_dict.replace_int_array("get_hair", 2, avatar_add_node.child_value("get_hair")) + avatar_add_dict.replace_int_array("get_face", 2, avatar_add_node.child_value("get_face")) + avatar_add_dict.replace_int_array("get_body", 2, avatar_add_node.child_value("get_body")) + avatar_add_dict.replace_int_array("get_effect", 2, avatar_add_node.child_value("get_effect")) + avatar_add_dict.replace_int_array("get_object", 2, avatar_add_node.child_value("get_object")) + avatar_add_dict.replace_int_array("get_comment_over", 2, avatar_add_node.child_value("get_comment_over")) + avatar_add_dict.replace_int_array("get_comment_under", 2, avatar_add_node.child_value("get_comment_under")) + avatar_add_dict.replace_int_array("new_hair", 2, avatar_add_node.child_value("new_hair")) + avatar_add_dict.replace_int_array("new_face", 2, avatar_add_node.child_value("new_face")) + avatar_add_dict.replace_int_array("new_body", 2, avatar_add_node.child_value("new_body")) + avatar_add_dict.replace_int_array("new_effect", 2, avatar_add_node.child_value("new_effect")) + avatar_add_dict.replace_int_array("new_object", 2, avatar_add_node.child_value("new_object")) + avatar_add_dict.replace_int_array("new_comment_over", 2, avatar_add_node.child_value("new_comment_over")) + avatar_add_dict.replace_int_array("new_comment_under", 2, avatar_add_node.child_value("new_comment_under")) newprofile.replace_dict("avatar_add", avatar_add_dict) # Keep track of play statistics @@ -736,9 +576,7 @@ class PopnMusicSunnyPark(PopnMusicBase): machine = self.get_machine() root = Node.void("playerdata") - root.add_child( - Node.s8("pref", machine.data.get_int("pref", self.get_machine_region())) - ) + root.add_child(Node.s8("pref", machine.data.get_int("pref", self.get_machine_region()))) if refid is None: root.add_child(Node.string("name", "")) root.add_child(Node.s8("get_coupon_cnt", -1)) @@ -766,9 +604,7 @@ class PopnMusicSunnyPark(PopnMusicBase): root.add_child(Node.u8("comment_2", 0)) return root - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: @@ -783,12 +619,8 @@ class PopnMusicSunnyPark(PopnMusicBase): root.add_child(Node.u8("body", avatar_dict.get_int("body", 0))) root.add_child(Node.u8("effect", avatar_dict.get_int("effect", 0))) root.add_child(Node.u8("object", avatar_dict.get_int("object", 0))) - root.add_child( - Node.u8("comment_1", avatar_dict.get_int_array("comment", 2)[0]) - ) - root.add_child( - Node.u8("comment_2", avatar_dict.get_int_array("comment", 2)[1]) - ) + root.add_child(Node.u8("comment_1", avatar_dict.get_int_array("comment", 2)[0])) + root.add_child(Node.u8("comment_2", avatar_dict.get_int_array("comment", 2)[1])) return root @@ -819,9 +651,7 @@ class PopnMusicSunnyPark(PopnMusicBase): for rival in links[:2]: rivalid = rival.other_userid rivalprofile = profiles[rivalid] - scores = self.data.remote.music.get_scores( - self.game, self.music_version, rivalid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, rivalid) # First, output general profile info. friend = Node.void("friend") @@ -833,9 +663,7 @@ class PopnMusicSunnyPark(PopnMusicBase): # Set up some sane defaults. friend.add_child(Node.string("name", rivalprofile.get_str("name", "なし"))) - friend.add_child( - Node.string("g_pm_id", ID.format_extid(rivalprofile.extid)) - ) + friend.add_child(Node.string("g_pm_id", ID.format_extid(rivalprofile.extid))) friend.add_child(Node.s16("chara", rivalprofile.get_int("chara", -1))) # Set up player avatar. @@ -845,9 +673,7 @@ class PopnMusicSunnyPark(PopnMusicBase): friend.add_child(Node.u8("body", avatar_dict.get_int("body", 0))) friend.add_child(Node.u8("effect", avatar_dict.get_int("effect", 0))) friend.add_child(Node.u8("object", avatar_dict.get_int("object", 0))) - friend.add_child( - Node.u8_array("comment", avatar_dict.get_int_array("comment", 2)) - ) + friend.add_child(Node.u8_array("comment", avatar_dict.get_int_array("comment", 2))) # Perform hiscore/medal conversion. hiscore_array = [0] * int((((self.GAME_MAX_MUSIC_ID * 4) * 17) + 7) / 8) @@ -867,9 +693,7 @@ class PopnMusicSunnyPark(PopnMusicBase): if score.data.get_int("medal") == self.PLAY_MEDAL_NO_PLAY: continue - clear_medal[score.id] = clear_medal[ - score.id - ] | self.__format_medal_for_score(score) + clear_medal[score.id] = clear_medal[score.id] | self.__format_medal_for_score(score) hiscore_index = (score.id * 4) + { self.CHART_TYPE_EASY: self.GAME_CHART_TYPE_EASY_POSITION, self.CHART_TYPE_NORMAL: self.GAME_CHART_TYPE_NORMAL_POSITION, @@ -879,15 +703,13 @@ class PopnMusicSunnyPark(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ( + (hiscore_value >> 8) & 0xFF + ) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ( + (hiscore_value >> 16) & 0xFF ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) hiscore = bytes(hiscore_array) friend.add_child(Node.u16_array("clear_medal", clear_medal)) diff --git a/bemani/backend/popn/tunestreet.py b/bemani/backend/popn/tunestreet.py index 13ab4ea..78e419c 100644 --- a/bemani/backend/popn/tunestreet.py +++ b/bemani/backend/popn/tunestreet.py @@ -227,9 +227,7 @@ class PopnMusicTuneStreet(PopnMusicBase): # Format Scores hiscore_array = [0] * int((((self.GAME_MAX_MUSIC_ID * 7) * 17) + 7) / 8) - scores = self.data.remote.music.get_scores( - self.game, self.music_version, userid - ) + scores = self.data.remote.music.get_scores(self.game, self.music_version, userid) for score in scores: if score.id > self.GAME_MAX_MUSIC_ID: continue @@ -245,12 +243,8 @@ class PopnMusicTuneStreet(PopnMusicBase): flags = self.__format_flags_for_score(score) flags_index = score.id * 2 - binary_profile[108 + flags_index] = binary_profile[108 + flags_index] | ( - flags & 0xFF - ) - binary_profile[109 + flags_index] = binary_profile[109 + flags_index] | ( - (flags >> 8) & 0xFF - ) + binary_profile[108 + flags_index] = binary_profile[108 + flags_index] | (flags & 0xFF) + binary_profile[109 + flags_index] = binary_profile[109 + flags_index] | ((flags >> 8) & 0xFF) if score.chart in [ self.CHART_TYPE_ENJOY_5_BUTTON, @@ -272,23 +266,12 @@ class PopnMusicTuneStreet(PopnMusicBase): hiscore_byte_pos = int((hiscore_index * 17) / 8) hiscore_bit_pos = int((hiscore_index * 17) % 8) hiscore_value = score.points << hiscore_bit_pos - hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | ( - hiscore_value & 0xFF - ) - hiscore_array[hiscore_byte_pos + 1] = hiscore_array[ - hiscore_byte_pos + 1 - ] | ((hiscore_value >> 8) & 0xFF) - hiscore_array[hiscore_byte_pos + 2] = hiscore_array[ - hiscore_byte_pos + 2 - ] | ((hiscore_value >> 16) & 0xFF) + hiscore_array[hiscore_byte_pos] = hiscore_array[hiscore_byte_pos] | (hiscore_value & 0xFF) + hiscore_array[hiscore_byte_pos + 1] = hiscore_array[hiscore_byte_pos + 1] | ((hiscore_value >> 8) & 0xFF) + hiscore_array[hiscore_byte_pos + 2] = hiscore_array[hiscore_byte_pos + 2] | ((hiscore_value >> 16) & 0xFF) # Format most played - most_played = [ - x[0] - for x in self.data.local.music.get_most_played( - self.game, self.music_version, userid, 20 - ) - ] + most_played = [x[0] for x in self.data.local.music.get_most_played(self.game, self.music_version, userid, 20)] while len(most_played) < 20: most_played.append(-1) profile_pos = 68 @@ -322,9 +305,7 @@ class PopnMusicTuneStreet(PopnMusicBase): bought_flg = town.get_int_array("bought_flg", 3) game_config = self.get_game_config() force_unlock_songs = game_config.get_bool("force_unlock_songs") - force_unlock_customizations = game_config.get_bool( - "force_unlock_customizations" - ) + force_unlock_customizations = game_config.get_bool("force_unlock_customizations") if force_unlock_songs: bought_flg[0] = 0xFFFFFFFF @@ -390,9 +371,7 @@ class PopnMusicTuneStreet(PopnMusicBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Extract the playmode, important for scores later @@ -404,13 +383,9 @@ class PopnMusicTuneStreet(PopnMusicBase): if "option" in request.attributes: newprofile.replace_int("option", int(request.attribute("option"))) if "last_play_flag" in request.attributes: - newprofile.replace_int( - "last_play_flag", int(request.attribute("last_play_flag")) - ) + newprofile.replace_int("last_play_flag", int(request.attribute("last_play_flag"))) if "medal_and_friend" in request.attributes: - newprofile.replace_int( - "medal_and_friend", int(request.attribute("medal_and_friend")) - ) + newprofile.replace_int("medal_and_friend", int(request.attribute("medal_and_friend"))) if "music_num" in request.attributes: newprofile.replace_int("music", int(request.attribute("music_num"))) if "sheet_num" in request.attributes: @@ -418,23 +393,15 @@ class PopnMusicTuneStreet(PopnMusicBase): if "category_num" in request.attributes: newprofile.replace_int("category", int(request.attribute("category_num"))) if "read_news_no_max" in request.attributes: - newprofile.replace_int( - "read_news", int(request.attribute("read_news_no_max")) - ) + newprofile.replace_int("read_news", int(request.attribute("read_news_no_max"))) if "jubeat_collabo" in request.attributes: - newprofile.replace_int( - "jubeat_collabo", int(request.attribute("jubeat_collabo")) - ) + newprofile.replace_int("jubeat_collabo", int(request.attribute("jubeat_collabo"))) if "norma_point" in request.attributes: newprofile.replace_int("norma_point", int(request.attribute("norma_point"))) if "skin_tex_note" in request.attributes: - newprofile.replace_int( - "skin_tex_note", int(request.attribute("skin_tex_note")) - ) + newprofile.replace_int("skin_tex_note", int(request.attribute("skin_tex_note"))) if "skin_tex_cmn" in request.attributes: - newprofile.replace_int( - "skin_tex_cmn", int(request.attribute("skin_tex_cmn")) - ) + newprofile.replace_int("skin_tex_cmn", int(request.attribute("skin_tex_cmn"))) if "skin_sd_bgm" in request.attributes: newprofile.replace_int("skin_sd_bgm", int(request.attribute("skin_sd_bgm"))) if "skin_sd_se" in request.attributes: @@ -532,19 +499,13 @@ class PopnMusicTuneStreet(PopnMusicBase): if "play_type" in townnode.attributes: town.replace_int("play_type", int(townnode.attribute("play_type"))) if "base" in townnode.attributes: - town.replace_int_array( - "base", 4, [int(x) for x in townnode.attribute("base").split(",")] - ) + town.replace_int_array("base", 4, [int(x) for x in townnode.attribute("base").split(",")]) if "bought_flg" in townnode.attributes: - bought_array = [ - int(x) for x in townnode.attribute("bought_flg").split(",") - ] + bought_array = [int(x) for x in townnode.attribute("bought_flg").split(",")] if len(bought_array) == 3: game_config = self.get_game_config() force_unlock_songs = game_config.get_bool("force_unlock_songs") - force_unlock_customizations = game_config.get_bool( - "force_unlock_customizations" - ) + force_unlock_customizations = game_config.get_bool("force_unlock_customizations") old_bought_array = town.get_int_array("bought_flg", 3) if force_unlock_songs: @@ -578,10 +539,7 @@ class PopnMusicTuneStreet(PopnMusicBase): town.replace_int_array( f"building_{bid}", 8, - [ - int(x) - for x in townnode.attribute(f"building_{bid}").split(",") - ], + [int(x) for x in townnode.attribute(f"building_{bid}").split(",")], ) newprofile.replace_dict("town", town) @@ -594,23 +552,17 @@ class PopnMusicTuneStreet(PopnMusicBase): town_phase = game_config.get_int("town_phase") root = Node.void("game") - root.set_attribute( - "game_phase", str(game_phase) - ) # Phase unlocks, for song availability. + root.set_attribute("game_phase", str(game_phase)) # Phase unlocks, for song availability. root.set_attribute("boss_battle_point", "1") root.set_attribute("boss_diff", "100,100,100,100,100,100,100,100,100,100") root.set_attribute("card_phase", "3") - root.set_attribute( - "event_phase", str(town_phase) - ) # Town mode, for the main event. + root.set_attribute("event_phase", str(town_phase)) # Town mode, for the main event. root.set_attribute("gfdm_phase", "2") root.set_attribute("ir_phase", "14") root.set_attribute("jubeat_phase", "2") root.set_attribute("local_matching_enable", "1") root.set_attribute("matching_sec", "120") - root.set_attribute( - "netvs_phase", "0" - ) # Net taisen mode phase, maximum 18 (no lobby support). + root.set_attribute("netvs_phase", "0") # Net taisen mode phase, maximum 18 (no lobby support). return root def handle_game_active_request(self, request: Node) -> Node: @@ -696,9 +648,7 @@ class PopnMusicTuneStreet(PopnMusicBase): if userid is None: return root - oldprofile = self.get_profile(userid) or Profile( - self.game, self.version, refid, 0 - ) + oldprofile = self.get_profile(userid) or Profile(self.game, self.version, refid, 0) newprofile = self.unformat_profile(userid, request, oldprofile) if newprofile is not None: diff --git a/bemani/backend/reflec/base.py b/bemani/backend/reflec/base.py index 23828e3..1c48db5 100644 --- a/bemani/backend/reflec/base.py +++ b/bemani/backend/reflec/base.py @@ -26,22 +26,14 @@ class ReflecBeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): CLEAR_TYPE_NO_PLAY: Final[int] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_NO_PLAY CLEAR_TYPE_FAILED: Final[int] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_FAILED CLEAR_TYPE_CLEARED: Final[int] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_CLEARED - CLEAR_TYPE_HARD_CLEARED: Final[ - int - ] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_HARD_CLEARED - CLEAR_TYPE_S_HARD_CLEARED: Final[ - int - ] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_S_HARD_CLEARED + CLEAR_TYPE_HARD_CLEARED: Final[int] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_HARD_CLEARED + CLEAR_TYPE_S_HARD_CLEARED: Final[int] = DBConstants.REFLEC_BEAT_CLEAR_TYPE_S_HARD_CLEARED # Combo types, as saved/loaded from the DB COMBO_TYPE_NONE: Final[int] = DBConstants.REFLEC_BEAT_COMBO_TYPE_NONE - COMBO_TYPE_ALMOST_COMBO: Final[ - int - ] = DBConstants.REFLEC_BEAT_COMBO_TYPE_ALMOST_COMBO + COMBO_TYPE_ALMOST_COMBO: Final[int] = DBConstants.REFLEC_BEAT_COMBO_TYPE_ALMOST_COMBO COMBO_TYPE_FULL_COMBO: Final[int] = DBConstants.REFLEC_BEAT_COMBO_TYPE_FULL_COMBO - COMBO_TYPE_FULL_COMBO_ALL_JUST: Final[ - int - ] = DBConstants.REFLEC_BEAT_COMBO_TYPE_FULL_COMBO_ALL_JUST + COMBO_TYPE_FULL_COMBO_ALL_JUST: Final[int] = DBConstants.REFLEC_BEAT_COMBO_TYPE_FULL_COMBO_ALL_JUST # Return the local2 and lobby2 service so that matching will work on newer # Reflec Beat games. @@ -64,9 +56,7 @@ class ReflecBeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("pc") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -94,9 +84,7 @@ class ReflecBeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): return None return self.format_profile(userid, profile) - def put_profile_by_refid( - self, refid: Optional[str], request: Node - ) -> Optional[Profile]: + def put_profile_by_refid(self, refid: Optional[str], request: Node) -> Optional[Profile]: """ Given a RefID and a request node, unformat the profile and save it. """ @@ -192,17 +180,13 @@ class ReflecBeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Replace clear type with highest value and timestamps if clear_type >= scoredata.get_int("clear_type"): - scoredata.replace_int( - "clear_type", max(scoredata.get_int("clear_type"), clear_type) - ) + scoredata.replace_int("clear_type", max(scoredata.get_int("clear_type"), clear_type)) scoredata.replace_int("best_clear_type_time", now) history.replace_int("clear_type", clear_type) # Replace combo type with highest value and timestamps if combo_type >= scoredata.get_int("combo_type"): - scoredata.replace_int( - "combo_type", max(scoredata.get_int("combo_type"), combo_type) - ) + scoredata.replace_int("combo_type", max(scoredata.get_int("combo_type"), combo_type)) scoredata.replace_int("best_clear_type_time", now) history.replace_int("combo_type", combo_type) @@ -238,10 +222,7 @@ class ReflecBeatBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Update the miss count with timestamps, either if it was lowered, or if the old value was blank. # If the new value is -1 (we didn't get a miss count this time), never update the old value. if miss_count >= 0: - if ( - miss_count <= scoredata.get_int("miss_count", 999999) - or scoredata.get_int("miss_count") == -1 - ): + if miss_count <= scoredata.get_int("miss_count", 999999) or scoredata.get_int("miss_count") == -1: scoredata.replace_int( "miss_count", min(scoredata.get_int("miss_count", 999999), miss_count), diff --git a/bemani/backend/reflec/colette.py b/bemani/backend/reflec/colette.py index 89a40fc..625227f 100644 --- a/bemani/backend/reflec/colette.py +++ b/bemani/backend/reflec/colette.py @@ -157,9 +157,7 @@ class ReflecBeatColette(ReflecBeatBase): ranking = Node.void("ranking") root.add_child(ranking) - def add_hitchart( - name: str, start: int, end: int, hitchart: List[Tuple[int, int]] - ) -> None: + def add_hitchart(name: str, start: int, end: int, hitchart: List[Tuple[int, int]]) -> None: base = Node.void(name) ranking.add_child(base) base.add_child(Node.s32("bt", start)) @@ -207,18 +205,12 @@ class ReflecBeatColette(ReflecBeatBase): comments = [ achievement - for achievement in self.data.local.user.get_all_time_based_achievements( - self.game, self.version - ) + for achievement in self.data.local.user.get_all_time_based_achievements(self.game, self.version) if achievement[1].type == "puzzle_comment" ] comments.sort(key=lambda x: x[1].timestamp, reverse=True) favorites = [comment for comment in comments if comment[0] == userid] - teamcomments = [ - comment - for comment in comments - if comment[1].data.get_int("teamid") == teamid - ] + teamcomments = [comment for comment in comments if comment[1].data.get_int("teamid") == teamid] # Cap all comment blocks to the limit if limit >= 0: @@ -232,9 +224,7 @@ class ReflecBeatColette(ReflecBeatBase): comment.add_child(Node.s32("time", Time.now())) # Mapping of profiles to userIDs - uid_mapping = { - uid: prof for (uid, prof) in self.get_any_profiles([c[0] for c in comments]) - } + uid_mapping = {uid: prof for (uid, prof) in self.get_any_profiles([c[0] for c in comments])} # Handle anonymous comments by returning a default profile uid_mapping[UserID(0)] = Profile( @@ -622,9 +612,7 @@ class ReflecBeatColette(ReflecBeatBase): ) if lobby is not None: self.data.local.lobby.destroy_lobby(lobby.get_int("id")) - self.data.local.lobby.destroy_play_session_info( - self.game, self.version, userid - ) + self.data.local.lobby.destroy_play_session_info(self.game, self.version, userid) return Node.void("player") @@ -637,9 +625,7 @@ class ReflecBeatColette(ReflecBeatBase): achievements = self.data.local.user.get_achievements( previous_version.game, previous_version.version, userid ) - scores = self.data.remote.music.get_scores( - previous_version.game, previous_version.version, userid - ) + scores = self.data.remote.music.get_scores(previous_version.game, previous_version.version, userid) else: profile = None @@ -715,9 +701,7 @@ class ReflecBeatColette(ReflecBeatBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) scores = self.data.remote.music.get_scores(self.game, self.version, userid) links = self.data.local.user.get_links(self.game, self.version, userid) root = Node.void("player") @@ -749,9 +733,7 @@ class ReflecBeatColette(ReflecBeatBase): base.add_child(Node.string("tname", profile.get_str("team_name", ""))) base.add_child(Node.string("cmnt", "")) base.add_child(Node.s32("uattr", profile.get_int("uattr"))) - base.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 50)) - ) + base.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 50))) base.add_child(Node.s32("tbs", -1)) base.add_child(Node.s32("tbs_r", -1)) @@ -793,73 +775,41 @@ class ReflecBeatColette(ReflecBeatBase): custom.add_child(Node.u8("st_jdg_disp", customdict.get_int("st_jdg_disp"))) custom.add_child(Node.u8("st_tm_disp", customdict.get_int("st_tm_disp"))) custom.add_child(Node.u8("st_rnd", customdict.get_int("st_rnd"))) - custom.add_child( - Node.s16_array("schat_0", customdict.get_int_array("schat_0", 9)) - ) - custom.add_child( - Node.s16_array("schat_1", customdict.get_int_array("schat_1", 9)) - ) - custom.add_child( - Node.s16_array("ichat_0", customdict.get_int_array("ichat_0", 6)) - ) - custom.add_child( - Node.s16_array("ichat_1", customdict.get_int_array("ichat_1", 6)) - ) + custom.add_child(Node.s16_array("schat_0", customdict.get_int_array("schat_0", 9))) + custom.add_child(Node.s16_array("schat_1", customdict.get_int_array("schat_1", 9))) + custom.add_child(Node.s16_array("ichat_0", customdict.get_int_array("ichat_0", 6))) + custom.add_child(Node.s16_array("ichat_1", customdict.get_int_array("ichat_1", 6))) # Player external config config = Node.void("config") configdict = profile.get_dict("config") pdata.add_child(config) config.add_child(Node.u8("msel_bgm", configdict.get_int("msel_bgm"))) - config.add_child( - Node.u8("narrowdown_type", configdict.get_int("narrowdown_type")) - ) + config.add_child(Node.u8("narrowdown_type", configdict.get_int("narrowdown_type"))) config.add_child(Node.s16("icon_id", configdict.get_int("icon_id"))) config.add_child(Node.s16("byword_0", configdict.get_int("byword_0"))) config.add_child(Node.s16("byword_1", configdict.get_int("byword_1"))) - config.add_child( - Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0")) - ) - config.add_child( - Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1")) - ) + config.add_child(Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0"))) + config.add_child(Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1"))) config.add_child(Node.u8("mrec_type", configdict.get_int("mrec_type"))) config.add_child(Node.u8("tab_sel", configdict.get_int("tab_sel"))) config.add_child(Node.u8("card_disp", configdict.get_int("card_disp"))) - config.add_child( - Node.u8("score_tab_disp", configdict.get_int("score_tab_disp")) - ) - config.add_child( - Node.s16("last_music_id", configdict.get_int("last_music_id", -1)) - ) - config.add_child( - Node.u8("last_note_grade", configdict.get_int("last_note_grade")) - ) + config.add_child(Node.u8("score_tab_disp", configdict.get_int("score_tab_disp"))) + config.add_child(Node.s16("last_music_id", configdict.get_int("last_music_id", -1))) + config.add_child(Node.u8("last_note_grade", configdict.get_int("last_note_grade"))) config.add_child(Node.u8("sort_type", configdict.get_int("sort_type"))) - config.add_child( - Node.u8("rival_panel_type", configdict.get_int("rival_panel_type")) - ) - config.add_child( - Node.u64("random_entry_work", configdict.get_int("random_entry_work")) - ) - config.add_child( - Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type")) - ) + config.add_child(Node.u8("rival_panel_type", configdict.get_int("rival_panel_type"))) + config.add_child(Node.u64("random_entry_work", configdict.get_int("random_entry_work"))) + config.add_child(Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type"))) config.add_child(Node.bool("is_tweet", configdict.get_bool("is_tweet"))) - config.add_child( - Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter")) - ) + config.add_child(Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter"))) # Stamps stamp = Node.void("stamp") stampdict = profile.get_dict("stamp") pdata.add_child(stamp) - stamp.add_child( - Node.s32_array("stmpcnt", stampdict.get_int_array("stmpcnt", 5)) - ) - stamp.add_child( - Node.s32_array("tcktcnt", stampdict.get_int_array("tcktcnt", 5)) - ) + stamp.add_child(Node.s32_array("stmpcnt", stampdict.get_int_array("stmpcnt", 5))) + stamp.add_child(Node.s32_array("tcktcnt", stampdict.get_int_array("tcktcnt", 5))) stamp.add_child(Node.s64("area", stampdict.get_int("area"))) stamp.add_child(Node.s64("prfvst", stampdict.get_int("prfvst"))) stamp.add_child(Node.s32("reserve", stampdict.get_int("reserve"))) @@ -993,73 +943,47 @@ class ReflecBeatColette(ReflecBeatBase): rec.add_child(Node.s16("cmb", score.data.get_int("combo"))) rec.add_child(Node.s16("ms", score.data.get_int("miss_count"))) rec.add_child(Node.s32("bscrt", score.timestamp)) - rec.add_child( - Node.s32("bart", score.data.get_int("best_achievement_rate_time")) - ) + rec.add_child(Node.s32("bart", score.data.get_int("best_achievement_rate_time"))) rec.add_child(Node.s32("bctt", score.data.get_int("best_clear_type_time"))) rec.add_child(Node.s32("bmst", score.data.get_int("best_miss_count_time"))) rec.add_child(Node.s32("time", score.data.get_int("last_played_time"))) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() - newprofile.replace_int( - "lid", ID.parse_machine_id(request.child_value("pdata/account/lid")) - ) + newprofile.replace_int("lid", ID.parse_machine_id(request.child_value("pdata/account/lid"))) newprofile.replace_str("name", request.child_value("pdata/base/name")) newprofile.replace_int("exp", request.child_value("pdata/base/exp")) newprofile.replace_int("lvl", request.child_value("pdata/base/lvl")) newprofile.replace_int("mg", request.child_value("pdata/base/mg")) newprofile.replace_int("ap", request.child_value("pdata/base/ap")) - newprofile.replace_int_array( - "hidden_param", 50, request.child_value("pdata/base/hidden_param") - ) + newprofile.replace_int_array("hidden_param", 50, request.child_value("pdata/base/hidden_param")) configdict = newprofile.get_dict("config") config = request.child("pdata/config") if config: configdict.replace_int("msel_bgm", config.child_value("msel_bgm")) - configdict.replace_int( - "narrowdown_type", config.child_value("narrowdown_type") - ) + configdict.replace_int("narrowdown_type", config.child_value("narrowdown_type")) configdict.replace_int("icon_id", config.child_value("icon_id")) configdict.replace_int("byword_0", config.child_value("byword_0")) configdict.replace_int("byword_1", config.child_value("byword_1")) - configdict.replace_bool( - "is_auto_byword_0", config.child_value("is_auto_byword_0") - ) - configdict.replace_bool( - "is_auto_byword_1", config.child_value("is_auto_byword_1") - ) + configdict.replace_bool("is_auto_byword_0", config.child_value("is_auto_byword_0")) + configdict.replace_bool("is_auto_byword_1", config.child_value("is_auto_byword_1")) configdict.replace_int("mrec_type", config.child_value("mrec_type")) configdict.replace_int("tab_sel", config.child_value("tab_sel")) configdict.replace_int("card_disp", config.child_value("card_disp")) - configdict.replace_int( - "score_tab_disp", config.child_value("score_tab_disp") - ) + configdict.replace_int("score_tab_disp", config.child_value("score_tab_disp")) configdict.replace_int("last_music_id", config.child_value("last_music_id")) - configdict.replace_int( - "last_note_grade", config.child_value("last_note_grade") - ) + configdict.replace_int("last_note_grade", config.child_value("last_note_grade")) configdict.replace_int("sort_type", config.child_value("sort_type")) - configdict.replace_int( - "rival_panel_type", config.child_value("rival_panel_type") - ) - configdict.replace_int( - "random_entry_work", config.child_value("random_entry_work") - ) - configdict.replace_int( - "folder_lamp_type", config.child_value("folder_lamp_type") - ) + configdict.replace_int("rival_panel_type", config.child_value("rival_panel_type")) + configdict.replace_int("random_entry_work", config.child_value("random_entry_work")) + configdict.replace_int("folder_lamp_type", config.child_value("folder_lamp_type")) configdict.replace_bool("is_tweet", config.child_value("is_tweet")) - configdict.replace_bool( - "is_link_twitter", config.child_value("is_link_twitter") - ) + configdict.replace_bool("is_link_twitter", config.child_value("is_link_twitter")) newprofile.replace_dict("config", configdict) customdict = newprofile.get_dict("custom") diff --git a/bemani/backend/reflec/groovin.py b/bemani/backend/reflec/groovin.py index bc76db5..e2c6ff2 100644 --- a/bemani/backend/reflec/groovin.py +++ b/bemani/backend/reflec/groovin.py @@ -131,9 +131,7 @@ class ReflecBeatGroovin(ReflecBeatBase): userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: profile = self.get_profile(userid) - info = self.data.local.lobby.get_play_session_info( - self.game, self.version, userid - ) + info = self.data.local.lobby.get_play_session_info(self.game, self.version, userid) if profile is None or info is None: return root @@ -214,9 +212,7 @@ class ReflecBeatGroovin(ReflecBeatBase): continue profile = self.get_profile(user) - info = self.data.local.lobby.get_play_session_info( - self.game, self.version, userid - ) + info = self.data.local.lobby.get_play_session_info(self.game, self.version, userid) if profile is None or info is None: # No profile info, don't return this lobby return root @@ -306,16 +302,11 @@ class ReflecBeatGroovin(ReflecBeatBase): ) machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - lids = [ - machine.id - for machine in self.data.local.machine.get_all_machines(machine.arcade) - ] + lids = [machine.id for machine in self.data.local.machine.get_all_machines(machine.arcade)] else: lids = [machine.id] - relevant_profiles = [ - profile for profile in all_profiles if profile[1].get_int("lid", -1) in lids - ] + relevant_profiles = [profile for profile in all_profiles if profile[1].get_int("lid", -1) in lids] for rootnode, timeoffset in [ (today, 0), @@ -343,10 +334,7 @@ class ReflecBeatGroovin(ReflecBeatBase): scores_by_user[userid][attempt.id][attempt.chart] = attempt else: # If this attempt is better than the stored one, replace it - if ( - scores_by_user[userid][attempt.id][attempt.chart].points - < attempt.points - ): + if scores_by_user[userid][attempt.id][attempt.chart].points < attempt.points: scores_by_user[userid][attempt.id][attempt.chart] = attempt # Calculate points earned by user in the day @@ -355,33 +343,20 @@ class ReflecBeatGroovin(ReflecBeatBase): points_by_user[userid] = 0 for mid in scores_by_user[userid]: for chart in scores_by_user[userid][mid]: - points_by_user[userid] = ( - points_by_user[userid] - + scores_by_user[userid][mid][chart].points - ) + points_by_user[userid] = points_by_user[userid] + scores_by_user[userid][mid][chart].points # Output that day's earned points for userid, profile in relevant_profiles: data = Node.void("data") rootnode.add_child(data) - data.add_child( - Node.s16( - "day_id", int((Time.now() - timeoffset) / Time.SECONDS_IN_DAY) - ) - ) + data.add_child(Node.s16("day_id", int((Time.now() - timeoffset) / Time.SECONDS_IN_DAY))) data.add_child(Node.s32("user_id", profile.extid)) - data.add_child( - Node.s16("icon_id", profile.get_dict("config").get_int("icon_id")) - ) - data.add_child( - Node.s16("point", min(points_by_user.get(userid, 0), 32767)) - ) + data.add_child(Node.s16("icon_id", profile.get_dict("config").get_int("icon_id"))) + data.add_child(Node.s16("point", min(points_by_user.get(userid, 0), 32767))) data.add_child(Node.s32("update_time", Time.now())) data.add_child(Node.string("name", profile.get_str("name"))) - rootnode.add_child( - Node.s32("timestamp", Time.beginning_of_today() - timeoffset) - ) + rootnode.add_child(Node.s32("timestamp", Time.beginning_of_today() - timeoffset)) def handle_info_rb4common_request(self, request: Node) -> Node: root = Node.void("info") @@ -398,9 +373,7 @@ class ReflecBeatGroovin(ReflecBeatBase): ranking = Node.void("ranking") root.add_child(ranking) - def add_hitchart( - name: str, start: int, end: int, hitchart: List[Tuple[int, int]] - ) -> None: + def add_hitchart(name: str, start: int, end: int, hitchart: List[Tuple[int, int]]) -> None: base = Node.void(name) ranking.add_child(base) base.add_child(Node.s32("bt", start)) @@ -483,17 +456,11 @@ class ReflecBeatGroovin(ReflecBeatBase): data.add_child( Node.s8( "clear_type", - self.__db_to_game_clear_type( - score.data.get_int("clear_type") - ), + self.__db_to_game_clear_type(score.data.get_int("clear_type")), ) ) data.add_child(Node.s32("user_id", profile.extid)) - data.add_child( - Node.s16( - "icon_id", profile.get_dict("config").get_int("icon_id") - ) - ) + data.add_child(Node.s16("icon_id", profile.get_dict("config").get_int("icon_id"))) data.add_child(Node.s32("score", score.points)) data.add_child(Node.s32("time", score.timestamp)) data.add_child(Node.string("name", profile.get_str("name"))) @@ -508,16 +475,12 @@ class ReflecBeatGroovin(ReflecBeatBase): comments = [ achievement - for achievement in self.data.local.user.get_all_time_based_achievements( - self.game, self.version - ) + for achievement in self.data.local.user.get_all_time_based_achievements(self.game, self.version) if achievement[1].type == "puzzle_comment" ] comments.sort(key=lambda x: x[1].timestamp, reverse=True) favorites = [comment for comment in comments if comment[0] == userid] - locationcomments = [ - comment for comment in comments if comment[1].data.get_int("locid") == locid - ] + locationcomments = [comment for comment in comments if comment[1].data.get_int("locid") == locid] # Cap all comment blocks to the limit if limit >= 0: @@ -531,9 +494,7 @@ class ReflecBeatGroovin(ReflecBeatBase): comment.add_child(Node.s32("time", Time.now())) # Mapping of profiles to userIDs - uid_mapping = { - uid: prof for (uid, prof) in self.get_any_profiles([c[0] for c in comments]) - } + uid_mapping = {uid: prof for (uid, prof) in self.get_any_profiles([c[0] for c in comments])} # Handle anonymous comments by returning a default profile uid_mapping[UserID(0)] = Profile( @@ -552,9 +513,7 @@ class ReflecBeatGroovin(ReflecBeatBase): cmnt.add_child(Node.string("name", uid_mapping[uid].get_str("name"))) cmnt.add_child(Node.s16("icon", ach.data.get_int("icon"))) cmnt.add_child(Node.s8("bln", ach.data.get_int("bln"))) - cmnt.add_child( - Node.string("lid", ID.format_machine_id(ach.data.get_int("locid"))) - ) + cmnt.add_child(Node.string("lid", ID.format_machine_id(ach.data.get_int("locid")))) cmnt.add_child(Node.s8("pref", ach.data.get_int("prefecture"))) cmnt.add_child(Node.s32("time", ach.timestamp)) cmnt.add_child(Node.string("comment", ach.data.get_str("comment"))) @@ -654,9 +613,7 @@ class ReflecBeatGroovin(ReflecBeatBase): ) if lobby is not None: self.data.local.lobby.destroy_lobby(lobby.get_int("id")) - self.data.local.lobby.destroy_play_session_info( - self.game, self.version, userid - ) + self.data.local.lobby.destroy_play_session_info(self.game, self.version, userid) return Node.void("player") @@ -664,9 +621,7 @@ class ReflecBeatGroovin(ReflecBeatBase): extid = request.child_value("user_id") userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) else: achievements = [] @@ -714,25 +669,18 @@ class ReflecBeatGroovin(ReflecBeatBase): rec.add_child(Node.s16("mid", score.id)) rec.add_child(Node.s8("ntgrd", score.chart)) rec.add_child(Node.s32("pc", score.plays)) - rec.add_child( - Node.s8( - "ct", self.__db_to_game_clear_type(score.data.get_int("clear_type")) - ) - ) + rec.add_child(Node.s8("ct", self.__db_to_game_clear_type(score.data.get_int("clear_type")))) rec.add_child(Node.s16("ar", score.data.get_int("achievement_rate"))) rec.add_child(Node.s16("scr", score.points)) rec.add_child(Node.s16("ms", score.data.get_int("miss_count"))) rec.add_child( Node.s16( "param", - self.__db_to_game_combo_type(score.data.get_int("combo_type")) - + score.data.get_int("param"), + self.__db_to_game_combo_type(score.data.get_int("combo_type")) + score.data.get_int("param"), ) ) rec.add_child(Node.s32("bscrt", score.timestamp)) - rec.add_child( - Node.s32("bart", score.data.get_int("best_achievement_rate_time")) - ) + rec.add_child(Node.s32("bart", score.data.get_int("best_achievement_rate_time"))) rec.add_child(Node.s32("bctt", score.data.get_int("best_clear_type_time"))) rec.add_child(Node.s32("bmst", score.data.get_int("best_miss_count_time"))) rec.add_child(Node.s32("time", score.data.get_int("last_played_time"))) @@ -748,9 +696,7 @@ class ReflecBeatGroovin(ReflecBeatBase): score = None profile = None else: - score = self.data.remote.music.get_score( - self.game, self.version, userid, songid, chart - ) + score = self.data.remote.music.get_score(self.game, self.version, userid, songid, chart) profile = self.get_any_profile(userid) root = Node.void("player") @@ -762,9 +708,7 @@ class ReflecBeatGroovin(ReflecBeatBase): player_select_score.add_child(Node.string("name", profile.get_str("name"))) player_select_score.add_child(Node.s32("m_score", score.points)) player_select_score.add_child(Node.s32("m_scoreTime", score.timestamp)) - player_select_score.add_child( - Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id")) - ) + player_select_score.add_child(Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id"))) return root def handle_player_rbsvLinkageSave_request(self, request: Node) -> Node: @@ -800,11 +744,7 @@ class ReflecBeatGroovin(ReflecBeatBase): all_songs = self.data.local.music.get_all_songs(self.game, self.version) # Figure out what song IDs are new - new_songs = { - song.id - for song in all_songs - if song.data.get_int("folder", 0) == self.version - } + new_songs = {song.id for song in all_songs if song.data.get_int("folder", 0) == self.version} # Now grab all participating users that had scores all_users = {userid for (userid, score) in all_scores} @@ -815,68 +755,40 @@ class ReflecBeatGroovin(ReflecBeatBase): userid: [ score for (uid, score) in all_scores - if uid == userid - and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED + if uid == userid and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED ] for userid in all_users } # Now, sum up the scores into the six categories that the game expects. total_scores = sorted( - [ - sum([score.points for score in scores]) - for userid, scores in scores_by_user.items() - ], + [sum([score.points for score in scores]) for userid, scores in scores_by_user.items()], reverse=True, ) basic_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_BASIC - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_BASIC]) for userid, scores in scores_by_user.items() ], reverse=True, ) medium_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_MEDIUM - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_MEDIUM]) for userid, scores in scores_by_user.items() ], reverse=True, ) hard_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_HARD - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_HARD]) for userid, scores in scores_by_user.items() ], reverse=True, ) special_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_SPECIAL - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_SPECIAL]) for userid, scores in scores_by_user.items() ], reverse=True, @@ -943,9 +855,7 @@ class ReflecBeatGroovin(ReflecBeatBase): achievements = self.data.local.user.get_achievements( previous_version.game, previous_version.version, userid ) - scores = self.data.remote.music.get_scores( - previous_version.game, previous_version.version, userid - ) + scores = self.data.remote.music.get_scores(previous_version.game, previous_version.version, userid) else: profile = None @@ -997,15 +907,9 @@ class ReflecBeatGroovin(ReflecBeatBase): mrec.add_child(Node.s16("ms", score.data.get_int("miss_count"))) mrec.add_child(Node.u16("ver", 0)) mrec.add_child(Node.s32("bst", score.timestamp)) - mrec.add_child( - Node.s32("bat", score.data.get_int("best_achievement_rate_time")) - ) - mrec.add_child( - Node.s32("bct", score.data.get_int("best_clear_type_time")) - ) - mrec.add_child( - Node.s32("bmt", score.data.get_int("best_miss_count_time")) - ) + mrec.add_child(Node.s32("bat", score.data.get_int("best_achievement_rate_time"))) + mrec.add_child(Node.s32("bct", score.data.get_int("best_clear_type_time"))) + mrec.add_child(Node.s32("bmt", score.data.get_int("best_miss_count_time"))) return root @@ -1023,9 +927,7 @@ class ReflecBeatGroovin(ReflecBeatBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) links = self.data.local.user.get_links(self.game, self.version, userid) root = Node.void("player") pdata = Node.void("pdata") @@ -1086,9 +988,7 @@ class ReflecBeatGroovin(ReflecBeatBase): rprofile = self.get_profile(link.other_userid) if rprofile is None: continue - lobbyinfo = self.data.local.lobby.get_play_session_info( - self.game, self.version, link.other_userid - ) + lobbyinfo = self.data.local.lobby.get_play_session_info(self.game, self.version, link.other_userid) if lobbyinfo is None: lobbyinfo = ValidatedDict() @@ -1114,9 +1014,7 @@ class ReflecBeatGroovin(ReflecBeatBase): stamp = Node.void("stamp") stampdict = profile.get_dict("stamp") pdata.add_child(stamp) - stamp.add_child( - Node.s32_array("stmpcnt", stampdict.get_int_array("stmpcnt", 10)) - ) + stamp.add_child(Node.s32_array("stmpcnt", stampdict.get_int_array("stmpcnt", 10))) stamp.add_child(Node.s64("area", stampdict.get_int("area"))) stamp.add_child(Node.s64("prfvst", stampdict.get_int("prfvst"))) @@ -1125,48 +1023,26 @@ class ReflecBeatGroovin(ReflecBeatBase): config = Node.void("config") pdata.add_child(config) config.add_child(Node.u8("msel_bgm", configdict.get_int("msel_bgm"))) - config.add_child( - Node.u8("narrowdown_type", configdict.get_int("narrowdown_type")) - ) + config.add_child(Node.u8("narrowdown_type", configdict.get_int("narrowdown_type"))) config.add_child(Node.s16("icon_id", configdict.get_int("icon_id"))) config.add_child(Node.s16("byword_0", configdict.get_int("byword_0"))) config.add_child(Node.s16("byword_1", configdict.get_int("byword_1"))) - config.add_child( - Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0")) - ) - config.add_child( - Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1")) - ) + config.add_child(Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0"))) + config.add_child(Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1"))) config.add_child(Node.u8("mrec_type", configdict.get_int("mrec_type"))) config.add_child(Node.u8("tab_sel", configdict.get_int("tab_sel"))) config.add_child(Node.u8("card_disp", configdict.get_int("card_disp"))) - config.add_child( - Node.u8("score_tab_disp", configdict.get_int("score_tab_disp")) - ) - config.add_child( - Node.s16("last_music_id", configdict.get_int("last_music_id", -1)) - ) - config.add_child( - Node.u8("last_note_grade", configdict.get_int("last_note_grade")) - ) + config.add_child(Node.u8("score_tab_disp", configdict.get_int("score_tab_disp"))) + config.add_child(Node.s16("last_music_id", configdict.get_int("last_music_id", -1))) + config.add_child(Node.u8("last_note_grade", configdict.get_int("last_note_grade"))) config.add_child(Node.u8("sort_type", configdict.get_int("sort_type"))) - config.add_child( - Node.u8("rival_panel_type", configdict.get_int("rival_panel_type")) - ) - config.add_child( - Node.u64("random_entry_work", configdict.get_int("random_entry_work")) - ) - config.add_child( - Node.u64("custom_folder_work", configdict.get_int("custom_folder_work")) - ) + config.add_child(Node.u8("rival_panel_type", configdict.get_int("rival_panel_type"))) + config.add_child(Node.u64("random_entry_work", configdict.get_int("random_entry_work"))) + config.add_child(Node.u64("custom_folder_work", configdict.get_int("custom_folder_work"))) config.add_child(Node.u8("folder_type", configdict.get_int("folder_type"))) - config.add_child( - Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type")) - ) + config.add_child(Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type"))) config.add_child(Node.bool("is_tweet", configdict.get_bool("is_tweet"))) - config.add_child( - Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter")) - ) + config.add_child(Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter"))) # Customizations customdict = profile.get_dict("custom") @@ -1186,16 +1062,10 @@ class ReflecBeatGroovin(ReflecBeatBase): custom.add_child(Node.u8("st_rnd", customdict.get_int("st_rnd"))) custom.add_child(Node.u8("st_hazard", customdict.get_int("st_hazard"))) custom.add_child(Node.u8("st_clr_cond", customdict.get_int("st_clr_cond"))) - custom.add_child( - Node.s16_array("schat_0", customdict.get_int_array("schat_0", 10)) - ) - custom.add_child( - Node.s16_array("schat_1", customdict.get_int_array("schat_1", 10)) - ) + custom.add_child(Node.s16_array("schat_0", customdict.get_int_array("schat_0", 10))) + custom.add_child(Node.s16_array("schat_1", customdict.get_int_array("schat_1", 10))) custom.add_child(Node.u8("cheer_voice", customdict.get_int("cheer_voice"))) - custom.add_child( - Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp")) - ) + custom.add_child(Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp"))) # Unlocks released = Node.void("released") @@ -1249,9 +1119,7 @@ class ReflecBeatGroovin(ReflecBeatBase): info.add_child(Node.u8("type", announcementtype)) info.add_child(Node.u16("id", announcement.id)) info.add_child(Node.u16("param", announcement.data.get_int("param"))) - info.add_child( - Node.bool("bneedannounce", announcement.data.get_bool("need")) - ) + info.add_child(Node.bool("bneedannounce", announcement.data.get_bool("need"))) # Dojo ranking return dojo = Node.void("dojo") @@ -1268,12 +1136,8 @@ class ReflecBeatGroovin(ReflecBeatBase): rec.add_child(Node.s32("total_ar", entry.data.get_int("ar"))) rec.add_child(Node.s32("total_score", entry.data.get_int("score"))) rec.add_child(Node.s32("play_count", entry.data.get_int("plays"))) - rec.add_child( - Node.s32("last_play_time", entry.data.get_int("play_timestamp")) - ) - rec.add_child( - Node.s32("record_update_time", entry.data.get_int("record_timestamp")) - ) + rec.add_child(Node.s32("last_play_time", entry.data.get_int("play_timestamp"))) + rec.add_child(Node.s32("record_update_time", entry.data.get_int("record_timestamp"))) rec.add_child(Node.s32("rank", 0)) # Player Parameters @@ -1289,9 +1153,7 @@ class ReflecBeatGroovin(ReflecBeatBase): player_param.add_child(itemnode) itemnode.add_child(Node.s32("type", itemtype)) itemnode.add_child(Node.s32("bank", param.id)) - itemnode.add_child( - Node.s32_array("data", param.data.get_int_array("data", 256)) - ) + itemnode.add_child(Node.s32_array("data", param.data.get_int_array("data", 256))) # Shop score for players self.__add_shop_score(pdata) @@ -1349,16 +1211,12 @@ class ReflecBeatGroovin(ReflecBeatBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() # Save base player profile info - newprofile.replace_int( - "lid", ID.parse_machine_id(request.child_value("pdata/account/lid")) - ) + newprofile.replace_int("lid", ID.parse_machine_id(request.child_value("pdata/account/lid"))) newprofile.replace_str("name", request.child_value("pdata/base/name")) newprofile.replace_int("exp", request.child_value("pdata/base/exp")) newprofile.replace_int("lvl", request.child_value("pdata/base/lvl")) @@ -1442,46 +1300,26 @@ class ReflecBeatGroovin(ReflecBeatBase): config = request.child("pdata/config") if config: configdict.replace_int("msel_bgm", config.child_value("msel_bgm")) - configdict.replace_int( - "narrowdown_type", config.child_value("narrowdown_type") - ) + configdict.replace_int("narrowdown_type", config.child_value("narrowdown_type")) configdict.replace_int("icon_id", config.child_value("icon_id")) configdict.replace_int("byword_0", config.child_value("byword_0")) configdict.replace_int("byword_1", config.child_value("byword_1")) - configdict.replace_bool( - "is_auto_byword_0", config.child_value("is_auto_byword_0") - ) - configdict.replace_bool( - "is_auto_byword_1", config.child_value("is_auto_byword_1") - ) + configdict.replace_bool("is_auto_byword_0", config.child_value("is_auto_byword_0")) + configdict.replace_bool("is_auto_byword_1", config.child_value("is_auto_byword_1")) configdict.replace_int("mrec_type", config.child_value("mrec_type")) configdict.replace_int("tab_sel", config.child_value("tab_sel")) configdict.replace_int("card_disp", config.child_value("card_disp")) - configdict.replace_int( - "score_tab_disp", config.child_value("score_tab_disp") - ) + configdict.replace_int("score_tab_disp", config.child_value("score_tab_disp")) configdict.replace_int("last_music_id", config.child_value("last_music_id")) - configdict.replace_int( - "last_note_grade", config.child_value("last_note_grade") - ) + configdict.replace_int("last_note_grade", config.child_value("last_note_grade")) configdict.replace_int("sort_type", config.child_value("sort_type")) - configdict.replace_int( - "rival_panel_type", config.child_value("rival_panel_type") - ) - configdict.replace_int( - "random_entry_work", config.child_value("random_entry_work") - ) - configdict.replace_int( - "custom_folder_work", config.child_value("custom_folder_work") - ) + configdict.replace_int("rival_panel_type", config.child_value("rival_panel_type")) + configdict.replace_int("random_entry_work", config.child_value("random_entry_work")) + configdict.replace_int("custom_folder_work", config.child_value("custom_folder_work")) configdict.replace_int("folder_type", config.child_value("folder_type")) - configdict.replace_int( - "folder_lamp_type", config.child_value("folder_lamp_type") - ) + configdict.replace_int("folder_lamp_type", config.child_value("folder_lamp_type")) configdict.replace_bool("is_tweet", config.child_value("is_tweet")) - configdict.replace_bool( - "is_link_twitter", config.child_value("is_link_twitter") - ) + configdict.replace_bool("is_link_twitter", config.child_value("is_link_twitter")) newprofile.replace_dict("config", configdict) # Save player custom settings @@ -1505,9 +1343,7 @@ class ReflecBeatGroovin(ReflecBeatBase): customdict.replace_int_array("schat_0", 10, custom.child_value("schat_0")) customdict.replace_int_array("schat_1", 10, custom.child_value("schat_1")) customdict.replace_int("cheer_voice", custom.child_value("cheer_voice")) - customdict.replace_int( - "same_time_note_disp", custom.child_value("same_time_note_disp") - ) + customdict.replace_int("same_time_note_disp", custom.child_value("same_time_note_disp")) newprofile.replace_dict("custom", customdict) # Save player parameter info @@ -1543,9 +1379,7 @@ class ReflecBeatGroovin(ReflecBeatBase): # I assume this is copypasta, but I want to be sure extid = child.child_value("user_id") if extid != newprofile.extid: - raise Exception( - f"Unexpected user ID, got {extid} expecting {newprofile.extid}" - ) + raise Exception(f"Unexpected user ID, got {extid} expecting {newprofile.extid}") episode_type = child.child_value("type") episode_value0 = child.child_value("value0") @@ -1622,9 +1456,7 @@ class ReflecBeatGroovin(ReflecBeatBase): continue extid = child.child_value("id") - other_userid = self.data.remote.user.from_extid( - self.game, self.version, extid - ) + other_userid = self.data.remote.user.from_extid(self.game, self.version, extid) if other_userid is None: continue diff --git a/bemani/backend/reflec/limelight.py b/bemani/backend/reflec/limelight.py index 57845eb..f868b6f 100644 --- a/bemani/backend/reflec/limelight.py +++ b/bemani/backend/reflec/limelight.py @@ -176,15 +176,11 @@ class ReflecBeatLimelight(ReflecBeatBase): comments = [ achievement - for achievement in self.data.local.user.get_all_time_based_achievements( - self.game, self.version - ) + for achievement in self.data.local.user.get_all_time_based_achievements(self.game, self.version) if achievement[1].type == "puzzle_comment" ] comments.sort(key=lambda x: x[1].timestamp, reverse=True) - statuses = self.data.local.lobby.get_all_play_session_infos( - self.game, self.version - ) + statuses = self.data.local.lobby.get_all_play_session_infos(self.game, self.version) statuses.sort(key=lambda x: x[1]["time"], reverse=True) # Cap all comment blocks to the limit @@ -194,10 +190,7 @@ class ReflecBeatLimelight(ReflecBeatBase): # Mapping of profiles to userIDs uid_mapping = { - uid: prof - for (uid, prof) in self.get_any_profiles( - [c[0] for c in comments] + [s[0] for s in statuses] - ) + uid: prof for (uid, prof) in self.get_any_profiles([c[0] for c in comments] + [s[0] for s in statuses]) } # Mapping of location ID to machine name @@ -254,9 +247,7 @@ class ReflecBeatLimelight(ReflecBeatBase): s.add_child(Node.s32("exp", uid_mapping[uid].get_int("exp"))) s.add_child(Node.s32("customize", status.get_int("customize"))) s.add_child(Node.s32("tid", uid_mapping[uid].get_int("team_id", -1))) - s.add_child( - Node.string("t_name", uid_mapping[uid].get_str("team_name", "")) - ) + s.add_child(Node.string("t_name", uid_mapping[uid].get_str("team_name", ""))) s.add_child(Node.string("lid", status.get_str("lid"))) s.add_child(Node.string("s_name", lid_mapping[lid])) s.add_child(Node.s8("pref", status.get_int("prefecture"))) @@ -457,9 +448,7 @@ class ReflecBeatLimelight(ReflecBeatBase): refid = request.child_value("rid") userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - self.data.local.lobby.put_play_session_info( - self.game, self.version, userid, {} - ) + self.data.local.lobby.put_play_session_info(self.game, self.version, userid, {}) root = Node.void("player") root.add_child(Node.bool("is_suc", True)) @@ -525,9 +514,7 @@ class ReflecBeatLimelight(ReflecBeatBase): ) if lobby is not None: self.data.local.lobby.destroy_lobby(lobby.get_int("id")) - self.data.local.lobby.destroy_play_session_info( - self.game, self.version, userid - ) + self.data.local.lobby.destroy_play_session_info(self.game, self.version, userid) return Node.void("player") @@ -559,9 +546,7 @@ class ReflecBeatLimelight(ReflecBeatBase): achievements = self.data.local.user.get_achievements( previous_version.game, previous_version.version, userid ) - scores = self.data.remote.music.get_scores( - previous_version.game, previous_version.version, userid - ) + scores = self.data.remote.music.get_scores(previous_version.game, previous_version.version, userid) else: profile = None @@ -598,15 +583,9 @@ class ReflecBeatLimelight(ReflecBeatBase): mrecord.add_child(mrec) mrec.add_child(Node.s32("mid", score.id)) mrec.add_child(Node.s32("ctype", score.chart)) - mrec.add_child( - Node.s32("win", score.data.get_dict("stats").get_int("win")) - ) - mrec.add_child( - Node.s32("lose", score.data.get_dict("stats").get_int("win")) - ) - mrec.add_child( - Node.s32("draw", score.data.get_dict("stats").get_int("win")) - ) + mrec.add_child(Node.s32("win", score.data.get_dict("stats").get_int("win"))) + mrec.add_child(Node.s32("lose", score.data.get_dict("stats").get_int("win"))) + mrec.add_child(Node.s32("draw", score.data.get_dict("stats").get_int("win"))) mrec.add_child(Node.s32("score", score.points)) mrec.add_child(Node.s32("combo", score.data.get_int("combo"))) mrec.add_child(Node.s32("miss", score.data.get_int("miss_count"))) @@ -626,9 +605,7 @@ class ReflecBeatLimelight(ReflecBeatBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) scores = self.data.remote.music.get_scores(self.game, self.version, userid) links = self.data.local.user.get_links(self.game, self.version, userid) root = Node.void("player") @@ -672,50 +649,24 @@ class ReflecBeatLimelight(ReflecBeatBase): custom.add_child(Node.u8("se_s", customdict.get_int("se_s"))) custom.add_child(Node.u8("se_s_v", customdict.get_int("se_s_v"))) custom.add_child(Node.s16("last_music_id", customdict.get_int("last_music_id"))) - custom.add_child( - Node.u8("last_note_grade", customdict.get_int("last_note_grade")) - ) + custom.add_child(Node.u8("last_note_grade", customdict.get_int("last_note_grade"))) custom.add_child(Node.u8("sort_type", customdict.get_int("sort_type"))) - custom.add_child( - Node.u8("narrowdown_type", customdict.get_int("narrowdown_type")) - ) - custom.add_child( - Node.bool("is_begginer", customdict.get_bool("is_begginer")) - ) # Yes, this is spelled right + custom.add_child(Node.u8("narrowdown_type", customdict.get_int("narrowdown_type"))) + custom.add_child(Node.bool("is_begginer", customdict.get_bool("is_begginer"))) # Yes, this is spelled right custom.add_child(Node.bool("is_tut", customdict.get_bool("is_tut"))) - custom.add_child( - Node.s16_array( - "symbol_chat_0", customdict.get_int_array("symbol_chat_0", 6) - ) - ) - custom.add_child( - Node.s16_array( - "symbol_chat_1", customdict.get_int_array("symbol_chat_1", 6) - ) - ) + custom.add_child(Node.s16_array("symbol_chat_0", customdict.get_int_array("symbol_chat_0", 6))) + custom.add_child(Node.s16_array("symbol_chat_1", customdict.get_int_array("symbol_chat_1", 6))) custom.add_child(Node.u8("gauge_style", customdict.get_int("gauge_style"))) custom.add_child(Node.u8("obj_shade", customdict.get_int("obj_shade"))) custom.add_child(Node.u8("obj_size", customdict.get_int("obj_size"))) - custom.add_child( - Node.s16_array("byword", customdict.get_int_array("byword", 2)) - ) - custom.add_child( - Node.bool_array( - "is_auto_byword", customdict.get_bool_array("is_auto_byword", 2) - ) - ) + custom.add_child(Node.s16_array("byword", customdict.get_int_array("byword", 2))) + custom.add_child(Node.bool_array("is_auto_byword", customdict.get_bool_array("is_auto_byword", 2))) custom.add_child(Node.bool("is_tweet", customdict.get_bool("is_tweet"))) - custom.add_child( - Node.bool("is_link_twitter", customdict.get_bool("is_link_twitter")) - ) + custom.add_child(Node.bool("is_link_twitter", customdict.get_bool("is_link_twitter"))) custom.add_child(Node.s16("mrec_type", customdict.get_int("mrec_type"))) - custom.add_child( - Node.s16("card_disp_type", customdict.get_int("card_disp_type")) - ) + custom.add_child(Node.s16("card_disp_type", customdict.get_int("card_disp_type"))) custom.add_child(Node.s16("tab_sel", customdict.get_int("tab_sel"))) - custom.add_child( - Node.s32_array("hidden_param", customdict.get_int_array("hidden_param", 20)) - ) + custom.add_child(Node.s32_array("hidden_param", customdict.get_int_array("hidden_param", 20))) released = Node.void("released") pdata.add_child(released) @@ -763,22 +714,14 @@ class ReflecBeatLimelight(ReflecBeatBase): record.add_child(rec) rec.add_child(Node.u16("mid", score.id)) rec.add_child(Node.u8("ng", score.chart)) - rec.add_child( - Node.s32("point", score.data.get_dict("stats").get_int("earned_points")) - ) + rec.add_child(Node.s32("point", score.data.get_dict("stats").get_int("earned_points"))) rec.add_child(Node.s32("played_time", score.timestamp)) mrec_0 = Node.void("mrec_0") rec.add_child(mrec_0) - mrec_0.add_child( - Node.s32("win", score.data.get_dict("stats").get_int("win")) - ) - mrec_0.add_child( - Node.s32("lose", score.data.get_dict("stats").get_int("lose")) - ) - mrec_0.add_child( - Node.s32("draw", score.data.get_dict("stats").get_int("draw")) - ) + mrec_0.add_child(Node.s32("win", score.data.get_dict("stats").get_int("win"))) + mrec_0.add_child(Node.s32("lose", score.data.get_dict("stats").get_int("lose"))) + mrec_0.add_child(Node.s32("draw", score.data.get_dict("stats").get_int("draw"))) mrec_0.add_child( Node.u8( "ct", @@ -788,9 +731,7 @@ class ReflecBeatLimelight(ReflecBeatBase): ), ) ) - mrec_0.add_child( - Node.s16("ar", int(score.data.get_int("achievement_rate") / 10)) - ) + mrec_0.add_child(Node.s16("ar", int(score.data.get_int("achievement_rate") / 10))) mrec_0.add_child(Node.s32("bs", score.points)) mrec_0.add_child(Node.s16("mc", score.data.get_int("combo"))) mrec_0.add_child(Node.s16("bmc", score.data.get_int("miss_count"))) @@ -888,9 +829,7 @@ class ReflecBeatLimelight(ReflecBeatBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() @@ -916,42 +855,24 @@ class ReflecBeatLimelight(ReflecBeatBase): customdict.replace_int("se_s", custom.child_value("se_s")) customdict.replace_int("se_s_v", custom.child_value("se_s_v")) customdict.replace_int("last_music_id", custom.child_value("last_music_id")) - customdict.replace_int( - "last_note_grade", custom.child_value("last_note_grade") - ) + customdict.replace_int("last_note_grade", custom.child_value("last_note_grade")) customdict.replace_int("sort_type", custom.child_value("sort_type")) - customdict.replace_int( - "narrowdown_type", custom.child_value("narrowdown_type") - ) - customdict.replace_bool( - "is_begginer", custom.child_value("is_begginer") - ) # Yes, this is spelled right + customdict.replace_int("narrowdown_type", custom.child_value("narrowdown_type")) + customdict.replace_bool("is_begginer", custom.child_value("is_begginer")) # Yes, this is spelled right customdict.replace_bool("is_tut", custom.child_value("is_tut")) - customdict.replace_int_array( - "symbol_chat_0", 6, custom.child_value("symbol_chat_0") - ) - customdict.replace_int_array( - "symbol_chat_1", 6, custom.child_value("symbol_chat_1") - ) + customdict.replace_int_array("symbol_chat_0", 6, custom.child_value("symbol_chat_0")) + customdict.replace_int_array("symbol_chat_1", 6, custom.child_value("symbol_chat_1")) customdict.replace_int("gauge_style", custom.child_value("gauge_style")) customdict.replace_int("obj_shade", custom.child_value("obj_shade")) customdict.replace_int("obj_size", custom.child_value("obj_size")) customdict.replace_int_array("byword", 2, custom.child_value("byword")) - customdict.replace_bool_array( - "is_auto_byword", 2, custom.child_value("is_auto_byword") - ) + customdict.replace_bool_array("is_auto_byword", 2, custom.child_value("is_auto_byword")) customdict.replace_bool("is_tweet", custom.child_value("is_tweet")) - customdict.replace_bool( - "is_link_twitter", custom.child_value("is_link_twitter") - ) + customdict.replace_bool("is_link_twitter", custom.child_value("is_link_twitter")) customdict.replace_int("mrec_type", custom.child_value("mrec_type")) - customdict.replace_int( - "card_disp_type", custom.child_value("card_disp_type") - ) + customdict.replace_int("card_disp_type", custom.child_value("card_disp_type")) customdict.replace_int("tab_sel", custom.child_value("tab_sel")) - customdict.replace_int_array( - "hidden_param", 20, custom.child_value("hidden_param") - ) + customdict.replace_int_array("hidden_param", 20, custom.child_value("hidden_param")) newprofile.replace_dict("custom", customdict) # Music unlocks and other stuff @@ -1036,10 +957,7 @@ class ReflecBeatLimelight(ReflecBeatBase): if chart in savedrecords[songid]: data = savedrecords[songid][chart] - if ( - data["achievement_rate"] == achievement_rate - and data["points"] == points - ): + if data["achievement_rate"] == achievement_rate and data["points"] == points: # This is the same record! Use the stats from it to update our # internal representation. combo = data["combo"] diff --git a/bemani/backend/reflec/reflecbeat.py b/bemani/backend/reflec/reflecbeat.py index 173101f..35e0a00 100644 --- a/bemani/backend/reflec/reflecbeat.py +++ b/bemani/backend/reflec/reflecbeat.py @@ -61,9 +61,7 @@ class ReflecBeat(ReflecBeatBase): raise Exception(f"Invalid db_combo_type {db_combo_type}") raise Exception(f"Invalid db_clear_type {db_clear_type}") - def __game_to_db_clear_type( - self, game_clear_type: int, game_achievement_rate: int - ) -> Tuple[int, int]: + def __game_to_db_clear_type(self, game_clear_type: int, game_achievement_rate: int) -> Tuple[int, int]: if game_clear_type == self.GAME_CLEAR_TYPE_NO_PLAY: return (self.CLEAR_TYPE_NO_PLAY, self.COMBO_TYPE_NONE) if game_clear_type == self.GAME_CLEAR_TYPE_PLAYED: @@ -254,9 +252,7 @@ class ReflecBeat(ReflecBeatBase): refid = request.child_value("rid") userid = self.data.remote.user.from_refid(self.game, self.version, refid) if userid is not None: - self.data.local.lobby.put_play_session_info( - self.game, self.version, userid, {} - ) + self.data.local.lobby.put_play_session_info(self.game, self.version, userid, {}) root = Node.void("player") root.add_child(Node.bool("is_suc", True)) @@ -282,9 +278,7 @@ class ReflecBeat(ReflecBeatBase): ) if lobby is not None: self.data.local.lobby.destroy_lobby(lobby.get_int("id")) - self.data.local.lobby.destroy_play_session_info( - self.game, self.version, userid - ) + self.data.local.lobby.destroy_play_session_info(self.game, self.version, userid) return Node.void("player") @@ -310,9 +304,7 @@ class ReflecBeat(ReflecBeatBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) scores = self.data.remote.music.get_scores(self.game, self.version, userid) root = Node.void("player") pdata = Node.void("pdata") @@ -368,10 +360,7 @@ class ReflecBeat(ReflecBeatBase): info.add_child(Node.u16("id", item.id)) if game_config.get_bool("force_unlock_songs"): - songs = { - song.id - for song in self.data.local.music.get_all_songs(self.game, self.version) - } + songs = {song.id for song in self.data.local.music.get_all_songs(self.game, self.version)} for songid in songs: info = Node.void("info") @@ -389,12 +378,8 @@ class ReflecBeat(ReflecBeatBase): rec.add_child(Node.u16("mid", score.id)) rec.add_child(Node.u8("ng", score.chart)) rec.add_child(Node.s32("win", score.data.get_dict("stats").get_int("win"))) - rec.add_child( - Node.s32("lose", score.data.get_dict("stats").get_int("lose")) - ) - rec.add_child( - Node.s32("draw", score.data.get_dict("stats").get_int("draw")) - ) + rec.add_child(Node.s32("lose", score.data.get_dict("stats").get_int("lose"))) + rec.add_child(Node.s32("draw", score.data.get_dict("stats").get_int("draw"))) rec.add_child( Node.u8( "ct", @@ -404,9 +389,7 @@ class ReflecBeat(ReflecBeatBase): ), ) ) - rec.add_child( - Node.s16("ar", int(score.data.get_int("achievement_rate") / 10)) - ) + rec.add_child(Node.s16("ar", int(score.data.get_int("achievement_rate") / 10))) rec.add_child(Node.s16("bs", score.points)) rec.add_child(Node.s16("mc", score.data.get_int("combo"))) rec.add_child(Node.s16("bmc", score.data.get_int("miss_count"))) @@ -421,9 +404,7 @@ class ReflecBeat(ReflecBeatBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() @@ -515,9 +496,7 @@ class ReflecBeat(ReflecBeatBase): achievement_rate = child.child_value("myself/ar") * 10 points = child.child_value("myself/s") - clear_type, combo_type = self.__game_to_db_clear_type( - clear_type, achievement_rate - ) + clear_type, combo_type = self.__game_to_db_clear_type(clear_type, achievement_rate) combo = None miss_count = -1 @@ -527,10 +506,7 @@ class ReflecBeat(ReflecBeatBase): if chart in savedrecords[songid]: data = savedrecords[songid][chart] - if ( - data["achievement_rate"] == achievement_rate - and data["points"] == points - ): + if data["achievement_rate"] == achievement_rate and data["points"] == points: # This is the same record! Use the stats from it to update our # internal representation. combo = data["combo"] diff --git a/bemani/backend/reflec/volzza.py b/bemani/backend/reflec/volzza.py index bc58d67..665f307 100644 --- a/bemani/backend/reflec/volzza.py +++ b/bemani/backend/reflec/volzza.py @@ -76,25 +76,18 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): rec.add_child(Node.s16("mid", score.id)) rec.add_child(Node.s8("ntgrd", score.chart)) rec.add_child(Node.s32("pc", score.plays)) - rec.add_child( - Node.s8( - "ct", self._db_to_game_clear_type(score.data.get_int("clear_type")) - ) - ) + rec.add_child(Node.s8("ct", self._db_to_game_clear_type(score.data.get_int("clear_type")))) rec.add_child(Node.s16("ar", score.data.get_int("achievement_rate"))) rec.add_child(Node.s16("scr", score.points)) rec.add_child(Node.s16("ms", score.data.get_int("miss_count"))) rec.add_child( Node.s16( "param", - self._db_to_game_combo_type(score.data.get_int("combo_type")) - + score.data.get_int("param"), + self._db_to_game_combo_type(score.data.get_int("combo_type")) + score.data.get_int("param"), ) ) rec.add_child(Node.s32("bscrt", score.timestamp)) - rec.add_child( - Node.s32("bart", score.data.get_int("best_achievement_rate_time")) - ) + rec.add_child(Node.s32("bart", score.data.get_int("best_achievement_rate_time"))) rec.add_child(Node.s32("bctt", score.data.get_int("best_clear_type_time"))) rec.add_child(Node.s32("bmst", score.data.get_int("best_miss_count_time"))) rec.add_child(Node.s32("time", score.data.get_int("last_played_time"))) @@ -111,9 +104,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): score = None profile = None else: - score = self.data.remote.music.get_score( - self.game, self.version, userid, songid, chart - ) + score = self.data.remote.music.get_score(self.game, self.version, userid, songid, chart) profile = self.get_any_profile(userid) root = Node.void("player") @@ -125,14 +116,10 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): player_select_score.add_child(Node.string("name", profile.get_str("name"))) player_select_score.add_child(Node.s32("m_score", score.points)) player_select_score.add_child(Node.s32("m_scoreTime", score.timestamp)) - player_select_score.add_child( - Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id")) - ) + player_select_score.add_child(Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id"))) return root - def handle_player_rb5_player_read_rival_ranking_data_request( - self, request: Node - ) -> Node: + def handle_player_rb5_player_read_rival_ranking_data_request(self, request: Node) -> Node: extid = request.child_value("uid") userid = self.data.remote.user.from_extid(self.game, self.version, extid) @@ -154,13 +141,9 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): rival_data.add_child(rl) rl.add_child(Node.s32("uid", rprofile.extid)) rl.add_child(Node.string("nm", rprofile.get_str("name"))) - rl.add_child( - Node.s16("ic", rprofile.get_dict("config").get_int("icon_id")) - ) + rl.add_child(Node.s16("ic", rprofile.get_dict("config").get_int("icon_id"))) - scores = self.data.remote.music.get_scores( - self.game, self.version, link.other_userid - ) + scores = self.data.remote.music.get_scores(self.game, self.version, link.other_userid) scores_by_musicid: Dict[int, List[Score]] = {} for score in scores: if score.id not in scores_by_musicid: @@ -168,13 +151,8 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): scores_by_musicid[score.id][score.chart] = score for mid, scores in scores_by_musicid.items(): - points = [ - score.points << 32 if score is not None else 0 - for score in scores - ] - timestamps = [ - score.timestamp if score is not None else 0 for score in scores - ] + points = [score.points << 32 if score is not None else 0 for score in scores] + timestamps = [score.timestamp if score is not None else 0 for score in scores] sl = Node.void("sl") rl.add_child(sl) @@ -206,86 +184,50 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): userid: [ score for (uid, score) in all_scores - if uid == userid - and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED + if uid == userid and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED ] for userid in all_users } # Now grab all user profiles for this game all_profiles = { - profile[0]: profile[1] - for profile in self.data.remote.user.get_all_profiles( - self.game, self.version - ) + profile[0]: profile[1] for profile in self.data.remote.user.get_all_profiles(self.game, self.version) } # Now, sum up the scores into the five categories that the game expects. total_scores = sorted( - [ - sum([score.points for score in scores]) - for userid, scores in scores_by_user.items() - ], + [sum([score.points for score in scores]) for userid, scores in scores_by_user.items()], reverse=True, ) basic_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_BASIC - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_BASIC]) for userid, scores in scores_by_user.items() ], reverse=True, ) medium_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_MEDIUM - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_MEDIUM]) for userid, scores in scores_by_user.items() ], reverse=True, ) hard_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_HARD - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_HARD]) for userid, scores in scores_by_user.items() ], ) special_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_SPECIAL - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_SPECIAL]) for userid, scores in scores_by_user.items() ], reverse=True, ) minigame_scores = sorted( - [ - all_profiles.get( - userid, Profile(self.game, self.version, "", 0) - ).get_int("mgsc") - for userid in all_users - ], + [all_profiles.get(userid, Profile(self.game, self.version, "", 0)).get_int("mgsc") for userid in all_users], reverse=True, ) @@ -351,9 +293,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) links = self.data.local.user.get_links(self.game, self.version, userid) root = Node.void("player") pdata = Node.void("pdata") @@ -436,9 +376,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): rprofile = self.get_profile(link.other_userid) if rprofile is None: continue - lobbyinfo = self.data.local.lobby.get_play_session_info( - self.game, self.version, link.other_userid - ) + lobbyinfo = self.data.local.lobby.get_play_session_info(self.game, self.version, link.other_userid) if lobbyinfo is None: lobbyinfo = ValidatedDict() @@ -447,9 +385,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): r.add_child(Node.s32("slot_id", slotid)) r.add_child(Node.s32("id", rprofile.extid)) r.add_child(Node.string("name", rprofile.get_str("name"))) - r.add_child( - Node.s32("icon", rprofile.get_dict("config").get_int("icon_id")) - ) + r.add_child(Node.s32("icon", rprofile.get_dict("config").get_int("icon_id"))) r.add_child(Node.s32("class", rprofile.get_int("class"))) r.add_child(Node.s32("class_ar", rprofile.get_int("class_ar"))) r.add_child(Node.bool("friend", True)) @@ -466,48 +402,26 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): config = Node.void("config") pdata.add_child(config) config.add_child(Node.u8("msel_bgm", configdict.get_int("msel_bgm"))) - config.add_child( - Node.u8("narrowdown_type", configdict.get_int("narrowdown_type")) - ) + config.add_child(Node.u8("narrowdown_type", configdict.get_int("narrowdown_type"))) config.add_child(Node.s16("icon_id", configdict.get_int("icon_id"))) config.add_child(Node.s16("byword_0", configdict.get_int("byword_0"))) config.add_child(Node.s16("byword_1", configdict.get_int("byword_1"))) - config.add_child( - Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0")) - ) - config.add_child( - Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1")) - ) + config.add_child(Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0"))) + config.add_child(Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1"))) config.add_child(Node.u8("mrec_type", configdict.get_int("mrec_type"))) config.add_child(Node.u8("tab_sel", configdict.get_int("tab_sel"))) config.add_child(Node.u8("card_disp", configdict.get_int("card_disp"))) - config.add_child( - Node.u8("score_tab_disp", configdict.get_int("score_tab_disp")) - ) - config.add_child( - Node.s16("last_music_id", configdict.get_int("last_music_id", -1)) - ) - config.add_child( - Node.u8("last_note_grade", configdict.get_int("last_note_grade")) - ) + config.add_child(Node.u8("score_tab_disp", configdict.get_int("score_tab_disp"))) + config.add_child(Node.s16("last_music_id", configdict.get_int("last_music_id", -1))) + config.add_child(Node.u8("last_note_grade", configdict.get_int("last_note_grade"))) config.add_child(Node.u8("sort_type", configdict.get_int("sort_type"))) - config.add_child( - Node.u8("rival_panel_type", configdict.get_int("rival_panel_type")) - ) - config.add_child( - Node.u64("random_entry_work", configdict.get_int("random_entry_work")) - ) - config.add_child( - Node.u64("custom_folder_work", configdict.get_int("custom_folder_work")) - ) + config.add_child(Node.u8("rival_panel_type", configdict.get_int("rival_panel_type"))) + config.add_child(Node.u64("random_entry_work", configdict.get_int("random_entry_work"))) + config.add_child(Node.u64("custom_folder_work", configdict.get_int("custom_folder_work"))) config.add_child(Node.u8("folder_type", configdict.get_int("folder_type"))) - config.add_child( - Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type")) - ) + config.add_child(Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type"))) config.add_child(Node.bool("is_tweet", configdict.get_bool("is_tweet"))) - config.add_child( - Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter")) - ) + config.add_child(Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter"))) # Customizations customdict = profile.get_dict("custom") @@ -526,18 +440,10 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): custom.add_child(Node.u8("st_rnd", customdict.get_int("st_rnd"))) custom.add_child(Node.u8("st_hazard", customdict.get_int("st_hazard"))) custom.add_child(Node.u8("st_clr_cond", customdict.get_int("st_clr_cond"))) - custom.add_child( - Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp")) - ) - custom.add_child( - Node.u8("st_gr_gauge_type", customdict.get_int("st_gr_gauge_type")) - ) - custom.add_child( - Node.s16("voice_message_set", customdict.get_int("voice_message_set", -1)) - ) - custom.add_child( - Node.u8("voice_message_volume", customdict.get_int("voice_message_volume")) - ) + custom.add_child(Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp"))) + custom.add_child(Node.u8("st_gr_gauge_type", customdict.get_int("st_gr_gauge_type"))) + custom.add_child(Node.s16("voice_message_set", customdict.get_int("voice_message_set", -1))) + custom.add_child(Node.u8("voice_message_volume", customdict.get_int("voice_message_volume"))) # Unlocks released = Node.void("released") @@ -591,9 +497,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): info.add_child(Node.u8("type", announcementtype)) info.add_child(Node.u16("id", announcement.id)) info.add_child(Node.u16("param", announcement.data.get_int("param"))) - info.add_child( - Node.bool("bneedannounce", announcement.data.get_bool("need")) - ) + info.add_child(Node.bool("bneedannounce", announcement.data.get_bool("need"))) # Dojo ranking return dojo = Node.void("dojo") @@ -610,12 +514,8 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): rec.add_child(Node.s32("total_ar", entry.data.get_int("ar"))) rec.add_child(Node.s32("total_score", entry.data.get_int("score"))) rec.add_child(Node.s32("play_count", entry.data.get_int("plays"))) - rec.add_child( - Node.s32("last_play_time", entry.data.get_int("play_timestamp")) - ) - rec.add_child( - Node.s32("record_update_time", entry.data.get_int("record_timestamp")) - ) + rec.add_child(Node.s32("last_play_time", entry.data.get_int("play_timestamp"))) + rec.add_child(Node.s32("record_update_time", entry.data.get_int("record_timestamp"))) rec.add_child(Node.s32("rank", 0)) # Player Parameters @@ -631,9 +531,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): player_param.add_child(itemnode) itemnode.add_child(Node.s32("type", itemtype)) itemnode.add_child(Node.s32("bank", param.id)) - itemnode.add_child( - Node.s32_array("data", param.data.get_int_array("data", 256)) - ) + itemnode.add_child(Node.s32_array("data", param.data.get_int_array("data", 256))) # Shop score for players self._add_shop_score(pdata) @@ -644,9 +542,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): listdata = Node.void("list") mylist.add_child(listdata) listdata.add_child(Node.s16("idx", 0)) - listdata.add_child( - Node.s16_array("mlst", profile.get_int_array("favorites", 30, [-1] * 30)) - ) + listdata.add_child(Node.s16_array("mlst", profile.get_int_array("favorites", 30, [-1] * 30))) # Minigame settings minigame = Node.void("minigame") @@ -661,16 +557,12 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() # Save base player profile info - newprofile.replace_int( - "lid", ID.parse_machine_id(request.child_value("pdata/account/lid")) - ) + newprofile.replace_int("lid", ID.parse_machine_id(request.child_value("pdata/account/lid"))) newprofile.replace_str("name", request.child_value("pdata/base/name")) newprofile.replace_int("mg", request.child_value("pdata/base/mg")) newprofile.replace_int("ap", request.child_value("pdata/base/ap")) @@ -680,55 +572,33 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): newprofile.replace_int("class_ar", request.child_value("pdata/base/class_ar")) newprofile.replace_int("mgid", request.child_value("pdata/minigame/mgid")) newprofile.replace_int("mgsc", request.child_value("pdata/minigame/sc")) - newprofile.replace_int_array( - "favorites", 30, request.child_value("pdata/mylist/list/mlst") - ) + newprofile.replace_int_array("favorites", 30, request.child_value("pdata/mylist/list/mlst")) # Save player config configdict = newprofile.get_dict("config") config = request.child("pdata/config") if config: configdict.replace_int("msel_bgm", config.child_value("msel_bgm")) - configdict.replace_int( - "narrowdown_type", config.child_value("narrowdown_type") - ) + configdict.replace_int("narrowdown_type", config.child_value("narrowdown_type")) configdict.replace_int("icon_id", config.child_value("icon_id")) configdict.replace_int("byword_0", config.child_value("byword_0")) configdict.replace_int("byword_1", config.child_value("byword_1")) - configdict.replace_bool( - "is_auto_byword_0", config.child_value("is_auto_byword_0") - ) - configdict.replace_bool( - "is_auto_byword_1", config.child_value("is_auto_byword_1") - ) + configdict.replace_bool("is_auto_byword_0", config.child_value("is_auto_byword_0")) + configdict.replace_bool("is_auto_byword_1", config.child_value("is_auto_byword_1")) configdict.replace_int("mrec_type", config.child_value("mrec_type")) configdict.replace_int("tab_sel", config.child_value("tab_sel")) configdict.replace_int("card_disp", config.child_value("card_disp")) - configdict.replace_int( - "score_tab_disp", config.child_value("score_tab_disp") - ) + configdict.replace_int("score_tab_disp", config.child_value("score_tab_disp")) configdict.replace_int("last_music_id", config.child_value("last_music_id")) - configdict.replace_int( - "last_note_grade", config.child_value("last_note_grade") - ) + configdict.replace_int("last_note_grade", config.child_value("last_note_grade")) configdict.replace_int("sort_type", config.child_value("sort_type")) - configdict.replace_int( - "rival_panel_type", config.child_value("rival_panel_type") - ) - configdict.replace_int( - "random_entry_work", config.child_value("random_entry_work") - ) - configdict.replace_int( - "custom_folder_work", config.child_value("custom_folder_work") - ) + configdict.replace_int("rival_panel_type", config.child_value("rival_panel_type")) + configdict.replace_int("random_entry_work", config.child_value("random_entry_work")) + configdict.replace_int("custom_folder_work", config.child_value("custom_folder_work")) configdict.replace_int("folder_type", config.child_value("folder_type")) - configdict.replace_int( - "folder_lamp_type", config.child_value("folder_lamp_type") - ) + configdict.replace_int("folder_lamp_type", config.child_value("folder_lamp_type")) configdict.replace_bool("is_tweet", config.child_value("is_tweet")) - configdict.replace_bool( - "is_link_twitter", config.child_value("is_link_twitter") - ) + configdict.replace_bool("is_link_twitter", config.child_value("is_link_twitter")) newprofile.replace_dict("config", configdict) # Save player custom settings @@ -747,18 +617,10 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): customdict.replace_int("st_rnd", custom.child_value("st_rnd")) customdict.replace_int("st_hazard", custom.child_value("st_hazard")) customdict.replace_int("st_clr_cond", custom.child_value("st_clr_cond")) - customdict.replace_int( - "same_time_note_disp", custom.child_value("same_time_note_disp") - ) - customdict.replace_int( - "st_gr_gauge_type", custom.child_value("st_gr_gauge_type") - ) - customdict.replace_int( - "voice_message_set", custom.child_value("voice_message_set") - ) - customdict.replace_int( - "voice_message_volume", custom.child_value("voice_message_volume") - ) + customdict.replace_int("same_time_note_disp", custom.child_value("same_time_note_disp")) + customdict.replace_int("st_gr_gauge_type", custom.child_value("st_gr_gauge_type")) + customdict.replace_int("voice_message_set", custom.child_value("voice_message_set")) + customdict.replace_int("voice_message_volume", custom.child_value("voice_message_volume")) newprofile.replace_dict("custom", customdict) # Save player parameter info @@ -794,9 +656,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): # I assume this is copypasta, but I want to be sure extid = child.child_value("user_id") if extid != newprofile.extid: - raise Exception( - f"Unexpected user ID, got {extid} expecting {newprofile.extid}" - ) + raise Exception(f"Unexpected user ID, got {extid} expecting {newprofile.extid}") episode_type = child.child_value("type") episode_value0 = child.child_value("value0") @@ -923,9 +783,7 @@ class ReflecBeatVolzza(ReflecBeatVolzzaBase): continue extid = child.child_value("id") - other_userid = self.data.remote.user.from_extid( - self.game, self.version, extid - ) + other_userid = self.data.remote.user.from_extid(self.game, self.version, extid) if other_userid is None: continue diff --git a/bemani/backend/reflec/volzza2.py b/bemani/backend/reflec/volzza2.py index 0977f82..c80bf4d 100644 --- a/bemani/backend/reflec/volzza2.py +++ b/bemani/backend/reflec/volzza2.py @@ -57,10 +57,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): mycourse_ctrl = Node.void("mycourse_ctrl") root.add_child(mycourse_ctrl) - songs = { - song.id - for song in self.data.local.music.get_all_songs(self.game, self.version) - } + songs = {song.id for song in self.data.local.music.get_all_songs(self.game, self.version)} for song in songs: data = Node.void("data") mycourse_ctrl.add_child(data) @@ -98,25 +95,18 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): rec.add_child(Node.s16("mid", score.id)) rec.add_child(Node.s8("ntgrd", score.chart)) rec.add_child(Node.s32("pc", score.plays)) - rec.add_child( - Node.s8( - "ct", self._db_to_game_clear_type(score.data.get_int("clear_type")) - ) - ) + rec.add_child(Node.s8("ct", self._db_to_game_clear_type(score.data.get_int("clear_type")))) rec.add_child(Node.s16("ar", score.data.get_int("achievement_rate"))) rec.add_child(Node.s16("scr", score.points)) rec.add_child(Node.s16("ms", score.data.get_int("miss_count"))) rec.add_child( Node.s16( "param", - self._db_to_game_combo_type(score.data.get_int("combo_type")) - + score.data.get_int("param"), + self._db_to_game_combo_type(score.data.get_int("combo_type")) + score.data.get_int("param"), ) ) rec.add_child(Node.s32("bscrt", score.timestamp)) - rec.add_child( - Node.s32("bart", score.data.get_int("best_achievement_rate_time")) - ) + rec.add_child(Node.s32("bart", score.data.get_int("best_achievement_rate_time"))) rec.add_child(Node.s32("bctt", score.data.get_int("best_clear_type_time"))) rec.add_child(Node.s32("bmst", score.data.get_int("best_miss_count_time"))) rec.add_child(Node.s32("time", score.data.get_int("last_played_time"))) @@ -124,9 +114,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): return root - def handle_player_rb5_player_read_rival_score_5_request( - self, request: Node - ) -> Node: + def handle_player_rb5_player_read_rival_score_5_request(self, request: Node) -> Node: extid = request.child_value("uid") songid = request.child_value("music_id") chart = request.child_value("note_grade") @@ -135,9 +123,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): score = None profile = None else: - score = self.data.remote.music.get_score( - self.game, self.version, userid, songid, chart - ) + score = self.data.remote.music.get_score(self.game, self.version, userid, songid, chart) profile = self.get_any_profile(userid) root = Node.void("player") @@ -149,14 +135,10 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): player_select_score.add_child(Node.string("name", profile.get_str("name"))) player_select_score.add_child(Node.s32("m_score", score.points)) player_select_score.add_child(Node.s32("m_scoreTime", score.timestamp)) - player_select_score.add_child( - Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id")) - ) + player_select_score.add_child(Node.s16("m_iconID", profile.get_dict("config").get_int("icon_id"))) return root - def handle_player_rb5_player_read_rival_ranking_data_5_request( - self, request: Node - ) -> Node: + def handle_player_rb5_player_read_rival_ranking_data_5_request(self, request: Node) -> Node: extid = request.child_value("uid") userid = self.data.remote.user.from_extid(self.game, self.version, extid) @@ -178,13 +160,9 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): rival_data.add_child(rl) rl.add_child(Node.s32("uid", rprofile.extid)) rl.add_child(Node.string("nm", rprofile.get_str("name"))) - rl.add_child( - Node.s16("ic", rprofile.get_dict("config").get_int("icon_id")) - ) + rl.add_child(Node.s16("ic", rprofile.get_dict("config").get_int("icon_id"))) - scores = self.data.remote.music.get_scores( - self.game, self.version, link.other_userid - ) + scores = self.data.remote.music.get_scores(self.game, self.version, link.other_userid) scores_by_musicid: Dict[int, List[Score]] = {} for score in scores: if score.id not in scores_by_musicid: @@ -192,13 +170,8 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): scores_by_musicid[score.id][score.chart] = score for mid, scores in scores_by_musicid.items(): - points = [ - score.points << 32 if score is not None else 0 - for score in scores - ] - timestamps = [ - score.timestamp if score is not None else 0 for score in scores - ] + points = [score.points << 32 if score is not None else 0 for score in scores] + timestamps = [score.timestamp if score is not None else 0 for score in scores] sl = Node.void("sl") rl.add_child(sl) @@ -230,86 +203,50 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): userid: [ score for (uid, score) in all_scores - if uid == userid - and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED + if uid == userid and score.data.get_int("clear_type") >= self.CLEAR_TYPE_CLEARED ] for userid in all_users } # Now grab all user profiles for this game all_profiles = { - profile[0]: profile[1] - for profile in self.data.remote.user.get_all_profiles( - self.game, self.version - ) + profile[0]: profile[1] for profile in self.data.remote.user.get_all_profiles(self.game, self.version) } # Now, sum up the scores into the five categories that the game expects. total_scores = sorted( - [ - sum([score.points for score in scores]) - for userid, scores in scores_by_user.items() - ], + [sum([score.points for score in scores]) for userid, scores in scores_by_user.items()], reverse=True, ) basic_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_BASIC - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_BASIC]) for userid, scores in scores_by_user.items() ], reverse=True, ) medium_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_MEDIUM - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_MEDIUM]) for userid, scores in scores_by_user.items() ], reverse=True, ) hard_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_HARD - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_HARD]) for userid, scores in scores_by_user.items() ], ) special_scores = sorted( [ - sum( - [ - score.points - for score in scores - if score.chart == self.CHART_TYPE_SPECIAL - ] - ) + sum([score.points for score in scores if score.chart == self.CHART_TYPE_SPECIAL]) for userid, scores in scores_by_user.items() ], reverse=True, ) minigame_scores = sorted( - [ - all_profiles.get( - userid, Profile(self.game, self.version, "", 0) - ).get_int("mgsc") - for userid in all_users - ], + [all_profiles.get(userid, Profile(self.game, self.version, "", 0)).get_int("mgsc") for userid in all_users], reverse=True, ) @@ -375,9 +312,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): def format_profile(self, userid: UserID, profile: Profile) -> Node: statistics = self.get_play_statistics(userid) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) links = self.data.local.user.get_links(self.game, self.version, userid) rprofiles: Dict[UserID, Profile] = {} root = Node.void("player") @@ -468,9 +403,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): rprofiles[link.other_userid] = rprofile else: rprofile = rprofiles[link.other_userid] - lobbyinfo = self.data.local.lobby.get_play_session_info( - self.game, self.version, link.other_userid - ) + lobbyinfo = self.data.local.lobby.get_play_session_info(self.game, self.version, link.other_userid) if lobbyinfo is None: lobbyinfo = ValidatedDict() @@ -479,9 +412,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): r.add_child(Node.s32("slot_id", slotid)) r.add_child(Node.s32("id", rprofile.extid)) r.add_child(Node.string("name", rprofile.get_str("name"))) - r.add_child( - Node.s32("icon", rprofile.get_dict("config").get_int("icon_id")) - ) + r.add_child(Node.s32("icon", rprofile.get_dict("config").get_int("icon_id"))) r.add_child(Node.s32("class", rprofile.get_int("class"))) r.add_child(Node.s32("class_ar", rprofile.get_int("class_ar"))) r.add_child(Node.bool("friend", True)) @@ -498,48 +429,26 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): config = Node.void("config") pdata.add_child(config) config.add_child(Node.u8("msel_bgm", configdict.get_int("msel_bgm"))) - config.add_child( - Node.u8("narrowdown_type", configdict.get_int("narrowdown_type")) - ) + config.add_child(Node.u8("narrowdown_type", configdict.get_int("narrowdown_type"))) config.add_child(Node.s16("icon_id", configdict.get_int("icon_id"))) config.add_child(Node.s16("byword_0", configdict.get_int("byword_0"))) config.add_child(Node.s16("byword_1", configdict.get_int("byword_1"))) - config.add_child( - Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0")) - ) - config.add_child( - Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1")) - ) + config.add_child(Node.bool("is_auto_byword_0", configdict.get_bool("is_auto_byword_0"))) + config.add_child(Node.bool("is_auto_byword_1", configdict.get_bool("is_auto_byword_1"))) config.add_child(Node.u8("mrec_type", configdict.get_int("mrec_type"))) config.add_child(Node.u8("tab_sel", configdict.get_int("tab_sel"))) config.add_child(Node.u8("card_disp", configdict.get_int("card_disp"))) - config.add_child( - Node.u8("score_tab_disp", configdict.get_int("score_tab_disp")) - ) - config.add_child( - Node.s16("last_music_id", configdict.get_int("last_music_id", -1)) - ) - config.add_child( - Node.u8("last_note_grade", configdict.get_int("last_note_grade")) - ) + config.add_child(Node.u8("score_tab_disp", configdict.get_int("score_tab_disp"))) + config.add_child(Node.s16("last_music_id", configdict.get_int("last_music_id", -1))) + config.add_child(Node.u8("last_note_grade", configdict.get_int("last_note_grade"))) config.add_child(Node.u8("sort_type", configdict.get_int("sort_type"))) - config.add_child( - Node.u8("rival_panel_type", configdict.get_int("rival_panel_type")) - ) - config.add_child( - Node.u64("random_entry_work", configdict.get_int("random_entry_work")) - ) - config.add_child( - Node.u64("custom_folder_work", configdict.get_int("custom_folder_work")) - ) + config.add_child(Node.u8("rival_panel_type", configdict.get_int("rival_panel_type"))) + config.add_child(Node.u64("random_entry_work", configdict.get_int("random_entry_work"))) + config.add_child(Node.u64("custom_folder_work", configdict.get_int("custom_folder_work"))) config.add_child(Node.u8("folder_type", configdict.get_int("folder_type"))) - config.add_child( - Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type")) - ) + config.add_child(Node.u8("folder_lamp_type", configdict.get_int("folder_lamp_type"))) config.add_child(Node.bool("is_tweet", configdict.get_bool("is_tweet"))) - config.add_child( - Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter")) - ) + config.add_child(Node.bool("is_link_twitter", configdict.get_bool("is_link_twitter"))) # Customizations customdict = profile.get_dict("custom") @@ -555,31 +464,17 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): custom.add_child(Node.u8("st_jr_gauge", customdict.get_int("st_jr_gauge"))) custom.add_child(Node.u8("st_clr_gauge", customdict.get_int("st_clr_gauge"))) custom.add_child(Node.u8("st_rnd", customdict.get_int("st_rnd"))) - custom.add_child( - Node.u8("st_gr_gauge_type", customdict.get_int("st_gr_gauge_type")) - ) - custom.add_child( - Node.s16("voice_message_set", customdict.get_int("voice_message_set", -1)) - ) - custom.add_child( - Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp")) - ) - custom.add_child( - Node.u8("st_score_disp_type", customdict.get_int("st_score_disp_type")) - ) + custom.add_child(Node.u8("st_gr_gauge_type", customdict.get_int("st_gr_gauge_type"))) + custom.add_child(Node.s16("voice_message_set", customdict.get_int("voice_message_set", -1))) + custom.add_child(Node.u8("same_time_note_disp", customdict.get_int("same_time_note_disp"))) + custom.add_child(Node.u8("st_score_disp_type", customdict.get_int("st_score_disp_type"))) custom.add_child(Node.u8("st_bonus_type", customdict.get_int("st_bonus_type"))) - custom.add_child( - Node.u8("st_rivalnote_type", customdict.get_int("st_rivalnote_type")) - ) - custom.add_child( - Node.u8("st_topassist_type", customdict.get_int("st_topassist_type")) - ) + custom.add_child(Node.u8("st_rivalnote_type", customdict.get_int("st_rivalnote_type"))) + custom.add_child(Node.u8("st_topassist_type", customdict.get_int("st_topassist_type"))) custom.add_child(Node.u8("high_speed", customdict.get_int("high_speed"))) custom.add_child(Node.u8("st_hazard", customdict.get_int("st_hazard"))) custom.add_child(Node.u8("st_clr_cond", customdict.get_int("st_clr_cond"))) - custom.add_child( - Node.u8("voice_message_volume", customdict.get_int("voice_message_volume")) - ) + custom.add_child(Node.u8("voice_message_volume", customdict.get_int("voice_message_volume"))) # Unlocks released = Node.void("released") @@ -635,9 +530,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): info.add_child(Node.u8("type", announcementtype)) info.add_child(Node.u16("id", announcement.id)) info.add_child(Node.u16("param", announcement.data.get_int("param"))) - info.add_child( - Node.bool("bneedannounce", announcement.data.get_bool("need")) - ) + info.add_child(Node.bool("bneedannounce", announcement.data.get_bool("need"))) # Dojo ranking return dojo = Node.void("dojo") @@ -654,12 +547,8 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): rec.add_child(Node.s32("total_ar", entry.data.get_int("ar"))) rec.add_child(Node.s32("total_score", entry.data.get_int("score"))) rec.add_child(Node.s32("play_count", entry.data.get_int("plays"))) - rec.add_child( - Node.s32("last_play_time", entry.data.get_int("play_timestamp")) - ) - rec.add_child( - Node.s32("record_update_time", entry.data.get_int("record_timestamp")) - ) + rec.add_child(Node.s32("last_play_time", entry.data.get_int("play_timestamp"))) + rec.add_child(Node.s32("record_update_time", entry.data.get_int("record_timestamp"))) rec.add_child(Node.s32("rank", 0)) # Player Parameters @@ -675,9 +564,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): player_param.add_child(itemnode) itemnode.add_child(Node.s32("type", itemtype)) itemnode.add_child(Node.s32("bank", param.id)) - itemnode.add_child( - Node.s32_array("data", param.data.get_int_array("data", 256)) - ) + itemnode.add_child(Node.s32_array("data", param.data.get_int_array("data", 256))) # Shop score for players self._add_shop_score(pdata) @@ -688,9 +575,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): listdata = Node.void("list") mylist.add_child(listdata) listdata.add_child(Node.s16("idx", 0)) - listdata.add_child( - Node.s16_array("mlst", profile.get_int_array("favorites", 30, [-1] * 30)) - ) + listdata.add_child(Node.s16_array("mlst", profile.get_int_array("favorites", 30, [-1] * 30))) # Minigame settings minigame = Node.void("minigame") @@ -724,37 +609,19 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): mycoursedict = profile.get_dict("mycourse") pdata.add_child(mycourse) mycourse.add_child(Node.s16("mycourse_id", 1)) - mycourse.add_child( - Node.s32("music_id_1", mycoursedict.get_int("music_id_1", -1)) - ) - mycourse.add_child( - Node.s16("note_grade_1", mycoursedict.get_int("note_grade_1", -1)) - ) + mycourse.add_child(Node.s32("music_id_1", mycoursedict.get_int("music_id_1", -1))) + mycourse.add_child(Node.s16("note_grade_1", mycoursedict.get_int("note_grade_1", -1))) mycourse.add_child(Node.s32("score_1", mycoursedict.get_int("score_1", -1))) - mycourse.add_child( - Node.s32("music_id_2", mycoursedict.get_int("music_id_2", -1)) - ) - mycourse.add_child( - Node.s16("note_grade_2", mycoursedict.get_int("note_grade_2", -1)) - ) + mycourse.add_child(Node.s32("music_id_2", mycoursedict.get_int("music_id_2", -1))) + mycourse.add_child(Node.s16("note_grade_2", mycoursedict.get_int("note_grade_2", -1))) mycourse.add_child(Node.s32("score_2", mycoursedict.get_int("score_2", -1))) - mycourse.add_child( - Node.s32("music_id_3", mycoursedict.get_int("music_id_3", -1)) - ) - mycourse.add_child( - Node.s16("note_grade_3", mycoursedict.get_int("note_grade_3", -1)) - ) + mycourse.add_child(Node.s32("music_id_3", mycoursedict.get_int("music_id_3", -1))) + mycourse.add_child(Node.s16("note_grade_3", mycoursedict.get_int("note_grade_3", -1))) mycourse.add_child(Node.s32("score_3", mycoursedict.get_int("score_3", -1))) - mycourse.add_child( - Node.s32("music_id_4", mycoursedict.get_int("music_id_4", -1)) - ) - mycourse.add_child( - Node.s16("note_grade_4", mycoursedict.get_int("note_grade_4", -1)) - ) + mycourse.add_child(Node.s32("music_id_4", mycoursedict.get_int("music_id_4", -1))) + mycourse.add_child(Node.s16("note_grade_4", mycoursedict.get_int("note_grade_4", -1))) mycourse.add_child(Node.s32("score_4", mycoursedict.get_int("score_4", -1))) - mycourse.add_child( - Node.s32("insert_time", mycoursedict.get_int("insert_time", -1)) - ) + mycourse.add_child(Node.s32("insert_time", mycoursedict.get_int("insert_time", -1))) mycourse.add_child(Node.s32("def_music_id_1", -1)) mycourse.add_child(Node.s16("def_note_grade_1", -1)) mycourse.add_child(Node.s32("def_music_id_2", -1)) @@ -785,50 +652,28 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): mycourse_f.add_child(rec) rec.add_child(Node.s32("rival_id", rprofile.extid)) rec.add_child(Node.s16("mycourse_id", 1)) - rec.add_child( - Node.s32("music_id_1", mycoursedict.get_int("music_id_1", -1)) - ) - rec.add_child( - Node.s16("note_grade_1", mycoursedict.get_int("note_grade_1", -1)) - ) + rec.add_child(Node.s32("music_id_1", mycoursedict.get_int("music_id_1", -1))) + rec.add_child(Node.s16("note_grade_1", mycoursedict.get_int("note_grade_1", -1))) rec.add_child(Node.s32("score_1", mycoursedict.get_int("score_1", -1))) - rec.add_child( - Node.s32("music_id_2", mycoursedict.get_int("music_id_2", -1)) - ) - rec.add_child( - Node.s16("note_grade_2", mycoursedict.get_int("note_grade_2", -1)) - ) + rec.add_child(Node.s32("music_id_2", mycoursedict.get_int("music_id_2", -1))) + rec.add_child(Node.s16("note_grade_2", mycoursedict.get_int("note_grade_2", -1))) rec.add_child(Node.s32("score_2", mycoursedict.get_int("score_2", -1))) - rec.add_child( - Node.s32("music_id_3", mycoursedict.get_int("music_id_3", -1)) - ) - rec.add_child( - Node.s16("note_grade_3", mycoursedict.get_int("note_grade_3", -1)) - ) + rec.add_child(Node.s32("music_id_3", mycoursedict.get_int("music_id_3", -1))) + rec.add_child(Node.s16("note_grade_3", mycoursedict.get_int("note_grade_3", -1))) rec.add_child(Node.s32("score_3", mycoursedict.get_int("score_3", -1))) - rec.add_child( - Node.s32("music_id_4", mycoursedict.get_int("music_id_4", -1)) - ) - rec.add_child( - Node.s16("note_grade_4", mycoursedict.get_int("note_grade_4", -1)) - ) + rec.add_child(Node.s32("music_id_4", mycoursedict.get_int("music_id_4", -1))) + rec.add_child(Node.s16("note_grade_4", mycoursedict.get_int("note_grade_4", -1))) rec.add_child(Node.s32("score_4", mycoursedict.get_int("score_4", -1))) - rec.add_child( - Node.s32("insert_time", mycoursedict.get_int("insert_time", -1)) - ) + rec.add_child(Node.s32("insert_time", mycoursedict.get_int("insert_time", -1))) return root - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: game_config = self.get_game_config() newprofile = oldprofile.clone() # Save base player profile info - newprofile.replace_int( - "lid", ID.parse_machine_id(request.child_value("pdata/account/lid")) - ) + newprofile.replace_int("lid", ID.parse_machine_id(request.child_value("pdata/account/lid"))) newprofile.replace_str("name", request.child_value("pdata/base/name")) newprofile.replace_int("mg", request.child_value("pdata/base/mg")) newprofile.replace_int("ap", request.child_value("pdata/base/ap")) @@ -836,60 +681,36 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): newprofile.replace_int("money", request.child_value("pdata/base/money")) newprofile.replace_int("class", request.child_value("pdata/base/class")) newprofile.replace_int("class_ar", request.child_value("pdata/base/class_ar")) - newprofile.replace_int( - "skill_point", request.child_value("pdata/base/skill_point") - ) + newprofile.replace_int("skill_point", request.child_value("pdata/base/skill_point")) newprofile.replace_int("mgid", request.child_value("pdata/minigame/mgid")) newprofile.replace_int("mgsc", request.child_value("pdata/minigame/sc")) - newprofile.replace_int_array( - "favorites", 30, request.child_value("pdata/mylist/list/mlst") - ) + newprofile.replace_int_array("favorites", 30, request.child_value("pdata/mylist/list/mlst")) # Save player config configdict = newprofile.get_dict("config") config = request.child("pdata/config") if config: configdict.replace_int("msel_bgm", config.child_value("msel_bgm")) - configdict.replace_int( - "narrowdown_type", config.child_value("narrowdown_type") - ) + configdict.replace_int("narrowdown_type", config.child_value("narrowdown_type")) configdict.replace_int("icon_id", config.child_value("icon_id")) configdict.replace_int("byword_0", config.child_value("byword_0")) configdict.replace_int("byword_1", config.child_value("byword_1")) - configdict.replace_bool( - "is_auto_byword_0", config.child_value("is_auto_byword_0") - ) - configdict.replace_bool( - "is_auto_byword_1", config.child_value("is_auto_byword_1") - ) + configdict.replace_bool("is_auto_byword_0", config.child_value("is_auto_byword_0")) + configdict.replace_bool("is_auto_byword_1", config.child_value("is_auto_byword_1")) configdict.replace_int("mrec_type", config.child_value("mrec_type")) configdict.replace_int("tab_sel", config.child_value("tab_sel")) configdict.replace_int("card_disp", config.child_value("card_disp")) - configdict.replace_int( - "score_tab_disp", config.child_value("score_tab_disp") - ) + configdict.replace_int("score_tab_disp", config.child_value("score_tab_disp")) configdict.replace_int("last_music_id", config.child_value("last_music_id")) - configdict.replace_int( - "last_note_grade", config.child_value("last_note_grade") - ) + configdict.replace_int("last_note_grade", config.child_value("last_note_grade")) configdict.replace_int("sort_type", config.child_value("sort_type")) - configdict.replace_int( - "rival_panel_type", config.child_value("rival_panel_type") - ) - configdict.replace_int( - "random_entry_work", config.child_value("random_entry_work") - ) - configdict.replace_int( - "custom_folder_work", config.child_value("custom_folder_work") - ) + configdict.replace_int("rival_panel_type", config.child_value("rival_panel_type")) + configdict.replace_int("random_entry_work", config.child_value("random_entry_work")) + configdict.replace_int("custom_folder_work", config.child_value("custom_folder_work")) configdict.replace_int("folder_type", config.child_value("folder_type")) - configdict.replace_int( - "folder_lamp_type", config.child_value("folder_lamp_type") - ) + configdict.replace_int("folder_lamp_type", config.child_value("folder_lamp_type")) configdict.replace_bool("is_tweet", config.child_value("is_tweet")) - configdict.replace_bool( - "is_link_twitter", config.child_value("is_link_twitter") - ) + configdict.replace_bool("is_link_twitter", config.child_value("is_link_twitter")) newprofile.replace_dict("config", configdict) # Save player custom settings @@ -905,31 +726,17 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): customdict.replace_int("st_obj_size", custom.child_value("st_obj_size")) customdict.replace_int("st_jr_gauge", custom.child_value("st_jr_gauge")) customdict.replace_int("st_clr_gauge", custom.child_value("st_clr_gauge")) - customdict.replace_int( - "st_gr_gauge_type", custom.child_value("st_gr_gauge_type") - ) - customdict.replace_int( - "voice_message_set", custom.child_value("voice_message_set") - ) - customdict.replace_int( - "same_time_note_disp", custom.child_value("same_time_note_disp") - ) - customdict.replace_int( - "st_score_disp_type", custom.child_value("st_score_disp_type") - ) + customdict.replace_int("st_gr_gauge_type", custom.child_value("st_gr_gauge_type")) + customdict.replace_int("voice_message_set", custom.child_value("voice_message_set")) + customdict.replace_int("same_time_note_disp", custom.child_value("same_time_note_disp")) + customdict.replace_int("st_score_disp_type", custom.child_value("st_score_disp_type")) customdict.replace_int("st_bonus_type", custom.child_value("st_bonus_type")) - customdict.replace_int( - "st_rivalnote_type", custom.child_value("st_rivalnote_type") - ) - customdict.replace_int( - "st_topassist_type", custom.child_value("st_topassist_type") - ) + customdict.replace_int("st_rivalnote_type", custom.child_value("st_rivalnote_type")) + customdict.replace_int("st_topassist_type", custom.child_value("st_topassist_type")) customdict.replace_int("high_speed", custom.child_value("high_speed")) customdict.replace_int("st_hazard", custom.child_value("st_hazard")) customdict.replace_int("st_clr_cond", custom.child_value("st_clr_cond")) - customdict.replace_int( - "voice_message_volume", custom.child_value("voice_message_volume") - ) + customdict.replace_int("voice_message_volume", custom.child_value("voice_message_volume")) newprofile.replace_dict("custom", customdict) # Save player parameter info @@ -965,9 +772,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): # I assume this is copypasta, but I want to be sure extid = child.child_value("user_id") if extid != newprofile.extid: - raise Exception( - f"Unexpected user ID, got {extid} expecting {newprofile.extid}" - ) + raise Exception(f"Unexpected user ID, got {extid} expecting {newprofile.extid}") episode_type = child.child_value("type") episode_value0 = child.child_value("value0") @@ -1085,9 +890,7 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): continue extid = child.child_value("id") - other_userid = self.data.remote.user.from_extid( - self.game, self.version, extid - ) + other_userid = self.data.remote.user.from_extid(self.game, self.version, extid) if other_userid is None: continue @@ -1189,33 +992,17 @@ class ReflecBeatVolzza2(ReflecBeatVolzzaBase): ) if total >= oldtotal: - mycoursedict.replace_int( - "music_id_1", mycourse.child_value("music_id_1") - ) - mycoursedict.replace_int( - "note_grade_1", mycourse.child_value("note_grade_1") - ) + mycoursedict.replace_int("music_id_1", mycourse.child_value("music_id_1")) + mycoursedict.replace_int("note_grade_1", mycourse.child_value("note_grade_1")) mycoursedict.replace_int("score_1", score_1) - mycoursedict.replace_int( - "music_id_2", mycourse.child_value("music_id_2") - ) - mycoursedict.replace_int( - "note_grade_2", mycourse.child_value("note_grade_2") - ) + mycoursedict.replace_int("music_id_2", mycourse.child_value("music_id_2")) + mycoursedict.replace_int("note_grade_2", mycourse.child_value("note_grade_2")) mycoursedict.replace_int("score_2", score_2) - mycoursedict.replace_int( - "music_id_3", mycourse.child_value("music_id_3") - ) - mycoursedict.replace_int( - "note_grade_3", mycourse.child_value("note_grade_3") - ) + mycoursedict.replace_int("music_id_3", mycourse.child_value("music_id_3")) + mycoursedict.replace_int("note_grade_3", mycourse.child_value("note_grade_3")) mycoursedict.replace_int("score_3", score_3) - mycoursedict.replace_int( - "music_id_4", mycourse.child_value("music_id_4") - ) - mycoursedict.replace_int( - "note_grade_4", mycourse.child_value("note_grade_4") - ) + mycoursedict.replace_int("music_id_4", mycourse.child_value("music_id_4")) + mycoursedict.replace_int("note_grade_4", mycourse.child_value("note_grade_4")) mycoursedict.replace_int("score_4", score_4) mycoursedict.replace_int("insert_time", Time.now()) newprofile.replace_dict("mycourse", mycoursedict) diff --git a/bemani/backend/reflec/volzzabase.py b/bemani/backend/reflec/volzzabase.py index b296751..c616394 100644 --- a/bemani/backend/reflec/volzzabase.py +++ b/bemani/backend/reflec/volzzabase.py @@ -87,16 +87,11 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): ) machine = self.data.local.machine.get_machine(self.config.machine.pcbid) if machine.arcade is not None: - lids = [ - machine.id - for machine in self.data.local.machine.get_all_machines(machine.arcade) - ] + lids = [machine.id for machine in self.data.local.machine.get_all_machines(machine.arcade)] else: lids = [machine.id] - relevant_profiles = [ - profile for profile in all_profiles if profile[1].get_int("lid", -1) in lids - ] + relevant_profiles = [profile for profile in all_profiles if profile[1].get_int("lid", -1) in lids] for rootnode, timeoffset in [ (today, 0), @@ -124,10 +119,7 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): scores_by_user[userid][attempt.id][attempt.chart] = attempt else: # If this attempt is better than the stored one, replace it - if ( - scores_by_user[userid][attempt.id][attempt.chart].points - < attempt.points - ): + if scores_by_user[userid][attempt.id][attempt.chart].points < attempt.points: scores_by_user[userid][attempt.id][attempt.chart] = attempt # Calculate points earned by user in the day @@ -136,27 +128,16 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): points_by_user[userid] = 0 for mid in scores_by_user[userid]: for chart in scores_by_user[userid][mid]: - points_by_user[userid] = ( - points_by_user[userid] - + scores_by_user[userid][mid][chart].points - ) + points_by_user[userid] = points_by_user[userid] + scores_by_user[userid][mid][chart].points # Output that day's earned points for userid, profile in relevant_profiles: data = Node.void("data") rootnode.add_child(data) - data.add_child( - Node.s16( - "day_id", int((Time.now() - timeoffset) / Time.SECONDS_IN_DAY) - ) - ) + data.add_child(Node.s16("day_id", int((Time.now() - timeoffset) / Time.SECONDS_IN_DAY))) data.add_child(Node.s32("user_id", profile.extid)) - data.add_child( - Node.s16("icon_id", profile.get_dict("config").get_int("icon_id")) - ) - data.add_child( - Node.s16("point", min(points_by_user.get(userid, 0), 32767)) - ) + data.add_child(Node.s16("icon_id", profile.get_dict("config").get_int("icon_id"))) + data.add_child(Node.s16("point", min(points_by_user.get(userid, 0), 32767))) data.add_child(Node.s32("update_time", Time.now())) data.add_child(Node.string("name", profile.get_str("name"))) @@ -176,9 +157,7 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): ranking = Node.void("ranking") root.add_child(ranking) - def add_hitchart( - name: str, start: int, end: int, hitchart: List[Tuple[int, int]] - ) -> None: + def add_hitchart(name: str, start: int, end: int, hitchart: List[Tuple[int, int]]) -> None: base = Node.void(name) ranking.add_child(base) base.add_child(Node.s32("bt", start)) @@ -261,17 +240,11 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): data.add_child( Node.s8( "clear_type", - self._db_to_game_clear_type( - score.data.get_int("clear_type") - ), + self._db_to_game_clear_type(score.data.get_int("clear_type")), ) ) data.add_child(Node.s32("user_id", profile.extid)) - data.add_child( - Node.s16( - "icon_id", profile.get_dict("config").get_int("icon_id") - ) - ) + data.add_child(Node.s16("icon_id", profile.get_dict("config").get_int("icon_id"))) data.add_child(Node.s32("score", score.points)) data.add_child(Node.s32("time", score.timestamp)) data.add_child(Node.string("name", profile.get_str("name"))) @@ -288,9 +261,7 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): userid = self.data.remote.user.from_extid(self.game, self.version, extid) if userid is not None: profile = self.get_profile(userid) - info = self.data.local.lobby.get_play_session_info( - self.game, self.version, userid - ) + info = self.data.local.lobby.get_play_session_info(self.game, self.version, userid) if profile is None or info is None: return root @@ -369,9 +340,7 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): continue profile = self.get_profile(user) - info = self.data.local.lobby.get_play_session_info( - self.game, self.version, userid - ) + info = self.data.local.lobby.get_play_session_info(self.game, self.version, userid) if profile is None or info is None: # No profile info, don't return this lobby return root @@ -502,9 +471,7 @@ class ReflecBeatVolzzaBase(ReflecBeatBase): ) if lobby is not None: self.data.local.lobby.destroy_lobby(lobby.get_int("id")) - self.data.local.lobby.destroy_play_session_info( - self.game, self.version, userid - ) + self.data.local.lobby.destroy_play_session_info(self.game, self.version, userid) return Node.void("player") diff --git a/bemani/backend/sdvx/base.py b/bemani/backend/sdvx/base.py index 0eebed3..2d5ecef 100644 --- a/bemani/backend/sdvx/base.py +++ b/bemani/backend/sdvx/base.py @@ -21,9 +21,7 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): CLEAR_TYPE_CLEAR: Final[int] = DBConstants.SDVX_CLEAR_TYPE_CLEAR CLEAR_TYPE_HARD_CLEAR: Final[int] = DBConstants.SDVX_CLEAR_TYPE_HARD_CLEAR CLEAR_TYPE_ULTIMATE_CHAIN: Final[int] = DBConstants.SDVX_CLEAR_TYPE_ULTIMATE_CHAIN - CLEAR_TYPE_PERFECT_ULTIMATE_CHAIN: Final[ - int - ] = DBConstants.SDVX_CLEAR_TYPE_PERFECT_ULTIMATE_CHAIN + CLEAR_TYPE_PERFECT_ULTIMATE_CHAIN: Final[int] = DBConstants.SDVX_CLEAR_TYPE_PERFECT_ULTIMATE_CHAIN GRADE_NO_PLAY: Final[int] = DBConstants.SDVX_GRADE_NO_PLAY GRADE_D: Final[int] = DBConstants.SDVX_GRADE_D @@ -68,9 +66,7 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # Now, return it return self.format_profile(userid, profile) - def new_profile_by_refid( - self, refid: Optional[str], name: Optional[str], locid: Optional[int] - ) -> Node: + def new_profile_by_refid(self, refid: Optional[str], name: Optional[str], locid: Optional[int]) -> Node: """ Given a RefID and an optional name, create a profile and then return a formatted profile node. Similar rationale to get_profile_by_refid. @@ -103,9 +99,7 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): """ return Node.void("game") - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: """ Base handler for profile parsing. Given a request and an old profile, return a new profile that's been updated with the contents of the request. @@ -154,10 +148,7 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): # We saw an attempt, keep the total attempts in sync. attempts[attempt.id][attempt.chart]["average"] = int( ( - ( - attempts[attempt.id][attempt.chart]["average"] - * attempts[attempt.id][attempt.chart]["total"] - ) + (attempts[attempt.id][attempt.chart]["average"] * attempts[attempt.id][attempt.chart]["total"]) + attempt.points ) / (attempts[attempt.id][attempt.chart]["total"] + 1) @@ -187,12 +178,8 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): "average": 0, } - attempts[songid][songchart]["total"] += remote_attempts[songid][ - songchart - ]["plays"] - attempts[songid][songchart]["clears"] += remote_attempts[songid][ - songchart - ]["clears"] + attempts[songid][songchart]["total"] += remote_attempts[songid][songchart]["plays"] + attempts[songid][songchart]["clears"] += remote_attempts[songid][songchart]["clears"] return attempts @@ -267,9 +254,7 @@ class SoundVoltexBase(CoreHandler, CardManagerHandler, PASELIHandler, Base): scoredata = oldscore.data # Replace clear type and grade - scoredata.replace_int( - "clear_type", max(scoredata.get_int("clear_type"), clear_type) - ) + scoredata.replace_int("clear_type", max(scoredata.get_int("clear_type"), clear_type)) history.replace_int("clear_type", clear_type) scoredata.replace_int("grade", max(scoredata.get_int("grade"), grade)) history.replace_int("grade", grade) diff --git a/bemani/backend/sdvx/booth.py b/bemani/backend/sdvx/booth.py index 34c561c..aecf55c 100644 --- a/bemani/backend/sdvx/booth.py +++ b/bemani/backend/sdvx/booth.py @@ -227,10 +227,7 @@ class SoundVoltexBooth( records_by_id[score.id][score.chart] = record missing_users.append(userid) - users = { - userid: profile - for (userid, profile) in self.get_any_profiles(missing_users) - } + users = {userid: profile for (userid, profile) in self.get_any_profiles(missing_users)} # Output records for songid in records_by_id: @@ -492,22 +489,16 @@ class SoundVoltexBooth( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update experience and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) gain_exp = request.child_value("gain_exp") if gain_exp is not None: newprofile.replace_int("exp", newprofile.get_int("exp") + gain_exp) @@ -520,15 +511,11 @@ class SoundVoltexBooth( if not game_config.get_bool("force_unlock_cards"): have_item = request.child_value("have_item") if have_item is not None: - newprofile.replace_int_array( - "have_item", 512, [1 if x else 0 for x in have_item] - ) + newprofile.replace_int_array("have_item", 512, [1 if x else 0 for x in have_item]) if not game_config.get_bool("force_unlock_songs"): have_note = request.child_value("have_note") if have_note is not None: - newprofile.replace_int_array( - "have_note", 512, [1 if x else 0 for x in have_note] - ) + newprofile.replace_int_array("have_note", 512, [1 if x else 0 for x in have_note]) # Grab last information. lastdict = newprofile.get_dict("last") diff --git a/bemani/backend/sdvx/gravitywars.py b/bemani/backend/sdvx/gravitywars.py index d80f1d2..a8ea150 100644 --- a/bemani/backend/sdvx/gravitywars.py +++ b/bemani/backend/sdvx/gravitywars.py @@ -204,9 +204,7 @@ class SoundVoltexGravityWars( courses = self._get_skill_analyzer_courses() max_level: Dict[int, int] = {} for course in courses: - max_level[course["level"]] = max( - course["season_id"], max_level.get(course["level"], -1) - ) + max_level[course["level"]] = max(course["season_id"], max_level.get(course["level"], -1)) for course in courses: info = Node.void("info") skill_course.add_child(info) @@ -214,11 +212,7 @@ class SoundVoltexGravityWars( info.add_child(Node.s16("level", course["level"])) info.add_child(Node.s32("season_id", course["season_id"])) info.add_child(Node.string("season_name", seasons[course["season_id"]])) - info.add_child( - Node.bool( - "season_new_flg", max_level[course["level"]] == course["season_id"] - ) - ) + info.add_child(Node.bool("season_new_flg", max_level[course["level"]] == course["season_id"])) info.add_child( Node.string( "course_name", @@ -226,14 +220,8 @@ class SoundVoltexGravityWars( ) ) info.add_child(Node.s16("course_type", 0)) - info.add_child( - Node.s16("skill_name_id", course.get("skill_name_id", course["level"])) - ) - info.add_child( - Node.bool( - "matching_assist", course["level"] >= 0 and course["level"] <= 6 - ) - ) + info.add_child(Node.s16("skill_name_id", course.get("skill_name_id", course["level"]))) + info.add_child(Node.bool("matching_assist", course["level"] >= 0 and course["level"] <= 6)) info.add_child(Node.s16("gauge_type", self.GAME_GAUGE_TYPE_SKILL)) info.add_child(Node.s16("paseli_type", 0)) @@ -464,11 +452,7 @@ class SoundVoltexGravityWars( self.__db_to_game_clear_type(score.data.get_int("clear_type")), ) ) - music.add_child( - Node.u32( - "score_grade", self.__db_to_game_grade(score.data.get_int("grade")) - ) - ) + music.add_child(Node.u32("score_grade", self.__db_to_game_grade(score.data.get_int("grade")))) stats = score.data.get_dict("stats") music.add_child(Node.u32("btn_rate", stats.get_int("btn_rate"))) music.add_child(Node.u32("long_rate", stats.get_int("long_rate"))) diff --git a/bemani/backend/sdvx/gravitywars_s1.py b/bemani/backend/sdvx/gravitywars_s1.py index 47f0e84..2d09126 100644 --- a/bemani/backend/sdvx/gravitywars_s1.py +++ b/bemani/backend/sdvx/gravitywars_s1.py @@ -3063,10 +3063,7 @@ class SoundVoltexGravityWarsSeason1( # Now, grab user records records = self.data.remote.music.get_all_records(self.game, self.version) missing_users = [userid for (userid, _) in records] - users = { - userid: profile - for (userid, profile) in self.get_any_profiles(missing_users) - } + users = {userid: profile for (userid, profile) in self.get_any_profiles(missing_users)} hiscore_allover = Node.void("hiscore_allover") game.add_child(hiscore_allover) @@ -3091,14 +3088,10 @@ class SoundVoltexGravityWarsSeason1( # Now, grab local records area_users = [ uid - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) + for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version) if prof.get_int("loc", -1) == locid ] - records = self.data.local.music.get_all_records( - self.game, self.version, userlist=area_users - ) + records = self.data.local.music.get_all_records(self.game, self.version, userlist=area_users) missing_users = [userid for (userid, _) in records if userid not in users] for userid, profile in self.get_any_profiles(missing_users): users[userid] = profile @@ -3131,9 +3124,7 @@ class SoundVoltexGravityWarsSeason1( for songid in clears: for chart in clears[songid]: if clears[songid][chart]["total"] > 0: - rate = float(clears[songid][chart]["clears"]) / float( - clears[songid][chart]["total"] - ) + rate = float(clears[songid][chart]["clears"]) / float(clears[songid][chart]["total"]) dnode = Node.void("d") clear_rate.add_child(dnode) dnode.add_child(Node.u32("id", songid)) @@ -3151,9 +3142,7 @@ class SoundVoltexGravityWarsSeason1( game.add_child(Node.u32("gamecoin_packet", profile.get_int("packet"))) game.add_child(Node.u32("gamecoin_block", profile.get_int("block"))) game.add_child(Node.s16("skill_name_id", profile.get_int("skill_name_id", -1))) - game.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20)) - ) + game.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20))) game.add_child(Node.u32("blaster_energy", profile.get_int("blaster_energy"))) game.add_child(Node.u32("blaster_count", profile.get_int("blaster_count"))) @@ -3182,25 +3171,17 @@ class SoundVoltexGravityWarsSeason1( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": continue itemtype = int(item.type[5:]) - if ( - game_config.get_bool("force_unlock_songs") - and itemtype == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and itemtype == self.GAME_CATALOG_TYPE_SONG: # Don't echo unlocked songs, we will add all of them later continue - if ( - game_config.get_bool("force_unlock_cards") - and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't echo unlocked appeal cards, we will add all of them later continue @@ -3274,30 +3255,22 @@ class SoundVoltexGravityWarsSeason1( storynode.add_child(info) info.add_child(Node.s32("story_id", story.id)) info.add_child(Node.s32("progress_id", story.data.get_int("progress_id"))) - info.add_child( - Node.s32("progress_param", story.data.get_int("progress_param")) - ) + info.add_child(Node.s32("progress_param", story.data.get_int("progress_param"))) info.add_child(Node.s32("clear_cnt", story.data.get_int("clear_cnt"))) info.add_child(Node.u32("route_flg", story.data.get_int("route_flg"))) return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -3308,9 +3281,7 @@ class SoundVoltexGravityWarsSeason1( # Miscelaneous stuff newprofile.replace_int("blaster_count", request.child_value("blaster_count")) newprofile.replace_int("skill_name_id", request.child_value("skill_name_id")) - newprofile.replace_int_array( - "hidden_param", 20, request.child_value("hidden_param") - ) + newprofile.replace_int_array("hidden_param", 20, request.child_value("hidden_param")) # Update user's unlock status if we aren't force unlocked game_config = self.get_game_config() @@ -3324,22 +3295,13 @@ class SoundVoltexGravityWarsSeason1( item_type = child.child_value("type") param = child.child_value("param") - if ( - game_config.get_bool("force_unlock_cards") - and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't save back appeal cards because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_songs") - and item_type == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and item_type == self.GAME_CATALOG_TYPE_SONG: # Don't save back songs, because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_crew") - and item_type == self.GAME_CATALOG_TYPE_CREW - ): + if game_config.get_bool("force_unlock_crew") and item_type == self.GAME_CATALOG_TYPE_CREW: # Don't save back crew, because they were force unlocked continue diff --git a/bemani/backend/sdvx/gravitywars_s2.py b/bemani/backend/sdvx/gravitywars_s2.py index 0492dfb..e0e0a14 100644 --- a/bemani/backend/sdvx/gravitywars_s2.py +++ b/bemani/backend/sdvx/gravitywars_s2.py @@ -3850,22 +3850,15 @@ class SoundVoltexGravityWarsSeason2( # Now, grab global and local scores as well as clear rates global_records = self.data.remote.music.get_all_records(self.game, self.version) - users = { - uid: prof - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) - } + users = {uid: prof for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version)} area_users = [uid for uid in users if users[uid].get_int("loc", -1) == locid] - area_records = self.data.local.music.get_all_records( - self.game, self.version, userlist=area_users - ) + area_records = self.data.local.music.get_all_records(self.game, self.version, userlist=area_users) clears = self.get_clear_rates() records: Dict[int, Dict[int, Dict[str, Tuple[UserID, Score]]]] = {} - missing_users = [ - userid for (userid, _) in global_records if userid not in users - ] + [userid for (userid, _) in area_records if userid not in users] + missing_users = [userid for (userid, _) in global_records if userid not in users] + [ + userid for (userid, _) in area_records if userid not in users + ] for userid, profile in self.get_any_profiles(missing_users): users[userid] = profile @@ -3896,9 +3889,7 @@ class SoundVoltexGravityWarsSeason2( global_profile = users[globaluserid] if clears[musicid][chart]["total"] > 0: - clear_rate = float(clears[musicid][chart]["clears"]) / float( - clears[musicid][chart]["total"] - ) + clear_rate = float(clears[musicid][chart]["clears"]) / float(clears[musicid][chart]["total"]) else: clear_rate = 0.0 @@ -3906,9 +3897,7 @@ class SoundVoltexGravityWarsSeason2( highscores.add_child(info) info.add_child(Node.u32("id", musicid)) info.add_child(Node.u32("ty", chart)) - info.add_child( - Node.string("a_sq", ID.format_extid(global_profile.extid)) - ) + info.add_child(Node.string("a_sq", ID.format_extid(global_profile.extid))) info.add_child(Node.string("a_nm", global_profile.get_str("name"))) info.add_child(Node.u32("a_sc", globalscore.points)) info.add_child(Node.s32("cr", int(clear_rate * 10000))) @@ -3916,9 +3905,7 @@ class SoundVoltexGravityWarsSeason2( if "area" in records[musicid][chart]: (localuserid, localscore) = records[musicid][chart]["area"] local_profile = users[localuserid] - info.add_child( - Node.string("l_sq", ID.format_extid(local_profile.extid)) - ) + info.add_child(Node.string("l_sq", ID.format_extid(local_profile.extid))) info.add_child(Node.string("l_nm", local_profile.get_str("name"))) info.add_child(Node.u32("l_sc", localscore.points)) @@ -3946,15 +3933,11 @@ class SoundVoltexGravityWarsSeason2( rival = Node.void("rival") game.add_child(rival) rival.add_child(Node.s16("no", index)) - rival.add_child( - Node.string("seq", ID.format_extid(other_profile.extid)) - ) + rival.add_child(Node.string("seq", ID.format_extid(other_profile.extid))) rival.add_child(Node.string("name", other_profile.get_str("name"))) # Return scores for this user on random charts - scores = self.data.remote.music.get_scores( - self.game, self.version, link.other_userid - ) + scores = self.data.remote.music.get_scores(self.game, self.version, link.other_userid) for score in scores: music = Node.void("music") rival.add_child(music) @@ -3975,14 +3958,10 @@ class SoundVoltexGravityWarsSeason2( game.add_child( Node.s16( "skill_name_id", - profile.get_int( - "chosen_skill_id", profile.get_int("skill_name_id", -1) - ), + profile.get_int("chosen_skill_id", profile.get_int("skill_name_id", -1)), ) ) - game.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20)) - ) + game.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20))) game.add_child(Node.u32("blaster_energy", profile.get_int("blaster_energy"))) game.add_child(Node.u32("blaster_count", profile.get_int("blaster_count"))) @@ -4011,31 +3990,20 @@ class SoundVoltexGravityWarsSeason2( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": continue itemtype = int(item.type[5:]) - if ( - game_config.get_bool("force_unlock_songs") - and itemtype == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and itemtype == self.GAME_CATALOG_TYPE_SONG: # Don't echo unlocked songs, we will add all of them later continue - if ( - game_config.get_bool("force_unlock_cards") - and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't echo unlocked appeal cards, we will add all of them later continue - if ( - game_config.get_bool("force_unlock_crew") - and itemtype == self.GAME_CATALOG_TYPE_CREW - ): + if game_config.get_bool("force_unlock_crew") and itemtype == self.GAME_CATALOG_TYPE_CREW: # Don't echo unlocked crew, we will add all of them later continue @@ -4104,8 +4072,7 @@ class SoundVoltexGravityWarsSeason2( courselist = [ c for c in self._get_skill_analyzer_courses() - if c.get("id", c["level"]) == course_id - and c["season_id"] == season_id + if c.get("id", c["level"]) == course_id and c["season_id"] == season_id ] if len(courselist) > 0: skill_level = max(skill_level, courselist[0]["level"]) @@ -4132,9 +4099,7 @@ class SoundVoltexGravityWarsSeason2( storynode.add_child(info) info.add_child(Node.s32("story_id", story.id)) info.add_child(Node.s32("progress_id", story.data.get_int("progress_id"))) - info.add_child( - Node.s32("progress_param", story.data.get_int("progress_param")) - ) + info.add_child(Node.s32("progress_param", story.data.get_int("progress_param"))) info.add_child(Node.s32("clear_cnt", story.data.get_int("clear_cnt"))) info.add_child(Node.u32("route_flg", story.data.get_int("route_flg"))) @@ -4157,22 +4122,16 @@ class SoundVoltexGravityWarsSeason2( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -4183,9 +4142,7 @@ class SoundVoltexGravityWarsSeason2( # Miscelaneous stuff newprofile.replace_int("blaster_count", request.child_value("blaster_count")) newprofile.replace_int("chosen_skill_id", request.child_value("skill_name_id")) - newprofile.replace_int_array( - "hidden_param", 20, request.child_value("hidden_param") - ) + newprofile.replace_int_array("hidden_param", 20, request.child_value("hidden_param")) # Update user's unlock status if we aren't force unlocked game_config = self.get_game_config() @@ -4199,22 +4156,13 @@ class SoundVoltexGravityWarsSeason2( item_type = child.child_value("type") param = child.child_value("param") - if ( - game_config.get_bool("force_unlock_cards") - and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't save back appeal cards because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_songs") - and item_type == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and item_type == self.GAME_CATALOG_TYPE_SONG: # Don't save back songs, because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_crew") - and item_type == self.GAME_CATALOG_TYPE_CREW - ): + if game_config.get_bool("force_unlock_crew") and item_type == self.GAME_CATALOG_TYPE_CREW: # Don't save back crew, because they were force unlocked continue diff --git a/bemani/backend/sdvx/heavenlyhaven.py b/bemani/backend/sdvx/heavenlyhaven.py index 842b5d4..8047142 100644 --- a/bemani/backend/sdvx/heavenlyhaven.py +++ b/bemani/backend/sdvx/heavenlyhaven.py @@ -68,9 +68,7 @@ class SoundVoltexHeavenlyHaven( GAME_SKILL_NAME_ID_BMK2017: Final[int] = 19 GAME_SKILL_NAME_ID_KAC_7TH_TIGER: Final[int] = 20 GAME_SKILL_NAME_ID_KAC_7TH_WOLF: Final[int] = 21 - GAME_SKILL_NAME_ID_RIKKA: Final[ - int - ] = 22 # For the course that ran from 1/18/2018-2/18/2018 + GAME_SKILL_NAME_ID_RIKKA: Final[int] = 22 # For the course that ran from 1/18/2018-2/18/2018 GAME_SKILL_NAME_ID_KAC_8TH: Final[int] = 23 # Return the local2 service so that SDVX 4 and above will send certain packets. @@ -3336,9 +3334,7 @@ class SoundVoltexHeavenlyHaven( skill_course = Node.void("skill_course") game.add_child(skill_course) - achievements = self.data.local.user.get_all_achievements( - self.game, self.version, achievementtype="course" - ) + achievements = self.data.local.user.get_all_achievements(self.game, self.version, achievementtype="course") courserates: Dict[Tuple[int, int], Dict[str, int]] = {} def getrates(season_id: int, course_id: int) -> Dict[str, int]: @@ -3372,14 +3368,8 @@ class SoundVoltexHeavenlyHaven( info.add_child(Node.s32("season_id", course["season_id"])) info.add_child(Node.string("season_name", seasons[course["season_id"]])) - info.add_child( - Node.bool("season_new_flg", course["season_id"] in {10, 11, 12, 22, 23}) - ) - info.add_child( - Node.s16( - "course_id", course.get("course_id", course.get("skill_level", -1)) - ) - ) + info.add_child(Node.bool("season_new_flg", course["season_id"] in {10, 11, 12, 22, 23})) + info.add_child(Node.s16("course_id", course.get("course_id", course.get("skill_level", -1)))) info.add_child( Node.string( "course_name", @@ -3409,8 +3399,7 @@ class SoundVoltexHeavenlyHaven( info.add_child( Node.bool( "matching_assist", - course.get("skill_level", -1) >= 1 - and course.get("skill_level", -1) <= 7, + course.get("skill_level", -1) >= 1 and course.get("skill_level", -1) <= 7, ) ) @@ -3420,14 +3409,8 @@ class SoundVoltexHeavenlyHaven( course.get("course_id", course.get("skill_level", -1)), ) if rate["attempts"] > 0: - info.add_child( - Node.s32( - "clear_rate", int(100.0 * (rate["clears"] / rate["attempts"])) - ) - ) - info.add_child( - Node.u32("avg_score", rate["total_score"] // rate["attempts"]) - ) + info.add_child(Node.s32("clear_rate", int(100.0 * (rate["clears"] / rate["attempts"])))) + info.add_child(Node.u32("avg_score", rate["total_score"] // rate["attempts"])) else: info.add_child(Node.s32("clear_rate", 0)) info.add_child(Node.u32("avg_score", 0)) @@ -3461,22 +3444,15 @@ class SoundVoltexHeavenlyHaven( # Now, grab global and local scores as well as clear rates global_records = self.data.remote.music.get_all_records(self.game, self.version) - users = { - uid: prof - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) - } + users = {uid: prof for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version)} area_users = [uid for uid in users if users[uid].get_int("loc", -1) == locid] - area_records = self.data.local.music.get_all_records( - self.game, self.version, userlist=area_users - ) + area_records = self.data.local.music.get_all_records(self.game, self.version, userlist=area_users) clears = self.get_clear_rates() records: Dict[int, Dict[int, Dict[str, Tuple[UserID, Score]]]] = {} - missing_users = [ - userid for (userid, _) in global_records if userid not in users - ] + [userid for (userid, _) in area_records if userid not in users] + missing_users = [userid for (userid, _) in global_records if userid not in users] + [ + userid for (userid, _) in area_records if userid not in users + ] for userid, profile in self.get_any_profiles(missing_users): users[userid] = profile @@ -3507,9 +3483,7 @@ class SoundVoltexHeavenlyHaven( global_profile = users[globaluserid] if clears[musicid][chart]["total"] > 0: - clear_rate = float(clears[musicid][chart]["clears"]) / float( - clears[musicid][chart]["total"] - ) + clear_rate = float(clears[musicid][chart]["clears"]) / float(clears[musicid][chart]["total"]) else: clear_rate = 0.0 @@ -3517,9 +3491,7 @@ class SoundVoltexHeavenlyHaven( highscores.add_child(info) info.add_child(Node.u32("id", musicid)) info.add_child(Node.u32("ty", chart)) - info.add_child( - Node.string("a_sq", ID.format_extid(global_profile.extid)) - ) + info.add_child(Node.string("a_sq", ID.format_extid(global_profile.extid))) info.add_child(Node.string("a_nm", global_profile.get_str("name"))) info.add_child(Node.u32("a_sc", globalscore.points)) info.add_child(Node.s32("cr", int(clear_rate * 10000))) @@ -3528,9 +3500,7 @@ class SoundVoltexHeavenlyHaven( if "area" in records[musicid][chart]: (localuserid, localscore) = records[musicid][chart]["area"] local_profile = users[localuserid] - info.add_child( - Node.string("l_sq", ID.format_extid(local_profile.extid)) - ) + info.add_child(Node.string("l_sq", ID.format_extid(local_profile.extid))) info.add_child(Node.string("l_nm", local_profile.get_str("name"))) info.add_child(Node.u32("l_sc", localscore.points)) @@ -3655,18 +3625,14 @@ class SoundVoltexHeavenlyHaven( rival = Node.void("rival") game.add_child(rival) rival.add_child(Node.s16("no", index)) - rival.add_child( - Node.string("seq", ID.format_extid(other_profile.extid)) - ) + rival.add_child(Node.string("seq", ID.format_extid(other_profile.extid))) rival.add_child(Node.string("name", other_profile.get_str("name"))) # Keep track of index index = index + 1 # Return scores for this user on random charts - scores = self.data.remote.music.get_scores( - self.game, self.version, link.other_userid - ) + scores = self.data.remote.music.get_scores(self.game, self.version, link.other_userid) for score in scores: music = Node.void("music") rival.add_child(music) @@ -3677,9 +3643,7 @@ class SoundVoltexHeavenlyHaven( score.id, score.chart, score.points, - self.__db_to_game_clear_type( - score.data.get_int("clear_type") - ), + self.__db_to_game_clear_type(score.data.get_int("clear_type")), self.__db_to_game_grade(score.data.get_int("grade")), ], ) @@ -3956,31 +3920,20 @@ class SoundVoltexHeavenlyHaven( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": continue itemtype = int(item.type[5:]) - if ( - game_config.get_bool("force_unlock_songs") - and itemtype == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and itemtype == self.GAME_CATALOG_TYPE_SONG: # Don't echo unlocked songs, we will add all of them later continue - if ( - game_config.get_bool("force_unlock_cards") - and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and itemtype == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't echo unlocked appeal cards, we will add all of them later continue - if ( - game_config.get_bool("force_unlock_crew") - and itemtype == self.GAME_CATALOG_TYPE_CREW - ): + if game_config.get_bool("force_unlock_crew") and itemtype == self.GAME_CATALOG_TYPE_CREW: # Don't echo unlocked crew, we will add all of them later continue @@ -4047,8 +4000,7 @@ class SoundVoltexHeavenlyHaven( courselist = [ c for c in self.__get_skill_analyzer_courses() - if c.get("course_id", c.get("skill_level", -1)) == course_id - and c["season_id"] == season_id + if c.get("course_id", c.get("skill_level", -1)) == course_id and c["season_id"] == season_id ] if len(courselist) > 0: skill_level = max(skill_level, courselist[0]["skill_level"]) @@ -4060,9 +4012,7 @@ class SoundVoltexHeavenlyHaven( course_node.add_child(Node.s32("sc", course.data.get_int("score"))) course_node.add_child(Node.s16("ct", course.data.get_int("clear_type"))) course_node.add_child(Node.s16("gr", course.data.get_int("grade"))) - course_node.add_child( - Node.s16("ar", course.data.get_int("achievement_rate")) - ) + course_node.add_child(Node.s16("ar", course.data.get_int("achievement_rate"))) course_node.add_child(Node.s16("cnt", 1)) # Calculated skill level @@ -4104,22 +4054,16 @@ class SoundVoltexHeavenlyHaven( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -4146,22 +4090,13 @@ class SoundVoltexHeavenlyHaven( item_type = child.child_value("type") param = child.child_value("param") - if ( - game_config.get_bool("force_unlock_cards") - and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD - ): + if game_config.get_bool("force_unlock_cards") and item_type == self.GAME_CATALOG_TYPE_APPEAL_CARD: # Don't save back appeal cards because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_songs") - and item_type == self.GAME_CATALOG_TYPE_SONG - ): + if game_config.get_bool("force_unlock_songs") and item_type == self.GAME_CATALOG_TYPE_SONG: # Don't save back songs, because they were force unlocked continue - if ( - game_config.get_bool("force_unlock_crew") - and item_type == self.GAME_CATALOG_TYPE_CREW - ): + if game_config.get_bool("force_unlock_crew") and item_type == self.GAME_CATALOG_TYPE_CREW: # Don't save back crew, because they were force unlocked continue diff --git a/bemani/backend/sdvx/infiniteinfection.py b/bemani/backend/sdvx/infiniteinfection.py index da8f5e2..3a4704d 100644 --- a/bemani/backend/sdvx/infiniteinfection.py +++ b/bemani/backend/sdvx/infiniteinfection.py @@ -1920,9 +1920,7 @@ class SoundVoltexInfiniteInfection( elif unlock.type == "special_unlock": info = Node.void("info") catalog.add_child(info) - info.add_child( - Node.u8("catalog_type", self.GAME_CATALOG_TYPE_SPECIAL_SONG) - ) + info.add_child(Node.u8("catalog_type", self.GAME_CATALOG_TYPE_SPECIAL_SONG)) info.add_child(Node.u32("catalog_id", unlock.id)) info.add_child(Node.u32("currency_type", self.GAME_CURRENCY_BLOCKS)) info.add_child(Node.u32("price", unlock.data.get_int("blocks"))) @@ -1941,9 +1939,7 @@ class SoundVoltexInfiniteInfection( info.add_child(Node.s16("level", course["level"])) info.add_child(Node.s32("season_id", course["season_id"])) info.add_child(Node.string("season_name", seasons[course["season_id"]])) - info.add_child( - Node.bool("season_new_flg", course["season_id"] == last_season) - ) + info.add_child(Node.bool("season_new_flg", course["season_id"] == last_season)) info.add_child(Node.string("course_name", skillnames[course["level"]])) info.add_child(Node.s16("course_type", 0)) info.add_child(Node.s16("skill_name_id", course["level"])) @@ -1983,10 +1979,7 @@ class SoundVoltexInfiniteInfection( # Now, grab user records records = self.data.remote.music.get_all_records(self.game, self.version) missing_users = [userid for (userid, _) in records] - users = { - userid: profile - for (userid, profile) in self.get_any_profiles(missing_users) - } + users = {userid: profile for (userid, profile) in self.get_any_profiles(missing_users)} hiscore_allover = Node.void("hiscore_allover") game.add_child(hiscore_allover) @@ -2011,14 +2004,10 @@ class SoundVoltexInfiniteInfection( # Now, grab local records area_users = [ uid - for (uid, prof) in self.data.local.user.get_all_profiles( - self.game, self.version - ) + for (uid, prof) in self.data.local.user.get_all_profiles(self.game, self.version) if prof.get_int("loc", -1) == locid ] - records = self.data.local.music.get_all_records( - self.game, self.version, userlist=area_users - ) + records = self.data.local.music.get_all_records(self.game, self.version, userlist=area_users) missing_users = [userid for (userid, _) in records if userid not in users] for userid, profile in self.get_any_profiles(missing_users): users[userid] = profile @@ -2051,9 +2040,7 @@ class SoundVoltexInfiniteInfection( for songid in clears: for chart in clears[songid]: if clears[songid][chart]["total"] > 0: - rate = float(clears[songid][chart]["clears"]) / float( - clears[songid][chart]["total"] - ) + rate = float(clears[songid][chart]["clears"]) / float(clears[songid][chart]["total"]) dnode = Node.void("d") clear_rate.add_child(dnode) dnode.add_child(Node.u32("id", songid)) @@ -2155,11 +2142,7 @@ class SoundVoltexInfiniteInfection( self.__db_to_game_clear_type(score.data.get_int("clear_type")), ) ) - music.add_child( - Node.u32( - "score_grade", self.__db_to_game_grade(score.data.get_int("grade")) - ) - ) + music.add_child(Node.u32("score_grade", self.__db_to_game_grade(score.data.get_int("grade")))) stats = score.data.get_dict("stats") music.add_child(Node.u32("btn_rate", stats.get_int("btn_rate"))) music.add_child(Node.u32("long_rate", stats.get_int("long_rate"))) @@ -2330,9 +2313,7 @@ class SoundVoltexInfiniteInfection( game.add_child(Node.u32("gamecoin_packet", profile.get_int("packet"))) game.add_child(Node.u32("gamecoin_block", profile.get_int("block"))) game.add_child(Node.s16("skill_name_id", profile.get_int("skill_name_id", -1))) - game.add_child( - Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20)) - ) + game.add_child(Node.s32_array("hidden_param", profile.get_int_array("hidden_param", 20))) game.add_child(Node.u32("blaster_energy", profile.get_int("blaster_energy"))) game.add_child(Node.u32("blaster_count", profile.get_int("blaster_count"))) @@ -2362,9 +2343,7 @@ class SoundVoltexInfiniteInfection( game.add_child(itemnode) game_config = self.get_game_config() - achievements = self.data.local.user.get_achievements( - self.game, self.version, userid - ) + achievements = self.data.local.user.get_achievements(self.game, self.version, userid) for item in achievements: if item.type[:5] != "item_": @@ -2375,9 +2354,7 @@ class SoundVoltexInfiniteInfection( # Type 1 is appeal cards, and the game saves this for non-default cards but # we take care of this below. continue - if itemtype == self.GAME_CATALOG_TYPE_SONG and game_config.get_bool( - "force_unlock_songs" - ): + if itemtype == self.GAME_CATALOG_TYPE_SONG and game_config.get_bool("force_unlock_songs"): # We will echo this below in the force unlock song section continue @@ -2452,22 +2429,16 @@ class SoundVoltexInfiniteInfection( return game - def unformat_profile( - self, userid: UserID, request: Node, oldprofile: Profile - ) -> Profile: + def unformat_profile(self, userid: UserID, request: Node, oldprofile: Profile) -> Profile: newprofile = oldprofile.clone() # Update blaster energy and in-game currencies earned_gamecoin_packet = request.child_value("earned_gamecoin_packet") if earned_gamecoin_packet is not None: - newprofile.replace_int( - "packet", newprofile.get_int("packet") + earned_gamecoin_packet - ) + newprofile.replace_int("packet", newprofile.get_int("packet") + earned_gamecoin_packet) earned_gamecoin_block = request.child_value("earned_gamecoin_block") if earned_gamecoin_block is not None: - newprofile.replace_int( - "block", newprofile.get_int("block") + earned_gamecoin_block - ) + newprofile.replace_int("block", newprofile.get_int("block") + earned_gamecoin_block) earned_blaster_energy = request.child_value("earned_blaster_energy") if earned_blaster_energy is not None: newprofile.replace_int( @@ -2478,9 +2449,7 @@ class SoundVoltexInfiniteInfection( # Miscelaneous stuff newprofile.replace_int("blaster_count", request.child_value("blaster_count")) newprofile.replace_int("skill_name_id", request.child_value("skill_name_id")) - newprofile.replace_int_array( - "hidden_param", 20, request.child_value("hidden_param") - ) + newprofile.replace_int_array("hidden_param", 20, request.child_value("hidden_param")) # Update user's unlock status if we aren't force unlocked game_config = self.get_game_config() diff --git a/bemani/client/base.py b/bemani/client/base.py index effb4d6..543f975 100644 --- a/bemani/client/base.py +++ b/bemani/client/base.py @@ -22,9 +22,7 @@ class BaseClient: CORRECT_PASSWORD: Final[str] = "1234" WRONG_PASSWORD: Final[str] = "4321" - def __init__( - self, proto: ClientProtocol, pcbid: str, config: Dict[str, Any] - ) -> None: + def __init__(self, proto: ClientProtocol, pcbid: str, config: Dict[str, Any]) -> None: self.__proto = proto self.pcbid = pcbid self.config = config @@ -92,9 +90,7 @@ class BaseClient: if not self.__assert_path(root, path): raise Exception(f"Path '{path}' not found in root node:\n{root}") - def verify_services_get( - self, expected_services: List[str] = [], include_net: bool = False - ) -> None: + def verify_services_get(self, expected_services: List[str] = [], include_net: bool = False) -> None: call = self.call_node() # Construct node @@ -254,9 +250,7 @@ class BaseClient: # Verify that response is correct self.assert_path(resp, "response/pcbevent") - def verify_cardmng_inquire( - self, card_id: str, msg_type: str, paseli_enabled: bool - ) -> Optional[str]: + def verify_cardmng_inquire(self, card_id: str, msg_type: str, paseli_enabled: bool) -> Optional[str]: call = self.call_node() # Construct node @@ -295,17 +289,11 @@ class BaseClient: ecflag = int(resp.child("cardmng").attribute("ecflag")) if binded != 0: - raise Exception( - f"Card '{card_id}' returned invalid binded value '{binded}'" - ) + raise Exception(f"Card '{card_id}' returned invalid binded value '{binded}'") if newflag != 1: - raise Exception( - f"Card '{card_id}' returned invalid newflag value '{newflag}'" - ) + raise Exception(f"Card '{card_id}' returned invalid newflag value '{newflag}'") if ecflag != (1 if paseli_enabled else 0): - raise Exception( - f"Card '{card_id}' returned invalid ecflag value '{newflag}'" - ) + raise Exception(f"Card '{card_id}' returned invalid ecflag value '{newflag}'") # Return the refid return resp.child("cardmng").attribute("refid") @@ -321,17 +309,11 @@ class BaseClient: ecflag = int(resp.child("cardmng").attribute("ecflag")) if binded != 1: - raise Exception( - f"Card '{card_id}' returned invalid binded value '{binded}'" - ) + raise Exception(f"Card '{card_id}' returned invalid binded value '{binded}'") if newflag != 0: - raise Exception( - f"Card '{card_id}' returned invalid newflag value '{newflag}'" - ) + raise Exception(f"Card '{card_id}' returned invalid newflag value '{newflag}'") if ecflag != (1 if paseli_enabled else 0): - raise Exception( - f"Card '{card_id}' returned invalid ecflag value '{newflag}'" - ) + raise Exception(f"Card '{card_id}' returned invalid ecflag value '{newflag}'") # Return the refid return resp.child("cardmng").attribute("refid") @@ -365,9 +347,7 @@ class BaseClient: cardmng = Node.void("cardmng") call.add_child(cardmng) cardmng.set_attribute("method", "authpass") - cardmng.set_attribute( - "pass", self.CORRECT_PASSWORD if correct else self.CORRECT_PASSWORD[::-1] - ) + cardmng.set_attribute("pass", self.CORRECT_PASSWORD if correct else self.CORRECT_PASSWORD[::-1]) cardmng.set_attribute("refid", ref_id) # Swap with server @@ -426,9 +406,7 @@ class BaseClient: newbalance = resp.child("eacoin").child_value("balance") if balance - amount != newbalance: - raise Exception( - f"Expected to get back balance {balance - amount} but got {newbalance}" - ) + raise Exception(f"Expected to get back balance {balance - amount} but got {newbalance}") def verify_eacoin_checkout(self, session: str) -> None: call = self.call_node() diff --git a/bemani/client/bishi/bishi.py b/bemani/client/bishi/bishi.py index 021fbaa..2b07f26 100644 --- a/bemani/client/bishi/bishi.py +++ b/bemani/client/bishi/bishi.py @@ -190,32 +190,22 @@ class TheStarBishiBashiClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Bishi doesn't read a new profile, it just writes out CSV for a blank one self.verify_usergamedata_send(ref_id, msg_type="new") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/ddr/ddr2013.py b/bemani/client/ddr/ddr2013.py index 686a28f..cc403b4 100644 --- a/bemani/client/ddr/ddr2013.py +++ b/bemani/client/ddr/ddr2013.py @@ -403,9 +403,7 @@ class DDR2013Client(BaseClient): scores[reclink][chart] = vals return scores - def verify_game_save( - self, ref_id: str, style: int, gauge: Optional[List[int]] = None - ) -> None: + def verify_game_save(self, ref_id: str, style: int, gauge: Optional[List[int]] = None) -> None: gauge = gauge or [0, 0, 0, 0, 0] call = self.call_node() @@ -460,9 +458,7 @@ class DDR2013Client(BaseClient): int(resp.child("game").attribute("sc5")), ] - def verify_game_save_m( - self, ref_id: str, ext_id: str, score: Dict[str, Any] - ) -> None: + def verify_game_save_m(self, ref_id: str, ext_id: str, score: Dict[str, Any]) -> None: call = self.call_node() game = Node.void("game") call.add_child(game) @@ -544,33 +540,23 @@ class DDR2013Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Bishi doesn't read a new profile, it just writes out CSV for a blank one self.verify_game_load(ref_id, msg_type="new") self.verify_game_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify locking and unlocking profile ability @@ -703,22 +689,16 @@ class DDR2013Client(BaseClient): # Verify empty scores for starters if phase == 1: for score in dummyscores: - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if any([s != 0 for s in last_five]): - raise Exception( - "Score already found on song not played yet!" - ) + raise Exception("Score already found on song not played yet!") for score in dummyscores: self.verify_game_save_m(ref_id, ext_id, score) scores = self.verify_game_load_m(ref_id) for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') # Verify the attributes of the score expected_score = score.get("expected_score", score["score"]) @@ -739,9 +719,7 @@ class DDR2013Client(BaseClient): ) # Verify that the last score is our score - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if last_five[0] != score["score"]: raise Exception( f'Invalid score returned for last five scores on song {score["id"]} chart {score["chart"]}!' diff --git a/bemani/client/ddr/ddr2014.py b/bemani/client/ddr/ddr2014.py index acf2c43..dd2e24c 100644 --- a/bemani/client/ddr/ddr2014.py +++ b/bemani/client/ddr/ddr2014.py @@ -423,9 +423,7 @@ class DDR2014Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game") - def verify_game_save( - self, ref_id: str, style: int, gauge: Optional[List[int]] = None - ) -> None: + def verify_game_save(self, ref_id: str, style: int, gauge: Optional[List[int]] = None) -> None: gauge = gauge or [0, 0, 0, 0, 0] call = self.call_node() @@ -453,9 +451,7 @@ class DDR2014Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game") - def verify_game_save_m( - self, ref_id: str, ext_id: str, score: Dict[str, Any] - ) -> None: + def verify_game_save_m(self, ref_id: str, ext_id: str, score: Dict[str, Any]) -> None: call = self.call_node() game = Node.void("game") call.add_child(game) @@ -546,33 +542,23 @@ class DDR2014Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Bishi doesn't read a new profile, it just writes out CSV for a blank one self.verify_game_load(ref_id, msg_type="new") self.verify_game_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify locking and unlocking profile ability @@ -709,9 +695,7 @@ class DDR2014Client(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') # Verify the attributes of the score expected_score = score.get("expected_score", score["score"]) diff --git a/bemani/client/ddr/ddrace.py b/bemani/client/ddr/ddrace.py index 576970c..bf1660a 100644 --- a/bemani/client/ddr/ddrace.py +++ b/bemani/client/ddr/ddrace.py @@ -99,9 +99,7 @@ class DDRAceClient(BaseClient): return resp.child_value("playerdata/code") - def verify_playerdata_usergamedata_advanced_ghostload( - self, refid: str, ghostid: int - ) -> Dict[str, Any]: + def verify_playerdata_usergamedata_advanced_ghostload(self, refid: str, ghostid: int) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -140,9 +138,7 @@ class DDRAceClient(BaseClient): "ghost": resp.child_value("playerdata/ghostdata/ghost"), } - def verify_playerdata_usergamedata_advanced_rivalload( - self, refid: str, loadflag: int - ) -> None: + def verify_playerdata_usergamedata_advanced_rivalload(self, refid: str, loadflag: int) -> None: call = self.call_node() # Construct node @@ -191,9 +187,7 @@ class DDRAceClient(BaseClient): if resp.child_value("playerdata/data/recordtype") != loadflag: raise Exception("Invalid record type returned!") - def verify_playerdata_usergamedata_advanced_userload( - self, refid: str - ) -> Tuple[bool, List[Dict[str, Any]]]: + def verify_playerdata_usergamedata_advanced_userload(self, refid: str) -> Tuple[bool, List[Dict[str, Any]]]: call = self.call_node() # Construct node @@ -252,9 +246,7 @@ class DDRAceClient(BaseClient): music, ) - def verify_playerdata_usergamedata_advanced_inheritance( - self, refid: str, locid: str - ) -> None: + def verify_playerdata_usergamedata_advanced_inheritance(self, refid: str, locid: str) -> None: call = self.call_node() # Construct node @@ -454,9 +446,7 @@ class DDRAceClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/playerdata/result") - def verify_usergamedata_send( - self, ref_id: str, ext_id: int, msg_type: str, send_only_common: bool = False - ) -> None: + def verify_usergamedata_send(self, ref_id: str, ext_id: int, msg_type: str, send_only_common: bool = False) -> None: call = self.call_node() # Set up profile write @@ -720,9 +710,7 @@ class DDRAceClient(BaseClient): self.verify_eventlog_write(location) # Verify the game-wide packets Ace insists on sending before profile load - is_new, music = self.verify_playerdata_usergamedata_advanced_userload( - "X0000000000000000000000000123456" - ) + is_new, music = self.verify_playerdata_usergamedata_advanced_userload("X0000000000000000000000000123456") if not is_new: raise Exception("Fake profiles should be new!") if len(music) > 0: @@ -736,18 +724,12 @@ class DDRAceClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) self.verify_system_convcardnumber(card) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") extid = self.verify_playerdata_usergamedata_advanced_usernew(ref_id) self.verify_usergamedata_send(ref_id, extid, "new") @@ -755,30 +737,22 @@ class DDRAceClient(BaseClient): name = self.verify_usergamedata_recv(ref_id) if name != "": raise Exception("Name stored on profile we just created!") - self.verify_usergamedata_send( - ref_id, extid, "existing", send_only_common=True - ) + self.verify_usergamedata_send(ref_id, extid, "existing", send_only_common=True) name = self.verify_usergamedata_recv(ref_id) if name != self.NAME: raise Exception("Name stored on profile is incorrect!") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: - is_new, music = self.verify_playerdata_usergamedata_advanced_userload( - ref_id - ) + is_new, music = self.verify_playerdata_usergamedata_advanced_userload(ref_id) if is_new: raise Exception("Profile should not be new!") if len(music) > 0: @@ -862,9 +836,7 @@ class DDRAceClient(BaseClient): ) pos = pos + 1 - is_new, scores = self.verify_playerdata_usergamedata_advanced_userload( - ref_id - ) + is_new, scores = self.verify_playerdata_usergamedata_advanced_userload(ref_id) if is_new: raise Exception("Profile should not be new!") if len(scores) == 0: @@ -873,17 +845,12 @@ class DDRAceClient(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] @@ -912,9 +879,7 @@ class DDRAceClient(BaseClient): ) # Now verify that the ghost for this score is what we saved - ghost = self.verify_playerdata_usergamedata_advanced_ghostload( - ref_id, received["ghostid"] - ) + ghost = self.verify_playerdata_usergamedata_advanced_ghostload(ref_id, received["ghostid"]) if "expected_ghost" in expected: expected_ghost = expected["expected_ghost"] else: @@ -933,9 +898,7 @@ class DDRAceClient(BaseClient): f'Wrong ghost data \'{ghost["ghost"]}\' returned for ghost, expected \'{expected_ghost}\'' ) if ghost["extid"] != extid: - raise Exception( - f'Wrong extid \'{ghost["extid"]}\' returned for ghost, expected \'{extid}\'' - ) + raise Exception(f'Wrong extid \'{ghost["extid"]}\' returned for ghost, expected \'{extid}\'') # Sleep so we don't end up putting in score history on the same second time.sleep(1) @@ -952,15 +915,9 @@ class DDRAceClient(BaseClient): print("Skipping score checks for existing card") # Verify global scores now that we've inserted some - self.verify_playerdata_usergamedata_advanced_rivalload( - "X0000000000000000000000000123456", 1 - ) - self.verify_playerdata_usergamedata_advanced_rivalload( - "X0000000000000000000000000123456", 2 - ) - self.verify_playerdata_usergamedata_advanced_rivalload( - "X0000000000000000000000000123456", 4 - ) + self.verify_playerdata_usergamedata_advanced_rivalload("X0000000000000000000000000123456", 1) + self.verify_playerdata_usergamedata_advanced_rivalload("X0000000000000000000000000123456", 2) + self.verify_playerdata_usergamedata_advanced_rivalload("X0000000000000000000000000123456", 4) # Verify paseli handling if paseli_enabled: diff --git a/bemani/client/ddr/ddrx2.py b/bemani/client/ddr/ddrx2.py index 13ff837..49b440a 100644 --- a/bemani/client/ddr/ddrx2.py +++ b/bemani/client/ddr/ddrx2.py @@ -347,9 +347,7 @@ class DDRX2Client(BaseClient): index = index + 1 return courses - def verify_game_save( - self, ref_id: str, style: int, gauge: Optional[List[int]] = None - ) -> None: + def verify_game_save(self, ref_id: str, style: int, gauge: Optional[List[int]] = None) -> None: gauge = gauge or [0, 0, 0, 0, 0] call = self.call_node() @@ -502,33 +500,23 @@ class DDRX2Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Bishi doesn't read a new profile, it just writes out CSV for a blank one self.verify_game_load(ref_id, msg_type="new") self.verify_game_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify locking and unlocking profile ability @@ -655,22 +643,16 @@ class DDRX2Client(BaseClient): # Verify empty scores for starters if phase == 1: for score in dummyscores: - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if any([s != 0 for s in last_five]): - raise Exception( - "Score already found on song not played yet!" - ) + raise Exception("Score already found on song not played yet!") for score in dummyscores: self.verify_game_save_m(ref_id, score) scores = self.verify_game_load_m(ref_id) for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') # Verify the attributes of the score expected_score = score.get("expected_score", score["score"]) @@ -691,9 +673,7 @@ class DDRX2Client(BaseClient): ) # Verify that the last score is our score - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if last_five[0] != score["score"]: raise Exception( f'Invalid score returned for last five scores on song {score["id"]} chart {score["chart"]}!' @@ -769,9 +749,7 @@ class DDRX2Client(BaseClient): expected_combo = course.get("expected_combo", course["combo"]) expected_rank = course.get("expected_rank", course["rank"]) expected_stage = course.get("expected_stage", course["stage"]) - expected_combo_type = course.get( - "expected_combo_type", course["combo_type"] - ) + expected_combo_type = course.get("expected_combo_type", course["combo_type"]) if data["score"] != expected_score: raise Exception( diff --git a/bemani/client/ddr/ddrx3.py b/bemani/client/ddr/ddrx3.py index 0e22dcb..11c2bd9 100644 --- a/bemani/client/ddr/ddrx3.py +++ b/bemani/client/ddr/ddrx3.py @@ -414,9 +414,7 @@ class DDRX3Client(BaseClient): index = index + 1 return courses - def verify_game_save( - self, ref_id: str, style: int, gauge: Optional[List[int]] = None - ) -> None: + def verify_game_save(self, ref_id: str, style: int, gauge: Optional[List[int]] = None) -> None: gauge = gauge or [0, 0, 0, 0, 0] call = self.call_node() @@ -579,33 +577,23 @@ class DDRX3Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Bishi doesn't read a new profile, it just writes out CSV for a blank one self.verify_game_load(ref_id, msg_type="new") self.verify_game_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify locking and unlocking profile ability @@ -778,33 +766,23 @@ class DDRX3Client(BaseClient): # Verify empty scores for starters if phase == 1: for score in dummyscores: - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if any([s != 0 for s in last_five]): - raise Exception( - "Score already found on song not played yet!" - ) + raise Exception("Score already found on song not played yet!") for score in dummyscores: self.verify_game_save_m(ref_id, score) scores = self.verify_game_load_m(ref_id) for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') # Verify the attributes of the score expected_score = score.get("expected_score", score["score"]) expected_rank = score.get("expected_rank", score["rank"]) expected_halo = score.get("expected_halo", score["halo"]) - expected_score_2nd = score.get( - "expected_score_2nd", score["score_2nd"] - ) - expected_rank_2nd = score.get( - "expected_rank_2nd", score["rank_2nd"] - ) + expected_score_2nd = score.get("expected_score_2nd", score["score_2nd"]) + expected_rank_2nd = score.get("expected_rank_2nd", score["rank_2nd"]) if score["score"] != 0: if data["score"] != expected_score: @@ -821,9 +799,7 @@ class DDRX3Client(BaseClient): ) # Verify that the last score is our score - last_five = self.verify_game_score( - ref_id, score["id"], score["chart"] - ) + last_five = self.verify_game_score(ref_id, score["id"], score["chart"]) if last_five[0] != score["score"]: raise Exception( f'Invalid score returned for last five scores on song {score["id"]} chart {score["chart"]}!' @@ -908,9 +884,7 @@ class DDRX3Client(BaseClient): expected_combo = course.get("expected_combo", course["combo"]) expected_rank = course.get("expected_rank", course["rank"]) expected_stage = course.get("expected_stage", course["stage"]) - expected_combo_type = course.get( - "expected_combo_type", course["combo_type"] - ) + expected_combo_type = course.get("expected_combo_type", course["combo_type"]) if data["score"] != expected_score: raise Exception( diff --git a/bemani/client/iidx/cannonballers.py b/bemani/client/iidx/cannonballers.py index 47b3d41..d430ea8 100644 --- a/bemani/client/iidx/cannonballers.py +++ b/bemani/client/iidx/cannonballers.py @@ -91,9 +91,7 @@ class IIDXCannonBallersClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 1001: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx25shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -175,9 +173,7 @@ class IIDXCannonBallersClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX25shop") - def verify_iidx25pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx25pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -297,9 +293,7 @@ class IIDXCannonBallersClient(BaseClient): "expert_point": expert_point, } - def verify_iidx25music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx25music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -321,9 +315,7 @@ class IIDXCannonBallersClient(BaseClient): for child in resp.child("IIDX25music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -461,9 +453,7 @@ class IIDXCannonBallersClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX25pc") - def verify_iidx25music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx25music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -491,9 +481,7 @@ class IIDXCannonBallersClient(BaseClient): self.assert_path(resp, "response/IIDX25music/shopdata/@rank") self.assert_path(resp, "response/IIDX25music/ranklist/data") - def verify_iidx25music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx25music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -618,9 +606,7 @@ class IIDXCannonBallersClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX25music") - def verify_iidx25grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx25grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -644,9 +630,7 @@ class IIDXCannonBallersClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX25grade/@pnum") - def verify_iidx25ranking_entry( - self, iidxid: int, shop_name: str, coursetype: str - ) -> None: + def verify_iidx25ranking_entry(self, iidxid: int, shop_name: str, coursetype: str) -> None: call = self.call_node() # Construct node @@ -757,13 +741,9 @@ class IIDXCannonBallersClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX25music/cpu_score_list/score_list/score") - self.assert_path( - resp, "response/IIDX25music/cpu_score_list/score_list/enable_score" - ) + self.assert_path(resp, "response/IIDX25music/cpu_score_list/score_list/enable_score") self.assert_path(resp, "response/IIDX25music/cpu_score_list/score_list/ghost") - self.assert_path( - resp, "response/IIDX25music/cpu_score_list/score_list/enable_ghost" - ) + self.assert_path(resp, "response/IIDX25music/cpu_score_list/score_list/enable_ghost") def verify_iidx25gamesystem_systeminfo(self, lid: str) -> None: call = self.call_node() @@ -820,32 +800,22 @@ class IIDXCannonBallersClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx25pc_reg(ref_id, card, lid) self.verify_iidx25pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -940,9 +910,7 @@ class IIDXCannonBallersClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -971,9 +939,7 @@ class IIDXCannonBallersClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx25music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx25music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -1078,9 +1044,7 @@ class IIDXCannonBallersClient(BaseClient): ) scores = self.verify_iidx25music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: @@ -1101,12 +1065,8 @@ class IIDXCannonBallersClient(BaseClient): self.verify_iidx25ranking_classicentry(profile["extid"]) profile = self.verify_iidx25pc_get(ref_id, card, lid) for ptype in ["ir_data", "secret_course_data", "classic_course_data"]: - if profile[ptype] != { - 2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}} - }: - raise Exception( - f"Invalid data {profile[ptype]} returned on profile load for {ptype}!" - ) + if profile[ptype] != {2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}}}: + raise Exception(f"Invalid data {profile[ptype]} returned on profile load for {ptype}!") else: print("Skipping score checks for existing card") diff --git a/bemani/client/iidx/copula.py b/bemani/client/iidx/copula.py index 1385976..b6c8e4d 100644 --- a/bemani/client/iidx/copula.py +++ b/bemani/client/iidx/copula.py @@ -90,9 +90,7 @@ class IIDXCopulaClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 101: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx23shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -171,9 +169,7 @@ class IIDXCopulaClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX23shop") - def verify_iidx23pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx23pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -269,9 +265,7 @@ class IIDXCopulaClient(BaseClient): "expert_point": expert_point, } - def verify_iidx23music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx23music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -293,9 +287,7 @@ class IIDXCopulaClient(BaseClient): for child in resp.child("IIDX23music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -434,9 +426,7 @@ class IIDXCopulaClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX23pc") - def verify_iidx23music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx23music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -464,9 +454,7 @@ class IIDXCopulaClient(BaseClient): self.assert_path(resp, "response/IIDX23music/shopdata/@rank") self.assert_path(resp, "response/IIDX23music/ranklist/data") - def verify_iidx23music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx23music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -586,9 +574,7 @@ class IIDXCopulaClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX23music") - def verify_iidx23grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx23grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -612,9 +598,7 @@ class IIDXCopulaClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX23grade/@pnum") - def verify_iidx23ranking_entry( - self, iidxid: int, shop_name: str, coursetype: str - ) -> None: + def verify_iidx23ranking_entry(self, iidxid: int, shop_name: str, coursetype: str) -> None: call = self.call_node() # Construct node @@ -682,32 +666,22 @@ class IIDXCopulaClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx23pc_reg(ref_id, card, lid) self.verify_iidx23pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -802,9 +776,7 @@ class IIDXCopulaClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -833,9 +805,7 @@ class IIDXCopulaClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx23music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx23music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -940,9 +910,7 @@ class IIDXCopulaClient(BaseClient): ) scores = self.verify_iidx23music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: @@ -962,12 +930,8 @@ class IIDXCopulaClient(BaseClient): self.verify_iidx23ranking_entry(profile["extid"], newname, "secret") profile = self.verify_iidx23pc_get(ref_id, card, lid) for ptype in ["ir_data", "secret_course_data"]: - if profile[ptype] != { - 2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}} - }: - raise Exception( - f"Invalid data {profile[ptype]} returned on profile load for {ptype}!" - ) + if profile[ptype] != {2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}}}: + raise Exception(f"Invalid data {profile[ptype]} returned on profile load for {ptype}!") else: print("Skipping score checks for existing card") diff --git a/bemani/client/iidx/pendual.py b/bemani/client/iidx/pendual.py index acb7600..5ecaee6 100644 --- a/bemani/client/iidx/pendual.py +++ b/bemani/client/iidx/pendual.py @@ -90,9 +90,7 @@ class IIDXPendualClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 101: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx22shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -171,9 +169,7 @@ class IIDXPendualClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX22shop") - def verify_iidx22pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx22pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -270,9 +266,7 @@ class IIDXPendualClient(BaseClient): "expert_point": expert_point, } - def verify_iidx22music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx22music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -294,9 +288,7 @@ class IIDXPendualClient(BaseClient): for child in resp.child("IIDX22music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -435,9 +427,7 @@ class IIDXPendualClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX22pc") - def verify_iidx22music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx22music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -465,9 +455,7 @@ class IIDXPendualClient(BaseClient): self.assert_path(resp, "response/IIDX22music/shopdata/@rank") self.assert_path(resp, "response/IIDX22music/ranklist/data") - def verify_iidx22music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx22music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -587,9 +575,7 @@ class IIDXPendualClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX22music") - def verify_iidx22grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx22grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -613,9 +599,7 @@ class IIDXPendualClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX22grade/@pnum") - def verify_iidx22ranking_entry( - self, iidxid: int, shop_name: str, coursetype: str - ) -> None: + def verify_iidx22ranking_entry(self, iidxid: int, shop_name: str, coursetype: str) -> None: call = self.call_node() # Construct node @@ -683,32 +667,22 @@ class IIDXPendualClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx22pc_reg(ref_id, card, lid) self.verify_iidx22pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -803,9 +777,7 @@ class IIDXPendualClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -834,9 +806,7 @@ class IIDXPendualClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx22music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx22music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -941,9 +911,7 @@ class IIDXPendualClient(BaseClient): ) scores = self.verify_iidx22music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: @@ -963,12 +931,8 @@ class IIDXPendualClient(BaseClient): self.verify_iidx22ranking_entry(profile["extid"], newname, "secret") profile = self.verify_iidx22pc_get(ref_id, card, lid) for ptype in ["ir_data", "secret_course_data"]: - if profile[ptype] != { - 2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}} - }: - raise Exception( - f"Invalid data {profile[ptype]} returned on profile load for {ptype}!" - ) + if profile[ptype] != {2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}}}: + raise Exception(f"Invalid data {profile[ptype]} returned on profile load for {ptype}!") else: print("Skipping score checks for existing card") diff --git a/bemani/client/iidx/rootage.py b/bemani/client/iidx/rootage.py index e7c0405..03009a6 100644 --- a/bemani/client/iidx/rootage.py +++ b/bemani/client/iidx/rootage.py @@ -90,9 +90,7 @@ class IIDXRootageClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 1001: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx26shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -174,9 +172,7 @@ class IIDXRootageClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX26shop") - def verify_iidx26pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx26pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -238,9 +234,7 @@ class IIDXRootageClient(BaseClient): "expert_point": expert_point, } - def verify_iidx26music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx26music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -262,9 +256,7 @@ class IIDXRootageClient(BaseClient): for child in resp.child("IIDX26music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -406,9 +398,7 @@ class IIDXRootageClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX26pc") - def verify_iidx26music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx26music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -436,9 +426,7 @@ class IIDXRootageClient(BaseClient): self.assert_path(resp, "response/IIDX26music/shopdata/@rank") self.assert_path(resp, "response/IIDX26music/ranklist/data") - def verify_iidx26music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx26music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -563,9 +551,7 @@ class IIDXRootageClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX26music") - def verify_iidx26grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx26grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -650,13 +636,9 @@ class IIDXRootageClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX26music/cpu_score_list/score_list/score") - self.assert_path( - resp, "response/IIDX26music/cpu_score_list/score_list/enable_score" - ) + self.assert_path(resp, "response/IIDX26music/cpu_score_list/score_list/enable_score") self.assert_path(resp, "response/IIDX26music/cpu_score_list/score_list/ghost") - self.assert_path( - resp, "response/IIDX26music/cpu_score_list/score_list/enable_ghost" - ) + self.assert_path(resp, "response/IIDX26music/cpu_score_list/score_list/enable_ghost") def verify_iidx26gamesystem_systeminfo(self, lid: str) -> None: call = self.call_node() @@ -713,32 +695,22 @@ class IIDXRootageClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx26pc_reg(ref_id, card, lid) self.verify_iidx26pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -829,9 +801,7 @@ class IIDXRootageClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -860,9 +830,7 @@ class IIDXRootageClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx26music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx26music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -967,9 +935,7 @@ class IIDXRootageClient(BaseClient): ) scores = self.verify_iidx26music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: diff --git a/bemani/client/iidx/sinobuz.py b/bemani/client/iidx/sinobuz.py index 117fa5a..ac527ce 100644 --- a/bemani/client/iidx/sinobuz.py +++ b/bemani/client/iidx/sinobuz.py @@ -92,9 +92,7 @@ class IIDXSinobuzClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 1001: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx24shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -176,9 +174,7 @@ class IIDXSinobuzClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX24shop") - def verify_iidx24pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx24pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -298,9 +294,7 @@ class IIDXSinobuzClient(BaseClient): "expert_point": expert_point, } - def verify_iidx24music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx24music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -322,9 +316,7 @@ class IIDXSinobuzClient(BaseClient): for child in resp.child("IIDX24music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -454,9 +446,7 @@ class IIDXSinobuzClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX24pc") - def verify_iidx24music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx24music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -485,9 +475,7 @@ class IIDXSinobuzClient(BaseClient): self.assert_path(resp, "response/IIDX24music/shopdata/@rank") self.assert_path(resp, "response/IIDX24music/ranklist/data") - def verify_iidx24music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx24music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -612,9 +600,7 @@ class IIDXSinobuzClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX24music") - def verify_iidx24grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx24grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -638,9 +624,7 @@ class IIDXSinobuzClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX24grade/@pnum") - def verify_iidx24ranking_entry( - self, iidxid: int, shop_name: str, coursetype: str - ) -> None: + def verify_iidx24ranking_entry(self, iidxid: int, shop_name: str, coursetype: str) -> None: call = self.call_node() # Construct node @@ -730,32 +714,22 @@ class IIDXSinobuzClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx24pc_reg(ref_id, card, lid) self.verify_iidx24pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -850,9 +824,7 @@ class IIDXSinobuzClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -881,9 +853,7 @@ class IIDXSinobuzClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx24music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx24music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -988,9 +958,7 @@ class IIDXSinobuzClient(BaseClient): ) scores = self.verify_iidx24music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: @@ -1011,12 +979,8 @@ class IIDXSinobuzClient(BaseClient): self.verify_iidx24ranking_classicentry(profile["extid"]) profile = self.verify_iidx24pc_get(ref_id, card, lid) for ptype in ["ir_data", "secret_course_data", "classic_course_data"]: - if profile[ptype] != { - 2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}} - }: - raise Exception( - f"Invalid data {profile[ptype]} returned on profile load for {ptype}!" - ) + if profile[ptype] != {2: {1: {"clear_status": 4, "pgnum": 1771, "gnum": 967}}}: + raise Exception(f"Invalid data {profile[ptype]} returned on profile load for {ptype}!") else: print("Skipping score checks for existing card") diff --git a/bemani/client/iidx/spada.py b/bemani/client/iidx/spada.py index b75536f..c70dbe8 100644 --- a/bemani/client/iidx/spada.py +++ b/bemani/client/iidx/spada.py @@ -92,9 +92,7 @@ class IIDXSpadaClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 101: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_iidx21shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -173,9 +171,7 @@ class IIDXSpadaClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/IIDX21shop") - def verify_iidx21pc_get( - self, ref_id: str, card_id: str, lid: str - ) -> Dict[str, Any]: + def verify_iidx21pc_get(self, ref_id: str, card_id: str, lid: str) -> Dict[str, Any]: call = self.call_node() # Construct node @@ -223,9 +219,7 @@ class IIDXSpadaClient(BaseClient): "deller": int(resp.child("IIDX21pc/deller").attribute("deller")), } - def verify_iidx21music_getrank( - self, extid: int - ) -> Dict[int, Dict[int, Dict[str, int]]]: + def verify_iidx21music_getrank(self, extid: int) -> Dict[int, Dict[int, Dict[str, int]]]: scores: Dict[int, Dict[int, Dict[str, int]]] = {} for cltype in [0, 1]: # singles, doubles call = self.call_node() @@ -247,9 +241,7 @@ class IIDXSpadaClient(BaseClient): for child in resp.child("IIDX21music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -374,9 +366,7 @@ class IIDXSpadaClient(BaseClient): resp = self.exchange("", call) self.assert_path(resp, "response/IIDX21pc") - def verify_iidx21music_reg( - self, extid: int, lid: str, score: Dict[str, Any] - ) -> None: + def verify_iidx21music_reg(self, extid: int, lid: str, score: Dict[str, Any]) -> None: call = self.call_node() # Construct node @@ -404,9 +394,7 @@ class IIDXSpadaClient(BaseClient): self.assert_path(resp, "response/IIDX21music/shopdata/@rank") self.assert_path(resp, "response/IIDX21music/ranklist/data") - def verify_iidx21music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_iidx21music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -526,9 +514,7 @@ class IIDXSpadaClient(BaseClient): # Verify nodes that cause crashes if they don't exist self.assert_path(resp, "response/IIDX21music") - def verify_iidx21grade_raised( - self, iidxid: int, shop_name: str, dantype: str - ) -> None: + def verify_iidx21grade_raised(self, iidxid: int, shop_name: str, dantype: str) -> None: call = self.call_node() # Construct node @@ -592,32 +578,22 @@ class IIDXSpadaClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_iidx21pc_reg(ref_id, card, lid) self.verify_iidx21pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -706,9 +682,7 @@ class IIDXSpadaClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -737,9 +711,7 @@ class IIDXSpadaClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_iidx21music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_iidx21music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -791,9 +763,7 @@ class IIDXSpadaClient(BaseClient): ) scores = self.verify_iidx21music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: diff --git a/bemani/client/iidx/tricoro.py b/bemani/client/iidx/tricoro.py index 2895334..7767cc1 100644 --- a/bemani/client/iidx/tricoro.py +++ b/bemani/client/iidx/tricoro.py @@ -89,9 +89,7 @@ class IIDXTricoroClient(BaseClient): raise Exception(f"Invalid node data {child} in clear rate response!") for v in child.value: if v < 0 or v > 101: - raise Exception( - f"Invalid clear percent {child} in clear rate response!" - ) + raise Exception(f"Invalid clear percent {child} in clear rate response!") def verify_shop_getconvention(self, lid: str) -> None: call = self.call_node() @@ -238,9 +236,7 @@ class IIDXTricoroClient(BaseClient): for child in resp.child("music").children: if child.name == "m": if child.value[0] != -1: - raise Exception( - "Got non-self score back when requesting only our scores!" - ) + raise Exception("Got non-self score back when requesting only our scores!") music_id = child.value[1] normal_clear_status = child.value[2] @@ -368,9 +364,7 @@ class IIDXTricoroClient(BaseClient): self.assert_path(resp, "response/music/shopdata/@rank") self.assert_path(resp, "response/music/ranklist/data") - def verify_music_appoint( - self, extid: int, musicid: int, chart: int - ) -> Tuple[int, bytes]: + def verify_music_appoint(self, extid: int, musicid: int, chart: int) -> Tuple[int, bytes]: call = self.call_node() # Construct node @@ -554,32 +548,22 @@ class IIDXTricoroClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_pc_reg(ref_id, card, lid) self.verify_pc_get(ref_id, card, lid) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -668,9 +652,7 @@ class IIDXTricoroClient(BaseClient): for score in dummyscores: data = scores.get(score["id"], {}).get(score["chart"], None) if data is None: - raise Exception( - f'Expected to get score back for song {score["id"]} chart {score["chart"]}!' - ) + raise Exception(f'Expected to get score back for song {score["id"]} chart {score["chart"]}!') if "expected_ex_score" in score: expected_score = score["expected_ex_score"] @@ -699,9 +681,7 @@ class IIDXTricoroClient(BaseClient): ) # Verify we can fetch our own ghost - ex_score, ghost = self.verify_music_appoint( - profile["extid"], score["id"], score["chart"] - ) + ex_score, ghost = self.verify_music_appoint(profile["extid"], score["id"], score["chart"]) if ex_score != expected_score: raise Exception( f'Expected a score of \'{expected_score}\' for song \'{score["id"]}\' chart \'{score["chart"]}\' but got score \'{data["ex_score"]}\'' @@ -753,9 +733,7 @@ class IIDXTricoroClient(BaseClient): ) scores = self.verify_music_getrank(profile["extid"]) if 1000 not in scores: - raise Exception( - f"Didn't get expected scores back for song {1000} beginner chart!" - ) + raise Exception(f"Didn't get expected scores back for song {1000} beginner chart!") if 6 not in scores[1000]: raise Exception(f"Didn't get beginner score back for song {1000}!") if scores[1000][6] != {"clear_status": 4, "ex_score": -1, "miss_count": -1}: diff --git a/bemani/client/jubeat/clan.py b/bemani/client/jubeat/clan.py index ebbbd70..0d7b7bd 100644 --- a/bemani/client/jubeat/clan.py +++ b/bemani/client/jubeat/clan.py @@ -53,24 +53,12 @@ class JubeatClanClient(BaseClient): self.assert_path(resp, "response/shopinfo/data/info/born/year") self.assert_path(resp, "response/shopinfo/data/info/collection/rating_s") self.assert_path(resp, "response/shopinfo/data/info/expert_option/is_available") - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/is_available" - ) - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/team/default_flag" - ) - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/team/redbelk_flag" - ) - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/team/cyanttle_flag" - ) - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/team/greenesia_flag" - ) - self.assert_path( - resp, "response/shopinfo/data/info/all_music_matching/team/plumpark_flag" - ) + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/is_available") + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/team/default_flag") + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/team/redbelk_flag") + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/team/cyanttle_flag") + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/team/greenesia_flag") + self.assert_path(resp, "response/shopinfo/data/info/all_music_matching/team/plumpark_flag") self.assert_path(resp, "response/shopinfo/data/info/question_list") self.assert_path(resp, "response/shopinfo/data/info/drop_list") self.assert_path(resp, "response/shopinfo/data/info/daily_bonus_list") @@ -138,24 +126,12 @@ class JubeatClanClient(BaseClient): self.assert_path(resp, "response/gametop/data/info/born/year") self.assert_path(resp, "response/gametop/data/info/collection/rating_s") self.assert_path(resp, "response/gametop/data/info/expert_option/is_available") - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/is_available" - ) - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/team/default_flag" - ) - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/team/redbelk_flag" - ) - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/team/cyanttle_flag" - ) - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/team/greenesia_flag" - ) - self.assert_path( - resp, "response/gametop/data/info/all_music_matching/team/plumpark_flag" - ) + self.assert_path(resp, "response/gametop/data/info/all_music_matching/is_available") + self.assert_path(resp, "response/gametop/data/info/all_music_matching/team/default_flag") + self.assert_path(resp, "response/gametop/data/info/all_music_matching/team/redbelk_flag") + self.assert_path(resp, "response/gametop/data/info/all_music_matching/team/cyanttle_flag") + self.assert_path(resp, "response/gametop/data/info/all_music_matching/team/greenesia_flag") + self.assert_path(resp, "response/gametop/data/info/all_music_matching/team/plumpark_flag") self.assert_path(resp, "response/gametop/data/info/question_list") self.assert_path(resp, "response/gametop/data/info/drop_list") self.assert_path(resp, "response/gametop/data/info/daily_bonus_list") @@ -234,19 +210,13 @@ class JubeatClanClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/lab_edit_seq") self.assert_path(resp, "response/gametop/data/player/event_info") self.assert_path(resp, "response/gametop/data/player/navi/flag") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/today/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/state") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/whim/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/state") self.assert_path(resp, "response/gametop/data/player/official_news/news_list") self.assert_path(resp, "response/gametop/data/player/rivallist") - self.assert_path( - resp, "response/gametop/data/player/free_first_play/is_available" - ) + self.assert_path(resp, "response/gametop/data/player/free_first_play/is_available") self.assert_path(resp, "response/gametop/data/player/jbox/point") self.assert_path(resp, "response/gametop/data/player/jbox/emblem/normal/index") self.assert_path(resp, "response/gametop/data/player/jbox/emblem/premium/index") @@ -255,9 +225,7 @@ class JubeatClanClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/born/status") self.assert_path(resp, "response/gametop/data/player/question_list") self.assert_path(resp, "response/gametop/data/player/jubility/@param") - self.assert_path( - resp, "response/gametop/data/player/jubility/target_music_list" - ) + self.assert_path(resp, "response/gametop/data/player/jubility/target_music_list") self.assert_path(resp, "response/gametop/data/player/team/@id") self.assert_path(resp, "response/gametop/data/player/team/section") self.assert_path(resp, "response/gametop/data/player/team/street") @@ -277,24 +245,12 @@ class JubeatClanClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/drop_list/drop/@id") self.assert_path(resp, "response/gametop/data/player/drop_list/drop/exp") self.assert_path(resp, "response/gametop/data/player/drop_list/drop/flag") - self.assert_path( - resp, "response/gametop/data/player/drop_list/drop/item_list/item/@id" - ) - self.assert_path( - resp, "response/gametop/data/player/drop_list/drop/item_list/item/num" - ) - self.assert_path( - resp, "response/gametop/data/player/fill_in_category/no_gray_flag_list" - ) - self.assert_path( - resp, "response/gametop/data/player/fill_in_category/all_yellow_flag_list" - ) - self.assert_path( - resp, "response/gametop/data/player/fill_in_category/full_combo_flag_list" - ) - self.assert_path( - resp, "response/gametop/data/player/fill_in_category/excellent_flag_list" - ) + self.assert_path(resp, "response/gametop/data/player/drop_list/drop/item_list/item/@id") + self.assert_path(resp, "response/gametop/data/player/drop_list/drop/item_list/item/num") + self.assert_path(resp, "response/gametop/data/player/fill_in_category/no_gray_flag_list") + self.assert_path(resp, "response/gametop/data/player/fill_in_category/all_yellow_flag_list") + self.assert_path(resp, "response/gametop/data/player/fill_in_category/full_combo_flag_list") + self.assert_path(resp, "response/gametop/data/player/fill_in_category/excellent_flag_list") self.assert_path(resp, "response/gametop/data/player/daily_bonus_list") self.assert_path(resp, "response/gametop/data/player/ticket_list") @@ -661,31 +617,21 @@ class JubeatClanClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/jubeat/festo.py b/bemani/client/jubeat/festo.py index c6de1d8..4c94a99 100644 --- a/bemani/client/jubeat/festo.py +++ b/bemani/client/jubeat/festo.py @@ -26,13 +26,9 @@ class JubeatFestoClient(BaseClient): self.assert_path(resp, f"response/{base}/data/info/jbox/emblem/premium/index") self.assert_path(resp, f"response/{base}/data/info/born/status") self.assert_path(resp, f"response/{base}/data/info/born/year") - self.assert_path( - resp, f"response/{base}/data/info/konami_logo_50th/is_available" - ) + self.assert_path(resp, f"response/{base}/data/info/konami_logo_50th/is_available") self.assert_path(resp, f"response/{base}/data/info/expert_option/is_available") - self.assert_path( - resp, f"response/{base}/data/info/all_music_matching/is_available" - ) + self.assert_path(resp, f"response/{base}/data/info/all_music_matching/is_available") self.assert_path(resp, f"response/{base}/data/info/department/shop_list") self.assert_path(resp, f"response/{base}/data/info/question_list") # Don't bother asserting on actual courses, this is highly specific. @@ -171,9 +167,7 @@ class JubeatFestoClient(BaseClient): data = Node.void("data") logger.add_child(data) data.add_child(Node.string("code", "pcbinfo_01")) - data.add_child( - Node.string("information", "u can literally put anything here lmao") - ) + data.add_child(Node.string("information", "u can literally put anything here lmao")) # Swap with server resp = self.exchange("", call) @@ -326,19 +320,13 @@ class JubeatFestoClient(BaseClient): # Required nodes for events and stuff self.assert_path(resp, "response/gametop/data/player/rivallist") self.assert_path(resp, "response/gametop/data/player/lab_edit_seq") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/today/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/state") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/whim/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/state") self.assert_path(resp, "response/gametop/data/player/official_news/news_list") self.assert_path(resp, "response/gametop/data/player/history/@count") - self.assert_path( - resp, "response/gametop/data/player/free_first_play/is_available" - ) + self.assert_path(resp, "response/gametop/data/player/free_first_play/is_available") self.assert_path(resp, "response/gametop/data/player/event_info") self.assert_path(resp, "response/gametop/data/player/jbox/point") self.assert_path(resp, "response/gametop/data/player/jbox/emblem/normal/index") @@ -369,9 +357,7 @@ class JubeatFestoClient(BaseClient): resp, "response/gametop/data/player/fill_in_category/normal/excellent_flag_list", ) - self.assert_path( - resp, "response/gametop/data/player/fill_in_category/hard/no_gray_flag_list" - ) + self.assert_path(resp, "response/gametop/data/player/fill_in_category/hard/no_gray_flag_list") self.assert_path( resp, "response/gametop/data/player/fill_in_category/hard/all_yellow_flag_list", @@ -783,31 +769,21 @@ class JubeatFestoClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/jubeat/prop.py b/bemani/client/jubeat/prop.py index 47b52af..4fc346c 100644 --- a/bemani/client/jubeat/prop.py +++ b/bemani/client/jubeat/prop.py @@ -41,16 +41,12 @@ class JubeatPropClient(BaseClient): self.assert_path(resp, "response/shopinfo/data/info/share_music") self.assert_path(resp, "response/shopinfo/data/info/bonus_music") self.assert_path(resp, "response/shopinfo/data/info/only_now_music") - self.assert_path( - resp, "response/shopinfo/data/info/fc_challenge/today/music_id" - ) + self.assert_path(resp, "response/shopinfo/data/info/fc_challenge/today/music_id") self.assert_path(resp, "response/shopinfo/data/info/white_music_list") self.assert_path(resp, "response/shopinfo/data/info/open_music_list") self.assert_path(resp, "response/shopinfo/data/info/cabinet_survey/id") self.assert_path(resp, "response/shopinfo/data/info/cabinet_survey/status") - self.assert_path( - resp, "response/shopinfo/data/info/kaitou_bisco/remaining_days" - ) + self.assert_path(resp, "response/shopinfo/data/info/kaitou_bisco/remaining_days") self.assert_path(resp, "response/shopinfo/data/info/league/status") self.assert_path(resp, "response/shopinfo/data/info/bistro/bistro_id") self.assert_path(resp, "response/shopinfo/data/info/jbox/point") @@ -165,27 +161,17 @@ class JubeatPropClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/cabinet_survey/read_flag") self.assert_path(resp, "response/gametop/data/player/kaitou_bisco/read_flag") self.assert_path(resp, "response/gametop/data/player/navi/flag") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/today/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/state") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/whim/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/state") self.assert_path(resp, "response/gametop/data/player/news/checked") self.assert_path(resp, "response/gametop/data/player/news/checked_flag") self.assert_path(resp, "response/gametop/data/player/rivallist") - self.assert_path( - resp, "response/gametop/data/player/free_first_play/is_available" - ) + self.assert_path(resp, "response/gametop/data/player/free_first_play/is_available") self.assert_path(resp, "response/gametop/data/player/free_first_play/point") - self.assert_path( - resp, "response/gametop/data/player/free_first_play/point_used" - ) - self.assert_path( - resp, "response/gametop/data/player/free_first_play/come_come_jbox/is_valid" - ) + self.assert_path(resp, "response/gametop/data/player/free_first_play/point_used") + self.assert_path(resp, "response/gametop/data/player/free_first_play/come_come_jbox/is_valid") self.assert_path( resp, "response/gametop/data/player/free_first_play/come_come_jbox/end_time_if_paired", @@ -201,17 +187,13 @@ class JubeatPropClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/league/class") self.assert_path(resp, "response/gametop/data/player/league/subclass") self.assert_path(resp, "response/gametop/data/player/new_music") - self.assert_path( - resp, "response/gametop/data/player/eapass_privilege/emblem_list" - ) + self.assert_path(resp, "response/gametop/data/player/eapass_privilege/emblem_list") self.assert_path(resp, "response/gametop/data/player/bonus_music/music") self.assert_path(resp, "response/gametop/data/player/bonus_music/event_id") self.assert_path(resp, "response/gametop/data/player/bonus_music/till_time") self.assert_path(resp, "response/gametop/data/player/bistro/chef/id") self.assert_path(resp, "response/gametop/data/player/bistro/carry_over") - self.assert_path( - resp, "response/gametop/data/player/bistro/route_list/route_count" - ) + self.assert_path(resp, "response/gametop/data/player/bistro/route_list/route_count") self.assert_path(resp, "response/gametop/data/player/bistro/extension") self.assert_path(resp, "response/gametop/data/player/gift_list") @@ -507,9 +489,7 @@ class JubeatPropClient(BaseClient): leagueid = resp.child_value("gametop/data/league_list/league/id") playernode = None - for player in resp.child( - "gametop/data/league_list/league/player_list" - ).children: + for player in resp.child("gametop/data/league_list/league/player_list").children: if player.child_value("jid") == jid: playernode = player break @@ -599,31 +579,21 @@ class JubeatPropClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -731,13 +701,9 @@ class JubeatPropClient(BaseClient): courses = self.verify_gametop_get_course(jid) league = self.verify_gametop_get_league(jid) if len(courses) > 0: - raise Exception( - "Got nonzero course count without playing any courses!" - ) + raise Exception("Got nonzero course count without playing any courses!") if league[1][0] != 0 or league[1][1] != 0 or league[1][2] != 0: - raise Exception( - "Got nonzero league count without playing any league!" - ) + raise Exception("Got nonzero league count without playing any league!") for score in dummyscores: newscore = scores[str(score["id"])][score["chart"]] @@ -808,14 +774,10 @@ class JubeatPropClient(BaseClient): for course in dummycourses: # Find the course - foundcourses = [ - c for c in courses if c["course_id"] == course["course_id"] - ] + foundcourses = [c for c in courses if c["course_id"] == course["course_id"]] if len(foundcourses) == 0: - raise Exception( - f"Didn't find course by ID {course['course_id']}" - ) + raise Exception(f"Didn't find course by ID {course['course_id']}") foundcourse = foundcourses[0] if "expected_rating" in course: @@ -846,33 +808,21 @@ class JubeatPropClient(BaseClient): time.sleep(1) # Play a league course, save the score - self.verify_gameend_regist( - ref_id, jid, [], {}, (league[0], (123456, 234567, 345678)) - ) + self.verify_gameend_regist(ref_id, jid, [], {}, (league[0], (123456, 234567, 345678))) jid = self.verify_gametop_get_pdata(card, ref_id) league = self.verify_gametop_get_league(jid) - if ( - league[1][0] != 123456 - or league[1][1] != 234567 - or league[1][2] != 345678 - ): + if league[1][0] != 123456 or league[1][1] != 234567 or league[1][2] != 345678: raise Exception( f"League score didn\t save! Got wrong values {league[1][0]}, {league[1][1]}, {league[1][2]} back!" ) # Play a league course, do worse, make sure it doesn't overwrite - self.verify_gameend_regist( - ref_id, jid, [], {}, (league[0], (12345, 23456, 34567)) - ) + self.verify_gameend_regist(ref_id, jid, [], {}, (league[0], (12345, 23456, 34567))) jid = self.verify_gametop_get_pdata(card, ref_id) league = self.verify_gametop_get_league(jid) - if ( - league[1][0] != 123456 - or league[1][1] != 234567 - or league[1][2] != 345678 - ): + if league[1][0] != 123456 or league[1][1] != 234567 or league[1][2] != 345678: raise Exception( f"League score got overwritten! Got wrong values {league[1][0]}, {league[1][1]}, {league[1][2]} back!" ) diff --git a/bemani/client/jubeat/qubell.py b/bemani/client/jubeat/qubell.py index 2509f3a..3f8e70f 100644 --- a/bemani/client/jubeat/qubell.py +++ b/bemani/client/jubeat/qubell.py @@ -160,20 +160,14 @@ class JubeatQubellClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/lab_edit_seq") self.assert_path(resp, "response/gametop/data/player/event_info") self.assert_path(resp, "response/gametop/data/player/navi/flag") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/today/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/today/state") - self.assert_path( - resp, "response/gametop/data/player/fc_challenge/whim/music_id" - ) + self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/music_id") self.assert_path(resp, "response/gametop/data/player/fc_challenge/whim/state") self.assert_path(resp, "response/gametop/data/player/news/checked") self.assert_path(resp, "response/gametop/data/player/news/checked_flag") self.assert_path(resp, "response/gametop/data/player/rivallist") - self.assert_path( - resp, "response/gametop/data/player/free_first_play/is_available" - ) + self.assert_path(resp, "response/gametop/data/player/free_first_play/is_available") self.assert_path(resp, "response/gametop/data/player/jbox/point") self.assert_path(resp, "response/gametop/data/player/jbox/emblem/normal/index") self.assert_path(resp, "response/gametop/data/player/jbox/emblem/premium/index") @@ -189,28 +183,14 @@ class JubeatQubellClient(BaseClient): self.assert_path(resp, "response/gametop/data/player/digdig/eternal/ratio") self.assert_path(resp, "response/gametop/data/player/digdig/eternal/used_point") self.assert_path(resp, "response/gametop/data/player/digdig/eternal/point") - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/excavated_point" - ) + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/excavated_point") self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/state") - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/item/kind" - ) - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/item/value" - ) - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/norma/till_time" - ) - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/norma/kind" - ) - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/norma/value" - ) - self.assert_path( - resp, "response/gametop/data/player/digdig/eternal/cube/norma/param" - ) + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/item/kind") + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/item/value") + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/norma/till_time") + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/norma/kind") + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/norma/value") + self.assert_path(resp, "response/gametop/data/player/digdig/eternal/cube/norma/param") # Return the jid return resp.child_value("gametop/data/player/jid") @@ -497,31 +477,21 @@ class JubeatQubellClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/jubeat/saucer.py b/bemani/client/jubeat/saucer.py index 8127959..73decd4 100644 --- a/bemani/client/jubeat/saucer.py +++ b/bemani/client/jubeat/saucer.py @@ -134,9 +134,7 @@ class JubeatSaucerClient(BaseClient): # Return the jid return resp.child_value("gametop/data/player/jid") - def verify_gameend_regist( - self, ref_id: str, jid: int, scores: List[Dict[str, Any]] - ) -> None: + def verify_gameend_regist(self, ref_id: str, jid: int, scores: List[Dict[str, Any]]) -> None: call = self.call_node() # Construct node @@ -378,31 +376,21 @@ class JubeatSaucerClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/jubeat/saucerfulfill.py b/bemani/client/jubeat/saucerfulfill.py index 297e8a9..a02a375 100644 --- a/bemani/client/jubeat/saucerfulfill.py +++ b/bemani/client/jubeat/saucerfulfill.py @@ -457,31 +457,21 @@ class JubeatSaucerFulfillClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_gametop_regist(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: @@ -583,9 +573,7 @@ class JubeatSaucerFulfillClient(BaseClient): scores = self.verify_gametop_get_mdata(jid) courses = self.verify_gametop_get_course(jid) if len(courses) > 0: - raise Exception( - "Got nonzero course count without playing any courses!" - ) + raise Exception("Got nonzero course count without playing any courses!") for score in dummyscores: newscore = scores[str(score["id"])][score["chart"]] @@ -656,14 +644,10 @@ class JubeatSaucerFulfillClient(BaseClient): for course in dummycourses: # Find the course - foundcourses = [ - c for c in courses if c["course_id"] == course["course_id"] - ] + foundcourses = [c for c in courses if c["course_id"] == course["course_id"]] if len(foundcourses) == 0: - raise Exception( - f"Didn't find course by ID {course['course_id']}" - ) + raise Exception(f"Didn't find course by ID {course['course_id']}") foundcourse = foundcourses[0] if "expected_rating" in course: diff --git a/bemani/client/mga/mga.py b/bemani/client/mga/mga.py index 994c8da..7702a5e 100644 --- a/bemani/client/mga/mga.py +++ b/bemani/client/mga/mga.py @@ -318,32 +318,22 @@ class MetalGearArcadeClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # MGA doesn't read a new profile, it just writes out CSV for a blank one self.verify_usergamedata_send(ref_id, msg_type="new") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/museca/museca1.py b/bemani/client/museca/museca1.py index 1dab0db..ddf13d0 100644 --- a/bemani/client/museca/museca1.py +++ b/bemani/client/museca/museca1.py @@ -165,9 +165,7 @@ class Museca1Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3/result") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, blaster_energy: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, blaster_energy: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -230,9 +228,7 @@ class Museca1Client(BaseClient): self.assert_path(resp, "response/game_3/music_limited") self.assert_path(resp, "response/game_3/event") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game_3") @@ -354,9 +350,7 @@ class Museca1Client(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game_3") @@ -428,17 +422,11 @@ class Museca1Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Museca doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -446,16 +434,12 @@ class Museca1Client(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify account freezing @@ -467,34 +451,24 @@ class Museca1Client(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") - self.verify_game_save( - location, ref_id, packet=123, block=234, blaster_energy=42 - ) + self.verify_game_save(location, ref_id, packet=123, block=234, blaster_energy=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") # Verify empty profile has no scores on it scores = self.verify_game_load_m(ref_id) @@ -567,17 +541,12 @@ class Museca1Client(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/museca/museca1plus.py b/bemani/client/museca/museca1plus.py index bd1b4a1..a0c60d3 100644 --- a/bemani/client/museca/museca1plus.py +++ b/bemani/client/museca/museca1plus.py @@ -165,9 +165,7 @@ class Museca1PlusClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3/result") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, blaster_energy: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, blaster_energy: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -230,9 +228,7 @@ class Museca1PlusClient(BaseClient): self.assert_path(resp, "response/game_3/music_limited") self.assert_path(resp, "response/game_3/event") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game_3") @@ -369,9 +365,7 @@ class Museca1PlusClient(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game_3") @@ -443,17 +437,11 @@ class Museca1PlusClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Museca doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -461,16 +449,12 @@ class Museca1PlusClient(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify account freezing @@ -485,34 +469,24 @@ class Museca1PlusClient(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") - self.verify_game_save( - location, ref_id, packet=123, block=234, blaster_energy=42 - ) + self.verify_game_save(location, ref_id, packet=123, block=234, blaster_energy=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") # Verify empty profile has no scores on it scores = self.verify_game_load_m(ref_id) @@ -585,17 +559,12 @@ class Museca1PlusClient(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/popn/eclale.py b/bemani/client/popn/eclale.py index 0cca4f2..a345ad6 100644 --- a/bemani/client/popn/eclale.py +++ b/bemani/client/popn/eclale.py @@ -118,9 +118,7 @@ class PopnMusicEclaleClient(BaseClient): self.assert_path(resp, "response/player23/stamp/stamp_id") self.assert_path(resp, "response/player23/stamp/cnt") - def verify_player23_read( - self, ref_id: str, msg_type: str - ) -> Dict[str, Dict[int, Dict[str, int]]]: + def verify_player23_read(self, ref_id: str, msg_type: str) -> Dict[str, Dict[int, Dict[str, int]]]: call = self.call_node() # Construct node @@ -139,9 +137,7 @@ class PopnMusicEclaleClient(BaseClient): self.assert_path(resp, "response/player23/result") status = resp.child_value("player23/result") if status != 2: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") return { "medals": {}, @@ -156,9 +152,7 @@ class PopnMusicEclaleClient(BaseClient): self.assert_path(resp, "response/player23/result") status = resp.child_value("player23/result") if status != 0: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") name = resp.child_value("player23/account/name") if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for Ref ID '{ref_id}'") @@ -192,9 +186,7 @@ class PopnMusicEclaleClient(BaseClient): else: raise Exception(f"Unrecognized message type '{msg_type}'") - def verify_player23_read_score( - self, ref_id: str - ) -> Dict[str, Dict[int, Dict[int, int]]]: + def verify_player23_read_score(self, ref_id: str) -> Dict[str, Dict[int, Dict[int, int]]]: call = self.call_node() # Construct node @@ -418,32 +410,22 @@ class PopnMusicEclaleClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_player23_read(ref_id, msg_type="new") self.verify_player23_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify proper handling of basic stuff @@ -489,9 +471,7 @@ class PopnMusicEclaleClient(BaseClient): raise Exception("Expecting to see chara ID 5 to have type 2 in characters!") # Verify purchases work - self.verify_player23_buy( - ref_id, item={"id": 6, "type": 7, "param": 8, "lumina": 400, "price": 250} - ) + self.verify_player23_buy(ref_id, item={"id": 6, "type": 7, "param": 8, "lumina": 400, "price": 250}) unlocks = self.verify_player23_read(ref_id, msg_type="query") if 6 not in unlocks["items"]: raise Exception("Expecting to see item ID 6 in items!") @@ -500,9 +480,7 @@ class PopnMusicEclaleClient(BaseClient): if unlocks["items"][6]["param"] != 8: raise Exception("Expecting to see item ID 6 to have param 8 in items!") if unlocks["lumina"][0]["lumina"] != 150: - raise Exception( - f'Got wrong value for lumina {unlocks["lumina"][0]["lumina"]} after purchase!' - ) + raise Exception(f'Got wrong value for lumina {unlocks["lumina"][0]["lumina"]} after purchase!') if cardid is None: # Verify score handling diff --git a/bemani/client/popn/fantasia.py b/bemani/client/popn/fantasia.py index 197a531..b1eb9b5 100644 --- a/bemani/client/popn/fantasia.py +++ b/bemani/client/popn/fantasia.py @@ -115,9 +115,7 @@ class PopnMusicFantasiaClient(BaseClient): if len(node.value) != length: raise Exception(f"Node '{name}' is wrong array length!") - def verify_playerdata_get( - self, ref_id: str, msg_type: str - ) -> Optional[Dict[str, Any]]: + def verify_playerdata_get(self, ref_id: str, msg_type: str) -> Optional[Dict[str, Any]]: call = self.call_node() # Construct node @@ -125,9 +123,7 @@ class PopnMusicFantasiaClient(BaseClient): call.add_child(playerdata) playerdata.set_attribute("method", "get") if msg_type == "new": - playerdata.set_attribute( - "model", self.config["old_profile_model"].split(":")[0] - ) + playerdata.set_attribute("model", self.config["old_profile_model"].split(":")[0]) playerdata.add_child(Node.string("ref_id", ref_id)) playerdata.add_child(Node.string("shop_name", "")) @@ -143,9 +139,7 @@ class PopnMusicFantasiaClient(BaseClient): status = int(resp.child("playerdata").attribute("status")) if status != 109: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") # No score data return None @@ -181,11 +175,7 @@ class PopnMusicFantasiaClient(BaseClient): ) medals = [ - transform_medals(medal) - for medal in resp.child("playerdata") - .child("base") - .child("clear_medal") - .value + transform_medals(medal) for medal in resp.child("playerdata").child("base").child("clear_medal").value ] hiscore = resp.child("playerdata").child("hiscore").value @@ -202,8 +192,7 @@ class PopnMusicFantasiaClient(BaseClient): hiscores.append(value & 0x1FFFF) scores = [ - (hiscores[x], hiscores[x + 1], hiscores[x + 2], hiscores[x + 3]) - for x in range(0, len(hiscores), 4) + (hiscores[x], hiscores[x + 1], hiscores[x + 2], hiscores[x + 3]) for x in range(0, len(hiscores), 4) ] return {"medals": medals, "scores": scores} @@ -240,9 +229,7 @@ class PopnMusicFantasiaClient(BaseClient): }[score["chart"]], ) ) - stage.add_child( - Node.u16("n_data", (score["medal"] << (4 * score["chart"]))) - ) + stage.add_child(Node.u16("n_data", (score["medal"] << (4 * score["chart"])))) stage.add_child(Node.u8("e_data", 0)) stage.add_child(Node.s32("score", score["score"])) stage.add_child(Node.u8("ojama_1", 0)) @@ -325,32 +312,22 @@ class PopnMusicFantasiaClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_playerdata_get(ref_id, msg_type="new") self.verify_playerdata_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/popn/kaimei.py b/bemani/client/popn/kaimei.py index 7c7ae5b..f983a10 100644 --- a/bemani/client/popn/kaimei.py +++ b/bemani/client/popn/kaimei.py @@ -136,9 +136,7 @@ class PopnMusicKaimeiClient(BaseClient): self.assert_path(resp, "response/player24/stamp/stamp_id") self.assert_path(resp, "response/player24/stamp/cnt") - def verify_player24_read( - self, ref_id: str, msg_type: str - ) -> Dict[str, Dict[int, Dict[str, int]]]: + def verify_player24_read(self, ref_id: str, msg_type: str) -> Dict[str, Dict[int, Dict[str, int]]]: call = self.call_node() # Construct node @@ -157,9 +155,7 @@ class PopnMusicKaimeiClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 2: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") return { "items": {}, @@ -173,9 +169,7 @@ class PopnMusicKaimeiClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 0: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") name = resp.child_value("player24/account/name") if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for Ref ID '{ref_id}'") @@ -207,16 +201,12 @@ class PopnMusicKaimeiClient(BaseClient): "items": items, "characters": charas, "courses": courses, - "points": { - 0: {"points": resp.child_value("player24/account/player_point")} - }, + "points": {0: {"points": resp.child_value("player24/account/player_point")}}, } else: raise Exception(f"Unrecognized message type '{msg_type}'") - def verify_player24_read_score( - self, ref_id: str - ) -> Dict[str, Dict[int, Dict[int, int]]]: + def verify_player24_read_score(self, ref_id: str) -> Dict[str, Dict[int, Dict[int, int]]]: call = self.call_node() # Construct node @@ -468,32 +458,22 @@ class PopnMusicKaimeiClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_player24_read(ref_id, msg_type="new") self.verify_player24_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify proper handling of basic stuff @@ -531,9 +511,7 @@ class PopnMusicKaimeiClient(BaseClient): if 5 not in unlocks["characters"]: raise Exception("Expecting to see chara ID 5 in characters!") if unlocks["characters"][5]["friendship"] != 420: - raise Exception( - "Expecting to see chara ID 5 to have type 2 in characters!" - ) + raise Exception("Expecting to see chara ID 5 to have type 2 in characters!") # Verify purchases work self.verify_player24_buy( @@ -548,9 +526,7 @@ class PopnMusicKaimeiClient(BaseClient): if unlocks["items"][6]["param"] != 8: raise Exception("Expecting to see item ID 6 to have param 8 in items!") if unlocks["points"][0]["points"] != 150: - raise Exception( - f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!' - ) + raise Exception(f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!') # Verify course handling self.verify_player24_update_ranking(ref_id, location) @@ -558,25 +534,15 @@ class PopnMusicKaimeiClient(BaseClient): if 12345 not in unlocks["courses"]: raise Exception("Expecting to see course ID 12345 in courses!") if unlocks["courses"][12345]["clear_type"] != 7: - raise Exception( - "Expecting to see item ID 12345 to have clear_type 7 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_type 7 in courses!") if unlocks["courses"][12345]["clear_rank"] != 5: - raise Exception( - "Expecting to see item ID 12345 to have clear_rank 5 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_rank 5 in courses!") if unlocks["courses"][12345]["total_score"] != 86000: - raise Exception( - "Expecting to see item ID 12345 to have total_score 86000 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have total_score 86000 in courses!") if unlocks["courses"][12345]["count"] != 1: - raise Exception( - "Expecting to see item ID 12345 to have count 1 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have count 1 in courses!") if unlocks["courses"][12345]["sheet_num"] != 2: - raise Exception( - "Expecting to see item ID 12345 to have sheet_num 2 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have sheet_num 2 in courses!") # Verify score handling scores = self.verify_player24_read_score(ref_id) diff --git a/bemani/client/popn/lapistoria.py b/bemani/client/popn/lapistoria.py index 94343eb..cd37781 100644 --- a/bemani/client/popn/lapistoria.py +++ b/bemani/client/popn/lapistoria.py @@ -49,9 +49,7 @@ class PopnMusicLapistoriaClient(BaseClient): if node.data_type != "void": raise Exception(f"Node '{name}' has wrong data type!") - def verify_player22_read( - self, ref_id: str, msg_type: str - ) -> Optional[Dict[str, Any]]: + def verify_player22_read(self, ref_id: str, msg_type: str) -> Optional[Dict[str, Any]]: call = self.call_node() # Construct node @@ -72,9 +70,7 @@ class PopnMusicLapistoriaClient(BaseClient): status = int(resp.child("player22").attribute("status")) if status != 109: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") # No score data return None @@ -287,32 +283,22 @@ class PopnMusicLapistoriaClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_player22_read(ref_id, msg_type="new") self.verify_player22_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/popn/peace.py b/bemani/client/popn/peace.py index 7fcdd86..0e66b62 100644 --- a/bemani/client/popn/peace.py +++ b/bemani/client/popn/peace.py @@ -136,9 +136,7 @@ class PopnMusicPeaceClient(BaseClient): self.assert_path(resp, "response/player24/stamp/stamp_id") self.assert_path(resp, "response/player24/stamp/cnt") - def verify_player24_read( - self, ref_id: str, msg_type: str - ) -> Dict[str, Dict[int, Dict[str, int]]]: + def verify_player24_read(self, ref_id: str, msg_type: str) -> Dict[str, Dict[int, Dict[str, int]]]: call = self.call_node() # Construct node @@ -157,9 +155,7 @@ class PopnMusicPeaceClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 2: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") return { "items": {}, @@ -173,9 +169,7 @@ class PopnMusicPeaceClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 0: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") name = resp.child_value("player24/account/name") if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for Ref ID '{ref_id}'") @@ -207,16 +201,12 @@ class PopnMusicPeaceClient(BaseClient): "items": items, "characters": charas, "courses": courses, - "points": { - 0: {"points": resp.child_value("player24/account/player_point")} - }, + "points": {0: {"points": resp.child_value("player24/account/player_point")}}, } else: raise Exception(f"Unrecognized message type '{msg_type}'") - def verify_player24_read_score( - self, ref_id: str - ) -> Dict[str, Dict[int, Dict[int, int]]]: + def verify_player24_read_score(self, ref_id: str) -> Dict[str, Dict[int, Dict[int, int]]]: call = self.call_node() # Construct node @@ -468,32 +458,22 @@ class PopnMusicPeaceClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_player24_read(ref_id, msg_type="new") self.verify_player24_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify proper handling of basic stuff @@ -531,9 +511,7 @@ class PopnMusicPeaceClient(BaseClient): if 5 not in unlocks["characters"]: raise Exception("Expecting to see chara ID 5 in characters!") if unlocks["characters"][5]["friendship"] != 420: - raise Exception( - "Expecting to see chara ID 5 to have type 2 in characters!" - ) + raise Exception("Expecting to see chara ID 5 to have type 2 in characters!") # Verify purchases work self.verify_player24_buy( @@ -548,9 +526,7 @@ class PopnMusicPeaceClient(BaseClient): if unlocks["items"][6]["param"] != 8: raise Exception("Expecting to see item ID 6 to have param 8 in items!") if unlocks["points"][0]["points"] != 150: - raise Exception( - f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!' - ) + raise Exception(f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!') # Verify course handling self.verify_player24_update_ranking(ref_id, location) @@ -558,25 +534,15 @@ class PopnMusicPeaceClient(BaseClient): if 12345 not in unlocks["courses"]: raise Exception("Expecting to see course ID 12345 in courses!") if unlocks["courses"][12345]["clear_type"] != 7: - raise Exception( - "Expecting to see item ID 12345 to have clear_type 7 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_type 7 in courses!") if unlocks["courses"][12345]["clear_rank"] != 5: - raise Exception( - "Expecting to see item ID 12345 to have clear_rank 5 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_rank 5 in courses!") if unlocks["courses"][12345]["total_score"] != 86000: - raise Exception( - "Expecting to see item ID 12345 to have total_score 86000 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have total_score 86000 in courses!") if unlocks["courses"][12345]["count"] != 1: - raise Exception( - "Expecting to see item ID 12345 to have count 1 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have count 1 in courses!") if unlocks["courses"][12345]["sheet_num"] != 2: - raise Exception( - "Expecting to see item ID 12345 to have sheet_num 2 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have sheet_num 2 in courses!") # Verify score handling scores = self.verify_player24_read_score(ref_id) diff --git a/bemani/client/popn/sunnypark.py b/bemani/client/popn/sunnypark.py index dee82c9..bab6776 100644 --- a/bemani/client/popn/sunnypark.py +++ b/bemani/client/popn/sunnypark.py @@ -80,9 +80,7 @@ class PopnMusicSunnyParkClient(BaseClient): if len(node.value) != 5: raise Exception(f"Node '{name}' is wrong array length!") - def verify_playerdata_get( - self, ref_id: str, msg_type: str - ) -> Optional[Dict[str, Any]]: + def verify_playerdata_get(self, ref_id: str, msg_type: str) -> Optional[Dict[str, Any]]: call = self.call_node() # Construct node @@ -90,9 +88,7 @@ class PopnMusicSunnyParkClient(BaseClient): call.add_child(playerdata) playerdata.set_attribute("method", "get") if msg_type == "new": - playerdata.set_attribute( - "model", self.config["old_profile_model"].split(":")[0] - ) + playerdata.set_attribute("model", self.config["old_profile_model"].split(":")[0]) playerdata.add_child(Node.string("ref_id", ref_id)) playerdata.add_child(Node.string("shop_name", "")) @@ -115,9 +111,7 @@ class PopnMusicSunnyParkClient(BaseClient): status = int(resp.child("playerdata").attribute("status")) if status != 109: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") # No score data return None @@ -149,11 +143,7 @@ class PopnMusicSunnyParkClient(BaseClient): ) medals = [ - transform_medals(medal) - for medal in resp.child("playerdata") - .child("base") - .child("clear_medal") - .value + transform_medals(medal) for medal in resp.child("playerdata").child("base").child("clear_medal").value ] hiscore = resp.child("playerdata").child("hiscore").value @@ -170,8 +160,7 @@ class PopnMusicSunnyParkClient(BaseClient): hiscores.append(value & 0x1FFFF) scores = [ - (hiscores[x], hiscores[x + 1], hiscores[x + 2], hiscores[x + 3]) - for x in range(0, len(hiscores), 4) + (hiscores[x], hiscores[x + 1], hiscores[x + 2], hiscores[x + 3]) for x in range(0, len(hiscores), 4) ] return {"medals": medals, "scores": scores} @@ -198,9 +187,7 @@ class PopnMusicSunnyParkClient(BaseClient): playerdata.add_child(stage) stage.add_child(Node.s16("no", score["id"])) stage.add_child(Node.u8("sheet", score["chart"])) - stage.add_child( - Node.u16("n_data", (score["medal"] << (4 * score["chart"]))) - ) + stage.add_child(Node.u16("n_data", (score["medal"] << (4 * score["chart"])))) stage.add_child(Node.s32("score", score["score"])) # Swap with server @@ -273,32 +260,22 @@ class PopnMusicSunnyParkClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_playerdata_get(ref_id, msg_type="new") self.verify_playerdata_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/popn/tunestreet.py b/bemani/client/popn/tunestreet.py index b3c03c7..c6d8b83 100644 --- a/bemani/client/popn/tunestreet.py +++ b/bemani/client/popn/tunestreet.py @@ -66,9 +66,7 @@ class PopnMusicTuneStreetClient(BaseClient): if name not in resp.child("game").attributes: raise Exception(f"Missing attribute '{name}' in response!") - def verify_playerdata_get( - self, ref_id: str, msg_type: str - ) -> Optional[Dict[str, Any]]: + def verify_playerdata_get(self, ref_id: str, msg_type: str) -> Optional[Dict[str, Any]]: call = self.call_node() # Construct node @@ -80,9 +78,7 @@ class PopnMusicTuneStreetClient(BaseClient): playerdata.set_attribute("ref_id", ref_id) if msg_type == "new": - playerdata.set_attribute( - "model", self.config["old_profile_model"].split(":")[0] - ) + playerdata.set_attribute("model", self.config["old_profile_model"].split(":")[0]) # Swap with server resp = self.exchange("pnm/playerdata", call) @@ -93,9 +89,7 @@ class PopnMusicTuneStreetClient(BaseClient): status = int(resp.child("playerdata").attribute("status")) if status != 109: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") # No score data return None @@ -105,20 +99,12 @@ class PopnMusicTuneStreetClient(BaseClient): self.assert_path(resp, "response/playerdata/hiscore") self.assert_path(resp, "response/playerdata/town") - name = ( - resp.child("playerdata") - .child("b") - .value[0:12] - .decode("SHIFT_JIS") - .replace("\x00", "") - ) + name = resp.child("playerdata").child("b").value[0:12].decode("SHIFT_JIS").replace("\x00", "") if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for Ref ID '{ref_id}'") medals = resp.child("playerdata").child("b").value[108:] - medals = [ - (medals[x] + (medals[x + 1] << 8)) for x in range(0, len(medals), 2) - ] + medals = [(medals[x] + (medals[x + 1] << 8)) for x in range(0, len(medals), 2)] # Extract and return score data def transform_medals(medal: int) -> Tuple[int, int, int, int]: @@ -273,32 +259,22 @@ class PopnMusicTuneStreetClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_playerdata_get(ref_id, msg_type="new") self.verify_playerdata_new(card, ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") if cardid is None: diff --git a/bemani/client/popn/usaneko.py b/bemani/client/popn/usaneko.py index 5be00db..534a4ab 100644 --- a/bemani/client/popn/usaneko.py +++ b/bemani/client/popn/usaneko.py @@ -136,9 +136,7 @@ class PopnMusicUsaNekoClient(BaseClient): self.assert_path(resp, "response/player24/stamp/stamp_id") self.assert_path(resp, "response/player24/stamp/cnt") - def verify_player24_read( - self, ref_id: str, msg_type: str - ) -> Dict[str, Dict[int, Dict[str, int]]]: + def verify_player24_read(self, ref_id: str, msg_type: str) -> Dict[str, Dict[int, Dict[str, int]]]: call = self.call_node() # Construct node @@ -157,9 +155,7 @@ class PopnMusicUsaNekoClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 2: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") return { "items": {}, @@ -173,9 +169,7 @@ class PopnMusicUsaNekoClient(BaseClient): self.assert_path(resp, "response/player24/result") status = resp.child_value("player24/result") if status != 0: - raise Exception( - f"Reference ID '{ref_id}' returned invalid status '{status}'" - ) + raise Exception(f"Reference ID '{ref_id}' returned invalid status '{status}'") name = resp.child_value("player24/account/name") if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for Ref ID '{ref_id}'") @@ -207,16 +201,12 @@ class PopnMusicUsaNekoClient(BaseClient): "items": items, "characters": charas, "courses": courses, - "points": { - 0: {"points": resp.child_value("player24/account/player_point")} - }, + "points": {0: {"points": resp.child_value("player24/account/player_point")}}, } else: raise Exception(f"Unrecognized message type '{msg_type}'") - def verify_player24_read_score( - self, ref_id: str - ) -> Dict[str, Dict[int, Dict[int, int]]]: + def verify_player24_read_score(self, ref_id: str) -> Dict[str, Dict[int, Dict[int, int]]]: call = self.call_node() # Construct node @@ -468,32 +458,22 @@ class PopnMusicUsaNekoClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") self.verify_player24_read(ref_id, msg_type="new") self.verify_player24_new(ref_id) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify proper handling of basic stuff @@ -531,9 +511,7 @@ class PopnMusicUsaNekoClient(BaseClient): if 5 not in unlocks["characters"]: raise Exception("Expecting to see chara ID 5 in characters!") if unlocks["characters"][5]["friendship"] != 420: - raise Exception( - "Expecting to see chara ID 5 to have type 2 in characters!" - ) + raise Exception("Expecting to see chara ID 5 to have type 2 in characters!") # Verify purchases work self.verify_player24_buy( @@ -548,9 +526,7 @@ class PopnMusicUsaNekoClient(BaseClient): if unlocks["items"][6]["param"] != 8: raise Exception("Expecting to see item ID 6 to have param 8 in items!") if unlocks["points"][0]["points"] != 150: - raise Exception( - f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!' - ) + raise Exception(f'Got wrong value for points {unlocks["points"][0]["points"]} after purchase!') # Verify course handling self.verify_player24_update_ranking(ref_id, location) @@ -558,25 +534,15 @@ class PopnMusicUsaNekoClient(BaseClient): if 12345 not in unlocks["courses"]: raise Exception("Expecting to see course ID 12345 in courses!") if unlocks["courses"][12345]["clear_type"] != 7: - raise Exception( - "Expecting to see item ID 12345 to have clear_type 7 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_type 7 in courses!") if unlocks["courses"][12345]["clear_rank"] != 5: - raise Exception( - "Expecting to see item ID 12345 to have clear_rank 5 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have clear_rank 5 in courses!") if unlocks["courses"][12345]["total_score"] != 86000: - raise Exception( - "Expecting to see item ID 12345 to have total_score 86000 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have total_score 86000 in courses!") if unlocks["courses"][12345]["count"] != 1: - raise Exception( - "Expecting to see item ID 12345 to have count 1 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have count 1 in courses!") if unlocks["courses"][12345]["sheet_num"] != 2: - raise Exception( - "Expecting to see item ID 12345 to have sheet_num 2 in courses!" - ) + raise Exception("Expecting to see item ID 12345 to have sheet_num 2 in courses!") # Verify score handling scores = self.verify_player24_read_score(ref_id) diff --git a/bemani/client/reflec/colette.py b/bemani/client/reflec/colette.py index f5a28f4..59862c1 100644 --- a/bemani/client/reflec/colette.py +++ b/bemani/client/reflec/colette.py @@ -182,9 +182,7 @@ class ReflecBeatColette(BaseClient): self.assert_path(resp, "response/player/pdata/record") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') scores = [] for child in resp.child("player/pdata/record").children: @@ -203,9 +201,7 @@ class ReflecBeatColette(BaseClient): scores.append(score) return scores - def verify_player_write( - self, refid: str, loc: str, scores: List[Dict[str, int]] - ) -> int: + def verify_player_write(self, refid: str, loc: str, scores: List[Dict[str, int]]) -> int: call = self.call_node() player = Node.void("player") @@ -471,9 +467,7 @@ class ReflecBeatColette(BaseClient): if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for comment!") if comment != "アメ〜〜!": - raise Exception( - f"Invalid comment '{comment}' returned for comment!" - ) + raise Exception(f"Invalid comment '{comment}' returned for comment!") found = True if not found: @@ -553,17 +547,11 @@ class ReflecBeatColette(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not self.verify_player_start(ref_id) @@ -586,16 +574,12 @@ class ReflecBeatColette(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -690,26 +674,19 @@ class ReflecBeatColette(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/reflec/groovin.py b/bemani/client/reflec/groovin.py index 604906d..f6adfa4 100644 --- a/bemani/client/reflec/groovin.py +++ b/bemani/client/reflec/groovin.py @@ -123,11 +123,7 @@ class ReflecBeatGroovinUpper(BaseClient): player.add_child(Node.u8_array("ga", [127, 0, 0, 1])) player.add_child(Node.u16("gp", 10573)) player.add_child(Node.u8_array("la", [16, 0, 0, 0])) - player.add_child( - Node.u8_array( - "pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60] - ) - ) + player.add_child(Node.u8_array("pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60])) call.add_child(player) @@ -293,13 +289,9 @@ class ReflecBeatGroovinUpper(BaseClient): self.assert_path(resp, "response/player/pdata/pue") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') - def verify_player_rb4readscore( - self, refid: str, location: str - ) -> List[Dict[str, int]]: + def verify_player_rb4readscore(self, refid: str, location: str) -> List[Dict[str, int]]: call = self.call_node() player = Node.void("player") @@ -347,9 +339,7 @@ class ReflecBeatGroovinUpper(BaseClient): continue if child.child_value("user_id") != extid: - raise Exception( - f'Invalid user ID returned {child.child_value("user_id")}' - ) + raise Exception(f'Invalid user ID returned {child.child_value("user_id")}') episode = { "id": child.child_value("type"), @@ -598,9 +588,7 @@ class ReflecBeatGroovinUpper(BaseClient): if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for comment!") if comment != "アメ〜〜!": - raise Exception( - f"Invalid comment '{comment}' returned for comment!" - ) + raise Exception(f"Invalid comment '{comment}' returned for comment!") found = True if not found: @@ -683,17 +671,11 @@ class ReflecBeatGroovinUpper(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not @@ -706,16 +688,12 @@ class ReflecBeatGroovinUpper(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -853,26 +831,19 @@ class ReflecBeatGroovinUpper(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/reflec/limelight.py b/bemani/client/reflec/limelight.py index 1ecbccc..ff45d9c 100644 --- a/bemani/client/reflec/limelight.py +++ b/bemani/client/reflec/limelight.py @@ -213,9 +213,7 @@ class ReflecBeatLimelight(BaseClient): self.assert_path(resp, "response/player/pdata/narrow_down/adv_param") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') scores = [] for child in resp.child("player/pdata/record").children: @@ -343,9 +341,7 @@ class ReflecBeatLimelight(BaseClient): return f'{thing["id"]}-{thing["chart"]}' updates = [key(score) for score in scores] - sortedrecords = { - key(record): record for record in records if key(record) in updates - } + sortedrecords = {key(record): record for record in records if key(record) in updates} # Now, see what records need updating and update them for score in scores: @@ -366,9 +362,7 @@ class ReflecBeatLimelight(BaseClient): "id": score["id"], "chart": score["chart"], "clear_type": max(record["clear_type"], score["clear_type"]), - "achievement_rate": max( - record["achievement_rate"], score["achievement_rate"] - ), + "achievement_rate": max(record["achievement_rate"], score["achievement_rate"]), "score": max(record["score"], score["score"]), "combo": max(record["combo"], score["combo"]), "miss_count": min(record["miss_count"], score["miss_count"]), @@ -443,9 +437,7 @@ class ReflecBeatLimelight(BaseClient): self.assert_path(resp, "response/player/time") return resp.child_value("player/uid") - def verify_log_play( - self, extid: int, loc: str, scores: List[Dict[str, int]] - ) -> None: + def verify_log_play(self, extid: int, loc: str, scores: List[Dict[str, int]]) -> None: call = self.call_node() log = Node.void("log") @@ -683,9 +675,7 @@ class ReflecBeatLimelight(BaseClient): if name != self.NAME: raise Exception(f"Invalid name '{name}' returned for comment!") if comment != "アメ〜〜!": - raise Exception( - f"Invalid comment '{comment}' returned for comment!" - ) + raise Exception(f"Invalid comment '{comment}' returned for comment!") found = True if not found: @@ -745,17 +735,11 @@ class ReflecBeatLimelight(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not self.verify_player_start(ref_id) @@ -769,16 +753,12 @@ class ReflecBeatLimelight(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -875,26 +855,19 @@ class ReflecBeatLimelight(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/reflec/reflec.py b/bemani/client/reflec/reflec.py index e2a5fb3..cb81cb5 100644 --- a/bemani/client/reflec/reflec.py +++ b/bemani/client/reflec/reflec.py @@ -155,9 +155,7 @@ class ReflecBeat(BaseClient): self.assert_path(resp, "response/player/pdata/cmnt") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') scores = [] for child in resp.child("player/pdata/record").children: @@ -224,9 +222,7 @@ class ReflecBeat(BaseClient): return f'{thing["id"]}-{thing["chart"]}' updates = [key(score) for score in scores] - sortedrecords = { - key(record): record for record in records if key(record) in updates - } + sortedrecords = {key(record): record for record in records if key(record) in updates} # Now, see what records need updating and update them for score in scores: @@ -247,9 +243,7 @@ class ReflecBeat(BaseClient): "id": score["id"], "chart": score["chart"], "clear_type": max(record["clear_type"], score["clear_type"]), - "achievement_rate": max( - record["achievement_rate"], score["achievement_rate"] - ), + "achievement_rate": max(record["achievement_rate"], score["achievement_rate"]), "score": max(record["score"], score["score"]), "combo": max(record["combo"], score["combo"]), "miss_count": min(record["miss_count"], score["miss_count"]), @@ -310,9 +304,7 @@ class ReflecBeat(BaseClient): self.assert_path(resp, "response/player/time") return resp.child_value("player/uid") - def verify_log_play( - self, extid: int, loc: str, scores: List[Dict[str, int]] - ) -> None: + def verify_log_play(self, extid: int, loc: str, scores: List[Dict[str, int]]) -> None: call = self.call_node() log = Node.void("log") @@ -468,17 +460,11 @@ class ReflecBeat(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not self.verify_player_start(ref_id) @@ -492,16 +478,12 @@ class ReflecBeat(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -593,26 +575,19 @@ class ReflecBeat(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/reflec/volzza.py b/bemani/client/reflec/volzza.py index 812e16a..c2087a3 100644 --- a/bemani/client/reflec/volzza.py +++ b/bemani/client/reflec/volzza.py @@ -121,11 +121,7 @@ class ReflecBeatVolzza(BaseClient): player.add_child(Node.u8_array("ga", [127, 0, 0, 1])) player.add_child(Node.u16("gp", 10573)) player.add_child(Node.u8_array("la", [16, 0, 0, 0])) - player.add_child( - Node.u8_array( - "pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60] - ) - ) + player.add_child(Node.u8_array("pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60])) call.add_child(player) @@ -246,9 +242,7 @@ class ReflecBeatVolzza(BaseClient): self.assert_path(resp, "response/player/ap") self.assert_path(resp, "response/player/uattr") - def verify_player_rb5_player_read( - self, refid: str, cardid: str, location: str - ) -> None: + def verify_player_rb5_player_read(self, refid: str, cardid: str, location: str) -> None: call = self.call_node() player = Node.void("player") @@ -303,13 +297,9 @@ class ReflecBeatVolzza(BaseClient): self.assert_path(resp, "response/player/pdata/mylist/list/mlst") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') - def verify_player_rb5_player_read_score( - self, refid: str, location: str - ) -> List[Dict[str, int]]: + def verify_player_rb5_player_read_score(self, refid: str, location: str) -> List[Dict[str, int]]: call = self.call_node() player = Node.void("player") @@ -581,17 +571,11 @@ class ReflecBeatVolzza(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not @@ -603,16 +587,12 @@ class ReflecBeatVolzza(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -699,35 +679,26 @@ class ReflecBeatVolzza(BaseClient): "expected_miss_count": 0, }, ] - self.verify_player_rb5_player_write( - ref_id, location, scores=dummyscores - ) + self.verify_player_rb5_player_write(ref_id, location, scores=dummyscores) self.verify_player_rb5_player_read(ref_id, card, location) scores = self.verify_player_rb5_player_read_score(ref_id, location) for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/reflec/volzza2.py b/bemani/client/reflec/volzza2.py index 8001c19..3db7e0b 100644 --- a/bemani/client/reflec/volzza2.py +++ b/bemani/client/reflec/volzza2.py @@ -122,11 +122,7 @@ class ReflecBeatVolzza2(BaseClient): player.add_child(Node.u8_array("ga", [127, 0, 0, 1])) player.add_child(Node.u16("gp", 10573)) player.add_child(Node.u8_array("la", [16, 0, 0, 0])) - player.add_child( - Node.u8_array( - "pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60] - ) - ) + player.add_child(Node.u8_array("pnid", [39, 16, 0, 0, 0, 23, 62, 60, 39, 127, 0, 0, 1, 23, 62, 60])) call.add_child(player) @@ -248,9 +244,7 @@ class ReflecBeatVolzza2(BaseClient): self.assert_path(resp, "response/player/ap") self.assert_path(resp, "response/player/uattr") - def verify_player_rb5_player_read( - self, refid: str, cardid: str, location: str - ) -> Dict[str, Any]: + def verify_player_rb5_player_read(self, refid: str, cardid: str, location: str) -> Dict[str, Any]: call = self.call_node() player = Node.void("player") @@ -310,9 +304,7 @@ class ReflecBeatVolzza2(BaseClient): self.assert_path(resp, "response/player/pdata/mycourse_f") if resp.child_value("player/pdata/base/name") != self.NAME: - raise Exception( - f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!' - ) + raise Exception(f'Invalid name {resp.child_value("player/pdata/base/name")} returned on profile read!') mycourse = [ { @@ -340,9 +332,7 @@ class ReflecBeatVolzza2(BaseClient): "mycourse": mycourse, } - def verify_player_rb5_player_read_score_5( - self, refid: str, location: str - ) -> List[Dict[str, int]]: + def verify_player_rb5_player_read_score_5(self, refid: str, location: str) -> List[Dict[str, int]]: call = self.call_node() player = Node.void("player") @@ -386,9 +376,7 @@ class ReflecBeatVolzza2(BaseClient): scores.append(score) return scores - def verify_player_rb5_player_read_score_old_5( - self, refid: str, location: str - ) -> List[Dict[str, int]]: + def verify_player_rb5_player_read_score_old_5(self, refid: str, location: str) -> List[Dict[str, int]]: call = self.call_node() player = Node.void("player") @@ -688,17 +676,11 @@ class ReflecBeatVolzza2(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Always get a player start, regardless of new profile or not @@ -710,16 +692,12 @@ class ReflecBeatVolzza2(BaseClient): ) else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify lobby functionality @@ -815,35 +793,26 @@ class ReflecBeatVolzza2(BaseClient): "expected_miss_count": 0, }, ] - self.verify_player_rb5_player_write_5( - ref_id, location, scores=dummyscores - ) + self.verify_player_rb5_player_write_5(ref_id, location, scores=dummyscores) self.verify_player_rb5_player_read(ref_id, card, location) scores = self.verify_player_rb5_player_read_score_5(ref_id, location) for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] else: expected_score = expected["score"] if "expected_achievement_rate" in expected: - expected_achievement_rate = expected[ - "expected_achievement_rate" - ] + expected_achievement_rate = expected["expected_achievement_rate"] else: expected_achievement_rate = expected["achievement_rate"] if "expected_clear_type" in expected: diff --git a/bemani/client/sdvx/booth.py b/bemani/client/sdvx/booth.py index a205930..e954b09 100644 --- a/bemani/client/sdvx/booth.py +++ b/bemani/client/sdvx/booth.py @@ -137,9 +137,7 @@ class SoundVoltexBoothClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game/@result") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, exp: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, exp: int) -> None: call = self.call_node() game = Node.void("game") @@ -239,9 +237,7 @@ class SoundVoltexBoothClient(BaseClient): if resp.child_value("game/result") == 0: raise Exception("Purchased when shouldn't have!") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game") @@ -386,9 +382,7 @@ class SoundVoltexBoothClient(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game") @@ -447,17 +441,11 @@ class SoundVoltexBoothClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # SDVX doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -465,16 +453,12 @@ class SoundVoltexBoothClient(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify account freezing @@ -490,9 +474,7 @@ class SoundVoltexBoothClient(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: @@ -506,9 +488,7 @@ class SoundVoltexBoothClient(BaseClient): self.verify_game_save(location, ref_id, packet=123, block=234, exp=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: @@ -519,9 +499,7 @@ class SoundVoltexBoothClient(BaseClient): self.verify_game_save(location, ref_id, packet=1, block=2, exp=3) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 236: @@ -533,9 +511,7 @@ class SoundVoltexBoothClient(BaseClient): self.verify_game_buy(ref_id, 1004, True) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 226: @@ -614,17 +590,12 @@ class SoundVoltexBoothClient(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/sdvx/gravitywars_s1.py b/bemani/client/sdvx/gravitywars_s1.py index c0f4e68..56ee4aa 100644 --- a/bemani/client/sdvx/gravitywars_s1.py +++ b/bemani/client/sdvx/gravitywars_s1.py @@ -150,9 +150,7 @@ class SoundVoltexGravityWarsS1Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3/result") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, blaster_energy: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, blaster_energy: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -288,9 +286,7 @@ class SoundVoltexGravityWarsS1Client(BaseClient): if resp.child_value("game_3/result") == 0: raise Exception("Purchased when shouldn't have!") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game_3") @@ -501,9 +497,7 @@ class SoundVoltexGravityWarsS1Client(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game_3") @@ -537,9 +531,7 @@ class SoundVoltexGravityWarsS1Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3") - def verify_game_save_c( - self, location: str, refid: str, season: int, course: int - ) -> None: + def verify_game_save_c(self, location: str, refid: str, season: int, course: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -596,17 +588,11 @@ class SoundVoltexGravityWarsS1Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # SDVX doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -614,16 +600,12 @@ class SoundVoltexGravityWarsS1Client(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify account freezing @@ -641,17 +623,13 @@ class SoundVoltexGravityWarsS1Client(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") if profile["items"]: raise Exception("Profile already has purchased items!") if profile["courses"]: @@ -660,22 +638,16 @@ class SoundVoltexGravityWarsS1Client(BaseClient): # Verify purchase failure, try buying song we can't afford self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, False) - self.verify_game_save( - location, ref_id, packet=123, block=234, blaster_energy=42 - ) + self.verify_game_save(location, ref_id, packet=123, block=234, blaster_energy=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 5 not in profile["items"]: raise Exception("Profile doesn't have user settings items in it!") if profile["courses"]: @@ -684,17 +656,13 @@ class SoundVoltexGravityWarsS1Client(BaseClient): self.verify_game_save(location, ref_id, packet=1, block=2, blaster_energy=3) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 236: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 5 not in profile["items"]: raise Exception("Profile doesn't have user settings items in it!") if profile["courses"]: @@ -704,17 +672,13 @@ class SoundVoltexGravityWarsS1Client(BaseClient): self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, True) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 226: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 0 not in profile["items"] or 29 not in profile["items"][0]: raise Exception("Purchase didn't add to profile!") if profile["items"][0][29] != 3: @@ -803,17 +767,12 @@ class SoundVoltexGravityWarsS1Client(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/sdvx/gravitywars_s2.py b/bemani/client/sdvx/gravitywars_s2.py index 8a2ca7f..17100d7 100644 --- a/bemani/client/sdvx/gravitywars_s2.py +++ b/bemani/client/sdvx/gravitywars_s2.py @@ -113,9 +113,7 @@ class SoundVoltexGravityWarsS2Client(BaseClient): setting.add_child(Node.string("time_service", "0,0,0")) setting.add_child(Node.string("service_value", "10,10,10")) setting.add_child(Node.string("service_limit", "10,10,10")) - setting.add_child( - Node.string("service_time", "07:00-11:00,07:00-11:00,07:00-11:00") - ) + setting.add_child(Node.string("service_time", "07:00-11:00,07:00-11:00,07:00-11:00")) # Swap with server resp = self.exchange("", call) @@ -157,9 +155,7 @@ class SoundVoltexGravityWarsS2Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3/result") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game_3") @@ -240,9 +236,7 @@ class SoundVoltexGravityWarsS2Client(BaseClient): else: raise Exception(f"Invalid game load type {msg_type}") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, blaster_energy: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, blaster_energy: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -511,9 +505,7 @@ class SoundVoltexGravityWarsS2Client(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game_3") @@ -562,9 +554,7 @@ class SoundVoltexGravityWarsS2Client(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_3") - def verify_game_save_c( - self, location: str, refid: str, season: int, course: int - ) -> None: + def verify_game_save_c(self, location: str, refid: str, season: int, course: int) -> None: call = self.call_node() game = Node.void("game_3") @@ -621,17 +611,11 @@ class SoundVoltexGravityWarsS2Client(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # SDVX doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -639,16 +623,12 @@ class SoundVoltexGravityWarsS2Client(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify rivals node (necessary to return but can hold nothing) @@ -669,17 +649,13 @@ class SoundVoltexGravityWarsS2Client(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") if profile["items"]: raise Exception("Profile already has purchased items!") if profile["courses"]: @@ -688,22 +664,16 @@ class SoundVoltexGravityWarsS2Client(BaseClient): # Verify purchase failure, try buying song we can't afford self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, False) - self.verify_game_save( - location, ref_id, packet=123, block=234, blaster_energy=42 - ) + self.verify_game_save(location, ref_id, packet=123, block=234, blaster_energy=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 5 not in profile["items"]: raise Exception("Profile doesn't have user settings items in it!") if profile["courses"]: @@ -712,17 +682,13 @@ class SoundVoltexGravityWarsS2Client(BaseClient): self.verify_game_save(location, ref_id, packet=1, block=2, blaster_energy=3) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 236: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 5 not in profile["items"]: raise Exception("Profile doesn't have user settings items in it!") if profile["courses"]: @@ -732,17 +698,13 @@ class SoundVoltexGravityWarsS2Client(BaseClient): self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, True) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 226: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 0 not in profile["items"] or 29 not in profile["items"][0]: raise Exception("Purchase didn't add to profile!") if profile["items"][0][29] != 3: @@ -831,17 +793,12 @@ class SoundVoltexGravityWarsS2Client(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/sdvx/heavenlyhaven.py b/bemani/client/sdvx/heavenlyhaven.py index 0d684df..4bd75be 100644 --- a/bemani/client/sdvx/heavenlyhaven.py +++ b/bemani/client/sdvx/heavenlyhaven.py @@ -127,9 +127,7 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): setting.add_child(Node.string("time_service", "0,0,0")) setting.add_child(Node.string("service_value", "10,10,10")) setting.add_child(Node.string("service_limit", "10,10,10")) - setting.add_child( - Node.string("service_time", "07:00-11:00,07:00-11:00,07:00-11:00") - ) + setting.add_child(Node.string("service_time", "07:00-11:00,07:00-11:00,07:00-11:00")) # Swap with server resp = self.exchange("", call) @@ -171,9 +169,7 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game/result") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game") @@ -268,9 +264,7 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): else: raise Exception(f"Invalid game load type {msg_type}") - def verify_game_save( - self, location: str, refid: str, packet: int, block: int, blaster_energy: int - ) -> None: + def verify_game_save(self, location: str, refid: str, packet: int, block: int, blaster_energy: int) -> None: call = self.call_node() game = Node.void("game") @@ -577,9 +571,7 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, play_id: int, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, play_id: int, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game") @@ -631,9 +623,7 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game") - def verify_game_save_c( - self, location: str, refid: str, play_id: int, season: int, course: int - ) -> None: + def verify_game_save_c(self, location: str, refid: str, play_id: int, season: int, course: int) -> None: call = self.call_node() game = Node.void("game") @@ -695,17 +685,11 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # SDVX doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -713,16 +697,12 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify rivals node (necessary to return but can hold nothing) @@ -742,17 +722,13 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") if profile["items"]: raise Exception("Profile already has purchased items!") if profile["courses"]: @@ -761,39 +737,29 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): # Verify purchase failure, try buying song we can't afford self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, False) - self.verify_game_save( - location, ref_id, packet=123, block=234, blaster_energy=42 - ) + self.verify_game_save(location, ref_id, packet=123, block=234, blaster_energy=42) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if profile["courses"]: raise Exception("Profile already has finished courses!") self.verify_game_save(location, ref_id, packet=1, block=2, blaster_energy=3) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 236: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if profile["courses"]: raise Exception("Profile has invalid finished courses!") @@ -801,17 +767,13 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, True) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 226: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 0 not in profile["items"] or 29 not in profile["items"][0]: raise Exception("Purchase didn't add to profile!") if profile["items"][0][29] != 3: @@ -904,17 +866,12 @@ class SoundVoltexHeavenlyHavenClient(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/client/sdvx/infiniteinfection.py b/bemani/client/sdvx/infiniteinfection.py index 5601f28..723569e 100644 --- a/bemani/client/sdvx/infiniteinfection.py +++ b/bemani/client/sdvx/infiniteinfection.py @@ -276,9 +276,7 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): if resp.child_value("game_2/result") == 0: raise Exception("Purchased when shouldn't have!") - def verify_game_load( - self, cardid: str, refid: str, msg_type: str - ) -> Dict[str, Any]: + def verify_game_load(self, cardid: str, refid: str, msg_type: str) -> Dict[str, Any]: call = self.call_node() game = Node.void("game_2") @@ -459,9 +457,7 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): return scores - def verify_game_save_m( - self, location: str, refid: str, score: Dict[str, int] - ) -> None: + def verify_game_save_m(self, location: str, refid: str, score: Dict[str, int]) -> None: call = self.call_node() game = Node.void("game_2") @@ -495,9 +491,7 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): # Verify that response is correct self.assert_path(resp, "response/game_2") - def verify_game_save_c( - self, location: str, refid: str, season: int, course: int - ) -> None: + def verify_game_save_c(self, location: str, refid: str, season: int, course: int) -> None: call = self.call_node() game = Node.void("game_2") @@ -554,17 +548,11 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): print(f"Generated random card ID {card} for use.") if cardid is None: - self.verify_cardmng_inquire( - card, msg_type="unregistered", paseli_enabled=paseli_enabled - ) + self.verify_cardmng_inquire(card, msg_type="unregistered", paseli_enabled=paseli_enabled) ref_id = self.verify_cardmng_getrefid(card) if len(ref_id) != 16: - raise Exception( - f"Invalid refid '{ref_id}' returned when registering card" - ) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="new", paseli_enabled=paseli_enabled - ): + raise Exception(f"Invalid refid '{ref_id}' returned when registering card") + if ref_id != self.verify_cardmng_inquire(card, msg_type="new", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # SDVX doesn't read the new profile, it asks for the profile itself after calling new self.verify_game_load(card, ref_id, msg_type="new") @@ -572,16 +560,12 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): self.verify_game_load(card, ref_id, msg_type="existing") else: print("Skipping new card checks for existing card") - ref_id = self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ) + ref_id = self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled) # Verify pin handling and return card handling self.verify_cardmng_authpass(ref_id, correct=True) self.verify_cardmng_authpass(ref_id, correct=False) - if ref_id != self.verify_cardmng_inquire( - card, msg_type="query", paseli_enabled=paseli_enabled - ): + if ref_id != self.verify_cardmng_inquire(card, msg_type="query", paseli_enabled=paseli_enabled): raise Exception(f"Invalid refid '{ref_id}' returned when querying card") # Verify account freezing @@ -597,17 +581,13 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): # Verify profile loading and saving profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 0: raise Exception("Profile has nonzero blocks associated with it!") if profile["block"] != 0: raise Exception("Profile has nonzero packets associated with it!") if profile["blaster_energy"] != 0: - raise Exception( - "Profile has nonzero blaster energy associated with it!" - ) + raise Exception("Profile has nonzero blaster energy associated with it!") if profile["items"]: raise Exception("Profile already has purchased items!") if profile["appealcards"]: @@ -628,17 +608,13 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): ) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 123: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 234: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 42: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if profile["items"]: raise Exception("Profile already has purchased items!") if profile["appealcards"]: @@ -646,22 +622,16 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): if profile["courses"]: raise Exception("Profile already has finished courses!") - self.verify_game_save( - location, ref_id, packet=1, block=2, blaster_energy=3, appealcards=[] - ) + self.verify_game_save(location, ref_id, packet=1, block=2, blaster_energy=3, appealcards=[]) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 236: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if profile["items"]: raise Exception("Profile has invalid purchased items!") if profile["appealcards"]: @@ -673,17 +643,13 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): self.verify_game_buy(ref_id, 0, 29, 1, 10, 0, 29, 3, True) profile = self.verify_game_load(card, ref_id, msg_type="existing") if profile["name"] != self.NAME: - raise Exception( - f'Profile has incorrect name {profile["name"]} associated with it!' - ) + raise Exception(f'Profile has incorrect name {profile["name"]} associated with it!') if profile["packet"] != 124: raise Exception("Profile has invalid blocks associated with it!") if profile["block"] != 226: raise Exception("Profile has invalid packets associated with it!") if profile["blaster_energy"] != 45: - raise Exception( - "Profile has invalid blaster energy associated with it!" - ) + raise Exception("Profile has invalid blaster energy associated with it!") if 0 not in profile["items"] or 29 not in profile["items"][0]: raise Exception("Purchase didn't add to profile!") if profile["items"][0][29] != 3: @@ -790,17 +756,12 @@ class SoundVoltexInfiniteInfectionClient(BaseClient): for expected in dummyscores: actual = None for received in scores: - if ( - received["id"] == expected["id"] - and received["chart"] == expected["chart"] - ): + if received["id"] == expected["id"] and received["chart"] == expected["chart"]: actual = received break if actual is None: - raise Exception( - f"Didn't find song {expected['id']} chart {expected['chart']} in response!" - ) + raise Exception(f"Didn't find song {expected['id']} chart {expected['chart']} in response!") if "expected_score" in expected: expected_score = expected["expected_score"] diff --git a/bemani/common/aes.py b/bemani/common/aes.py index bf29764..bcff3f0 100644 --- a/bemani/common/aes.py +++ b/bemani/common/aes.py @@ -29,9 +29,7 @@ class AESCipher: random = Random.new() iv = random.read(AES.block_size) cipher = AES.new(self.__key, AES.MODE_CBC, iv) - return base64.b64encode( - iv + cipher.encrypt(raw.encode("utf-8")), altchars=b"._" - ).decode("utf-8") + return base64.b64encode(iv + cipher.encrypt(raw.encode("utf-8")), altchars=b"._").decode("utf-8") def decrypt(self, encoded: str) -> str: enc = base64.b64decode(encoded.encode("utf-8"), altchars=b"._") diff --git a/bemani/common/http.py b/bemani/common/http.py index 3b5a883..a020bde 100644 --- a/bemani/common/http.py +++ b/bemani/common/http.py @@ -3,9 +3,7 @@ from typing import Any, Dict, List, Optional, Tuple class HTTP: @staticmethod - def parse( - data: bytes, request: bool = False, response: bool = False - ) -> Optional[Dict[str, Any]]: + def parse(data: bytes, request: bool = False, response: bool = False) -> Optional[Dict[str, Any]]: """ A very lazy and hastily coded HTTP parser. @@ -64,9 +62,7 @@ class HTTP: if "content-length" in headers: data = data[: int(headers["content-length"])] valid = len(data) == int(headers["content-length"]) - elif ( - "transfer-encoding" in headers and headers["transfer-encoding"] == "chunked" - ): + elif "transfer-encoding" in headers and headers["transfer-encoding"] == "chunked": real_data = b"" while True: @@ -139,13 +135,9 @@ class HTTP: # Add first part of header if request: - out.append( - f'{parsed_headers["method"]} {parsed_headers["uri"]} {parsed_headers["version"]}' - ) + out.append(f'{parsed_headers["method"]} {parsed_headers["uri"]} {parsed_headers["version"]}') elif response: - out.append( - f'{parsed_headers["version"]} {parsed_headers["code"]} {parsed_headers["error"]}' - ) + out.append(f'{parsed_headers["version"]} {parsed_headers["code"]} {parsed_headers["error"]}') else: raise Exception("Logic error!") diff --git a/bemani/common/id.py b/bemani/common/id.py index 454094f..5af1c6a 100644 --- a/bemani/common/id.py +++ b/bemani/common/id.py @@ -68,8 +68,7 @@ class ID: """ try: if ( - machine_id[:2] - in {"JP", "KR", "TW", "HK", "US", "GB", "IT", "ES", "FR", "PT", "XX"} + machine_id[:2] in {"JP", "KR", "TW", "HK", "US", "GB", "IT", "ES", "FR", "PT", "XX"} and machine_id[2] == "-" ): return int(machine_id[3:]) diff --git a/bemani/common/model.py b/bemani/common/model.py index c4e2c14..3c4a227 100644 --- a/bemani/common/model.py +++ b/bemani/common/model.py @@ -6,9 +6,7 @@ class Model: Object representing a parsed Model String. """ - def __init__( - self, gamecode: str, dest: str, spec: str, rev: str, version: Optional[int] - ) -> None: + def __init__(self, gamecode: str, dest: str, spec: str, rev: str, version: Optional[int]) -> None: """ Initialize a Model object. diff --git a/bemani/common/parallel.py b/bemani/common/parallel.py index 122f81b..20caaed 100644 --- a/bemani/common/parallel.py +++ b/bemani/common/parallel.py @@ -20,12 +20,8 @@ class Parallel: if len(lambdas) == 0: return [] - with concurrent.futures.ThreadPoolExecutor( - max_workers=len(lambdas) - ) as executor: - futures = { - executor.submit(lambdas[pos]): pos for pos in range(len(lambdas)) - } + with concurrent.futures.ThreadPoolExecutor(max_workers=len(lambdas)) as executor: + futures = {executor.submit(lambdas[pos]): pos for pos in range(len(lambdas))} results = [] # List: Tuple[Any, int] for future in concurrent.futures.as_completed(futures): @@ -46,9 +42,7 @@ class Parallel: if len(params) == 0: return [] with concurrent.futures.ThreadPoolExecutor(max_workers=len(params)) as executor: - futures = { - executor.submit(lam, params[pos]): pos for pos in range(len(params)) - } + futures = {executor.submit(lam, params[pos]): pos for pos in range(len(params))} results = [] # List: Tuple[Any, int] for future in concurrent.futures.as_completed(futures): @@ -69,13 +63,8 @@ class Parallel: if len(lambdas) == 0: return [] - with concurrent.futures.ThreadPoolExecutor( - max_workers=len(lambdas) - ) as executor: - futures = { - executor.submit(lambdas[pos], *params): pos - for pos in range(len(lambdas)) - } + with concurrent.futures.ThreadPoolExecutor(max_workers=len(lambdas)) as executor: + futures = {executor.submit(lambdas[pos], *params): pos for pos in range(len(lambdas))} results = [] # List: Tuple[Any, int] for future in concurrent.futures.as_completed(futures): diff --git a/bemani/common/pe.py b/bemani/common/pe.py index f702ad3..f81b53e 100644 --- a/bemani/common/pe.py +++ b/bemani/common/pe.py @@ -34,9 +34,7 @@ class Memory: else: # Attempt to return the default. for virtual_start in self.defaults: - if i >= virtual_start and i < ( - virtual_start + len(self.defaults[virtual_start]) - ): + if i >= virtual_start and i < (virtual_start + len(self.defaults[virtual_start])): data.append(self.defaults[virtual_start][i - virtual_start]) break else: @@ -101,9 +99,7 @@ class PEFile: if offset == virtual: return physical - raise InvalidVirtualOffsetException( - f"Couldn't find physical offset for virtual offset 0x{offset:08x}" - ) + raise InvalidVirtualOffsetException(f"Couldn't find physical offset for virtual offset 0x{offset:08x}") def physical_to_virtual(self, offset: int) -> int: for section in self.__pe.sections: @@ -111,19 +107,13 @@ class PEFile: end = start + section.SizeOfRawData if offset >= start and offset < end: - return ( - (offset - start) - + section.VirtualAddress - + self.__pe.OPTIONAL_HEADER.ImageBase - ) + return (offset - start) + section.VirtualAddress + self.__pe.OPTIONAL_HEADER.ImageBase for virtual, physical in self.__adhoc_mapping.items(): if offset == physical: return virtual - raise InvalidPhysicalOffsetException( - f"Couldn't find virtual offset for physical offset 0x{offset:08x}" - ) + raise InvalidPhysicalOffsetException(f"Couldn't find virtual offset for physical offset 0x{offset:08x}") def is_virtual(self, offset: int) -> bool: return offset >= self.__pe.OPTIONAL_HEADER.ImageBase @@ -259,9 +249,7 @@ class PEFile: while loc < len(chunk): inst = chunk[loc] loc = loc + 1 - mnemonic = formatter.format_mnemonic( - inst, FormatMnemonicOptions.NO_PREFIXES - ) + mnemonic = formatter.format_mnemonic(inst, FormatMnemonicOptions.NO_PREFIXES) if mnemonic == "mov": dest = formatter.format_operand(inst, 0) @@ -271,9 +259,7 @@ class PEFile: size = get_size(src) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") result = fetch(registers, memory, size, src) assign(registers, memory, size, dest, result) @@ -286,9 +272,7 @@ class PEFile: srcsize = get_size(src) dstsize = get_size(dest) if srcsize is None or dstsize is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") result = fetch(registers, memory, srcsize, src) assign(registers, memory, dstsize, dest, result) @@ -300,9 +284,7 @@ class PEFile: size = get_size(amt) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") # Special case for adjusting ESP, to make sure our memory contains zeros for reading # out the stack later. @@ -312,9 +294,7 @@ class PEFile: memory.init(min(before, after), max(before, after)) assign(registers, memory, size, dest, after) else: - result = fetch(registers, memory, size, dest) + fetch( - registers, memory, size, amt - ) + result = fetch(registers, memory, size, dest) + fetch(registers, memory, size, amt) assign(registers, memory, size, dest, result) elif mnemonic == "sub": @@ -325,9 +305,7 @@ class PEFile: size = get_size(amt) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") # Special case for adjusting ESP, to make sure our memory contains zeros for reading # out the stack later. @@ -337,9 +315,7 @@ class PEFile: memory.init(min(before, after), max(before, after)) assign(registers, memory, size, dest, after) else: - result = fetch(registers, memory, size, dest) - fetch( - registers, memory, size, amt - ) + result = fetch(registers, memory, size, dest) - fetch(registers, memory, size, amt) assign(registers, memory, size, dest, result) elif mnemonic == "imul": @@ -352,19 +328,11 @@ class PEFile: const = None vprint(f"imul {dest}, {mult}") - size = ( - get_size(mult) - or get_size(dest) - or (get_size(const) if const is not None else None) - ) + size = get_size(mult) or get_size(dest) or (get_size(const) if const is not None else None) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") if const is None: - result = fetch(registers, memory, size, dest) * fetch( - registers, memory, size, mult - ) + result = fetch(registers, memory, size, dest) * fetch(registers, memory, size, mult) else: result = fetch(registers, memory, size, mult) * get_value(const) assign(registers, memory, size, dest, result) @@ -376,9 +344,7 @@ class PEFile: size = get_size(src) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") result = fetch(registers, memory, size, src) registers.rsp -= size assign( @@ -396,12 +362,8 @@ class PEFile: size = get_size(src) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) - result = fetch( - registers, memory, size, "[rsp]" if self.is_64bit() else "[esp]" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") + result = fetch(registers, memory, size, "[rsp]" if self.is_64bit() else "[esp]") assign(registers, memory, size, dest, result) registers.rsp += size @@ -413,12 +375,8 @@ class PEFile: size = get_size(op1) or get_size(op2) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) - result = fetch(registers, memory, size, op1) & fetch( - registers, memory, size, op2 - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") + result = fetch(registers, memory, size, op1) & fetch(registers, memory, size, op2) registers.zf = result == 0 if size == 1: @@ -492,12 +450,8 @@ class PEFile: size = get_size(src) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) - result = fetch(registers, memory, size, dest) & fetch( - registers, memory, size, src - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") + result = fetch(registers, memory, size, dest) & fetch(registers, memory, size, src) assign(registers, memory, size, dest, result) elif mnemonic == "or": @@ -508,12 +462,8 @@ class PEFile: size = get_size(src) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) - result = fetch(registers, memory, size, dest) | fetch( - registers, memory, size, src - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") + result = fetch(registers, memory, size, dest) | fetch(registers, memory, size, src) assign(registers, memory, size, dest, result) elif mnemonic == "xor": @@ -524,12 +474,8 @@ class PEFile: size = get_size(src) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) - result = fetch(registers, memory, size, dest) ^ fetch( - registers, memory, size, src - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") + result = fetch(registers, memory, size, dest) ^ fetch(registers, memory, size, src) assign(registers, memory, size, dest, result) elif mnemonic == "lea": @@ -540,22 +486,16 @@ class PEFile: size = get_size(src) or get_size(dest) if size is None: - raise Exception( - f"Could not determine size of {mnemonic} operation!" - ) + raise Exception(f"Could not determine size of {mnemonic} operation!") result = get_address(registers, src) if result is None: - raise Exception( - f"Could not compute effective address for {mnemonic} operation!" - ) + raise Exception(f"Could not compute effective address for {mnemonic} operation!") assign(registers, memory, size, dest, result) elif mnemonic == "ret": vprint("ret") - raise RetException( - "Encountered {mnemonic} instruction but we aren't in function context!" - ) + raise RetException("Encountered {mnemonic} instruction but we aren't in function context!") else: raise Exception(f"Unsupported mnemonic {mnemonic}!") @@ -732,9 +672,7 @@ def get_size(operand: str) -> Optional[int]: return None -def assign( - registers: Registers, memory: Memory, size: int, loc: str, value: int -) -> None: +def assign(registers: Registers, memory: Memory, size: int, loc: str, value: int) -> None: """ Given the registers and memory of our emulator, the size of the operation performed, the location to assign to and the value we should assign, diff --git a/bemani/common/time.py b/bemani/common/time.py index be5d317..f30178b 100644 --- a/bemani/common/time.py +++ b/bemani/common/time.py @@ -31,9 +31,7 @@ class Time: Returns the unix timestamp for the end of today in UTC timezone. """ now = datetime.datetime.utcnow().date() - beginning_of_day = datetime.datetime( - now.year, now.month, now.day, tzinfo=tz.tzutc() - ) + beginning_of_day = datetime.datetime(now.year, now.month, now.day, tzinfo=tz.tzutc()) end_of_day = beginning_of_day + datetime.timedelta(days=1) return calendar.timegm(end_of_day.timetuple()) @@ -43,9 +41,7 @@ class Time: Returns the unix timestamp for the beginning of today in UTC timezone. """ now = datetime.datetime.utcnow().date() - beginning_of_day = datetime.datetime( - now.year, now.month, now.day, tzinfo=tz.tzutc() - ) + beginning_of_day = datetime.datetime(now.year, now.month, now.day, tzinfo=tz.tzutc()) return calendar.timegm(beginning_of_day.timetuple()) @staticmethod diff --git a/bemani/common/validateddict.py b/bemani/common/validateddict.py index 17ba855..cc2ba8a 100644 --- a/bemani/common/validateddict.py +++ b/bemani/common/validateddict.py @@ -120,9 +120,7 @@ class ValidatedDict(dict): return default return val - def get_int_array( - self, name: str, length: int, default: Optional[List[int]] = None - ) -> List[int]: + def get_int_array(self, name: str, length: int, default: Optional[List[int]] = None) -> List[int]: """ Given the name of a value, return a list of integers stored under that name. @@ -152,9 +150,7 @@ class ValidatedDict(dict): return default return val - def get_bool_array( - self, name: str, length: int, default: Optional[List[bool]] = None - ) -> List[bool]: + def get_bool_array(self, name: str, length: int, default: Optional[List[bool]] = None) -> List[bool]: """ Given the name of a value, return a list of booleans stored under that name. @@ -184,9 +180,7 @@ class ValidatedDict(dict): return default return val - def get_bytes_array( - self, name: str, length: int, default: Optional[List[bytes]] = None - ) -> List[bytes]: + def get_bytes_array(self, name: str, length: int, default: Optional[List[bytes]] = None) -> List[bytes]: """ Given the name of a value, return a list of bytestrings stored under that name. @@ -216,9 +210,7 @@ class ValidatedDict(dict): return default return val - def get_str_array( - self, name: str, length: int, default: Optional[List[str]] = None - ) -> List[str]: + def get_str_array(self, name: str, length: int, default: Optional[List[str]] = None) -> List[str]: """ Given the name of a value, return a list of strings stored under that name. @@ -248,9 +240,7 @@ class ValidatedDict(dict): return default return val - def get_dict( - self, name: str, default: Optional[Dict[Any, Any]] = None - ) -> "ValidatedDict": + def get_dict(self, name: str, default: Optional[Dict[Any, Any]] = None) -> "ValidatedDict": """ Given the name of a value, return a dictionary stored under that name. @@ -477,9 +467,7 @@ class Profile(ValidatedDict): self.extid = extid def clone(self) -> "Profile": - return Profile( - self.game, self.version, self.refid, self.extid, copy.deepcopy(self) - ) + return Profile(self.game, self.version, self.refid, self.extid, copy.deepcopy(self)) class PlayStatistics(ValidatedDict): diff --git a/bemani/data/api/base.py b/bemani/data/api/base.py index 37ba452..7ad7992 100644 --- a/bemani/data/api/base.py +++ b/bemani/data/api/base.py @@ -14,10 +14,7 @@ class BaseGlobalData: if self.__apiclients is None: servers = self.__localapi.get_all_servers() self.__apiclients = [ - APIClient( - server.uri, server.token, server.allow_stats, server.allow_scores - ) - for server in servers + APIClient(server.uri, server.token, server.allow_stats, server.allow_scores) for server in servers ] return self.__apiclients diff --git a/bemani/data/api/client.py b/bemani/data/api/client.py index a33bb11..bbb1423 100644 --- a/bemani/data/api/client.py +++ b/bemani/data/api/client.py @@ -45,9 +45,7 @@ class APIClient: API_VERSION: Final[str] = "v1" - def __init__( - self, base_uri: str, token: str, allow_stats: bool, allow_scores: bool - ) -> None: + def __init__(self, base_uri: str, token: str, allow_stats: bool, allow_scores: bool) -> None: self.base_uri = base_uri self.token = token self.allow_stats = allow_stats @@ -82,9 +80,7 @@ class APIClient: return True return False - def __exchange_data( - self, request_uri: str, request_args: Dict[str, Any] - ) -> Dict[str, Any]: + def __exchange_data(self, request_uri: str, request_args: Dict[str, Any]) -> Dict[str, Any]: if self.base_uri[-1:] != "/": uri = f"{self.base_uri}/{request_uri}" else: @@ -110,9 +106,7 @@ class APIClient: # Verify that content type is in the form of "application/json; charset=utf-8". if not self._content_type_valid(r.headers["content-type"]): - raise APIException( - f'API returned invalid content type \'{r.headers["content-type"]}\'!' - ) + raise APIException(f'API returned invalid content type \'{r.headers["content-type"]}\'!') jsondata = r.json() @@ -126,28 +120,18 @@ class APIClient: error = jsondata["error"] if r.status_code == 401: - raise NotAuthorizedAPIException( - "The API token used is not authorized against this server!" - ) + raise NotAuthorizedAPIException("The API token used is not authorized against this server!") if r.status_code == 404: - raise UnsupportedRequestAPIException( - "The server does not support this game/version or request object!" - ) + raise UnsupportedRequestAPIException("The server does not support this game/version or request object!") if r.status_code == 405: - raise UnrecognizedRequestAPIException( - "The server did not recognize the request!" - ) + raise UnrecognizedRequestAPIException("The server did not recognize the request!") if r.status_code == 500: raise RemoteServerErrorAPIException( f"The server had an error processing the request and returned '{error}'" ) if r.status_code == 501: - raise UnsupportedVersionAPIException( - "The server does not support this version of the API!" - ) - raise APIException( - "The server returned an invalid status code {}!", format(r.status_code) - ) + raise UnsupportedVersionAPIException("The server does not support this version of the API!") + raise APIException("The server returned an invalid status code {}!", format(r.status_code)) def __translate(self, game: GameConstants, version: int) -> Tuple[str, str]: servergame = { @@ -160,9 +144,7 @@ class APIClient: GameConstants.SDVX: "soundvoltex", }.get(game) if servergame is None: - raise UnsupportedRequestAPIException( - "The client does not support this game/version!" - ) + raise UnsupportedRequestAPIException("The client does not support this game/version!") if version >= DBConstants.OMNIMIX_VERSION_BUMP: version = version - DBConstants.OMNIMIX_VERSION_BUMP @@ -234,9 +216,7 @@ class APIClient: .get(version) ) if serverversion is None: - raise UnsupportedRequestAPIException( - "The client does not support this game/version!" - ) + raise UnsupportedRequestAPIException("The client does not support this game/version!") if omnimix: serverversion = "o" + serverversion @@ -338,9 +318,7 @@ class APIClient: return [] @cache.memoize(Time.SECONDS_IN_HOUR * 1) - def get_catalog( - self, game: GameConstants, version: int - ) -> Dict[str, List[Dict[str, Any]]]: + def get_catalog(self, game: GameConstants, version: int) -> Dict[str, List[Dict[str, Any]]]: # No point disallowing this, since its only ever used for bootstrapping. try: diff --git a/bemani/data/api/game.py b/bemani/data/api/game.py index 152973b..b06cdf5 100644 --- a/bemani/data/api/game.py +++ b/bemani/data/api/game.py @@ -100,9 +100,7 @@ class GlobalGameData(BaseGlobalData): seen.add(key) return retval - def get_item( - self, game: GameConstants, version: int, catid: int, cattype: str - ) -> Optional[ValidatedDict]: + def get_item(self, game: GameConstants, version: int, catid: int, cattype: str) -> Optional[ValidatedDict]: """ Given a game/userid and catalog id/type, find that catalog entry. diff --git a/bemani/data/api/music.py b/bemani/data/api/music.py index 903e4cf..05de65a 100644 --- a/bemani/data/api/music.py +++ b/bemani/data/api/music.py @@ -16,9 +16,7 @@ from bemani.data.types import UserID, Score, Song class GlobalMusicData(BaseGlobalData): - def __init__( - self, api: APIProviderInterface, user: UserData, music: MusicData - ) -> None: + def __init__(self, api: APIProviderInterface, user: UserData, music: MusicData) -> None: super().__init__(api) self.user = user self.music = music @@ -40,9 +38,7 @@ class GlobalMusicData(BaseGlobalData): def __max(self, int1: int, int2: int) -> int: return max(int1, int2) - def __format_ddr_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_ddr_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: halo = { "none": DBConstants.DDR_HALO_NONE, "gfc": DBConstants.DDR_HALO_GOOD_FULL_COMBO, @@ -96,9 +92,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_iidx_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_iidx_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: status = { "np": DBConstants.IIDX_CLEAR_STATUS_NO_PLAY, "failed": DBConstants.IIDX_CLEAR_STATUS_FAILED, @@ -128,9 +122,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_jubeat_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_jubeat_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: status = { "failed": DBConstants.JUBEAT_PLAY_MEDAL_FAILED, "cleared": DBConstants.JUBEAT_PLAY_MEDAL_CLEARED, @@ -157,9 +149,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_museca_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_museca_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: rank = { "death": DBConstants.MUSECA_GRADE_DEATH, "poor": DBConstants.MUSECA_GRADE_POOR, @@ -198,9 +188,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_popn_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_popn_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: status = { "cf": DBConstants.POPN_MUSIC_PLAY_MEDAL_CIRCLE_FAILED, "df": DBConstants.POPN_MUSIC_PLAY_MEDAL_DIAMOND_FAILED, @@ -230,9 +218,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_reflec_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_reflec_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: status = { "np": DBConstants.REFLEC_BEAT_CLEAR_TYPE_NO_PLAY, "failed": DBConstants.REFLEC_BEAT_CLEAR_TYPE_FAILED, @@ -265,9 +251,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __format_sdvx_score( - self, version: int, songid: int, songchart: int, data: Dict[str, Any] - ) -> Score: + def __format_sdvx_score(self, version: int, songid: int, songchart: int, data: Dict[str, Any]) -> Score: status = { "np": DBConstants.SDVX_CLEAR_TYPE_NO_PLAY, "failed": DBConstants.SDVX_CLEAR_TYPE_FAILED, @@ -335,9 +319,7 @@ class GlobalMusicData(BaseGlobalData): return self.__format_sdvx_score(version, songid, songchart, data) return None - def __merge_ddr_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_ddr_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -363,9 +345,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __merge_iidx_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_iidx_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -379,9 +359,7 @@ class GlobalMusicData(BaseGlobalData): oldscore.location, # Always propagate location from local setup if possible oldscore.plays + newscore.plays, { - "clear_status": self.__max( - oldscore.data["clear_status"], newscore.data["clear_status"] - ), + "clear_status": self.__max(oldscore.data["clear_status"], newscore.data["clear_status"]), "ghost": oldscore.data.get("ghost") if oldscore.points > newscore.points else newscore.data.get("ghost"), @@ -398,12 +376,8 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __merge_jubeat_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: - rate = self.__max( - oldscore.data.get("music_rate", -1), newscore.data.get("music_rate", -1) - ) + def __merge_jubeat_score(self, version: int, oldscore: Score, newscore: Score) -> Score: + rate = self.__max(oldscore.data.get("music_rate", -1), newscore.data.get("music_rate", -1)) return Score( -1, @@ -428,9 +402,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __merge_museca_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_museca_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -445,19 +417,13 @@ class GlobalMusicData(BaseGlobalData): oldscore.plays + newscore.plays, { "grade": self.__max(oldscore.data["grade"], newscore.data["grade"]), - "clear_type": self.__max( - oldscore.data["clear_type"], newscore.data["clear_type"] - ), + "clear_type": self.__max(oldscore.data["clear_type"], newscore.data["clear_type"]), "combo": self.__max(oldscore.data["combo"], newscore.data["combo"]), - "stats": oldscore.data["stats"] - if oldscore.points > newscore.points - else newscore.data["stats"], + "stats": oldscore.data["stats"] if oldscore.points > newscore.points else newscore.data["stats"], }, ) - def __merge_popn_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_popn_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -476,9 +442,7 @@ class GlobalMusicData(BaseGlobalData): }, ) - def __merge_reflec_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_reflec_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -492,26 +456,18 @@ class GlobalMusicData(BaseGlobalData): oldscore.location, # Always propagate location from local setup if possible oldscore.plays + newscore.plays, { - "clear_type": self.__max( - oldscore.data["clear_type"], newscore.data["clear_type"] - ), - "combo_type": self.__max( - oldscore.data["combo_type"], newscore.data["combo_type"] - ), + "clear_type": self.__max(oldscore.data["clear_type"], newscore.data["clear_type"]), + "combo_type": self.__max(oldscore.data["combo_type"], newscore.data["combo_type"]), "miss_count": self.__min( oldscore.data.get_int("miss_count", -1), newscore.data.get_int("miss_count", -1), ), "combo": self.__max(oldscore.data["combo"], newscore.data["combo"]), - "achievement_rate": self.__max( - oldscore.data["achievement_rate"], newscore.data["achievement_rate"] - ), + "achievement_rate": self.__max(oldscore.data["achievement_rate"], newscore.data["achievement_rate"]), }, ) - def __merge_sdvx_score( - self, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_sdvx_score(self, version: int, oldscore: Score, newscore: Score) -> Score: return Score( -1, oldscore.id, @@ -526,26 +482,18 @@ class GlobalMusicData(BaseGlobalData): oldscore.plays + newscore.plays, { "grade": self.__max(oldscore.data["grade"], newscore.data["grade"]), - "clear_type": self.__max( - oldscore.data["clear_type"], newscore.data["clear_type"] - ), + "clear_type": self.__max(oldscore.data["clear_type"], newscore.data["clear_type"]), "combo": self.__max( oldscore.data.get_int("combo", 1), newscore.data.get_int("combo", -1), ), - "stats": oldscore.data["stats"] - if oldscore.points > newscore.points - else newscore.data["stats"], + "stats": oldscore.data["stats"] if oldscore.points > newscore.points else newscore.data["stats"], }, ) - def __merge_score( - self, game: GameConstants, version: int, oldscore: Score, newscore: Score - ) -> Score: + def __merge_score(self, game: GameConstants, version: int, oldscore: Score, newscore: Score) -> Score: if oldscore.id != newscore.id or oldscore.chart != newscore.chart: - raise Exception( - "Logic error! Tried to merge scores from different song/charts!" - ) + raise Exception("Logic error! Tried to merge scores from different song/charts!") if game == GameConstants.DDR: return self.__merge_ddr_score(version, oldscore, newscore) @@ -597,9 +545,7 @@ class GlobalMusicData(BaseGlobalData): else: localscore, scores = Parallel.execute( [ - lambda: self.music.get_score( - game, version, userid, songid, songchart - ), + lambda: self.music.get_score(game, version, userid, songid, songchart), lambda: Parallel.flatten( Parallel.map( get_scores_for_card, @@ -773,9 +719,7 @@ class GlobalMusicData(BaseGlobalData): ) -> List[Tuple[UserID, Score]]: # First, pass off to local-only if this was called with parameters we don't support if version is None or userid is not None or songid is None: - return self.music.get_all_scores( - game, version, userid, songid, songchart, since, until - ) + return self.music.get_all_scores(game, version, userid, songid, songchart, since, until) # Now, figure out the request key based on passed in parameters if songchart is None: @@ -787,9 +731,7 @@ class GlobalMusicData(BaseGlobalData): localcards, localscores, remotescores = Parallel.execute( [ self.user.get_all_cards, - lambda: self.music.get_all_scores( - game, version, userid, songid, songchart, since, until - ), + lambda: self.music.get_all_scores(game, version, userid, songid, songchart, since, until), lambda: Parallel.flatten( Parallel.call( [client.get_records for client in self.clients], @@ -804,9 +746,7 @@ class GlobalMusicData(BaseGlobalData): ] ) - return self.__merge_global_scores( - game, version, localcards, localscores, remotescores - ) + return self.__merge_global_scores(game, version, localcards, localscores, remotescores) def __merge_global_records( self, @@ -824,9 +764,7 @@ class GlobalMusicData(BaseGlobalData): allscores[score.id] = {} allscores[score.id][score.chart] = (userid, score) - def get_score( - songid: int, songchart: int - ) -> Tuple[Optional[UserID], Optional[Score]]: + def get_score(songid: int, songchart: int) -> Tuple[Optional[UserID], Optional[Score]]: return allscores.get(songid, {}).get(songchart, (None, None)) # First, seed with local records @@ -857,9 +795,7 @@ class GlobalMusicData(BaseGlobalData): else: # if IDs are the same then we should merge them if oldid == userid: - add_score( - userid, self.__merge_score(game, version, oldscore, newscore) - ) + add_score(userid, self.__merge_score(game, version, oldscore, newscore)) else: # if the IDs are different we need to check which score actually belongs if newscore.points > oldscore.points: @@ -869,9 +805,7 @@ class GlobalMusicData(BaseGlobalData): finalscores: List[Tuple[UserID, Score]] = [] for songid in allscores: for chart in allscores[songid]: - finalscores.append( - (allscores[songid][chart][0], allscores[songid][chart][1]) - ) + finalscores.append((allscores[songid][chart][0], allscores[songid][chart][1])) return finalscores @@ -890,9 +824,7 @@ class GlobalMusicData(BaseGlobalData): localcards, localscores, remotescores = Parallel.execute( [ self.user.get_all_cards, - lambda: self.music.get_all_records( - game, version, userlist, locationlist - ), + lambda: self.music.get_all_records(game, version, userlist, locationlist), lambda: Parallel.flatten( Parallel.call( [client.get_records for client in self.clients], @@ -905,9 +837,7 @@ class GlobalMusicData(BaseGlobalData): ] ) - return self.__merge_global_records( - game, version, localcards, localscores, remotescores - ) + return self.__merge_global_records(game, version, localcards, localscores, remotescores) def get_clear_rates( self, @@ -1104,9 +1034,7 @@ class GlobalMusicData(BaseGlobalData): "bpm_min": int(data["bpm_min"]), "bpm_max": int(data["bpm_max"]), "difficulty": int(data["difficulty"]), - "version": categorymapping.get( - data.get("category", "0"), defaultcategory - ), + "version": categorymapping.get(data.get("category", "0"), defaultcategory), }, ) @@ -1223,33 +1151,19 @@ class GlobalMusicData(BaseGlobalData): data: Dict[str, Any], ) -> Optional[Song]: if game == GameConstants.DDR: - return self.__format_ddr_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_ddr_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.IIDX: - return self.__format_iidx_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_iidx_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.JUBEAT: - return self.__format_jubeat_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_jubeat_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.MUSECA: - return self.__format_museca_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_museca_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.POPN_MUSIC: - return self.__format_popn_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_popn_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.REFLEC_BEAT: - return self.__format_reflec_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_reflec_song(version, songid, songchart, name, artist, genre, data) if game == GameConstants.SDVX: - return self.__format_sdvx_song( - version, songid, songchart, name, artist, genre, data - ) + return self.__format_sdvx_song(version, songid, songchart, name, artist, genre, data) return None def get_all_songs( diff --git a/bemani/data/api/user.py b/bemani/data/api/user.py index 8bbf09a..8cd3dff 100644 --- a/bemani/data/api/user.py +++ b/bemani/data/api/user.py @@ -89,9 +89,7 @@ class GlobalUserData(BaseGlobalData): return new - def __profile_request( - self, game: GameConstants, version: int, userid: UserID, exact: bool - ) -> Optional[Profile]: + def __profile_request(self, game: GameConstants, version: int, userid: UserID, exact: bool) -> Optional[Profile]: # First, get or create the extid/refid for this virtual user cardid = RemoteUser.userid_to_card(userid) refid = self.user.get_refid(game, version, userid) @@ -134,27 +132,19 @@ class GlobalUserData(BaseGlobalData): userid = RemoteUser.card_to_userid(cardid) return userid - def from_refid( - self, game: GameConstants, version: int, refid: str - ) -> Optional[UserID]: + def from_refid(self, game: GameConstants, version: int, refid: str) -> Optional[UserID]: return self.user.from_refid(game, version, refid) - def from_extid( - self, game: GameConstants, version: int, extid: int - ) -> Optional[UserID]: + def from_extid(self, game: GameConstants, version: int, extid: int) -> Optional[UserID]: return self.user.from_extid(game, version, extid) - def get_profile( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[Profile]: + def get_profile(self, game: GameConstants, version: int, userid: UserID) -> Optional[Profile]: if RemoteUser.is_remote(userid): return self.__profile_request(game, version, userid, exact=True) else: return self.user.get_profile(game, version, userid) - def get_any_profile( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[Profile]: + def get_any_profile(self, game: GameConstants, version: int, userid: UserID) -> Optional[Profile]: if RemoteUser.is_remote(userid): return self.__profile_request(game, version, userid, exact=False) else: @@ -175,9 +165,7 @@ class GlobalUserData(BaseGlobalData): else: # We have to fetch some local profiles and some remote profiles, and then # merge them together - card_to_userid = { - RemoteUser.userid_to_card(userid): userid for userid in remote_ids - } + card_to_userid = {RemoteUser.userid_to_card(userid): userid for userid in remote_ids} local_profiles, remote_profiles = Parallel.execute( [ @@ -188,10 +176,7 @@ class GlobalUserData(BaseGlobalData): game, version, APIConstants.ID_TYPE_CARD, - [ - RemoteUser.userid_to_card(userid) - for userid in remote_ids - ], + [RemoteUser.userid_to_card(userid) for userid in remote_ids], ) ), ] @@ -235,9 +220,7 @@ class GlobalUserData(BaseGlobalData): return local_profiles - def get_all_profiles( - self, game: GameConstants, version: int - ) -> List[Tuple[UserID, Profile]]: + def get_all_profiles(self, game: GameConstants, version: int) -> List[Tuple[UserID, Profile]]: # Fetch local and remote profiles, and then merge by adding remote profiles to local # profiles when we don't have a profile for that user ID yet. local_cards, local_profiles, remote_profiles = Parallel.execute( diff --git a/bemani/data/config.py b/bemani/data/config.py index 88cf45f..92f8ae2 100644 --- a/bemani/data/config.py +++ b/bemani/data/config.py @@ -31,13 +31,9 @@ class Database: def engine(self) -> Engine: engine = self.__config.get("database", {}).get("engine") if engine is None: - raise Exception( - "Config object is not instantiated properly, no SQLAlchemy engine present!" - ) + raise Exception("Config object is not instantiated properly, no SQLAlchemy engine present!") if not isinstance(engine, Engine): - raise Exception( - "Config object is not instantiated properly, engine property is not a SQLAlchemy Engine!" - ) + raise Exception("Config object is not instantiated properly, engine property is not a SQLAlchemy Engine!") return engine @property @@ -109,9 +105,7 @@ class Client: def address(self) -> str: address = self.__config.get("client", {}).get("address") if address is None: - raise Exception( - "Config object is not instantiated properly, no client address present!" - ) + raise Exception("Config object is not instantiated properly, no client address present!") return str(address) @@ -123,9 +117,7 @@ class Machine: def pcbid(self) -> str: pcbid = self.__config.get("machine", {}).get("pcbid") if pcbid is None: - raise Exception( - "Config object is not instantiated properly, no machine pcbid present!" - ) + raise Exception("Config object is not instantiated properly, no machine pcbid present!") return str(pcbid) @property @@ -206,22 +198,16 @@ class Config(dict): def filename(self) -> str: filename = self.get("filename") if filename is None: - raise Exception( - "Config object is not instantiated properly, no filename present!" - ) + raise Exception("Config object is not instantiated properly, no filename present!") return os.path.abspath(str(filename)) @property def support(self) -> Set[GameConstants]: support = self.get("support") if support is None: - raise Exception( - "Config object is not instantiated properly, no support list present!" - ) + raise Exception("Config object is not instantiated properly, no support list present!") if not isinstance(support, set): - raise Exception( - "Config object is not instantiated properly, support property is not a Set!" - ) + raise Exception("Config object is not instantiated properly, support property is not a Set!") return support @property diff --git a/bemani/data/data.py b/bemani/data/data.py index 7777db5..3df7086 100644 --- a/bemani/data/data.py +++ b/bemani/data/data.py @@ -135,17 +135,13 @@ class Data: def __exists(self) -> bool: # See if the DB was already created try: - cursor = self.__session.execute( - text("SELECT COUNT(version_num) AS count FROM alembic_version") - ) + cursor = self.__session.execute(text("SELECT COUNT(version_num) AS count FROM alembic_version")) return cursor.fetchone()["count"] == 1 except ProgrammingError: return False def __alembic_cmd(self, command: str, *args: str) -> None: - base_dir = os.path.join( - os.path.abspath(os.path.dirname(__file__)), "migrations" - ) + base_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "migrations") alembicArgs = [ "-c", os.path.join(base_dir, "alembic.ini"), @@ -165,9 +161,7 @@ class Data: """ if self.__exists(): # Cowardly refused to do anything, we should be using the upgrade path instead. - raise DBCreateException( - "Tables already created, use upgrade to upgrade schema!" - ) + raise DBCreateException("Tables already created, use upgrade to upgrade schema!") metadata.create_all( self.__config.database.engine.connect(), @@ -185,19 +179,13 @@ class Data: Generate upgrade scripts using alembic. """ if not self.__exists(): - raise DBCreateException( - "Tables have not been created yet, use create to create them!" - ) + raise DBCreateException("Tables have not been created yet, use create to create them!") # Verify that there are actual changes, and refuse to create empty migration scripts - context = MigrationContext.configure( - self.__config.database.engine.connect(), opts={"compare_type": True} - ) + context = MigrationContext.configure(self.__config.database.engine.connect(), opts={"compare_type": True}) diff = compare_metadata(context, metadata) if (not allow_empty) and (len(diff) == 0): - raise DBCreateException( - "There is nothing different between code and the DB, refusing to create migration!" - ) + raise DBCreateException("There is nothing different between code and the DB, refusing to create migration!") self.__alembic_cmd( "revision", @@ -211,9 +199,7 @@ class Data: Upgrade an existing DB to the current model. """ if not self.__exists(): - raise DBCreateException( - "Tables have not been created yet, use create to create them!" - ) + raise DBCreateException("Tables have not been created yet, use create to create them!") self.__alembic_cmd( "upgrade", diff --git a/bemani/data/mysql/base.py b/bemani/data/mysql/base.py index dd74bc3..1c71395 100644 --- a/bemani/data/mysql/base.py +++ b/bemani/data/mysql/base.py @@ -136,9 +136,7 @@ class BaseData: """ # Look up the user account, making sure to expire old sessions sql = "SELECT id FROM session WHERE session = :session AND type = :type AND expiration > :timestamp" - cursor = self.execute( - sql, {"session": session, "type": sesstype, "timestamp": Time.now()} - ) + cursor = self.execute(sql, {"session": session, "type": sesstype, "timestamp": Time.now()}) if cursor.rowcount != 1: # Couldn't find a user with this session return None @@ -146,9 +144,7 @@ class BaseData: result = cursor.fetchone() return result["id"] - def _create_session( - self, opid: int, optype: str, expiration: int = (30 * 86400) - ) -> str: + def _create_session(self, opid: int, optype: str, expiration: int = (30 * 86400)) -> str: """ Given an ID, create a session string. @@ -161,10 +157,7 @@ class BaseData: """ # Create a new session that is unique while True: - session = "".join( - random.choice("0123456789ABCDEF") - for _ in range(BaseData.SESSION_LENGTH) - ) + session = "".join(random.choice("0123456789ABCDEF") for _ in range(BaseData.SESSION_LENGTH)) sql = "SELECT session FROM session WHERE session = :session" cursor = self.execute(sql, {"session": session}) if cursor.rowcount == 0: @@ -198,9 +191,7 @@ class BaseData: """ # Remove the session token sql = "DELETE FROM session WHERE session = :session AND type = :sesstype" - self.execute( - sql, {"session": session, "sesstype": sesstype}, safe_write_operation=True - ) + self.execute(sql, {"session": session, "sesstype": sesstype}, safe_write_operation=True) # Also weed out any other defunct sessions sql = "DELETE FROM session WHERE expiration < :timestamp" diff --git a/bemani/data/mysql/game.py b/bemani/data/mysql/game.py index 78eef8e..2b92082 100644 --- a/bemani/data/mysql/game.py +++ b/bemani/data/mysql/game.py @@ -67,17 +67,13 @@ time_sensitive_settings = Table( Column("start_time", Integer, nullable=False, index=True), Column("end_time", Integer, nullable=False, index=True), Column("data", JSON, nullable=False), - UniqueConstraint( - "game", "version", "name", "start_time", name="game_version_name_start_time" - ), + UniqueConstraint("game", "version", "name", "start_time", name="game_version_name_start_time"), mysql_charset="utf8mb4", ) class GameData(BaseData): - def get_settings( - self, game: GameConstants, userid: UserID - ) -> Optional[ValidatedDict]: + def get_settings(self, game: GameConstants, userid: UserID) -> Optional[ValidatedDict]: """ Given a game and a user ID, look up game-wide settings as a dictionary. @@ -103,9 +99,7 @@ class GameData(BaseData): result = cursor.fetchone() return ValidatedDict(self.deserialize(result["data"])) - def put_settings( - self, game: GameConstants, userid: UserID, settings: Dict[str, Any] - ) -> None: + def put_settings(self, game: GameConstants, userid: UserID, settings: Dict[str, Any]) -> None: """ Given a game and a user ID, save game-wide settings to the DB. @@ -167,9 +161,7 @@ class GameData(BaseData): result = cursor.fetchone() return ValidatedDict(self.deserialize(result["data"])) - def get_achievements( - self, game: GameConstants, userid: UserID - ) -> List[Achievement]: + def get_achievements(self, game: GameConstants, userid: UserID) -> List[Achievement]: """ Given a game/userid, find all achievements @@ -228,9 +220,7 @@ class GameData(BaseData): }, ) - def get_time_sensitive_settings( - self, game: GameConstants, version: int, name: str - ) -> Optional[ValidatedDict]: + def get_time_sensitive_settings(self, game: GameConstants, version: int, name: str) -> Optional[ValidatedDict]: """ Given a game/version/name, look up the current time-sensitive settings for this game. @@ -267,9 +257,7 @@ class GameData(BaseData): retval["end_time"] = result["end_time"] return retval - def get_all_time_sensitive_settings( - self, game: GameConstants, version: int, name: str - ) -> List[ValidatedDict]: + def get_all_time_sensitive_settings(self, game: GameConstants, version: int, name: str) -> List[ValidatedDict]: """ Given a game/version/name, look up all of the time-sensitive settings for this game. @@ -287,9 +275,7 @@ class GameData(BaseData): SELECT data, start_time, end_time FROM time_sensitive_settings WHERE game = :game AND version = :version AND name = :name """ - cursor = self.execute( - sql, {"game": game.value, "version": version, "name": name} - ) + cursor = self.execute(sql, {"game": game.value, "version": version, "name": name}) if cursor.rowcount == 0: # setting doesn't exist return [] @@ -376,9 +362,7 @@ class GameData(BaseData): }, ) - def get_item( - self, game: GameConstants, version: int, catid: int, cattype: str - ) -> Optional[ValidatedDict]: + def get_item(self, game: GameConstants, version: int, catid: int, cattype: str) -> Optional[ValidatedDict]: """ Given a game/userid and catalog id/type, find that catalog entry. @@ -398,9 +382,7 @@ class GameData(BaseData): SELECT data FROM catalog WHERE game = :game AND version = :version AND id = :id AND type = :type """ - cursor = self.execute( - sql, {"game": game.value, "version": version, "id": catid, "type": cattype} - ) + cursor = self.execute(sql, {"game": game.value, "version": version, "id": catid, "type": cattype}) if cursor.rowcount != 1: # entry doesn't exist return None diff --git a/bemani/data/mysql/lobby.py b/bemani/data/mysql/lobby.py index 2a19186..0657c83 100644 --- a/bemani/data/mysql/lobby.py +++ b/bemani/data/mysql/lobby.py @@ -45,9 +45,7 @@ lobby = Table( class LobbyData(BaseData): - def get_play_session_info( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[ValidatedDict]: + def get_play_session_info(self, game: GameConstants, version: int, userid: UserID) -> Optional[ValidatedDict]: """ Given a game, version and a user ID, look up play session information for that user. @@ -90,9 +88,7 @@ class LobbyData(BaseData): data["time"] = result["time"] return data - def get_all_play_session_infos( - self, game: GameConstants, version: int - ) -> List[Tuple[UserID, ValidatedDict]]: + def get_all_play_session_infos(self, game: GameConstants, version: int) -> List[Tuple[UserID, ValidatedDict]]: """ Given a game and version, look up all play session information. @@ -125,9 +121,7 @@ class LobbyData(BaseData): return [(UserID(result["userid"]), format_result(result)) for result in cursor] - def put_play_session_info( - self, game: GameConstants, version: int, userid: UserID, data: Dict[str, Any] - ) -> None: + def put_play_session_info(self, game: GameConstants, version: int, userid: UserID, data: Dict[str, Any]) -> None: """ Given a game, version and a user ID, save play session information for that user. @@ -160,9 +154,7 @@ class LobbyData(BaseData): }, ) - def destroy_play_session_info( - self, game: GameConstants, version: int, userid: UserID - ) -> None: + def destroy_play_session_info(self, game: GameConstants, version: int, userid: UserID) -> None: """ Given a game, version and a user ID, throw away session info for that play session. @@ -185,9 +177,7 @@ class LobbyData(BaseData): sql = "DELETE FROM playsession WHERE time <= :time" self.execute(sql, {"time": Time.now() - Time.SECONDS_IN_HOUR}) - def get_lobby( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[ValidatedDict]: + def get_lobby(self, game: GameConstants, version: int, userid: UserID) -> Optional[ValidatedDict]: """ Given a game, version and a user ID, look up lobby information for that user. @@ -264,9 +254,7 @@ class LobbyData(BaseData): return [(UserID(result["userid"]), format_result(result)) for result in cursor] - def put_lobby( - self, game: GameConstants, version: int, userid: UserID, data: Dict[str, Any] - ) -> None: + def put_lobby(self, game: GameConstants, version: int, userid: UserID, data: Dict[str, Any]) -> None: """ Given a game, version and a user ID, save lobby information for that user. diff --git a/bemani/data/mysql/machine.py b/bemani/data/mysql/machine.py index 0ec2d46..0abf18e 100644 --- a/bemani/data/mysql/machine.py +++ b/bemani/data/mysql/machine.py @@ -71,9 +71,7 @@ arcade_settings = Table( Column("version", Integer, nullable=False), Column("type", String(64), nullable=False), Column("data", JSON, nullable=False), - UniqueConstraint( - "arcadeid", "game", "version", "type", name="arcadeid_game_version_type" - ), + UniqueConstraint("arcadeid", "game", "version", "type", name="arcadeid_game_version_type"), mysql_charset="utf8mb4", ) diff --git a/bemani/data/mysql/music.py b/bemani/data/mysql/music.py index 65c035e..7ecda29 100644 --- a/bemani/data/mysql/music.py +++ b/bemani/data/mysql/music.py @@ -75,17 +75,13 @@ music = Table( Column("artist", String(255)), Column("genre", String(255)), Column("data", JSON), - UniqueConstraint( - "songid", "chart", "game", "version", name="songid_chart_game_version" - ), + UniqueConstraint("songid", "chart", "game", "version", name="songid_chart_game_version"), mysql_charset="utf8mb4", ) class MusicData(BaseData): - def __get_musicid( - self, game: GameConstants, version: int, songid: int, songchart: int - ) -> int: + def __get_musicid(self, game: GameConstants, version: int, songid: int, songchart: int) -> int: """ Given a game/version/songid/chart, look up the unique music ID for this song. @@ -110,9 +106,7 @@ class MusicData(BaseData): ) if cursor.rowcount != 1: # music doesn't exist - raise Exception( - f"Song {songid} chart {songchart} doesn't exist for game {game} version {version}" - ) + raise Exception(f"Song {songid} chart {songchart} doesn't exist for game {game} version {version}") result = cursor.fetchone() return result["id"] @@ -315,9 +309,7 @@ class MusicData(BaseData): self.deserialize(result["data"]), ) - def get_score_by_key( - self, game: GameConstants, version: int, key: int - ) -> Optional[Tuple[UserID, Score]]: + def get_score_by_key(self, game: GameConstants, version: int, key: int) -> Optional[Tuple[UserID, Score]]: """ Look up previous high score by key. @@ -450,9 +442,7 @@ class MusicData(BaseData): for result in cursor ] - def get_most_played( - self, game: GameConstants, version: int, userid: UserID, count: int - ) -> List[Tuple[int, int]]: + def get_most_played(self, game: GameConstants, version: int, userid: UserID, count: int) -> List[Tuple[int, int]]: """ Look up a user's most played songs. @@ -484,9 +474,7 @@ class MusicData(BaseData): return [(result["songid"], result["plays"]) for result in cursor] - def get_last_played( - self, game: GameConstants, version: int, userid: UserID, count: int - ) -> List[Tuple[int, int]]: + def get_last_played(self, game: GameConstants, version: int, userid: UserID, count: int) -> List[Tuple[int, int]]: """ Look up a user's last played songs. @@ -684,11 +672,19 @@ class MusicData(BaseData): """ # First, construct the queries for grabbing the songid/chart if version is not None: - songidquery = "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" - chartquery = "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + songidquery = ( + "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + ) + chartquery = ( + "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + ) else: - songidquery = "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" - chartquery = "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + songidquery = ( + "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + ) + chartquery = ( + "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + ) # Select statement for getting play count playselect = "SELECT COUNT(timestamp) FROM score_history WHERE score_history.musicid = score.musicid AND score_history.userid = score.userid" @@ -784,14 +780,24 @@ class MusicData(BaseData): """ # First, construct the queries for grabbing the songid/chart if version is not None: - songidquery = "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" - chartquery = "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + songidquery = ( + "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + ) + chartquery = ( + "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game AND version = :version" + ) else: - songidquery = "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" - chartquery = "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + songidquery = ( + "SELECT songid FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + ) + chartquery = ( + "SELECT chart FROM music WHERE music.id = score.musicid AND game = :game ORDER BY version DESC LIMIT 1" + ) # Next, get a list of all songs that were played given the input criteria - musicid_sql = "SELECT DISTINCT(score.musicid) FROM score, music WHERE score.musicid = music.id AND music.game = :game" + musicid_sql = ( + "SELECT DISTINCT(score.musicid) FROM score, music WHERE score.musicid = music.id AND music.game = :game" + ) params: Dict[str, Any] = {"game": game.value} if version is not None: musicid_sql = musicid_sql + " AND music.version = :version" @@ -860,9 +866,7 @@ class MusicData(BaseData): for result in cursor ] - def get_attempt_by_key( - self, game: GameConstants, version: int, key: int - ) -> Optional[Tuple[UserID, Attempt]]: + def get_attempt_by_key(self, game: GameConstants, version: int, key: int) -> Optional[Tuple[UserID, Attempt]]: """ Look up a previous attempt by key. @@ -943,7 +947,9 @@ class MusicData(BaseData): # First, construct the queries for grabbing the songid/chart if version is not None: songidquery = "SELECT songid FROM music WHERE music.id = score_history.musicid AND game = :game AND version = :version" - chartquery = "SELECT chart FROM music WHERE music.id = score_history.musicid AND game = :game AND version = :version" + chartquery = ( + "SELECT chart FROM music WHERE music.id = score_history.musicid AND game = :game AND version = :version" + ) else: songidquery = "SELECT songid FROM music WHERE music.id = score_history.musicid AND game = :game ORDER BY version DESC LIMIT 1" chartquery = "SELECT chart FROM music WHERE music.id = score_history.musicid AND game = :game ORDER BY version DESC LIMIT 1" diff --git a/bemani/data/mysql/network.py b/bemani/data/mysql/network.py index 04e59c3..45394b9 100644 --- a/bemani/data/mysql/network.py +++ b/bemani/data/mysql/network.py @@ -34,9 +34,7 @@ scheduled_work = Table( Column("schedule", String(32), nullable=False), Column("year", Integer), Column("day", Integer), - UniqueConstraint( - "game", "version", "name", "schedule", name="game_version_name_schedule" - ), + UniqueConstraint("game", "version", "name", "schedule", name="game_version_name_schedule"), mysql_charset="utf8mb4", ) @@ -90,9 +88,7 @@ class NetworkData(BaseData): The ID of the newly created entry. """ sql = "INSERT INTO news (timestamp, title, body) VALUES (:timestamp, :title, :body)" - cursor = self.execute( - sql, {"timestamp": Time.now(), "title": title, "body": body} - ) + cursor = self.execute(sql, {"timestamp": Time.now(), "title": title, "body": body}) return cursor.lastrowid def get_news(self, newsid: int) -> Optional[News]: @@ -145,9 +141,7 @@ class NetworkData(BaseData): of the current schedule of this type. """ if schedule not in ["daily", "weekly"]: - raise Exception( - "Logic error, specify either 'daily' or 'weekly' for schedule type!" - ) + raise Exception("Logic error, specify either 'daily' or 'weekly' for schedule type!") if schedule == "daily": return (Time.beginning_of_today(), Time.end_of_today()) @@ -158,17 +152,13 @@ class NetworkData(BaseData): # Should never happen return (0, 0) - def should_schedule( - self, game: GameConstants, version: int, name: str, schedule: str - ) -> bool: + def should_schedule(self, game: GameConstants, version: int, name: str, schedule: str) -> bool: """ Given a game/version/name pair and a schedule value, return whether this scheduled work is overdue or not. """ if schedule not in ["daily", "weekly"]: - raise Exception( - "Logic error, specify either 'daily' or 'weekly' for schedule type!" - ) + raise Exception("Logic error, specify either 'daily' or 'weekly' for schedule type!") sql = """ SELECT year, day FROM scheduled_work @@ -212,13 +202,9 @@ class NetworkData(BaseData): # We have already run this work for this schedule return False - def mark_scheduled( - self, game: GameConstants, version: int, name: str, schedule: str - ) -> None: + def mark_scheduled(self, game: GameConstants, version: int, name: str, schedule: str) -> None: if schedule not in ["daily", "weekly"]: - raise Exception( - "Logic error, specify either 'daily' or 'weekly' for schedule type!" - ) + raise Exception("Logic error, specify either 'daily' or 'weekly' for schedule type!") if schedule == "daily": year, day = Time.days_into_year() @@ -327,9 +313,7 @@ class NetworkData(BaseData): result["id"], result["timestamp"], UserID(result["userid"]) if result["userid"] is not None else None, - ArcadeID(result["arcadeid"]) - if result["arcadeid"] is not None - else None, + ArcadeID(result["arcadeid"]) if result["arcadeid"] is not None else None, result["type"], self.deserialize(result["data"]), ) diff --git a/bemani/data/mysql/user.py b/bemani/data/mysql/user.py index 82c56f5..5ab8304 100644 --- a/bemani/data/mysql/user.py +++ b/bemani/data/mysql/user.py @@ -123,9 +123,7 @@ time_based_achievement = Table( Column("type", String(64), nullable=False), Column("timestamp", Integer, nullable=False, index=True), Column("data", JSON, nullable=False), - UniqueConstraint( - "refid", "id", "type", "timestamp", name="refid_id_type_timestamp" - ), + UniqueConstraint("refid", "id", "type", "timestamp", name="refid_id_type_timestamp"), mysql_charset="utf8mb4", ) @@ -218,9 +216,7 @@ class UserData(BaseData): result = cursor.fetchone() return UserID(result["id"]) - def from_refid( - self, game: GameConstants, version: int, refid: str - ) -> Optional[UserID]: + def from_refid(self, game: GameConstants, version: int, refid: str) -> Optional[UserID]: """ Given a generated RefID, look up a user ID. @@ -237,9 +233,7 @@ class UserData(BaseData): """ # First, look up the user account sql = "SELECT userid FROM refid WHERE game = :game AND version = :version AND refid = :refid" - cursor = self.execute( - sql, {"game": game.value, "version": version, "refid": refid} - ) + cursor = self.execute(sql, {"game": game.value, "version": version, "refid": refid}) if cursor.rowcount != 1: # Couldn't find a user with this refid return None @@ -247,9 +241,7 @@ class UserData(BaseData): result = cursor.fetchone() return UserID(result["userid"]) - def from_extid( - self, game: GameConstants, version: int, extid: int - ) -> Optional[UserID]: + def from_extid(self, game: GameConstants, version: int, extid: int) -> Optional[UserID]: """ Given a generated ExtID, look up a user ID. @@ -378,9 +370,7 @@ class UserData(BaseData): cardid - 16-digit card ID to add. """ if RemoteUser.is_remote(userid): - raise AccountCreationException( - "Should not add local cards to remote users!" - ) + raise AccountCreationException("Should not add local cards to remote users!") sql = "INSERT INTO card (userid, id) VALUES (:userid, :cardid)" self.execute(sql, {"userid": userid, "cardid": cardid}) @@ -499,9 +489,7 @@ class UserData(BaseData): sql = "UPDATE user SET password = :hash WHERE id = :userid" self.execute(sql, {"hash": passhash, "userid": userid}) - def get_profile( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[Profile]: + def get_profile(self, game: GameConstants, version: int, userid: UserID) -> Optional[Profile]: """ Given a game/version/userid, look up the associated profile. @@ -524,9 +512,7 @@ class UserData(BaseData): extid.game = refid.game AND profile.refid = refid.refid """ - cursor = self.execute( - sql, {"userid": userid, "game": game.value, "version": version} - ) + cursor = self.execute(sql, {"userid": userid, "game": game.value, "version": version}) if cursor.rowcount != 1: # Profile doesn't exist return None @@ -540,9 +526,7 @@ class UserData(BaseData): self.deserialize(result["data"]), ) - def get_any_profile( - self, game: GameConstants, version: int, userid: UserID - ) -> Optional[Profile]: + def get_any_profile(self, game: GameConstants, version: int, userid: UserID) -> Optional[Profile]: """ Given a game/version/userid, look up the associated profile. If the profile for that version doesn't exist, try another profile, failing only if there is no profile for any version of @@ -613,16 +597,12 @@ class UserData(BaseData): return [ ( uid, - self.get_profile(game, profilever[uid], uid) - if uid in profilever - else None, + self.get_profile(game, profilever[uid], uid) if uid in profilever else None, ) for uid in userids ] - def get_games_played( - self, userid: UserID, game: Optional[GameConstants] = None - ) -> List[Tuple[GameConstants, int]]: + def get_games_played(self, userid: UserID, game: Optional[GameConstants] = None) -> List[Tuple[GameConstants, int]]: """ Given a user ID, look up all game/version combos this user has played. @@ -648,9 +628,7 @@ class UserData(BaseData): cursor = self.execute(sql, vals) return [(GameConstants(result["game"]), result["version"]) for result in cursor] - def get_all_profiles( - self, game: GameConstants, version: int - ) -> List[Tuple[UserID, Profile]]: + def get_all_profiles(self, game: GameConstants, version: int) -> List[Tuple[UserID, Profile]]: """ Given a game/version, look up all user profiles for that game. @@ -757,9 +735,7 @@ class UserData(BaseData): for result in cursor ] - def put_profile( - self, game: GameConstants, version: int, userid: UserID, profile: Profile - ) -> None: + def put_profile(self, game: GameConstants, version: int, userid: UserID, profile: Profile) -> None: """ Given a game/version/userid, save an associated profile. @@ -827,9 +803,7 @@ class UserData(BaseData): """ refid = self.get_refid(game, version, userid) sql = "SELECT data FROM achievement WHERE refid = :refid AND id = :id AND type = :type" - cursor = self.execute( - sql, {"refid": refid, "id": achievementid, "type": achievementtype} - ) + cursor = self.execute(sql, {"refid": refid, "id": achievementid, "type": achievementtype}) if cursor.rowcount != 1: # score doesn't exist return None @@ -837,9 +811,7 @@ class UserData(BaseData): result = cursor.fetchone() return ValidatedDict(self.deserialize(result["data"])) - def get_achievements( - self, game: GameConstants, version: int, userid: UserID - ) -> List[Achievement]: + def get_achievements(self, game: GameConstants, version: int, userid: UserID) -> List[Achievement]: """ Given a game/version/userid, find all achievements @@ -928,9 +900,7 @@ class UserData(BaseData): DELETE FROM achievement WHERE refid = :refid AND id = :id AND type = :type """ - self.execute( - sql, {"refid": refid, "id": achievementid, "type": achievementtype} - ) + self.execute(sql, {"refid": refid, "id": achievementid, "type": achievementtype}) def get_time_based_achievements( self, @@ -1017,9 +987,7 @@ class UserData(BaseData): }, ) - def get_all_time_based_achievements( - self, game: GameConstants, version: int - ) -> List[Tuple[UserID, Achievement]]: + def get_all_time_based_achievements(self, game: GameConstants, version: int) -> List[Tuple[UserID, Achievement]]: """ Given a game/version, find all time-based achievements for all players. @@ -1109,9 +1077,7 @@ class UserData(BaseData): result = cursor.fetchone() return ValidatedDict(self.deserialize(result["data"])) - def get_links( - self, game: GameConstants, version: int, userid: UserID - ) -> List[Link]: + def get_links(self, game: GameConstants, version: int, userid: UserID) -> List[Link]: """ Given a game/version/userid, find all links between this user and other users @@ -1128,9 +1094,7 @@ class UserData(BaseData): FROM link WHERE game = :game AND version = :version AND userid = :userid """ - cursor = self.execute( - sql, {"game": game.value, "version": version, "userid": userid} - ) + cursor = self.execute(sql, {"game": game.value, "version": version, "userid": userid}) return [ Link( @@ -1237,9 +1201,7 @@ class UserData(BaseData): else: return 0 - def update_balance( - self, userid: UserID, arcadeid: ArcadeID, delta: int - ) -> Optional[int]: + def update_balance(self, userid: UserID, arcadeid: ArcadeID, delta: int) -> Optional[int]: """ Given a user and an arcade ID, update the PASELI balance for that arcade. @@ -1278,9 +1240,7 @@ class UserData(BaseData): and returns it, which can be used for creating/looking up a profile in the future. """ sql = "SELECT refid FROM refid WHERE userid = :userid AND game = :game AND version = :version" - cursor = self.execute( - sql, {"userid": userid, "game": game.value, "version": version} - ) + cursor = self.execute(sql, {"userid": userid, "game": game.value, "version": version}) if cursor.rowcount == 1: result = cursor.fetchone() return result["refid"] @@ -1319,9 +1279,7 @@ class UserData(BaseData): if extid is not None: return extid else: - raise AccountCreationException( - "Failed to cteate a new refid/extid pair!" - ) + raise AccountCreationException("Failed to cteate a new refid/extid pair!") def create_session(self, userid: UserID, expiration: int = (30 * 86400)) -> str: """ @@ -1376,18 +1334,14 @@ class UserData(BaseData): VALUES (:game, :extid, :userid) """ try: - cursor = self.execute( - sql, {"game": game.value, "extid": extid, "userid": userid} - ) + cursor = self.execute(sql, {"game": game.value, "extid": extid, "userid": userid}) except IntegrityError: # User already has an ExtID for this game series pass # Create a new refid that is unique while True: - refid = "".join( - random.choice("0123456789ABCDEF") for _ in range(UserData.REF_ID_LENGTH) - ) + refid = "".join(random.choice("0123456789ABCDEF") for _ in range(UserData.REF_ID_LENGTH)) sql = "SELECT refid FROM refid WHERE refid = :refid" cursor = self.execute(sql, {"refid": refid}) if cursor.rowcount == 0: @@ -1409,17 +1363,13 @@ class UserData(BaseData): }, ) if cursor.rowcount != 1: - raise AccountCreationException( - "Failed to create and fetch a new refid!" - ) + raise AccountCreationException("Failed to create and fetch a new refid!") return refid except IntegrityError: # We maybe lost the race? Look up the ID from another creation. Don't call get_refid # because it calls us, so we don't want an infinite loop. sql = "SELECT refid FROM refid WHERE userid = :userid AND game = :game AND version = :version" - cursor = self.execute( - sql, {"userid": userid, "game": game.value, "version": version} - ) + cursor = self.execute(sql, {"userid": userid, "game": game.value, "version": version}) if cursor.rowcount == 1: result = cursor.fetchone() return result["refid"] diff --git a/bemani/data/triggers.py b/bemani/data/triggers.py index ede984c..ab9f3ef 100644 --- a/bemani/data/triggers.py +++ b/bemani/data/triggers.py @@ -37,26 +37,18 @@ class Triggers: # Nothing is hooked up for this game, so there is no destination. return False - def broadcast_score( - self, data: Dict[BroadcastConstants, str], game: GameConstants, song: Song - ) -> None: + def broadcast_score(self, data: Dict[BroadcastConstants, str], game: GameConstants, song: Song) -> None: # For now we only support discord if self.config.webhooks.discord[game] is not None: self.broadcast_score_discord(data, game, song) - def broadcast_score_discord( - self, data: Dict[BroadcastConstants, str], game: GameConstants, song: Song - ) -> None: + def broadcast_score_discord(self, data: Dict[BroadcastConstants, str], game: GameConstants, song: Song) -> None: if game in {GameConstants.IIDX, GameConstants.POPN_MUSIC}: now = datetime.now() webhook = DiscordWebhook(url=self.config.webhooks.discord[game]) - scoreembed = DiscordEmbed( - title=f"New {self.__gameconst_to_series(game)} Score!", color="fbba08" - ) - scoreembed.set_footer( - text=(now.strftime("Score was recorded on %m/%d/%y at %H:%M:%S")) - ) + scoreembed = DiscordEmbed(title=f"New {self.__gameconst_to_series(game)} Score!", color="fbba08") + scoreembed.set_footer(text=(now.strftime("Score was recorded on %m/%d/%y at %H:%M:%S"))) # lets give it an author song_url = ( diff --git a/bemani/data/types.py b/bemani/data/types.py index e942c5f..821eb83 100644 --- a/bemani/data/types.py +++ b/bemani/data/types.py @@ -15,9 +15,7 @@ class User: more cards, or swap out a card for a new one. """ - def __init__( - self, userid: UserID, username: Optional[str], email: Optional[str], admin: bool - ) -> None: + def __init__(self, userid: UserID, username: Optional[str], email: Optional[str], admin: bool) -> None: """ Initialize the user object. @@ -76,9 +74,7 @@ class Link: determined by the game that needs this linkage. """ - def __init__( - self, userid: UserID, linktype: str, other_userid: UserID, data: Dict[str, Any] - ) -> None: + def __init__(self, userid: UserID, linktype: str, other_userid: UserID, data: Dict[str, Any]) -> None: """ Initialize the achievement object. diff --git a/bemani/format/afp/blend/blend.py b/bemani/format/afp/blend/blend.py index 594c34b..b9996a8 100644 --- a/bemani/format/afp/blend/blend.py +++ b/bemani/format/afp/blend/blend.py @@ -36,15 +36,9 @@ def blend_normal( srcremainder = 1.0 - srcpercent new_alpha = max(min(0.0, srcpercent + destpercent * srcremainder), 1.0) return ( - clamp( - ((dest[0] * destpercent * srcremainder) + (src[0] * srcpercent)) / new_alpha - ), - clamp( - ((dest[1] * destpercent * srcremainder) + (src[1] * srcpercent)) / new_alpha - ), - clamp( - ((dest[2] * destpercent * srcremainder) + (src[2] * srcpercent)) / new_alpha - ), + clamp(((dest[0] * destpercent * srcremainder) + (src[0] * srcpercent)) / new_alpha), + clamp(((dest[1] * destpercent * srcremainder) + (src[1] * srcpercent)) / new_alpha), + clamp(((dest[2] * destpercent * srcremainder) + (src[2] * srcpercent)) / new_alpha), clamp(255 * new_alpha), ) @@ -120,18 +114,9 @@ def blend_multiply( src_alpha = src[3] / 255.0 src_remainder = 1.0 - src_alpha return ( - clamp( - (255 * ((dest[0] / 255.0) * (src[0] / 255.0) * src_alpha)) - + (dest[0] * src_remainder) - ), - clamp( - (255 * ((dest[1] / 255.0) * (src[1] / 255.0) * src_alpha)) - + (dest[1] * src_remainder) - ), - clamp( - (255 * ((dest[2] / 255.0) * (src[2] / 255.0) * src_alpha)) - + (dest[2] * src_remainder) - ), + clamp((255 * ((dest[0] / 255.0) * (src[0] / 255.0) * src_alpha)) + (dest[0] * src_remainder)), + clamp((255 * ((dest[1] / 255.0) * (src[1] / 255.0) * src_alpha)) + (dest[1] * src_remainder)), + clamp((255 * ((dest[2] / 255.0) * (src[2] / 255.0) * src_alpha)) + (dest[2] * src_remainder)), dest[3], ) @@ -205,9 +190,7 @@ def blend_point( # convert and shift. Also I'm not sure if this should be done before or # after the add and multiply. if not hsl_shift.is_identity: - hslcolor = Color( - src_color[0] / 255, src_color[1] / 255, src_color[2] / 255, 1.0 - ).as_hsl() + hslcolor = Color(src_color[0] / 255, src_color[1] / 255, src_color[2] / 255, 1.0).as_hsl() hslcolor = hslcolor.add(hsl_shift) newcolor = hslcolor.as_rgb() @@ -312,12 +295,7 @@ def pixel_renderer( aaloc = callback(Point(imgx + 0.5, imgy + 0.5)) if aaloc is not None: aax, aay, _ = aaloc.as_tuple() - if not ( - aax <= 0 - or aay <= 0 - or aax >= (texwidth - 1) - or aay >= (texheight - 1) - ): + if not (aax <= 0 or aay <= 0 or aax >= (texwidth - 1) or aay >= (texheight - 1)): bilinear = True # Now perform the desired AA operation. @@ -351,9 +329,7 @@ def pixel_renderer( average = [255, 255, 255, 0] else: # Interpolate in the X direction on both Y axis. - y0r = (texbytes[tex00] * tex00percent * (1.0 - aaxrem)) + ( - texbytes[tex10] * tex10percent * aaxrem - ) + y0r = (texbytes[tex00] * tex00percent * (1.0 - aaxrem)) + (texbytes[tex10] * tex10percent * aaxrem) y0g = (texbytes[tex00 + 1] * tex00percent * (1.0 - aaxrem)) + ( texbytes[tex10 + 1] * tex10percent * aaxrem ) @@ -361,9 +337,7 @@ def pixel_renderer( texbytes[tex10 + 2] * tex10percent * aaxrem ) - y1r = (texbytes[tex01] * tex01percent * (1.0 - aaxrem)) + ( - texbytes[tex11] * tex11percent * aaxrem - ) + y1r = (texbytes[tex01] * tex01percent * (1.0 - aaxrem)) + (texbytes[tex11] * tex11percent * aaxrem) y1g = (texbytes[tex01 + 1] * tex01percent * (1.0 - aaxrem)) + ( texbytes[tex11 + 1] * tex11percent * aaxrem ) @@ -383,12 +357,7 @@ def pixel_renderer( for addx in xpoints: xloc = imgx + addx yloc = imgy + addy - if ( - xloc < 0.0 - or yloc < 0.0 - or xloc >= imgwidth - or yloc >= imgheight - ): + if xloc < 0.0 or yloc < 0.0 or xloc >= imgwidth or yloc >= imgheight: continue texloc = callback(Point(xloc, yloc)) @@ -496,9 +465,7 @@ def affine_line_renderer( if imgy is None: return - rowbytes = bytearray( - imgbytes[(imgy * imgwidth * 4) : ((imgy + 1) * imgwidth * 4)] - ) + rowbytes = bytearray(imgbytes[(imgy * imgwidth * 4) : ((imgy + 1) * imgwidth * 4)]) for imgx in range(imgwidth): if imgx < minx or imgx >= maxx: # No need to even consider this pixel. @@ -726,9 +693,7 @@ def perspective_line_renderer( if imgy is None: return - rowbytes = bytearray( - imgbytes[(imgy * imgwidth * 4) : ((imgy + 1) * imgwidth * 4)] - ) + rowbytes = bytearray(imgbytes[(imgy * imgwidth * 4) : ((imgy + 1) * imgwidth * 4)]) for imgx in range(imgwidth): if imgx < minx or imgx >= maxx: # No need to even consider this pixel. diff --git a/bemani/format/afp/container.py b/bemani/format/afp/container.py index 309b988..7b47063 100644 --- a/bemani/format/afp/container.py +++ b/bemani/format/afp/container.py @@ -112,16 +112,12 @@ class Texture: ], "fmt_flags": self.fmtflags, "raw": self.raw.hex(), - "compressed": self.compressed.hex() - if self.compressed is not None - else None, + "compressed": self.compressed.hex() if self.compressed is not None else None, } class TextureRegion: - def __init__( - self, textureno: int, left: int, top: int, right: int, bottom: int - ) -> None: + def __init__(self, textureno: int, left: int, top: int, right: int, bottom: int) -> None: self.textureno = textureno self.left = left self.top = top @@ -268,9 +264,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): "modern_lz": self.modern_lz, "textures": [tex.as_dict(*args, **kwargs) for tex in self.textures], "texturemap": self.texturemap.as_dict(*args, **kwargs), - "textureregion": [ - reg.as_dict(*args, **kwargs) for reg in self.texture_to_region - ], + "textureregion": [reg.as_dict(*args, **kwargs) for reg in self.texture_to_region], "regionmap": self.regionmap.as_dict(*args, **kwargs), "swfdata": [data.as_dict(*args, **kwargs) for data in self.swfdata], "swfmap": self.swfmap.as_dict(*args, **kwargs), @@ -300,9 +294,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): result = 0 for byte in bytestream: for i in range(6): - result = TXP2File.poly(result) ^ TXP2File.cap32( - (result << 1) | ((byte >> i) & 1) - ) + result = TXP2File.poly(result) ^ TXP2File.cap32((result << 1) | ((byte >> i) & 1)) return result def get_until_null(self, offset: int) -> bytes: @@ -421,15 +413,11 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x01: # List of textures that exist in the file, with pointers to their data. - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x000001 - textures; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x000001 - textures; count: {length}, offset: {hex(offset)}") for x in range(length): interesting_offset = offset + (x * 12) @@ -458,9 +446,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): ) self.add_coverage(texture_offset, 8) if deflated_size != (texture_length - 8): - raise Exception( - "We got an incorrect length for lz texture!" - ) + raise Exception("We got an incorrect length for lz texture!") self.vprint( f" {name}, length: {texture_length}, offset: {hex(texture_offset)}, deflated_size: {deflated_size}, inflated_size: {inflated_size}" ) @@ -468,9 +454,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Get the data offset. lz_data_offset = texture_offset + 8 - lz_data = self.data[ - lz_data_offset : (lz_data_offset + deflated_size) - ] + lz_data = self.data[lz_data_offset : (lz_data_offset + deflated_size)] self.add_coverage(lz_data_offset, deflated_size) # This takes forever, so skip it if we're pretending. @@ -485,19 +469,13 @@ class TXP2File(TrackedCoverage, VerboseOutput): # I'm guessing how raw textures work because I haven't seen them. # I assume they're like the above, so lets put in some asertions. if deflated_size != (texture_length - 8): - raise Exception( - "We got an incorrect length for raw texture!" - ) + raise Exception("We got an incorrect length for raw texture!") self.vprint( f" {name}, length: {texture_length}, offset: {hex(texture_offset)}, deflated_size: {deflated_size}, inflated_size: {inflated_size}" ) # Just grab the raw data. - raw_data = self.data[ - (texture_offset + 8) : ( - texture_offset + 8 + deflated_size - ) - ] + raw_data = self.data[(texture_offset + 8) : (texture_offset + 8 + deflated_size)] self.add_coverage(texture_offset, deflated_size + 8) tdxt = TDXT.fromBytes(raw_data) @@ -505,9 +483,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): raise Exception("Unexpected texture format!") if tdxt.img is None: - self.vprint( - f"Unsupported format {hex(tdxt.fmt)} for texture {name}" - ) + self.vprint(f"Unsupported format {hex(tdxt.fmt)} for texture {name}") self.textures.append( Texture( @@ -522,9 +498,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Mapping between texture index and the name of the texture. if feature_mask & 0x02: # Mapping of texture name to texture index. This is used by regions to look up textures. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -546,15 +520,11 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Mapping between individual graphics and their respective textures. # This is 10 bytes per entry. Seems to need both 0x2 (texture index) # and 0x10 (region index). - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x000008 - regions; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x000008 - regions; count: {length}, offset: {hex(offset)}") if offset != 0 and length > 0: for i in range(length): @@ -580,9 +550,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x10: # Names of the graphics regions, so we can look into the texture_to_region # mapping above. Used by shapes to find the right region offset given a name. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -601,30 +569,22 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x40: # Two unknown bytes, first is a length or a count. Secound is # an optional offset to grab another set of bytes from. - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x000040 - unknown; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x000040 - unknown; count: {length}, offset: {hex(offset)}") if offset != 0 and length > 0: for i in range(length): unk_offset = offset + (i * 16) - name_offset = struct.unpack( - f"{self.endian}I", self.data[unk_offset : (unk_offset + 4)] - )[0] + name_offset = struct.unpack(f"{self.endian}I", self.data[unk_offset : (unk_offset + 4)])[0] self.add_coverage(unk_offset, 4) # The game does some very bizarre bit-shifting. Its clear tha the first value # points at a name structure, but its not in the correct endianness. This replicates # the weird logic seen in game disassembly. - name_offset = (((name_offset >> 7) & 0x1FF) << 16) + ( - (name_offset >> 16) & 0xFFFF - ) + name_offset = (((name_offset >> 7) & 0x1FF) << 16) + ((name_offset >> 16) & 0xFFFF) if name_offset != 0: # Let's decode this until the first null. bytedata = self.get_until_null(name_offset) @@ -645,9 +605,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x80: # One unknown byte, treated as an offset. This is clearly the mapping for the parsed # structures from 0x40, but I don't know what those are. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -662,22 +620,16 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x100: # Two unknown bytes, first is a length or a count. Secound is # an optional offset to grab another set of bytes from. - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x000100 - unknown; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x000100 - unknown; count: {length}, offset: {hex(offset)}") if offset != 0 and length > 0: for i in range(length): unk_offset = offset + (i * 4) - self.unknown2.append( - Unknown2(self.data[unk_offset : (unk_offset + 4)]) - ) + self.unknown2.append(Unknown2(self.data[unk_offset : (unk_offset + 4)])) self.add_coverage(unk_offset, 4) else: self.vprint("Bit 0x000100 - unknown; NOT PRESENT") @@ -685,9 +637,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x200: # One unknown byte, treated as an offset. Almost positive its a string mapping # for the above 0x100 structure. That's how this file format appears to work. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -703,9 +653,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # One unknown byte, treated as an offset. I have no idea what this is used for, # it seems to be empty data in files that I've looked at, it doesn't go to any # structure or mapping. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -716,15 +664,11 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x800: # SWF raw data that is loaded and passed to AFP core. It is equivalent to the # afp files in an IFS container. - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x000800 - swfdata; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x000800 - swfdata; count: {length}, offset: {hex(offset)}") for x in range(length): interesting_offset = offset + (x * 12) @@ -739,23 +683,17 @@ class TXP2File(TrackedCoverage, VerboseOutput): bytedata = self.get_until_null(name_offset) self.add_coverage(name_offset, len(bytedata) + 1, unique=False) name = descramble_text(bytedata, self.text_obfuscated) - self.vprint( - f" {name}, length: {swf_length}, offset: {hex(swf_offset)}" - ) + self.vprint(f" {name}, length: {swf_length}, offset: {hex(swf_offset)}") if swf_offset != 0: - self.swfdata.append( - SWF(name, self.data[swf_offset : (swf_offset + swf_length)]) - ) + self.swfdata.append(SWF(name, self.data[swf_offset : (swf_offset + swf_length)])) self.add_coverage(swf_offset, swf_length) else: self.vprint("Bit 0x000800 - swfdata; NOT PRESENT") if feature_mask & 0x1000: # A mapping structure that allows looking up SWF data by name. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -770,15 +708,11 @@ class TXP2File(TrackedCoverage, VerboseOutput): # These are shapes as used with the SWF data above. They contain mappings between a # loaded texture shape and the region that contains data. They are equivalent to the # geo files found in an IFS container. - length, offset = struct.unpack( - f"{self.endian}II", self.data[header_offset : (header_offset + 8)] - ) + length, offset = struct.unpack(f"{self.endian}II", self.data[header_offset : (header_offset + 8)]) self.add_coverage(header_offset, 8) header_offset += 8 - self.vprint( - f"Bit 0x002000 - shapes; count: {length}, offset: {hex(offset)}" - ) + self.vprint(f"Bit 0x002000 - shapes; count: {length}, offset: {hex(offset)}") for x in range(length): shape_base_offset = offset + (x * 12) @@ -806,9 +740,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): self.shapes.append(shape) self.add_coverage(shape_offset, shape_length) - self.vprint( - f" {name}, length: {shape_length}, offset: {hex(shape_offset)}" - ) + self.vprint(f" {name}, length: {shape_length}, offset: {hex(shape_offset)}") for line in str(shape).split(os.linesep): self.vprint(f" {line}") @@ -817,9 +749,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x4000: # Mapping so that shapes can be looked up by name to get their offset. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -833,9 +763,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x8000: # One unknown byte, treated as an offset. I have no idea what this is because # the games I've looked at don't include this bit. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -850,22 +778,16 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x10000: # Included font package, BINXRPC encoded. This is basically a texture sheet with an XML # pointing at the region in the texture sheet for every renderable character. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 # I am not sure what the unknown byte is for. It always appears as # all zeros in all files I've looked at. - expect_zero, length, binxrpc_offset = struct.unpack( - f"{self.endian}III", self.data[offset : (offset + 12)] - ) + expect_zero, length, binxrpc_offset = struct.unpack(f"{self.endian}III", self.data[offset : (offset + 12)]) self.add_coverage(offset, 12) - self.vprint( - f"Bit 0x010000 - fontinfo; offset: {hex(offset)}, binxrpc offset: {hex(binxrpc_offset)}" - ) + self.vprint(f"Bit 0x010000 - fontinfo; offset: {hex(offset)}, binxrpc offset: {hex(binxrpc_offset)}") if expect_zero != 0: # If we find non-zero versions of this, then that means updating the file is @@ -873,9 +795,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): raise Exception("Expected a zero in font package header!") if binxrpc_offset != 0: - self.fontdata = self.benc.decode( - self.data[binxrpc_offset : (binxrpc_offset + length)] - ) + self.fontdata = self.benc.decode(self.data[binxrpc_offset : (binxrpc_offset + length)]) self.add_coverage(binxrpc_offset, length) else: self.fontdata = None @@ -885,9 +805,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0x20000: # This is the byteswapping headers that allow us to byteswap the SWF data before passing it # to AFP core. It is equivalent to the bsi files in an IFS container. - offset = struct.unpack( - f"{self.endian}I", self.data[header_offset : (header_offset + 4)] - )[0] + offset = struct.unpack(f"{self.endian}I", self.data[header_offset : (header_offset + 4)])[0] self.add_coverage(header_offset, 4) header_offset += 4 @@ -904,9 +822,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): f"{self.endian}III", self.data[structure_offset : (structure_offset + 12)], ) - self.vprint( - f" length: {afp_header_length}, offset: {hex(afp_header)}" - ) + self.vprint(f" length: {afp_header_length}, offset: {hex(afp_header)}") self.add_coverage(structure_offset, 12) if expect_zero != 0: @@ -914,9 +830,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # potentially unsafe as we could rewrite it incorrectly. So, let's assert! raise Exception("Expected a zero in SWF header!") - self.swfdata[i].descramble_info = self.data[ - afp_header : (afp_header + afp_header_length) - ] + self.swfdata[i].descramble_info = self.data[afp_header : (afp_header + afp_header_length)] self.add_coverage(afp_header, afp_header_length) else: self.vprint("Bit 0x020000 - swfheaders; NOT PRESENT") @@ -933,9 +847,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): if feature_mask & 0xFFF00000: # We don't know these bits at all! - raise Exception( - f"Invalid bits set in feature mask {hex(feature_mask & 0xFFF80000)}!" - ) + raise Exception(f"Invalid bits set in feature mask {hex(feature_mask & 0xFFF80000)}!") if header_offset != header_length: raise Exception("Failed to parse bitfield of header correctly!") @@ -956,9 +868,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): return data - def write_pman( - self, data: bytes, offset: int, pman: PMAN, string_offsets: Dict[str, int] - ) -> bytes: + def write_pman(self, data: bytes, offset: int, pman: PMAN, string_offsets: Dict[str, int]) -> bytes: # First, lay down the PMAN header if self.endian == "<": magic = b"PMAN" @@ -1180,9 +1090,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): body = pad(body, offset) # First, lay down pointers and length, regardless of number of entries. - bitchunks[3] = struct.pack( - f"{self.endian}II", len(self.texture_to_region), offset - ) + bitchunks[3] = struct.pack(f"{self.endian}II", len(self.texture_to_region), offset) for bounds in self.texture_to_region: body += struct.pack( @@ -1216,10 +1124,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): string_offset += len(entry1.name) + 1 # Write out the chunk itself. - body += ( - struct.pack(f"{self.endian}I", string_offsets[entry1.name]) - + entry1.data - ) + body += struct.pack(f"{self.endian}I", string_offsets[entry1.name]) + entry1.data # Now, put down the strings that were new in this chunk. body = self.write_strings(body, pending_strings) @@ -1248,9 +1153,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Now, calculate where we can put SWF data and their names. swfdata_offset = align(len(body) + (len(self.swfdata) * 12)) - string_offset = align( - swfdata_offset + sum(align(len(a.data)) for a in self.swfdata) - ) + string_offset = align(swfdata_offset + sum(align(len(a.data)) for a in self.swfdata)) swfdata = b"" # Now, lay them out. @@ -1285,9 +1188,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Now, calculate where we can put shapes and their names. shape_offset = align(len(body) + (len(self.shapes) * 12)) - string_offset = align( - shape_offset + sum(align(len(s.data)) for s in self.shapes) - ) + string_offset = align(shape_offset + sum(align(len(s.data)) for s in self.shapes)) shapedata = b"" # Now, lay them out. @@ -1438,11 +1339,7 @@ class TXP2File(TrackedCoverage, VerboseOutput): body = pad(body, offset) + texture_data # Now, update the patch location to make sure we point at the texture data. - body = ( - body[:fix_offset] - + struct.pack(f"{self.endian}I", offset) - + body[(fix_offset + 4) :] - ) + body = body[:fix_offset] + struct.pack(f"{self.endian}I", offset) + body[(fix_offset + 4) :] # Bit 0x40000 is for lz options. @@ -1501,9 +1398,9 @@ class TXP2File(TrackedCoverage, VerboseOutput): # Now, figure out if the PNG data we got is valid. sprite_img = Image.open(io.BytesIO(png_data)) - if sprite_img.width != ( - (region.right // 2) - (region.left // 2) - ) or sprite_img.height != ((region.bottom // 2) - (region.top // 2)): + if sprite_img.width != ((region.right // 2) - (region.left // 2)) or sprite_img.height != ( + (region.bottom // 2) - (region.top // 2) + ): raise Exception("Cannot update sprite with different size!") # Now, copy the data over and update the raw texture. diff --git a/bemani/format/afp/decompile.py b/bemani/format/afp/decompile.py index 8df006f..17536a5 100644 --- a/bemani/format/afp/decompile.py +++ b/bemani/format/afp/decompile.py @@ -89,9 +89,7 @@ from .util import VerboseOutput class ByteCode: # A list of bytecodes to execute. - def __init__( - self, name: Optional[str], actions: Sequence[AP2Action], end_offset: int - ) -> None: + def __init__(self, name: Optional[str], actions: Sequence[AP2Action], end_offset: int) -> None: self.name = name self.actions = list(actions) self.start_offset = self.actions[0].offset if actions else None @@ -104,9 +102,7 @@ class ByteCode: if self.name: opar = "{" cpar = "}" - code = ( - f"{self.name}(){os.linesep}{opar}{os.linesep}{code}{os.linesep}{cpar}" - ) + code = f"{self.name}(){os.linesep}{opar}{os.linesep}{code}{os.linesep}{cpar}" return code def as_dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: @@ -143,13 +139,9 @@ class ControlFlow: def is_last(self, offset: int) -> bool: return self.end == (offset + 1) - def split( - self, offset: int, link: bool = False - ) -> Tuple["ControlFlow", "ControlFlow"]: + def split(self, offset: int, link: bool = False) -> Tuple["ControlFlow", "ControlFlow"]: if not self.contains(offset): - raise Exception( - f"Logic error, this ControlFlow does not contain offset {offset}" - ) + raise Exception(f"Logic error, this ControlFlow does not contain offset {offset}") # First, make the second half that the first half will point to. second = ControlFlow( @@ -212,9 +204,7 @@ class MaybeStackEntry(Expression): return f"MaybeStackEntry({self.parent_stack_id})" def render(self, parent_prefix: str, nested: bool = False) -> str: - raise Exception( - "Logic error, a MaybeStackEntry should never make it to the render stage!" - ) + raise Exception("Logic error, a MaybeStackEntry should never make it to the render stage!") class MultiAction(ConvertedAction): @@ -262,9 +252,7 @@ class IntermediateIf(ConvertedAction): ] ) else: - return os.linesep.join( - [f"if <{self.parent_action}> {{", os.linesep.join(true_entries), "}"] - ) + return os.linesep.join([f"if <{self.parent_action}> {{", os.linesep.join(true_entries), "}"]) class ByteCodeChunk: @@ -318,9 +306,7 @@ class Loop: self.id = id # Calculate predecessors (who points into it) and successors (who we point out of). - ided_chunks: Dict[int, ArbitraryCodeChunk] = { - chunk.id: chunk for chunk in chunks - } + ided_chunks: Dict[int, ArbitraryCodeChunk] = {chunk.id: chunk for chunk in chunks} self.previous_chunks: List[int] = [] self.next_chunks: List[int] = [] @@ -416,9 +402,7 @@ class InsertionLocation(Statement): return f"" def render(self, prefix: str, verbose: bool = False) -> List[str]: - raise Exception( - "Logic error, an InsertionLocation should never make it to the render stage!" - ) + raise Exception("Logic error, an InsertionLocation should never make it to the render stage!") class OriginalCallLocation(Statement): @@ -429,9 +413,7 @@ class OriginalCallLocation(Statement): return f"" def render(self, prefix: str, verbose: bool = False) -> List[str]: - raise Exception( - "Logic error, an InsertionLocation should never make it to the render stage!" - ) + raise Exception("Logic error, an InsertionLocation should never make it to the render stage!") class BitVector: @@ -449,17 +431,13 @@ class BitVector: def setBit(self, bit: int) -> "BitVector": if bit < 0 or bit >= len(self.__bits): - raise Exception( - f"Logic error, trying to set bit {bit} of a bitvector length {len(self.__bits)}!" - ) + raise Exception(f"Logic error, trying to set bit {bit} of a bitvector length {len(self.__bits)}!") self.__bits[bit] = True return self def clearBit(self, bit: int) -> "BitVector": if bit < 0 or bit >= len(self.__bits): - raise Exception( - f"Logic error, trying to set bit {bit} of a bitvector length {len(self.__bits)}!" - ) + raise Exception(f"Logic error, trying to set bit {bit} of a bitvector length {len(self.__bits)}!") self.__bits[bit] = False return self @@ -520,9 +498,7 @@ class ByteCodeDecompiler(VerboseOutput): raise Exception("Call decompile() first before retrieving statements!") return self.__statements - def _graph_control_flow( - self, bytecode: ByteCode - ) -> Tuple[List[ByteCodeChunk], Dict[int, int]]: + def _graph_control_flow(self, bytecode: ByteCode) -> Tuple[List[ByteCodeChunk], Dict[int, int]]: # Start by assuming that the whole bytecode never directs flow. This is, confusingly, # indexed by AP2Action offset, not by actual bytecode offset, so we can avoid the # prickly problem of opcodes that take more than one byte in the data. @@ -542,9 +518,7 @@ class ByteCodeDecompiler(VerboseOutput): if cf.contains(opcodeno): return start - raise Exception( - f"Logic error, offset {opcodeno} somehow not in our control flow graph!" - ) + raise Exception(f"Logic error, offset {opcodeno} somehow not in our control flow graph!") # Now, walk the entire bytecode, and every control flow point split the graph at that point. for i, action in enumerate(bytecode.actions): @@ -562,9 +536,7 @@ class ByteCodeDecompiler(VerboseOutput): first, second = flows[current_action_flow].split(next_action) first.next_flow = [end] - self.vprint( - f"{action} action split {flows[current_action_flow]} into {first}, {second}" - ) + self.vprint(f"{action} action split {flows[current_action_flow]} into {first}, {second}") flows[current_action_flow] = first flows[next_action] = second @@ -576,9 +548,7 @@ class ByteCodeDecompiler(VerboseOutput): # link it to the end. flows[current_action_flow].next_flow = [end] - self.vprint( - f"{action} action repointed {flows[current_action_flow]} to end" - ) + self.vprint(f"{action} action repointed {flows[current_action_flow]} to end") elif action.opcode == AP2Action.JUMP: # Unconditional control flow redirection after this, we should split the # section if necessary and point this section at the new offset. @@ -593,9 +563,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.jump_offset == bytecode.end_offset: dest_action = end else: - raise Exception( - f"{action} jumps to an opcode that doesn't exist!" - ) + raise Exception(f"{action} jumps to an opcode that doesn't exist!") # If the destination action flow already starts with the jump offset, # then we're good, we just need to point our current split at this new @@ -603,13 +571,9 @@ class ByteCodeDecompiler(VerboseOutput): # that flow so we can point to the opcode directly. dest_action_flow = find(dest_action) if not flows[dest_action_flow].is_first(dest_action): - first, second = flows[dest_action_flow].split( - dest_action, link=True - ) + first, second = flows[dest_action_flow].split(dest_action, link=True) - self.vprint( - f"{action} action required split of {flows[dest_action_flow]} into {first, second}" - ) + self.vprint(f"{action} action required split of {flows[dest_action_flow]} into {first, second}") flows[dest_action_flow] = first flows[dest_action] = second @@ -626,9 +590,7 @@ class ByteCodeDecompiler(VerboseOutput): first, second = flows[current_action_flow].split(next_action) first.next_flow = [dest_action_flow] - self.vprint( - f"{action} action split {flows[current_action_flow]} into {first}, {second}" - ) + self.vprint(f"{action} action split {flows[current_action_flow]} into {first}, {second}") flows[current_action_flow] = first flows[next_action] = second @@ -639,9 +601,7 @@ class ByteCodeDecompiler(VerboseOutput): # link it to the end. flows[current_action_flow].next_flow = [dest_action_flow] - self.vprint( - f"{action} action repointed {flows[current_action_flow]} to new chunk" - ) + self.vprint(f"{action} action repointed {flows[current_action_flow]} to new chunk") elif action.opcode == AP2Action.IF: # Conditional control flow redirection after this, we should split the # section if necessary and point this section at the new offset as well @@ -657,9 +617,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.jump_if_true_offset == bytecode.end_offset: dest_action = end else: - raise Exception( - f"{action} conditionally jumps to an opcode that doesn't exist!" - ) + raise Exception(f"{action} conditionally jumps to an opcode that doesn't exist!") # If the destination action flow already starts with the jump offset, # then we're good, we just need to point our current split at this new @@ -667,13 +625,9 @@ class ByteCodeDecompiler(VerboseOutput): # that flow so we can point to the opcode directly. dest_action_flow = find(dest_action) if not flows[dest_action_flow].is_first(dest_action): - first, second = flows[dest_action_flow].split( - dest_action, link=True - ) + first, second = flows[dest_action_flow].split(dest_action, link=True) - self.vprint( - f"{action} action required split of {flows[dest_action_flow]} into {first, second}" - ) + self.vprint(f"{action} action required split of {flows[dest_action_flow]} into {first, second}") flows[dest_action_flow] = first flows[dest_action] = second @@ -690,9 +644,7 @@ class ByteCodeDecompiler(VerboseOutput): first, second = flows[current_action_flow].split(next_action) first.next_flow = [next_action, dest_action_flow] - self.vprint( - f"{action} action split {flows[current_action_flow]} into {first}, {second}" - ) + self.vprint(f"{action} action split {flows[current_action_flow]} into {first}, {second}") flows[current_action_flow] = first flows[next_action] = second @@ -706,9 +658,7 @@ class ByteCodeDecompiler(VerboseOutput): dest_action_flow, ] - self.vprint( - f"{action} action repointed {flows[current_action_flow]} to new chunk" - ) + self.vprint(f"{action} action repointed {flows[current_action_flow]} to new chunk") elif action.opcode == AP2Action.IF2: # We don't emit this anymore, so this is a problem. raise Exception( @@ -754,15 +704,9 @@ class ByteCodeDecompiler(VerboseOutput): # Now, eliminate any dead code since it will trip us up later. Chunk ID is still the # offset of the first entry in the chunk since we haven't assigned IDs yet. while True: - dead_chunk_ids = { - c.id - for c in chunks - if not c.previous_chunks and c.id != bytecode.start_offset - } + dead_chunk_ids = {c.id for c in chunks if not c.previous_chunks and c.id != bytecode.start_offset} if dead_chunk_ids: - self.vprint( - f"Elimitating dead code chunks {', '.join(str(d) for d in dead_chunk_ids)}" - ) + self.vprint(f"Elimitating dead code chunks {', '.join(str(d) for d in dead_chunk_ids)}") chunks = [c for c in chunks if c.id not in dead_chunk_ids] for chunk in chunks: @@ -772,9 +716,7 @@ class ByteCodeDecompiler(VerboseOutput): raise Exception( f"Logic error, chunk ID {chunk.id} points at a dead code chunk we're eliminating!" ) - chunk.previous_chunks = [ - c for c in chunk.previous_chunks if c not in dead_chunk_ids - ] + chunk.previous_chunks = [c for c in chunk.previous_chunks if c not in dead_chunk_ids] else: break @@ -809,9 +751,7 @@ class ByteCodeDecompiler(VerboseOutput): chunk.previous_chunks = [offset_to_id[c] for c in chunk.previous_chunks] # Add the "return" chunk now that we've converted everything. - chunks.append( - ByteCodeChunk(end_chunk_id, [], [], previous_chunks=end_previous_chunks) - ) + chunks.append(ByteCodeChunk(end_chunk_id, [], [], previous_chunks=end_previous_chunks)) # Verify a few invariants about the tree we just created. num_start_chunks = 0 @@ -852,20 +792,14 @@ class ByteCodeDecompiler(VerboseOutput): f"Chunk ID {chunk.id} has two next chunks but control flow action is not an if statement!" ) if len(chunk.next_chunks) > 2: - raise Exception( - f"Chunk ID {chunk.id} has more than two next chunks!" - ) + raise Exception(f"Chunk ID {chunk.id} has more than two next chunks!") # Num start chunks can be 0 (if the start chunk is a loop beginning) or 1 (if its a normal chunk). if num_start_chunks > 1: - raise Exception( - f"Found {num_start_chunks} start chunks but expecting at most 1!" - ) + raise Exception(f"Found {num_start_chunks} start chunks but expecting at most 1!") # Num end chunks can only be 1 as we created an artificial end chunk. if num_end_chunks != 1: - raise Exception( - f"Found {num_end_chunks} end chunks but expecting exactly 1!" - ) + raise Exception(f"Found {num_end_chunks} end chunks but expecting exactly 1!") # Now that we're satisfied with the tree we created, return it. return (chunks, offset_to_id) @@ -885,14 +819,10 @@ class ByteCodeDecompiler(VerboseOutput): raise Exception("Logic error, no start block found!") return start_id - def __compute_dominators( - self, start_id: int, chunks: Sequence[ByteCodeChunk] - ) -> Dict[int, Set[int]]: + def __compute_dominators(self, start_id: int, chunks: Sequence[ByteCodeChunk]) -> Dict[int, Set[int]]: # Compute dominators recursively chunklen = len(chunks) - dominators: Dict[int, BitVector] = { - chunk.id: BitVector(chunklen, init=True) for chunk in chunks - } + dominators: Dict[int, BitVector] = {chunk.id: BitVector(chunklen, init=True) for chunk in chunks} dominators[start_id].setAllBitsTo(False).setBit(start_id) # Verify that the chunk IDs are contiguous. Otherwise this algorithm fails, since it @@ -929,20 +859,14 @@ class ByteCodeDecompiler(VerboseOutput): header_chunks = [c for c in loop.chunks if c.id == loop.id] if len(header_chunks) != 1: # Should never happen, only one should match ID. - raise Exception( - "Logic error, didn't find the header chunk based on Loop ID!" - ) + raise Exception("Logic error, didn't find the header chunk based on Loop ID!") header_chunk = header_chunks[0] # Identify external jumps from the header. - break_points = [ - i for i in header_chunk.next_chunks if i not in internal_jump_points - ] + break_points = [i for i in header_chunk.next_chunks if i not in internal_jump_points] if len(break_points) > 1: # We should not have two exits here, if so this isn't a loop! - raise Exception( - "Logic error, loop has more than one next chunk to jump to on break!" - ) + raise Exception("Logic error, loop has more than one next chunk to jump to on break!") if not break_points: # This might be possible, but I don't know how to deal with it. raise Exception("Logic error, loop has no chunk to jump to on break!") @@ -951,9 +875,7 @@ class ByteCodeDecompiler(VerboseOutput): break_point = break_points[0] continue_point = header_chunk.id - self.vprint( - f"Loop ID {loop.id} breaks to {break_point} and continues to {continue_point}" - ) + self.vprint(f"Loop ID {loop.id} breaks to {break_point} and continues to {continue_point}") # Now, go through each chunk, identify whether it has an if, and fix up the # if statements. @@ -981,36 +903,26 @@ class ByteCodeDecompiler(VerboseOutput): next_chunk = chunk.next_chunks[0] if next_chunk == break_point: - self.vprint( - "Converting jump to loop break into break statement." - ) + self.vprint("Converting jump to loop break into break statement.") chunk.actions[-1] = BreakStatement() chunk.next_chunks = [] elif next_chunk == continue_point: - self.vprint( - "Converting jump to loop continue into continue statement." - ) + self.vprint("Converting jump to loop continue into continue statement.") chunk.actions[-1] = ContinueStatement() chunk.next_chunks = [] elif next_chunk not in internal_jump_points: if next_chunk == offset_map[self.bytecode.end_offset]: - self.vprint( - "Converting jump to external point into return statement." - ) + self.vprint("Converting jump to external point into return statement.") chunk.actions[-1] = NullReturnStatement() else: - self.vprint( - "Converting jump to external point into goto statement." - ) + self.vprint("Converting jump to external point into goto statement.") chunk.actions[-1] = GotoStatement(next_chunk) chunk.next_chunks = [] continue if last_action.opcode == AP2Action.IF: # Calculate true and false jump points. - true_jump_point, false_jump_point = self.__get_jump_points( - chunk, offset_map - ) + true_jump_point, false_jump_point = self.__get_jump_points(chunk, offset_map) end_offset = offset_map[self.bytecode.end_offset] # Calculate true and false jump points, see if they are break/continue/goto. @@ -1020,67 +932,39 @@ class ByteCodeDecompiler(VerboseOutput): # continue or return statement). true_action: Optional[Statement] = None if true_jump_point == break_point: - self.vprint( - "Converting jump if true to loop break into break statement." - ) + self.vprint("Converting jump if true to loop break into break statement.") true_action = BreakStatement() - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != true_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != true_jump_point] elif true_jump_point == continue_point: - self.vprint( - "Converting jump if true to loop continue into continue statement." - ) + self.vprint("Converting jump if true to loop continue into continue statement.") true_action = ContinueStatement() - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != true_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != true_jump_point] elif true_jump_point not in internal_jump_points: if true_jump_point == end_offset: - self.vprint( - "Converting jump if true to external point into return statement." - ) + self.vprint("Converting jump if true to external point into return statement.") true_action = NullReturnStatement() else: - self.vprint( - "Converting jump if true to external point into goto statement." - ) + self.vprint("Converting jump if true to external point into goto statement.") true_action = GotoStatement(true_jump_point) - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != true_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != true_jump_point] false_action: Optional[Statement] = None if false_jump_point == break_point: - self.vprint( - "Converting jump if false to loop break into break statement." - ) + self.vprint("Converting jump if false to loop break into break statement.") false_action = BreakStatement() - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != false_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != false_jump_point] elif false_jump_point == continue_point: - self.vprint( - "Converting jump if false to loop continue into continue statement." - ) + self.vprint("Converting jump if false to loop continue into continue statement.") false_action = ContinueStatement() - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != false_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != false_jump_point] elif false_jump_point not in internal_jump_points: if false_jump_point == end_offset: - self.vprint( - "Converting jump if false to external point into return statement." - ) + self.vprint("Converting jump if false to external point into return statement.") false_action = NullReturnStatement() else: - self.vprint( - "Converting jump if false to external point into goto statement." - ) + self.vprint("Converting jump if false to external point into goto statement.") false_action = GotoStatement(false_jump_point) - chunk.next_chunks = [ - n for n in chunk.next_chunks if n != false_jump_point - ] + chunk.next_chunks = [n for n in chunk.next_chunks if n != false_jump_point] if true_action is None and false_action is None: # This is an internal-only if statement, we don't care. We will handle it in @@ -1099,13 +983,9 @@ class ByteCodeDecompiler(VerboseOutput): AP2Action.END, ]: if len(chunk.next_chunks) != 1: - raise Exception( - f"Logic error, chunkd ID {chunk.id} returns, throws or end to multiple blocks!" - ) + raise Exception(f"Logic error, chunkd ID {chunk.id} returns, throws or end to multiple blocks!") if chunk.next_chunks[0] != offset_map[self.bytecode.end_offset]: - raise Exception( - f"Expected chunk ID {chunk.id} to jump to return block but jumped elsewhere!" - ) + raise Exception(f"Expected chunk ID {chunk.id} to jump to return block but jumped elsewhere!") # We will convert this later. self.vprint("Severing link to return address.") chunk.next_chunks = [] @@ -1120,23 +1000,14 @@ class ByteCodeDecompiler(VerboseOutput): if isinstance(chunk, ByteCodeChunk): last_action = chunk.actions[-1] if isinstance(last_action, AP2Action): - if ( - last_action.opcode == AP2Action.IF - and len(chunk.next_chunks) != 2 - ): - raise Exception( - f"Somehow messed up the next pointers on if statement in chunk ID {chunk.id}!" - ) - if ( - last_action.opcode == AP2Action.JUMP - and len(chunk.next_chunks) != 1 - ): + if last_action.opcode == AP2Action.IF and len(chunk.next_chunks) != 2: + raise Exception(f"Somehow messed up the next pointers on if statement in chunk ID {chunk.id}!") + if last_action.opcode == AP2Action.JUMP and len(chunk.next_chunks) != 1: raise Exception( f"Somehow messed up the next pointers on control flow statement in chunk ID {chunk.id}!" ) if ( - last_action.opcode - in [AP2Action.RETURN, AP2Action.THROW, AP2Action.END] + last_action.opcode in [AP2Action.RETURN, AP2Action.THROW, AP2Action.END] and len(chunk.next_chunks) != 0 ): raise Exception( @@ -1163,9 +1034,7 @@ class ByteCodeDecompiler(VerboseOutput): dominators: Dict[int, Set[int]], offset_map: Dict[int, int], ) -> List[Union[ByteCodeChunk, Loop]]: - chunks_by_id: Dict[int, Union[ByteCodeChunk, Loop]] = { - chunk.id: chunk for chunk in chunks - } + chunks_by_id: Dict[int, Union[ByteCodeChunk, Loop]] = {chunk.id: chunk for chunk in chunks} # Go through and gather up all loops in the chunks. loops: Dict[int, Set[int]] = {} @@ -1192,9 +1061,7 @@ class ByteCodeDecompiler(VerboseOutput): blocks.add(predecessor) blocks_to_examine.append(predecessor) - self.vprint( - f"Found loop with header {header} and blocks {', '.join(str(b) for b in blocks)}." - ) + self.vprint(f"Found loop with header {header} and blocks {', '.join(str(b) for b in blocks)}.") # Now, make sure we scoop up any remaining if/else bodies not found in the backwards walk. changed: bool = True @@ -1208,26 +1075,18 @@ class ByteCodeDecompiler(VerboseOutput): continue add_id: Optional[int] = None for cid, doms in dominators.items(): - if ( - dominators[b] == doms - {cid} - and cid not in blocks - and cid != header - ): + if dominators[b] == doms - {cid} and cid not in blocks and cid != header: add_id = cid break if add_id is not None: - self.vprint( - f"Chunk {cid} should be included in loop list!" - ) + self.vprint(f"Chunk {cid} should be included in loop list!") blocks.add(add_id) changed = True break # We found a loop! if header in loops: - raise Exception( - f"Logic error, loop with header {header} was already found!" - ) + raise Exception(f"Logic error, loop with header {header} was already found!") loops[header] = blocks # Now, we need to reduce our list of chunks down to non-loops only. We do this @@ -1253,9 +1112,7 @@ class ByteCodeDecompiler(VerboseOutput): else: # This loop does not contain any loops of its own. It is safe to # convert. - self.vprint( - f"Converting loop with header {header} and blocks {', '.join(str(b) for b in blocks)}." - ) + self.vprint(f"Converting loop with header {header} and blocks {', '.join(str(b) for b in blocks)}.") new_loop = Loop(header, [chunks_by_id[i] for i in blocks]) # Eliminate jumps that are to the beginning/end of the loop to @@ -1264,9 +1121,7 @@ class ByteCodeDecompiler(VerboseOutput): # to a break/continue/goto. new_loop = self.__analyze_loop_jumps(new_loop, offset_map) if len(new_loop.next_chunks) != 1: - raise Exception( - f"Newly created loop ID {new_loop.id} has more than one exit point!" - ) + raise Exception(f"Newly created loop ID {new_loop.id} has more than one exit point!") chunks_by_id[header] = new_loop # These blocks are now part of the loop, so we need to remove them @@ -1277,17 +1132,14 @@ class ByteCodeDecompiler(VerboseOutput): if delete_header is None: # We must find at LEAST one loop that has no inner loops of its own. - raise Exception( - "Logic error, we found no fixable loops, yet have at least one loop to fix up!" - ) + raise Exception("Logic error, we found no fixable loops, yet have at least one loop to fix up!") # Remove this loop from the processing list del loops[delete_header] # Go through and remove the rest of the chunks from the rest of the loops loops = { - header: {block for block in blocks if block not in delete_blocks} - for (header, blocks) in loops.items() + header: {block for block in blocks if block not in delete_blocks} for (header, blocks) in loops.items() } # Also remove the rest of the chunks from our IDed chunks as they are part of this loop now. @@ -1299,9 +1151,7 @@ class ByteCodeDecompiler(VerboseOutput): for nextid in chunk_or_loop.next_chunks: if nextid in delete_blocks: # Woah, we point at a chunk inside this loop that isn't the header! - raise Exception( - f"Logic error, chunkd ID {chunk_id} points into loop ID {delete_header} body!" - ) + raise Exception(f"Logic error, chunkd ID {chunk_id} points into loop ID {delete_header} body!") # Update our master list of chunks we deleted. deleted_chunks.update(delete_blocks) @@ -1315,9 +1165,7 @@ class ByteCodeDecompiler(VerboseOutput): ) return updated_chunks - def __get_jump_points( - self, chunk: ByteCodeChunk, offset_map: Dict[int, int] - ) -> Tuple[int, int]: + def __get_jump_points(self, chunk: ByteCodeChunk, offset_map: Dict[int, int]) -> Tuple[int, int]: action = chunk.actions[-1] if isinstance(action, IfAction): @@ -1335,13 +1183,9 @@ class ByteCodeDecompiler(VerboseOutput): return true_jump_point, false_jump_point else: - raise Exception( - f"Logic error, expecting JumpAction but got {action} in chunk {chunk.id}!" - ) + raise Exception(f"Logic error, expecting JumpAction but got {action} in chunk {chunk.id}!") - def __break_graph( - self, chunks: Sequence[Union[ByteCodeChunk, Loop]], offset_map: Dict[int, int] - ) -> None: + def __break_graph(self, chunks: Sequence[Union[ByteCodeChunk, Loop]], offset_map: Dict[int, int]) -> None: for chunk in chunks: if chunk.id == offset_map[self.bytecode.end_offset]: # Don't examine the sentinel we keep around as a jump point for returns. @@ -1352,9 +1196,7 @@ class ByteCodeDecompiler(VerboseOutput): # At this point, we know chunk.chunks is a Union[ByteCodeChunk, Loop] because we haven't run # any if detection yet. - self.__break_graph( - cast(List[Union[ByteCodeChunk, Loop]], chunk.chunks), offset_map - ) + self.__break_graph(cast(List[Union[ByteCodeChunk, Loop]], chunk.chunks), offset_map) else: # Examine the last instruction. last_action = chunk.actions[-1] @@ -1366,42 +1208,29 @@ class ByteCodeDecompiler(VerboseOutput): ]: # The last action already dictates what we should do here. Break # the chain at this point. - self.vprint( - f"Breaking chain on {chunk.id} because it is a {last_action}." - ) + self.vprint(f"Breaking chain on {chunk.id} because it is a {last_action}.") chunk.next_chunks = [] - elif ( - len(chunk.next_chunks) == 1 - and chunk.next_chunks[0] == offset_map[self.bytecode.end_offset] - ): + elif len(chunk.next_chunks) == 1 and chunk.next_chunks[0] == offset_map[self.bytecode.end_offset]: # The jump point for this is the end of the function. If it is a jump, # then we should replace it with a return. If it is not a jump, we should # add a return. if last_action.opcode == AP2Action.JUMP: - self.vprint( - f"Converting jump to end of code in {chunk.id} into a null return." - ) + self.vprint(f"Converting jump to end of code in {chunk.id} into a null return.") chunk.actions[-1] = NullReturnStatement() else: if last_action.opcode == AP2Action.IF: raise Exception( f"Logic error, unexpected if statement with only one successor in {chunk.id}!" ) - self.vprint( - f"Converting fall-through to end of code in {chunk.id} into a null return." - ) + self.vprint(f"Converting fall-through to end of code in {chunk.id} into a null return.") chunk.actions.append(NullReturnStatement()) chunk.next_chunks = [] elif len(chunk.next_chunks) == 2: if last_action.opcode != AP2Action.IF: - raise Exception( - f"Logic error, expected if statement with two successors in {chunk.id}!" - ) + raise Exception(f"Logic error, expected if statement with two successors in {chunk.id}!") # This is an if statement, let's see if any of the arms point to a return. - true_jump_point, false_jump_point = self.__get_jump_points( - chunk, offset_map - ) + true_jump_point, false_jump_point = self.__get_jump_points(chunk, offset_map) end_offset = offset_map[self.bytecode.end_offset] # It's possible for the true and false jump point to be equal, if the code being @@ -1413,9 +1242,7 @@ class ByteCodeDecompiler(VerboseOutput): f"Converting jump if true to external point into return statement in {chunk.id}." ) true_action = NullReturnStatement() - chunk.next_chunks = [ - c for c in chunk.next_chunks if c != true_jump_point - ] + chunk.next_chunks = [c for c in chunk.next_chunks if c != true_jump_point] false_action: Optional[Statement] = None if false_jump_point == end_offset: @@ -1423,9 +1250,7 @@ class ByteCodeDecompiler(VerboseOutput): f"Converting jump if false to external point into return statement in {chunk.id}." ) false_action = NullReturnStatement() - chunk.next_chunks = [ - c for c in chunk.next_chunks if c != false_jump_point - ] + chunk.next_chunks = [c for c in chunk.next_chunks if c != false_jump_point] if true_action or false_action: chunk.actions[-1] = IntermediateIf( @@ -1457,11 +1282,7 @@ class ByteCodeDecompiler(VerboseOutput): # goto/return/throw statements as they should be treated the same as not finding an # end. new_candidates.extend( - [ - c - for c in chunks_by_id[candidate].next_chunks - if c not in visited and c in chunks_by_id - ] + [c for c in chunks_by_id[candidate].next_chunks if c not in visited and c in chunks_by_id] ) candidates = new_candidates @@ -1481,13 +1302,7 @@ class ByteCodeDecompiler(VerboseOutput): for candidate in candidates: # We can't take the same shortcut here as above, as we are trying to ask the question # of what's the shallowest successor, not color them in. - new_candidates.extend( - [ - c - for c in chunks_by_id[candidate].next_chunks - if c in chunks_by_id - ] - ) + new_candidates.extend([c for c in chunks_by_id[candidate].next_chunks if c in chunks_by_id]) candidates = new_candidates # If we didn't find a successor, that means one of the control paths leads to end of execution. @@ -1550,9 +1365,7 @@ class ByteCodeDecompiler(VerboseOutput): chunks: Sequence[ArbitraryCodeChunk], offset_map: Dict[int, int], ) -> List[ArbitraryCodeChunk]: - chunks_by_id: Dict[int, ArbitraryCodeChunk] = { - chunk.id: chunk for chunk in chunks - } + chunks_by_id: Dict[int, ArbitraryCodeChunk] = {chunk.id: chunk for chunk in chunks} cur_id = start_id self.vprint(f"Separating if statements out of graph starting at {start_id}") @@ -1561,20 +1374,14 @@ class ByteCodeDecompiler(VerboseOutput): cur_chunk = chunks_by_id[cur_id] if isinstance(cur_chunk, Loop): self.vprint(f"Examining loop {cur_chunk.id} body for if statements...") - cur_chunk.chunks = self.__separate_ifs( - cur_chunk.id, None, cur_chunk.chunks, offset_map - ) - self.vprint( - f"Finished examining loop {cur_chunk.id} body for if statements..." - ) + cur_chunk.chunks = self.__separate_ifs(cur_chunk.id, None, cur_chunk.chunks, offset_map) + self.vprint(f"Finished examining loop {cur_chunk.id} body for if statements...") # Filter out anything pointing at the end chunk, since we know that's where we will end up # when we leave this if statement anyway. Don't do this for if statements as we need to # preserve the jump point in that case. if len(chunks_by_id[cur_id].next_chunks) == 1: - chunks_by_id[cur_id].next_chunks = [ - c for c in chunks_by_id[cur_id].next_chunks if c != end_id - ] + chunks_by_id[cur_id].next_chunks = [c for c in chunks_by_id[cur_id].next_chunks if c != end_id] if not chunks_by_id[cur_id].next_chunks: # We're done! @@ -1588,9 +1395,7 @@ class ByteCodeDecompiler(VerboseOutput): if next_id not in chunks_by_id: # We need to go to the next chunk, but we don't own it. Convert it to a goto. if isinstance(cur_chunk, Loop): - self.vprint( - f"Loop ID {cur_id} needs a goto outside of this if." - ) + self.vprint(f"Loop ID {cur_id} needs a goto outside of this if.") cur_chunk.post_statements.append(GotoStatement(next_id)) chunks_by_id[cur_id].next_chunks = [] break @@ -1604,9 +1409,7 @@ class ByteCodeDecompiler(VerboseOutput): last_action = cur_chunk.actions[-1] if isinstance(last_action, IfAction): - raise Exception( - f"Logic error, IfAction with only one child in chunk {cur_chunk}!" - ) + raise Exception(f"Logic error, IfAction with only one child in chunk {cur_chunk}!") next_id = chunks_by_id[cur_id].next_chunks[0] if isinstance(last_action, AP2Action) and last_action.opcode in [ @@ -1624,9 +1427,7 @@ class ByteCodeDecompiler(VerboseOutput): else: if next_id not in chunks_by_id: # We need to go to the next chunk, but we don't own it. Convert it to a goto. - self.vprint( - f"Chunk ID {cur_id} needs a goto outside of this if." - ) + self.vprint(f"Chunk ID {cur_id} needs a goto outside of this if.") cur_chunk.actions.append(GotoStatement(next_id)) chunks_by_id[cur_id].next_chunks = [] break @@ -1649,16 +1450,12 @@ class ByteCodeDecompiler(VerboseOutput): last_action = cur_chunk.actions[-1] if not isinstance(last_action, IfAction): # This needs, again, to be an if statement. - raise Exception( - "Logic error, only IfActions can have multiple successors in chunk {cur_chunk.id}!" - ) + raise Exception("Logic error, only IfActions can have multiple successors in chunk {cur_chunk.id}!") # This should be an if statement. Figure out if it is an if-else or an # if, and if both branches return. if_end = self.__find_shallowest_successor(cur_id, chunks_by_id) - true_jump_point, false_jump_point = self.__get_jump_points( - cur_chunk, offset_map - ) + true_jump_point, false_jump_point = self.__get_jump_points(cur_chunk, offset_map) if true_jump_point == false_jump_point: # This is an optimized-away if statement, render it out as an empty intermediate If # and set the jump point to the next location. @@ -1687,12 +1484,8 @@ class ByteCodeDecompiler(VerboseOutput): true_chunks: List[ArbitraryCodeChunk] = [] if true_jump_point not in chunks_by_id and true_jump_point != if_end: - self.vprint( - f"If statement true jump point {true_jump_point} is a goto!" - ) - true_chunks.append( - ByteCodeChunk(self.__goto_body_id, [GotoStatement(true_jump_point)]) - ) + self.vprint(f"If statement true jump point {true_jump_point} is a goto!") + true_chunks.append(ByteCodeChunk(self.__goto_body_id, [GotoStatement(true_jump_point)])) self.__goto_body_id -= 1 elif true_jump_point not in {if_end, end_id}: self.vprint( @@ -1700,12 +1493,8 @@ class ByteCodeDecompiler(VerboseOutput): ) # First, grab all the chunks in this if statement body. - true_chunks = self.__gather_chunks( - true_jump_point, if_end, chunks_by_id - ) - self.vprint( - f"True chunks are {', '.join(str(c.id) for c in true_chunks)}" - ) + true_chunks = self.__gather_chunks(true_jump_point, if_end, chunks_by_id) + self.vprint(f"True chunks are {', '.join(str(c.id) for c in true_chunks)}") # Delete these chunks from our chunk mapping since we're putting them in an if body. for chunk in true_chunks: @@ -1721,14 +1510,8 @@ class ByteCodeDecompiler(VerboseOutput): false_chunks: List[ArbitraryCodeChunk] = [] if false_jump_point not in chunks_by_id and false_jump_point != if_end: - self.vprint( - f"If statement false jump point {false_jump_point} is a goto!" - ) - false_chunks.append( - ByteCodeChunk( - self.__goto_body_id, [GotoStatement(false_jump_point)] - ) - ) + self.vprint(f"If statement false jump point {false_jump_point} is a goto!") + false_chunks.append(ByteCodeChunk(self.__goto_body_id, [GotoStatement(false_jump_point)])) self.__goto_body_id -= 1 elif false_jump_point not in {if_end, end_id}: self.vprint( @@ -1736,12 +1519,8 @@ class ByteCodeDecompiler(VerboseOutput): ) # First, grab all the chunks in this if statement body. - false_chunks = self.__gather_chunks( - false_jump_point, if_end, chunks_by_id - ) - self.vprint( - f"False chunks are {', '.join(str(c.id) for c in false_chunks)}" - ) + false_chunks = self.__gather_chunks(false_jump_point, if_end, chunks_by_id) + self.vprint(f"False chunks are {', '.join(str(c.id) for c in false_chunks)}") # Delete these chunks from our chunk mapping since we're putting them in an if body. for chunk in false_chunks: @@ -1767,12 +1546,8 @@ class ByteCodeDecompiler(VerboseOutput): # Add a new if body that this current chunk points to. At this point, chunks_by_id contains # none of the chunks in the true or false bodies of the if, so we add it back to the graph # in the form of an IfBody. - self.vprint( - f"Created new IfBody for chunk {cur_id} to point at, ending at {if_id}" - ) - chunks_by_id[if_id] = IfBody( - if_id, true_chunks, false_chunks, if_end, cur_id - ) + self.vprint(f"Created new IfBody for chunk {cur_id} to point at, ending at {if_id}") + chunks_by_id[if_id] = IfBody(if_id, true_chunks, false_chunks, if_end, cur_id) chunks_by_id[cur_id].next_chunks = [if_id] if if_end is not None: @@ -1782,19 +1557,13 @@ class ByteCodeDecompiler(VerboseOutput): # This if statement encompases all the rest of the statements, we're done. break - self.vprint( - f"Finished separating if statements out of graph starting at {start_id}" - ) + self.vprint(f"Finished separating if statements out of graph starting at {start_id}") return [c for _, c in chunks_by_id.items()] - def __check_graph( - self, start_id: int, chunks: Sequence[ArbitraryCodeChunk] - ) -> List[ArbitraryCodeChunk]: + def __check_graph(self, start_id: int, chunks: Sequence[ArbitraryCodeChunk]) -> List[ArbitraryCodeChunk]: # Recursively go through and verify that all entries to the graph have only one link. # Also, clean up the graph. - chunks_by_id: Dict[int, ArbitraryCodeChunk] = { - chunk.id: chunk for chunk in chunks - } + chunks_by_id: Dict[int, ArbitraryCodeChunk] = {chunk.id: chunk for chunk in chunks} new_chunks: List[ArbitraryCodeChunk] = [] while True: @@ -1810,17 +1579,11 @@ class ByteCodeDecompiler(VerboseOutput): if cur_chunk.true_chunks: self.vprint(f"Cleaning up graph of IfBody {cur_chunk.id} true case") true_start = self.__get_entry_block(cur_chunk.true_chunks) - cur_chunk.true_chunks = self.__check_graph( - true_start, cur_chunk.true_chunks - ) + cur_chunk.true_chunks = self.__check_graph(true_start, cur_chunk.true_chunks) if cur_chunk.false_chunks: - self.vprint( - f"Cleaning up graph of IfBody {cur_chunk.id} false case" - ) + self.vprint(f"Cleaning up graph of IfBody {cur_chunk.id} false case") false_start = self.__get_entry_block(cur_chunk.false_chunks) - cur_chunk.false_chunks = self.__check_graph( - false_start, cur_chunk.false_chunks - ) + cur_chunk.false_chunks = self.__check_graph(false_start, cur_chunk.false_chunks) # Now, check to make sure that we have only one exit pointer. num_exits = len(cur_chunk.next_chunks) @@ -1886,11 +1649,7 @@ class ByteCodeDecompiler(VerboseOutput): elif action.comparison in [IfAction.COMP_BITAND, IfAction.COMP_NOT_BITAND]: conditional2 = stack.pop() conditional1 = stack.pop() - comp = ( - TwoParameterIf.NOT_EQUALS - if action.comparison == IfAction.COMP_BITAND - else TwoParameterIf.EQUALS - ) + comp = TwoParameterIf.NOT_EQUALS if action.comparison == IfAction.COMP_BITAND else TwoParameterIf.EQUALS return TwoParameterIf( ArithmeticExpression(conditional1, "&", conditional2), @@ -1916,9 +1675,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.name: # This defines a global function, so it won't go on the stack. - chunk.actions[i] = SetVariableStatement( - action.name, NewFunction(action.flags, decompiler) - ) + chunk.actions[i] = SetVariableStatement(action.name, NewFunction(action.flags, decompiler)) else: # This defines a function object, most likely for attaching to a member of an object. stack.append(NewFunction(action.flags, decompiler)) @@ -2114,11 +1871,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.opcode == AP2Action.INSTANCEOF: name_ref = stack.pop() obj_to_check = stack.pop() - stack.append( - FunctionCall( - self.__insertion_id, "isinstance", [obj_to_check, name_ref] - ) - ) + stack.append(FunctionCall(self.__insertion_id, "isinstance", [obj_to_check, name_ref])) chunk.actions[i] = OriginalCallLocation(self.__insertion_id) self.__insertion_id += 1 @@ -2126,9 +1879,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.opcode == AP2Action.TYPEOF: obj_to_check = stack.pop() - stack.append( - FunctionCall(self.__insertion_id, "typeof", [obj_to_check]) - ) + stack.append(FunctionCall(self.__insertion_id, "typeof", [obj_to_check])) chunk.actions[i] = OriginalCallLocation(self.__insertion_id) self.__insertion_id += 1 @@ -2145,11 +1896,7 @@ class ByteCodeDecompiler(VerboseOutput): params = [] for _ in range(num_params): params.append(stack.pop()) - stack.append( - MethodCall( - self.__insertion_id, object_reference, method_name, params - ) - ) + stack.append(MethodCall(self.__insertion_id, object_reference, method_name, params)) chunk.actions[i] = OriginalCallLocation(self.__insertion_id) self.__insertion_id += 1 @@ -2165,9 +1912,7 @@ class ByteCodeDecompiler(VerboseOutput): params = [] for _ in range(num_params): params.append(stack.pop()) - stack.append( - FunctionCall(self.__insertion_id, function_name, params) - ) + stack.append(FunctionCall(self.__insertion_id, function_name, params)) chunk.actions[i] = OriginalCallLocation(self.__insertion_id) self.__insertion_id += 1 @@ -2214,9 +1959,7 @@ class ByteCodeDecompiler(VerboseOutput): else: # This is probably a reference to a variable by # string concatenation. - chunk.actions[i] = SetMemberStatement( - GLOBAL, local_name, set_value - ) + chunk.actions[i] = SetMemberStatement(GLOBAL, local_name, set_value) continue @@ -2254,9 +1997,7 @@ class ByteCodeDecompiler(VerboseOutput): raise Exception("Logic error!") object_reference = stack.pop() - chunk.actions[i] = SetMemberStatement( - object_reference, member_name, set_value - ) + chunk.actions[i] = SetMemberStatement(object_reference, member_name, set_value) continue if action.opcode == AP2Action.GET_PROPERTY: @@ -2268,9 +2009,7 @@ class ByteCodeDecompiler(VerboseOutput): # SET_PROPERTY so this is just here for documentation. raise Exception("Logic error!") object_reference = stack.pop() - stack.append( - Member(object_reference, StringConstant(property_int + 0x100)) - ) + stack.append(Member(object_reference, StringConstant(property_int + 0x100))) chunk.actions[i] = NopStatement() continue @@ -2293,9 +2032,7 @@ class ByteCodeDecompiler(VerboseOutput): set_value = stack.pop() local_name = stack.pop() if not isinstance(local_name, (str, StringConstant)): - raise Exception( - f"Logic error, local name {local_name} is not a string!" - ) + raise Exception(f"Logic error, local name {local_name} is not a string!") chunk.actions[i] = SetLocalStatement(local_name, set_value) continue @@ -2303,9 +2040,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.opcode == AP2Action.DEFINE_LOCAL2: local_name = stack.pop() if not isinstance(local_name, (str, StringConstant)): - raise Exception( - f"Logic error, local name {local_name} is not a string!" - ) + raise Exception(f"Logic error, local name {local_name} is not a string!") chunk.actions[i] = SetLocalStatement(local_name, UNDEFINED) continue @@ -2494,9 +2229,7 @@ class ByteCodeDecompiler(VerboseOutput): if action.opcode == AP2Action.CAST_OP: obj_ref = stack.pop() class_ref = stack.pop() - stack.append( - FunctionCall(self.__insertion_id, "cast", [obj_ref, class_ref]) - ) + stack.append(FunctionCall(self.__insertion_id, "cast", [obj_ref, class_ref])) chunk.actions[i] = OriginalCallLocation(self.__insertion_id) self.__insertion_id += 1 @@ -2567,9 +2300,7 @@ class ByteCodeDecompiler(VerboseOutput): ) continue - raise Exception( - f"Unexpected action {action}, the cases above should be exhaustive!" - ) + raise Exception(f"Unexpected action {action}, the cases above should be exhaustive!") # Now, clean up code generation. new_actions: List[ConvertedAction] = [] @@ -2641,14 +2372,8 @@ class ByteCodeDecompiler(VerboseOutput): elif isinstance(statement, OriginalCallLocation): # Convert any orphaned function calls to calls without an assignment. if statement.insertion_id in orphaned_functions: - self.vprint( - f"Inserting orphaned function into insertion location {statement.insertion_id}" - ) - new_statements.append( - ExpressionStatement( - orphaned_functions[statement.insertion_id] - ) - ) + self.vprint(f"Inserting orphaned function into insertion location {statement.insertion_id}") + new_statements.append(ExpressionStatement(orphaned_functions[statement.insertion_id])) del orphaned_functions[statement.insertion_id] else: new_statements.append(statement) @@ -2657,9 +2382,7 @@ class ByteCodeDecompiler(VerboseOutput): statements = fixup(statements) if orphaned_functions: - raise Exception( - f"Unexpected leftover orphan functions {orphaned_functions}!" - ) + raise Exception(f"Unexpected leftover orphan functions {orphaned_functions}!") # Make sure we consumed the stack. for cid, leftovers in stack.items(): @@ -2680,19 +2403,13 @@ class ByteCodeDecompiler(VerboseOutput): other_stack_locs: Dict[int, int], offset_map: Dict[int, int], ) -> List[Statement]: - chunks_by_id: Dict[int, ArbitraryCodeChunk] = { - chunk.id: chunk for chunk in chunks - } + chunks_by_id: Dict[int, ArbitraryCodeChunk] = {chunk.id: chunk for chunk in chunks} statements: List[Statement] = [] - def reconcile_stacks( - cur_chunk: int, new_stack_id: int, new_stack: List[Any] - ) -> List[Statement]: + def reconcile_stacks(cur_chunk: int, new_stack_id: int, new_stack: List[Any]) -> List[Statement]: if new_stack_id in stacks: if cur_chunk == other_stack_locs[new_stack_id]: - raise Exception( - "Logic error, cannot reconcile variable names with self!" - ) + raise Exception("Logic error, cannot reconcile variable names with self!") other_chunk = other_stack_locs[new_stack_id] if len(stacks[new_stack_id]) != len(new_stack): min_len = min(len(stacks[new_stack_id]), len(new_stack)) @@ -2704,9 +2421,7 @@ class ByteCodeDecompiler(VerboseOutput): # It doesn't matter what it is, just mark the stack entry as being poisoned since # we couldn't reconcile it. We want to throw an exception down the line if we # run into this value, as we needed it but only sometimes got it. - borrow_vals = [ - MaybeStackEntry(new_stack_id) for _ in range(borrows) - ] + borrow_vals = [MaybeStackEntry(new_stack_id) for _ in range(borrows)] if min_len > 0: stacks[new_stack_id] = [ @@ -2749,9 +2464,7 @@ class ByteCodeDecompiler(VerboseOutput): ] stack.append(TempVariable(tmpname)) - self.vprint( - f"Reusing temporary variable {tmpname} to hold stack value {new_stack[i]}" - ) + self.vprint(f"Reusing temporary variable {tmpname} to hold stack value {new_stack[i]}") else: tmpname = f"tempvar_{self.__tmpvar_id}" self.__tmpvar_id += 1 @@ -2759,9 +2472,9 @@ class ByteCodeDecompiler(VerboseOutput): insertables[cur_chunk] = insertables.get(cur_chunk, []) + [ SetVariableStatement(tmpname, new_entry) ] - insertables[other_chunk] = insertables.get( - other_chunk, [] - ) + [SetVariableStatement(tmpname, old_entry)] + insertables[other_chunk] = insertables.get(other_chunk, []) + [ + SetVariableStatement(tmpname, old_entry) + ] stack.append(TempVariable(tmpname)) self.vprint( @@ -2770,9 +2483,7 @@ class ByteCodeDecompiler(VerboseOutput): else: stack.append(new_entry) - self.vprint( - f"Redefining stack for chunk ID {new_stack_id} to be {stack} after merging multiple paths" - ) + self.vprint(f"Redefining stack for chunk ID {new_stack_id} to be {stack} after merging multiple paths") stacks[new_stack_id] = stack[::-1] return definitions else: @@ -2817,20 +2528,14 @@ class ByteCodeDecompiler(VerboseOutput): # Grab the computed start stack for this ID if chunk.id not in stacks: # We somehow failed to assign a stack to this chunk but got here anyway? - raise Exception( - f"Logic error, stack for {chunk.id} does not exist!" - ) + raise Exception(f"Logic error, stack for {chunk.id} does not exist!") stack = stacks[chunk.id] del stacks[chunk.id] # Calculate the statements for this chunk, as well as the leftover stack entries. - self.vprint( - f"Evaluating graph of ByteCodeChunk {chunk.id} with stack {stack}" - ) - new_statements, stack_leftovers = self.__eval_stack( - chunk, stack, offset_map - ) + self.vprint(f"Evaluating graph of ByteCodeChunk {chunk.id} with stack {stack}") + new_statements, stack_leftovers = self.__eval_stack(chunk, stack, offset_map) # We need to check and see if the last entry is an IfExpr, and hoist it # into a statement here. @@ -2840,15 +2545,11 @@ class ByteCodeDecompiler(VerboseOutput): if not isinstance(if_body_chunk, IfBody): # IfBody should always follow a chunk that ends with an if. - raise Exception( - f"Logic error, expecting an IfBody chunk but got {if_body_chunk}!" - ) + raise Exception(f"Logic error, expecting an IfBody chunk but got {if_body_chunk}!") if if_body in stacks: # Nothing should ever create a stack pointing at an IfBody except this code here. - raise Exception( - f"Logic error, IfBody ID {if_body} already has a stack {stacks[if_body]}!" - ) + raise Exception(f"Logic error, IfBody ID {if_body} already has a stack {stacks[if_body]}!") # Recalculate next chunk ID since we're calculating two chunks here. if len(if_body_chunk.next_chunks) > 1: @@ -2858,9 +2559,7 @@ class ByteCodeDecompiler(VerboseOutput): next_chunk_id = if_body_chunk.next_chunks[0] else: next_chunk_id = next_id - self.vprint( - f"Recalculated next ID for IfBody {if_body} to be {next_chunk_id}" - ) + self.vprint(f"Recalculated next ID for IfBody {if_body} to be {next_chunk_id}") # Make sure if its an if with only one body (true/false) that we track # the stack in this case as well. @@ -2872,9 +2571,7 @@ class ByteCodeDecompiler(VerboseOutput): # Evaluate the if body true_statements: List[Statement] = [] if if_body_chunk.true_chunks: - self.vprint( - f"Evaluating graph of IfBody {if_body_chunk.id} true case" - ) + self.vprint(f"Evaluating graph of IfBody {if_body_chunk.id} true case") true_start = self.__get_entry_block(if_body_chunk.true_chunks) if true_start in stacks: raise Exception("Logic error, unexpected stack for if!") @@ -2882,9 +2579,7 @@ class ByteCodeDecompiler(VerboseOutput): # The stack for both of these is the leftovers from the previous evaluation as they # rollover. stacks[true_start] = [s for s in stack_leftovers] - self.vprint( - f"True start {true_start} of IfBody has stack {stacks[true_start]}" - ) + self.vprint(f"True start {true_start} of IfBody has stack {stacks[true_start]}") true_statements = self.__eval_chunks_impl( true_start, if_body_chunk.true_chunks, @@ -2897,16 +2592,12 @@ class ByteCodeDecompiler(VerboseOutput): ) else: if next_chunk_id is None: - raise Exception( - "Logic error, cannot reconcile stacks when next chunk is the end!" - ) + raise Exception("Logic error, cannot reconcile stacks when next chunk is the end!") reconcile_stacks(chunk.id, next_chunk_id, stack_leftovers) false_statements: List[Statement] = [] if if_body_chunk.false_chunks: - self.vprint( - f"Evaluating graph of IfBody {if_body_chunk.id} false case" - ) + self.vprint(f"Evaluating graph of IfBody {if_body_chunk.id} false case") false_start = self.__get_entry_block(if_body_chunk.false_chunks) if false_start in stacks: raise Exception("Logic error, unexpected stack for if!") @@ -2914,9 +2605,7 @@ class ByteCodeDecompiler(VerboseOutput): # The stack for both of these is the leftovers from the previous evaluation as they # rollover. stacks[false_start] = [s for s in stack_leftovers] - self.vprint( - f"False start {false_start} of IfBody has stack {stacks[false_start]}" - ) + self.vprint(f"False start {false_start} of IfBody has stack {stacks[false_start]}") false_statements = self.__eval_chunks_impl( false_start, if_body_chunk.false_chunks, @@ -2929,9 +2618,7 @@ class ByteCodeDecompiler(VerboseOutput): ) else: if next_chunk_id is None: - raise Exception( - "Logic error, cannot reconcile stacks when next chunk is the end!" - ) + raise Exception("Logic error, cannot reconcile stacks when next chunk is the end!") reconcile_stacks(chunk.id, next_chunk_id, stack_leftovers) # Convert this IfExpr to a full-blown IfStatement. @@ -2972,9 +2659,7 @@ class ByteCodeDecompiler(VerboseOutput): f"Logic error, expected only one false statement in intermediate if {last_new_statement}!" ) else: - intermediates.extend( - last_new_statement.false_statements - ) + intermediates.extend(last_new_statement.false_statements) for stmt in intermediates: if isinstance(stmt, GotoStatement): @@ -2997,28 +2682,20 @@ class ByteCodeDecompiler(VerboseOutput): if next_id is not None: new_next_ids.add(next_id) else: - raise Exception( - f"Logic error, unexpected statement {stmt}!" - ) + raise Exception(f"Logic error, unexpected statement {stmt}!") if new_next_ids: for new_next_id in new_next_ids: - reconcile_stacks( - chunk.id, new_next_id, [s for s in stack_leftovers] - ) + reconcile_stacks(chunk.id, new_next_id, [s for s in stack_leftovers]) # Insert a sentinel for where temporary variables can be added if we # need to in the future. - sentinels: List[Union[Statement, IntermediateIf]] = [ - InsertionLocation(chunk.id) - ] + sentinels: List[Union[Statement, IntermediateIf]] = [InsertionLocation(chunk.id)] # If we have a goto or intermediate if, we need to insert the tempvar assignment before it. # This is because in both cases we will redirect control flow, so we need to make sure # tempvar assignment happens before that redirection for the code to make sense. - if new_statements and isinstance( - new_statements[-1], (GotoStatement, IntermediateIf) - ): + if new_statements and isinstance(new_statements[-1], (GotoStatement, IntermediateIf)): sentinels.append(new_statements[-1]) new_statements = new_statements[:-1] @@ -3026,23 +2703,13 @@ class ByteCodeDecompiler(VerboseOutput): new_statements.extend(sentinels) else: # We have nowhere else to go, verify that we have an empty stack. - orphans = [ - s - for s in stack_leftovers - if isinstance(s, (FunctionCall, MethodCall)) - ] + orphans = [s for s in stack_leftovers if isinstance(s, (FunctionCall, MethodCall))] stack_leftovers = [ - s - for s in stack_leftovers - if not isinstance( - s, (MaybeStackEntry, FunctionCall, MethodCall) - ) + s for s in stack_leftovers if not isinstance(s, (MaybeStackEntry, FunctionCall, MethodCall)) ] for func in orphans: if func.insertion_ref in orphaned_functions: - raise Exception( - f"Logic error, already have an insertion ID {func.insertion_ref}!" - ) + raise Exception(f"Logic error, already have an insertion ID {func.insertion_ref}!") orphaned_functions[func.insertion_ref] = func if stack_leftovers: raise Exception( @@ -3055,17 +2722,10 @@ class ByteCodeDecompiler(VerboseOutput): # Intermediate if conditional (such as a break/return/goto inside # a loop. if not isinstance(statement.parent_action, IfExpr): - raise Exception( - f"Logic error, found unconverted IntermediateIf {statement}!" - ) + raise Exception(f"Logic error, found unconverted IntermediateIf {statement}!") - if ( - not statement.true_statements - and not statement.false_statements - ): - self.vprint( - f"Skipping adding if statement {statement} because it is an empty sentinel!" - ) + if not statement.true_statements and not statement.false_statements: + self.vprint(f"Skipping adding if statement {statement} because it is an empty sentinel!") else: statements.append( IfStatement( @@ -3101,12 +2761,8 @@ class ByteCodeDecompiler(VerboseOutput): new_statement.body = self.__walk(new_statement.body, do) new_statements.append(new_statement) elif isinstance(new_statement, IfStatement): - new_statement.true_statements = self.__walk( - new_statement.true_statements, do - ) - new_statement.false_statements = self.__walk( - new_statement.false_statements, do - ) + new_statement.true_statements = self.__walk(new_statement.true_statements, do) + new_statement.false_statements = self.__walk(new_statement.false_statements, do) new_statements.append(new_statement) elif isinstance(new_statement, SwitchStatement): new_statement.cases = [ @@ -3122,9 +2778,7 @@ class ByteCodeDecompiler(VerboseOutput): return new_statements - def __collapse_identical_labels( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __collapse_identical_labels(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find labels that point at gotos, remove them and point the # gotos to those labels at the second gotos. statements = list(statements) @@ -3134,24 +2788,16 @@ class ByteCodeDecompiler(VerboseOutput): for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] if (i < len(statements) - 1) else None - ) - if isinstance(cur_statement, DefineLabelStatement) and isinstance( - next_statement, GotoStatement - ): + next_statement = statements[i + 1] if (i < len(statements) - 1) else None + if isinstance(cur_statement, DefineLabelStatement) and isinstance(next_statement, GotoStatement): label_and_goto[cur_statement.location] = next_statement.location elif isinstance(cur_statement, DoWhileStatement): label_and_goto.update(find_labels_and_gotos(cur_statement.body)) elif isinstance(cur_statement, IfStatement): - label_and_goto.update( - find_labels_and_gotos(cur_statement.true_statements) - ) - label_and_goto.update( - find_labels_and_gotos(cur_statement.false_statements) - ) + label_and_goto.update(find_labels_and_gotos(cur_statement.true_statements)) + label_and_goto.update(find_labels_and_gotos(cur_statement.false_statements)) elif isinstance(cur_statement, SwitchStatement): for case in cur_statement.cases: @@ -3196,38 +2842,24 @@ class ByteCodeDecompiler(VerboseOutput): return statements, changed - def __remove_goto_return( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __remove_goto_return(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find labels that point at returns, convert any gotos pointing # at them to returns. - def find_labels( - statements: Sequence[Statement], parent_next_statement: Optional[Statement] - ) -> Set[int]: + def find_labels(statements: Sequence[Statement], parent_next_statement: Optional[Statement]) -> Set[int]: labels: Set[int] = set() for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] - if (i < len(statements) - 1) - else parent_next_statement - ) - if isinstance(cur_statement, DefineLabelStatement) and isinstance( - next_statement, NullReturnStatement - ): + next_statement = statements[i + 1] if (i < len(statements) - 1) else parent_next_statement + if isinstance(cur_statement, DefineLabelStatement) and isinstance(next_statement, NullReturnStatement): labels.add(cur_statement.location) elif isinstance(cur_statement, DoWhileStatement): labels.update(find_labels(cur_statement.body, next_statement)) elif isinstance(cur_statement, IfStatement): - labels.update( - find_labels(cur_statement.true_statements, next_statement) - ) - labels.update( - find_labels(cur_statement.false_statements, next_statement) - ) + labels.update(find_labels(cur_statement.true_statements, next_statement)) + labels.update(find_labels(cur_statement.false_statements, next_statement)) elif isinstance(cur_statement, SwitchStatement): for case in cur_statement.cases: @@ -3251,39 +2883,25 @@ class ByteCodeDecompiler(VerboseOutput): statements = self.__walk(statements, update_gotos) return statements, updated - def __eliminate_useless_returns( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __eliminate_useless_returns(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find returns that are on the "last" line. Basically, any # return statement where the next statement is another return statement # or the end of a function. - def find_returns( - statements: Sequence[Statement], parent_next_statement: Statement - ) -> Set[NullReturnStatement]: + def find_returns(statements: Sequence[Statement], parent_next_statement: Statement) -> Set[NullReturnStatement]: returns: Set[NullReturnStatement] = set() for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] - if (i < len(statements) - 1) - else parent_next_statement - ) - if isinstance(cur_statement, NullReturnStatement) and isinstance( - next_statement, NullReturnStatement - ): + next_statement = statements[i + 1] if (i < len(statements) - 1) else parent_next_statement + if isinstance(cur_statement, NullReturnStatement) and isinstance(next_statement, NullReturnStatement): returns.add(cur_statement) elif isinstance(cur_statement, DoWhileStatement): returns.update(find_returns(cur_statement.body, next_statement)) elif isinstance(cur_statement, IfStatement): - returns.update( - find_returns(cur_statement.true_statements, next_statement) - ) - returns.update( - find_returns(cur_statement.false_statements, next_statement) - ) + returns.update(find_returns(cur_statement.true_statements, next_statement)) + returns.update(find_returns(cur_statement.false_statements, next_statement)) elif isinstance(cur_statement, SwitchStatement): for case in cur_statement.cases: @@ -3309,57 +2927,37 @@ class ByteCodeDecompiler(VerboseOutput): statements = self.__walk(statements, remove_returns) return statements, updated - def __remove_useless_gotos( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __remove_useless_gotos(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find gotos that point at the very next line and remove them. # This can happen due to the way we analyze if statements. statements = list(statements) - def find_goto_next_line( - statements: Sequence[Statement], next_instruction: Statement - ) -> List[Statement]: + def find_goto_next_line(statements: Sequence[Statement], next_instruction: Statement) -> List[Statement]: gotos: List[Statement] = [] for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] if (i < len(statements) - 1) else next_instruction - ) + next_statement = statements[i + 1] if (i < len(statements) - 1) else next_instruction - if isinstance(cur_statement, GotoStatement) and isinstance( - next_statement, DefineLabelStatement - ): + if isinstance(cur_statement, GotoStatement) and isinstance(next_statement, DefineLabelStatement): if cur_statement.location == next_statement.location: gotos.append(cur_statement) - if isinstance(cur_statement, GotoStatement) and isinstance( - next_statement, GotoStatement - ): + if isinstance(cur_statement, GotoStatement) and isinstance(next_statement, GotoStatement): if cur_statement.location == next_statement.location: gotos.append(cur_statement) elif isinstance(cur_statement, DoWhileStatement): # Loops do not "flow" into the next line, they can only "break" to the next # line. Goto of the next line has already been converted to a "break" statement. - gotos.extend( - find_goto_next_line(cur_statement.body, NopStatement()) - ) + gotos.extend(find_goto_next_line(cur_statement.body, NopStatement())) elif isinstance(cur_statement, IfStatement): # The next statement for both the if and else body is the next statement we have # looked up, either the next statement in this group of statements, or the next # statement in the parent. - gotos.extend( - find_goto_next_line( - cur_statement.true_statements, next_statement - ) - ) - gotos.extend( - find_goto_next_line( - cur_statement.false_statements, next_statement - ) - ) + gotos.extend(find_goto_next_line(cur_statement.true_statements, next_statement)) + gotos.extend(find_goto_next_line(cur_statement.false_statements, next_statement)) elif isinstance(cur_statement, SwitchStatement): # Switch cases do not "flow" into the next line, they flow into the next switch @@ -3389,20 +2987,10 @@ class ByteCodeDecompiler(VerboseOutput): return NopStatement() for case in cases: - if case.statements and isinstance( - case.statements[-1], BreakStatement - ): - gotos.extend( - find_goto_next_line( - case.statements[:-1], next_statement - ) - ) + if case.statements and isinstance(case.statements[-1], BreakStatement): + gotos.extend(find_goto_next_line(case.statements[:-1], next_statement)) else: - gotos.extend( - find_goto_next_line( - case.statements, get_next_instruction(case) - ) - ) + gotos.extend(find_goto_next_line(case.statements, get_next_instruction(case))) return gotos @@ -3427,9 +3015,7 @@ class ByteCodeDecompiler(VerboseOutput): return statements, changed - def __eliminate_unused_labels( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __eliminate_unused_labels(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find labels that nothing is pointing at, and remove them. locations: Set[int] = set() @@ -3452,49 +3038,31 @@ class ByteCodeDecompiler(VerboseOutput): return self.__walk(statements, remove_label), changed - def __eliminate_useless_continues( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __eliminate_useless_continues(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find continues that are on the "last" line of a while. Basically, any # continue statement where the next statement is another continue statement or the end # of a loop. - def find_continues( - statements: Sequence[Statement], parent_next_statement: Statement - ) -> Set[ContinueStatement]: + def find_continues(statements: Sequence[Statement], parent_next_statement: Statement) -> Set[ContinueStatement]: continues: Set[ContinueStatement] = set() for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] - if (i < len(statements) - 1) - else parent_next_statement - ) - if isinstance(cur_statement, ContinueStatement) and isinstance( - next_statement, ContinueStatement - ): + next_statement = statements[i + 1] if (i < len(statements) - 1) else parent_next_statement + if isinstance(cur_statement, ContinueStatement) and isinstance(next_statement, ContinueStatement): continues.add(cur_statement) elif isinstance(cur_statement, DoWhileStatement): # Clever hack, where we pretend the next value after the loop is a continue, # because hitting the bottom of a loop is actually a continue. - continues.update( - find_continues(cur_statement.body, ContinueStatement()) - ) + continues.update(find_continues(cur_statement.body, ContinueStatement())) elif isinstance(cur_statement, IfStatement): - continues.update( - find_continues(cur_statement.true_statements, next_statement) - ) - continues.update( - find_continues(cur_statement.false_statements, next_statement) - ) + continues.update(find_continues(cur_statement.true_statements, next_statement)) + continues.update(find_continues(cur_statement.false_statements, next_statement)) elif isinstance(cur_statement, SwitchStatement): for case in cur_statement.cases: - continues.update( - find_continues(case.statements, next_statement) - ) + continues.update(find_continues(case.statements, next_statement)) return continues @@ -3516,25 +3084,15 @@ class ByteCodeDecompiler(VerboseOutput): statements = self.__walk(statements, remove_continues) return statements, updated - def __eliminate_useless_breaks( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __eliminate_useless_breaks(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find breaks that show up just before another break logically. - def find_breaks( - statements: Sequence[Statement], parent_next_statement: Statement - ) -> Set[BreakStatement]: + def find_breaks(statements: Sequence[Statement], parent_next_statement: Statement) -> Set[BreakStatement]: breaks: Set[BreakStatement] = set() for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] - if (i < len(statements) - 1) - else parent_next_statement - ) - if isinstance(cur_statement, BreakStatement) and isinstance( - next_statement, BreakStatement - ): + next_statement = statements[i + 1] if (i < len(statements) - 1) else parent_next_statement + if isinstance(cur_statement, BreakStatement) and isinstance(next_statement, BreakStatement): breaks.add(cur_statement) elif isinstance(cur_statement, DoWhileStatement): @@ -3542,12 +3100,8 @@ class ByteCodeDecompiler(VerboseOutput): breaks.update(find_breaks(cur_statement.body, NopStatement())) elif isinstance(cur_statement, IfStatement): - breaks.update( - find_breaks(cur_statement.true_statements, next_statement) - ) - breaks.update( - find_breaks(cur_statement.false_statements, next_statement) - ) + breaks.update(find_breaks(cur_statement.true_statements, next_statement)) + breaks.update(find_breaks(cur_statement.false_statements, next_statement)) elif isinstance(cur_statement, SwitchStatement): # The next entry after a switch can be a break, as it applies to a different statement. @@ -3629,9 +3183,7 @@ class ByteCodeDecompiler(VerboseOutput): self, possible_if: Statement, required_variable: Optional[str] ) -> Tuple[Optional[IfExpr], List[Statement]]: if isinstance(possible_if, IfStatement): - if len(possible_if.true_statements) == 1 and isinstance( - possible_if.true_statements[0], BreakStatement - ): + if len(possible_if.true_statements) == 1 and isinstance(possible_if.true_statements[0], BreakStatement): # This is possibly a candidate, check the condition's variable usage. if isinstance(possible_if.cond, IsUndefinedIf): if required_variable is not None: @@ -3673,9 +3225,7 @@ class ByteCodeDecompiler(VerboseOutput): return possible_if.cond, possible_if.false_statements return None, [] - def __convert_loops( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __convert_loops(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Convert any do {} while loops that resemble for statements into actual for statements. # First, we need to hoist any increment to the actual end of the loop in case its in the # last statement of some if/else condition. This isn't going to be perfectly accurate because @@ -3690,20 +3240,14 @@ class ByteCodeDecompiler(VerboseOutput): for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] if (i < len(statements) - 1) else None - ) + next_statement = statements[i + 1] if (i < len(statements) - 1) else None if isinstance(cur_statement, IfStatement): # Don't care about this, but we need to recursively walk its children. - cur_statement.true_statements, new_changed = convert_loops( - cur_statement.true_statements - ) + cur_statement.true_statements, new_changed = convert_loops(cur_statement.true_statements) changed = changed or new_changed - cur_statement.false_statements, new_changed = convert_loops( - cur_statement.false_statements - ) + cur_statement.false_statements, new_changed = convert_loops(cur_statement.false_statements) changed = changed or new_changed new_statements.append(cur_statement) @@ -3725,9 +3269,7 @@ class ByteCodeDecompiler(VerboseOutput): # This might be a candidate for white statement hoisting. if len(cur_statement.body) > 0: # Let's see if the first statement is an if statement with a break. - possible_cond, false_body = self.__extract_condition( - cur_statement.body[0], None - ) + possible_cond, false_body = self.__extract_condition(cur_statement.body[0], None) else: possible_cond = None @@ -3761,19 +3303,14 @@ class ByteCodeDecompiler(VerboseOutput): # This is a possible conversion that hasn't been converted yet. Let's try to grab # the increment variable. if next_statement.body: - inc_variable = self.__get_increment_variable( - next_statement.body[-1] - ) + inc_variable = self.__get_increment_variable(next_statement.body[-1]) else: inc_variable = None # Now that we know what's being incremented, let's see if it matches our # initializer. inc_assignment = None - if ( - inc_variable is not None - and inc_variable != cur_statement.code_equiv() - ): + if inc_variable is not None and inc_variable != cur_statement.code_equiv(): # This doesn't match, so let's kill our reference. inc_variable = None else: @@ -3787,9 +3324,7 @@ class ByteCodeDecompiler(VerboseOutput): possible_cond = next_statement.cond.invert() if isinstance(possible_cond, TwoParameterIf): try: - if_variable = object_ref( - possible_cond.conditional2, "" - ) + if_variable = object_ref(possible_cond.conditional2, "") if inc_variable == if_variable: possible_cond = possible_cond.swap() except Exception: @@ -3797,9 +3332,7 @@ class ByteCodeDecompiler(VerboseOutput): false_body = [] else: # Let's see if the first statement is an if statement with a break. - possible_cond, false_body = self.__extract_condition( - next_statement.body[0], inc_variable - ) + possible_cond, false_body = self.__extract_condition(next_statement.body[0], inc_variable) else: possible_cond = None @@ -3830,9 +3363,7 @@ class ByteCodeDecompiler(VerboseOutput): return convert_loops(statements) - def __swap_empty_ifs( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __swap_empty_ifs(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Get rid of empty if statements. If statements with empty if bodies and nonempty # else bodies will also be swapped. changed: bool = False @@ -3852,9 +3383,7 @@ class ByteCodeDecompiler(VerboseOutput): statement.false_statements, statement.true_statements, ) - elif (not statement.true_statements) and ( - not statement.false_statements - ): + elif (not statement.true_statements) and (not statement.false_statements): # Drop the if, it has no body. changed = True updated = True @@ -3867,9 +3396,7 @@ class ByteCodeDecompiler(VerboseOutput): if not changed: return statements, updated - def __swap_ugly_ifexprs( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __swap_ugly_ifexprs(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Swap if expressions that have a constant on the LHS. changed: bool = False @@ -3897,9 +3424,7 @@ class ByteCodeDecompiler(VerboseOutput): statements = self.__walk(statements, swap_ugly_ifs) return statements, changed - def __drop_unneeded_else( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __drop_unneeded_else(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # If an if has an else, but the last line of the if is a break/continue/return/throw/goto # then the else body doesn't need to exist, so hoist it up into the parent. If the false # statement also has an exit condition, don't drop it for asthetics. @@ -3957,14 +3482,10 @@ class ByteCodeDecompiler(VerboseOutput): ): # We need to walk both halves still, but once we're done, hoist the false # statements up to our level. - statement.true_statements, new_changed = update_ifs( - statement.true_statements - ) + statement.true_statements, new_changed = update_ifs(statement.true_statements) changed = changed or new_changed - new_false_statements, new_changed = update_ifs( - statement.false_statements - ) + new_false_statements, new_changed = update_ifs(statement.false_statements) changed = changed or new_changed statement.false_statements = [] @@ -3972,14 +3493,10 @@ class ByteCodeDecompiler(VerboseOutput): new_statements.append(statement) new_statements.extend(new_false_statements) else: - statement.true_statements, new_changed = update_ifs( - statement.true_statements - ) + statement.true_statements, new_changed = update_ifs(statement.true_statements) changed = changed or new_changed - statement.false_statements, new_changed = update_ifs( - statement.false_statements - ) + statement.false_statements, new_changed = update_ifs(statement.false_statements) changed = changed or new_changed new_statements.append(statement) @@ -4039,20 +3556,12 @@ class ByteCodeDecompiler(VerboseOutput): if true_cond == IsBooleanIf(False) and false_cond == IsBooleanIf(False): # Both conditionals exited. running_conditional = IsBooleanIf(False) - elif true_cond != IsBooleanIf(False) and false_cond == IsBooleanIf( - False - ): + elif true_cond != IsBooleanIf(False) and false_cond == IsBooleanIf(False): # The subsequent statements are only parented by the true conditional. - running_conditional = AndIf( - true_cond, running_conditional - ).simplify() - elif true_cond == IsBooleanIf(False) and false_cond != IsBooleanIf( - False - ): + running_conditional = AndIf(true_cond, running_conditional).simplify() + elif true_cond == IsBooleanIf(False) and false_cond != IsBooleanIf(False): # The subsequent statements are only parented by the false conditional. - running_conditional = AndIf( - false_cond, running_conditional - ).simplify() + running_conditional = AndIf(false_cond, running_conditional).simplify() else: # We are parented by either of the true/false cases. running_conditional = OrIf( @@ -4087,9 +3596,7 @@ class ByteCodeDecompiler(VerboseOutput): # to which there is no goto. if stmt.location not in gotos: continue - goto_conditional = OrIf( - gotos[stmt.location], goto_conditional - ).simplify() + goto_conditional = OrIf(gotos[stmt.location], goto_conditional).simplify() flowed_statements[i] = (OrIf(cond, goto_conditional).simplify(), stmt) if isinstance( stmt, @@ -4160,16 +3667,10 @@ class ByteCodeDecompiler(VerboseOutput): # Finally, simplify it for ease of comparison. return combined.simplify() - def get_candidate_group( - conditional: IfExpr, statement: IfStatement - ) -> Optional[List[IfStatement]]: + def get_candidate_group(conditional: IfExpr, statement: IfStatement) -> Optional[List[IfStatement]]: candidate_statements: List[IfStatement] = [statement] - if ( - candidates - and (not statement.false_statements) - and len(statement.true_statements) == 1 - ): + if candidates and (not statement.false_statements) and len(statement.true_statements) == 1: while True: # First, is the current combination a valid combined or statement? candidate_true_expr = get_compound_if(candidate_statements) @@ -4198,9 +3699,7 @@ class ByteCodeDecompiler(VerboseOutput): if isinstance(statement, IfStatement): # See if this is a compound if pattern. - candidate_statements = get_candidate_group( - parent_conditional, statement - ) + candidate_statements = get_candidate_group(parent_conditional, statement) if candidate_statements is None: # Move past this statement, we don't care about it. i += 1 @@ -4323,9 +3822,7 @@ class ByteCodeDecompiler(VerboseOutput): ) changed = changed or child_changed false_statements, child_changed = self.__hoist_compound_ifs( - AndIf( - parent_conditional, stmt.cond.invert() - ).simplify(), + AndIf(parent_conditional, stmt.cond.invert()).simplify(), stmt.false_statements, candidates, flow, @@ -4339,9 +3836,7 @@ class ByteCodeDecompiler(VerboseOutput): ) ) elif isinstance(stmt, DoWhileStatement): - new_body, child_changed = self.__rearrange_compound_ifs( - stmt.body - ) + new_body, child_changed = self.__rearrange_compound_ifs(stmt.body) changed = changed or child_changed stmt.body = new_body new_statements.append(stmt) @@ -4351,17 +3846,13 @@ class ByteCodeDecompiler(VerboseOutput): # We hoisted a compound if, so report a change. changed = True elif isinstance(statement, DoWhileStatement): - statement.body, child_changed = self.__rearrange_compound_ifs( - statement.body - ) + statement.body, child_changed = self.__rearrange_compound_ifs(statement.body) changed = changed or child_changed new_statements.append(statement) i += 1 elif isinstance(statement, SwitchStatement): for case in statement.cases: - case.statements, new_changed = self.__rearrange_compound_ifs( - case.statements - ) + case.statements, new_changed = self.__rearrange_compound_ifs(case.statements) changed = changed or new_changed new_statements.append(statement) i += 1 @@ -4371,22 +3862,16 @@ class ByteCodeDecompiler(VerboseOutput): return new_statements, changed - def __rearrange_compound_ifs( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __rearrange_compound_ifs(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: candidates = self.__gather_candidates(statements) if candidates: _, _, flow = self.__gather_flow(IsBooleanIf(True), statements) else: flow = [] - return self.__hoist_compound_ifs( - IsBooleanIf(True), statements, candidates, flow - ) + return self.__hoist_compound_ifs(IsBooleanIf(True), statements, candidates, flow) - def __convert_switches( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __convert_switches(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Convert any cascading if statements comparing the same variable/register against a series # of constants into switch statements. This relies on a previous run of anohter optimizer # that ensures that variables show up on the LHS of if statements. @@ -4404,9 +3889,7 @@ class ByteCodeDecompiler(VerboseOutput): TwoParameterIf.STRICT_NOT_EQUALS, }: return None - if not isinstance( - statement.cond.conditional1, (Variable, Register, Member) - ): + if not isinstance(statement.cond.conditional1, (Variable, Register, Member)): return None # We intentionally widen this to allow variables, since there are a lot of places in # various code that uses variables as constants. We made up the entire language we are @@ -4419,9 +3902,7 @@ class ByteCodeDecompiler(VerboseOutput): return statement.cond.conditional1 - def get_next_candidate( - statements: List[Statement], lhs: Expression - ) -> Optional[IfStatement]: + def get_next_candidate(statements: List[Statement], lhs: Expression) -> Optional[IfStatement]: if len(statements) != 1: return None statement = statements[0] @@ -4553,9 +4034,7 @@ class ByteCodeDecompiler(VerboseOutput): # This isn't even an if statement. We should never hit # this but the type checker wants to be happy. return statement - if has_break(cur_statement.true_statements) or has_break( - cur_statement.false_statements - ): + if has_break(cur_statement.true_statements) or has_break(cur_statement.false_statements): # This code already uses a 'break' statement. If we stuck it # in a switch, it would change the sematics of this statement # so we have no choice but to ignore this. @@ -4638,9 +4117,7 @@ class ByteCodeDecompiler(VerboseOutput): statements = self.__walk(statements, replace_if_with_switch) return statements, changed - def __convert_if_gotos( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __convert_if_gotos(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Find if statements in the middle of a chunk of code whose last true statement is # a return/goto/throw. Take all the following statements and put them in the if # statement's false clause. We do this because it allows us to recognize other @@ -4681,9 +4158,7 @@ class ByteCodeDecompiler(VerboseOutput): false_statements: List[Statement] = [] while i < len(statements): false_statement = statements[i] - if stop_at_label is not None and isinstance( - false_statement, DefineLabelStatement - ): + if stop_at_label is not None and isinstance(false_statement, DefineLabelStatement): if stop_at_label == false_statement.location: # Exit early, the rest of the code including this # label is not part of the else case. @@ -4701,31 +4176,23 @@ class ByteCodeDecompiler(VerboseOutput): i += 1 # Regardless of whether we modified the if statement, recurse down its true and false path. - cur_statement.true_statements, new_changed = self.__convert_if_gotos( - cur_statement.true_statements - ) + cur_statement.true_statements, new_changed = self.__convert_if_gotos(cur_statement.true_statements) changed = changed or new_changed - cur_statement.false_statements, new_changed = self.__convert_if_gotos( - cur_statement.false_statements - ) + cur_statement.false_statements, new_changed = self.__convert_if_gotos(cur_statement.false_statements) changed = changed or new_changed new_statements.append(cur_statement) elif isinstance(cur_statement, SwitchStatement): for case in cur_statement.cases: - case.statements, new_changed = self.__convert_if_gotos( - case.statements - ) + case.statements, new_changed = self.__convert_if_gotos(case.statements) changed = changed or new_changed new_statements.append(cur_statement) i += 1 elif isinstance(cur_statement, DoWhileStatement): - cur_statement.body, new_changed = self.__convert_if_gotos( - cur_statement.body - ) + cur_statement.body, new_changed = self.__convert_if_gotos(cur_statement.body) changed = changed or new_changed new_statements.append(cur_statement) @@ -4737,9 +4204,7 @@ class ByteCodeDecompiler(VerboseOutput): return new_statements, changed - def __convert_switch_gotos( - self, statements: Sequence[Statement] - ) -> Tuple[List[Statement], bool]: + def __convert_switch_gotos(self, statements: Sequence[Statement]) -> Tuple[List[Statement], bool]: # Go through and find switch cases that goto the next line in the switch, replacing those # with break statements. def find_gotos( @@ -4751,11 +4216,7 @@ class ByteCodeDecompiler(VerboseOutput): for i in range(len(statements)): cur_statement = statements[i] - next_statement = ( - statements[i + 1] - if (i < len(statements) - 1) - else parent_next_statement - ) + next_statement = statements[i + 1] if (i < len(statements) - 1) else parent_next_statement if ( isinstance(cur_statement, GotoStatement) @@ -4768,9 +4229,7 @@ class ByteCodeDecompiler(VerboseOutput): elif isinstance(cur_statement, DoWhileStatement): # We don't want to track gotos into while loops because replacing one of # these with a break would change the flow. - gotos.update( - find_gotos(cur_statement.body, next_statement, NopStatement()) - ) + gotos.update(find_gotos(cur_statement.body, next_statement, NopStatement())) elif isinstance(cur_statement, IfStatement): gotos.update( @@ -4794,9 +4253,7 @@ class ByteCodeDecompiler(VerboseOutput): # We don't care about the semantic next statement for the purposes of this # call, so just set it as a NOP. for case in cur_statement.cases: - gotos.update( - find_gotos(case.statements, NopStatement(), next_statement) - ) + gotos.update(find_gotos(case.statements, NopStatement(), next_statement)) return gotos @@ -4895,17 +4352,13 @@ class ByteCodeDecompiler(VerboseOutput): ) if unmatched_labels and self.optimize: formatted_labels = ", ".join(f"label_{x}" for x in unmatched_labels) - raise Exception( - f"Logic error, labels found with no gotos pointing at them: {formatted_labels}" - ) + raise Exception(f"Logic error, labels found with no gotos pointing at them: {formatted_labels}") def __verify_no_empty_ifs(self, statements: Sequence[Statement]) -> None: def check_ifs(statement: Statement) -> Optional[Statement]: if isinstance(statement, IfStatement): if (not statement.true_statements) and (not statement.false_statements): - raise Exception( - f"If statement {statement} has no true or false statements inside it!" - ) + raise Exception(f"If statement {statement} has no true or false statements inside it!") return statement self.__walk(statements, check_ifs) @@ -4936,9 +4389,7 @@ class ByteCodeDecompiler(VerboseOutput): # Now, separate chunks out into chunks and loops. self.vprint("Identifying and separating loops...") - chunks_and_loops = self.__separate_loops( - start_id, chunks, dominators, offset_map - ) + chunks_and_loops = self.__separate_loops(start_id, chunks, dominators, offset_map) # Now, break the graph anywhere where we have control # flow that ends the execution (return, throw, goto end). @@ -4947,9 +4398,7 @@ class ByteCodeDecompiler(VerboseOutput): # Now, identify any remaining control flow logic. self.vprint("Identifying and separating ifs...") - chunks_loops_and_ifs = self.__separate_ifs( - start_id, None, chunks_and_loops, offset_map - ) + chunks_loops_and_ifs = self.__separate_ifs(start_id, None, chunks_and_loops, offset_map) # At this point, we *should* have a directed graph where there are no # backwards refs and every fork has been identified as an if. This means diff --git a/bemani/format/afp/geo.py b/bemani/format/afp/geo.py index 6f841c4..ebb2ddc 100644 --- a/bemani/format/afp/geo.py +++ b/bemani/format/afp/geo.py @@ -116,9 +116,7 @@ class Shape: # point and there are only 8 of them, making a rectangle. for vertexno in range(vertex_count): vertexno_offset = vertex_offset + (8 * vertexno) - x, y = struct.unpack( - f"{endian}ff", self.data[vertexno_offset : vertexno_offset + 8] - ) + x, y = struct.unpack(f"{endian}ff", self.data[vertexno_offset : vertexno_offset + 8]) vertex_points.append(Point(x, y)) self.vertex_points = vertex_points @@ -126,9 +124,7 @@ class Shape: if tex_offset != 0: for texno in range(tex_count): texno_offset = tex_offset + (8 * texno) - x, y = struct.unpack( - f"{endian}ff", self.data[texno_offset : texno_offset + 8] - ) + x, y = struct.unpack(f"{endian}ff", self.data[texno_offset : texno_offset + 8]) tex_points.append(Point(x, y)) self.tex_points = tex_points @@ -136,9 +132,7 @@ class Shape: if color_offset != 0: for colorno in range(color_count): colorno_offset = color_offset + (4 * colorno) - rgba = struct.unpack( - f"{endian}I", self.data[colorno_offset : colorno_offset + 4] - )[0] + rgba = struct.unpack(f"{endian}I", self.data[colorno_offset : colorno_offset + 4])[0] color = Color( a=(rgba & 0xFF) / 255.0, b=((rgba >> 8) & 0xFF) / 255.0, @@ -152,9 +146,7 @@ class Shape: if label_offset != 0: for labelno in range(label_count): labelno_offset = label_offset + (4 * labelno) - labelptr = struct.unpack( - f"{endian}I", self.data[labelno_offset : labelno_offset + 4] - )[0] + labelptr = struct.unpack(f"{endian}I", self.data[labelno_offset : labelno_offset + 4])[0] bytedata = self.get_until_null(labelptr) labels.append(descramble_text(bytedata, text_obfuscated)) @@ -215,17 +207,11 @@ class Shape: if mode != 4: raise Exception("Unexpected mode in GE2D structure!") if (flags & 0x2) and not labels: - raise Exception( - "GE2D structure has a texture, but no region labels present!" - ) + raise Exception("GE2D structure has a texture, but no region labels present!") if (flags & 0x2) and (tex1 == 0xFF): - raise Exception( - "GE2D structure requests a texture, but no texture pointer present!" - ) + raise Exception("GE2D structure requests a texture, but no texture pointer present!") if tex2 != 0xFF: - raise Exception( - "GE2D structure requests a second texture, but we don't support this!" - ) + raise Exception("GE2D structure requests a second texture, but we don't support this!") if unk != 0x0: raise Exception("Unhandled unknown data in GE2D structure!") @@ -238,16 +224,10 @@ class Shape: verticies: List[int] = [] for render_paramstriangleno in range(trianglecount): - render_paramstriangleno_offset = triangleoffset + ( - 2 * render_paramstriangleno - ) + render_paramstriangleno_offset = triangleoffset + (2 * render_paramstriangleno) tex_offset = struct.unpack( f"{endian}H", - self.data[ - render_paramstriangleno_offset : ( - render_paramstriangleno_offset + 2 - ) - ], + self.data[render_paramstriangleno_offset : (render_paramstriangleno_offset + 2)], )[0] verticies.append(tex_offset) diff --git a/bemani/format/afp/render.py b/bemani/format/afp/render.py index 49d2d71..f566367 100644 --- a/bemani/format/afp/render.py +++ b/bemani/format/afp/render.py @@ -511,14 +511,10 @@ class Global: return retval except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call gotoAndPlay({frame}) on {self.clip} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call gotoAndPlay({frame}) on {self.clip} but that method doesn't exist!") return UNDEFINED - def __find_parent( - self, parent: PlacedClip, child: PlacedClip - ) -> Optional[PlacedClip]: + def __find_parent(self, parent: PlacedClip, child: PlacedClip) -> Optional[PlacedClip]: for obj in parent.placed_objects: if obj is child: # This is us, so the parent is our parent. @@ -535,9 +531,7 @@ class Global: class AEPLib: - def aep_set_rect_mask( - self, thisptr: Any, left: Any, right: Any, top: Any, bottom: Any - ) -> None: + def aep_set_rect_mask(self, thisptr: Any, left: Any, right: Any, top: Any, bottom: Any) -> None: if ( not isinstance(left, (int, float)) or not isinstance(right, (int, float)) @@ -558,9 +552,7 @@ class AEPLib: ), ) else: - print( - f"WARNING: Ignoring aeplib.aep_set_rect_mask call with unrecognized target {thisptr}!" - ) + print(f"WARNING: Ignoring aeplib.aep_set_rect_mask call with unrecognized target {thisptr}!") def aep_set_set_frame(self, thisptr: Any, frame: Any) -> None: # This appears to be some sort of callback that the game or other animations can use to figure out @@ -571,25 +563,19 @@ class AEPLib: def aep_set_frame_control(self, thisptr: Any, depth: Any, frame: Any) -> None: if not isinstance(thisptr, PlacedClip): - print( - f"WARNING: Ignoring aeplib.aep_set_frame_control with unrecognized current object {thisptr}!" - ) + print(f"WARNING: Ignoring aeplib.aep_set_frame_control with unrecognized current object {thisptr}!") return for obj in thisptr.placed_objects: if obj.depth == depth: if not isinstance(obj, PlacedClip): - print( - f"WARNING: Ignoring aeplib.aep_set_frame_control called on object {obj} at depth {depth}!" - ) + print(f"WARNING: Ignoring aeplib.aep_set_frame_control called on object {obj} at depth {depth}!") return obj.setInvisibleUntil(frame) return - print( - f"WARNING: Ignoring aeplib.aep_set_frame_control called on nonexistent object at depth {depth}!" - ) + print(f"WARNING: Ignoring aeplib.aep_set_frame_control called on nonexistent object at depth {depth}!") def gotoAndPlay(self, thisptr: Any, frame: Any) -> Any: # This appears to be a wrapper to allow calling gotoAndPlay on clips. @@ -600,9 +586,7 @@ class AEPLib: return meth(frame) except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!") return UNDEFINED def gotoAndStop(self, thisptr: Any, frame: Any) -> Any: @@ -614,9 +598,7 @@ class AEPLib: return meth(frame) except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!") return UNDEFINED def deepGotoAndPlay(self, thisptr: Any, frame: Any) -> Any: @@ -640,9 +622,7 @@ class AEPLib: return retval except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!") return UNDEFINED def deepGotoAndStop(self, thisptr: Any, frame: Any) -> Any: @@ -666,9 +646,7 @@ class AEPLib: return retval except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!") return UNDEFINED def play(self, thisptr: Any) -> Any: @@ -680,9 +658,7 @@ class AEPLib: return meth() except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call play() on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call play() on {thisptr} but that method doesn't exist!") return UNDEFINED def stop(self, thisptr: Any) -> Any: @@ -694,21 +670,15 @@ class AEPLib: return meth() except AttributeError: # Function does not exist! - print( - f"WARNING: Tried to call stop() on {thisptr} but that method doesn't exist!" - ) + print(f"WARNING: Tried to call stop() on {thisptr} but that method doesn't exist!") return UNDEFINED class ASDLib: def sound_play(self, sound: Any) -> None: if not isinstance(sound, str): - print( - f"WARNING: Ignoring asdlib.sound_play call with invalid parameters {sound}!" - ) - print( - f"WARNING: Requested sound {sound} be played but we don't support sound yet!" - ) + print(f"WARNING: Ignoring asdlib.sound_play call with invalid parameters {sound}!") + print(f"WARNING: Requested sound {sound} be played but we don't support sound yet!") MissingThis = object() @@ -859,9 +829,7 @@ class AFPRenderer(VerboseOutput): prefix: str = "", ) -> None: if self.__root is None: - raise Exception( - "Logic error, executing bytecode outside of a rendering movie clip!" - ) + raise Exception("Logic error, executing bytecode outside of a rendering movie clip!") thisobj = clip if (thisptr is MissingThis) else thisptr globalobj = Global(self.__root, clip) @@ -880,9 +848,7 @@ class AFPRenderer(VerboseOutput): if action.opcode == AP2Action.END: # End the execution. - self.vprint( - f"{prefix} Ending bytecode execution.", component="bytecode" - ) + self.vprint(f"{prefix} Ending bytecode execution.", component="bytecode") break elif action.opcode == AP2Action.GET_VARIABLE: varname = stack.pop() @@ -918,9 +884,7 @@ class AFPRenderer(VerboseOutput): # Grab the parameters to pass to the function. num_params = stack.pop() if not isinstance(num_params, int): - raise Exception( - "Logic error, cannot get number of parameters to method call!" - ) + raise Exception("Logic error, cannot get number of parameters to method call!") params = [] for _ in range(num_params): params.append(stack.pop()) @@ -948,9 +912,7 @@ class AFPRenderer(VerboseOutput): # Grab the parameters to pass to the function. num_params = stack.pop() if not isinstance(num_params, int): - raise Exception( - "Logic error, cannot get number of parameters to function call!" - ) + raise Exception("Logic error, cannot get number of parameters to function call!") params = [] for _ in range(num_params): params.append(stack.pop()) @@ -1015,9 +977,7 @@ class AFPRenderer(VerboseOutput): self.vprint(f"{prefix}Bytecode engine finished.", component="bytecode") - def __place( - self, tag: Tag, operating_clip: PlacedClip, prefix: str = "" - ) -> Tuple[Optional[PlacedClip], bool]: + def __place(self, tag: Tag, operating_clip: PlacedClip, prefix: str = "") -> Tuple[Optional[PlacedClip], bool]: # "Place" a tag on the screen. Most of the time, this means performing the action of the tag, # such as defining a shape (registering it with our shape list) or adding/removing an object. if isinstance(tag, AP2ShapeTag): @@ -1065,9 +1025,7 @@ class AFPRenderer(VerboseOutput): ) # Register a new clip that we might reference to execute. - self.__registered_objects[tag.id] = RegisteredClip( - tag.id, tag.frames, tag.tags, tag.labels - ) + self.__registered_objects[tag.id] = RegisteredClip(tag.id, tag.frames, tag.tags, tag.labels) # Didn't place a new clip, didn't change anything. return None, False @@ -1094,27 +1052,18 @@ class AFPRenderer(VerboseOutput): new_transform = ( obj.transform.update( tag.transform, - tag.projection - == AP2PlaceObjectTag.PROJECTION_PERSPECTIVE, - ) - if ( - tag.transform is not None - and tag.projection != AP2PlaceObjectTag.PROJECTION_NONE + tag.projection == AP2PlaceObjectTag.PROJECTION_PERSPECTIVE, ) + if (tag.transform is not None and tag.projection != AP2PlaceObjectTag.PROJECTION_NONE) else obj.transform ) new_rotation_origin = tag.rotation_origin or obj.rotation_origin new_blend = tag.blend or obj.blend new_projection = ( - tag.projection - if tag.projection != AP2PlaceObjectTag.PROJECTION_NONE - else obj.projection + tag.projection if tag.projection != AP2PlaceObjectTag.PROJECTION_NONE else obj.projection ) - if ( - tag.source_tag_id is not None - and tag.source_tag_id != obj.source.tag_id - ): + if tag.source_tag_id is not None and tag.source_tag_id != obj.source.tag_id: # This completely updates the pointed-at object. newobj = self.__registered_objects[tag.source_tag_id] self.vprint( @@ -1192,9 +1141,7 @@ class AFPRenderer(VerboseOutput): # Didn't place a new clip, changed the parent clip. return None, True else: - raise Exception( - f"Unrecognized object with Tag ID {tag.source_tag_id}!" - ) + raise Exception(f"Unrecognized object with Tag ID {tag.source_tag_id}!") else: # As far as I can tell, pretty much only color and matrix stuff can be updated. self.vprint( @@ -1211,15 +1158,11 @@ class AFPRenderer(VerboseOutput): return None, True # Didn't place a new clip, did change something. - print( - f"WARNING: Couldn't find tag {tag.object_id} on depth {tag.depth} to update!" - ) + print(f"WARNING: Couldn't find tag {tag.object_id} on depth {tag.depth} to update!") return None, False else: if tag.source_tag_id is None: - raise Exception( - "Cannot place a tag with no source ID and no update flags!" - ) + raise Exception("Cannot place a tag with no source ID and no update flags!") if tag.source_tag_id in self.__registered_objects: newobj = self.__registered_objects[tag.source_tag_id] @@ -1285,13 +1228,9 @@ class AFPRenderer(VerboseOutput): for flags, code in tag.triggers.items(): if flags & AP2Trigger.ON_LOAD: for bytecode in code: - self.__execute_bytecode( - bytecode, placed_clip, prefix=prefix + " " - ) + self.__execute_bytecode(bytecode, placed_clip, prefix=prefix + " ") else: - print( - "WARNING: Unhandled PLACE_OBJECT trigger with flags {flags}!" - ) + print("WARNING: Unhandled PLACE_OBJECT trigger with flags {flags}!") # Placed a new clip, changed the parent. return placed_clip, True @@ -1315,13 +1254,9 @@ class AFPRenderer(VerboseOutput): # Didn't place a new clip, changed the parent clip. return None, True else: - raise Exception( - f"Unrecognized object with Tag ID {tag.source_tag_id}!" - ) + raise Exception(f"Unrecognized object with Tag ID {tag.source_tag_id}!") - raise Exception( - f"Cannot find a shape or sprite with Tag ID {tag.source_tag_id}!" - ) + raise Exception(f"Cannot find a shape or sprite with Tag ID {tag.source_tag_id}!") elif isinstance(tag, AP2RemoveObjectTag): self.vprint( @@ -1353,9 +1288,7 @@ class AFPRenderer(VerboseOutput): real_index = len(operating_clip.placed_objects) - (i + 1) if operating_clip.placed_objects[real_index].depth == tag.depth: - removed_objects = operating_clip.placed_objects[ - real_index : (real_index + 1) - ] + removed_objects = operating_clip.placed_objects[real_index : (real_index + 1)] operating_clip.placed_objects = ( operating_clip.placed_objects[:real_index] + operating_clip.placed_objects[(real_index + 1) :] @@ -1363,9 +1296,7 @@ class AFPRenderer(VerboseOutput): break if not removed_objects: - print( - f"WARNING: Couldn't find object to remove by ID {tag.object_id} and depth {tag.depth}!" - ) + print(f"WARNING: Couldn't find object to remove by ID {tag.object_id} and depth {tag.depth}!") # TODO: Handle ON_UNLOAD triggers for this object. I don't think I've ever seen one # on any object so this might be a pedantic request. @@ -1375,9 +1306,7 @@ class AFPRenderer(VerboseOutput): elif isinstance(tag, AP2DoActionTag): self.vprint(f"{prefix} Execution action tag.", component="tags") - self.__execute_bytecode( - tag.bytecode, operating_clip, prefix=prefix + " " - ) + self.__execute_bytecode(tag.bytecode, operating_clip, prefix=prefix + " ") # Didn't place a new clip. return None, False @@ -1450,9 +1379,7 @@ class AFPRenderer(VerboseOutput): # Draw the mask onto a new image. if projection == AP2PlaceObjectTag.PROJECTION_AFFINE: calculated_mask = affine_composite( - Image.new( - "RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0) - ), + Image.new("RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0)), Color(0.0, 0.0, 0.0, 0.0), Color(1.0, 1.0, 1.0, 1.0), HSL(0.0, 0.0, 0.0), @@ -1465,13 +1392,9 @@ class AFPRenderer(VerboseOutput): ) elif projection == AP2PlaceObjectTag.PROJECTION_PERSPECTIVE: if self.__camera is None: - print( - "WARNING: Element requests perspective projection but no camera exists!" - ) + print("WARNING: Element requests perspective projection but no camera exists!") calculated_mask = affine_composite( - Image.new( - "RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0) - ), + Image.new("RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0)), Color(0.0, 0.0, 0.0, 0.0), Color(1.0, 1.0, 1.0, 1.0), HSL(0.0, 0.0, 0.0), @@ -1484,9 +1407,7 @@ class AFPRenderer(VerboseOutput): ) else: calculated_mask = perspective_composite( - Image.new( - "RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0) - ), + Image.new("RGBA", (parent_mask.width, parent_mask.height), (0, 0, 0, 0)), Color(0.0, 0.0, 0.0, 0.0), Color(1.0, 1.0, 1.0, 1.0), HSL(0.0, 0.0, 0.0), @@ -1551,13 +1472,9 @@ class AFPRenderer(VerboseOutput): ) # Calculate blending and blend color if it is present. - mult_color = (renderable.mult_color or Color(1.0, 1.0, 1.0, 1.0)).multiply( - parent_mult_color - ) + mult_color = (renderable.mult_color or Color(1.0, 1.0, 1.0, 1.0)).multiply(parent_mult_color) add_color = ( - (renderable.add_color or Color(0.0, 0.0, 0.0, 0.0)) - .multiply(parent_mult_color) - .add(parent_add_color) + (renderable.add_color or Color(0.0, 0.0, 0.0, 0.0)).multiply(parent_mult_color).add(parent_add_color) ) hsl_shift = (renderable.hsl_shift or HSL(0.0, 0.0, 0.0)).add(parent_hsl_shift) blend = renderable.blend or 0 @@ -1565,9 +1482,7 @@ class AFPRenderer(VerboseOutput): blend = parent_blend if renderable.mask: - mask = self.__apply_mask( - parent_mask, transform, projection, renderable.mask - ) + mask = self.__apply_mask(parent_mask, transform, projection, renderable.mask) else: mask = parent_mask @@ -1668,9 +1583,7 @@ class AFPRenderer(VerboseOutput): if params.flags & 0x2: # We need to look up the texture for this. if params.region not in self.textures: - raise Exception( - f"Cannot find texture reference {params.region}!" - ) + raise Exception(f"Cannot find texture reference {params.region}!") texture = self.textures[params.region] if params.flags & 0x8: @@ -1684,9 +1597,7 @@ class AFPRenderer(VerboseOutput): if len(shape.vertex_points) != 4: print("WARNING: Unsupported non-rectangle shape!") if params.blend is None: - raise Exception( - "Logic error, rectangle without a blend color!" - ) + raise Exception("Logic error, rectangle without a blend color!") x_points = set(p.x for p in shape.vertex_points) y_points = set(p.y for p in shape.vertex_points) @@ -1719,11 +1630,7 @@ class AFPRenderer(VerboseOutput): if texture is not None: if projection == AP2PlaceObjectTag.PROJECTION_AFFINE: if self.__enable_aa: - aamode = ( - AAMode.UNSCALED_SSAA_ONLY - if rectangle - else AAMode.SSAA_OR_BILINEAR - ) + aamode = AAMode.UNSCALED_SSAA_ONLY if rectangle else AAMode.SSAA_OR_BILINEAR else: aamode = AAMode.NONE @@ -1742,17 +1649,11 @@ class AFPRenderer(VerboseOutput): elif projection == AP2PlaceObjectTag.PROJECTION_PERSPECTIVE: if self.__camera is None: if self.__enable_aa: - aamode = ( - AAMode.UNSCALED_SSAA_ONLY - if rectangle - else AAMode.SSAA_OR_BILINEAR - ) + aamode = AAMode.UNSCALED_SSAA_ONLY if rectangle else AAMode.SSAA_OR_BILINEAR else: aamode = AAMode.NONE - print( - "WARNING: Element requests perspective projection but no camera exists!" - ) + print("WARNING: Element requests perspective projection but no camera exists!") img = affine_composite( img, add_color, @@ -1767,11 +1668,7 @@ class AFPRenderer(VerboseOutput): ) else: if self.__enable_aa: - aamode = ( - AAMode.UNSCALED_SSAA_ONLY - if rectangle - else AAMode.SSAA_ONLY - ) + aamode = AAMode.UNSCALED_SSAA_ONLY if rectangle else AAMode.SSAA_ONLY else: aamode = AAMode.NONE @@ -1821,15 +1718,11 @@ class AFPRenderer(VerboseOutput): blend, texture, single_threaded=self.__single_threaded, - aa_mode=AAMode.SSAA_OR_BILINEAR - if self.__enable_aa - else AAMode.NONE, + aa_mode=AAMode.SSAA_OR_BILINEAR if self.__enable_aa else AAMode.NONE, ) elif projection == AP2PlaceObjectTag.PROJECTION_PERSPECTIVE: if self.__camera is None: - print( - "WARNING: Element requests perspective projection but no camera exists!" - ) + print("WARNING: Element requests perspective projection but no camera exists!") img = affine_composite( img, add_color, @@ -1840,9 +1733,7 @@ class AFPRenderer(VerboseOutput): blend, texture, single_threaded=self.__single_threaded, - aa_mode=AAMode.SSAA_OR_BILINEAR - if self.__enable_aa - else AAMode.NONE, + aa_mode=AAMode.SSAA_OR_BILINEAR if self.__enable_aa else AAMode.NONE, ) else: img = perspective_composite( @@ -1881,9 +1772,7 @@ class AFPRenderer(VerboseOutput): # None of our children (or their children, etc...) or ourselves is dirty. return False - def __process_tags( - self, clip: PlacedClip, only_dirty: bool, prefix: str = " " - ) -> bool: + def __process_tags(self, clip: PlacedClip, only_dirty: bool, prefix: str = " ") -> bool: self.vprint( f"{prefix}Handling {'dirty updates on ' if only_dirty else ''}placed clip {clip.object_id} at depth {clip.depth}", component="tags", @@ -1894,11 +1783,7 @@ class AFPRenderer(VerboseOutput): # Make sure to set the requested frame if it isn't set by an external force. if clip.requested_frame is None: - if ( - not clip.playing - or only_dirty - or (clip.finished and clip is self.__root) - ): + if not clip.playing or only_dirty or (clip.finished and clip is self.__root): # We aren't playing this clip because its either paused or finished, # or it isn't dirty and we're doing dirty updates only. So, we don't # need to advance to any frame. @@ -1917,9 +1802,7 @@ class AFPRenderer(VerboseOutput): if clip.frame > clip.requested_frame: # Rewind this clip to the beginning so we can replay until the requested frame. if clip is self.__root: - print( - "WARNING: Root clip was rewound, its possible this animation plays forever!" - ) + print("WARNING: Root clip was rewound, its possible this animation plays forever!") clip.rewind() self.vprint( @@ -1946,25 +1829,14 @@ class AFPRenderer(VerboseOutput): played_tags.add(unplayed_tag) orphans.append(clip.source.tags[unplayed_tag]) - for tagno in range( - frame.start_tag_offset, frame.start_tag_offset + frame.num_tags - ): + for tagno in range(frame.start_tag_offset, frame.start_tag_offset + frame.num_tags): played_tags.add(tagno) # Check these off our future todo list. - clip.unplayed_tags = [ - t for t in clip.unplayed_tags if t not in played_tags - ] + clip.unplayed_tags = [t for t in clip.unplayed_tags if t not in played_tags] # Grab the normal list of tags, add to the orphans. - tags = ( - orphans - + clip.source.tags[ - frame.start_tag_offset : ( - frame.start_tag_offset + frame.num_tags - ) - ] - ) + tags = orphans + clip.source.tags[frame.start_tag_offset : (frame.start_tag_offset + frame.num_tags)] for tagno, tag in enumerate(tags): # Perform the action of this tag. self.vprint( @@ -1977,20 +1849,14 @@ class AFPRenderer(VerboseOutput): # If we create a new movie clip, process it as well for this frame. if new_clip: # These are never dirty-only updates as they're fresh-placed. - changed = ( - self.__process_tags(new_clip, False, prefix=prefix + " ") - or changed - ) + changed = self.__process_tags(new_clip, False, prefix=prefix + " ") or changed # Now, advance the frame for this clip since we processed the frame. clip.advance() # Now, handle each of the existing clips. for child in child_clips: - changed = ( - self.__process_tags(child, only_dirty, prefix=prefix + " ") - or changed - ) + changed = self.__process_tags(child, only_dirty, prefix=prefix + " ") or changed # See if we're done with this clip. if clip.frame == clip.requested_frame: @@ -2007,9 +1873,7 @@ class AFPRenderer(VerboseOutput): def __handle_imports( self, swf: SWF - ) -> Dict[ - int, Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy] - ]: + ) -> Dict[int, Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy]]: external_objects: Dict[ int, Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy], @@ -2027,16 +1891,12 @@ class AFPRenderer(VerboseOutput): external_objects[tag_id] = RegisteredDummy(tag_id) break else: - external_objects[tag_id] = self.__find_import( - other, other.exported_tags[imp.tag] - ) + external_objects[tag_id] = self.__find_import(other, other.exported_tags[imp.tag]) break else: # Only display a warning if we don't have our own stub implementation of this SWF. if repr(imp) not in self.__stubbed_swfs: - print( - f"WARNING: {swf.exported_name} imports {imp} but that SWF is not in our library!" - ) + print(f"WARNING: {swf.exported_name} imports {imp} but that SWF is not in our library!") external_objects[tag_id] = RegisteredDummy(tag_id) # Fix up tag IDs to point at our local definition of them. @@ -2067,22 +1927,16 @@ class AFPRenderer(VerboseOutput): tag = self.__find_tag(root_clip, tag_id) if tag is None: - print( - f"WARNING: {swf.exported_name} exports {swf.imported_tags[tag_id]} but does not manifest an object!" - ) + print(f"WARNING: {swf.exported_name} exports {swf.imported_tags[tag_id]} but does not manifest an object!") return RegisteredDummy(tag_id) return tag def __find_tag( self, clip: RegisteredClip, tag_id: int - ) -> Optional[ - Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy] - ]: + ) -> Optional[Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy]]: # Fake-execute this clip to find the tag we need to manifest. for frame in clip.frames: - tags = clip.tags[ - frame.start_tag_offset : (frame.start_tag_offset + frame.num_tags) - ] + tags = clip.tags[frame.start_tag_offset : (frame.start_tag_offset + frame.num_tags)] for tag in tags: # Attempt to place any tags. @@ -2090,9 +1944,7 @@ class AFPRenderer(VerboseOutput): if tag.id == tag_id: # We need to be able to see this shape to place it. if tag.reference not in self.shapes: - raise Exception( - f"Cannot find shape reference {tag.reference}!" - ) + raise Exception(f"Cannot find shape reference {tag.reference}!") # This matched, so this is the import. return RegisteredShape( @@ -2108,9 +1960,7 @@ class AFPRenderer(VerboseOutput): if tag.id == tag_id: # We need to be able to see this shape to place it. if tag.reference not in self.textures: - raise Exception( - f"Cannot find texture reference {tag.reference}!" - ) + raise Exception(f"Cannot find texture reference {tag.reference}!") # This matched, so this is the import. return RegisteredImage( @@ -2153,9 +2003,7 @@ class AFPRenderer(VerboseOutput): # Calculate actual size based on given movie transform. actual_width = overridden_width or swf.location.width actual_height = overridden_height or swf.location.height - resized_width, resized_height, _ = movie_transform.multiply_point( - Point(actual_width, actual_height) - ).as_tuple() + resized_width, resized_height, _ = movie_transform.multiply_point(Point(actual_width, actual_height)).as_tuple() if round(swf.location.top, 2) != 0.0 or round(swf.location.left, 2) != 0.0: # TODO: If the location top/left is nonzero, we need move the root transform @@ -2235,9 +2083,7 @@ class AFPRenderer(VerboseOutput): root_clip.placed_objects.append(background_container) # Create the root mask for where to draw the root clip. - movie_mask = Image.new( - "RGBA", (resized_width, resized_height), color=(255, 0, 0, 255) - ) + movie_mask = Image.new("RGBA", (resized_width, resized_height), color=(255, 0, 0, 255)) # These could possibly be overwritten from an external source of we wanted. actual_mult_color = Color(1.0, 1.0, 1.0, 1.0) @@ -2271,9 +2117,7 @@ class AFPRenderer(VerboseOutput): if obj is background_container: break else: - self.vprint( - "Root clip was rewound, re-placing background image on clip." - ) + self.vprint("Root clip was rewound, re-placing background image on clip.") root_clip.placed_objects.append(background_container) # Now, update the background image if we need to. @@ -2285,9 +2129,7 @@ class AFPRenderer(VerboseOutput): # Adjust camera based on the movie's scaling. if self.__camera is not None and not self.__camera.adjusted: - self.__camera.center = movie_transform.multiply_point( - self.__camera.center - ) + self.__camera.center = movie_transform.multiply_point(self.__camera.center) self.__camera.adjusted = True # If we're only rendering some frames, don't bother to do the draw operations @@ -2302,25 +2144,17 @@ class AFPRenderer(VerboseOutput): continue if changed or last_rendered_frame is None: - if ( - last_width != root_clip._width - or last_height != root_clip._height - ): + if last_width != root_clip._width or last_height != root_clip._height: last_width = root_clip._width last_height = root_clip._height - if ( - root_clip._width > actual_width - or root_clip._height > actual_height - ): + if root_clip._width > actual_width or root_clip._height > actual_height: print( f"WARNING: Root clip requested to resize to {last_width}x{last_height} which overflows root canvas!" ) # Now, render out the placed objects. color = swf.color or Color(0.0, 0.0, 0.0, 0.0) - curimage = Image.new( - "RGBA", (resized_width, resized_height), color=color.as_tuple() - ) + curimage = Image.new("RGBA", (resized_width, resized_height), color=color.as_tuple()) curimage = self.__render_object( curimage, root_clip, diff --git a/bemani/format/afp/swf.py b/bemani/format/afp/swf.py index 56bc4e9..513df90 100644 --- a/bemani/format/afp/swf.py +++ b/bemani/format/afp/swf.py @@ -57,25 +57,19 @@ class NamedTagReference: class TagPointer: # A pointer to a tag in this SWF by Tag ID and containing an optional initialization bytecode # to run for this tag when it is placed/executed. - def __init__( - self, id: Optional[int], init_bytecode: Optional[ByteCode] = None - ) -> None: + def __init__(self, id: Optional[int], init_bytecode: Optional[ByteCode] = None) -> None: self.id = id self.init_bytecode = init_bytecode def as_dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: return { "id": self.id, - "init_bytecode": self.init_bytecode.as_dict(*args, **kwargs) - if self.init_bytecode - else None, + "init_bytecode": self.init_bytecode.as_dict(*args, **kwargs) if self.init_bytecode else None, } class Frame: - def __init__( - self, start_tag_offset: int, num_tags: int, imported_tags: List[TagPointer] = [] - ) -> None: + def __init__(self, start_tag_offset: int, num_tags: int, imported_tags: List[TagPointer] = []) -> None: # The start tag offset into the tag list where we should begin placing/executing tags for this frame. self.start_tag_offset = start_tag_offset @@ -252,9 +246,7 @@ class AP2DefineButtonTag(Tag): class AP2PlaceCameraTag(Tag): - def __init__( - self, camera_id: int, center: Optional[Point], focal_length: float - ) -> None: + def __init__(self, camera_id: int, center: Optional[Point], focal_length: float) -> None: super().__init__(None) # This is not actually Tag ID, just a way to refer to the camera. Confusing, I know. @@ -267,9 +259,7 @@ class AP2PlaceCameraTag(Tag): return { **super().as_dict(*args, **kwargs), "camera_id": self.camera_id, - "center": self.center.as_dict(*args, **kwargs) - if self.center is not None - else None, + "center": self.center.as_dict(*args, **kwargs) if self.center is not None else None, "focal_length": self.focal_length, } @@ -386,30 +376,17 @@ class AP2PlaceObjectTag(Tag): "label_name": self.label_name, "blend": self.blend, "update": self.update, - "transform": self.transform.as_dict(*args, **kwargs) - if self.transform is not None - else None, + "transform": self.transform.as_dict(*args, **kwargs) if self.transform is not None else None, "rotation_origin": self.rotation_origin.as_dict(*args, **kwargs) if self.rotation_origin is not None else None, "projection": "none" if self.projection == self.PROJECTION_NONE - else ( - "affine" if self.projection == self.PROJECTION_AFFINE else "perspective" - ), - "mult_color": self.mult_color.as_dict(*args, **kwargs) - if self.mult_color is not None - else None, - "add_color": self.add_color.as_dict(*args, **kwargs) - if self.add_color is not None - else None, - "hsl_shift": self.hsl_shift.as_dict(*args, **kwargs) - if self.hsl_shift - else None, - "triggers": { - i: [b.as_dict(*args, **kwargs) for b in t] - for (i, t) in self.triggers.items() - }, + else ("affine" if self.projection == self.PROJECTION_AFFINE else "perspective"), + "mult_color": self.mult_color.as_dict(*args, **kwargs) if self.mult_color is not None else None, + "add_color": self.add_color.as_dict(*args, **kwargs) if self.add_color is not None else None, + "hsl_shift": self.hsl_shift.as_dict(*args, **kwargs) if self.hsl_shift else None, + "triggers": {i: [b.as_dict(*args, **kwargs) for b in t] for (i, t) in self.triggers.items()}, } def __repr__(self) -> str: @@ -438,9 +415,7 @@ class AP2RemoveObjectTag(Tag): class AP2DefineSpriteTag(Tag): id: int - def __init__( - self, id: int, tags: List[Tag], frames: List[Frame], labels: Dict[str, int] - ) -> None: + def __init__(self, id: int, tags: List[Tag], frames: List[Frame], labels: Dict[str, int]) -> None: super().__init__(id) # The list of tags that this sprite consists of. Sprites are, much like vanilla @@ -579,15 +554,10 @@ class SWF(VerboseOutput, TrackedCoverage): "data_version": self.data_version, "container_version": self.container_version, "fps": self.fps, - "color": self.color.as_dict(*args, **kwargs) - if self.color is not None - else None, + "color": self.color.as_dict(*args, **kwargs) if self.color is not None else None, "location": self.location.as_dict(*args, **kwargs), "exported_tags": self.exported_tags, - "imported_tags": { - i: self.imported_tags[i].as_dict(*args, **kwargs) - for i in self.imported_tags - }, + "imported_tags": {i: self.imported_tags[i].as_dict(*args, **kwargs) for i in self.imported_tags}, "tags": [t.as_dict(*args, **kwargs) for t in self.tags], "frames": [f.as_dict(*args, **kwargs) for f in self.frames], "labels": self.labels, @@ -644,9 +614,7 @@ class SWF(VerboseOutput, TrackedCoverage): if opcode in AP2Action.actions_without_params(): # Simple opcodes need no parsing, they can go directly onto the stack. - self.vprint( - f"{prefix} {lineno}: {action_name}", component="bytecode" - ) + self.vprint(f"{prefix} {lineno}: {action_name}", component="bytecode") offset_ptr += 1 actions.append(AP2Action(lineno, opcode)) elif opcode == AP2Action.DEFINE_FUNCTION2: @@ -683,26 +651,18 @@ class SWF(VerboseOutput, TrackedCoverage): self.vprint(f"{prefix} END_{action_name}", component="bytecode") - actions.append( - DefineFunction2Action(lineno, funcname, function_flags, function) - ) + actions.append(DefineFunction2Action(lineno, funcname, function_flags, function)) offset_ptr += bytecode_count elif opcode == AP2Action.PUSH: - obj_count = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + obj_count = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 - self.vprint( - f"{prefix} {lineno}: {action_name}", component="bytecode" - ) + self.vprint(f"{prefix} {lineno}: {action_name}", component="bytecode") objects: List[Any] = [] while obj_count > 0: - obj_to_create = struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + obj_to_create = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] offset_ptr += 1 if obj_to_create == 0x0: @@ -711,15 +671,11 @@ class SWF(VerboseOutput, TrackedCoverage): self.vprint(f"{prefix} INTEGER: 0", component="bytecode") elif obj_to_create == 0x1: # Float object, represented internally as a double. - fval = struct.unpack( - ">f", datachunk[offset_ptr : (offset_ptr + 4)] - )[0] + fval = struct.unpack(">f", datachunk[offset_ptr : (offset_ptr + 4)])[0] objects.append(fval) offset_ptr += 4 - self.vprint( - f"{prefix} FLOAT: {fval}", component="bytecode" - ) + self.vprint(f"{prefix} FLOAT: {fval}", component="bytecode") elif obj_to_create == 0x2: # Null pointer object. objects.append(NULL) @@ -730,9 +686,7 @@ class SWF(VerboseOutput, TrackedCoverage): self.vprint(f"{prefix} UNDEFINED", component="bytecode") elif obj_to_create == 0x4: # Register value. - regno = struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + regno = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] objects.append(Register(regno)) offset_ptr += 1 @@ -743,31 +697,21 @@ class SWF(VerboseOutput, TrackedCoverage): elif obj_to_create == 0x5: # Boolean "TRUE" object. objects.append(True) - self.vprint( - f"{prefix} BOOLEAN: True", component="bytecode" - ) + self.vprint(f"{prefix} BOOLEAN: True", component="bytecode") elif obj_to_create == 0x6: # Boolean "FALSE" object. objects.append(False) - self.vprint( - f"{prefix} BOOLEAN: False", component="bytecode" - ) + self.vprint(f"{prefix} BOOLEAN: False", component="bytecode") elif obj_to_create == 0x7: # Integer object. - ival = struct.unpack( - ">i", datachunk[offset_ptr : (offset_ptr + 4)] - )[0] + ival = struct.unpack(">i", datachunk[offset_ptr : (offset_ptr + 4)])[0] objects.append(ival) offset_ptr += 4 - self.vprint( - f"{prefix} INTEGER: {ival}", component="bytecode" - ) + self.vprint(f"{prefix} INTEGER: {ival}", component="bytecode") elif obj_to_create == 0x8: # String constant object. - const_offset = struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + const_offset = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] const = self.__get_string(string_offsets[const_offset]) objects.append(const) offset_ptr += 1 @@ -779,9 +723,7 @@ class SWF(VerboseOutput, TrackedCoverage): elif obj_to_create == 0x9: # String constant, but with 16 bits for the offset. Probably not used except # on the largest files. - const_offset = struct.unpack( - ">H", datachunk[offset_ptr : (offset_ptr + 2)] - )[0] + const_offset = struct.unpack(">H", datachunk[offset_ptr : (offset_ptr + 2)])[0] const = self.__get_string(string_offsets[const_offset]) objects.append(const) offset_ptr += 2 @@ -801,23 +743,17 @@ class SWF(VerboseOutput, TrackedCoverage): elif obj_to_create == 0xC: # Pointer to "this" object, whatever currently is executing the bytecode. objects.append(THIS) - self.vprint( - f"{prefix} POINTER TO THIS", component="bytecode" - ) + self.vprint(f"{prefix} POINTER TO THIS", component="bytecode") elif obj_to_create == 0xD: # Pointer to "root" object, which is the movieclip this bytecode exists in. objects.append(ROOT) - self.vprint( - f"{prefix} POINTER TO ROOT", component="bytecode" - ) + self.vprint(f"{prefix} POINTER TO ROOT", component="bytecode") elif obj_to_create == 0xE: # Pointer to "parent" object, whatever currently is executing the bytecode. # This seems to be the parent of the movie clip, or the current movieclip # if that isn't set. objects.append(PARENT) - self.vprint( - f"{prefix} POINTER TO PARENT", component="bytecode" - ) + self.vprint(f"{prefix} POINTER TO PARENT", component="bytecode") elif obj_to_create == 0xF: # Current movie clip. objects.append(CLIP) @@ -827,12 +763,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x10: # Property constant with no alias. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x100 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x100 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -841,9 +772,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x11: # Property constant referencing a string table entry. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x100 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -855,9 +784,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x12: # Same as above, but with allowance for a 16-bit constant offset. - propertyval, reference = struct.unpack( - ">BH", datachunk[offset_ptr : (offset_ptr + 3)] - ) + propertyval, reference = struct.unpack(">BH", datachunk[offset_ptr : (offset_ptr + 3)]) propertyval += 0x100 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -869,12 +796,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x13: # Class property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x300 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x300 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -883,9 +805,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x14: # Class property constant with alias. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x300 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -899,12 +819,7 @@ class SWF(VerboseOutput, TrackedCoverage): # that this has been omitted from game binaries. elif obj_to_create == 0x16: # Func property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x400 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x400 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -913,9 +828,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x17: # Func property name referencing a string table entry. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x400 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -928,12 +841,7 @@ class SWF(VerboseOutput, TrackedCoverage): # Same comment with 0x15 applies here with 0x18. elif obj_to_create == 0x19: # Other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x200 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x200 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -942,9 +850,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x1A: # Other property name referencing a string table entry. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x200 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -957,12 +863,7 @@ class SWF(VerboseOutput, TrackedCoverage): # Same comment with 0x15 and 0x18 applies here with 0x1b. elif obj_to_create == 0x1C: # Event property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x500 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x500 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -971,9 +872,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x1D: # Event property name referencing a string table entry. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x500 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -986,12 +885,7 @@ class SWF(VerboseOutput, TrackedCoverage): # Same comment with 0x15, 0x18 and 0x1b applies here with 0x1e. elif obj_to_create == 0x1F: # Key constants. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x600 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x600 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1000,9 +894,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) elif obj_to_create == 0x20: # Key property name referencing a string table entry. - propertyval, reference = struct.unpack( - ">BB", datachunk[offset_ptr : (offset_ptr + 2)] - ) + propertyval, reference = struct.unpack(">BB", datachunk[offset_ptr : (offset_ptr + 2)]) propertyval += 0x600 referenceval = self.__get_string(string_offsets[reference]) objects.append(StringConstant(propertyval, referenceval)) @@ -1026,12 +918,7 @@ class SWF(VerboseOutput, TrackedCoverage): self.vprint(f"{prefix} -INFINITY", component="bytecode") elif obj_to_create == 0x24: # Some other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x700 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x700 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1042,12 +929,7 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x24. elif obj_to_create == 0x27: # Some other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x800 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x800 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1058,12 +940,7 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x27. elif obj_to_create == 0x2A: # Some other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0x900 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0x900 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1074,12 +951,7 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x2a. elif obj_to_create == 0x2D: # Some other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0xA00 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0xA00 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1090,12 +962,7 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x2d. elif obj_to_create == 0x30: # Some other property name. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0xB00 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0xB00 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1106,23 +973,14 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x30. elif obj_to_create == 0x33: # Signed 64 bit integer init. Uses special "S64" type. - int64 = struct.unpack( - ">q", datachunk[offset_ptr : (offset_ptr + 8)] - ) + int64 = struct.unpack(">q", datachunk[offset_ptr : (offset_ptr + 8)]) objects.append(int64) offset_ptr += 8 - self.vprint( - f"{prefix} INTEGER: {int64}", component="bytecode" - ) + self.vprint(f"{prefix} INTEGER: {int64}", component="bytecode") elif obj_to_create == 0x34: # Some other property names. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0xC00 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0xC00 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1133,23 +991,14 @@ class SWF(VerboseOutput, TrackedCoverage): # versions of 0x34. elif obj_to_create == 0x37: # Integer object but one byte. - ival = struct.unpack( - ">b", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + ival = struct.unpack(">b", datachunk[offset_ptr : (offset_ptr + 1)])[0] objects.append(ival) offset_ptr += 1 - self.vprint( - f"{prefix} INTEGER: {ival}", component="bytecode" - ) + self.vprint(f"{prefix} INTEGER: {ival}", component="bytecode") elif obj_to_create == 0x38: # Some other property names. - propertyval = ( - struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] - + 0xD00 - ) + propertyval = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] + 0xD00 objects.append(StringConstant(propertyval)) offset_ptr += 1 self.vprint( @@ -1159,9 +1008,7 @@ class SWF(VerboseOutput, TrackedCoverage): # Possibly in newer binaries, 0x39 and 0x3a are implemented as 8-bit and 16-bit alias pointer # versions of 0x38. else: - raise Exception( - f"Unsupported object {hex(obj_to_create)} to push!" - ) + raise Exception(f"Unsupported object {hex(obj_to_create)} to push!") obj_count -= 1 @@ -1169,20 +1016,14 @@ class SWF(VerboseOutput, TrackedCoverage): actions.append(PushAction(lineno, objects)) elif opcode == AP2Action.INIT_REGISTER: - obj_count = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + obj_count = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 - self.vprint( - f"{prefix} {lineno}: {action_name}", component="bytecode" - ) + self.vprint(f"{prefix} {lineno}: {action_name}", component="bytecode") init_registers: List[Register] = [] while obj_count > 0: - register_no = struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + register_no = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] init_registers.append(Register(register_no)) offset_ptr += 1 obj_count -= 1 @@ -1195,20 +1036,14 @@ class SWF(VerboseOutput, TrackedCoverage): actions.append(InitRegisterAction(lineno, init_registers)) elif opcode == AP2Action.STORE_REGISTER: - obj_count = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + obj_count = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 - self.vprint( - f"{prefix} {lineno}: {action_name}", component="bytecode" - ) + self.vprint(f"{prefix} {lineno}: {action_name}", component="bytecode") store_registers: List[Register] = [] while obj_count > 0: - register_no = struct.unpack( - ">B", datachunk[offset_ptr : (offset_ptr + 1)] - )[0] + register_no = struct.unpack(">B", datachunk[offset_ptr : (offset_ptr + 1)])[0] store_registers.append(Register(register_no)) offset_ptr += 1 obj_count -= 1 @@ -1219,32 +1054,18 @@ class SWF(VerboseOutput, TrackedCoverage): ) self.vprint(f"{prefix} END_{action_name}", component="bytecode") - actions.append( - StoreRegisterAction(lineno, store_registers, preserve_stack=True) - ) + actions.append(StoreRegisterAction(lineno, store_registers, preserve_stack=True)) elif opcode == AP2Action.STORE_REGISTER2: - register_no = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + register_no = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 - self.vprint( - f"{prefix} {lineno}: {action_name}", component="bytecode" - ) - self.vprint( - f"{prefix} REGISTER NO: {register_no}", component="bytecode" - ) + self.vprint(f"{prefix} {lineno}: {action_name}", component="bytecode") + self.vprint(f"{prefix} REGISTER NO: {register_no}", component="bytecode") self.vprint(f"{prefix} END_{action_name}", component="bytecode") - actions.append( - StoreRegisterAction( - lineno, [Register(register_no)], preserve_stack=False - ) - ) + actions.append(StoreRegisterAction(lineno, [Register(register_no)], preserve_stack=False)) elif opcode == AP2Action.IF: - jump_if_true_offset = struct.unpack( - ">h", datachunk[(offset_ptr + 1) : (offset_ptr + 3)] - )[0] + jump_if_true_offset = struct.unpack(">h", datachunk[(offset_ptr + 1) : (offset_ptr + 3)])[0] jump_if_true_offset += lineno + 3 offset_ptr += 3 @@ -1252,13 +1073,9 @@ class SWF(VerboseOutput, TrackedCoverage): f"{prefix} {lineno}: Offset If True: {jump_if_true_offset}", component="bytecode", ) - actions.append( - IfAction(lineno, IfAction.COMP_IS_TRUE, jump_if_true_offset) - ) + actions.append(IfAction(lineno, IfAction.COMP_IS_TRUE, jump_if_true_offset)) elif opcode == AP2Action.IF2: - if2_type, jump_if_true_offset = struct.unpack( - ">Bh", datachunk[(offset_ptr + 1) : (offset_ptr + 4)] - ) + if2_type, jump_if_true_offset = struct.unpack(">Bh", datachunk[(offset_ptr + 1) : (offset_ptr + 4)]) jump_if_true_offset += lineno + 4 offset_ptr += 4 @@ -1268,9 +1085,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) actions.append(IfAction(lineno, if2_type, jump_if_true_offset)) elif opcode == AP2Action.JUMP: - jump_offset = struct.unpack( - ">h", datachunk[(offset_ptr + 1) : (offset_ptr + 3)] - )[0] + jump_offset = struct.unpack(">h", datachunk[(offset_ptr + 1) : (offset_ptr + 3)])[0] jump_offset += lineno + 3 offset_ptr += 3 @@ -1280,9 +1095,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) actions.append(JumpAction(lineno, jump_offset)) elif opcode == AP2Action.WITH: - skip_offset = struct.unpack( - ">H", datachunk[(offset_ptr + 1) : (offset_ptr + 3)] - )[0] + skip_offset = struct.unpack(">H", datachunk[(offset_ptr + 1) : (offset_ptr + 3)])[0] offset_ptr += 3 # TODO: I have absolutely no idea what the data which exists in the bytecode buffer at this point @@ -1295,9 +1108,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) actions.append(WithAction(lineno, unknown_data)) elif opcode == AP2Action.ADD_NUM_VARIABLE: - amount_to_add = struct.unpack( - ">b", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + amount_to_add = struct.unpack(">b", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 self.vprint( @@ -1306,9 +1117,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) actions.append(AddNumVariableAction(lineno, amount_to_add)) elif opcode == AP2Action.GET_URL2: - get_url_action = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + get_url_action = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 self.vprint( @@ -1317,9 +1126,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) actions.append(GetURL2Action(lineno, get_url_action >> 6)) elif opcode == AP2Action.START_DRAG: - constraint = struct.unpack( - ">b", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + constraint = struct.unpack(">b", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 self.vprint( @@ -1329,28 +1136,20 @@ class SWF(VerboseOutput, TrackedCoverage): actions.append( StartDragAction( lineno, - constrain=True - if constraint > 0 - else (False if constraint == 0 else None), + constrain=True if constraint > 0 else (False if constraint == 0 else None), ) ) elif opcode == AP2Action.ADD_NUM_REGISTER: - register_no, amount_to_add = struct.unpack( - ">Bb", datachunk[(offset_ptr + 1) : (offset_ptr + 3)] - ) + register_no, amount_to_add = struct.unpack(">Bb", datachunk[(offset_ptr + 1) : (offset_ptr + 3)]) offset_ptr += 3 self.vprint( f"{prefix} {lineno}: {action_name} Register No: {register_no}, Add Value: {amount_to_add}", component="bytecode", ) - actions.append( - AddNumRegisterAction(lineno, Register(register_no), amount_to_add) - ) + actions.append(AddNumRegisterAction(lineno, Register(register_no), amount_to_add)) elif opcode == AP2Action.GOTO_FRAME2: - flags = struct.unpack( - ">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)] - )[0] + flags = struct.unpack(">B", datachunk[(offset_ptr + 1) : (offset_ptr + 2)])[0] offset_ptr += 2 if flags & 0x1: @@ -1360,9 +1159,7 @@ class SWF(VerboseOutput, TrackedCoverage): if flags & 0x2: # Additional frames to add on top of stack value. - additional_frames = struct.unpack( - ">H", datachunk[offset_ptr : (offset_ptr + 2)] - )[0] + additional_frames = struct.unpack(">H", datachunk[offset_ptr : (offset_ptr + 2)])[0] offset_ptr += 2 else: additional_frames = 0 @@ -1371,13 +1168,9 @@ class SWF(VerboseOutput, TrackedCoverage): f"{prefix} {lineno}: {action_name} AND {post} Additional Frames: {additional_frames}", component="bytecode", ) - actions.append( - GotoFrame2Action(lineno, additional_frames, stop=bool(flags & 0x1)) - ) + actions.append(GotoFrame2Action(lineno, additional_frames, stop=bool(flags & 0x1))) else: - raise Exception( - f"Can't advance, no handler for opcode {opcode} ({hex(opcode)})!" - ) + raise Exception(f"Can't advance, no handler for opcode {opcode} ({hex(opcode)})!") return ByteCode(bytecode_name, actions, offset_ptr) @@ -1397,9 +1190,7 @@ class SWF(VerboseOutput, TrackedCoverage): if size != 4: raise Exception(f"Invalid shape size {size}") - unknown, shape_id = struct.unpack( - " extra_data: # There seems to be some amount of data left over at the end, not sure what it # is or does. I don't see any references to it being used in the tag loader. @@ -2326,9 +2023,7 @@ class SWF(VerboseOutput, TrackedCoverage): return AP2DefineTextTag(text_id, lines) elif tagid == AP2Tag.AP2_DEFINE_EDIT_TEXT: if size != 44: - raise Exception( - f"Invalid size {size} to get data from AP2_DEFINE_EDIT_TEXT!" - ) + raise Exception(f"Invalid size {size} to get data from AP2_DEFINE_EDIT_TEXT!") ( flags, @@ -2339,9 +2034,7 @@ class SWF(VerboseOutput, TrackedCoverage): ) = struct.unpack("> 16) & 0xFF) / 255.0 multcolor.b = float((rgba >> 8) & 0xFF) / 255.0 multcolor.a = float(rgba & 0xFF) / 255.0 - self.vprint( - f"{prefix} Mult Color: {multcolor}", component="tags" - ) + self.vprint(f"{prefix} Mult Color: {multcolor}", component="tags") if flags & 0x4000: # Additive color present, smaller integers. - rgba = struct.unpack( - "> 16) & 0xFF) / 255.0 addcolor.b = float((rgba >> 8) & 0xFF) / 255.0 addcolor.a = float(rgba & 0xFF) / 255.0 - self.vprint( - f"{prefix} Add Color: {addcolor}", component="tags" - ) + self.vprint(f"{prefix} Add Color: {addcolor}", component="tags") if flags & 0x8000: # Some sort of filter data? Not sure what this is either. Needs more investigation # if I encounter files with it. - count, filter_size = struct.unpack( - " bytes: + def __descramble_stringtable(self, scrambled_data: bytes, stringtable_offset: int, stringtable_size: int) -> bytes: data = bytearray(scrambled_data) curstring: List[int] = [] curloc = stringtable_offset @@ -3136,9 +2733,7 @@ class SWF(VerboseOutput, TrackedCoverage): if magic != b"AP2\x00": raise Exception(f"Unrecognzied magic {magic}!") if length != len(data): - raise Exception( - f"Unexpected length in AFP header, {length} != {len(data)}!" - ) + raise Exception(f"Unexpected length in AFP header, {length} != {len(data)}!") if ap2_data_version not in [7, 8, 9, 10]: raise Exception(f"Unsupported AP2 container version {ap2_data_version}!") if version != 0x200: @@ -3199,16 +2794,12 @@ class SWF(VerboseOutput, TrackedCoverage): # Get exported SWF name. self.exported_name = self.__get_string(nameoffset) self.vprint(f"{os.linesep}AFP name: {self.name}", component="core") - self.vprint( - f"Container Version: {hex(self.container_version)}", component="core" - ) + self.vprint(f"Container Version: {hex(self.container_version)}", component="core") self.vprint(f"Version: {hex(self.data_version)}", component="core") self.vprint(f"Exported Name: {self.exported_name}", component="core") self.vprint(f"SWF Flags: {hex(flags)}", component="core") if flags & 0x1: - self.vprint( - f" 0x1: Movie background color: {self.color}", component="core" - ) + self.vprint(f" 0x1: Movie background color: {self.color}", component="core") else: self.vprint(" 0x1: No movie background color", component="core") if flags & 0x2: @@ -3216,13 +2807,9 @@ class SWF(VerboseOutput, TrackedCoverage): else: self.vprint(" 0x2: FPS is a float", component="core") if flags & 0x4: - self.vprint( - " 0x4: Imported tag initializer section present", component="core" - ) + self.vprint(" 0x4: Imported tag initializer section present", component="core") else: - self.vprint( - " 0x4: Imported tag initializer section not present", component="core" - ) + self.vprint(" 0x4: Imported tag initializer section not present", component="core") self.vprint( f"Dimensions: {int(self.location.width)}x{int(self.location.height)}", component="core", @@ -3239,9 +2826,7 @@ class SWF(VerboseOutput, TrackedCoverage): self.exported_tags = {} self.vprint(f"Number of Exported Tags: {num_exported_assets}", component="tags") for assetno in range(num_exported_assets): - asset_tag_id, asset_string_offset = struct.unpack( - "= len(self.frames): - raise Exception( - f"Unexpected frame {frame}, we only have {len(self.frames)} frames in this movie!" - ) + raise Exception(f"Unexpected frame {frame}, we only have {len(self.frames)} frames in this movie!") self.frames[frame].imported_tags.append(TagPointer(tag_id, bytecode)) if verbose: diff --git a/bemani/format/afp/types/ap2.py b/bemani/format/afp/types/ap2.py index 4f4775e..5e1a40a 100644 --- a/bemani/format/afp/types/ap2.py +++ b/bemani/format/afp/types/ap2.py @@ -715,9 +715,7 @@ class AP2Action: class DefineFunction2Action(AP2Action): - def __init__( - self, offset: int, name: Optional[str], flags: int, body: "ByteCode" - ) -> None: + def __init__(self, offset: int, name: Optional[str], flags: int, body: "ByteCode") -> None: super().__init__(offset, AP2Action.DEFINE_FUNCTION2) self.name = name self.flags = flags @@ -792,9 +790,7 @@ class InitRegisterAction(AP2Action): class StoreRegisterAction(AP2Action): - def __init__( - self, offset: int, registers: List[Register], preserve_stack: bool - ) -> None: + def __init__(self, offset: int, registers: List[Register], preserve_stack: bool) -> None: super().__init__(offset, AP2Action.STORE_REGISTER) self.registers = registers self.preserve_stack = preserve_stack diff --git a/bemani/format/afp/types/expression.py b/bemani/format/afp/types/expression.py index 0bbb132..c84c6de 100644 --- a/bemani/format/afp/types/expression.py +++ b/bemani/format/afp/types/expression.py @@ -11,9 +11,7 @@ class Expression: # Any thing that can be evaluated for a result, such as a variable # reference, function call, or mathematical operation. def render(self, parent_prefix: str, nested: bool = False) -> str: - raise NotImplementedError( - f"{self.__class__.__name__} does not implement render()!" - ) + raise NotImplementedError(f"{self.__class__.__name__} does not implement render()!") class GenericObject(Expression): @@ -2039,8 +2037,7 @@ class Object(Expression): def render(self, parent_prefix: str, nested: bool = False) -> str: params = [ - f"{value_ref(key, parent_prefix)}: {value_ref(val, parent_prefix)}" - for (key, val) in self.params.items() + f"{value_ref(key, parent_prefix)}: {value_ref(val, parent_prefix)}" for (key, val) in self.params.items() ] lpar = "{" rpar = "}" @@ -2050,9 +2047,7 @@ class Object(Expression): class FunctionCall(Expression): # Call a method on an object. - def __init__( - self, insertion_ref: int, name: Union[str, StringConstant], params: List[Any] - ) -> None: + def __init__(self, insertion_ref: int, name: Union[str, StringConstant], params: List[Any]) -> None: self.insertion_ref = insertion_ref self.name = name self.params = params @@ -2182,9 +2177,7 @@ class Member(Expression): # The following are helpers which facilitate rendering out various parts of expressions. def object_ref(obj: Any, parent_prefix: str) -> str: - if isinstance( - obj, (GenericObject, Variable, Member, MethodCall, FunctionCall, Register) - ): + if isinstance(obj, (GenericObject, Variable, Member, MethodCall, FunctionCall, Register)): return obj.render(parent_prefix, nested=True) else: raise Exception(f"Unsupported objectref {obj} ({type(obj)})") diff --git a/bemani/format/afp/types/generic.py b/bemani/format/afp/types/generic.py index 8edeefe..da366e5 100644 --- a/bemani/format/afp/types/generic.py +++ b/bemani/format/afp/types/generic.py @@ -255,9 +255,7 @@ class Matrix: return new @staticmethod - def affine( - *, a: float, b: float, c: float, d: float, tx: float, ty: float - ) -> "Matrix": + def affine(*, a: float, b: float, c: float, d: float, tx: float, ty: float) -> "Matrix": return Matrix( a11=a, a12=b, @@ -414,27 +412,15 @@ class Matrix: @property def xscale(self) -> float: - return math.sqrt( - (self.__a11 * self.__a11) - + (self.__a12 * self.__a12) - + (self.__a13 * self.__a13) - ) + return math.sqrt((self.__a11 * self.__a11) + (self.__a12 * self.__a12) + (self.__a13 * self.__a13)) @property def yscale(self) -> float: - return math.sqrt( - (self.__a21 * self.__a21) - + (self.__a22 * self.__a22) - + (self.__a23 * self.__a23) - ) + return math.sqrt((self.__a21 * self.__a21) + (self.__a22 * self.__a22) + (self.__a23 * self.__a23)) @property def zscale(self) -> float: - return math.sqrt( - (self.__a31 * self.__a31) - + (self.__a32 * self.__a32) - + (self.__a33 * self.__a33) - ) + return math.sqrt((self.__a31 * self.__a31) + (self.__a32 * self.__a32) + (self.__a33 * self.__a33)) @property def a(self) -> float: @@ -613,18 +599,9 @@ class Matrix: def multiply_point(self, point: Point) -> Point: return Point( - x=(self.__a11 * point.x) - + (self.__a21 * point.y) - + (self.__a31 * point.z) - + self.__a41, - y=(self.__a12 * point.x) - + (self.__a22 * point.y) - + (self.__a32 * point.z) - + self.__a42, - z=(self.__a13 * point.x) - + (self.__a23 * point.y) - + (self.__a33 * point.z) - + self.__a43, + x=(self.__a11 * point.x) + (self.__a21 * point.y) + (self.__a31 * point.z) + self.__a41, + y=(self.__a12 * point.x) + (self.__a22 * point.y) + (self.__a32 * point.z) + self.__a42, + z=(self.__a13 * point.x) + (self.__a23 * point.y) + (self.__a33 * point.z) + self.__a43, ) def translate(self, point: Point) -> "Matrix": @@ -646,45 +623,18 @@ class Matrix: def multiply(self, other: "Matrix") -> "Matrix": return Matrix( - a11=self.__a11 * other.__a11 - + self.__a12 * other.__a21 - + self.__a13 * other.__a31, - a12=self.__a11 * other.__a12 - + self.__a12 * other.__a22 - + self.__a13 * other.__a32, - a13=self.__a11 * other.__a13 - + self.__a12 * other.__a23 - + self.__a13 * other.__a33, - a21=self.__a21 * other.__a11 - + self.__a22 * other.__a21 - + self.__a23 * other.__a31, - a22=self.__a21 * other.__a12 - + self.__a22 * other.__a22 - + self.__a23 * other.__a32, - a23=self.__a21 * other.__a13 - + self.__a22 * other.__a23 - + self.__a23 * other.__a33, - a31=self.__a31 * other.__a11 - + self.__a32 * other.__a21 - + self.__a33 * other.__a31, - a32=self.__a31 * other.__a12 - + self.__a32 * other.__a22 - + self.__a33 * other.__a32, - a33=self.__a31 * other.__a13 - + self.__a32 * other.__a23 - + self.__a33 * other.__a33, - a41=self.__a41 * other.__a11 - + self.__a42 * other.__a21 - + self.__a43 * other.__a31 - + other.__a41, - a42=self.__a41 * other.__a12 - + self.__a42 * other.__a22 - + self.__a43 * other.__a32 - + other.__a42, - a43=self.__a41 * other.__a13 - + self.__a42 * other.__a23 - + self.__a43 * other.__a33 - + other.__a43, + a11=self.__a11 * other.__a11 + self.__a12 * other.__a21 + self.__a13 * other.__a31, + a12=self.__a11 * other.__a12 + self.__a12 * other.__a22 + self.__a13 * other.__a32, + a13=self.__a11 * other.__a13 + self.__a12 * other.__a23 + self.__a13 * other.__a33, + a21=self.__a21 * other.__a11 + self.__a22 * other.__a21 + self.__a23 * other.__a31, + a22=self.__a21 * other.__a12 + self.__a22 * other.__a22 + self.__a23 * other.__a32, + a23=self.__a21 * other.__a13 + self.__a22 * other.__a23 + self.__a23 * other.__a33, + a31=self.__a31 * other.__a11 + self.__a32 * other.__a21 + self.__a33 * other.__a31, + a32=self.__a31 * other.__a12 + self.__a32 * other.__a22 + self.__a33 * other.__a32, + a33=self.__a31 * other.__a13 + self.__a32 * other.__a23 + self.__a33 * other.__a33, + a41=self.__a41 * other.__a11 + self.__a42 * other.__a21 + self.__a43 * other.__a31 + other.__a41, + a42=self.__a41 * other.__a12 + self.__a42 * other.__a22 + self.__a43 * other.__a32 + other.__a42, + a43=self.__a41 * other.__a13 + self.__a42 * other.__a23 + self.__a43 * other.__a33 + other.__a43, ) def inverse(self) -> "Matrix": @@ -704,9 +654,7 @@ class Matrix: [self.__a31, self.__a32, self.__a33, 0.0], [self.__a41, self.__a42, self.__a43, 1.0], ] - inverse: List[List[float]] = [ - [1 if row == col else 0 for col in range(size)] for row in range(size) - ] + inverse: List[List[float]] = [[1 if row == col else 0 for col in range(size)] for row in range(size)] for col in range(size): # First, get upper triangle of the matrix. @@ -764,10 +712,7 @@ class Matrix: ] inverse = [ *inverse[:row], - [ - inverse[row][i] + inverse[col][i] * factor - for i in range(size) - ], + [inverse[row][i] + inverse[col][i] * factor for i in range(size)], *inverse[(row + 1) :], ] diff --git a/bemani/format/afp/types/statement.py b/bemani/format/afp/types/statement.py index 44e57ee..6c70070 100644 --- a/bemani/format/afp/types/statement.py +++ b/bemani/format/afp/types/statement.py @@ -23,9 +23,7 @@ class ConvertedAction: class Statement(ConvertedAction): # This is just a type class for finished statements. def render(self, prefix: str) -> List[str]: - raise NotImplementedError( - f"{self.__class__.__name__} does not implement render()!" - ) + raise NotImplementedError(f"{self.__class__.__name__} does not implement render()!") class DefineLabelStatement(Statement): @@ -61,9 +59,7 @@ class GotoStatement(Statement): # A goto, including the ID of the chunk we want to jump to. def __init__(self, location: int) -> None: if location < 0: - raise Exception( - f"Logic error, attempting to go to artificially inserted location {location}!" - ) + raise Exception(f"Logic error, attempting to go to artificially inserted location {location}!") self.location = location @@ -122,9 +118,7 @@ class NopStatement(Statement): def render(self, prefix: str) -> List[str]: # We should never render this! - raise Exception( - "Logic error, a NopStatement should never make it to the render stage!" - ) + raise Exception("Logic error, a NopStatement should never make it to the render stage!") class ExpressionStatement(Statement): @@ -271,9 +265,7 @@ class GetURL2Statement(Statement): class SetMemberStatement(Statement): # Call a method on an object. - def __init__( - self, objectref: Any, name: Union[str, int, Expression], valueref: Any - ) -> None: + def __init__(self, objectref: Any, name: Union[str, int, Expression], valueref: Any) -> None: self.objectref = objectref self.name = name self.valueref = valueref @@ -485,9 +477,7 @@ class AndIf(IfExpr): # for a fact that this if can never be true. self.__false = True else: - self.__false = ( - self.left.is_always_false() or self.right.is_always_false() - ) + self.__false = self.left.is_always_false() or self.right.is_always_false() return self.__false def simplify(self) -> "IfExpr": @@ -562,16 +552,11 @@ class AndIf(IfExpr): def __hash__(self) -> int: if self.__hash is None: - self.__hash = hash( - "AND:" + ",".join(sorted(str(hash(s)) for s in set(_gather_and(self)))) - ) + self.__hash = hash("AND:" + ",".join(sorted(str(hash(s)) for s in set(_gather_and(self))))) return self.__hash def __repr__(self) -> str: - return " && ".join( - (f"({c!r})" if isinstance(c, (AndIf, OrIf)) else repr(c)) - for c in _gather_and(self) - ) + return " && ".join((f"({c!r})" if isinstance(c, (AndIf, OrIf)) else repr(c)) for c in _gather_and(self)) class OrIf(IfExpr): @@ -687,16 +672,11 @@ class OrIf(IfExpr): def __hash__(self) -> int: if self.__hash is None: - self.__hash = hash( - "OR:" + ",".join(sorted(str(hash(s)) for s in set(_gather_or(self)))) - ) + self.__hash = hash("OR:" + ",".join(sorted(str(hash(s)) for s in set(_gather_or(self))))) return self.__hash def __repr__(self) -> str: - return " || ".join( - (f"({c!r})" if isinstance(c, (AndIf, OrIf)) else repr(c)) - for c in _gather_or(self) - ) + return " || ".join((f"({c!r})" if isinstance(c, (AndIf, OrIf)) else repr(c)) for c in _gather_or(self)) def _gather_and(obj: IfExpr) -> List[IfExpr]: @@ -733,9 +713,7 @@ def _factor_and(left: IfExpr, right: IfExpr) -> Optional[IfExpr]: if not left_ors or not right_ors: return _accum_or(commons).simplify() - return OrIf( - _accum_or(commons), AndIf(_accum_or(left_ors), _accum_or(right_ors)) - ).simplify() + return OrIf(_accum_or(commons), AndIf(_accum_or(left_ors), _accum_or(right_ors))).simplify() else: return None @@ -800,9 +778,7 @@ def _factor_or(left: IfExpr, right: IfExpr) -> Optional[IfExpr]: if not left_ands or not right_ands: return _accum_and(commons).simplify() - return AndIf( - _accum_and(commons), OrIf(_accum_and(left_ands), _accum_and(right_ands)) - ).simplify() + return AndIf(_accum_and(commons), OrIf(_accum_and(left_ands), _accum_and(right_ands))).simplify() else: return None @@ -940,13 +916,9 @@ class TwoParameterIf(IfExpr): if self.comp == self.GT_EQUALS: return TwoParameterIf(self.conditional1, self.LT, self.conditional2) if self.comp == self.STRICT_EQUALS: - return TwoParameterIf( - self.conditional1, self.STRICT_NOT_EQUALS, self.conditional2 - ) + return TwoParameterIf(self.conditional1, self.STRICT_NOT_EQUALS, self.conditional2) if self.comp == self.STRICT_NOT_EQUALS: - return TwoParameterIf( - self.conditional1, self.STRICT_EQUALS, self.conditional2 - ) + return TwoParameterIf(self.conditional1, self.STRICT_EQUALS, self.conditional2) raise Exception(f"Cannot invert {self.comp}!") def swap(self) -> "TwoParameterIf": @@ -963,13 +935,9 @@ class TwoParameterIf(IfExpr): if self.comp == self.GT_EQUALS: return TwoParameterIf(self.conditional2, self.LT_EQUALS, self.conditional1) if self.comp == self.STRICT_EQUALS: - return TwoParameterIf( - self.conditional2, self.STRICT_EQUALS, self.conditional1 - ) + return TwoParameterIf(self.conditional2, self.STRICT_EQUALS, self.conditional1) if self.comp == self.STRICT_NOT_EQUALS: - return TwoParameterIf( - self.conditional2, self.STRICT_NOT_EQUALS, self.conditional1 - ) + return TwoParameterIf(self.conditional2, self.STRICT_NOT_EQUALS, self.conditional1) raise Exception(f"Cannot swap {self.comp}!") def __repr__(self) -> str: @@ -1009,9 +977,7 @@ class IfStatement(Statement): ] ) else: - return os.linesep.join( - [f"if ({self.cond}) {{", os.linesep.join(true_entries), "}"] - ) + return os.linesep.join([f"if ({self.cond}) {{", os.linesep.join(true_entries), "}"]) def render(self, prefix: str) -> List[str]: true_entries: List[str] = [] @@ -1136,9 +1102,7 @@ class WhileStatement(DoWhileStatement): for statement in self.body: entries.extend([f" {s}" for s in str(statement).split(os.linesep)]) - return os.linesep.join( - [f"while ({self.cond}) {{", os.linesep.join(entries), "}"] - ) + return os.linesep.join([f"while ({self.cond}) {{", os.linesep.join(entries), "}"]) def render(self, prefix: str) -> List[str]: entries: List[str] = [] diff --git a/bemani/format/afp/util.py b/bemani/format/afp/util.py index be95263..9b2383b 100644 --- a/bemani/format/afp/util.py +++ b/bemani/format/afp/util.py @@ -69,9 +69,7 @@ class TrackedCoverage: raise Exception(f"Already covered {hex(offset)}!") self.coverage[i] = True - def print_coverage( - self, req_start: Optional[int] = None, req_end: Optional[int] = None - ) -> None: + def print_coverage(self, req_start: Optional[int] = None, req_end: Optional[int] = None) -> None: for start, offset in self.get_uncovered_chunks(req_start, req_end): print( f"Uncovered: {hex(start)} - {hex(offset)} ({offset-start} bytes)", @@ -165,9 +163,7 @@ class VerboseOutput: return VerboseOutputManager(self, verbose) def vprint(self, *args: Any, **kwargs: Any) -> None: - should_print = self.verbose or ( - kwargs.get("component", None) in self.components - ) + should_print = self.verbose or (kwargs.get("component", None) in self.components) kwargs = {k: v for k, v in kwargs.items() if k != "component"} if should_print: print(*args, **kwargs, file=sys.stderr) diff --git a/bemani/format/arc.py b/bemani/format/arc.py index 130c890..f47181f 100644 --- a/bemani/format/arc.py +++ b/bemani/format/arc.py @@ -28,9 +28,7 @@ class ARC: for fno in range(numfiles): start = 16 + (16 * fno) end = start + 16 - (nameoffset, fileoffset, uncompressedsize, compressedsize) = struct.unpack( - " Tuple[int, int, int]: # This function converts RGB565 format to raw pixels @@ -39,12 +37,7 @@ class DXTBuffer: def swapbytes(self, data: bytes, swap: bool) -> bytes: if swap: - return b"".join( - [ - data[(x + 1) : (x + 2)] + data[x : (x + 1)] - for x in range(0, len(data), 2) - ] - ) + return b"".join([data[(x + 1) : (x + 2)] + data[x : (x + 1)] for x in range(0, len(data), 2)]) return data def DXT5Decompress(self, filedata: bytes, swap: bool = False) -> bytes: @@ -53,9 +46,7 @@ class DXTBuffer: for row in range(self.block_county): for col in range(self.block_countx): # Get the alpha values, and color lookup table - a0, a1, acode0, acode1, c0, c1, ctable = struct.unpack( - " None: - code = ( - ctable >> (2 * ((4 * j) + i)) - ) & 0x03 # Get the color of the current pixel + code = (ctable >> (2 * ((4 * j) + i))) & 0x03 # Get the color of the current pixel pixel_color = None r0, g0, b0 = self.unpackRGB(c0) @@ -146,9 +133,7 @@ class DXTBuffer: # While not surpassing the image dimensions, assign pixels the colors. if pixel_color is not None and (x + i) < self.width and (y + j) < self.height: - self.decompressed_buffer[(y + j) * self.width + (x + i)] = struct.pack( - " int: # Using the same method as the colors calculate the alpha values diff --git a/bemani/format/ifs.py b/bemani/format/ifs.py index 804ba23..d32f799 100644 --- a/bemani/format/ifs.py +++ b/bemani/format/ifs.py @@ -77,10 +77,7 @@ class IFS: if header is None: # Now, try as XML xenc = XmlEncoding() - header = xenc.decode( - b'' - + data[header_offset:data_index].split(b"\0")[0] - ) + header = xenc.decode(b'' + data[header_offset:data_index].split(b"\0")[0]) if header is None: raise Exception("Invalid IFS file!") @@ -109,9 +106,7 @@ class IFS: def get_children(parent: str, node: Node) -> None: real_name = self.__fix_name(node.name) if node.data_type == "3s32": - node_name = os.path.join(parent, real_name).replace( - f"{os.sep}imgfs{os.sep}", "" - ) + node_name = os.path.join(parent, real_name).replace(f"{os.sep}imgfs{os.sep}", "") ref = None for subnode in node.children: if subnode.name == "i": @@ -147,9 +142,7 @@ class IFS: ifsdata = self.__loader(external_file) if ifsdata is None: - raise Exception( - f"Couldn't extract file data for {fn} referencing IFS file {external_file}!" - ) + raise Exception(f"Couldn't extract file data for {fn} referencing IFS file {external_file}!") else: otherdata[external_file] = ifsdata @@ -178,17 +171,13 @@ class IFS: # Now, try as XML xenc = XmlEncoding() encoding = "ascii" - texdata = xenc.decode( - b'' + self.__files[filename] - ) + texdata = xenc.decode(b'' + self.__files[filename]) if texdata is None: continue else: if benc.encoding is None: - raise Exception( - "Logic error, expected an encoding from binary decoder!" - ) + raise Exception("Logic error, expected an encoding from binary decoder!") encoding = benc.encoding if texdata.name != "texturelist": @@ -271,17 +260,13 @@ class IFS: # Now, try as XML xenc = XmlEncoding() encoding = "ascii" - afpdata = xenc.decode( - b'' + self.__files[filename] - ) + afpdata = xenc.decode(b'' + self.__files[filename]) if afpdata is None: continue else: if benc.encoding is None: - raise Exception( - "Logic error, expected an encoding from binary decoder!" - ) + raise Exception("Logic error, expected an encoding from binary decoder!") encoding = benc.encoding if afpdata.name != "afplist": diff --git a/bemani/format/iidxchart.py b/bemani/format/iidxchart.py index 5c917de..72ec59a 100644 --- a/bemani/format/iidxchart.py +++ b/bemani/format/iidxchart.py @@ -40,9 +40,7 @@ class IIDXChart: continue while True: - time, event, side, value = struct.unpack( - " List[IIDXSong]: - return sorted( - [self.__songs[mid][0] for mid in self.__songs], key=lambda song: song.id - ) + return sorted([self.__songs[mid][0] for mid in self.__songs], key=lambda song: song.id) @property def songids(self) -> List[int]: diff --git a/bemani/format/tdxt.py b/bemani/format/tdxt.py index 6e73aa7..374cb3b 100644 --- a/bemani/format/tdxt.py +++ b/bemani/format/tdxt.py @@ -136,9 +136,7 @@ class TDXT: endian=endian, length_fixup=length_fixup, raw=raw_data[64:], - img=TDXT._rawToImg( - width, height, fmt, endian, invert_channels, raw_data[64:] - ), + img=TDXT._rawToImg(width, height, fmt, endian, invert_channels, raw_data[64:]), invert_channels=invert_channels, ) diff --git a/bemani/format/twodx.py b/bemani/format/twodx.py index d8dc8b6..8c11586 100644 --- a/bemani/format/twodx.py +++ b/bemani/format/twodx.py @@ -56,9 +56,7 @@ class TwoDX: @property def name(self) -> str: if self.__name is None: - raise Exception( - "Logic error, tried to get name of 2dx file before setting it or parsing file!" - ) + raise Exception("Logic error, tried to get name of 2dx file before setting it or parsing file!") return self.__name def set_name(self, name: str) -> None: diff --git a/bemani/frontend/account/account.py b/bemani/frontend/account/account.py index c80ced2..1658c90 100644 --- a/bemani/frontend/account/account.py +++ b/bemani/frontend/account/account.py @@ -73,11 +73,7 @@ def login() -> Response: @account_pages.route("/login") @loginprohibited def viewlogin() -> Response: - return Response( - render_template( - "account/login.html", **{"title": "Log In", "show_navigation": False} - ) - ) + return Response(render_template("account/login.html", **{"title": "Log In", "show_navigation": False})) def register_display(card_number: str, username: str, email: str) -> Response: diff --git a/bemani/frontend/admin/admin.py b/bemani/frontend/admin/admin.py index d65c8b6..ac5f6b0 100644 --- a/bemani/frontend/admin/admin.py +++ b/bemani/frontend/admin/admin.py @@ -161,26 +161,14 @@ def viewevents() -> Response: "Events", "admin/events.react.js", { - "events": [ - format_event(event) - for event in g.data.local.network.get_events(limit=100) - ], - "users": { - user.id: user.username for user in g.data.local.user.get_all_users() - }, - "arcades": { - arcade.id: arcade.name - for arcade in g.data.local.machine.get_all_arcades() - }, + "events": [format_event(event) for event in g.data.local.network.get_events(limit=100)], + "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, + "arcades": {arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades()}, "iidxsongs": iidx.get_all_songs(), "jubeatsongs": jubeat.get_all_songs(), "pnmsongs": pnm.get_all_songs(), - "iidxversions": { - version: name for (game, version, name) in iidx.all_games() - }, - "jubeatversions": { - version: name for (game, version, name) in jubeat.all_games() - }, + "iidxversions": {version: name for (game, version, name) in iidx.all_games()}, + "jubeatversions": {version: name for (game, version, name) in jubeat.all_games()}, "pnmversions": {version: name for (game, version, name) in pnm.all_games()}, }, { @@ -205,10 +193,7 @@ def viewevents() -> Response: @adminrequired def backfillevents(until: int) -> Dict[str, Any]: return { - "events": [ - format_event(event) - for event in g.data.local.network.get_events(until_id=until, limit=1000) - ], + "events": [format_event(event) for event in g.data.local.network.get_events(until_id=until, limit=1000)], } @@ -217,14 +202,9 @@ def backfillevents(until: int) -> Dict[str, Any]: @adminrequired def listevents(since: int) -> Dict[str, Any]: return { - "events": [ - format_event(event) - for event in g.data.local.network.get_events(since_id=since) - ], + "events": [format_event(event) for event in g.data.local.network.get_events(since_id=since)], "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, - "arcades": { - arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades() - }, + "arcades": {arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades()}, } @@ -235,12 +215,8 @@ def viewapi() -> Response: "Data API", "admin/api.react.js", { - "clients": [ - format_client(client) for client in g.data.local.api.get_all_clients() - ], - "servers": [ - format_server(server) for server in g.data.local.api.get_all_servers() - ], + "clients": [format_client(client) for client in g.data.local.api.get_all_clients()], + "servers": [format_server(server) for server in g.data.local.api.get_all_servers()], }, { "addclient": url_for("admin_pages.addclient"), @@ -261,10 +237,7 @@ def viewarcades() -> Response: "Arcades", "admin/arcades.react.js", { - "arcades": [ - format_arcade(arcade) - for arcade in g.data.local.machine.get_all_arcades() - ], + "arcades": [format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades()], "regions": RegionConstants.LUT, "usernames": g.data.local.user.get_all_usernames(), "paseli_enabled": g.config.paseli.enabled, @@ -294,14 +267,8 @@ def viewmachines() -> Response: "Machines", "admin/machines.react.js", { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], - "arcades": { - arcade.id: arcade.name - for arcade in g.data.local.machine.get_all_arcades() - }, + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], + "arcades": {arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades()}, "series": { GameConstants.BISHI_BASHI.value: "BishiBashi", GameConstants.DDR.value: "DDR", @@ -384,9 +351,7 @@ def viewgamesettings() -> Response: "Game Settings", "admin/gamesettings.react.js", { - "game_settings": get_game_settings( - g.data, g.data.local.machine.DEFAULT_SETTINGS_ARCADE - ), + "game_settings": get_game_settings(g.data, g.data.local.machine.DEFAULT_SETTINGS_ARCADE), }, { "update_settings": url_for("admin_pages.updatesettings"), @@ -419,15 +384,10 @@ def viewuser(userid: int) -> Response: }, "cards": cards, "arcades": {arcade.id: arcade.name for arcade in arcades}, - "balances": { - arcade.id: g.data.local.user.get_balance(userid, arcade.id) - for arcade in arcades - }, + "balances": {arcade.id: g.data.local.user.get_balance(userid, arcade.id) for arcade in arcades}, "events": [ format_event(event) - for event in g.data.local.network.get_events( - userid=userid, event="paseli_transaction" - ) + for event in g.data.local.network.get_events(userid=userid, event="paseli_transaction") ], }, { @@ -461,15 +421,9 @@ def listuser(userid: int) -> Dict[str, Any]: return { "cards": cards, "arcades": {arcade.id: arcade.name for arcade in arcades}, - "balances": { - arcade.id: g.data.local.user.get_balance(userid, arcade.id) - for arcade in arcades - }, + "balances": {arcade.id: g.data.local.user.get_balance(userid, arcade.id) for arcade in arcades}, "events": [ - format_event(event) - for event in g.data.local.network.get_events( - userid=userid, event="paseli_transaction" - ) + format_event(event) for event in g.data.local.network.get_events(userid=userid, event="paseli_transaction") ], } @@ -479,13 +433,8 @@ def listuser(userid: int) -> Dict[str, Any]: @adminrequired def listmachines() -> Dict[str, Any]: return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], - "arcades": { - arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades() - }, + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], + "arcades": {arcade.id: arcade.name for arcade in g.data.local.machine.get_all_arcades()}, } @@ -517,9 +466,7 @@ def updatearcade() -> Dict[str, Any]: # Just return all arcades for ease of updating return { - "arcades": [ - format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades() - ], + "arcades": [format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades()], } @@ -556,9 +503,7 @@ def addarcade() -> Dict[str, Any]: # Just return all arcades for ease of updating return { - "arcades": [ - format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades() - ], + "arcades": [format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades()], } @@ -575,9 +520,7 @@ def removearcade() -> Dict[str, Any]: # Just return all arcades for ease of updating return { - "arcades": [ - format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades() - ], + "arcades": [format_arcade(arcade) for arcade in g.data.local.machine.get_all_arcades()], } @@ -599,9 +542,7 @@ def updateclient() -> Dict[str, Any]: # Just return all clients for ease of updating return { - "clients": [ - format_client(client) for client in g.data.local.api.get_all_clients() - ], + "clients": [format_client(client) for client in g.data.local.api.get_all_clients()], } @@ -621,9 +562,7 @@ def addclient() -> Dict[str, Any]: # Just return all clientss for ease of updating return { - "clients": [ - format_client(client) for client in g.data.local.api.get_all_clients() - ], + "clients": [format_client(client) for client in g.data.local.api.get_all_clients()], } @@ -640,9 +579,7 @@ def removeclient() -> Dict[str, Any]: # Just return all clients for ease of updating return { - "clients": [ - format_client(client) for client in g.data.local.api.get_all_clients() - ], + "clients": [format_client(client) for client in g.data.local.api.get_all_clients()], } @@ -662,9 +599,7 @@ def queryserver(serverid: int) -> Dict[str, Any]: "name": serverinfo["name"], "email": serverinfo["email"], } - info["status"] = ( - "ok" if APIClient.API_VERSION in serverinfo["versions"] else "badversion" - ) + info["status"] = "ok" if APIClient.API_VERSION in serverinfo["versions"] else "badversion" except NotAuthorizedAPIException: info = { "name": "unknown", @@ -704,9 +639,7 @@ def updateserver() -> Dict[str, Any]: # Just return all servers for ease of updating return { - "servers": [ - format_server(server) for server in g.data.local.api.get_all_servers() - ], + "servers": [format_server(server) for server in g.data.local.api.get_all_servers()], } @@ -729,9 +662,7 @@ def addserver() -> Dict[str, Any]: # Just return all serverss for ease of updating return { - "servers": [ - format_server(server) for server in g.data.local.api.get_all_servers() - ], + "servers": [format_server(server) for server in g.data.local.api.get_all_servers()], } @@ -748,9 +679,7 @@ def removeserver() -> Dict[str, Any]: # Just return all servers for ease of updating return { - "servers": [ - format_server(server) for server in g.data.local.api.get_all_servers() - ], + "servers": [format_server(server) for server in g.data.local.api.get_all_servers()], } @@ -770,22 +699,15 @@ def generatepcbid() -> Dict[str, Any]: pcbid: Optional[str] = None while pcbid is None: # Generate a new PCBID, check for uniqueness - potential_pcbid = "01201000000000" + "".join( - [random.choice("0123456789ABCDEF") for _ in range(6)] - ) + potential_pcbid = "01201000000000" + "".join([random.choice("0123456789ABCDEF") for _ in range(6)]) if g.data.local.machine.get_machine(potential_pcbid) is None: pcbid = potential_pcbid - g.data.local.machine.create_machine( - pcbid, name, new_pcbid["description"], new_pcbid["arcade"] - ) + g.data.local.machine.create_machine(pcbid, name, new_pcbid["description"], new_pcbid["arcade"]) # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], } @@ -801,9 +723,7 @@ def addpcbid() -> Dict[str, Any]: raise Exception("Unable to find arcade to link PCBID to!") # Verify that the PCBID is valid - potential_pcbid = "".join( - [c for c in new_pcbid["pcbid"].upper() if c in "0123456789ABCDEF"] - ) + potential_pcbid = "".join([c for c in new_pcbid["pcbid"].upper() if c in "0123456789ABCDEF"]) if len(potential_pcbid) != len(new_pcbid["pcbid"]): raise Exception("Invalid characters in PCBID!") if len(potential_pcbid) != 20: @@ -814,16 +734,11 @@ def addpcbid() -> Dict[str, Any]: # Will be set by the game on boot. name = "なし" - g.data.local.machine.create_machine( - potential_pcbid, name, new_pcbid["description"], new_pcbid["arcade"] - ) + g.data.local.machine.create_machine(potential_pcbid, name, new_pcbid["description"], new_pcbid["arcade"]) # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], } @@ -850,18 +765,13 @@ def updatepcbid() -> Dict[str, Any]: current_machine.description = machine["description"] current_machine.arcade = machine["arcade"] current_machine.port = machine["port"] - current_machine.game = ( - None if machine["game"] == "any" else GameConstants(machine["game"]) - ) + current_machine.game = None if machine["game"] == "any" else GameConstants(machine["game"]) current_machine.version = None if machine["game"] == "any" else machine["version"] g.data.local.machine.put_machine(current_machine) # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], } @@ -878,10 +788,7 @@ def removepcbid() -> Dict[str, Any]: # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines() - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines()], } @@ -963,11 +870,7 @@ def searchusers() -> Dict[str, Any]: return True return { - "users": [ - format_user(user) - for user in g.data.local.user.get_all_users() - if match(user) - ], + "users": [format_user(user) for user in g.data.local.user.get_all_users() if match(user)], } @@ -1003,15 +906,9 @@ def updatebalance(userid: int) -> Dict[str, Any]: return { "arcades": {arcade.id: arcade.name for arcade in arcades}, - "balances": { - arcade.id: g.data.local.user.get_balance(userid, arcade.id) - for arcade in arcades - }, + "balances": {arcade.id: g.data.local.user.get_balance(userid, arcade.id) for arcade in arcades}, "events": [ - format_event(event) - for event in g.data.local.network.get_events( - userid=userid, event="paseli_transaction" - ) + format_event(event) for event in g.data.local.network.get_events(userid=userid, event="paseli_transaction") ], } @@ -1144,9 +1041,7 @@ def removeusercard(userid: int) -> Dict[str, Any]: # Return new card list return { - "cards": [ - CardCipher.encode(card) for card in g.data.local.user.get_cards(userid) - ], + "cards": [CardCipher.encode(card) for card in g.data.local.user.get_cards(userid)], } @@ -1178,9 +1073,7 @@ def addusercard(userid: int) -> Dict[str, Any]: # Return new card list return { - "cards": [ - CardCipher.encode(card) for card in g.data.local.user.get_cards(userid) - ], + "cards": [CardCipher.encode(card) for card in g.data.local.user.get_cards(userid)], } @@ -1261,24 +1154,18 @@ def updatesettings() -> Dict[str, Any]: new_value = game_setting["value"] # Update the value - current_settings = g.data.local.machine.get_settings( - arcadeid, game, version, category - ) + current_settings = g.data.local.machine.get_settings(arcadeid, game, version, category) if current_settings is None: current_settings = ValidatedDict() getattr(current_settings, update_function)(setting, new_value) # Save it back - g.data.local.machine.put_settings( - arcadeid, game, version, category, current_settings - ) + g.data.local.machine.put_settings(arcadeid, game, version, category, current_settings) # Return the updated value return { "game_settings": [ - gs - for gs in get_game_settings(g.data, arcadeid) - if gs["game"] == game.value and gs["version"] == version + gs for gs in get_game_settings(g.data, arcadeid) if gs["game"] == game.value and gs["version"] == version ][0], } diff --git a/bemani/frontend/app.py b/bemani/frontend/app.py index 0c07acf..c276c6e 100644 --- a/bemani/frontend/app.py +++ b/bemani/frontend/app.py @@ -99,9 +99,7 @@ def adminrequired(func: Callable) -> Callable: else: user = g.data.local.user.get_user(g.userID) if not user.admin: - return Response( - render_template("403.html", **{"title": "403 Forbidden"}), 403 - ) + return Response(render_template("403.html", **{"title": "403 Forbidden"}), 403) else: return func(*args, **kwargs) @@ -169,9 +167,7 @@ def jsx(filename: str) -> Response: if jsx is None: with open(jsxfile, "rb") as f: transformer = JSXTransformer() - jsx = transformer.transform_string( - polyfill_fragments(f.read().decode("utf-8")) - ) + jsx = transformer.transform_string(polyfill_fragments(f.read().decode("utf-8"))) # Set the cache to one year, since we namespace on this file's update time g.cache.set(namespace, jsx, timeout=86400 * 365) return Response(jsx, mimetype="application/javascript") @@ -179,11 +175,7 @@ def jsx(filename: str) -> Response: if app.debug: # We should make sure this error shows up on the frontend # much like python or template errors do. - stack = "".join( - traceback.format_exception( - type(exception), exception, exception.__traceback__ - ) - ) + stack = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__)) stack = stack.replace('"', '\\"') stack = stack.replace("\r\n", "\\n") stack = stack.replace("\r", "\\n") @@ -263,9 +255,7 @@ def render_react( def exception(sender: Any, exception: Exception, **extra: Any) -> None: - stack = "".join( - traceback.format_exception(type(exception), exception, exception.__traceback__) - ) + stack = "".join(traceback.format_exception(type(exception), exception, exception.__traceback__)) try: g.data.local.network.put_event( "exception", @@ -294,9 +284,7 @@ def page_not_found(error: Any) -> Response: @app.errorhandler(500) def server_error(error: Any) -> Response: - return Response( - render_template("500.html", **{"title": "500 Internal Server Error"}), 500 - ) + return Response(render_template("500.html", **{"title": "500 Internal Server Error"}), 500) def error(msg: str) -> None: @@ -316,10 +304,7 @@ def info(msg: str) -> None: def valid_email(email: str) -> bool: - return ( - re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email) - is not None - ) + return re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email) is not None def valid_username(username: str) -> bool: diff --git a/bemani/frontend/arcade/arcade.py b/bemani/frontend/arcade/arcade.py index 8ccf66b..cef62cb 100644 --- a/bemani/frontend/arcade/arcade.py +++ b/bemani/frontend/arcade/arcade.py @@ -48,15 +48,11 @@ def format_machine(machine: Machine) -> Dict[str, Any]: }.get(machine.game) elif machine.version > 0: game = [ - name - for (game, version, name) in Base.all_games() - if game == machine.game and version == machine.version + name for (game, version, name) in Base.all_games() if game == machine.game and version == machine.version ][0] elif machine.version < 0: game = [ - name - for (game, version, name) in Base.all_games() - if game == machine.game and version == -machine.version + name for (game, version, name) in Base.all_games() if game == machine.game and version == -machine.version ][0] + " or older" return { @@ -104,10 +100,7 @@ def viewarcade(arcadeid: int) -> Response: arcade = g.data.local.machine.get_arcade(arcadeid) if arcade is None or g.userID not in arcade.owners: abort(403) - machines = [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines(arcade.id) - ] + machines = [format_machine(machine) for machine in g.data.local.machine.get_all_machines(arcade.id)] return render_react( arcade.name, "arcade/arcade.react.js", @@ -116,18 +109,11 @@ def viewarcade(arcadeid: int) -> Response: "regions": RegionConstants.LUT, "machines": machines, "game_settings": get_game_settings(g.data, arcadeid), - "balances": { - balance[0]: balance[1] - for balance in g.data.local.machine.get_balances(arcadeid) - }, - "users": { - user.id: user.username for user in g.data.local.user.get_all_users() - }, + "balances": {balance[0]: balance[1] for balance in g.data.local.machine.get_balances(arcadeid)}, + "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, "events": [ format_event(event) - for event in g.data.local.network.get_events( - arcadeid=arcadeid, event="paseli_transaction" - ) + for event in g.data.local.network.get_events(arcadeid=arcadeid, event="paseli_transaction") ], "enforcing": g.config.server.enforce_pcbid, "max_pcbids": g.config.server.pcbid_self_grant_limit, @@ -149,9 +135,7 @@ def viewarcade(arcadeid: int) -> Response: arcadeid=arcadeid, attribute="mask_services_url", ), - "update_settings": url_for( - "arcade_pages.updatesettings", arcadeid=arcadeid - ), + "update_settings": url_for("arcade_pages.updatesettings", arcadeid=arcadeid), "add_balance": url_for("arcade_pages.addbalance", arcadeid=arcadeid), "update_balance": url_for("arcade_pages.updatebalance", arcadeid=arcadeid), "update_pin": url_for("arcade_pages.updatepin", arcadeid=arcadeid), @@ -176,22 +160,14 @@ def listarcade(arcadeid: int) -> Dict[str, Any]: if arcade is None or g.userID not in arcade.owners: raise Exception("You don't own this arcade, refusing to list!") - machines = [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines(arcade.id) - ] + machines = [format_machine(machine) for machine in g.data.local.machine.get_all_machines(arcade.id)] return { "machines": machines, - "balances": { - balance[0]: balance[1] - for balance in g.data.local.machine.get_balances(arcadeid) - }, + "balances": {balance[0]: balance[1] for balance in g.data.local.machine.get_balances(arcadeid)}, "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, "events": [ format_event(event) - for event in g.data.local.network.get_events( - arcadeid=arcadeid, event="paseli_transaction" - ) + for event in g.data.local.network.get_events(arcadeid=arcadeid, event="paseli_transaction") ], } @@ -234,16 +210,11 @@ def addbalance(arcadeid: int) -> Dict[str, Any]: ) return { - "balances": { - balance[0]: balance[1] - for balance in g.data.local.machine.get_balances(arcadeid) - }, + "balances": {balance[0]: balance[1] for balance in g.data.local.machine.get_balances(arcadeid)}, "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, "events": [ format_event(event) - for event in g.data.local.network.get_events( - arcadeid=arcadeid, event="paseli_transaction" - ) + for event in g.data.local.network.get_events(arcadeid=arcadeid, event="paseli_transaction") ], } @@ -277,16 +248,11 @@ def updatebalance(arcadeid: int) -> Dict[str, Any]: ) return { - "balances": { - balance[0]: balance[1] - for balance in g.data.local.machine.get_balances(arcadeid) - }, + "balances": {balance[0]: balance[1] for balance in g.data.local.machine.get_balances(arcadeid)}, "users": {user.id: user.username for user in g.data.local.user.get_all_users()}, "events": [ format_event(event) - for event in g.data.local.network.get_events( - arcadeid=arcadeid, event="paseli_transaction" - ) + for event in g.data.local.network.get_events(arcadeid=arcadeid, event="paseli_transaction") ], } @@ -390,11 +356,7 @@ def generatepcbid(arcadeid: int) -> Dict[str, Any]: # Make sure the user hasn't gone over their limit of PCBIDs. existing_machine_count = len( - [ - machine - for machine in g.data.local.machine.get_all_machines(arcade.id) - if is_user_editable(machine) - ] + [machine for machine in g.data.local.machine.get_all_machines(arcade.id) if is_user_editable(machine)] ) if existing_machine_count >= g.config.server.pcbid_self_grant_limit: raise Exception("You have hit your limit of allowed PCBIDs!") @@ -406,23 +368,16 @@ def generatepcbid(arcadeid: int) -> Dict[str, Any]: while pcbid is None: # Generate a new PCBID, check for uniqueness - potential_pcbid = "01201000000000" + "".join( - [random.choice("0123456789ABCDEF") for _ in range(6)] - ) + potential_pcbid = "01201000000000" + "".join([random.choice("0123456789ABCDEF") for _ in range(6)]) if g.data.local.machine.get_machine(potential_pcbid) is None: pcbid = potential_pcbid # Finally, add the generated PCBID to the network. - g.data.local.machine.create_machine( - pcbid, name, new_machine["description"], arcade.id - ) + g.data.local.machine.create_machine(pcbid, name, new_machine["description"], arcade.id) # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines(arcade.id) - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines(arcade.id)], } @@ -449,11 +404,7 @@ def updatepcbid(arcadeid: int) -> Dict[str, Any]: # Make sure the PCBID we are trying to modify is actually owned by this arcade. # Also, make sure that the PCBID is actually user-editable. - if ( - current_machine is None - or current_machine.arcade != arcadeid - or not is_user_editable(current_machine) - ): + if current_machine is None or current_machine.arcade != arcadeid or not is_user_editable(current_machine): raise Exception("You don't own this PCBID, refusing to update!") # Make sure the port is actually valid. @@ -478,10 +429,7 @@ def updatepcbid(arcadeid: int) -> Dict[str, Any]: # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines(arcade.id) - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines(arcade.id)], } @@ -516,10 +464,7 @@ def removepcbid(arcadeid: int) -> Dict[str, Any]: # Just return all machines for ease of updating return { - "machines": [ - format_machine(machine) - for machine in g.data.local.machine.get_all_machines(arcade.id) - ], + "machines": [format_machine(machine) for machine in g.data.local.machine.get_all_machines(arcade.id)], } @@ -581,24 +526,18 @@ def updatesettings(arcadeid: int) -> Dict[str, Any]: new_value = game_setting["value"] # Update the value - current_settings = g.data.local.machine.get_settings( - arcadeid, game, version, category - ) + current_settings = g.data.local.machine.get_settings(arcadeid, game, version, category) if current_settings is None: current_settings = ValidatedDict() getattr(current_settings, update_function)(setting, new_value) # Save it back - g.data.local.machine.put_settings( - arcade.id, game, version, category, current_settings - ) + g.data.local.machine.put_settings(arcade.id, game, version, category, current_settings) # Return the updated value return { "game_settings": [ - gs - for gs in get_game_settings(g.data, arcadeid) - if gs["game"] == game.value and gs["version"] == version + gs for gs in get_game_settings(g.data, arcadeid) if gs["game"] == game.value and gs["version"] == version ][0], } diff --git a/bemani/frontend/base.py b/bemani/frontend/base.py index 0c8b44c..485a4c2 100644 --- a/bemani/frontend/base.py +++ b/bemani/frontend/base.py @@ -75,9 +75,7 @@ class FrontendBase(ABC): "remote": RemoteUser.is_remote(link.other_userid), } - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: return { "name": profile.get_str("name"), "extid": ID.format_extid(profile.extid), @@ -138,30 +136,22 @@ class FrontendBase(ABC): playstats: Dict[UserID, ValidatedDict] = {} # Find all versions of the users' profiles, sorted newest to oldest. - versions = sorted( - [version for (game, version, name) in self.all_games()], reverse=True - ) + versions = sorted([version for (game, version, name) in self.all_games()], reverse=True) for userid in userids: info[userid] = {} userlimit = limit for version in versions: if allow_remote: - profile = self.data.remote.user.get_profile( - self.game, version, userid - ) + profile = self.data.remote.user.get_profile(self.game, version, userid) else: - profile = self.data.local.user.get_profile( - self.game, version, userid - ) + profile = self.data.local.user.get_profile(self.game, version, userid) if profile is not None: if userid not in playstats: stats = self.data.local.game.get_settings(self.game, userid) if stats is None: stats = ValidatedDict() playstats[userid] = stats - info[userid][version] = self.format_profile( - profile, playstats[userid] - ) + info[userid][version] = self.format_profile(profile, playstats[userid]) info[userid][version]["remote"] = RemoteUser.is_remote(userid) # Exit out if we've hit the limit if userlimit is not None: @@ -171,9 +161,7 @@ class FrontendBase(ABC): return info - def get_latest_player_info( - self, userids: List[UserID] - ) -> Dict[UserID, Dict[str, Any]]: + def get_latest_player_info(self, userids: List[UserID]) -> Dict[UserID, Dict[str, Any]]: # Grab the latest profile for each user all_info = self.get_all_player_info(userids, 1) info = {} @@ -200,9 +188,7 @@ class FrontendBase(ABC): # Find all attempts across all games attempts = [ attempt - for attempt in self.data.local.music.get_all_attempts( - game=self.game, version=self.version, limit=limit - ) + for attempt in self.data.local.music.get_all_attempts(game=self.game, version=self.version, limit=limit) if attempt[0] is not None ] for attempt in attempts: @@ -227,9 +213,7 @@ class FrontendBase(ABC): userids: List[UserID] = [] # Find all high-scores across all games - highscores = self.data.local.music.get_all_records( - game=self.game, version=self.version - ) + highscores = self.data.local.music.get_all_records(game=self.game, version=self.version) for score in highscores: index = self.make_index(score[1].id, score[1].chart) if index not in records: @@ -248,16 +232,11 @@ class FrontendBase(ABC): records[index] = newscore return { - "records": [ - self.format_score(records[index][0], records[index][1]) - for index in records - ], + "records": [self.format_score(records[index][0], records[index][1]) for index in records], "players": self.get_latest_player_info(userids), } - def get_scores( - self, userid: UserID, limit: Optional[int] = None - ) -> List[Dict[str, Any]]: + def get_scores(self, userid: UserID, limit: Optional[int] = None) -> List[Dict[str, Any]]: # Find all attempts across all games attempts = [ attempt @@ -281,9 +260,7 @@ class FrontendBase(ABC): records: Dict[str, Tuple[UserID, Score]] = {} # Find all high-scores across all games - highscores = self.data.local.music.get_all_scores( - game=self.game, version=self.version, userid=userid - ) + highscores = self.data.local.music.get_all_scores(game=self.game, version=self.version, userid=userid) for score in highscores: index = self.make_index(score[1].id, score[1].chart) if index not in records: @@ -302,9 +279,7 @@ class FrontendBase(ABC): # Copy over records to duplicate IDs, such as revivals indexes = [index for index in records] for index in indexes: - alternate = self.get_duplicate_id( - records[index][1].id, records[index][1].chart - ) + alternate = self.get_duplicate_id(records[index][1].id, records[index][1].chart) if alternate is not None: altid, altchart = alternate newindex = self.make_index(altid, altchart) @@ -317,9 +292,7 @@ class FrontendBase(ABC): return [self.format_score(None, records[index][1]) for index in records] def get_top_scores(self, musicid: int) -> Dict[str, Any]: - scores = self.data.local.music.get_all_scores( - game=self.game, version=self.version, songid=musicid - ) + scores = self.data.local.music.get_all_scores(game=self.game, version=self.version, songid=musicid) userids: List[UserID] = [] for score in scores: if score[1].chart not in self.valid_charts: @@ -342,18 +315,14 @@ class FrontendBase(ABC): return { "topscores": [ - self.format_top_score(score[0], score[1]) - for score in scores - if score[1].chart in self.valid_charts + self.format_top_score(score[0], score[1]) for score in scores if score[1].chart in self.valid_charts ], "players": self.get_latest_player_info(userids), } def get_rivals( self, userid: UserID - ) -> Tuple[ - Dict[int, List[Dict[str, Any]]], Dict[UserID, Dict[int, Dict[str, Any]]] - ]: + ) -> Tuple[Dict[int, List[Dict[str, Any]]], Dict[UserID, Dict[int, Dict[str, Any]]]]: rivals = {} userids = set() versions = [version for (game, version, name) in self.all_games()] @@ -373,12 +342,6 @@ class FrontendBase(ABC): userids.add(rival.other_userid) return ( - { - version: [ - self.format_rival(rival, profiles[version]) - for rival in rivals[version] - ] - for version in rivals - }, + {version: [self.format_rival(rival, profiles[version]) for rival in rivals[version]] for version in rivals}, self.get_all_player_info(list(userids), allow_remote=True), ) diff --git a/bemani/frontend/bishi/bishi.py b/bemani/frontend/bishi/bishi.py index e85a8f3..3bec865 100644 --- a/bemani/frontend/bishi/bishi.py +++ b/bemani/frontend/bishi/bishi.py @@ -54,9 +54,7 @@ class BishiBashiFrontend(FrontendBase): return newprofile - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: name = "なし" # Nothing shop = "未設定" # Not set shop_area = "未設定" # Not set diff --git a/bemani/frontend/bishi/endpoints.py b/bemani/frontend/bishi/endpoints.py index 303ec86..bc10654 100644 --- a/bemani/frontend/bishi/endpoints.py +++ b/bemani/frontend/bishi/endpoints.py @@ -62,9 +62,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("bishi_pages.listplayer", userid=userid), @@ -98,9 +96,7 @@ def viewsettings() -> Response: "bishi/settings.react.js", { "player": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("bishi_pages.updatename"), diff --git a/bemani/frontend/ddr/ddr.py b/bemani/frontend/ddr/ddr.py index c2c05fb..4e199b0 100644 --- a/bemani/frontend/ddr/ddr.py +++ b/bemani/frontend/ddr/ddr.py @@ -66,16 +66,12 @@ class DDRFrontend(FrontendBase): newprofile.replace_int("early_late", 1 if display_early_late else 0) return newprofile - def update_background_combo( - self, profile: Profile, background_combo: bool - ) -> Profile: + def update_background_combo(self, profile: Profile, background_combo: bool) -> Profile: newprofile = copy.deepcopy(profile) newprofile.replace_int("combo", 1 if background_combo else 0) return newprofile - def update_settings( - self, profile: Profile, new_settings: Dict[str, Any] - ) -> Profile: + def update_settings(self, profile: Profile, new_settings: Dict[str, Any]) -> Profile: newprofile = copy.deepcopy(profile) if newprofile.version in (VersionConstants.DDR_ACE, VersionConstants.DDR_A20): newprofile.replace_int("arrowskin", new_settings["arrowskin"]) @@ -87,9 +83,7 @@ class DDRFrontend(FrontendBase): pass return newprofile - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) if profile.version in (VersionConstants.DDR_ACE, VersionConstants.DDR_A20): formatted_profile.update( diff --git a/bemani/frontend/ddr/endpoints.py b/bemani/frontend/ddr/endpoints.py index eb56bf1..60c4947 100644 --- a/bemani/frontend/ddr/endpoints.py +++ b/bemani/frontend/ddr/endpoints.py @@ -37,9 +37,7 @@ def viewnetworkscores() -> Response: "attempts": network_scores["attempts"], "songs": frontend.get_all_songs(), "players": network_scores["players"], - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "shownames": True, "shownewrecords": False, }, @@ -78,9 +76,7 @@ def viewscores(userid: UserID) -> Response: "attempts": scores, "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "shownames": False, "shownewrecords": True, }, @@ -116,9 +112,7 @@ def viewnetworkrecords() -> Response: "records": network_records["records"], "songs": frontend.get_all_songs(), "players": network_records["players"], - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "shownames": True, "showpersonalsort": False, "filterempty": False, @@ -154,9 +148,7 @@ def viewrecords(userid: UserID) -> Response: "records": frontend.get_records(userid), "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "shownames": False, "showpersonalsort": True, "filterempty": True, @@ -274,9 +266,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("ddr_pages.listplayer", userid=userid), @@ -312,9 +302,7 @@ def viewsettings() -> Response: "ddr/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("ddr_pages.updatename"), @@ -475,9 +463,7 @@ def viewrivals() -> Response: "rivals": rivals, "max_active_rivals": frontend.max_active_rivals, "players": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("ddr_pages.listrivals"), diff --git a/bemani/frontend/gamesettings.py b/bemani/frontend/gamesettings.py index 1bdbc90..2f4ddca 100644 --- a/bemani/frontend/gamesettings.py +++ b/bemani/frontend/gamesettings.py @@ -41,17 +41,13 @@ def get_game_settings(data: Data, arcadeid: ArcadeID) -> List[Dict[str, Any]]: ]: for setting in settings.get(setting_type, []): if setting["category"] not in settings_lut[game][version]: - cached_setting = data.local.machine.get_settings( - arcadeid, game, version, setting["category"] - ) + cached_setting = data.local.machine.get_settings(arcadeid, game, version, setting["category"]) if cached_setting is None: cached_setting = ValidatedDict() settings_lut[game][version][setting["category"]] = cached_setting current_settings = settings_lut[game][version][setting["category"]] - setting["value"] = getattr(current_settings, setting_unpacker)( - setting["setting"] - ) + setting["value"] = getattr(current_settings, setting_unpacker)(setting["setting"]) game_settings[setting_type].append(setting) # Now, include it! diff --git a/bemani/frontend/iidx/endpoints.py b/bemani/frontend/iidx/endpoints.py index 02f576e..6fbe402 100644 --- a/bemani/frontend/iidx/endpoints.py +++ b/bemani/frontend/iidx/endpoints.py @@ -36,9 +36,7 @@ def viewnetworkscores() -> Response: "attempts": network_scores["attempts"], "songs": frontend.get_all_songs(), "players": network_scores["players"], - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "showdjnames": True, "shownewrecords": False, }, @@ -77,9 +75,7 @@ def viewscores(userid: UserID) -> Response: "attempts": scores, "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "showdjnames": False, "shownewrecords": True, }, @@ -115,9 +111,7 @@ def viewnetworkrecords() -> Response: "records": network_records["records"], "songs": frontend.get_all_songs(), "players": network_records["players"], - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "showdjnames": True, "showpersonalsort": False, "filterempty": False, @@ -153,9 +147,7 @@ def viewrecords(userid: UserID) -> Response: "records": frontend.get_records(userid), "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "showdjnames": False, "showpersonalsort": True, "filterempty": True, @@ -197,9 +189,7 @@ def viewtopscores(musicid: int) -> Response: for version in versions: for omniadd in [0, DBConstants.OMNIMIX_VERSION_BUMP]: for chart in [0, 1, 2, 3, 4, 5]: - details = g.data.local.music.get_song( - GameConstants.IIDX, version + omniadd, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.IIDX, version + omniadd, musicid, chart) if details is not None: name = details.name artist = details.artist @@ -275,12 +265,8 @@ def viewplayer(userid: UserID) -> Response: latest_version = sorted(djinfo.keys(), reverse=True)[0] for version in djinfo: - sp_rival = g.data.local.user.get_link( - GameConstants.IIDX, version, g.userID, "sp_rival", userid - ) - dp_rival = g.data.local.user.get_link( - GameConstants.IIDX, version, g.userID, "dp_rival", userid - ) + sp_rival = g.data.local.user.get_link(GameConstants.IIDX, version, g.userID, "sp_rival", userid) + dp_rival = g.data.local.user.get_link(GameConstants.IIDX, version, g.userID, "dp_rival", userid) djinfo[version]["sp_rival"] = sp_rival is not None djinfo[version]["dp_rival"] = dp_rival is not None @@ -291,9 +277,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("iidx_pages.listplayer", userid=userid), @@ -313,12 +297,8 @@ def listplayer(userid: UserID) -> Dict[str, Any]: djinfo = frontend.get_all_player_info([userid])[userid] for version in djinfo: - sp_rival = g.data.local.user.get_link( - GameConstants.IIDX, version, g.userID, "sp_rival", userid - ) - dp_rival = g.data.local.user.get_link( - GameConstants.IIDX, version, g.userID, "dp_rival", userid - ) + sp_rival = g.data.local.user.get_link(GameConstants.IIDX, version, g.userID, "sp_rival", userid) + dp_rival = g.data.local.user.get_link(GameConstants.IIDX, version, g.userID, "dp_rival", userid) djinfo[version]["sp_rival"] = sp_rival is not None djinfo[version]["dp_rival"] = dp_rival is not None @@ -345,9 +325,7 @@ def viewsettings() -> Response: { "player": djinfo, "regions": RegionConstants.LUT, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "qpros": frontend.get_all_items(versions), }, { @@ -394,13 +372,9 @@ def updateflags() -> Dict[str, Any]: settings_dict.replace_int("flags", flagint) # Update special case flags - settings_dict.replace_int( - "disable_song_preview", 1 if flags["disable_song_preview"] else 0 - ) + settings_dict.replace_int("disable_song_preview", 1 if flags["disable_song_preview"] else 0) settings_dict.replace_int("effector_lock", 1 if flags["effector_lock"] else 0) - settings_dict.replace_int( - "disable_hcn_color", 1 if flags["disable_hcn_color"] else 0 - ) + settings_dict.replace_int("disable_hcn_color", 1 if flags["disable_hcn_color"] else 0) # Update the settings dict profile.replace_dict("settings", settings_dict) @@ -540,9 +514,7 @@ def updateprefecture() -> Dict[str, Any]: profile = g.data.local.user.get_profile(GameConstants.IIDX, version, user.id) if profile is None: raise Exception("Unable to find profile to update!") - profile.replace_int( - "pid", RegionConstants.db_to_game_region(version >= 25, prefecture) - ) + profile.replace_int("pid", RegionConstants.db_to_game_region(version >= 25, prefecture)) g.data.local.user.put_profile(GameConstants.IIDX, version, user.id, profile) # Return that we updated @@ -565,9 +537,7 @@ def viewrivals() -> Response: "userid": str(g.userID), "rivals": rivals, "players": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("iidx_pages.listrivals"), diff --git a/bemani/frontend/iidx/iidx.py b/bemani/frontend/iidx/iidx.py index f836e61..cf35373 100644 --- a/bemani/frontend/iidx/iidx.py +++ b/bemani/frontend/iidx/iidx.py @@ -184,9 +184,7 @@ class IIDXFrontend(FrontendBase): ], } - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) formatted_profile.update( { @@ -283,10 +281,7 @@ class IIDXFrontend(FrontendBase): def merge_song(self, existing: Dict[str, Any], new: Song) -> Dict[str, Any]: new_song = super().merge_song(existing, new) - if ( - existing["difficulties"][new.chart] == 0 - or existing["notecounts"][new.chart] == 0 - ): + if existing["difficulties"][new.chart] == 0 or existing["notecounts"][new.chart] == 0: new_song["difficulties"][new.chart] = new.data.get_int("difficulty", 13) new_song["notecounts"][new.chart] = new.data.get_int("notecount", 5730) return new_song diff --git a/bemani/frontend/jubeat/endpoints.py b/bemani/frontend/jubeat/endpoints.py index 14c38be..d1aec64 100644 --- a/bemani/frontend/jubeat/endpoints.py +++ b/bemani/frontend/jubeat/endpoints.py @@ -36,9 +36,7 @@ def viewnetworkscores() -> Response: "attempts": network_scores["attempts"], "songs": frontend.get_all_songs(), "players": network_scores["players"], - "versions": { - version: name for (game, version, name) in frontend.sanitized_games() - }, + "versions": {version: name for (game, version, name) in frontend.sanitized_games()}, "shownames": True, "shownewrecords": False, }, @@ -77,9 +75,7 @@ def viewscores(userid: UserID) -> Response: "attempts": scores, "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.sanitized_games() - }, + "versions": {version: name for (game, version, name) in frontend.sanitized_games()}, "shownames": False, "shownewrecords": True, }, @@ -115,9 +111,7 @@ def viewnetworkrecords() -> Response: "records": network_records["records"], "songs": frontend.get_all_songs(), "players": network_records["players"], - "versions": { - version: name for (game, version, name) in frontend.sanitized_games() - }, + "versions": {version: name for (game, version, name) in frontend.sanitized_games()}, "shownames": True, "showpersonalsort": False, "filterempty": False, @@ -153,9 +147,7 @@ def viewrecords(userid: UserID) -> Response: "records": frontend.get_records(userid), "songs": frontend.get_all_songs(), "players": {}, - "versions": { - version: name for (game, version, name) in frontend.sanitized_games() - }, + "versions": {version: name for (game, version, name) in frontend.sanitized_games()}, "shownames": False, "showpersonalsort": True, "filterempty": True, @@ -197,9 +189,7 @@ def viewtopscores(musicid: int) -> Response: for version in versions: for omniadd in [0, DBConstants.OMNIMIX_VERSION_BUMP]: for chart in [0, 1, 2, 3, 4, 5]: - details = g.data.local.music.get_song( - GameConstants.JUBEAT, version + omniadd, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.JUBEAT, version + omniadd, musicid, chart) if details is not None: name = details.name artist = details.artist @@ -209,9 +199,7 @@ def viewtopscores(musicid: int) -> Response: if difficulties[chart] == 0.0: difficulties[chart] = details.data.get_float("difficulty", 13) if difficulties[chart] >= 13.0: - difficulties[chart] = float( - details.data.get_int("difficulty", 13) - ) + difficulties[chart] = float(details.data.get_int("difficulty", 13)) if name is None: # Not a real song! @@ -287,9 +275,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("jubeat_pages.listplayer", userid=userid), @@ -328,9 +314,7 @@ def showjubility(userid: UserID) -> Response: "playerid": userid, "player": info, "songs": frontend.get_all_songs(), - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("jubeat_pages.listplayer", userid=userid), @@ -359,9 +343,7 @@ def viewsettings() -> Response: "jubeat/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, "emblems": all_emblems, "assets_available": g.config.assets.jubeat.emblems is not None, }, @@ -451,9 +433,7 @@ def viewrivals() -> Response: "userid": str(g.userID), "rivals": rivals, "players": playerinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("jubeat_pages.listrivals"), @@ -511,9 +491,7 @@ def addrival() -> Dict[str, Any]: userid = g.userID # Add this rival link - profile = g.data.remote.user.get_profile( - GameConstants.JUBEAT, version, other_userid - ) + profile = g.data.remote.user.get_profile(GameConstants.JUBEAT, version, other_userid) if profile is None: raise Exception("Unable to find profile for rival!") diff --git a/bemani/frontend/jubeat/jubeat.py b/bemani/frontend/jubeat/jubeat.py index 4b8a141..25482b4 100644 --- a/bemani/frontend/jubeat/jubeat.py +++ b/bemani/frontend/jubeat/jubeat.py @@ -139,29 +139,19 @@ class JubeatFrontend(FrontendBase): "speech_bubble": emblem[4], } - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: # Grab achievements for both jubility in festo, as well as emblem parts in # prop onward. - userid = self.data.local.user.from_refid( - profile.game, profile.version, profile.refid - ) + userid = self.data.local.user.from_refid(profile.game, profile.version, profile.refid) if userid is not None: - achievements = self.data.local.user.get_achievements( - profile.game, profile.version, userid - ) + achievements = self.data.local.user.get_achievements(profile.game, profile.version, userid) else: achievements = [] formatted_profile = super().format_profile(profile, playstats) formatted_profile["plays"] = playstats.get_int("total_plays") - formatted_profile["emblem"] = self.format_emblem( - profile.get_dict("last").get_int_array("emblem", 5) - ) - formatted_profile["owned_emblems"] = [ - str(ach.id) for ach in achievements if ach.type == "emblem" - ] + formatted_profile["emblem"] = self.format_emblem(profile.get_dict("last").get_int_array("emblem", 5)) + formatted_profile["owned_emblems"] = [str(ach.id) for ach in achievements if ach.type == "emblem"] formatted_profile["jubility"] = ( profile.get_int("jubility") if profile.version @@ -173,24 +163,16 @@ class JubeatFrontend(FrontendBase): else 0 ) formatted_profile["pick_up_jubility"] = ( - profile.get_float("pick_up_jubility") - if profile.version == VersionConstants.JUBEAT_FESTO - else 0 + profile.get_float("pick_up_jubility") if profile.version == VersionConstants.JUBEAT_FESTO else 0 ) formatted_profile["common_jubility"] = ( - profile.get_float("common_jubility") - if profile.version == VersionConstants.JUBEAT_FESTO - else 0 + profile.get_float("common_jubility") if profile.version == VersionConstants.JUBEAT_FESTO else 0 ) if profile.version == VersionConstants.JUBEAT_FESTO: # Only reason this is a dictionary of dictionaries is because ValidatedDict doesn't support a list of dictionaries. # Probably intentionally lol. Just listify the pickup/common charts. - formatted_profile["pick_up_chart"] = list( - profile.get_dict("pick_up_chart").values() - ) - formatted_profile["common_chart"] = list( - profile.get_dict("common_chart").values() - ) + formatted_profile["pick_up_chart"] = list(profile.get_dict("pick_up_chart").values()) + formatted_profile["common_chart"] = list(profile.get_dict("common_chart").values()) elif profile.version == VersionConstants.JUBEAT_CLAN: # Look up achievements which is where jubility was stored. This is a bit of a hack # due to the fact that this could be formatting remote profiles, but then they should @@ -210,9 +192,7 @@ class JubeatFrontend(FrontendBase): bestentry.replace_int("songid", achievement.id) bestentry.replace_int("chart", chart) jubeat_entries.append(bestentry) - jubeat_entries = sorted( - jubeat_entries, key=lambda entry: entry.get_int("value"), reverse=True - )[:30] + jubeat_entries = sorted(jubeat_entries, key=lambda entry: entry.get_int("value"), reverse=True)[:30] formatted_profile["chart"] = jubeat_entries formatted_profile["ex_count"] = profile.get_int("ex_cnt") @@ -258,7 +238,5 @@ class JubeatFrontend(FrontendBase): if existing["difficulties"][new.chart] == 0.0: new_song["difficulties"][new.chart] = new.data.get_float("difficulty", 13) if new_song["difficulties"][new.chart] == 13.0: - new_song["difficulties"][new.chart] = float( - new.data.get_int("difficulty", 13) - ) + new_song["difficulties"][new.chart] = float(new.data.get_int("difficulty", 13)) return new_song diff --git a/bemani/frontend/mga/endpoints.py b/bemani/frontend/mga/endpoints.py index 8e993dc..139d1fd 100644 --- a/bemani/frontend/mga/endpoints.py +++ b/bemani/frontend/mga/endpoints.py @@ -62,9 +62,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("mga_pages.listplayer", userid=userid), @@ -98,9 +96,7 @@ def viewsettings() -> Response: "mga/settings.react.js", { "player": djinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("mga_pages.updatename"), diff --git a/bemani/frontend/mga/mga.py b/bemani/frontend/mga/mga.py index c41b688..a599959 100644 --- a/bemani/frontend/mga/mga.py +++ b/bemani/frontend/mga/mga.py @@ -54,9 +54,7 @@ class MetalGearArcadeFrontend(FrontendBase): return newprofile - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: name = "なし" # Nothing shop = "未設定" # Not set shop_area = "未設定" # Not set diff --git a/bemani/frontend/museca/endpoints.py b/bemani/frontend/museca/endpoints.py index 61cb48b..38fd62d 100644 --- a/bemani/frontend/museca/endpoints.py +++ b/bemani/frontend/museca/endpoints.py @@ -188,9 +188,7 @@ def viewtopscores(musicid: int) -> Response: for version in versions: for omniadd in [0, DBConstants.OMNIMIX_VERSION_BUMP]: for chart in [0, 1, 2, 3, 4]: - details = g.data.local.music.get_song( - GameConstants.MUSECA, version + omniadd, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.MUSECA, version + omniadd, musicid, chart) if details is not None: if name is None: name = details.name @@ -271,9 +269,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("museca_pages.listplayer", userid=userid), @@ -309,9 +305,7 @@ def viewsettings() -> Response: "museca/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("museca_pages.updatename"), diff --git a/bemani/frontend/museca/museca.py b/bemani/frontend/museca/museca.py index 8fb3a02..d516703 100644 --- a/bemani/frontend/museca/museca.py +++ b/bemani/frontend/museca/museca.py @@ -81,9 +81,7 @@ class MusecaFrontend(FrontendBase): formatted_attempt["stats"] = attempt.data.get_dict("stats") return formatted_attempt - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) formatted_profile["plays"] = playstats.get_int("total_plays") return formatted_profile diff --git a/bemani/frontend/popn/endpoints.py b/bemani/frontend/popn/endpoints.py index b6d12ea..f07c593 100644 --- a/bemani/frontend/popn/endpoints.py +++ b/bemani/frontend/popn/endpoints.py @@ -188,9 +188,7 @@ def viewtopscores(musicid: int) -> Response: for version in versions: for omniadd in [0, DBConstants.OMNIMIX_VERSION_BUMP]: for chart in [0, 1, 2, 3]: - details = g.data.local.music.get_song( - GameConstants.POPN_MUSIC, version + omniadd, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.POPN_MUSIC, version + omniadd, musicid, chart) if details is not None: if name is None: name = details.name @@ -274,9 +272,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("popn_pages.listplayer", userid=userid), @@ -312,9 +308,7 @@ def viewsettings() -> Response: "popn/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("popn_pages.updatename"), @@ -381,9 +375,7 @@ def viewrivals() -> Response: "rivals": rivals, "max_active_rivals": frontend.max_active_rivals, "players": playerinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("popn_pages.listrivals"), @@ -446,9 +438,7 @@ def addrival() -> Dict[str, Any]: userid = g.userID # Add this rival link - profile = g.data.remote.user.get_profile( - GameConstants.POPN_MUSIC, version, other_userid - ) + profile = g.data.remote.user.get_profile(GameConstants.POPN_MUSIC, version, other_userid) if profile is None: raise Exception("Unable to find profile for rival!") diff --git a/bemani/frontend/popn/popn.py b/bemani/frontend/popn/popn.py index f19f76f..e21c8c8 100644 --- a/bemani/frontend/popn/popn.py +++ b/bemani/frontend/popn/popn.py @@ -79,9 +79,7 @@ class PopnMusicFrontend(FrontendBase): }.get(attempt.data.get_int("medal"), "NO PLAY") return formatted_attempt - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) formatted_profile["plays"] = playstats.get_int("total_plays") return formatted_profile diff --git a/bemani/frontend/reflec/endpoints.py b/bemani/frontend/reflec/endpoints.py index b7caa92..585002c 100644 --- a/bemani/frontend/reflec/endpoints.py +++ b/bemani/frontend/reflec/endpoints.py @@ -186,9 +186,7 @@ def viewtopscores(musicid: int) -> Response: difficulties = [0, 0, 0, 0] for chart in [0, 1, 2, 3]: - details = g.data.local.music.get_song( - GameConstants.REFLEC_BEAT, 0, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.REFLEC_BEAT, 0, musicid, chart) if details is not None: if name is None: name = details.name @@ -269,9 +267,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("reflec_pages.listplayer", userid=userid), @@ -307,9 +303,7 @@ def viewsettings() -> Response: "reflec/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("reflec_pages.updatename"), @@ -406,9 +400,7 @@ def viewrivals() -> Response: "rivals": rivals, "players": playerinfo, "versions": { - version: name - for (game, version, name) in frontend.all_games() - if version not in NO_RIVAL_SUPPORT + version: name for (game, version, name) in frontend.all_games() if version not in NO_RIVAL_SUPPORT }, }, { @@ -472,9 +464,7 @@ def addrival() -> Dict[str, Any]: userid = g.userID # Add this rival link - profile = g.data.remote.user.get_profile( - GameConstants.REFLEC_BEAT, version, other_userid - ) + profile = g.data.remote.user.get_profile(GameConstants.REFLEC_BEAT, version, other_userid) if profile is None: raise Exception("Unable to find profile for rival!") diff --git a/bemani/frontend/reflec/reflec.py b/bemani/frontend/reflec/reflec.py index cb34b10..96552f5 100644 --- a/bemani/frontend/reflec/reflec.py +++ b/bemani/frontend/reflec/reflec.py @@ -49,17 +49,13 @@ class ReflecBeatFrontend(FrontendBase): ReflecBeatBase.COMBO_TYPE_FULL_COMBO: "FULL COMBO", ReflecBeatBase.COMBO_TYPE_FULL_COMBO_ALL_JUST: "FULL COMBO + ALL JUST", }.get(score.data.get_int("combo_type"), "") - formatted_score["medal"] = score.data.get_int( - "combo_type" - ) * 1000 + score.data.get_int("clear_type") + formatted_score["medal"] = score.data.get_int("combo_type") * 1000 + score.data.get_int("clear_type") return formatted_score def format_attempt(self, userid: UserID, attempt: Attempt) -> Dict[str, Any]: formatted_attempt = super().format_attempt(userid, attempt) formatted_attempt["combo"] = attempt.data.get_int("combo", -1) - formatted_attempt["achievement_rate"] = attempt.data.get_int( - "achievement_rate", -1 - ) + formatted_attempt["achievement_rate"] = attempt.data.get_int("achievement_rate", -1) formatted_attempt["miss_count"] = attempt.data.get_int("miss_count", -1) formatted_attempt["clear_type"] = { ReflecBeatBase.CLEAR_TYPE_NO_PLAY: "NO PLAY", @@ -74,14 +70,10 @@ class ReflecBeatFrontend(FrontendBase): ReflecBeatBase.COMBO_TYPE_FULL_COMBO: "FULL COMBO", ReflecBeatBase.COMBO_TYPE_FULL_COMBO_ALL_JUST: "FULL COMBO + ALL JUST", }.get(attempt.data.get_int("combo_type"), "") - formatted_attempt["medal"] = attempt.data.get_int( - "combo_type" - ) * 1000 + attempt.data.get_int("clear_type") + formatted_attempt["medal"] = attempt.data.get_int("combo_type") * 1000 + attempt.data.get_int("clear_type") return formatted_attempt - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) formatted_profile["plays"] = playstats.get_int("total_plays") return formatted_profile diff --git a/bemani/frontend/sdvx/endpoints.py b/bemani/frontend/sdvx/endpoints.py index 24a3503..d91eb39 100644 --- a/bemani/frontend/sdvx/endpoints.py +++ b/bemani/frontend/sdvx/endpoints.py @@ -188,9 +188,7 @@ def viewtopscores(musicid: int) -> Response: for version in versions: for chart in [0, 1, 2, 3, 4]: - details = g.data.local.music.get_song( - GameConstants.SDVX, version, musicid, chart - ) + details = g.data.local.music.get_song(GameConstants.SDVX, version, musicid, chart) if details is not None: if name is None: name = details.name @@ -271,9 +269,7 @@ def viewplayer(userid: UserID) -> Response: "playerid": userid, "own_profile": userid == g.userID, "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("sdvx_pages.listplayer", userid=userid), @@ -309,9 +305,7 @@ def viewsettings() -> Response: "sdvx/settings.react.js", { "player": info, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "updatename": url_for("sdvx_pages.updatename"), @@ -372,9 +366,7 @@ def viewrivals() -> Response: "userid": str(g.userID), "rivals": rivals, "players": playerinfo, - "versions": { - version: name for (game, version, name) in frontend.all_games() - }, + "versions": {version: name for (game, version, name) in frontend.all_games()}, }, { "refresh": url_for("sdvx_pages.listrivals"), diff --git a/bemani/frontend/sdvx/sdvx.py b/bemani/frontend/sdvx/sdvx.py index bed50e2..12284ca 100644 --- a/bemani/frontend/sdvx/sdvx.py +++ b/bemani/frontend/sdvx/sdvx.py @@ -86,9 +86,7 @@ class SoundVoltexFrontend(FrontendBase): formatted_attempt["stats"] = attempt.data.get_dict("stats") return formatted_attempt - def format_profile( - self, profile: Profile, playstats: ValidatedDict - ) -> Dict[str, Any]: + def format_profile(self, profile: Profile, playstats: ValidatedDict) -> Dict[str, Any]: formatted_profile = super().format_profile(profile, playstats) formatted_profile["plays"] = playstats.get_int("total_plays") return formatted_profile diff --git a/bemani/protocol/binary.py b/bemani/protocol/binary.py index 2912b77..2eaeceb 100644 --- a/bemani/protocol/binary.py +++ b/bemani/protocol/binary.py @@ -278,36 +278,26 @@ class BinaryDecoder: """ length = self.stream.read_int() if length is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node name length!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node name length!") if not self.compressed: if length < 0x40: - raise BinaryEncodingException( - "Node name length under decompressed minimum" - ) + raise BinaryEncodingException("Node name length under decompressed minimum") elif length < 0x80: length -= 0x3F else: length_ex = self.stream.read_int() if length_ex is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node name length!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node name length!") length = (length << 8) | length_ex length -= 0x7FBF if length > BinaryEncoding.NAME_MAX_DECOMPRESSED: - raise BinaryEncodingException( - "Node name length over decompressed limit" - ) + raise BinaryEncodingException("Node name length over decompressed limit") name = self.stream.read_blob(length) if name is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node name!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node name!") return name.decode(self.encoding) @@ -327,9 +317,7 @@ class BinaryDecoder: for _ in range(binary_length): next_byte = self.stream.read_int() if next_byte is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node name!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node name!") data = data + int_to_bin(next_byte) data_str = [data[i : (i + 6)] for i in range(0, len(data), 6)] data_int = [int(val, 2) for val in data_str] @@ -352,9 +340,7 @@ class BinaryDecoder: while True: child_type = self.stream.read_int() if child_type is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node type!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node type!") if child_type == Node.END_OF_NODE: return node @@ -374,23 +360,17 @@ class BinaryDecoder: Node object """ if self.executed: - raise BinaryEncodingException( - "Logic error, should only call this once per instance" - ) + raise BinaryEncodingException("Logic error, should only call this once per instance") self.executed = True # Read the header first header_length = self.stream.read_int(4) if header_length is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read header length!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read header length!") node_type = self.stream.read_int() if node_type is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read root node type!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read root node type!") root = self.__read_node(node_type) eod = self.stream.read_int() @@ -444,9 +424,7 @@ class BinaryDecoder: elif alignment == 4: loc = ordering.get_next_int() if loc is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read node data location!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read node data location!") if size is None: # The size should be read from the first 4 bytes @@ -466,9 +444,7 @@ class BinaryDecoder: if composite: val_list = list(struct.unpack(decode_value, decode_data)) if value["type"] == "attribute": - raise Exception( - "Logic error, shouldn't have composite attribute type!" - ) + raise Exception("Logic error, shouldn't have composite attribute type!") node.set_value(val_list) continue @@ -491,9 +467,7 @@ class BinaryDecoder: # Array value loc = ordering.get_next_int() if loc is None: - raise BinaryEncodingException( - "Ran out of data when attempting to read array length location!" - ) + raise BinaryEncodingException("Ran out of data when attempting to read array length location!") # The raw size in bytes length = struct.unpack(">I", body[loc : (loc + 4)])[0] @@ -550,9 +524,7 @@ class BinaryEncoder: length = len(encoded) if length > BinaryEncoding.NAME_MAX_DECOMPRESSED: - raise BinaryEncodingException( - "Node name length over decompressed limit" - ) + raise BinaryEncodingException("Node name length over decompressed limit") if length < 64: self.stream.write_int(length + 0x3F) @@ -598,9 +570,7 @@ class BinaryEncoder: Parameters: node - A Node which should be encoded. """ - to_write = PackedOrdering.node_to_body_ordering( - node, include_children=False, include_void=True - ) + to_write = PackedOrdering.node_to_body_ordering(node, include_children=False, include_void=True) for thing in to_write: # First, write the type of this node out if thing["type"] == "value": @@ -699,9 +669,7 @@ class BinaryEncoder: elif alignment == 4: loc = ordering.get_next_int() if loc is None: - raise BinaryEncodingException( - "Ran out of data when attempting to allocate node location!" - ) + raise BinaryEncodingException("Ran out of data when attempting to allocate node location!") if dtype == "str": # Need to convert this to encoding from standard string. @@ -718,9 +686,7 @@ class BinaryEncoder: f'Node \'{value["name"]}\' has un-encodable string value \'{val}\'' ) size = len(valbytes) - self.__add_data( - struct.pack(">I", size) + valbytes, size + 4, loc - ) + self.__add_data(struct.pack(">I", size) + valbytes, size + 4, loc) ordering.mark_used(size + 4, loc, round_to=4) # We took care of this one @@ -736,9 +702,7 @@ class BinaryEncoder: elif composite: # Array, but not, somewhat silly if size is None: - raise Exception( - "Logic error, node size not set yet this is not an attribute!" - ) + raise Exception("Logic error, node size not set yet this is not an attribute!") encode_value = f">{enc}" self.__add_data(struct.pack(encode_value, *val), size, loc) @@ -751,9 +715,7 @@ class BinaryEncoder: # The size is built-in, emit it if size is None: - raise Exception( - "Logic error, node size not set yet this is not an attribute!" - ) + raise Exception("Logic error, node size not set yet this is not an attribute!") encode_value = f">{enc}" self.__add_data(struct.pack(encode_value, val), size, loc) @@ -762,13 +724,9 @@ class BinaryEncoder: # Array value loc = ordering.get_next_int() if loc is None: - raise BinaryEncodingException( - "Ran out of data when attempting allocate array location!" - ) + raise BinaryEncodingException("Ran out of data when attempting allocate array location!") if size is None: - raise Exception( - "Logic error, node size not set yet this is not an attribute!" - ) + raise Exception("Logic error, node size not set yet this is not an attribute!") # The raw size in bytes elems = len(val) @@ -859,9 +817,7 @@ class BinaryEncoding: if we couldn't decode the object for some reason. """ try: - data_magic, contents, encoding_raw, encoding_swapped = struct.unpack( - ">BBBB", data[0:4] - ) + data_magic, contents, encoding_raw, encoding_swapped = struct.unpack(">BBBB", data[0:4]) except struct.error: # Couldn't even parse magic return None @@ -886,9 +842,7 @@ class BinaryEncoding: if encoding is not None: self.encoding = encoding try: - decoder = BinaryDecoder( - data[4:], self.__sanitize_encoding(encoding), self.compressed - ) + decoder = BinaryDecoder(data[4:], self.__sanitize_encoding(encoding), self.compressed) return decoder.get_tree() except BinaryEncodingException: if skip_on_exceptions: @@ -898,9 +852,7 @@ class BinaryEncoding: else: return None - def encode( - self, tree: Node, encoding: Optional[str] = None, compressed: bool = True - ) -> bytes: + def encode(self, tree: Node, encoding: Optional[str] = None, compressed: bool = True) -> bytes: """ Given a tree of Node objects, encode the data with the current encoding. @@ -932,9 +884,7 @@ class BinaryEncoding: struct.pack( ">BBBB", BinaryEncoding.MAGIC, - BinaryEncoding.COMPRESSED_WITH_DATA - if compressed - else BinaryEncoding.DECOMPRESSED_WITH_DATA, + BinaryEncoding.COMPRESSED_WITH_DATA if compressed else BinaryEncoding.DECOMPRESSED_WITH_DATA, encoding_magic, (~encoding_magic & 0xFF), ) diff --git a/bemani/protocol/lz77.py b/bemani/protocol/lz77.py index 7218a03..978a955 100644 --- a/bemani/protocol/lz77.py +++ b/bemani/protocol/lz77.py @@ -11,11 +11,7 @@ from .. import package_root try: clib = None clib_path = os.path.join(package_root, "protocol") - files = [ - f - for f in os.listdir(clib_path) - if f.startswith("lz77cpp") and f.endswith(".so") - ] + files = [f for f in os.listdir(clib_path) if f.startswith("lz77cpp") and f.endswith(".so")] if len(files) > 0: clib = ctypes.cdll.LoadLibrary(os.path.join(clib_path, files[0])) clib.decompress.argtypes = ( @@ -110,11 +106,7 @@ class Lz77Decompress: if amount > (self.ringlength - self.write_pos): amount = self.ringlength - self.write_pos - self.ring = ( - self.ring[: self.write_pos] - + bytedata[:amount] - + self.ring[(self.write_pos + amount) :] - ) + self.ring = self.ring[: self.write_pos] + bytedata[:amount] + self.ring[(self.write_pos + amount) :] bytedata = bytedata[amount:] self.write_pos = (self.write_pos + amount) % self.ringlength @@ -356,14 +348,10 @@ class Lz77Compress: earliest = max(0, self.bytes_written - (self.ringlength - 1)) index = self.data[self.read_pos : (self.read_pos + 3)] updated_backref_locations: Set[int] = set( - absolute_pos - for absolute_pos in self.starts[index] - if absolute_pos >= earliest + absolute_pos for absolute_pos in self.starts[index] if absolute_pos >= earliest ) self.starts[index] = updated_backref_locations - possible_backref_locations: List[int] = list( - updated_backref_locations - ) + possible_backref_locations: List[int] = list(updated_backref_locations) # Output the data as a copy if we couldn't find a backref if not possible_backref_locations: @@ -385,11 +373,7 @@ class Lz77Compress: copy_amount = 3 while copy_amount < backref_amount: # First, let's see if we have any 3-wide chunks to consume. - index = self.data[ - (self.read_pos + copy_amount) : ( - self.read_pos + copy_amount + 3 - ) - ] + index = self.data[(self.read_pos + copy_amount) : (self.read_pos + copy_amount + 3)] locations = self.starts[index] new_backref_locations: List[int] = [ absolute_pos @@ -406,9 +390,7 @@ class Lz77Compress: # Check our existing locations to figure out if we still have # longest prefixes of 1 or 2 left. while copy_amount < backref_amount: - locations = self.locations[ - self.data[self.read_pos + copy_amount] - ] + locations = self.locations[self.data[self.read_pos + copy_amount]] new_backref_locations = [ absolute_pos for absolute_pos in possible_backref_locations @@ -422,11 +404,7 @@ class Lz77Compress: # Mark that we're copying an extra byte from the backref. self._ring_write( - self.data[ - (self.read_pos + copy_amount) : ( - self.read_pos + copy_amount + 1 - ) - ] + self.data[(self.read_pos + copy_amount) : (self.read_pos + copy_amount + 1)] ) copy_amount += 1 possible_backref_locations = new_backref_locations diff --git a/bemani/protocol/node.py b/bemani/protocol/node.py index 08d3926..9501237 100644 --- a/bemani/protocol/node.py +++ b/bemani/protocol/node.py @@ -22,9 +22,7 @@ class Node: constructor helper classmethods to make constructing a tree from source code easier. """ - NODE_NAME_CHARS: Final[ - str - ] = "0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" + NODE_NAME_CHARS: Final[str] = "0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" NODE_TYPE_VOID: Final[int] = 1 NODE_TYPE_S8: Final[int] = 2 @@ -649,9 +647,7 @@ class Node: A string data type name. This string can be fed to typename_to_type to get the original type back. """ if self.__translated_type is None: - raise Exception( - "Logic error, tried to fetch data type before setting type!" - ) + raise Exception("Logic error, tried to fetch data type before setting type!") return self.__translated_type["name"] @property @@ -664,9 +660,7 @@ class Node: An integer data length, or None if this node's element has variable length. """ if self.__translated_type is None: - raise Exception( - "Logic error, tried to fetch data length before setting type!" - ) + raise Exception("Logic error, tried to fetch data length before setting type!") if self.__translated_type["name"] in {"bin", "str"}: return None return struct.calcsize(self.__translated_type["enc"]) @@ -680,9 +674,7 @@ class Node: A character that can be passed to struct.pack or struct.unpack. """ if self.__translated_type is None: - raise Exception( - "Logic error, tried to fetch data encoding before setting type!" - ) + raise Exception("Logic error, tried to fetch data encoding before setting type!") return self.__translated_type["enc"] def set_attribute(self, attr: str, val: str = "") -> None: @@ -802,9 +794,7 @@ class Node: True if this Node is a composite type, False otherwise. """ if self.__translated_type is None: - raise Exception( - "Logic error, tried to fetch composite determination before setting type!" - ) + raise Exception("Logic error, tried to fetch composite determination before setting type!") return self.__translated_type["composite"] def set_value(self, val: Any) -> None: @@ -915,9 +905,7 @@ class Node: A string representing the XML-like data for this node and all children. """ if self.__translated_type is None: - raise Exception( - "Logic error, tried to get XML representation before setting type!" - ) + raise Exception("Logic error, tried to get XML representation before setting type!") translated_type: Dict[str, Any] = self.__translated_type attrs_dict = copy.deepcopy(self.__attrs) @@ -949,9 +937,7 @@ class Node: return str(val) if attrs_dict: - attrs = " " + " ".join( - [f'{attr}="{escape(attrs_dict[attr], attr=True)}"' for attr in order] - ) + attrs = " " + " ".join([f'{attr}="{escape(attrs_dict[attr], attr=True)}"' for attr in order]) else: attrs = "" @@ -986,7 +972,9 @@ class Node: f'{" " * ((depth + 1) * 4)}{get_val()}\n', ] + children - string = f'{" " * (depth * 4)}<{self.__name}{attrs}>\n{"".join(children)}{" " * (depth * 4)}\n' + string = ( + f'{" " * (depth * 4)}<{self.__name}{attrs}>\n{"".join(children)}{" " * (depth * 4)}\n' + ) else: # Doesn't have children nodes if self.data_length == 0: diff --git a/bemani/protocol/protocol.py b/bemani/protocol/protocol.py index 2377f62..3c93adc 100644 --- a/bemani/protocol/protocol.py +++ b/bemani/protocol/protocol.py @@ -88,10 +88,7 @@ class EAmuseProtocol: if encryption_key: # Key is concatenated with the shared secret above version, first, second = encryption_key.split("-") - key = ( - binascii.unhexlify((first + second).encode("ascii")) - + EAmuseProtocol.SHARED_SECRET - ) + key = binascii.unhexlify((first + second).encode("ascii")) + EAmuseProtocol.SHARED_SECRET # Next, key is sent through MD5 to derive the real key m = hashlib.md5() @@ -232,9 +229,7 @@ class EAmuseProtocol: else: raise EAmuseException(f"Invalid packet encoding {packet_encoding}") - def decode( - self, compression: Optional[str], encryption: Optional[str], data: bytes - ) -> Node: + def decode(self, compression: Optional[str], encryption: Optional[str], data: bytes) -> Node: """ Given a request with optional compression and encryption set, decrypt, decompress and decode the data, returning a parsed tree. diff --git a/bemani/protocol/xml.py b/bemani/protocol/xml.py index 1f31d55..44ac51f 100644 --- a/bemani/protocol/xml.py +++ b/bemani/protocol/xml.py @@ -60,9 +60,7 @@ class XmlDecoder: # Get the data value type_int = Node.typename_to_type(data_type) if type_int is None: - raise XmlEncodingException( - f'Invalid node type {data_type} for node {tag.decode("ascii")}' - ) + raise XmlEncodingException(f'Invalid node type {data_type} for node {tag.decode("ascii")}') node = Node(name=tag.decode("ascii"), type=type_int, array=array) @@ -87,9 +85,7 @@ class XmlDecoder: node = self.current.pop() if node.name != tag.decode("ascii"): - raise Exception( - f'Logic error, expected {tag.decode("ascii")} but got {node.name}' - ) + raise Exception(f'Logic error, expected {tag.decode("ascii")} but got {node.name}') if len(self.current) == 0: self.root = node @@ -154,22 +150,12 @@ class XmlDecoder: value = "".join([c for c in value if not c.isspace()]) if self.current[-1].value is None: self.current[-1].set_value( - b"".join( - [ - hex_to_bin(value[i : (i + 2)]) - for i in range(0, len(value), 2) - ] - ) + b"".join([hex_to_bin(value[i : (i + 2)]) for i in range(0, len(value), 2)]) ) else: self.current[-1].set_value( self.current[-1].value - + b"".join( - [ - hex_to_bin(value[i : (i + 2)]) - for i in range(0, len(value), 2) - ] - ) + + b"".join([hex_to_bin(value[i : (i + 2)]) for i in range(0, len(value), 2)]) ) elif data_type == "ip4": # Do nothing, already fine @@ -183,23 +169,17 @@ class XmlDecoder: return True if array or composite: - self.current[-1].set_value( - [conv_bool(v) for v in self.__yield_values(value)] - ) + self.current[-1].set_value([conv_bool(v) for v in self.__yield_values(value)]) else: self.current[-1].set_value(conv_bool(value)) elif data_type == "float": if array or composite: - self.current[-1].set_value( - [float(v) for v in self.__yield_values(value)] - ) + self.current[-1].set_value([float(v) for v in self.__yield_values(value)]) else: self.current[-1].set_value(float(value)) else: if array or composite: - self.current[-1].set_value( - [int(v) for v in self.__yield_values(value)] - ) + self.current[-1].set_value([int(v) for v in self.__yield_values(value)]) else: self.current[-1].set_value(int(value)) @@ -465,9 +445,7 @@ class XmlEncoder: vals = "" else: if node.data_type == "bool": - vals = " ".join( - [("1" if val else "0") for val in node.value] - ) + vals = " ".join([("1" if val else "0") for val in node.value]) else: vals = " ".join([str(val) for val in node.value]) binary = vals.encode("ascii") diff --git a/bemani/sniff/sniff.py b/bemani/sniff/sniff.py index ea67356..4390ed0 100644 --- a/bemani/sniff/sniff.py +++ b/bemani/sniff/sniff.py @@ -203,9 +203,7 @@ class Sniffer: IP_HEADER_LENGTH: Final[int] = 20 TCP_HEADER_LENGTH: Final[int] = 20 - def __init__( - self, address: Optional[str] = None, port: Optional[int] = None - ) -> None: + def __init__(self, address: Optional[str] = None, port: Optional[int] = None) -> None: """ Initialize the sniffer. Can be told to filter by address, port or both. If address or port is not provided, it defaults to all addresses or ports. @@ -309,9 +307,7 @@ class Sniffer: "fin": bool(flags & 0x001), } - def __process_address( - self, address: Tuple[int, int, int, int, int] - ) -> Dict[str, int]: + def __process_address(self, address: Tuple[int, int, int, int, int]) -> Dict[str, int]: """ Given an address tuple from Linux's recvfrom syscall, return a dict which represents this address. @@ -391,9 +387,7 @@ class Sniffer: offset = 0 # Make sure its a valid packet - eth_header = self.__process_ethframe( - packet[offset : (offset + Sniffer.ETH_HEADER_LENGTH)] - ) + eth_header = self.__process_ethframe(packet[offset : (offset + Sniffer.ETH_HEADER_LENGTH)]) offset = offset + eth_header["header_length"] if eth_header["protocol"] != 8: @@ -401,9 +395,7 @@ class Sniffer: raise UnknownPacketException(f'Unknown frame {eth_header["protocol"]}') # Get the IP header - ip_header = self.__process_ipframe( - packet[offset : (offset + Sniffer.IP_HEADER_LENGTH)] - ) + ip_header = self.__process_ipframe(packet[offset : (offset + Sniffer.IP_HEADER_LENGTH)]) offset = offset + ip_header["header_length"] if ip_header["protocol"] != 6: @@ -413,17 +405,11 @@ class Sniffer: ) # Get TCP header - tcp_header = self.__process_tcpframe( - packet[offset : (offset + Sniffer.TCP_HEADER_LENGTH)] - ) + tcp_header = self.__process_tcpframe(packet[offset : (offset + Sniffer.TCP_HEADER_LENGTH)]) offset = offset + tcp_header["header_length"] # Get payload length - payload_length = ( - ip_header["length"] - - ip_header["header_length"] - - tcp_header["header_length"] - ) + payload_length = ip_header["length"] - ip_header["header_length"] - tcp_header["header_length"] # Get payload data = packet[offset : offset + payload_length] @@ -449,10 +435,7 @@ class Sniffer: continue # Hack for sniffing on localhost - if ( - packet["address"]["interface"] == "lo" - and packet["address"]["type"] != 4 - ): + if packet["address"]["interface"] == "lo" and packet["address"]["type"] != 4: continue if self.address and self.port: diff --git a/bemani/tests/helpers.py b/bemani/tests/helpers.py index f168eac..7ca0771 100644 --- a/bemani/tests/helpers.py +++ b/bemani/tests/helpers.py @@ -28,9 +28,7 @@ class FakeCursor: def fetchone(self) -> Dict[str, Any]: if len(self.__rows) != 1: - raise Exception( - f"Tried to fetch one row and there are {len(self.__rows)} rows!" - ) + raise Exception(f"Tried to fetch one row and there are {len(self.__rows)} rows!") return self.__rows[0] def __iter__(self) -> "FakeCursor": diff --git a/bemani/tests/test_AES.py b/bemani/tests/test_AES.py index e57a9c8..15495f8 100644 --- a/bemani/tests/test_AES.py +++ b/bemani/tests/test_AES.py @@ -11,9 +11,7 @@ class TestAESCipher(unittest.TestCase): self.assertEqual(aes._unpad(aes._pad("")), "") self.assertEqual(aes._pad("1337"), "4.1337----------") self.assertEqual(aes._unpad(aes._pad("1337")), "1337") - self.assertEqual( - aes._pad("aaaaaaaaaaaaaaaa"), "16.aaaaaaaaaaaaaaaa-------------" - ) + self.assertEqual(aes._pad("aaaaaaaaaaaaaaaa"), "16.aaaaaaaaaaaaaaaa-------------") self.assertEqual(aes._unpad(aes._pad("aaaaaaaaaaaaaaaa")), "aaaaaaaaaaaaaaaa") self.assertEqual(aes._pad("aaaaaaaaaaaaa"), "13.aaaaaaaaaaaaa") self.assertEqual(aes._unpad(aes._pad("aaaaaaaaaaaaa")), "aaaaaaaaaaaaa") diff --git a/bemani/tests/test_APIClient.py b/bemani/tests/test_APIClient.py index 1f3f4f3..9244d43 100644 --- a/bemani/tests/test_APIClient.py +++ b/bemani/tests/test_APIClient.py @@ -9,9 +9,7 @@ class TestAPIClient(unittest.TestCase): client = APIClient("https://127.0.0.1", "token", False, False) self.assertFalse(client._content_type_valid("application/text")) self.assertFalse(client._content_type_valid("application/json")) - self.assertFalse( - client._content_type_valid("application/json; charset=shift-jis") - ) + self.assertFalse(client._content_type_valid("application/json; charset=shift-jis")) self.assertTrue(client._content_type_valid("application/json; charset=utf-8")) self.assertTrue(client._content_type_valid("application/json;charset=utf-8")) self.assertTrue(client._content_type_valid("application/json;charset = utf-8")) diff --git a/bemani/tests/test_CardCipher.py b/bemani/tests/test_CardCipher.py index 772379e..8b2183f 100644 --- a/bemani/tests/test_CardCipher.py +++ b/bemani/tests/test_CardCipher.py @@ -21,13 +21,9 @@ class TestCardCipher(unittest.TestCase): inp = bytes(pair[0]) out = bytes(pair[1]) encoded = CardCipher.INTERNAL_CIPHER.encrypt(inp) - self.assertEqual( - encoded, out, f"Card encode {encoded!r} doesn't match expected {out!r}" - ) + self.assertEqual(encoded, out, f"Card encode {encoded!r} doesn't match expected {out!r}") decoded = CardCipher.INTERNAL_CIPHER.decrypt(out) - self.assertEqual( - decoded, inp, f"Card decode {decoded!r} doesn't match expected {inp!r}" - ) + self.assertEqual(decoded, inp, f"Card decode {decoded!r} doesn't match expected {inp!r}") def test_external_cipher(self) -> None: test_cards = [ @@ -39,10 +35,6 @@ class TestCardCipher(unittest.TestCase): back = card[0] db = card[1] decoded = CardCipher.decode(back) - self.assertEqual( - decoded, db, f"Card DB {decoded} doesn't match expected {db}" - ) + self.assertEqual(decoded, db, f"Card DB {decoded} doesn't match expected {db}") encoded = CardCipher.encode(db) - self.assertEqual( - encoded, back, f"Card back {encoded} doesn't match expected {back}" - ) + self.assertEqual(encoded, back, f"Card back {encoded} doesn't match expected {back}") diff --git a/bemani/tests/test_GameData.py b/bemani/tests/test_GameData.py index 05a75b4..7cc42e4 100644 --- a/bemani/tests/test_GameData.py +++ b/bemani/tests/test_GameData.py @@ -19,9 +19,7 @@ class TestGameData(unittest.TestCase): "work", {"start_time": 12345, "end_time": 12340}, ) - self.assertTrue( - "Start time is greater than end time!" in str(context.exception) - ) + self.assertTrue("Start time is greater than end time!" in str(context.exception)) # Verify that we catch events spanning no time with self.assertRaises(Exception) as context: @@ -52,6 +50,5 @@ class TestGameData(unittest.TestCase): {"start_time": 12347, "end_time": 12355}, ) self.assertTrue( - "This event overlaps an existing one with start time 12345 and end time 12350" - in str(context.exception) + "This event overlaps an existing one with start time 12345 and end time 12350" in str(context.exception) ) diff --git a/bemani/tests/test_NetworkData.py b/bemani/tests/test_NetworkData.py index c2ec437..5529306 100644 --- a/bemani/tests/test_NetworkData.py +++ b/bemani/tests/test_NetworkData.py @@ -33,31 +33,19 @@ class TestNetworkData(unittest.TestCase): with freeze_time("2016-01-01"): # Check for should schedule if nothing in DB network.execute = Mock(return_value=FakeCursor([])) # type: ignore - self.assertTrue( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily") - ) - self.assertTrue( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly") - ) + self.assertTrue(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily")) + self.assertTrue(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly")) # Check for don't schedule if DB time is our current time network.execute = Mock(return_value=FakeCursor([{"year": 2016, "day": 1}])) # type: ignore - self.assertFalse( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily") - ) + self.assertFalse(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily")) network.execute = Mock(return_value=FakeCursor([{"year": None, "day": 16797}])) # type: ignore - self.assertFalse( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly") - ) + self.assertFalse(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly")) # Check for do schedule if DB time is older than our current time network.execute = Mock(return_value=FakeCursor([{"year": 2015, "day": 365}])) # type: ignore - self.assertTrue( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily") - ) + self.assertTrue(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "daily")) network.execute = Mock(return_value=FakeCursor([{"year": None, "day": 16790}])) # type: ignore - self.assertTrue( - network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly") - ) + self.assertTrue(network.should_schedule(GameConstants.BISHI_BASHI, 1, "work", "weekly")) diff --git a/bemani/tests/test_PlayStats.py b/bemani/tests/test_PlayStats.py index 963067c..0bfb308 100644 --- a/bemani/tests/test_PlayStats.py +++ b/bemani/tests/test_PlayStats.py @@ -21,9 +21,7 @@ def mock_stats(existing_value: Dict[str, Any]) -> Mock: data = Mock() data.local = Mock() data.local.game = Mock() - data.local.game.get_settings = Mock( - return_value=ValidatedDict(existing_value) if existing_value else None - ) + data.local.game.get_settings = Mock(return_value=ValidatedDict(existing_value) if existing_value else None) data.local.game.put_settings = Mock() return data @@ -65,9 +63,7 @@ class TestPlayStats(unittest.TestCase): self.assertEqual(new_settings.get_int("consecutive_days"), 1) self.assertEqual(new_settings.get_int("first_play_timestamp"), Time.now()) self.assertEqual(new_settings.get_int("last_play_timestamp"), Time.now()) - self.assertEqual( - new_settings.get_int_array("last_play_date", 3), Time.todays_date() - ) + self.assertEqual(new_settings.get_int_array("last_play_date", 3), Time.todays_date()) def test_get_played_today(self) -> None: with freeze_time("2021-08-24"): @@ -119,9 +115,7 @@ class TestPlayStats(unittest.TestCase): self.assertEqual(new_settings.get_int("consecutive_days"), 69) self.assertEqual(new_settings.get_int("first_play_timestamp"), 1234567890) self.assertEqual(new_settings.get_int("last_play_timestamp"), Time.now()) - self.assertEqual( - new_settings.get_int_array("last_play_date", 3), Time.todays_date() - ) + self.assertEqual(new_settings.get_int_array("last_play_date", 3), Time.todays_date()) def test_get_played_yesterday(self) -> None: with freeze_time("2021-08-24"): @@ -173,9 +167,7 @@ class TestPlayStats(unittest.TestCase): self.assertEqual(new_settings.get_int("consecutive_days"), 70) self.assertEqual(new_settings.get_int("first_play_timestamp"), 1234567890) self.assertEqual(new_settings.get_int("last_play_timestamp"), Time.now()) - self.assertEqual( - new_settings.get_int_array("last_play_date", 3), Time.todays_date() - ) + self.assertEqual(new_settings.get_int_array("last_play_date", 3), Time.todays_date()) def test_get_played_awhile_ago(self) -> None: with freeze_time("2021-08-24"): @@ -225,9 +217,7 @@ class TestPlayStats(unittest.TestCase): self.assertEqual(new_settings.get_int("consecutive_days"), 1) self.assertEqual(new_settings.get_int("first_play_timestamp"), 1234567890) self.assertEqual(new_settings.get_int("last_play_timestamp"), Time.now()) - self.assertEqual( - new_settings.get_int_array("last_play_date", 3), Time.todays_date() - ) + self.assertEqual(new_settings.get_int_array("last_play_date", 3), Time.todays_date()) def test_get_extra_settings(self) -> None: with freeze_time("2021-08-24"): diff --git a/bemani/tests/test_ValidatedDict.py b/bemani/tests/test_ValidatedDict.py index e00e9a6..2a5a51d 100644 --- a/bemani/tests/test_ValidatedDict.py +++ b/bemani/tests/test_ValidatedDict.py @@ -33,13 +33,9 @@ class TestValidatedDict(unittest.TestCase): self.assertEqual(validict.get_int_array("int_array", 3), [0, 0, 0]) self.assertEqual(validict.get_int_array("int_array", 3, [1, 2, 3]), [1, 2, 3]) self.assertEqual(validict.get_bool_array("bool_array", 2), [False, False]) - self.assertEqual( - validict.get_bool_array("bool_array", 2, [False, True]), [False, True] - ) + self.assertEqual(validict.get_bool_array("bool_array", 2, [False, True]), [False, True]) self.assertEqual(validict.get_str_array("str_array", 3), ["", "", ""]) - self.assertEqual( - validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["1", "2", "3"] - ) + self.assertEqual(validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["1", "2", "3"]) self.assertEqual(validict.get_bytes_array("bytes_array", 3), [b"", b"", b""]) self.assertEqual( validict.get_bytes_array("bytes_array", 3, [b"1", b"2", b"3"]), @@ -77,13 +73,9 @@ class TestValidatedDict(unittest.TestCase): self.assertEqual(validict.get_int_array("int_array", 3), [3, 2, 1]) self.assertEqual(validict.get_int_array("int_array", 3, [1, 2, 3]), [3, 2, 1]) self.assertEqual(validict.get_bool_array("bool_array", 2), [True, False]) - self.assertEqual( - validict.get_bool_array("bool_array", 2, [False, True]), [True, False] - ) + self.assertEqual(validict.get_bool_array("bool_array", 2, [False, True]), [True, False]) self.assertEqual(validict.get_str_array("str_array", 3), ["3", "4", "5"]) - self.assertEqual( - validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["3", "4", "5"] - ) + self.assertEqual(validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["3", "4", "5"]) self.assertEqual(validict.get_bytes_array("bytes_array", 3), [b"3", b"5", b"7"]) self.assertEqual( validict.get_bytes_array("bytes_array", 3, [b"1", b"2", b"3"]), @@ -120,17 +112,13 @@ class TestValidatedDict(unittest.TestCase): self.assertEqual(validict.get_bytes("bytes", b"test"), b"test") self.assertEqual(validict.get_int_array("int_array", 3), [0, 0, 0]) self.assertEqual(validict.get_int_array("int_array", 3, [1, 2, 3]), [1, 2, 3]) - self.assertEqual( - validict.get_bool_array("bool_array", 3), [False, False, False] - ) + self.assertEqual(validict.get_bool_array("bool_array", 3), [False, False, False]) self.assertEqual( validict.get_bool_array("bool_array", 3, [False, True, True]), [False, True, True], ) self.assertEqual(validict.get_str_array("str_array", 3), ["", "", ""]) - self.assertEqual( - validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["1", "2", "3"] - ) + self.assertEqual(validict.get_str_array("str_array", 3, ["1", "2", "3"]), ["1", "2", "3"]) self.assertEqual(validict.get_bytes_array("bytes_array", 3), [b"", b"", b""]) self.assertEqual( validict.get_bytes_array("bytes_array", 3, [b"1", b"2", b"3"]), diff --git a/bemani/tests/test_XmlDecoder.py b/bemani/tests/test_XmlDecoder.py index 272e080..05b7e61 100644 --- a/bemani/tests/test_XmlDecoder.py +++ b/bemani/tests/test_XmlDecoder.py @@ -103,9 +103,7 @@ class TestXmlDecoder(unittest.TestCase): self.assertEqual(tree.data_type, "u32") self.assertEqual(tree.value, [1, 2, 3, 4]) - xml = XmlDecoder( - b'\n1\n2\n3\n4\n', "ascii" - ) + xml = XmlDecoder(b'\n1\n2\n3\n4\n', "ascii") tree = xml.get_tree() self.assertEqual(tree.children, []) diff --git a/bemani/tests/test_afp_decompile.py b/bemani/tests/test_afp_decompile.py index 1aa07e0..05c7a7f 100644 --- a/bemani/tests/test_afp_decompile.py +++ b/bemani/tests/test_afp_decompile.py @@ -155,9 +155,7 @@ class TestAFPControlGraph(ExtendedTestCase): actions[-1].offset + 1, ) - def __call_graph( - self, bytecode: ByteCode - ) -> Tuple[Dict[int, ByteCodeChunk], Dict[int, int]]: + def __call_graph(self, bytecode: ByteCode) -> Tuple[Dict[int, ByteCodeChunk], Dict[int, int]]: # Just create a dummy compiler so we can access the internal method for testing. bcd = ByteCodeDecompiler(bytecode, optimize=True) @@ -165,9 +163,7 @@ class TestAFPControlGraph(ExtendedTestCase): chunks, offset_map = bcd._graph_control_flow(bytecode) return {chunk.id: chunk for chunk in chunks}, offset_map - def __equiv( - self, bytecode: Union[ByteCode, ByteCodeChunk, List[AP2Action]] - ) -> List[str]: + def __equiv(self, bytecode: Union[ByteCode, ByteCodeChunk, List[AP2Action]]) -> List[str]: if isinstance(bytecode, (ByteCode, ByteCodeChunk)): return [str(x) for x in bytecode.actions] else: @@ -230,27 +226,13 @@ class TestAFPControlGraph(ExtendedTestCase): self.assertItemsEqual(chunks_by_id[8].next_chunks, []) # Also verify the code - self.assertEqual( - self.__equiv(chunks_by_id[0]), ["100: JUMP, Offset To Jump To: 102"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[1]), ["101: JUMP, Offset To Jump To: 104"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[2]), ["102: JUMP, Offset To Jump To: 101"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[3]), ["103: JUMP, Offset To Jump To: 106"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[4]), ["104: JUMP, Offset To Jump To: 103"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[5]), ["105: JUMP, Offset To Jump To: 107"] - ) - self.assertEqual( - self.__equiv(chunks_by_id[6]), ["106: JUMP, Offset To Jump To: 105"] - ) + self.assertEqual(self.__equiv(chunks_by_id[0]), ["100: JUMP, Offset To Jump To: 102"]) + self.assertEqual(self.__equiv(chunks_by_id[1]), ["101: JUMP, Offset To Jump To: 104"]) + self.assertEqual(self.__equiv(chunks_by_id[2]), ["102: JUMP, Offset To Jump To: 101"]) + self.assertEqual(self.__equiv(chunks_by_id[3]), ["103: JUMP, Offset To Jump To: 106"]) + self.assertEqual(self.__equiv(chunks_by_id[4]), ["104: JUMP, Offset To Jump To: 103"]) + self.assertEqual(self.__equiv(chunks_by_id[5]), ["105: JUMP, Offset To Jump To: 107"]) + self.assertEqual(self.__equiv(chunks_by_id[6]), ["106: JUMP, Offset To Jump To: 105"]) self.assertEqual(self.__equiv(chunks_by_id[7]), ["107: STOP"]) self.assertEqual(self.__equiv(chunks_by_id[8]), []) @@ -758,9 +740,7 @@ class TestAFPDecompile(ExtendedTestCase): ] ) statements = self.__call_decompile(bytecode) - self.assertEqual( - self.__equiv(statements), ["builtin_StopPlaying()", "builtin_StopPlaying()"] - ) + self.assertEqual(self.__equiv(statements), ["builtin_StopPlaying()", "builtin_StopPlaying()"]) def test_dead_code_elimination_return(self) -> None: # Return case @@ -814,9 +794,7 @@ class TestAFPDecompile(ExtendedTestCase): statements = self.__call_decompile(bytecode) self.assertEqual( self.__equiv(statements), - [ - f"if (True) {OPEN_BRACKET}{os.linesep} builtin_StartPlaying(){os.linesep}{CLOSE_BRACKET}" - ], + [f"if (True) {OPEN_BRACKET}{os.linesep} builtin_StartPlaying(){os.linesep}{CLOSE_BRACKET}"], ) def test_if_handling_basic_jump_to_end(self) -> None: @@ -835,9 +813,7 @@ class TestAFPDecompile(ExtendedTestCase): statements = self.__call_decompile(bytecode) self.assertEqual( self.__equiv(statements), - [ - f"if (True) {OPEN_BRACKET}{os.linesep} builtin_StartPlaying(){os.linesep}{CLOSE_BRACKET}" - ], + [f"if (True) {OPEN_BRACKET}{os.linesep} builtin_StartPlaying(){os.linesep}{CLOSE_BRACKET}"], ) def test_if_handling_diamond(self) -> None: @@ -1039,9 +1015,7 @@ class TestAFPDecompile(ExtendedTestCase): self.__equiv(statements), [ "local finished = False", - f"while (not finished) {OPEN_BRACKET}{os.linesep}" - f" builtin_GotoNextFrame(){os.linesep}" - "}", + f"while (not finished) {OPEN_BRACKET}{os.linesep}" f" builtin_GotoNextFrame(){os.linesep}" "}", ], ) @@ -1173,9 +1147,7 @@ class TestIfExprs(ExtendedTestCase): "a == b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")) - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b"))), "a != b", ) self.assertEqual( @@ -1195,19 +1167,11 @@ class TestIfExprs(ExtendedTestCase): "a >= b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b") - ) - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b"))), "a === b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b") - ) - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b"))), "a !== b", ) self.assertEqual( @@ -1230,68 +1194,38 @@ class TestIfExprs(ExtendedTestCase): ) def test_invert_simple(self) -> None: - self.assertEqual( - str(IsUndefinedIf(Variable("a")).invert()), "a is not UNDEFINED" - ) + self.assertEqual(str(IsUndefinedIf(Variable("a")).invert()), "a is not UNDEFINED") self.assertEqual(str(IsBooleanIf(Variable("a")).invert()), "not a") self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")).invert()), "a != b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")).invert()), "a == b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")).invert()), "a >= b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")).invert()), "a <= b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")).invert()), "a > b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")).invert()), "a < b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b")).invert()), "a !== b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b") - ).invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b")).invert()), "a === b", ) self.assertEqual( @@ -1314,76 +1248,38 @@ class TestIfExprs(ExtendedTestCase): ) def test_invert_double(self) -> None: - self.assertEqual( - str(IsUndefinedIf(Variable("a")).invert().invert()), "a is UNDEFINED" - ) + self.assertEqual(str(IsUndefinedIf(Variable("a")).invert().invert()), "a is UNDEFINED") self.assertEqual(str(IsBooleanIf(Variable("a")).invert().invert()), "a") self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")).invert().invert()), "a == b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")).invert().invert()), "a != b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")).invert().invert()), "a < b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")).invert().invert()), "a > b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")).invert().invert()), "a <= b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")).invert().invert()), "a >= b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b") - ) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b")).invert().invert()), "a === b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b") - ) - .invert() - .invert() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b")).invert().invert()), "a !== b", ) self.assertEqual( @@ -1413,19 +1309,11 @@ class TestIfExprs(ExtendedTestCase): self.assertEqual(str(IsUndefinedIf(Variable("a")).swap()), "a is UNDEFINED") self.assertEqual(str(IsBooleanIf(Variable("a")).swap()), "a") self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")).swap()), "b == a", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")).swap()), "b != a", ) self.assertEqual( @@ -1437,35 +1325,19 @@ class TestIfExprs(ExtendedTestCase): "b < a", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")).swap()), "b >= a", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")).swap()), "b <= a", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b")).swap()), "b === a", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b") - ).swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b")).swap()), "b !== a", ) self.assertEqual( @@ -1488,76 +1360,38 @@ class TestIfExprs(ExtendedTestCase): ) def test_swap_double(self) -> None: - self.assertEqual( - str(IsUndefinedIf(Variable("a")).swap().swap()), "a is UNDEFINED" - ) + self.assertEqual(str(IsUndefinedIf(Variable("a")).swap().swap()), "a is UNDEFINED") self.assertEqual(str(IsBooleanIf(Variable("a")).swap().swap()), "a") self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.EQUALS, Variable("b")).swap().swap()), "a == b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.NOT_EQUALS, Variable("b")).swap().swap()), "a != b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")).swap().swap()), "a < b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT, Variable("b")).swap().swap()), "a > b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.LT_EQUALS, Variable("b")).swap().swap()), "a <= b", ) self.assertEqual( - str( - TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")).swap().swap()), "a >= b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b") - ) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_EQUALS, Variable("b")).swap().swap()), "a === b", ) self.assertEqual( - str( - TwoParameterIf( - Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b") - ) - .swap() - .swap() - ), + str(TwoParameterIf(Variable("a"), TwoParameterIf.STRICT_NOT_EQUALS, Variable("b")).swap().swap()), "a !== b", ) self.assertEqual( @@ -1585,9 +1419,7 @@ class TestIfExprs(ExtendedTestCase): def test_simplify_noop(self) -> None: self.assertEqual(str(IsUndefinedIf(Variable("a")).simplify()), "a is UNDEFINED") - self.assertEqual( - str(IsUndefinedIf(Variable("a")).invert().simplify()), "a is not UNDEFINED" - ) + self.assertEqual(str(IsUndefinedIf(Variable("a")).invert().simplify()), "a is not UNDEFINED") self.assertEqual(str(IsBooleanIf(Variable("a")).simplify()), "a") self.assertEqual(str(IsBooleanIf(Variable("a")).invert().simplify()), "not a") self.assertEqual( @@ -1612,9 +1444,7 @@ class TestIfExprs(ExtendedTestCase): str( AndIf( TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")), - TwoParameterIf( - Variable("a"), TwoParameterIf.GT_EQUALS, Variable("c") - ), + TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("c")), ).simplify() ), "a < b && a >= c", @@ -1716,9 +1546,7 @@ class TestIfExprs(ExtendedTestCase): str( AndIf( TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")), - TwoParameterIf( - Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b") - ), + TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")), ).simplify() ), "False", @@ -1727,9 +1555,7 @@ class TestIfExprs(ExtendedTestCase): str( OrIf( TwoParameterIf(Variable("a"), TwoParameterIf.LT, Variable("b")), - TwoParameterIf( - Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b") - ), + TwoParameterIf(Variable("a"), TwoParameterIf.GT_EQUALS, Variable("b")), ).simplify() ), "True", @@ -1967,9 +1793,7 @@ class TestAFPOptimize(ExtendedTestCase): optimize=True, ) with bcd.debugging(verbose=self.verbose): - return bcd._pretty_print(bcd._optimize_code(statements), prefix="").split( - os.linesep - ) + return bcd._pretty_print(bcd._optimize_code(statements), prefix="").split(os.linesep) def test_no_flow(self) -> None: statements: List[Statement] = [ diff --git a/bemani/tests/test_protocol.py b/bemani/tests/test_protocol.py index 8bf1c61..250e10f 100644 --- a/bemani/tests/test_protocol.py +++ b/bemani/tests/test_protocol.py @@ -111,9 +111,7 @@ class TestProtocol(unittest.TestCase): eacoin = Node.void("eacoin") root.add_child(eacoin) eacoin.set_attribute("esdate", "2015-08-01T02:09:23") - eacoin.set_attribute( - "esid", "177baae4bdf0085f1f3da9b6fed02223ee9b482f62b83a28af704a9c7893a370" - ) + eacoin.set_attribute("esid", "177baae4bdf0085f1f3da9b6fed02223ee9b482f62b83a28af704a9c7893a370") eacoin.set_attribute("method", "consume") eacoin.add_child(Node.string("sessid", "5666-5524")) @@ -409,9 +407,7 @@ class TestProtocol(unittest.TestCase): root.add_child(Node.s32_array("s32_array_node", [-2000000000, -1])) root.add_child(Node.u32_array("u32_array_node", [4000000000, 0, 1, 2])) root.add_child(Node.s64_array("s64_array_node", [-1234567890000, -1, 1, 1337])) - root.add_child( - Node.u64_array("u64_array_node", [1234567890000, 123, 456, 7890]) - ) + root.add_child(Node.u64_array("u64_array_node", [1234567890000, 123, 456, 7890])) root.add_child(Node.time_array("time_array_node", [1234567890, 98765432])) root.add_child(Node.float_array("float_array_node", [2.5, 0.0, 5.0, 20.5])) root.add_child(Node.bool_array("bool_array_node", [False, True, True, False])) diff --git a/bemani/utils/afputils.py b/bemani/utils/afputils.py index d87129f..87e3831 100644 --- a/bemani/utils/afputils.py +++ b/bemani/utils/afputils.py @@ -307,9 +307,7 @@ def extract_txp2( sprite.save(bfp, format="PNG") else: if not announced.get(texturename, False): - print( - f"Cannot extract sprites from {texturename} because it is not a supported format!" - ) + print(f"Cannot extract sprites from {texturename} because it is not a supported format!") announced[texturename] = True if write_bytecode: for swf in afpfile.swfdata: @@ -318,9 +316,7 @@ def extract_txp2( return 0 -def update_txp2( - fname: str, update_dir: str, *, pretend: bool = False, verbose: bool = False -) -> int: +def update_txp2(fname: str, update_dir: str, *, pretend: bool = False, verbose: bool = False) -> int: # First, parse the file out with open(fname, "rb") as bfp: afpfile = TXP2File(bfp.read(), verbose=verbose) @@ -347,9 +343,7 @@ def update_txp2( filename = os.path.join(update_dir, filename) if os.path.isfile(filename): - print( - f"Updating {texturename} sprite piece {spritename} from {filename}..." - ) + print(f"Updating {texturename} sprite piece {spritename} from {filename}...") with open(filename, "rb") as bfp: afpfile.update_sprite(texturename, spritename, bfp.read()) @@ -367,9 +361,7 @@ def update_txp2( return 0 -def print_txp2( - fname: str, *, decompile_bytecode: bool = False, verbose: bool = False -) -> int: +def print_txp2(fname: str, *, decompile_bytecode: bool = False, verbose: bool = False) -> int: # First, parse the file out with open(fname, "rb") as bfp: afpfile = TXP2File(bfp.read(), verbose=verbose) @@ -386,9 +378,7 @@ def print_txp2( return 0 -def parse_afp( - afp: str, bsi: str, *, decompile_bytecode: bool = False, verbose: bool = False -) -> int: +def parse_afp(afp: str, bsi: str, *, decompile_bytecode: bool = False, verbose: bool = False) -> int: # First, load the AFP and BSI files with open(afp, "rb") as bafp: with open(bsi, "rb") as bbsi: @@ -434,9 +424,7 @@ def parse_geo(geo: str, *, verbose: bool = False) -> int: return 0 -def load_containers( - renderer: AFPRenderer, containers: List[str], *, need_extras: bool, verbose: bool -) -> None: +def load_containers(renderer: AFPRenderer, containers: List[str], *, need_extras: bool, verbose: bool) -> None: # This is a complicated one, as we need to be able to specify multiple # directories of files as well as support IFS files and TXP2 files. for container in containers: @@ -463,9 +451,7 @@ def load_containers( renderer.add_shape(name, shape) if verbose: - print( - f"Added {name} to animation shape library.", file=sys.stderr - ) + print(f"Added {name} to animation shape library.", file=sys.stderr) # Now, split and load textures into the renderer. sheets: Dict[str, Any] = {} @@ -482,9 +468,7 @@ def load_containers( sheets[texturename] = tex break else: - raise Exception( - "Could not find texture {texturename} to split!" - ) + raise Exception("Could not find texture {texturename} to split!") if sheets[texturename].img: sprite = sheets[texturename].img.crop( @@ -503,9 +487,7 @@ def load_containers( file=sys.stderr, ) else: - print( - f"Cannot load {name} from {texturename} because it is not a supported format!" - ) + print(f"Cannot load {name} from {texturename} because it is not a supported format!") # Finally, load the animation data itself into the renderer. for i, name in enumerate(afpfile.swfmap.entries): @@ -631,24 +613,16 @@ def adjust_background_loop( background_loop_end = len(background) if background_loop_start >= background_loop_end: - raise Exception( - "Cannot start background loop after the end of the background loop!" - ) + raise Exception("Cannot start background loop after the end of the background loop!") if background_loop_start < 0 or background_loop_end < 0: raise Exception("Cannot start or end background loop on a negative frame!") - if background_loop_start >= len(background) or background_loop_end > len( - background - ): - raise Exception( - "Cannot start or end background loop larger than the number of background animation frames!" - ) + if background_loop_start >= len(background) or background_loop_end > len(background): + raise Exception("Cannot start or end background loop larger than the number of background animation frames!") background = background[background_loop_start:background_loop_end] if background_loop_offset < 0 or background_loop_offset >= len(background): - raise Exception( - "Cannot start first iteration of background loop outside the loop bounds!" - ) + raise Exception("Cannot start first iteration of background loop outside the loop bounds!") return background[background_loop_offset:] + background[:background_loop_offset] @@ -680,9 +654,7 @@ def render_path( if show_progress: print("Loading textures, shapes and animation instructions...") - renderer = AFPRenderer( - single_threaded=disable_threads, enable_aa=enable_anti_aliasing - ) + renderer = AFPRenderer(single_threaded=disable_threads, enable_aa=enable_anti_aliasing) load_containers(renderer, containers, need_extras=True, verbose=verbose) if show_progress: @@ -702,9 +674,7 @@ def render_path( if background_color: colorvals = background_color.split(",") if len(colorvals) not in [3, 4]: - raise Exception( - "Invalid color, specify a color as a comma-separated RGB or RGBA value!" - ) + raise Exception("Invalid color, specify a color as a comma-separated RGB or RGBA value!") if len(colorvals) == 3: colorvals.append("255") @@ -766,9 +736,7 @@ def render_path( ) # Finally, get the filenames from this sequence. - filenames: List[str] = [ - os.path.join(dirof, filename) for (_, filename) in seqtuple - ] + filenames: List[str] = [os.path.join(dirof, filename) for (_, filename) in seqtuple] # Now that we have the list, lets load the images! for filename in filenames: @@ -816,9 +784,7 @@ def render_path( if force_aspect_ratio: ratio = force_aspect_ratio.split(":") if len(ratio) != 2: - raise Exception( - "Invalid aspect ratio, specify a ratio such as 16:9 or 4:3!" - ) + raise Exception("Invalid aspect ratio, specify a ratio such as 16:9 or 4:3!") rx, ry = [float(r.strip()) for r in ratio] if rx <= 0 or ry <= 0: @@ -888,9 +854,7 @@ def render_path( ) ): if show_progress: - frameno = ( - requested_frames[i] if requested_frames is not None else (i + 1) - ) + frameno = requested_frames[i] if requested_frames is not None else (i + 1) print(f"Rendered animation frame {frameno}/{frames}.") images.append(img) @@ -934,9 +898,7 @@ def render_path( movie_transform=transform, ) ): - frameno = ( - requested_frames[i] if requested_frames is not None else (i + 1) - ) + frameno = requested_frames[i] if requested_frames is not None else (i + 1) fullname = f"{filename}-{frameno:{digits}}{ext}" try: @@ -955,9 +917,7 @@ def render_path( def main() -> int: - parser = argparse.ArgumentParser( - description="Konami AFP graphic file unpacker/repacker." - ) + parser = argparse.ArgumentParser(description="Konami AFP graphic file unpacker/repacker.") subparsers = parser.add_subparsers(help="Action to take", dest="action") extract_parser = subparsers.add_parser( @@ -1381,13 +1341,9 @@ def main() -> int: verbose=args.verbose, ) elif args.action == "update": - return update_txp2( - args.file, args.dir, pretend=args.pretend, verbose=args.verbose - ) + return update_txp2(args.file, args.dir, pretend=args.pretend, verbose=args.verbose) elif args.action == "print": - return print_txp2( - args.file, decompile_bytecode=args.decompile_bytecode, verbose=args.verbose - ) + return print_txp2(args.file, decompile_bytecode=args.decompile_bytecode, verbose=args.verbose) elif args.action == "parseafp": return parse_afp( args.afp, diff --git a/bemani/utils/api.py b/bemani/utils/api.py index 82f85a3..f2ccc67 100644 --- a/bemani/utils/api.py +++ b/bemani/utils/api.py @@ -22,9 +22,7 @@ def main() -> None: parser = argparse.ArgumentParser( description="An API services provider for eAmusement games, conforming to BEMAPI specs." ) - parser.add_argument( - "-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80 - ) + parser.add_argument("-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80) parser.add_argument( "-c", "--config", diff --git a/bemani/utils/assetparse.py b/bemani/utils/assetparse.py index 9f34a5e..841a8c5 100644 --- a/bemani/utils/assetparse.py +++ b/bemani/utils/assetparse.py @@ -29,9 +29,7 @@ class ImportJubeat: }: self.version = actual_version else: - raise Exception( - "Unsupported Jubeat version, expected one of the following: prop, qubell, clan, festo!" - ) + raise Exception("Unsupported Jubeat version, expected one of the following: prop, qubell, clan, festo!") self.config = config self.update = update @@ -46,12 +44,8 @@ class ImportJubeat: file_mapping: Dict[str, str] = {} for emblem in root.find("emblem_list"): - emblem.find("texname").text = emblem.find("texname").text.replace( - ".tex", ".png" - ) - file_mapping[ - emblem.find("texname").text - ] = f'{emblem.find("index").text}.png' + emblem.find("texname").text = emblem.find("texname").text.replace(".tex", ".png") + file_mapping[emblem.find("texname").text] = f'{emblem.find("index").text}.png' if not file_mapping: # This isn't an emblem XML! @@ -62,9 +56,7 @@ class ImportJubeat: raise Exception("Expect a valid directory for emblems in config file!") # First, make the root directory structure. - actual_output = os.path.join( - self.config.assets.jubeat.emblems, f"{self.version}" - ) + actual_output = os.path.join(self.config.assets.jubeat.emblems, f"{self.version}") os.makedirs(actual_output, exist_ok=True) for fileroot, _, files in os.walk(assets): @@ -92,9 +84,7 @@ class ImportJubeat: if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Import game assets from various game files" - ) + parser = argparse.ArgumentParser(description="Import game assets from various game files") parser.add_argument( "--series", action="store", @@ -155,9 +145,7 @@ if __name__ == "__main__": if args.xml: jubeat.import_assets(args.xml, args.assets) else: - raise Exception( - "No emblem-info.xml provided! Please provide a --xml option!" - ) + raise Exception("No emblem-info.xml provided! Please provide a --xml option!") else: raise Exception("Unsupported game series!") diff --git a/bemani/utils/bemanishark.py b/bemani/utils/bemanishark.py index 8d0b7ef..900d7bf 100644 --- a/bemani/utils/bemanishark.py +++ b/bemani/utils/bemanishark.py @@ -6,9 +6,7 @@ from bemani.protocol import EAmuseProtocol, EAmuseException from bemani.common import HTTP -def mainloop( - address: Optional[str] = None, port: int = 80, verbose: bool = False -) -> None: +def mainloop(address: Optional[str] = None, port: int = 80, verbose: bool = False) -> None: """ Main loop of BEMANIShark. Starts an instance of Sniffer and EAmuseProtocol and does a lazy job of banging them together with the above HTTP.parse. Will loop trying to decode @@ -46,9 +44,7 @@ def mainloop( if verbose: print(f"HTTP {inbound['method']} request for URI {inbound['uri']}") print(f"Compression is {inbound['headers'].get('x-compress', 'none')}") - print( - f"Encryption key is {inbound['headers'].get('x-eamuse-info', 'none')}" - ) + print(f"Encryption key is {inbound['headers'].get('x-eamuse-info', 'none')}") if in_req is None: print("Inbound request was not parseable") else: @@ -72,9 +68,7 @@ def mainloop( ) if verbose: print(f"Compression is {outbound['headers'].get('x-compress', 'none')}") - print( - f"Encryption key is {outbound['headers'].get('x-eamuse-info', 'none')}" - ) + print(f"Encryption key is {outbound['headers'].get('x-eamuse-info', 'none')}") if out_req is None: print("Outbound response was not parseable") else: @@ -85,9 +79,7 @@ def main() -> None: parser = argparse.ArgumentParser( description="A utility to sniff packets and decode them as eAmusement packets. Should probably be run as root." ) - parser.add_argument( - "-p", "--port", help="Port to sniff on. Defaults to 80", type=int, default=80 - ) + parser.add_argument("-p", "--port", help="Port to sniff on. Defaults to 80", type=int, default=80) parser.add_argument( "-a", "--address", @@ -95,9 +87,7 @@ def main() -> None: type=str, default=None, ) - parser.add_argument( - "-v", "--verbose", help="Show extra packet information", action="store_true" - ) + parser.add_argument("-v", "--verbose", help="Show extra packet information", action="store_true") args = parser.parse_args() mainloop(address=args.address, port=args.port, verbose=args.verbose) diff --git a/bemani/utils/binutils.py b/bemani/utils/binutils.py index 86680fd..c05c2e6 100644 --- a/bemani/utils/binutils.py +++ b/bemani/utils/binutils.py @@ -6,9 +6,7 @@ from bemani.protocol.lz77 import Lz77 def main() -> None: - parser = argparse.ArgumentParser( - description="A utility to convert binxml files to their XML representation." - ) + parser = argparse.ArgumentParser(description="A utility to convert binxml files to their XML representation.") parser.add_argument( "-i", "--infile", diff --git a/bemani/utils/cardconvert.py b/bemani/utils/cardconvert.py index 0a1ec51..229d648 100644 --- a/bemani/utils/cardconvert.py +++ b/bemani/utils/cardconvert.py @@ -4,9 +4,7 @@ from bemani.common import CardCipher, CardCipherException def main() -> None: - parser = argparse.ArgumentParser( - description="A utility to convert between card IDs and back-of-card characters." - ) + parser = argparse.ArgumentParser(description="A utility to convert between card IDs and back-of-card characters.") parser.add_argument( "number", help="card ID or back-of-card characters to convert.", diff --git a/bemani/utils/dbutils.py b/bemani/utils/dbutils.py index 66849d6..0bd4fe8 100644 --- a/bemani/utils/dbutils.py +++ b/bemani/utils/dbutils.py @@ -69,9 +69,7 @@ def remove_admin(config: Config, username: Optional[str]) -> None: def main() -> None: - parser = argparse.ArgumentParser( - description="A utility for working with databases created with this codebase." - ) + parser = argparse.ArgumentParser(description="A utility for working with databases created with this codebase.") parser.add_argument( "operation", help="Operation to perform, options include 'create', 'generate', 'upgrade', 'change-password', 'add-admin' and 'remove-admin'.", diff --git a/bemani/utils/frontend.py b/bemani/utils/frontend.py index fe4ef4f..5fd3a92 100644 --- a/bemani/utils/frontend.py +++ b/bemani/utils/frontend.py @@ -68,12 +68,8 @@ def instantiate_cache(app: Any) -> None: def main() -> None: - parser = argparse.ArgumentParser( - description="A front end services provider for eAmusement games." - ) - parser.add_argument( - "-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80 - ) + parser = argparse.ArgumentParser(description="A front end services provider for eAmusement games.") + parser.add_argument("-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80) parser.add_argument( "-c", "--config", diff --git a/bemani/utils/iidxutils.py b/bemani/utils/iidxutils.py index ae9a78c..f358f80 100644 --- a/bemani/utils/iidxutils.py +++ b/bemani/utils/iidxutils.py @@ -4,9 +4,7 @@ from bemani.format import IIDXMusicDB def main() -> None: - parser = argparse.ArgumentParser( - description="A utility to patch a IIDX music database." - ) + parser = argparse.ArgumentParser(description="A utility to patch a IIDX music database.") parser.add_argument( "infile", help="Music DB to work with.", @@ -32,9 +30,7 @@ def main() -> None: if args.hide_leggendarias: for song in db.songs: if song.title[-1:] == "†" or ( - song.difficulties[0] == 0 - and song.difficulties[1] == 0 - and song.difficulties[2] == 12 + song.difficulties[0] == 0 and song.difficulties[1] == 0 and song.difficulties[2] == 12 ): print(f"Patching '{song.title}' to only appear in leggendaria folder!") song.folder = 0x5C diff --git a/bemani/utils/jsx.py b/bemani/utils/jsx.py index b85679f..df4f7ea 100644 --- a/bemani/utils/jsx.py +++ b/bemani/utils/jsx.py @@ -52,9 +52,7 @@ def main() -> None: os.makedirs(os.path.dirname(outfile), exist_ok=True) with open(infile, "rb") as f: - jsx = transformer.transform_string( - polyfill_fragments(f.read().decode("utf-8")) - ).encode("utf-8") + jsx = transformer.transform_string(polyfill_fragments(f.read().decode("utf-8"))).encode("utf-8") print(f"Writing {outfile}...") with open(outfile, "wb") as f: diff --git a/bemani/utils/proxy.py b/bemani/utils/proxy.py index 17ea930..6f1504b 100644 --- a/bemani/utils/proxy.py +++ b/bemani/utils/proxy.py @@ -56,9 +56,7 @@ def modify_response(config: Dict[str, Any], resp_body: Node) -> Optional[Node]: url.netloc, f'{config["local_host"]}:{config["local_port"]}' ) else: - new_url = child.attribute("url").replace( - url.netloc, f'{config["local_host"]}' - ) + new_url = child.attribute("url").replace(url.netloc, f'{config["local_host"]}') child.set_attribute("url", new_url) return resp_body @@ -280,9 +278,7 @@ def load_config(filename: str) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="A utility to MITM non-SSL eAmusement connections." - ) + parser = argparse.ArgumentParser(description="A utility to MITM non-SSL eAmusement connections.") parser.add_argument( "-p", "--port", @@ -304,12 +300,8 @@ if __name__ == "__main__": type=str, default="127.0.0.1", ) - parser.add_argument( - "-q", "--remote-port", help="Port to connect to.", type=int, required=True - ) - parser.add_argument( - "-b", "--remote-address", help="Address to connect to.", type=str, required=True - ) + parser.add_argument("-q", "--remote-port", help="Port to connect to.", type=int, required=True) + parser.add_argument("-b", "--remote-address", help="Address to connect to.", type=str, required=True) parser.add_argument( "-c", "--config", @@ -324,9 +316,7 @@ if __name__ == "__main__": type=str, default="localhost", ) - parser.add_argument( - "-v", "--verbose", help="Display verbose packet info.", action="store_true" - ) + parser.add_argument("-v", "--verbose", help="Display verbose packet info.", action="store_true") parser.add_argument( "-t", "--timeout", diff --git a/bemani/utils/psmap.py b/bemani/utils/psmap.py index 13f9b93..1388028 100644 --- a/bemani/utils/psmap.py +++ b/bemani/utils/psmap.py @@ -9,9 +9,7 @@ from bemani.protocol import Node from bemani.utils.responsegen import generate_lines -def parse_psmap( - pe: PEFile, offset: str, rootname: str, *, verbose: bool = False -) -> Node: +def parse_psmap(pe: PEFile, offset: str, rootname: str, *, verbose: bool = False) -> Node: root = Node.void(rootname) base = int(offset, 16) @@ -42,20 +40,14 @@ def parse_psmap( chunk = pe.data[base : (base + 24)] base = base + 24 - (nodetype, mandatory, outoffset, width, nameptr, default) = struct.unpack( - " None: - parser = argparse.ArgumentParser( - description="A utility to extract psmap node lists and generate code." - ) + parser = argparse.ArgumentParser(description="A utility to extract psmap node lists and generate code.") parser.add_argument( "--file", help="DLL file to extract from.", diff --git a/bemani/utils/read.py b/bemani/utils/read.py index b912780..6ba1f1c 100644 --- a/bemani/utils/read.py +++ b/bemani/utils/read.py @@ -83,9 +83,7 @@ class ImportBase: self.__session.commit() self.__batch = False - def execute( - self, sql: str, params: Optional[Dict[str, Any]] = None - ) -> CursorResult: + def execute(self, sql: str, params: Optional[Dict[str, Any]] = None) -> CursorResult: if not self.__batch: raise Exception("Logic error, cannot execute outside of a batch!") @@ -119,15 +117,11 @@ class ImportBase: # Nothing in DB return 1 - def get_music_id_for_song( - self, songid: int, chart: int, version: Optional[int] = None - ) -> Optional[int]: + def get_music_id_for_song(self, songid: int, chart: int, version: Optional[int] = None) -> Optional[int]: if version is None: # Normal lookup if self.version is None: - raise Exception( - "Cannot get music ID for song when operating on all versions!" - ) + raise Exception("Cannot get music ID for song when operating on all versions!") version = self.version sql = "SELECT id FROM `music` WHERE songid = :songid AND chart = :chart AND game = :game AND version != :version" else: @@ -170,9 +164,7 @@ class ImportBase: if version is None: # Normal lookup if self.version is None: - raise Exception( - "Cannot get music ID for song when operating on all versions!" - ) + raise Exception("Cannot get music ID for song when operating on all versions!") version = self.version frags.append("version != :version") else: @@ -209,9 +201,7 @@ class ImportBase: ) -> None: version = version if version is not None else self.version if version is None: - raise Exception( - "Cannot get insert new song when operating on all versions!" - ) + raise Exception("Cannot get insert new song when operating on all versions!") if data is None: jsondata = "{}" else: @@ -238,9 +228,7 @@ class ImportBase: except IntegrityError: if self.update: print("Entry already existed, so updating information!") - self.update_metadata_for_song( - songid, chart, name, artist, genre, data, version - ) + self.update_metadata_for_song(songid, chart, name, artist, genre, data, version) else: print("Entry already existed, so skip creating a second one!") @@ -342,8 +330,7 @@ class ImportBase: jsondata = json.dumps(data) try: sql = ( - "INSERT INTO `catalog` (game, version, type, id, data) " - + "VALUES (:game, :version, :type, :id, :data)" + "INSERT INTO `catalog` (game, version, type, id, data) " + "VALUES (:game, :version, :type, :id, :data)" ) self.execute( sql, @@ -482,10 +469,8 @@ class ImportPopn(ImportBase): "26": VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES, "omni-24": VersionConstants.POPN_MUSIC_USANEKO + DBConstants.OMNIMIX_VERSION_BUMP, # Omnimix v2 only works for 24 - 26 - "omni-25": VersionConstants.POPN_MUSIC_PEACE - + DBConstants.OMNIMIX_VERSION_BUMP, - "omni-26": VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES - + DBConstants.OMNIMIX_VERSION_BUMP, + "omni-25": VersionConstants.POPN_MUSIC_PEACE + DBConstants.OMNIMIX_VERSION_BUMP, + "omni-26": VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES + DBConstants.OMNIMIX_VERSION_BUMP, }.get(version, -1) if actual_version == VersionConstants.POPN_MUSIC_TUNE_STREET: @@ -501,13 +486,9 @@ class ImportPopn(ImportBase): "Unsupported Pop'n Music version, expected one of the following: 19, 20, 21, 22, 23, 24, omni-24, 25, omni-25, 26, omni-26!" ) - super().__init__( - config, GameConstants.POPN_MUSIC, actual_version, no_combine, update - ) + super().__init__(config, GameConstants.POPN_MUSIC, actual_version, no_combine, update) - def scrape_xml( - self, xmlfile: Path, songs: List[Dict[str, Any]] = [] - ) -> List[Dict[str, Any]]: + def scrape_xml(self, xmlfile: Path, songs: List[Dict[str, Any]] = []) -> List[Dict[str, Any]]: with open(xmlfile, "rb") as xmlhandle: xmldata = xmlhandle.read().decode("shift_jisx0213") root = ET.fromstring(xmldata) @@ -529,9 +510,7 @@ class ImportPopn(ImportBase): chart_idx = diff_map.get(chart.attrib["idx"]) if chart.find("diff") is not None: difficulties[chart_idx] = int(chart.find("diff").text) - filenames[ - chart_idx - ] = f'{chart.find("folder").text}/{chart.find("filename").text}' + filenames[chart_idx] = f'{chart.find("folder").text}/{chart.find("filename").text}' songinfo: Dict # Check if song metadata is in this entry if music_entry.find("fw_title") is not None: @@ -575,39 +554,25 @@ class ImportPopn(ImportBase): for song in songs: if song["id"] == int(music_entry.attrib["id"]): if difficulties is not None: - for diff, i in zip( - ["easy", "normal", "hyper", "ex"], range(4) - ): + for diff, i in zip(["easy", "normal", "hyper", "ex"], range(4)): song["difficulty"]["standard"][diff] = ( - difficulties[i] - if difficulties[i] - else song["difficulty"]["standard"][diff] + difficulties[i] if difficulties[i] else song["difficulty"]["standard"][diff] ) song["file"]["standard"][diff] = ( - filenames[i] - if filenames[i] - else song["file"]["standard"][diff] + filenames[i] if filenames[i] else song["file"]["standard"][diff] ) song["difficulty"]["battle"]["normal"] = ( - difficulties[4] - if difficulties[4] - else song["difficulty"]["battle"]["normal"] + difficulties[4] if difficulties[4] else song["difficulty"]["battle"]["normal"] ) song["difficulty"]["battle"]["hyper"] = ( - difficulties[5] - if difficulties[5] - else song["difficulty"]["battle"]["hyper"] + difficulties[5] if difficulties[5] else song["difficulty"]["battle"]["hyper"] ) song["file"]["battle"]["normal"] = ( - filenames[4] - if filenames[4] - else song["file"]["battle"]["normal"] + filenames[4] if filenames[4] else song["file"]["battle"]["normal"] ) song["file"]["battle"]["hyper"] = ( - filenames[5] - if filenames[5] - else song["file"]["battle"]["hyper"] + filenames[5] if filenames[5] else song["file"]["battle"]["hyper"] ) else: song["genre"] = music_entry.find("fw_genre").text @@ -1703,13 +1668,8 @@ class ImportPopn(ImportBase): available_charts=available_charts, ) ) - elif ( - self.version == VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES - or self.version - == ( - VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES - + DBConstants.OMNIMIX_VERSION_BUMP - ) + elif self.version == VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES or self.version == ( + VersionConstants.POPN_MUSIC_KAIMEI_RIDDLES + DBConstants.OMNIMIX_VERSION_BUMP ): # Decoding function for chart masks def available_charts( @@ -1965,11 +1925,7 @@ class ImportPopn(ImportBase): def file_handle(config: PopnScrapeConfiguration, offset: int) -> str: chunk = file_chunk(config, offset) - return ( - read_string(chunk[config.file_folder_offset]) - + "/" - + read_string(chunk[config.file_name_offset]) - ) + return read_string(chunk[config.file_folder_offset]) + "/" + read_string(chunk[config.file_name_offset]) for config in configurations: try: @@ -1980,9 +1936,7 @@ class ImportPopn(ImportBase): chunkoffset = config.offset + (config.step * songid) chunkdata = data[chunkoffset : (chunkoffset + config.step)] unpacked = struct.unpack(config.packedfmt, chunkdata) - valid_charts = config.available_charts( - unpacked[config.charts_offset] - ) + valid_charts = config.available_charts(unpacked[config.charts_offset]) songinfo = { "id": songid, "title": read_string(unpacked[config.title_offset]), @@ -1995,68 +1949,40 @@ class ImportPopn(ImportBase): "artist_en": read_string(unpacked[config.english_artist_offset]) if config.english_artist_offset is not None else "", - "long_genre": read_string( - unpacked[config.extended_genre_offset] - ) + "long_genre": read_string(unpacked[config.extended_genre_offset]) if config.extended_genre_offset is not None else "", "folder": unpacked[config.folder_offset], "difficulty": { "standard": { - "easy": unpacked[config.easy_offset] - if valid_charts[0] - else 0, - "normal": unpacked[config.normal_offset] - if valid_charts[1] - else 0, - "hyper": unpacked[config.hyper_offset] - if valid_charts[2] - else 0, - "ex": unpacked[config.ex_offset] - if valid_charts[3] - else 0, + "easy": unpacked[config.easy_offset] if valid_charts[0] else 0, + "normal": unpacked[config.normal_offset] if valid_charts[1] else 0, + "hyper": unpacked[config.hyper_offset] if valid_charts[2] else 0, + "ex": unpacked[config.ex_offset] if valid_charts[3] else 0, }, "battle": { - "normal": unpacked[config.battle_normal_offset] - if valid_charts[4] - else 0, - "hyper": unpacked[config.battle_hyper_offset] - if valid_charts[5] - else 0, + "normal": unpacked[config.battle_normal_offset] if valid_charts[4] else 0, + "hyper": unpacked[config.battle_hyper_offset] if valid_charts[5] else 0, }, }, "file": { "standard": { - "easy": file_handle( - config, unpacked[config.easy_file_offset] - ) + "easy": file_handle(config, unpacked[config.easy_file_offset]) if valid_charts[0] else "", - "normal": file_handle( - config, unpacked[config.normal_file_offset] - ) + "normal": file_handle(config, unpacked[config.normal_file_offset]) if valid_charts[1] else "", - "hyper": file_handle( - config, unpacked[config.hyper_file_offset] - ) + "hyper": file_handle(config, unpacked[config.hyper_file_offset]) if valid_charts[2] else "", - "ex": file_handle( - config, unpacked[config.ex_file_offset] - ) - if valid_charts[3] - else "", + "ex": file_handle(config, unpacked[config.ex_file_offset]) if valid_charts[3] else "", }, "battle": { - "normal": file_handle( - config, unpacked[config.battle_normal_file_offset] - ) + "normal": file_handle(config, unpacked[config.battle_normal_file_offset]) if valid_charts[4] else "", - "hyper": file_handle( - config, unpacked[config.battle_hyper_file_offset] - ) + "hyper": file_handle(config, unpacked[config.battle_hyper_file_offset]) if valid_charts[5] else "", }, @@ -2072,11 +1998,7 @@ class ImportPopn(ImportBase): # This is a removed song continue - if ( - songinfo["title"] == "DUMMY" - and songinfo["artist"] == "DUMMY" - and songinfo["genre"] == "DUMMY" - ): + if songinfo["title"] == "DUMMY" and songinfo["artist"] == "DUMMY" and songinfo["genre"] == "DUMMY": # This is a song the intern left in continue @@ -2182,9 +2104,7 @@ class ImportPopn(ImportBase): }, }, } - lut[song.id]["difficulty"]["standard"][ - chart_map[song.chart] - ] = song.data.get_int("difficulty") + lut[song.id]["difficulty"]["standard"][chart_map[song.chart]] = song.data.get_int("difficulty") # Return the reassembled data return [val for _, val in lut.items()] @@ -2205,9 +2125,7 @@ class ImportPopn(ImportBase): # Now, look up metadata title = song["title_en"] if len(song["title_en"]) > 0 else song["title"] - artist = ( - song["artist_en"] if len(song["artist_en"]) > 0 else song["artist"] - ) + artist = song["artist_en"] if len(song["artist_en"]) > 0 else song["artist"] genre = song["genre"] # We only care about easy/normal/hyper/ex, so only provide mappings there @@ -2218,14 +2136,10 @@ class ImportPopn(ImportBase): if self.no_combine or old_id is None: # Insert original - print( - f"New entry for {artist} {title} ({song['id']} chart {chart})" - ) + print(f"New entry for {artist} {title} ({song['id']} chart {chart})") next_id = self.get_next_music_id() else: - print( - f"Reused entry for {artist} {title} ({song['id']} chart {chart})" - ) + print(f"Reused entry for {artist} {title} ({song['id']} chart {chart})") next_id = old_id self.insert_music_id_for_song( next_id, @@ -2295,9 +2209,7 @@ class ImportJubeat(ImportBase): "Unsupported Jubeat version, expected one of the following: saucer, saucer-fulfill, prop, omni-prop, qubell, omni-qubell, clan, omni-clan, festo, omni-festo!" ) - super().__init__( - config, GameConstants.JUBEAT, actual_version, no_combine, update - ) + super().__init__(config, GameConstants.JUBEAT, actual_version, no_combine, update) def scrape(self, xmlfile: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if self.version is None: @@ -2354,9 +2266,7 @@ class ImportJubeat(ImportBase): float(music_entry.find("level_ext").text), ] genre = "other" - if ( - music_entry.find("genre") is not None - ): # Qubell extend music_info doesn't have this field + if music_entry.find("genre") is not None: # Qubell extend music_info doesn't have this field for possible_genre in music_entry.find("genre"): if int(possible_genre.text) != 0: genre = str(possible_genre.tag) @@ -2408,9 +2318,7 @@ class ImportJubeat(ImportBase): return songs, emblems - def lookup( - self, server: str, token: str - ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + def lookup(self, server: str, token: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if self.version is None: raise CLIException("Can't look up Jubeat database for 'all' version!") @@ -2445,9 +2353,7 @@ class ImportJubeat(ImportBase): "extreme": 0.0, }, } - lut[song.id]["difficulty"][chart_map[song.chart]] = song.data.get_float( - "difficulty" - ) + lut[song.id]["difficulty"][chart_map[song.chart]] = song.data.get_float("difficulty") # Reassemble the data reassembled_songs = [val for _, val in lut.items()] @@ -2597,9 +2503,7 @@ class ImportJubeat(ImportBase): def import_metadata(self, tsvfile: str) -> None: if self.version is not None: - raise CLIException( - "Unsupported Jubeat version, expected one of the following: all" - ) + raise CLIException("Unsupported Jubeat version, expected one of the following: all") with open(tsvfile, newline="") as tsvhandle: jubeatreader = csv.reader(tsvhandle, delimiter="\t", quotechar='"') @@ -2717,17 +2621,13 @@ class ImportIIDX(ImportBase): songid, extension = os.path.splitext(filename) if extension == ".1" or extension == ".ifs": try: - files[int(songid)] = os.path.join( - directory, os.path.join(dirpath, filename) - ) + files[int(songid)] = os.path.join(directory, os.path.join(dirpath, filename)) except ValueError: # Invalid file pass for dirname in dirnames: - files.update( - self.__gather_sound_files(os.path.join(directory, dirname)) - ) + files.update(self.__gather_sound_files(os.path.join(directory, dirname))) return files @@ -2847,9 +2747,7 @@ class ImportIIDX(ImportBase): return 1 return chart - def scrape( - self, binfile: str, assets_dir: Optional[str] - ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + def scrape(self, binfile: str, assets_dir: Optional[str]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if self.version is None: raise CLIException("Can't import IIDX database for 'all' version!") @@ -2909,13 +2807,9 @@ class ImportIIDX(ImportBase): bpm = (bpm_min, bpm_max) notecounts = iidxchart.notecounts else: - print( - f"Could not find chart information for song {song.id}!" - ) + print(f"Could not find chart information for song {song.id}!") else: - print( - f"No chart information because chart for song {song.id} is missing!" - ) + print(f"No chart information because chart for song {song.id} is missing!") songs.append( { "id": song.id, @@ -3029,8 +2923,7 @@ class ImportIIDX(ImportBase): qp_body_length=211, filename_offset=0, qpro_id_offset=1, - packedfmt="I" - "I", # filename # string containing id and name of the part + packedfmt="I" "I", # filename # string containing id and name of the part ) ) if self.version == VersionConstants.IIDX_SINOBUZ: @@ -3051,8 +2944,7 @@ class ImportIIDX(ImportBase): qp_body_length=256, filename_offset=0, qpro_id_offset=1, - packedfmt="I" - "I", # filename # string containing id and name of the part + packedfmt="I" "I", # filename # string containing id and name of the part ) ) if self.version == VersionConstants.IIDX_CANNON_BALLERS: @@ -3073,8 +2965,7 @@ class ImportIIDX(ImportBase): qp_body_length=282, filename_offset=0, qpro_id_offset=1, - packedfmt="Q" - "Q", # filename # string containing id and name of the part + packedfmt="Q" "Q", # filename # string containing id and name of the part ) ) if self.version == VersionConstants.IIDX_ROOTAGE: @@ -3095,8 +2986,7 @@ class ImportIIDX(ImportBase): qp_body_length=304, filename_offset=0, qpro_id_offset=1, - packedfmt="Q" - "Q", # filename # string containing id and name of the part + packedfmt="Q" "Q", # filename # string containing id and name of the part ) ) @@ -3124,15 +3014,9 @@ class ImportIIDX(ImportBase): chunkoffset = offset + (config.stride * qpro_id) chunkdata = binarydata[chunkoffset : (chunkoffset + config.stride)] unpacked = struct.unpack(config.packedfmt, chunkdata) - filename = read_string(unpacked[config.filename_offset]).replace( - "qp_", "" - ) + filename = read_string(unpacked[config.filename_offset]).replace("qp_", "") remove = f"_{qp_type}.ifs" - filename = ( - filename.replace(remove, "") - .replace("_head1.ifs", "") - .replace("_head2.ifs", "") - ) + filename = filename.replace(remove, "").replace("_head1.ifs", "").replace("_head2.ifs", "") if config.qpro_id_offset is None: name = filename # qpro names are not stored in these games so use the identifier instead else: @@ -3197,18 +3081,14 @@ class ImportIIDX(ImportBase): return [], qpros except (UnicodeError, InvalidOffsetException): # These offsets are possibly not correct, so try the next configuration. - print( - "Failed to parse game DB using current inferred data version!" - ) + print("Failed to parse game DB using current inferred data version!") pass raise CLIException( f"Could not determine correct binary parser configuration for IIDX version {self.version}" ) - def lookup( - self, server: str, token: str - ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + def lookup(self, server: str, token: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if self.version is None: raise CLIException("Can't look up IIDX database for 'all' version!") @@ -3259,12 +3139,8 @@ class ImportIIDX(ImportBase): }, } if song.chart in chart_map: - lut[song.id]["difficulty"][chart_map[song.chart]] = song.data.get_int( - "difficulty" - ) - lut[song.id]["notecount"][chart_map[song.chart]] = song.data.get_int( - "notecount" - ) + lut[song.id]["difficulty"][chart_map[song.chart]] = song.data.get_int("difficulty") + lut[song.id]["notecount"][chart_map[song.chart]] = song.data.get_int("notecount") # Return the reassembled data qpros: List[Dict[str, Any]] = [] @@ -3354,9 +3230,7 @@ class ImportIIDX(ImportBase): def import_metadata(self, tsvfile: str) -> None: if self.version is not None: - raise CLIException( - "Unsupported IIDX version, expected one of the following: all" - ) + raise CLIException("Unsupported IIDX version, expected one of the following: all") with open(tsvfile, newline="") as tsvhandle: iidxreader = csv.reader(tsvhandle, delimiter="\t", quotechar='"') @@ -3459,9 +3333,7 @@ class ImportDDR(ImportBase): }[version] self.charts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] else: - raise CLIException( - "Unsupported DDR version, expected one of the following: 12, 13, 14, 15, 16" - ) + raise CLIException("Unsupported DDR version, expected one of the following: 12, 13, 14, 15, 16") super().__init__(config, GameConstants.DDR, actual_version, no_combine, update) @@ -3706,89 +3578,39 @@ class ImportDDR(ImportBase): "groove_gauge": { "single": { "beginner": { - "voltage": unpacked[ - config.groove_single_beginner + config.voltage - ], - "stream": unpacked[ - config.groove_single_beginner + config.stream - ], - "air": unpacked[ - config.groove_single_beginner + config.air - ], - "chaos": unpacked[ - config.groove_single_beginner + config.chaos - ], - "freeze": unpacked[ - config.groove_single_beginner + config.freeze - ], + "voltage": unpacked[config.groove_single_beginner + config.voltage], + "stream": unpacked[config.groove_single_beginner + config.stream], + "air": unpacked[config.groove_single_beginner + config.air], + "chaos": unpacked[config.groove_single_beginner + config.chaos], + "freeze": unpacked[config.groove_single_beginner + config.freeze], }, "basic": { - "voltage": unpacked[ - config.groove_single_basic + config.voltage - ], - "stream": unpacked[ - config.groove_single_basic + config.stream - ], - "air": unpacked[ - config.groove_single_basic + config.air - ], - "chaos": unpacked[ - config.groove_single_basic + config.chaos - ], - "freeze": unpacked[ - config.groove_single_basic + config.freeze - ], + "voltage": unpacked[config.groove_single_basic + config.voltage], + "stream": unpacked[config.groove_single_basic + config.stream], + "air": unpacked[config.groove_single_basic + config.air], + "chaos": unpacked[config.groove_single_basic + config.chaos], + "freeze": unpacked[config.groove_single_basic + config.freeze], }, "difficult": { - "voltage": unpacked[ - config.groove_single_difficult + config.voltage - ], - "stream": unpacked[ - config.groove_single_difficult + config.stream - ], - "air": unpacked[ - config.groove_single_difficult + config.air - ], - "chaos": unpacked[ - config.groove_single_difficult + config.chaos - ], - "freeze": unpacked[ - config.groove_single_difficult + config.freeze - ], + "voltage": unpacked[config.groove_single_difficult + config.voltage], + "stream": unpacked[config.groove_single_difficult + config.stream], + "air": unpacked[config.groove_single_difficult + config.air], + "chaos": unpacked[config.groove_single_difficult + config.chaos], + "freeze": unpacked[config.groove_single_difficult + config.freeze], }, "expert": { - "voltage": unpacked[ - config.groove_single_expert + config.voltage - ], - "stream": unpacked[ - config.groove_single_expert + config.stream - ], - "air": unpacked[ - config.groove_single_expert + config.air - ], - "chaos": unpacked[ - config.groove_single_expert + config.chaos - ], - "freeze": unpacked[ - config.groove_single_expert + config.freeze - ], + "voltage": unpacked[config.groove_single_expert + config.voltage], + "stream": unpacked[config.groove_single_expert + config.stream], + "air": unpacked[config.groove_single_expert + config.air], + "chaos": unpacked[config.groove_single_expert + config.chaos], + "freeze": unpacked[config.groove_single_expert + config.freeze], }, "challenge": { - "voltage": unpacked[ - config.groove_single_challenge + config.voltage - ], - "stream": unpacked[ - config.groove_single_challenge + config.stream - ], - "air": unpacked[ - config.groove_single_challenge + config.air - ], - "chaos": unpacked[ - config.groove_single_challenge + config.chaos - ], - "freeze": unpacked[ - config.groove_single_challenge + config.freeze - ], + "voltage": unpacked[config.groove_single_challenge + config.voltage], + "stream": unpacked[config.groove_single_challenge + config.stream], + "air": unpacked[config.groove_single_challenge + config.air], + "chaos": unpacked[config.groove_single_challenge + config.chaos], + "freeze": unpacked[config.groove_single_challenge + config.freeze], }, }, "double": { @@ -3800,72 +3622,32 @@ class ImportDDR(ImportBase): "freeze": 0, }, "basic": { - "voltage": unpacked[ - config.groove_double_basic + config.voltage - ], - "stream": unpacked[ - config.groove_double_basic + config.stream - ], - "air": unpacked[ - config.groove_double_basic + config.air - ], - "chaos": unpacked[ - config.groove_double_basic + config.chaos - ], - "freeze": unpacked[ - config.groove_double_basic + config.freeze - ], + "voltage": unpacked[config.groove_double_basic + config.voltage], + "stream": unpacked[config.groove_double_basic + config.stream], + "air": unpacked[config.groove_double_basic + config.air], + "chaos": unpacked[config.groove_double_basic + config.chaos], + "freeze": unpacked[config.groove_double_basic + config.freeze], }, "difficult": { - "voltage": unpacked[ - config.groove_double_difficult + config.voltage - ], - "stream": unpacked[ - config.groove_double_difficult + config.stream - ], - "air": unpacked[ - config.groove_double_difficult + config.air - ], - "chaos": unpacked[ - config.groove_double_difficult + config.chaos - ], - "freeze": unpacked[ - config.groove_double_difficult + config.freeze - ], + "voltage": unpacked[config.groove_double_difficult + config.voltage], + "stream": unpacked[config.groove_double_difficult + config.stream], + "air": unpacked[config.groove_double_difficult + config.air], + "chaos": unpacked[config.groove_double_difficult + config.chaos], + "freeze": unpacked[config.groove_double_difficult + config.freeze], }, "expert": { - "voltage": unpacked[ - config.groove_double_expert + config.voltage - ], - "stream": unpacked[ - config.groove_double_expert + config.stream - ], - "air": unpacked[ - config.groove_double_expert + config.air - ], - "chaos": unpacked[ - config.groove_double_expert + config.chaos - ], - "freeze": unpacked[ - config.groove_double_expert + config.freeze - ], + "voltage": unpacked[config.groove_double_expert + config.voltage], + "stream": unpacked[config.groove_double_expert + config.stream], + "air": unpacked[config.groove_double_expert + config.air], + "chaos": unpacked[config.groove_double_expert + config.chaos], + "freeze": unpacked[config.groove_double_expert + config.freeze], }, "challenge": { - "voltage": unpacked[ - config.groove_double_challenge + config.voltage - ], - "stream": unpacked[ - config.groove_double_challenge + config.stream - ], - "air": unpacked[ - config.groove_double_challenge + config.air - ], - "chaos": unpacked[ - config.groove_double_challenge + config.chaos - ], - "freeze": unpacked[ - config.groove_double_challenge + config.freeze - ], + "voltage": unpacked[config.groove_double_challenge + config.voltage], + "stream": unpacked[config.groove_double_challenge + config.stream], + "air": unpacked[config.groove_double_challenge + config.air], + "chaos": unpacked[config.groove_double_challenge + config.chaos], + "freeze": unpacked[config.groove_double_challenge + config.freeze], }, }, }, @@ -3884,9 +3666,7 @@ class ImportDDR(ImportBase): print("Failed to parse game DB using current inferred data version!") pass - raise CLIException( - f"Could not determine correct binary parser configuration for DDR version {self.version}" - ) + raise CLIException(f"Could not determine correct binary parser configuration for DDR version {self.version}") def hydrate(self, songs: List[Dict[str, Any]], infile: str) -> List[Dict[str, Any]]: tree = ET.parse(infile) @@ -4157,21 +3937,11 @@ class ImportDDR(ImportBase): } style, chart = chart_map[song.chart] lut[song.id]["difficulty"][style][chart] = song.data.get_int("difficulty") - lut[song.id]["groove_gauge"][style][chart]["air"] = song.data.get_dict( - "groove" - ).get_int("air") - lut[song.id]["groove_gauge"][style][chart]["chaos"] = song.data.get_dict( - "groove" - ).get_int("chaos") - lut[song.id]["groove_gauge"][style][chart]["freeze"] = song.data.get_dict( - "groove" - ).get_int("freeze") - lut[song.id]["groove_gauge"][style][chart]["stream"] = song.data.get_dict( - "groove" - ).get_int("stream") - lut[song.id]["groove_gauge"][style][chart]["voltage"] = song.data.get_dict( - "groove" - ).get_int("voltage") + lut[song.id]["groove_gauge"][style][chart]["air"] = song.data.get_dict("groove").get_int("air") + lut[song.id]["groove_gauge"][style][chart]["chaos"] = song.data.get_dict("groove").get_int("chaos") + lut[song.id]["groove_gauge"][style][chart]["freeze"] = song.data.get_dict("groove").get_int("freeze") + lut[song.id]["groove_gauge"][style][chart]["stream"] = song.data.get_dict("groove").get_int("stream") + lut[song.id]["groove_gauge"][style][chart]["voltage"] = song.data.get_dict("groove").get_int("voltage") # Return the reassembled data return [val for _, val in lut.items()] @@ -4206,14 +3976,10 @@ class ImportDDR(ImportBase): old_id = self.get_music_id_for_song(song["edit_id"], chart, version=0) if self.no_combine or old_id is None: # Insert original - print( - f"New entry for {song['title']} {song['artist']} ({song['id']} chart {chart})" - ) + print(f"New entry for {song['title']} {song['artist']} ({song['id']} chart {chart})") next_id = self.get_next_music_id() else: - print( - f"Reused entry for {song['title']} {song['artist']} ({song['id']} chart {chart})" - ) + print(f"Reused entry for {song['title']} {song['artist']} ({song['id']} chart {chart})") next_id = old_id # Add the virtual entry we talked about above, so we can link this song in the future. self.insert_music_id_for_song( @@ -4277,9 +4043,7 @@ class ImportSDVX(ImportBase): elif actual_version == VersionConstants.SDVX_HEAVENLY_HAVEN: self.charts = [0, 1, 2, 3, 4] else: - raise CLIException( - "Unsupported SDVX version, expected one of the following: 1, 2, 3, 4!" - ) + raise CLIException("Unsupported SDVX version, expected one of the following: 1, 2, 3, 4!") super().__init__(config, GameConstants.SDVX, actual_version, no_combine, update) @@ -4370,9 +4134,7 @@ class ImportSDVX(ImportBase): except (TypeError, ValueError): pass else: - raise CLIException( - f"Cannot import appeal cards for SDVX version {self.version}" - ) + raise CLIException(f"Cannot import appeal cards for SDVX version {self.version}") self.start_batch() for appealid in appealids: @@ -4420,12 +4182,7 @@ class ImportSDVX(ImportBase): int(info.text), ] # Make sure we got everything - if ( - title is None - or artist is None - or bpm_min is None - or bpm_max is None - ): + if title is None or artist is None or bpm_min is None or bpm_max is None: raise Exception(f"Couldn't parse info for song {songid}") # Grab valid difficulties @@ -4527,9 +4284,7 @@ class ImportSDVX(ImportBase): "bpm_min": bpm_min, "bpm_max": bpm_max, } - self.insert_music_id_for_song( - next_id, songid, chart, title, artist, None, data - ) + self.insert_music_id_for_song(next_id, songid, chart, title, artist, None, data) self.finish_batch() appealids: List[int] = [] @@ -4590,9 +4345,7 @@ class ImportSDVX(ImportBase): "bpm_min": song.data.get_int("bpm_min"), "bpm_max": song.data.get_int("bpm_max"), } - self.insert_music_id_for_song( - next_id, song.id, song.chart, song.name, song.artist, None, data - ) + self.insert_music_id_for_song(next_id, song.id, song.chart, song.name, song.artist, None, data) self.finish_batch() # Now, attempt to insert any catalog items we got for this version. @@ -4607,9 +4360,7 @@ class ImportSDVX(ImportBase): {}, ) elif item.type == "song_unlock": - print( - f"New catalog entry for {item.data.get_int('musicid')} chart {item.data.get_int('chart')}" - ) + print(f"New catalog entry for {item.data.get_int('musicid')} chart {item.data.get_int('chart')}") self.insert_catalog_entry( "song_unlock", item.id, @@ -4634,8 +4385,7 @@ class ImportMuseca(ImportBase): actual_version = { "1": VersionConstants.MUSECA, "1+1/2": VersionConstants.MUSECA_1_PLUS, - "plus": VersionConstants.MUSECA_1_PLUS - + DBConstants.OMNIMIX_VERSION_BUMP, + "plus": VersionConstants.MUSECA_1_PLUS + DBConstants.OMNIMIX_VERSION_BUMP, }.get(version, -1) if actual_version in [ VersionConstants.MUSECA, @@ -4644,13 +4394,9 @@ class ImportMuseca(ImportBase): ]: self.charts = [0, 1, 2, 3] else: - raise CLIException( - "Unsupported Museca version, expected one of the following: 1, 1+1/2, plus!" - ) + raise CLIException("Unsupported Museca version, expected one of the following: 1, 1+1/2, plus!") - super().__init__( - config, GameConstants.MUSECA, actual_version, no_combine, update - ) + super().__init__(config, GameConstants.MUSECA, actual_version, no_combine, update) def import_music_db(self, xmlfile: str) -> None: with open(xmlfile, "rb") as fp: @@ -4710,9 +4456,7 @@ class ImportMuseca(ImportBase): "bpm_min": bpm_min, "bpm_max": bpm_max, } - self.insert_music_id_for_song( - next_id, songid, chart, title, artist, None, data - ) + self.insert_music_id_for_song(next_id, songid, chart, title, artist, None, data) self.finish_batch() def import_from_server(self, server: str, token: str) -> None: @@ -4758,9 +4502,7 @@ class ImportMuseca(ImportBase): "bpm_min": song.data.get_int("bpm_min"), "bpm_max": song.data.get_int("bpm_max"), } - self.insert_music_id_for_song( - next_id, song.id, song.chart, song.name, song.artist, None, data - ) + self.insert_music_id_for_song(next_id, song.id, song.chart, song.name, song.artist, None, data) self.finish_batch() @@ -4817,13 +4559,9 @@ class ImportReflecBeat(ImportBase): }[version] self.charts = [0, 1, 2, 3] else: - raise CLIException( - "Unsupported ReflecBeat version, expected one of the following: 1, 2, 3, 4, 5, 6" - ) + raise CLIException("Unsupported ReflecBeat version, expected one of the following: 1, 2, 3, 4, 5, 6") - super().__init__( - config, GameConstants.REFLEC_BEAT, actual_version, no_combine, update - ) + super().__init__(config, GameConstants.REFLEC_BEAT, actual_version, no_combine, update) def scrape(self, infile: str) -> List[Dict[str, Any]]: with open(infile, mode="rb") as myfile: @@ -4980,39 +4718,21 @@ class ImportReflecBeat(ImportBase): end = start + config.stride songdata = data[start:end] - title = convert_string( - songdata[ - config.song_offset : ( - config.song_offset + config.song_length - ) - ] - ) + title = convert_string(songdata[config.song_offset : (config.song_offset + config.song_length)]) if config.artist_offset is None: artist = "" else: artist = convert_string( - songdata[ - config.artist_offset : ( - config.artist_offset + config.artist_length - ) - ] + songdata[config.artist_offset : (config.artist_offset + config.artist_length)] ) if title == "" and artist == "": continue songid = struct.unpack(" List[Dict[str, Any]]: with open(infile, mode="rb") as myfile: @@ -5179,11 +4893,7 @@ class ImportDanceEvolution(ImportBase): length = 0 while data[lut_offset + length] != 0: length += 1 - return ( - data[lut_offset : (lut_offset + length)] - .decode("utf-8") - .replace("\n", " ") - ) + return data[lut_offset : (lut_offset + length)].decode("utf-8").replace("\n", " ") def get_int(offset: int) -> int: return struct.unpack(">I", data[(offset) : (offset + 4)])[0] @@ -5259,9 +4969,7 @@ class ImportDanceEvolution(ImportBase): "bpm_min": song["bpm_min"], "bpm_max": song["bpm_max"], } - self.insert_music_id_for_song( - next_id, song["id"], 0, song["title"], song["artist"], None, data - ) + self.insert_music_id_for_song(next_id, song["id"], 0, song["title"], song["artist"], None, data) self.finish_batch() @@ -5359,12 +5067,8 @@ def main() -> None: args = parser.parse_args() if (args.token and not args.server) or (args.server and not args.token): raise CLIException("Must specify both --server and --token together!") - if (args.csv or args.tsv or args.xml or args.bin or args.assets) and ( - args.server or args.token - ): - raise CLIException( - "Cannot specify both a remote server and a local file to read from!" - ) + if (args.csv or args.tsv or args.xml or args.bin or args.assets) and (args.server or args.token): + raise CLIException("Cannot specify both a remote server and a local file to read from!") # Load the config so we can talk to the server config = Config() @@ -5513,9 +5217,7 @@ def main() -> None: reflec.close() elif series == GameConstants.DANCE_EVOLUTION: - danevo = ImportDanceEvolution( - config, args.version, args.no_combine, args.update - ) + danevo = ImportDanceEvolution(config, args.version, args.no_combine, args.update) if args.server and args.token: songs = danevo.lookup(args.server, args.token) elif args.bin is not None: diff --git a/bemani/utils/replay.py b/bemani/utils/replay.py index a79f680..1dfb566 100644 --- a/bemani/utils/replay.py +++ b/bemani/utils/replay.py @@ -98,9 +98,7 @@ class Protocol: def main() -> None: - parser = argparse.ArgumentParser( - description="A utility to replay a packet from a log or binary dump." - ) + parser = argparse.ArgumentParser(description="A utility to replay a packet from a log or binary dump.") parser.add_argument( "-i", "--infile", @@ -116,9 +114,7 @@ def main() -> None: type=str, default="utf-8", ) - parser.add_argument( - "-p", "--port", help="Port to talk to. Defaults to 80", type=int, default=80 - ) + parser.add_argument("-p", "--port", help="Port to talk to. Defaults to 80", type=int, default=80) parser.add_argument( "-a", "--address", diff --git a/bemani/utils/responsegen.py b/bemani/utils/responsegen.py index acfc268..3108351 100644 --- a/bemani/utils/responsegen.py +++ b/bemani/utils/responsegen.py @@ -40,9 +40,7 @@ def generate_node_create(node: Node) -> str: if dtype == "str": value = f", '{node.value}'" elif dtype == "ip4": - value = ( - f", '{node.value[0]}.{node.value[1]}.{node.value[2]}.{node.value[3]}'" - ) + value = f", '{node.value[0]}.{node.value[1]}.{node.value[2]}.{node.value[3]}'" else: value = f", {node.value}" else: @@ -51,9 +49,7 @@ def generate_node_create(node: Node) -> str: return f"Node.{method}('{node.name}'{value})" -def generate_node_link( - node_name: str, used_names: Dict[str, Node], parent: Node -) -> str: +def generate_node_link(node_name: str, used_names: Dict[str, Node], parent: Node) -> str: # Find the node that parents this, link to it found_parent = None for parent_name in used_names: @@ -67,9 +63,7 @@ def generate_node_link( return f"{found_parent}.add_child({node_name})" -def generate_lines( - node: Node, used_names: Dict[str, Node], parent: Optional[Node] = None -) -> List[str]: +def generate_lines(node: Node, used_names: Dict[str, Node], parent: Optional[Node] = None) -> List[str]: # First, generate node itself create = generate_node_create(node) if not node.children and not node.attributes and parent: diff --git a/bemani/utils/sampleclient.py b/bemani/utils/sampleclient.py index f253c7e..c5ea21f 100644 --- a/bemani/utils/sampleclient.py +++ b/bemani/utils/sampleclient.py @@ -13,9 +13,7 @@ class APIClient: self.base_uri = base_uri self.token = token - def exchange_data( - self, request_uri: str, request_args: Dict[str, Any] - ) -> Dict[str, Any]: + def exchange_data(self, request_uri: str, request_args: Dict[str, Any]) -> Dict[str, Any]: if self.base_uri[-1:] != "/": uri = "{}/{}".format(self.base_uri, request_uri) else: @@ -36,11 +34,7 @@ class APIClient: ) if r.headers["content-type"] != "application/json; charset=utf-8": - raise Exception( - "API returned invalid content type '{}'!".format( - r.headers["content-type"] - ) - ) + raise Exception("API returned invalid content type '{}'!".format(r.headers["content-type"])) jsondata = r.json() @@ -59,27 +53,15 @@ class APIClient: raise Exception("The API token used is not authorized against the server!") if r.status_code == 404: raise Exception( - "The server does not support this game/version or request object and returned '{}'".format( - error - ) + "The server does not support this game/version or request object and returned '{}'".format(error) ) if r.status_code == 405: - raise Exception( - "The server did not recognize the request and returned '{}'".format( - error - ) - ) + raise Exception("The server did not recognize the request and returned '{}'".format(error)) if r.status_code == 500: - raise Exception( - "The server had an error processing the request and returned '{}'".format( - error - ) - ) + raise Exception("The server had an error processing the request and returned '{}'".format(error)) if r.status_code == 501: raise Exception("The server does not support this version of the API!") - raise Exception( - "The server returned an invalid status code {}!".format(r.status_code) - ) + raise Exception("The server returned an invalid status code {}!".format(r.status_code)) def info_exchange(self) -> None: resp = self.exchange_data("", {}) @@ -124,9 +106,7 @@ class APIClient: ) print(json.dumps(resp["records"], indent=4)) - def profile_exchange( - self, game: str, version: str, idtype: str, ids: List[str] - ) -> None: + def profile_exchange(self, game: str, version: str, idtype: str, ids: List[str]) -> None: self.__id_check(idtype, ids) resp = self.exchange_data( "{}/{}/{}".format(self.API_VERSION, game, version), @@ -138,9 +118,7 @@ class APIClient: ) print(json.dumps(resp["profile"], indent=4)) - def statistics_exchange( - self, game: str, version: str, idtype: str, ids: List[str] - ) -> None: + def statistics_exchange(self, game: str, version: str, idtype: str, ids: List[str]) -> None: self.__id_check(idtype, ids) resp = self.exchange_data( "{}/{}/{}".format(self.API_VERSION, game, version), @@ -166,9 +144,7 @@ class APIClient: def main() -> None: # Global arguments - parser = argparse.ArgumentParser( - description="A sample API client for an e-AMUSEMENT API provider." - ) + parser = argparse.ArgumentParser(description="A sample API client for an e-AMUSEMENT API provider.") parser.add_argument( "-t", "--token", diff --git a/bemani/utils/scheduler.py b/bemani/utils/scheduler.py index 76d021d..1dd31f3 100644 --- a/bemani/utils/scheduler.py +++ b/bemani/utils/scheduler.py @@ -75,9 +75,7 @@ def run_scheduled_work(config: Config) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="A scheduler for work that needs to be done periodically." - ) + parser = argparse.ArgumentParser(description="A scheduler for work that needs to be done periodically.") parser.add_argument( "-c", "--config", diff --git a/bemani/utils/services.py b/bemani/utils/services.py index 23cf3cc..f2a9a24 100644 --- a/bemani/utils/services.py +++ b/bemani/utils/services.py @@ -134,12 +134,8 @@ def instantiate_cache(app: Any) -> None: if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="A backend services provider for eAmusement games" - ) - parser.add_argument( - "-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80 - ) + parser = argparse.ArgumentParser(description="A backend services provider for eAmusement games") + parser.add_argument("-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80) parser.add_argument( "-c", "--config", diff --git a/bemani/utils/struct.py b/bemani/utils/struct.py index 5039f47..41a04bb 100644 --- a/bemani/utils/struct.py +++ b/bemani/utils/struct.py @@ -46,9 +46,7 @@ class StructPrinter: if not in_dereference: in_dereference = True if cur_accum: - raise Exception( - "Cannot have dereference marker in middle of specifier!" - ) + raise Exception("Cannot have dereference marker in middle of specifier!") else: # Double-indirect dereference. cur_accum += c @@ -84,19 +82,13 @@ class StructPrinter: continue # If we have either an integer prefix, or an offset prefix, accumulate here. - if ( - c.isdigit() - or c in "+-" - or (c in "xabcdefABCDEF" and ("+" in cur_accum or "-" in cur_accum)) - ): + if c.isdigit() or c in "+-" or (c in "xabcdefABCDEF" and ("+" in cur_accum or "-" in cur_accum)): cur_accum += c continue if c == "&": if cur_accum: - raise Exception( - "Hex specifier should be at beginning of specifier!" - ) + raise Exception("Hex specifier should be at beginning of specifier!") cur_accum += c continue @@ -115,16 +107,10 @@ class StructPrinter: return prefix, specs - def parse_struct( - self, startaddr: str, endaddr: str, countstr: str, fmt: str - ) -> List[Any]: + def parse_struct(self, startaddr: str, endaddr: str, countstr: str, fmt: str) -> List[Any]: start: int = int(startaddr, 16) end: Optional[int] = int(endaddr, 16) if endaddr is not None else None - count: Optional[int] = ( - int(countstr, 16 if "0x" in countstr else 10) - if countstr is not None - else None - ) + count: Optional[int] = int(countstr, 16 if "0x" in countstr else 10) if countstr is not None else None if end is None and count is None: raise Exception("Can't handle endless structures!") @@ -176,9 +162,7 @@ class StructPrinter: if spec[-1] == "#": if len(spec) > 1: if spec[0] not in "+-": - raise Exception( - "Line number offsets must include a '+' or '-' prefix!" - ) + raise Exception("Line number offsets must include a '+' or '-' prefix!") val = int(spec[:-1], 16 if "0x" in spec else 10) else: val = 0 @@ -222,9 +206,7 @@ class StructPrinter: line.append(None) else: pointer = self.pe.virtual_to_physical(pointer) - subparse = self.__parse_struct( - pointer, pointer + 1, None, prefix, spec - ) + subparse = self.__parse_struct(pointer, pointer + 1, None, prefix, spec) if len(subparse) != 1: raise Exception("Logic error!") line.append(subparse[0]) diff --git a/bemani/utils/tdxtutils.py b/bemani/utils/tdxtutils.py index b057b1f..424d543 100644 --- a/bemani/utils/tdxtutils.py +++ b/bemani/utils/tdxtutils.py @@ -28,9 +28,7 @@ def extract_texture( output_dir = os.path.dirname(os.path.abspath(output_fname)) os.makedirs(output_dir, exist_ok=True) - print( - f"Extracting texture from {os.path.abspath(fname)} to {os.path.abspath(output_fname)}" - ) + print(f"Extracting texture from {os.path.abspath(fname)} to {os.path.abspath(output_fname)}") with open(output_fname, "wb") as bfp: tdxt.img.save(bfp, format="PNG") @@ -53,9 +51,7 @@ def update_texture( tdxt.img = img - print( - f"Updating texture in {os.path.abspath(fname)} from {os.path.abspath(input_fname)}" - ) + print(f"Updating texture in {os.path.abspath(fname)} from {os.path.abspath(input_fname)}") with open(fname, "wb") as bfp: bfp.write(tdxt.toBytes()) @@ -63,9 +59,7 @@ def update_texture( def main() -> int: - parser = argparse.ArgumentParser( - description="Konami TDXT graphic file unpacker/repacker." - ) + parser = argparse.ArgumentParser(description="Konami TDXT graphic file unpacker/repacker.") subparsers = parser.add_subparsers(help="Action to take", dest="action") unpack_parser = subparsers.add_parser( diff --git a/bemani/utils/trafficgen.py b/bemani/utils/trafficgen.py index f3cebf7..7647ef6 100644 --- a/bemani/utils/trafficgen.py +++ b/bemani/utils/trafficgen.py @@ -61,9 +61,7 @@ from bemani.client.bishi import TheStarBishiBashiClient from bemani.client.mga.mga import MetalGearArcadeClient -def get_client( - proto: ClientProtocol, pcbid: str, game: str, config: Dict[str, Any] -) -> BaseClient: +def get_client(proto: ClientProtocol, pcbid: str, game: str, config: Dict[str, Any]) -> BaseClient: if game == "pnm-tune-street": return PopnMusicTuneStreetClient( proto, @@ -570,9 +568,7 @@ def main() -> None: parser = argparse.ArgumentParser( description="A utility to generate game-like traffic for testing an eAmusement server." ) - parser.add_argument( - "-p", "--port", help="Port to talk to. Defaults to 80", type=int, default=80 - ) + parser.add_argument("-p", "--port", help="Port to talk to. Defaults to 80", type=int, default=80) parser.add_argument( "-a", "--address", @@ -594,9 +590,7 @@ def main() -> None: type=str, default=None, ) - parser.add_argument( - "-l", "--list", help="List all known games and exit.", action="store_true" - ) + parser.add_argument("-l", "--list", help="List all known games and exit.", action="store_true") parser.add_argument( "-i", "--cardid", @@ -664,9 +658,7 @@ def main() -> None: "mga": "metal-gear-arcade", }.get(game, game) - mainloop( - args.address, args.port, args.config, action, game, args.cardid, args.verbose - ) + mainloop(args.address, args.port, args.config, action, game, args.cardid, args.verbose) if __name__ == "__main__": diff --git a/bemani/utils/twodxutils.py b/bemani/utils/twodxutils.py index 0bdd956..842d158 100644 --- a/bemani/utils/twodxutils.py +++ b/bemani/utils/twodxutils.py @@ -5,9 +5,7 @@ from bemani.format import TwoDX def main() -> None: - parser = argparse.ArgumentParser( - description="A utility to extract/build 2dx files." - ) + parser = argparse.ArgumentParser(description="A utility to extract/build 2dx files.") parser.add_argument( "file", help="2dx file to extract/build.", @@ -83,9 +81,7 @@ def main() -> None: wfp.write(twodx.get_new_data()) wfp.close() else: - raise Exception( - "Please provide either a directory to extract to, or a wav file to build into a 2dx file!" - ) + raise Exception("Please provide either a directory to extract to, or a wav file to build into a 2dx file!") if __name__ == "__main__": diff --git a/formatfiles b/formatfiles index e9c9b1d..88d0ff0 100755 --- a/formatfiles +++ b/formatfiles @@ -1,3 +1,3 @@ #! /bin/bash -black --extend-exclude "setup\.py|\.pyi|bemani\/data\/migrations\/" . +black --line-length 120 --extend-exclude "setup\.py|\.pyi|bemani\/data\/migrations\/" .