let black do it's magic

This commit is contained in:
2023-03-09 11:38:58 -05:00
parent fa7206848c
commit a76bb94eb1
150 changed files with 8474 additions and 4843 deletions

View File

@ -7,4 +7,4 @@ index = OngekiServlet
database = OngekiData
reader = OngekiReader
game_codes = [OngekiConstants.GAME_CODE]
current_schema_version = 2
current_schema_version = 2

View File

@ -11,6 +11,7 @@ from titles.ongeki.config import OngekiConfig
from titles.ongeki.database import OngekiData
from titles.ongeki.config import OngekiConfig
class OngekiBattleGrade(Enum):
FAILED = 0
DRAW = 1
@ -21,6 +22,7 @@ class OngekiBattleGrade(Enum):
UNBELIEVABLE_GOLD = 6
UNBELIEVABLE_RAINBOW = 7
class OngekiBattlePointGrade(Enum):
FRESHMAN = 0
KYU10 = 1
@ -45,20 +47,22 @@ class OngekiBattlePointGrade(Enum):
DAN10 = 20
SODEN = 21
class OngekiTechnicalGrade(Enum):
D = 0
C = 1
B = 2
BB = 3
BBB = 4
A = 5
AA = 6
AAA = 7
S = 8
SS = 9
SSS = 10
D = 0
C = 1
B = 2
BB = 3
BBB = 4
A = 5
AA = 6
AAA = 7
S = 8
SS = 9
SSS = 10
SSSp = 11
class OngekiDifficulty(Enum):
BASIC = 0
ADVANCED = 1
@ -66,6 +70,7 @@ class OngekiDifficulty(Enum):
MASTER = 3
LUNATIC = 10
class OngekiGPLogKind(Enum):
NONE = 0
BUY1_START = 1
@ -82,22 +87,28 @@ class OngekiGPLogKind(Enum):
PAY_MAS_UNLOCK = 13
PAY_MONEY = 14
class OngekiBase():
class OngekiBase:
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
self.core_cfg = core_cfg
self.game_cfg = game_cfg
self.data = OngekiData(core_cfg)
self.date_time_format = "%Y-%m-%d %H:%M:%S"
self.date_time_format_ext = "%Y-%m-%d %H:%M:%S.%f" # needs to be lopped off at [:-5]
self.date_time_format_ext = (
"%Y-%m-%d %H:%M:%S.%f" # needs to be lopped off at [:-5]
)
self.date_time_format_short = "%Y-%m-%d"
self.logger = logging.getLogger("ongeki")
self.game = OngekiConstants.GAME_CODE
self.version = OngekiConstants.VER_ONGEKI
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
reboot_start = date.strftime(datetime.now() + timedelta(hours=3), self.date_time_format)
reboot_end = date.strftime(datetime.now() + timedelta(hours=4), self.date_time_format)
reboot_start = date.strftime(
datetime.now() + timedelta(hours=3), self.date_time_format
)
reboot_end = date.strftime(
datetime.now() + timedelta(hours=4), self.date_time_format
)
return {
"gameSetting": {
"dataVersion": "1.00.00",
@ -128,20 +139,53 @@ class OngekiBase():
def handle_get_game_ranking_api_request(self, data: Dict) -> Dict:
return {"length": 0, "gameRankingList": []}
def handle_get_game_point_api_request(self, data: Dict) -> Dict:
"""
Sets the GP ammount for A and B sets for 1 - 3 crdits
"""
return {"length":6,"gamePointList":[
{"type":0,"cost":100,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"},
{"type":1,"cost":200,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"},
{"type":2,"cost":300,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"},
{"type":3,"cost":120,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"},
{"type":4,"cost":240,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"},
{"type":5,"cost":360,"startDate":"2000-01-01 05:00:00.0","endDate":"2099-01-01 05:00:00.0"}
]}
return {
"length": 6,
"gamePointList": [
{
"type": 0,
"cost": 100,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
{
"type": 1,
"cost": 200,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
{
"type": 2,
"cost": 300,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
{
"type": 3,
"cost": 120,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
{
"type": 4,
"cost": 240,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
{
"type": 5,
"cost": 360,
"startDate": "2000-01-01 05:00:00.0",
"endDate": "2099-01-01 05:00:00.0",
},
],
}
def handle_game_login_api_request(self, data: Dict) -> Dict:
return {"returnCode": 1, "apiName": "gameLogin"}
@ -184,11 +228,19 @@ class OngekiBase():
def handle_upsert_user_gplog_api_request(self, data: Dict) -> Dict:
user = data["userId"]
if user >= 200000000000000: # Account for guest play
if user >= 200000000000000: # Account for guest play
user = None
self.data.log.put_gp_log(user, data["usedCredit"], data["placeName"], data["userGplog"]["trxnDate"],
data["userGplog"]["placeId"], data["userGplog"]["kind"], data["userGplog"]["pattern"], data["userGplog"]["currentGP"])
self.data.log.put_gp_log(
user,
data["usedCredit"],
data["placeName"],
data["userGplog"]["trxnDate"],
data["userGplog"]["placeId"],
data["userGplog"]["kind"],
data["userGplog"]["pattern"],
data["userGplog"]["currentGP"],
)
return {"returnCode": 1, "apiName": "UpsertUserGplogApi"}
@ -197,39 +249,53 @@ class OngekiBase():
def handle_get_game_event_api_request(self, data: Dict) -> Dict:
evts = self.data.static.get_enabled_events(self.version)
evt_list = []
for event in evts:
evt_list.append({
"type": event["type"],
"id": event["eventId"],
"startDate": "2017-12-05 07:00:00.0",
"endDate": "2099-12-31 00:00:00.0"
})
return {"type": data["type"], "length": len(evt_list), "gameEventList": evt_list}
evt_list.append(
{
"type": event["type"],
"id": event["eventId"],
"startDate": "2017-12-05 07:00:00.0",
"endDate": "2099-12-31 00:00:00.0",
}
)
return {
"type": data["type"],
"length": len(evt_list),
"gameEventList": evt_list,
}
def handle_get_game_id_list_api_request(self, data: Dict) -> Dict:
game_idlist: list[str, Any] = [] #1 to 230 & 8000 to 8050
game_idlist: list[str, Any] = [] # 1 to 230 & 8000 to 8050
if data["type"] == 1:
for i in range(1,231):
for i in range(1, 231):
game_idlist.append({"type": 1, "id": i})
return {"type": data["type"], "length": len(game_idlist), "gameIdlistList": game_idlist}
return {
"type": data["type"],
"length": len(game_idlist),
"gameIdlistList": game_idlist,
}
elif data["type"] == 2:
for i in range(8000,8051):
for i in range(8000, 8051):
game_idlist.append({"type": 2, "id": i})
return {"type": data["type"], "length": len(game_idlist), "gameIdlistList": game_idlist}
return {
"type": data["type"],
"length": len(game_idlist),
"gameIdlistList": game_idlist,
}
def handle_get_user_region_api_request(self, data: Dict) -> Dict:
return {"userId": data["userId"], "length": 0, "userRegionList": []}
def handle_get_user_preview_api_request(self, data: Dict) -> Dict:
profile = self.data.profile.get_profile_preview(data["userId"], self.version)
if profile is None:
if profile is None:
return {
"userId": data["userId"],
"userId": data["userId"],
"isLogin": False,
"lastLoginDate": "0000-00-00 00:00:00",
"userName": "",
@ -240,12 +306,12 @@ class OngekiBase():
"lastGameId": "",
"lastRomVersion": "",
"lastDataVersion": "",
"lastPlayDate": "",
"lastPlayDate": "",
"nameplateId": 0,
"trophyId": 0,
"cardId": 0,
"dispPlayerLv": 0,
"dispRating": 0,
"trophyId": 0,
"cardId": 0,
"dispPlayerLv": 0,
"dispRating": 0,
"dispBP": 0,
"headphone": 0,
"banStatus": 0,
@ -253,7 +319,7 @@ class OngekiBase():
}
return {
"userId": data["userId"],
"userId": data["userId"],
"isLogin": False,
"lastLoginDate": profile["lastPlayDate"],
"userName": profile["userName"],
@ -264,12 +330,12 @@ class OngekiBase():
"lastGameId": profile["lastGameId"],
"lastRomVersion": profile["lastRomVersion"],
"lastDataVersion": profile["lastDataVersion"],
"lastPlayDate": profile["lastPlayDate"],
"lastPlayDate": profile["lastPlayDate"],
"nameplateId": profile["nameplateId"],
"trophyId": profile["trophyId"],
"cardId": profile["cardId"],
"dispPlayerLv": profile["dispPlayerLv"],
"dispRating": profile["dispRating"],
"trophyId": profile["trophyId"],
"cardId": profile["cardId"],
"dispPlayerLv": profile["dispPlayerLv"],
"dispRating": profile["dispRating"],
"dispBP": profile["dispBP"],
"headphone": profile["headphone"],
"banStatus": profile["banStatus"],
@ -297,7 +363,8 @@ class OngekiBase():
def handle_get_user_tech_event_api_request(self, data: Dict) -> Dict:
user_tech_event_list = self.data.item.get_tech_event(data["userId"])
if user_tech_event_list is None: return {}
if user_tech_event_list is None:
return {}
tech_evt = []
for evt in user_tech_event_list:
@ -313,11 +380,11 @@ class OngekiBase():
}
def handle_get_user_tech_event_ranking_api_request(self, data: Dict) -> Dict:
#user_event_ranking_list = self.data.item.get_tech_event_ranking(data["userId"])
#if user_event_ranking_list is None: return {}
# user_event_ranking_list = self.data.item.get_tech_event_ranking(data["userId"])
# if user_event_ranking_list is None: return {}
evt_ranking = []
#for evt in user_event_ranking_list:
# for evt in user_event_ranking_list:
# tmp = evt._asdict()
# tmp.pop("id")
# tmp.pop("user")
@ -331,7 +398,8 @@ class OngekiBase():
def handle_get_user_kop_api_request(self, data: Dict) -> Dict:
kop_list = self.data.profile.get_kop(data["userId"])
if kop_list is None: return {}
if kop_list is None:
return {}
for kop in kop_list:
kop.pop("user")
@ -349,10 +417,10 @@ class OngekiBase():
next_idx = data["nextIndex"]
start_idx = next_idx
end_idx = max_ct + start_idx
if len(song_list[start_idx:]) > max_ct:
next_idx += max_ct
else:
next_idx = -1
@ -360,15 +428,20 @@ class OngekiBase():
"userId": data["userId"],
"length": len(song_list[start_idx:end_idx]),
"nextIndex": next_idx,
"userMusicList": song_list[start_idx:end_idx]
"userMusicList": song_list[start_idx:end_idx],
}
def handle_get_user_item_api_request(self, data: Dict) -> Dict:
kind = data["nextIndex"] / 10000000000
p = self.data.item.get_items(data["userId"], kind)
if p is None:
return {"userId": data["userId"], "nextIndex": -1, "itemKind": kind, "userItemList": []}
if p is None:
return {
"userId": data["userId"],
"nextIndex": -1,
"itemKind": kind,
"userItemList": [],
}
items: list[Dict[str, Any]] = []
for i in range(data["nextIndex"] % 10000000000, len(p)):
@ -381,14 +454,23 @@ class OngekiBase():
xout = kind * 10000000000 + (data["nextIndex"] % 10000000000) + len(items)
if len(items) < data["maxCount"] or data["maxCount"] == 0: nextIndex = 0
else: nextIndex = xout
if len(items) < data["maxCount"] or data["maxCount"] == 0:
nextIndex = 0
else:
nextIndex = xout
return {"userId": data["userId"], "nextIndex": int(nextIndex), "itemKind": int(kind), "length": len(items), "userItemList": items}
return {
"userId": data["userId"],
"nextIndex": int(nextIndex),
"itemKind": int(kind),
"length": len(items),
"userItemList": items,
}
def handle_get_user_option_api_request(self, data: Dict) -> Dict:
o = self.data.profile.get_profile_options(data["userId"])
if o is None: return {}
if o is None:
return {}
# get the dict representation of the row so we can modify values
user_opts = o._asdict()
@ -401,14 +483,17 @@ class OngekiBase():
def handle_get_user_data_api_request(self, data: Dict) -> Dict:
p = self.data.profile.get_profile_data(data["userId"], self.version)
if p is None: return {}
if p is None:
return {}
cards = self.data.card.get_user_cards(data["userId"])
if cards is None or len(cards) == 0:
# This should never happen
self.logger.error(f"handle_get_user_data_api_request: Internal error - No cards found for user id {data['userId']}")
self.logger.error(
f"handle_get_user_data_api_request: Internal error - No cards found for user id {data['userId']}"
)
return {}
# get the dict representation of the row so we can modify values
user_data = p._asdict()
@ -422,14 +507,14 @@ class OngekiBase():
# add access code that we don't store
user_data["accessCode"] = cards[0]["access_code"]
return {"userId": data["userId"], "userData":user_data}
return {"userId": data["userId"], "userData": user_data}
def handle_get_user_event_ranking_api_request(self, data: Dict) -> Dict:
#user_event_ranking_list = self.data.item.get_event_ranking(data["userId"])
#if user_event_ranking_list is None: return {}
# user_event_ranking_list = self.data.item.get_event_ranking(data["userId"])
# if user_event_ranking_list is None: return {}
evt_ranking = []
#for evt in user_event_ranking_list:
# for evt in user_event_ranking_list:
# tmp = evt._asdict()
# tmp.pop("id")
# tmp.pop("user")
@ -443,7 +528,8 @@ class OngekiBase():
def handle_get_user_login_bonus_api_request(self, data: Dict) -> Dict:
user_login_bonus_list = self.data.item.get_login_bonuses(data["userId"])
if user_login_bonus_list is None: return {}
if user_login_bonus_list is None:
return {}
login_bonuses = []
for scenerio in user_login_bonus_list:
@ -451,16 +537,19 @@ class OngekiBase():
tmp.pop("id")
tmp.pop("user")
login_bonuses.append(tmp)
return {
"userId": data["userId"],
"length": len(login_bonuses),
"userLoginBonusList": login_bonuses
"userId": data["userId"],
"length": len(login_bonuses),
"userLoginBonusList": login_bonuses,
}
def handle_get_user_bp_base_request(self, data: Dict) -> Dict:
p = self.data.profile.get_profile(self.game, self.version, user_id = data["userId"])
if p is None: return {}
p = self.data.profile.get_profile(
self.game, self.version, user_id=data["userId"]
)
if p is None:
return {}
profile = json.loads(p["data"])
return {
"userId": data["userId"],
@ -470,7 +559,8 @@ class OngekiBase():
def handle_get_user_recent_rating_api_request(self, data: Dict) -> Dict:
recent_rating = self.data.profile.get_profile_recent_rating(data["userId"])
if recent_rating is None: return {}
if recent_rating is None:
return {}
userRecentRatingList = recent_rating["recentRating"]
@ -482,31 +572,35 @@ class OngekiBase():
def handle_get_user_activity_api_request(self, data: Dict) -> Dict:
activity = self.data.profile.get_profile_activity(data["userId"], data["kind"])
if activity is None: return {}
if activity is None:
return {}
user_activity = []
for act in activity:
user_activity.append({
"kind": act["kind"],
"id": act["activityId"],
"sortNumber": act["sortNumber"],
"param1": act["param1"],
"param2": act["param2"],
"param3": act["param3"],
"param4": act["param4"],
})
user_activity.append(
{
"kind": act["kind"],
"id": act["activityId"],
"sortNumber": act["sortNumber"],
"param1": act["param1"],
"param2": act["param2"],
"param3": act["param3"],
"param4": act["param4"],
}
)
return {
"userId": data["userId"],
"userId": data["userId"],
"length": len(user_activity),
"kind": data["kind"],
"userActivityList": user_activity
"userActivityList": user_activity,
}
def handle_get_user_story_api_request(self, data: Dict) -> Dict:
user_stories = self.data.item.get_stories(data["userId"])
if user_stories is None: return {}
if user_stories is None:
return {}
story_list = []
for story in user_stories:
@ -516,14 +610,15 @@ class OngekiBase():
story_list.append(tmp)
return {
"userId": data["userId"],
"length": len(story_list),
"userStoryList": story_list
"userId": data["userId"],
"length": len(story_list),
"userStoryList": story_list,
}
def handle_get_user_chapter_api_request(self, data: Dict) -> Dict:
user_chapters = self.data.item.get_chapters(data["userId"])
if user_chapters is None: return {}
if user_chapters is None:
return {}
chapter_list = []
for chapter in user_chapters:
@ -531,11 +626,11 @@ class OngekiBase():
tmp.pop("id")
tmp.pop("user")
chapter_list.append(tmp)
return {
"userId": data["userId"],
"length": len(chapter_list),
"userChapterList": chapter_list
"userId": data["userId"],
"length": len(chapter_list),
"userChapterList": chapter_list,
}
def handle_get_user_training_room_by_key_api_request(self, data: Dict) -> Dict:
@ -547,7 +642,8 @@ class OngekiBase():
def handle_get_user_character_api_request(self, data: Dict) -> Dict:
user_characters = self.data.item.get_characters(data["userId"])
if user_characters is None: return {}
if user_characters is None:
return {}
character_list = []
for character in user_characters:
@ -555,16 +651,17 @@ class OngekiBase():
tmp.pop("id")
tmp.pop("user")
character_list.append(tmp)
return {
"userId": data["userId"],
"length": len(character_list),
"userCharacterList": character_list
"userId": data["userId"],
"length": len(character_list),
"userCharacterList": character_list,
}
def handle_get_user_card_api_request(self, data: Dict) -> Dict:
user_cards = self.data.item.get_cards(data["userId"])
if user_cards is None: return {}
if user_cards is None:
return {}
card_list = []
for card in user_cards:
@ -572,17 +669,18 @@ class OngekiBase():
tmp.pop("id")
tmp.pop("user")
card_list.append(tmp)
return {
"userId": data["userId"],
"length": len(card_list),
"userCardList": card_list
"userId": data["userId"],
"length": len(card_list),
"userCardList": card_list,
}
def handle_get_user_deck_by_key_api_request(self, data: Dict) -> Dict:
# Auth key doesn't matter, it just wants all the decks
decks = self.data.item.get_decks(data["userId"])
if decks is None: return {}
if decks is None:
return {}
deck_list = []
for deck in decks:
@ -599,7 +697,8 @@ class OngekiBase():
def handle_get_user_trade_item_api_request(self, data: Dict) -> Dict:
user_trade_items = self.data.item.get_trade_items(data["userId"])
if user_trade_items is None: return {}
if user_trade_items is None:
return {}
trade_item_list = []
for trade_item in user_trade_items:
@ -616,7 +715,8 @@ class OngekiBase():
def handle_get_user_scenario_api_request(self, data: Dict) -> Dict:
user_scenerio = self.data.item.get_scenerios(data["userId"])
if user_scenerio is None: return {}
if user_scenerio is None:
return {}
scenerio_list = []
for scenerio in user_scenerio:
@ -624,7 +724,7 @@ class OngekiBase():
tmp.pop("id")
tmp.pop("user")
scenerio_list.append(tmp)
return {
"userId": data["userId"],
"length": len(scenerio_list),
@ -633,7 +733,8 @@ class OngekiBase():
def handle_get_user_ratinglog_api_request(self, data: Dict) -> Dict:
rating_log = self.data.profile.get_profile_rating_log(data["userId"])
if rating_log is None: return {}
if rating_log is None:
return {}
userRatinglogList = []
for rating in rating_log:
@ -650,7 +751,8 @@ class OngekiBase():
def handle_get_user_mission_point_api_request(self, data: Dict) -> Dict:
user_mission_point_list = self.data.item.get_mission_points(data["userId"])
if user_mission_point_list is None: return {}
if user_mission_point_list is None:
return {}
mission_point_list = []
for evt_music in user_mission_point_list:
@ -667,7 +769,8 @@ class OngekiBase():
def handle_get_user_event_point_api_request(self, data: Dict) -> Dict:
user_event_point_list = self.data.item.get_event_points(data["userId"])
if user_event_point_list is None: return {}
if user_event_point_list is None:
return {}
event_point_list = []
for evt_music in user_event_point_list:
@ -684,7 +787,8 @@ class OngekiBase():
def handle_get_user_music_item_api_request(self, data: Dict) -> Dict:
user_music_item_list = self.data.item.get_music_items(data["userId"])
if user_music_item_list is None: return {}
if user_music_item_list is None:
return {}
music_item_list = []
for evt_music in user_music_item_list:
@ -701,7 +805,8 @@ class OngekiBase():
def handle_get_user_event_music_api_request(self, data: Dict) -> Dict:
user_evt_music_list = self.data.item.get_event_music(data["userId"])
if user_evt_music_list is None: return {}
if user_evt_music_list is None:
return {}
evt_music_list = []
for evt_music in user_evt_music_list:
@ -718,7 +823,8 @@ class OngekiBase():
def handle_get_user_boss_api_request(self, data: Dict) -> Dict:
p = self.data.item.get_bosses(data["userId"])
if p is None: return {}
if p is None:
return {}
boss_list = []
for boss in p:
@ -740,7 +846,9 @@ class OngekiBase():
# The isNew fields are new as of Red and up. We just won't use them for now.
if "userData" in upsert and len(upsert["userData"]) > 0:
self.data.profile.put_profile_data(user_id, self.version, upsert["userData"][0])
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0]
)
if "userOption" in upsert and len(upsert["userOption"]) > 0:
self.data.profile.put_profile_options(user_id, upsert["userOption"][0])
@ -751,27 +859,37 @@ class OngekiBase():
if "userActivityList" in upsert:
for act in upsert["userActivityList"]:
self.data.profile.put_profile_activity(user_id, act["kind"], act["id"], act["sortNumber"], act["param1"],
act["param2"], act["param3"], act["param4"])
self.data.profile.put_profile_activity(
user_id,
act["kind"],
act["id"],
act["sortNumber"],
act["param1"],
act["param2"],
act["param3"],
act["param4"],
)
if "userRecentRatingList" in upsert:
self.data.profile.put_profile_recent_rating(user_id, upsert["userRecentRatingList"])
self.data.profile.put_profile_recent_rating(
user_id, upsert["userRecentRatingList"]
)
if "userBpBaseList" in upsert:
self.data.profile.put_profile_bp_list(user_id, upsert["userBpBaseList"])
if "userMusicDetailList" in upsert:
for x in upsert["userMusicDetailList"]:
self.data.score.put_best_score(user_id, x)
if "userCharacterList" in upsert:
for x in upsert["userCharacterList"]:
self.data.item.put_character(user_id, x)
if "userCardList" in upsert:
for x in upsert["userCardList"]:
self.data.item.put_card(user_id, x)
if "userDeckList" in upsert:
for x in upsert["userDeckList"]:
self.data.item.put_deck(user_id, x)
@ -779,43 +897,45 @@ class OngekiBase():
if "userTrainingRoomList" in upsert:
for x in upsert["userTrainingRoomList"]:
self.data.profile.put_training_room(user_id, x)
if "userStoryList" in upsert:
for x in upsert["userStoryList"]:
self.data.item.put_story(user_id, x)
if "userChapterList" in upsert:
for x in upsert["userChapterList"]:
self.data.item.put_chapter(user_id, x)
if "userMemoryChapterList" in upsert:
for x in upsert["userMemoryChapterList"]:
self.data.item.put_memorychapter(user_id, x)
if "userItemList" in upsert:
for x in upsert["userItemList"]:
self.data.item.put_item(user_id, x)
if "userMusicItemList" in upsert:
for x in upsert["userMusicItemList"]:
self.data.item.put_music_item(user_id, x)
if "userLoginBonusList" in upsert:
for x in upsert["userLoginBonusList"]:
self.data.item.put_login_bonus(user_id, x)
if "userEventPointList" in upsert:
for x in upsert["userEventPointList"]:
self.data.item.put_event_point(user_id, x)
if "userMissionPointList" in upsert:
for x in upsert["userMissionPointList"]:
self.data.item.put_mission_point(user_id, x)
if "userRatinglogList" in upsert:
for x in upsert["userRatinglogList"]:
self.data.profile.put_profile_rating_log(user_id, x["dataVersion"], x["highestRating"])
self.data.profile.put_profile_rating_log(
user_id, x["dataVersion"], x["highestRating"]
)
if "userBossList" in upsert:
for x in upsert["userBossList"]:
self.data.item.put_boss(user_id, x)
@ -844,7 +964,7 @@ class OngekiBase():
for x in upsert["userKopList"]:
self.data.profile.put_kop(user_id, x)
return {'returnCode': 1, 'apiName': 'upsertUserAll'}
return {"returnCode": 1, "apiName": "upsertUserAll"}
def handle_get_user_rival_api_request(self, data: Dict) -> Dict:
"""
@ -857,29 +977,28 @@ class OngekiBase():
"length": 0,
"userRivalList": [],
}
return {
"userId": data["userId"],
"length": len(rival_list),
"userRivalList": rival_list._asdict(),
}
def handle_get_user_rival_data_api_reqiest(self, data:Dict) -> Dict:
def handle_get_user_rival_data_api_reqiest(self, data: Dict) -> Dict:
"""
Added in Bright
"""
rivals = []
for rival in data["userRivalList"]:
name = self.data.profile.get_profile_name(rival["rivalUserId"], self.version)
name = self.data.profile.get_profile_name(
rival["rivalUserId"], self.version
)
if name is None:
continue
rivals.append({
"rivalUserId": rival["rival"],
"rivalUserName": name
})
rivals.append({"rivalUserId": rival["rival"], "rivalUserName": name})
return {
"userId": data["userId"],
"length": len(rivals),
@ -893,11 +1012,9 @@ class OngekiBase():
rival_id = data["rivalUserId"]
next_idx = data["nextIndex"]
max_ct = data["maxCount"]
music = self.handle_get_user_music_api_request({
"userId": rival_id,
"nextIndex": next_idx,
"maxCount": max_ct
})
music = self.handle_get_user_music_api_request(
{"userId": rival_id, "nextIndex": next_idx, "maxCount": max_ct}
)
for song in music["userMusicList"]:
song["userRivalMusicDetailList"] = song["userMusicDetailList"]
@ -921,18 +1038,15 @@ class OngekiBase():
tmp = md._asdict()
tmp.pop("user")
tmp.pop("id")
for song in song_list:
if song["userMusicDetailList"][0]["musicId"] == tmp["musicId"]:
found = True
song["userMusicDetailList"].append(tmp)
song["length"] = len(song["userMusicDetailList"])
break
if not found:
song_list.append({
"length": 1,
"userMusicDetailList": [tmp]
})
song_list.append({"length": 1, "userMusicDetailList": [tmp]})
return song_list

View File

@ -31,7 +31,8 @@ class OngekiBright(OngekiBase):
if cards is None or len(cards) == 0:
# This should never happen
self.logger.error(
f"handle_get_user_data_api_request: Internal error - No cards found for user id {data['userId']}")
f"handle_get_user_data_api_request: Internal error - No cards found for user id {data['userId']}"
)
return {}
# get the dict representation of the row so we can modify values
@ -86,7 +87,7 @@ class OngekiBright(OngekiBase):
"userId": data["userId"],
"length": len(card_list[start_idx:end_idx]),
"nextIndex": next_idx,
"userCardList": card_list[start_idx:end_idx]
"userCardList": card_list[start_idx:end_idx],
}
def handle_cm_get_user_character_api_request(self, data: Dict) -> Dict:
@ -115,31 +116,26 @@ class OngekiBright(OngekiBase):
"userId": data["userId"],
"length": len(character_list[start_idx:end_idx]),
"nextIndex": next_idx,
"userCharacterList": character_list[start_idx:end_idx]
"userCharacterList": character_list[start_idx:end_idx],
}
def handle_get_user_gacha_api_request(self, data: Dict) -> Dict:
user_gachas = self.data.item.get_user_gachas(data["userId"])
if user_gachas is None:
return {
"userId": data["userId"],
"length": 0,
"userGachaList": []
}
return {"userId": data["userId"], "length": 0, "userGachaList": []}
user_gacha_list = []
for gacha in user_gachas:
tmp = gacha._asdict()
tmp.pop("id")
tmp.pop("user")
tmp["dailyGachaDate"] = datetime.strftime(
tmp["dailyGachaDate"], "%Y-%m-%d")
tmp["dailyGachaDate"] = datetime.strftime(tmp["dailyGachaDate"], "%Y-%m-%d")
user_gacha_list.append(tmp)
return {
"userId": data["userId"],
"length": len(user_gacha_list),
"userGachaList": user_gacha_list
"userGachaList": user_gacha_list,
}
def handle_cm_get_user_item_api_request(self, data: Dict) -> Dict:
@ -147,21 +143,16 @@ class OngekiBright(OngekiBase):
def handle_cm_get_user_gacha_supply_api_request(self, data: Dict) -> Dict:
# not used for now? not sure what it even does
user_gacha_supplies = self.data.item.get_user_gacha_supplies(
data["userId"])
user_gacha_supplies = self.data.item.get_user_gacha_supplies(data["userId"])
if user_gacha_supplies is None:
return {
"supplyId": 1,
"length": 0,
"supplyCardList": []
}
return {"supplyId": 1, "length": 0, "supplyCardList": []}
supply_list = [gacha["cardId"] for gacha in user_gacha_supplies]
return {
"supplyId": 1,
"length": len(supply_list),
"supplyCardList": supply_list
"supplyCardList": supply_list,
}
def handle_get_game_gacha_api_request(self, data: Dict) -> Dict:
@ -182,29 +173,33 @@ class OngekiBright(OngekiBase):
tmp = gacha._asdict()
tmp.pop("id")
tmp.pop("version")
tmp["startDate"] = datetime.strftime(
tmp["startDate"], "%Y-%m-%d %H:%M:%S")
tmp["endDate"] = datetime.strftime(
tmp["endDate"], "%Y-%m-%d %H:%M:%S")
tmp["startDate"] = datetime.strftime(tmp["startDate"], "%Y-%m-%d %H:%M:%S")
tmp["endDate"] = datetime.strftime(tmp["endDate"], "%Y-%m-%d %H:%M:%S")
tmp["noticeStartDate"] = datetime.strftime(
tmp["noticeStartDate"], "%Y-%m-%d %H:%M:%S")
tmp["noticeStartDate"], "%Y-%m-%d %H:%M:%S"
)
tmp["noticeEndDate"] = datetime.strftime(
tmp["noticeEndDate"], "%Y-%m-%d %H:%M:%S")
tmp["noticeEndDate"], "%Y-%m-%d %H:%M:%S"
)
tmp["convertEndDate"] = datetime.strftime(
tmp["convertEndDate"], "%Y-%m-%d %H:%M:%S")
tmp["convertEndDate"], "%Y-%m-%d %H:%M:%S"
)
# make sure to only show gachas for the current version
# so only up to bright, 1140 is the first bright memory gacha
if self.version == OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY:
game_gacha_list.append(tmp)
elif self.version == OngekiConstants.VER_ONGEKI_BRIGHT and tmp["gachaId"] < 1140:
elif (
self.version == OngekiConstants.VER_ONGEKI_BRIGHT
and tmp["gachaId"] < 1140
):
game_gacha_list.append(tmp)
return {
"length": len(game_gacha_list),
"gameGachaList": game_gacha_list,
# no clue
"registIdList": []
"registIdList": [],
}
def handle_roll_gacha_api_request(self, data: Dict) -> Dict:
@ -251,7 +246,7 @@ class OngekiBright(OngekiBase):
assert len(rarity) == 100
# uniform distribution to get the rarity of the card
rolls = [rarity[randint(0, len(rarity)-1)] for _ in range(num_rolls)]
rolls = [rarity[randint(0, len(rarity) - 1)] for _ in range(num_rolls)]
# if SSR book used, make sure you always get one SSR
if book_used == 1:
@ -273,15 +268,9 @@ class OngekiBright(OngekiBase):
gacha_cards = self.data.static.get_gacha_cards(gacha_id)
for card in gacha_cards:
if card["rarity"] == 3:
cards_sr.append({
"cardId": card["cardId"],
"rarity": 2
})
cards_sr.append({"cardId": card["cardId"], "rarity": 2})
elif card["rarity"] == 4:
cards_ssr.append({
"cardId": card["cardId"],
"rarity": 3
})
cards_ssr.append({"cardId": card["cardId"], "rarity": 3})
else:
cards_sr = self.data.static.get_cards_by_rarity(self.version, 2)
cards_ssr = self.data.static.get_cards_by_rarity(self.version, 3)
@ -294,46 +283,39 @@ class OngekiBright(OngekiBase):
for card in gacha_cards:
# make sure to add the cards to the corresponding rarity
if card["rarity"] == 2:
cards_r += [{
"cardId": card["cardId"],
"rarity": 1
}] * chances
cards_r += [{"cardId": card["cardId"], "rarity": 1}] * chances
if card["rarity"] == 3:
cards_sr += [{
"cardId": card["cardId"],
"rarity": 2
}] * chances
cards_sr += [{"cardId": card["cardId"], "rarity": 2}] * chances
elif card["rarity"] == 4:
cards_ssr += [{
"cardId": card["cardId"],
"rarity": 3
}] * chances
cards_ssr += [{"cardId": card["cardId"], "rarity": 3}] * chances
# get the card id for each roll
rolled_cards = []
for i in range(len(rolls)):
if rolls[i] == 1:
rolled_cards.append(cards_r[randint(0, len(cards_r)-1)])
rolled_cards.append(cards_r[randint(0, len(cards_r) - 1)])
elif rolls[i] == 2:
rolled_cards.append(cards_sr[randint(0, len(cards_sr)-1)])
rolled_cards.append(cards_sr[randint(0, len(cards_sr) - 1)])
elif rolls[i] == 3:
rolled_cards.append(cards_ssr[randint(0, len(cards_ssr)-1)])
rolled_cards.append(cards_ssr[randint(0, len(cards_ssr) - 1)])
game_gacha_card_list = []
for card in rolled_cards:
game_gacha_card_list.append({
"gachaId": data["gachaId"],
"cardId": card["cardId"],
# +1 because Card Maker is weird
"rarity": card["rarity"] + 1,
"weight": 1,
"isPickup": False,
"isSelect": False
})
game_gacha_card_list.append(
{
"gachaId": data["gachaId"],
"cardId": card["cardId"],
# +1 because Card Maker is weird
"rarity": card["rarity"] + 1,
"weight": 1,
"isPickup": False,
"isSelect": False,
}
)
return {
"length": len(game_gacha_card_list),
"gameGachaCardList": game_gacha_card_list
"gameGachaCardList": game_gacha_card_list,
}
def handle_cm_upsert_user_gacha_api_request(self, data: Dict):
@ -342,12 +324,12 @@ class OngekiBright(OngekiBase):
gacha_id = data["gachaId"]
gacha_count = data["gachaCnt"]
play_date = datetime.strptime(data["playDate"][:10], '%Y-%m-%d')
play_date = datetime.strptime(data["playDate"][:10], "%Y-%m-%d")
select_point = data["selectPoint"]
total_gacha_count, ceiling_gacha_count = 0, 0
daily_gacha_cnt, five_gacha_cnt, eleven_gacha_cnt = 0, 0, 0
daily_gacha_date = datetime.strptime('2000-01-01', '%Y-%m-%d')
daily_gacha_date = datetime.strptime("2000-01-01", "%Y-%m-%d")
# check if the user previously rolled the exact same gacha
user_gacha = self.data.item.get_user_gacha(user_id, gacha_id)
@ -374,9 +356,11 @@ class OngekiBright(OngekiBase):
selectPoint=select_point,
useSelectPoint=0,
dailyGachaCnt=daily_gacha_cnt + gacha_count,
fiveGachaCnt=five_gacha_cnt+1 if gacha_count == 5 else five_gacha_cnt,
elevenGachaCnt=eleven_gacha_cnt+1 if gacha_count == 11 else eleven_gacha_cnt,
dailyGachaDate=daily_gacha_date
fiveGachaCnt=five_gacha_cnt + 1 if gacha_count == 5 else five_gacha_cnt,
elevenGachaCnt=eleven_gacha_cnt + 1
if gacha_count == 11
else eleven_gacha_cnt,
dailyGachaDate=daily_gacha_date,
)
if "userData" in upsert and len(upsert["userData"]) > 0:
@ -385,11 +369,13 @@ class OngekiBright(OngekiBase):
if p is not None:
# save the bright memory profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
else:
# save the bright profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
if "userCharacterList" in upsert:
for x in upsert["userCharacterList"]:
@ -407,7 +393,7 @@ class OngekiBright(OngekiBase):
# if "gameGachaCardList" in upsert:
# for x in upsert["gameGachaCardList"]:
return {'returnCode': 1, 'apiName': 'CMUpsertUserGachaApi'}
return {"returnCode": 1, "apiName": "CMUpsertUserGachaApi"}
def handle_cm_upsert_user_select_gacha_api_request(self, data: Dict) -> Dict:
upsert = data["cmUpsertUserSelectGacha"]
@ -419,11 +405,13 @@ class OngekiBright(OngekiBase):
if p is not None:
# save the bright memory profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
else:
# save the bright profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
if "userCharacterList" in upsert:
for x in upsert["userCharacterList"]:
@ -439,10 +427,10 @@ class OngekiBright(OngekiBase):
user_id,
x["gachaId"],
selectPoint=0,
useSelectPoint=x["useSelectPoint"]
useSelectPoint=x["useSelectPoint"],
)
return {'returnCode': 1, 'apiName': 'cmUpsertUserSelectGacha'}
return {"returnCode": 1, "apiName": "cmUpsertUserSelectGacha"}
def handle_get_game_gacha_card_by_id_api_request(self, data: Dict) -> Dict:
game_gacha_cards = self.data.static.get_gacha_cards(data["gachaId"])
@ -459,7 +447,7 @@ class OngekiBright(OngekiBase):
"rarity": 4,
"weight": 1,
"isPickup": False,
"isSelect": True
"isSelect": True,
},
{
"gachaId": data["gachaId"],
@ -467,7 +455,7 @@ class OngekiBright(OngekiBase):
"rarity": 3,
"weight": 2,
"isPickup": False,
"isSelect": True
"isSelect": True,
},
{
"gachaId": data["gachaId"],
@ -475,7 +463,7 @@ class OngekiBright(OngekiBase):
"rarity": 3,
"weight": 2,
"isPickup": False,
"isSelect": True
"isSelect": True,
},
{
"gachaId": data["gachaId"],
@ -483,7 +471,7 @@ class OngekiBright(OngekiBase):
"rarity": 2,
"weight": 3,
"isPickup": False,
"isSelect": True
"isSelect": True,
},
{
"gachaId": data["gachaId"],
@ -491,7 +479,7 @@ class OngekiBright(OngekiBase):
"rarity": 2,
"weight": 3,
"isPickup": False,
"isSelect": True
"isSelect": True,
},
{
"gachaId": data["gachaId"],
@ -499,12 +487,12 @@ class OngekiBright(OngekiBase):
"rarity": 2,
"weight": 3,
"isPickup": False,
"isSelect": True
}
"isSelect": True,
},
],
"emissionList": [],
"afterCalcList": [],
"ssrBookCalcList": []
"ssrBookCalcList": [],
}
game_gacha_card_list = []
@ -521,7 +509,7 @@ class OngekiBright(OngekiBase):
# again no clue
"emissionList": [],
"afterCalcList": [],
"ssrBookCalcList": []
"ssrBookCalcList": [],
}
def handle_get_game_theater_api_request(self, data: Dict) -> Dict:
@ -548,18 +536,14 @@ class OngekiBright(OngekiBase):
}
"""
return {
"length": 0,
"gameTheaterList": [],
"registIdList": []
}
return {"length": 0, "gameTheaterList": [], "registIdList": []}
def handle_cm_upsert_user_print_playlog_api_request(self, data: Dict) -> Dict:
return {
"returnCode": 1,
"orderId": 0,
"serialId": "11111111111111111111",
"apiName": "CMUpsertUserPrintPlaylogApi"
"apiName": "CMUpsertUserPrintPlaylogApi",
}
def handle_cm_upsert_user_printlog_api_request(self, data: Dict) -> Dict:
@ -567,34 +551,32 @@ class OngekiBright(OngekiBase):
"returnCode": 1,
"orderId": 0,
"serialId": "11111111111111111111",
"apiName": "CMUpsertUserPrintlogApi"
"apiName": "CMUpsertUserPrintlogApi",
}
def handle_cm_upsert_user_print_api_request(self, data: Dict) -> Dict:
user_print_detail = data["userPrintDetail"]
# generate random serial id
serial_id = ''.join([str(randint(0, 9)) for _ in range(20)])
serial_id = "".join([str(randint(0, 9)) for _ in range(20)])
# not needed because are either zero or unset
user_print_detail.pop("orderId")
user_print_detail.pop("printNumber")
user_print_detail.pop("serialId")
user_print_detail["printDate"] = datetime.strptime(
user_print_detail["printDate"], '%Y-%m-%d'
user_print_detail["printDate"], "%Y-%m-%d"
)
# add the entry to the user print table with the random serialId
self.data.item.put_user_print_detail(
data["userId"],
serial_id,
user_print_detail
data["userId"], serial_id, user_print_detail
)
return {
"returnCode": 1,
"serialId": serial_id,
"apiName": "CMUpsertUserPrintApi"
"apiName": "CMUpsertUserPrintApi",
}
def handle_cm_upsert_user_all_api_request(self, data: Dict) -> Dict:
@ -607,17 +589,26 @@ class OngekiBright(OngekiBase):
if p is not None:
# save the bright memory profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
else:
# save the bright profile
self.data.profile.put_profile_data(
user_id, self.version, upsert["userData"][0])
user_id, self.version, upsert["userData"][0]
)
if "userActivityList" in upsert:
for act in upsert["userActivityList"]:
self.data.profile.put_profile_activity(
user_id, act["kind"], act["id"], act["sortNumber"],
act["param1"], act["param2"], act["param3"], act["param4"])
user_id,
act["kind"],
act["id"],
act["sortNumber"],
act["param1"],
act["param2"],
act["param3"],
act["param4"],
)
if "userItemList" in upsert:
for x in upsert["userItemList"]:
@ -627,4 +618,4 @@ class OngekiBright(OngekiBase):
for x in upsert["userCardList"]:
self.data.item.put_card(user_id, x)
return {'returnCode': 1, 'apiName': 'cmUpsertUserAll'}
return {"returnCode": 1, "apiName": "cmUpsertUserAll"}

View File

@ -30,14 +30,96 @@ class OngekiBrightMemory(OngekiBright):
def handle_get_user_memory_chapter_api_request(self, data: Dict) -> Dict:
memories = self.data.item.get_memorychapters(data["userId"])
if not memories:
return {"userId": data["userId"], "length":6, "userMemoryChapterList":[
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70001, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0},
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70002, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0},
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70003, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0},
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70004, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0},
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70005, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0},
{"gaugeId":0, "isClear": False, "gaugeNum": 0, "chapterId": 70099, "jewelCount": 0, "isBossWatched": False, "isStoryWatched": False, "isDialogWatched": False, "isEndingWatched": False, "lastPlayMusicId": 0, "lastPlayMusicLevel": 0, "lastPlayMusicCategory": 0}
]}
return {
"userId": data["userId"],
"length": 6,
"userMemoryChapterList": [
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70001,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70002,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70003,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70004,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70005,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
{
"gaugeId": 0,
"isClear": False,
"gaugeNum": 0,
"chapterId": 70099,
"jewelCount": 0,
"isBossWatched": False,
"isStoryWatched": False,
"isDialogWatched": False,
"isEndingWatched": False,
"lastPlayMusicId": 0,
"lastPlayMusicLevel": 0,
"lastPlayMusicCategory": 0,
},
],
}
memory_chp = []
for chp in memories:
@ -49,14 +131,11 @@ class OngekiBrightMemory(OngekiBright):
return {
"userId": data["userId"],
"length": len(memory_chp),
"userMemoryChapterList": memory_chp
"userMemoryChapterList": memory_chp,
}
def handle_get_game_music_release_state_api_request(self, data: Dict) -> Dict:
return {
"techScore": 0,
"cardNum": 0
}
return {"techScore": 0, "cardNum": 0}
def handle_cm_get_user_data_api_request(self, data: Dict) -> Dict:
# check for a bright memory profile

View File

@ -3,26 +3,34 @@ from typing import List
from core.config import CoreConfig
class OngekiServerConfig():
class OngekiServerConfig:
def __init__(self, parent_config: "OngekiConfig") -> None:
self.__config = parent_config
@property
def enable(self) -> bool:
return CoreConfig.get_config_field(self.__config, 'ongeki', 'server', 'enable', default=True)
return CoreConfig.get_config_field(
self.__config, "ongeki", "server", "enable", default=True
)
@property
def loglevel(self) -> int:
return CoreConfig.str_to_loglevel(CoreConfig.get_config_field(self.__config, 'ongeki', 'server', 'loglevel', default="info"))
return CoreConfig.str_to_loglevel(
CoreConfig.get_config_field(
self.__config, "ongeki", "server", "loglevel", default="info"
)
)
class OngekiGachaConfig():
class OngekiGachaConfig:
def __init__(self, parent_config: "OngekiConfig") -> None:
self.__config = parent_config
@property
def enabled_gachas(self) -> List[int]:
return CoreConfig.get_config_field(self.__config, 'ongeki', 'gachas', 'enabled_gachas', default=[])
return CoreConfig.get_config_field(
self.__config, "ongeki", "gachas", "enabled_gachas", default=[]
)
class OngekiConfig(dict):

View File

@ -2,7 +2,7 @@ from typing import Final, Dict
from enum import Enum
class OngekiConstants():
class OngekiConstants:
GAME_CODE = "SDDT"
CONFIG_NAME = "ongeki.yaml"
@ -16,28 +16,31 @@ class OngekiConstants():
VER_ONGEKI_BRIGHT = 6
VER_ONGEKI_BRIGHT_MEMORY = 7
EVT_TYPES: Enum = Enum('EVT_TYPES', [
'None',
'Announcement',
'Movie',
'AddMyList',
'UnlockChapter',
'JewelEvent',
'RankingEvent',
'AcceptRankingEvent',
'UnlockMusic',
'UnlockCard',
'UnlockTrophy',
'UnlockNamePlate',
'UnlockLimitBreakItem',
'MissionEvent',
'DailyBonus',
'UnlockBossLockEarly',
'UnlockPurchaseItem',
'TechChallengeEvent',
'AcceptTechChallengeEvent',
'SilverJewelEvent',
])
EVT_TYPES: Enum = Enum(
"EVT_TYPES",
[
"None",
"Announcement",
"Movie",
"AddMyList",
"UnlockChapter",
"JewelEvent",
"RankingEvent",
"AcceptRankingEvent",
"UnlockMusic",
"UnlockCard",
"UnlockTrophy",
"UnlockNamePlate",
"UnlockLimitBreakItem",
"MissionEvent",
"DailyBonus",
"UnlockBossLockEarly",
"UnlockPurchaseItem",
"TechChallengeEvent",
"AcceptTechChallengeEvent",
"SilverJewelEvent",
],
)
class CM_GACHA_KINDS(Enum):
Normal = 0
@ -61,8 +64,16 @@ class OngekiConstants():
Master = 3
Lunatic = 10
VERSION_NAMES = ("ONGEKI", "ONGEKI+", "ONGEKI Summer", "ONGEKI Summer+", "ONGEKI Red", "ONGEKI Red+",
"ONGEKI Bright", "ONGEKI Bright Memory")
VERSION_NAMES = (
"ONGEKI",
"ONGEKI+",
"ONGEKI Summer",
"ONGEKI Summer+",
"ONGEKI Red",
"ONGEKI Red+",
"ONGEKI Bright",
"ONGEKI Bright Memory",
)
@classmethod
def game_ver_to_string(cls, ver: int):

View File

@ -3,6 +3,7 @@ from core.config import CoreConfig
from titles.ongeki.schema import OngekiItemData, OngekiProfileData, OngekiScoreData
from titles.ongeki.schema import OngekiStaticData, OngekiLogData
class OngekiData(Data):
def __init__(self, cfg: CoreConfig) -> None:
super().__init__(cfg)
@ -11,4 +12,4 @@ class OngekiData(Data):
self.profile = OngekiProfileData(cfg, self.session)
self.score = OngekiScoreData(cfg, self.session)
self.static = OngekiStaticData(cfg, self.session)
self.log = OngekiLogData(cfg, self.session)
self.log = OngekiLogData(cfg, self.session)

View File

@ -21,12 +21,15 @@ from titles.ongeki.redplus import OngekiRedPlus
from titles.ongeki.bright import OngekiBright
from titles.ongeki.brightmemory import OngekiBrightMemory
class OngekiServlet():
class OngekiServlet:
def __init__(self, core_cfg: CoreConfig, cfg_dir: str) -> None:
self.core_cfg = core_cfg
self.game_cfg = OngekiConfig()
if path.exists(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}"):
self.game_cfg.update(yaml.safe_load(open(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}")))
self.game_cfg.update(
yaml.safe_load(open(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}"))
)
self.versions = [
OngekiBase(core_cfg, self.game_cfg),
@ -42,34 +45,52 @@ class OngekiServlet():
self.logger = logging.getLogger("ongeki")
log_fmt_str = "[%(asctime)s] Ongeki | %(levelname)s | %(message)s"
log_fmt = logging.Formatter(log_fmt_str)
fileHandler = TimedRotatingFileHandler("{0}/{1}.log".format(self.core_cfg.server.log_dir, "ongeki"), encoding='utf8',
when="d", backupCount=10)
fileHandler = TimedRotatingFileHandler(
"{0}/{1}.log".format(self.core_cfg.server.log_dir, "ongeki"),
encoding="utf8",
when="d",
backupCount=10,
)
fileHandler.setFormatter(log_fmt)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(log_fmt)
self.logger.addHandler(fileHandler)
self.logger.addHandler(consoleHandler)
self.logger.setLevel(self.game_cfg.server.loglevel)
coloredlogs.install(level=self.game_cfg.server.loglevel, logger=self.logger, fmt=log_fmt_str)
coloredlogs.install(
level=self.game_cfg.server.loglevel, logger=self.logger, fmt=log_fmt_str
)
@classmethod
def get_allnet_info(cls, game_code: str, core_cfg: CoreConfig, cfg_dir: str) -> Tuple[bool, str, str]:
def get_allnet_info(
cls, game_code: str, core_cfg: CoreConfig, cfg_dir: str
) -> Tuple[bool, str, str]:
game_cfg = OngekiConfig()
if path.exists(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}"):
game_cfg.update(yaml.safe_load(open(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}")))
game_cfg.update(
yaml.safe_load(open(f"{cfg_dir}/{OngekiConstants.CONFIG_NAME}"))
)
if not game_cfg.server.enable:
return (False, "", "")
if core_cfg.server.is_develop:
return (True, f"http://{core_cfg.title.hostname}:{core_cfg.title.port}/{game_code}/$v/", f"{core_cfg.title.hostname}:{core_cfg.title.port}/")
return (True, f"http://{core_cfg.title.hostname}/{game_code}/$v/", f"{core_cfg.title.hostname}/")
return (
True,
f"http://{core_cfg.title.hostname}:{core_cfg.title.port}/{game_code}/$v/",
f"{core_cfg.title.hostname}:{core_cfg.title.port}/",
)
return (
True,
f"http://{core_cfg.title.hostname}/{game_code}/$v/",
f"{core_cfg.title.hostname}/",
)
def render_POST(self, request: Request, version: int, url_path: str) -> bytes:
if url_path.lower() == "/ping":
@ -80,39 +101,41 @@ class OngekiServlet():
internal_ver = 0
endpoint = url_split[len(url_split) - 1]
if version < 105: # 1.0
if version < 105: # 1.0
internal_ver = OngekiConstants.VER_ONGEKI
elif version >= 105 and version < 110: # Plus
elif version >= 105 and version < 110: # Plus
internal_ver = OngekiConstants.VER_ONGEKI_PLUS
elif version >= 110 and version < 115: # Summer
elif version >= 110 and version < 115: # Summer
internal_ver = OngekiConstants.VER_ONGEKI_SUMMER
elif version >= 115 and version < 120: # Summer Plus
elif version >= 115 and version < 120: # Summer Plus
internal_ver = OngekiConstants.VER_ONGEKI_SUMMER_PLUS
elif version >= 120 and version < 125: # Red
elif version >= 120 and version < 125: # Red
internal_ver = OngekiConstants.VER_ONGEKI_RED
elif version >= 125 and version < 130: # Red Plus
elif version >= 125 and version < 130: # Red Plus
internal_ver = OngekiConstants.VER_ONGEKI_RED_PLUS
elif version >= 130 and version < 135: # Bright
elif version >= 130 and version < 135: # Bright
internal_ver = OngekiConstants.VER_ONGEKI_BRIGHT
elif version >= 135 and version < 140: # Bright Memory
elif version >= 135 and version < 140: # Bright Memory
internal_ver = OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY
if all(c in string.hexdigits for c in endpoint) and len(endpoint) == 32:
# If we get a 32 character long hex string, it's a hash and we're
# doing encrypted. The likelyhood of false positives is low but
# If we get a 32 character long hex string, it's a hash and we're
# doing encrypted. The likelyhood of false positives is low but
# technically not 0
self.logger.error("Encryption not supported at this time")
return b""
try:
try:
unzip = zlib.decompress(req_raw)
except zlib.error as e:
self.logger.error(f"Failed to decompress v{version} {endpoint} request -> {e}")
self.logger.error(
f"Failed to decompress v{version} {endpoint} request -> {e}"
)
return zlib.compress(b'{"stat": "0"}')
req_data = json.loads(unzip)
self.logger.info(f"v{version} {endpoint} request - {req_data}")
func_to_find = "handle_" + inflection.underscore(endpoint) + "_request"
@ -128,13 +151,10 @@ class OngekiServlet():
except Exception as e:
self.logger.error(f"Error handling v{version} method {endpoint} - {e}")
return zlib.compress(b'{"stat": "0"}')
if resp == None:
resp = {'returnCode': 1}
resp = {"returnCode": 1}
self.logger.info(f"Response {resp}")
return zlib.compress(json.dumps(resp, ensure_ascii=False).encode("utf-8"))

View File

@ -5,11 +5,12 @@ from titles.ongeki.base import OngekiBase
from titles.ongeki.const import OngekiConstants
from titles.ongeki.config import OngekiConfig
class OngekiPlus(OngekiBase):
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
super().__init__(core_cfg, game_cfg)
self.version = OngekiConstants.VER_ONGEKI_PLUS
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
ret = super().handle_get_game_setting_api_request(data)
ret["gameSetting"]["dataVersion"] = "1.05.00"

View File

@ -13,14 +13,21 @@ from titles.ongeki.config import OngekiConfig
class OngekiReader(BaseReader):
def __init__(self, config: CoreConfig, version: int, bin_dir: Optional[str],
opt_dir: Optional[str], extra: Optional[str]) -> None:
def __init__(
self,
config: CoreConfig,
version: int,
bin_dir: Optional[str],
opt_dir: Optional[str],
extra: Optional[str],
) -> None:
super().__init__(config, version, bin_dir, opt_dir, extra)
self.data = OngekiData(config)
try:
self.logger.info(
f"Start importer for {OngekiConstants.game_ver_to_string(version)}")
f"Start importer for {OngekiConstants.game_ver_to_string(version)}"
)
except IndexError:
self.logger.error(f"Invalid ongeki version {version}")
exit(1)
@ -42,14 +49,14 @@ class OngekiReader(BaseReader):
self.logger.info(f"Reading cards from {base_dir}...")
version_ids = {
'1000': OngekiConstants.VER_ONGEKI,
'1005': OngekiConstants.VER_ONGEKI_PLUS,
'1010': OngekiConstants.VER_ONGEKI_SUMMER,
'1015': OngekiConstants.VER_ONGEKI_SUMMER_PLUS,
'1020': OngekiConstants.VER_ONGEKI_RED,
'1025': OngekiConstants.VER_ONGEKI_RED_PLUS,
'1030': OngekiConstants.VER_ONGEKI_BRIGHT,
'1035': OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY
"1000": OngekiConstants.VER_ONGEKI,
"1005": OngekiConstants.VER_ONGEKI_PLUS,
"1010": OngekiConstants.VER_ONGEKI_SUMMER,
"1015": OngekiConstants.VER_ONGEKI_SUMMER_PLUS,
"1020": OngekiConstants.VER_ONGEKI_RED,
"1025": OngekiConstants.VER_ONGEKI_RED_PLUS,
"1030": OngekiConstants.VER_ONGEKI_BRIGHT,
"1035": OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY,
}
for root, dirs, files in os.walk(base_dir):
@ -58,34 +65,39 @@ class OngekiReader(BaseReader):
with open(f"{root}/{dir}/Card.xml", "r", encoding="utf-8") as f:
troot = ET.fromstring(f.read())
card_id = int(troot.find('Name').find('id').text)
card_id = int(troot.find("Name").find("id").text)
# skip already existing cards
if self.data.static.get_card(
OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY, card_id) is not None:
if (
self.data.static.get_card(
OngekiConstants.VER_ONGEKI_BRIGHT_MEMORY, card_id
)
is not None
):
self.logger.info(f"Card {card_id} already added, skipping")
continue
name = troot.find('Name').find('str').text
chara_id = int(troot.find('CharaID').find('id').text)
nick_name = troot.find('NickName').text
school = troot.find('School').find('str').text
attribute = troot.find('Attribute').text
gakunen = troot.find('Gakunen').find('str').text
name = troot.find("Name").find("str").text
chara_id = int(troot.find("CharaID").find("id").text)
nick_name = troot.find("NickName").text
school = troot.find("School").find("str").text
attribute = troot.find("Attribute").text
gakunen = troot.find("Gakunen").find("str").text
rarity = OngekiConstants.RARITY_TYPES[
troot.find('Rarity').text].value
troot.find("Rarity").text
].value
level_param = []
for lvl in troot.find('LevelParam').findall('int'):
for lvl in troot.find("LevelParam").findall("int"):
level_param.append(lvl.text)
skill_id = int(troot.find('SkillID').find('id').text)
cho_kai_ka_skill_id = int(troot.find('ChoKaikaSkillID').find('id').text)
skill_id = int(troot.find("SkillID").find("id").text)
cho_kai_ka_skill_id = int(
troot.find("ChoKaikaSkillID").find("id").text
)
version = version_ids[
troot.find('VersionID').find('id').text]
card_number = troot.find('CardNumberString').text
version = version_ids[troot.find("VersionID").find("id").text]
card_number = troot.find("CardNumberString").text
self.data.static.put_card(
version,
@ -97,10 +109,10 @@ class OngekiReader(BaseReader):
attribute=attribute,
gakunen=gakunen,
rarity=rarity,
levelParam=','.join(level_param),
levelParam=",".join(level_param),
skillId=skill_id,
choKaikaSkillId=cho_kai_ka_skill_id,
cardNumber=card_number
cardNumber=card_number,
)
self.logger.info(f"Added card {card_id}")
@ -113,13 +125,13 @@ class OngekiReader(BaseReader):
with open(f"{root}/{dir}/Event.xml", "r", encoding="utf-8") as f:
troot = ET.fromstring(f.read())
name = troot.find('Name').find('str').text
id = int(troot.find('Name').find('id').text)
event_type = OngekiConstants.EVT_TYPES[troot.find(
'EventType').text].value
name = troot.find("Name").find("str").text
id = int(troot.find("Name").find("id").text)
event_type = OngekiConstants.EVT_TYPES[
troot.find("EventType").text
].value
self.data.static.put_event(
self.version, id, event_type, name)
self.data.static.put_event(self.version, id, event_type, name)
self.logger.info(f"Added event {id}")
def read_music(self, base_dir: str) -> None:
@ -138,15 +150,15 @@ class OngekiReader(BaseReader):
if root is None:
continue
name = troot.find('Name')
song_id = name.find('id').text
title = name.find('str').text
artist = troot.find('ArtistName').find('str').text
genre = troot.find('Genre').find('str').text
name = troot.find("Name")
song_id = name.find("id").text
title = name.find("str").text
artist = troot.find("ArtistName").find("str").text
genre = troot.find("Genre").find("str").text
fumens = troot.find("FumenData")
for fumens_data in fumens.findall('FumenData'):
path = fumens_data.find('FumenFile').find('path').text
for fumens_data in fumens.findall("FumenData"):
path = fumens_data.find("FumenFile").find("path").text
if path is None or not os.path.exists(f"{root}/{dir}/{path}"):
continue
@ -156,6 +168,6 @@ class OngekiReader(BaseReader):
)
self.data.static.put_chart(
self.version, song_id, chart_id, title, artist, genre, level)
self.logger.info(
f"Added song {song_id} chart {chart_id}")
self.version, song_id, chart_id, title, artist, genre, level
)
self.logger.info(f"Added song {song_id} chart {chart_id}")

View File

@ -5,11 +5,12 @@ from titles.ongeki.base import OngekiBase
from titles.ongeki.const import OngekiConstants
from titles.ongeki.config import OngekiConfig
class OngekiRed(OngekiBase):
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
super().__init__(core_cfg, game_cfg)
self.version = OngekiConstants.VER_ONGEKI_RED
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
ret = super().handle_get_game_setting_api_request(data)
ret["gameSetting"]["dataVersion"] = "1.20.00"

View File

@ -5,11 +5,12 @@ from titles.ongeki.base import OngekiBase
from titles.ongeki.const import OngekiConstants
from titles.ongeki.config import OngekiConfig
class OngekiRedPlus(OngekiBase):
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
super().__init__(core_cfg, game_cfg)
self.version = OngekiConstants.VER_ONGEKI_RED_PLUS
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
ret = super().handle_get_game_setting_api_request(data)
ret["gameSetting"]["dataVersion"] = "1.25.00"

View File

@ -4,4 +4,10 @@ from titles.ongeki.schema.static import OngekiStaticData
from titles.ongeki.schema.score import OngekiScoreData
from titles.ongeki.schema.log import OngekiLogData
__all__ = [OngekiProfileData, OngekiItemData, OngekiStaticData, OngekiScoreData, OngekiLogData]
__all__ = [
OngekiProfileData,
OngekiItemData,
OngekiStaticData,
OngekiScoreData,
OngekiLogData,
]

View File

@ -28,7 +28,7 @@ card = Table(
Column("isAcquired", Boolean),
Column("created", String(25)),
UniqueConstraint("user", "cardId", name="ongeki_user_card_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
deck = Table(
@ -41,7 +41,7 @@ deck = Table(
Column("cardId2", Integer),
Column("cardId3", Integer),
UniqueConstraint("user", "deckId", name="ongeki_user_deck_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
character = Table(
@ -59,10 +59,10 @@ character = Table(
Column("intimateCountDate", String(25)),
Column("isNew", Boolean),
UniqueConstraint("user", "characterId", name="ongeki_user_character_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
boss = Table (
boss = Table(
"ongeki_user_boss",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
@ -72,10 +72,10 @@ boss = Table (
Column("isClear", Boolean),
Column("eventId", Integer),
UniqueConstraint("user", "musicId", "eventId", name="ongeki_user_boss_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
story = Table (
story = Table(
"ongeki_user_story",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
@ -87,7 +87,7 @@ story = Table (
Column("lastPlayMusicCategory", Integer),
Column("lastPlayMusicLevel", Integer),
UniqueConstraint("user", "storyId", name="ongeki_user_story_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
chapter = Table(
@ -105,7 +105,7 @@ chapter = Table(
Column("skipTiming1", Integer),
Column("skipTiming2", Integer),
UniqueConstraint("user", "chapterId", name="ongeki_user_chapter_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
memorychapter = Table(
@ -126,7 +126,7 @@ memorychapter = Table(
Column("lastPlayMusicLevel", Integer),
Column("lastPlayMusicCategory", Integer),
UniqueConstraint("user", "chapterId", name="ongeki_user_memorychapter_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
item = Table(
@ -139,7 +139,7 @@ item = Table(
Column("stock", Integer),
Column("isValid", Boolean),
UniqueConstraint("user", "itemKind", "itemId", name="ongeki_user_item_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
music_item = Table(
@ -150,7 +150,7 @@ music_item = Table(
Column("musicId", Integer),
Column("status", Integer),
UniqueConstraint("user", "musicId", name="ongeki_user_music_item_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
login_bonus = Table(
@ -162,7 +162,7 @@ login_bonus = Table(
Column("bonusCount", Integer),
Column("lastUpdateDate", String(25)),
UniqueConstraint("user", "bonusId", name="ongeki_user_login_bonus_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
event_point = Table(
@ -174,7 +174,7 @@ event_point = Table(
Column("point", Integer),
Column("isRankingRewarded", Boolean),
UniqueConstraint("user", "eventId", name="ongeki_user_event_point_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
mission_point = Table(
@ -185,7 +185,7 @@ mission_point = Table(
Column("eventId", Integer),
Column("point", Integer),
UniqueConstraint("user", "eventId", name="ongeki_user_mission_point_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
scenerio = Table(
@ -196,7 +196,7 @@ scenerio = Table(
Column("scenarioId", Integer),
Column("playCount", Integer),
UniqueConstraint("user", "scenarioId", name="ongeki_user_scenerio_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
trade_item = Table(
@ -207,8 +207,10 @@ trade_item = Table(
Column("chapterId", Integer),
Column("tradeItemId", Integer),
Column("tradeCount", Integer),
UniqueConstraint("user", "chapterId", "tradeItemId", name="ongeki_user_trade_item_uk"),
mysql_charset='utf8mb4'
UniqueConstraint(
"user", "chapterId", "tradeItemId", name="ongeki_user_trade_item_uk"
),
mysql_charset="utf8mb4",
)
event_music = Table(
@ -224,8 +226,10 @@ event_music = Table(
Column("platinumScoreMax", Integer),
Column("techRecordDate", String(25)),
Column("isTechNewRecord", Boolean),
UniqueConstraint("user", "eventId", "type", "musicId", "level", name="ongeki_user_event_music"),
mysql_charset='utf8mb4'
UniqueConstraint(
"user", "eventId", "type", "musicId", "level", name="ongeki_user_event_music"
),
mysql_charset="utf8mb4",
)
tech_event = Table(
@ -240,14 +244,18 @@ tech_event = Table(
Column("isRankingRewarded", Boolean),
Column("isTotalTechNewRecord", Boolean),
UniqueConstraint("user", "eventId", name="ongeki_user_tech_event_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
gacha = Table(
"ongeki_user_gacha",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("gachaId", Integer, nullable=False),
Column("totalGachaCnt", Integer, server_default="0"),
Column("ceilingGachaCnt", Integer, server_default="0"),
@ -258,17 +266,21 @@ gacha = Table(
Column("elevenGachaCnt", Integer, server_default="0"),
Column("dailyGachaDate", TIMESTAMP, nullable=False, server_default=func.now()),
UniqueConstraint("user", "gachaId", name="ongeki_user_gacha_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
gacha_supply = Table(
"ongeki_user_gacha_supply",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("cardId", Integer, nullable=False),
UniqueConstraint("user", "cardId", name="ongeki_user_gacha_supply_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
@ -276,7 +288,11 @@ print_detail = Table(
"ongeki_user_print_detail",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("cardId", Integer, nullable=False),
Column("cardType", Integer, server_default="0"),
Column("printDate", TIMESTAMP, nullable=False),
@ -297,11 +313,11 @@ print_detail = Table(
Column("printOption9", Boolean, server_default="1"),
Column("printOption10", Boolean, server_default="0"),
UniqueConstraint("serialId", name="ongeki_user_print_detail_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
class OngekiItemData(BaseData):
class OngekiItemData(BaseData):
def put_card(self, aime_id: int, card_data: Dict) -> Optional[int]:
card_data["user"] = aime_id
@ -318,7 +334,8 @@ class OngekiItemData(BaseData):
sql = select(card).where(card.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_character(self, aime_id: int, character_data: Dict) -> Optional[int]:
@ -332,12 +349,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_character: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_characters(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(character).where(character.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_deck(self, aime_id: int, deck_data: Dict) -> Optional[int]:
@ -351,19 +369,21 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_deck: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_deck(self, aime_id: int, deck_id: int) -> Optional[Dict]:
sql = select(deck).where(and_(deck.c.user == aime_id, deck.c.deckId == deck_id))
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()
def get_decks(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(deck).where(deck.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_boss(self, aime_id: int, boss_data: Dict) -> Optional[int]:
@ -377,7 +397,7 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_boss: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def put_story(self, aime_id: int, story_data: Dict) -> Optional[int]:
story_data["user"] = aime_id
@ -389,12 +409,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_story: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_stories(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(story).where(story.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_chapter(self, aime_id: int, chapter_data: Dict) -> Optional[int]:
@ -408,12 +429,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_chapter: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_chapters(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(chapter).where(chapter.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_item(self, aime_id: int, item_data: Dict) -> Optional[int]:
@ -427,22 +449,26 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_item: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_item(self, aime_id: int, item_id: int, item_kind: int) -> Optional[Dict]:
sql = select(item).where(and_(item.c.user == aime_id, item.c.itemId == item_id))
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()
def get_items(self, aime_id: int, item_kind: int = None) -> Optional[List[Dict]]:
if item_kind is None:
sql = select(item).where(item.c.user == aime_id)
else:
sql = select(item).where(and_(item.c.user == aime_id, item.c.itemKind == item_kind))
sql = select(item).where(
and_(item.c.user == aime_id, item.c.itemKind == item_kind)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_music_item(self, aime_id: int, music_item_data: Dict) -> Optional[int]:
@ -456,12 +482,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_music_item: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_music_items(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(music_item).where(music_item.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_login_bonus(self, aime_id: int, login_bonus_data: Dict) -> Optional[int]:
@ -475,15 +502,18 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_login_bonus: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_login_bonuses(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(login_bonus).where(login_bonus.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_mission_point(self, aime_id: int, mission_point_data: Dict) -> Optional[int]:
def put_mission_point(
self, aime_id: int, mission_point_data: Dict
) -> Optional[int]:
mission_point_data["user"] = aime_id
sql = insert(mission_point).values(**mission_point_data)
@ -494,14 +524,15 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_mission_point: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_mission_points(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(mission_point).where(mission_point.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_event_point(self, aime_id: int, event_point_data: Dict) -> Optional[int]:
event_point_data["user"] = aime_id
@ -513,12 +544,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_event_point: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_event_points(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(event_point).where(event_point.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_scenerio(self, aime_id: int, scenerio_data: Dict) -> Optional[int]:
@ -532,12 +564,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_scenerio: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_scenerios(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(scenerio).where(scenerio.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_trade_item(self, aime_id: int, trade_item_data: Dict) -> Optional[int]:
@ -551,14 +584,15 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_trade_item: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_trade_items(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(trade_item).where(trade_item.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_event_music(self, aime_id: int, event_music_data: Dict) -> Optional[int]:
event_music_data["user"] = aime_id
@ -570,12 +604,13 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_event_music: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_event_music(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(event_music).where(event_music.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_tech_event(self, aime_id: int, tech_event_data: Dict) -> Optional[int]:
@ -589,22 +624,26 @@ class OngekiItemData(BaseData):
self.logger.warn(f"put_tech_event: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_tech_event(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(tech_event).where(tech_event.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_bosses(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(boss).where(boss.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_memorychapter(self, aime_id: int, memorychapter_data: Dict) -> Optional[int]:
def put_memorychapter(
self, aime_id: int, memorychapter_data: Dict
) -> Optional[int]:
memorychapter_data["user"] = aime_id
sql = insert(memorychapter).values(**memorychapter_data)
@ -625,10 +664,7 @@ class OngekiItemData(BaseData):
return result.fetchall()
def get_user_gacha(self, aime_id: int, gacha_id: int) -> Optional[Row]:
sql = gacha.select(and_(
gacha.c.user == aime_id,
gacha.c.gachaId == gacha_id
))
sql = gacha.select(and_(gacha.c.user == aime_id, gacha.c.gachaId == gacha_id))
result = self.execute(sql)
if result is None:
@ -652,15 +688,9 @@ class OngekiItemData(BaseData):
return result.fetchall()
def put_user_gacha(self, aime_id: int, gacha_id: int, **data) -> Optional[int]:
sql = insert(gacha).values(
user=aime_id,
gachaId=gacha_id,
**data)
sql = insert(gacha).values(user=aime_id, gachaId=gacha_id, **data)
conflict = sql.on_duplicate_key_update(
user=aime_id,
gachaId=gacha_id,
**data)
conflict = sql.on_duplicate_key_update(user=aime_id, gachaId=gacha_id, **data)
result = self.execute(conflict)
if result is None:
@ -668,20 +698,21 @@ class OngekiItemData(BaseData):
return None
return result.lastrowid
def put_user_print_detail(self, aime_id: int, serial_id: str,
user_print_data: Dict) -> Optional[int]:
def put_user_print_detail(
self, aime_id: int, serial_id: str, user_print_data: Dict
) -> Optional[int]:
sql = insert(print_detail).values(
user=aime_id,
serialId=serial_id,
**user_print_data)
user=aime_id, serialId=serial_id, **user_print_data
)
conflict = sql.on_duplicate_key_update(
user=aime_id,
serialId=serial_id,
**user_print_data)
user=aime_id, serialId=serial_id, **user_print_data
)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_user_print_detail: Failed to insert! aime_id: {aime_id}")
self.logger.warn(
f"put_user_print_detail: Failed to insert! aime_id: {aime_id}"
)
return None
return result.lastrowid

View File

@ -15,11 +15,13 @@ gp_log = Table(
Column("usedCredit", Integer),
Column("placeName", String(255)),
Column("trxnDate", String(255)),
Column("placeId", Integer), # Making this an FK would mess with people playing with default KC
Column("kind", Integer),
Column("pattern", Integer),
Column(
"placeId", Integer
), # Making this an FK would mess with people playing with default KC
Column("kind", Integer),
Column("pattern", Integer),
Column("currentGP", Integer),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
session_log = Table(
@ -32,12 +34,22 @@ session_log = Table(
Column("playDate", String(10)),
Column("userPlayDate", String(25)),
Column("isPaid", Boolean),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
class OngekiLogData(BaseData):
def put_gp_log(self, aime_id: Optional[int], used_credit: int, place_name: str, tx_date: str, place_id: int,
kind: int, pattern: int, current_gp: int) -> Optional[int]:
def put_gp_log(
self,
aime_id: Optional[int],
used_credit: int,
place_name: str,
tx_date: str,
place_id: int,
kind: int,
pattern: int,
current_gp: int,
) -> Optional[int]:
sql = insert(gp_log).values(
user=aime_id,
usedCredit=used_credit,
@ -51,5 +63,7 @@ class OngekiLogData(BaseData):
result = self.execute(sql)
if result is None:
self.logger.warn(f"put_gp_log: Failed to insert GP log! aime_id: {aime_id} kind {kind} pattern {pattern} current_gp {current_gp}")
return result.lastrowid
self.logger.warn(
f"put_gp_log: Failed to insert GP log! aime_id: {aime_id} kind {kind} pattern {pattern} current_gp {current_gp}"
)
return result.lastrowid

View File

@ -16,7 +16,11 @@ profile = Table(
"ongeki_profile_data",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("version", Integer, nullable=False),
Column("userName", String(8)),
Column("level", Integer),
@ -81,7 +85,7 @@ profile = Table(
Column("lastEmoneyCredit", Integer, server_default="0"),
Column("isDialogWatchedSuggestMemory", Boolean, server_default="0"),
UniqueConstraint("user", "version", name="ongeki_profile_profile_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
# No point setting defaults since the game sends everything on profile creation anyway
@ -89,7 +93,11 @@ option = Table(
"ongeki_profile_option",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("optionSet", Integer),
Column("speed", Integer),
Column("mirror", Integer),
@ -128,14 +136,18 @@ option = Table(
Column("stealthField", Integer),
Column("colorWallBright", Integer),
UniqueConstraint("user", name="ongeki_profile_option_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
activity = Table(
"ongeki_profile_activity",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("kind", Integer),
Column("activityId", Integer),
Column("sortNumber", Integer),
@ -144,40 +156,52 @@ activity = Table(
Column("param3", Integer),
Column("param4", Integer),
UniqueConstraint("user", "kind", "activityId", name="ongeki_profile_activity_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
recent_rating = Table(
"ongeki_profile_recent_rating",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("recentRating", JSON),
UniqueConstraint("user", name="ongeki_profile_recent_rating_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
rating_log = Table(
"ongeki_profile_rating_log",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("highestRating", Integer),
Column("dataVersion", String(10)),
UniqueConstraint("user", "dataVersion", name="ongeki_profile_rating_log_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
region = Table(
"ongeki_profile_region",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("regionId", Integer),
Column("playCount", Integer),
Column("created", String(25)),
UniqueConstraint("user", "regionId", name="ongeki_profile_region_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
training_room = Table(
@ -185,12 +209,12 @@ training_room = Table(
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("roomId", Integer),
Column("roomId", Integer),
Column("authKey", Integer),
Column("cardId", Integer),
Column("valueDate", String(25)),
UniqueConstraint("user", "roomId", name="ongeki_profile_training_room_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
kop = Table(
@ -199,14 +223,14 @@ kop = Table(
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("authKey", Integer),
Column("kopId", Integer),
Column("kopId", Integer),
Column("areaId", Integer),
Column("totalTechScore", Integer),
Column("totalPlatinumScore", Integer),
Column("techRecordDate", String(25)),
Column("isTotalTechNewRecord", Boolean),
UniqueConstraint("user", "kopId", name="ongeki_profile_kop_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
rival = Table(
@ -214,86 +238,112 @@ rival = Table(
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("rivalUserId", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column(
"rivalUserId",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
),
UniqueConstraint("user", "rivalUserId", name="ongeki_profile_rival_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
class OngekiProfileData(BaseData):
def __init__(self, cfg: CoreConfig, conn: Connection) -> None:
super().__init__(cfg, conn)
self.date_time_format_ext = "%Y-%m-%d %H:%M:%S.%f" # needs to be lopped off at [:-5]
self.date_time_format_ext = (
"%Y-%m-%d %H:%M:%S.%f" # needs to be lopped off at [:-5]
)
self.date_time_format_short = "%Y-%m-%d"
def get_profile_name(self, aime_id: int, version: int) -> Optional[str]:
sql = select(profile.c.userName).where(and_(profile.c.user == aime_id, profile.c.version == version))
result = self.execute(sql)
if result is None: return None
row = result.fetchone()
if row is None: return None
return row["userName"]
def get_profile_preview(self, aime_id: int, version: int) -> Optional[Row]:
sql = select([profile, option]).join(option, profile.c.user == option.c.user).filter(
sql = select(profile.c.userName).where(
and_(profile.c.user == aime_id, profile.c.version == version)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
row = result.fetchone()
if row is None:
return None
return row["userName"]
def get_profile_preview(self, aime_id: int, version: int) -> Optional[Row]:
sql = (
select([profile, option])
.join(option, profile.c.user == option.c.user)
.filter(and_(profile.c.user == aime_id, profile.c.version == version))
)
result = self.execute(sql)
if result is None:
return None
return result.fetchone()
def get_profile_data(self, aime_id: int, version: int) -> Optional[Row]:
sql = select(profile).where(and_(
profile.c.user == aime_id,
profile.c.version == version,
))
sql = select(profile).where(
and_(
profile.c.user == aime_id,
profile.c.version == version,
)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()
def get_profile_options(self, aime_id: int) -> Optional[Row]:
sql = select(option).where(and_(
option.c.user == aime_id,
))
sql = select(option).where(
and_(
option.c.user == aime_id,
)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()
def get_profile_recent_rating(self, aime_id: int) -> Optional[List[Row]]:
sql = select(recent_rating).where(recent_rating.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()
def get_profile_rating_log(self, aime_id: int) -> Optional[List[Row]]:
sql = select(rating_log).where(recent_rating.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_profile_activity(self, aime_id: int, kind: int = None) -> Optional[List[Row]]:
sql = select(activity).where(and_(
activity.c.user == aime_id,
(activity.c.kind == kind) if kind is not None else True
))
def get_profile_activity(
self, aime_id: int, kind: int = None
) -> Optional[List[Row]]:
sql = select(activity).where(
and_(
activity.c.user == aime_id,
(activity.c.kind == kind) if kind is not None else True,
)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_kop(self, aime_id: int) -> Optional[List[Row]]:
sql = select(kop).where(kop.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_rivals(self, aime_id: int) -> Optional[List[Row]]:
@ -326,48 +376,62 @@ class OngekiProfileData(BaseData):
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_profile_options: Failed to update! aime_id: {aime_id}")
self.logger.warn(
f"put_profile_options: Failed to update! aime_id: {aime_id}"
)
return None
return result.lastrowid
def put_profile_recent_rating(self, aime_id: int, recent_rating_data: List[Dict]) -> Optional[int]:
def put_profile_recent_rating(
self, aime_id: int, recent_rating_data: List[Dict]
) -> Optional[int]:
sql = insert(recent_rating).values(
user=aime_id,
recentRating=recent_rating_data
user=aime_id, recentRating=recent_rating_data
)
conflict = sql.on_duplicate_key_update(
recentRating=recent_rating_data
)
conflict = sql.on_duplicate_key_update(recentRating=recent_rating_data)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_profile_recent_rating: failed to update recent rating! aime_id {aime_id}")
self.logger.warn(
f"put_profile_recent_rating: failed to update recent rating! aime_id {aime_id}"
)
return None
return result.lastrowid
def put_profile_bp_list(self, aime_id: int, bp_base_list: List[Dict]) -> Optional[int]:
def put_profile_bp_list(
self, aime_id: int, bp_base_list: List[Dict]
) -> Optional[int]:
pass
def put_profile_rating_log(self, aime_id: int, data_version: str, highest_rating: int) -> Optional[int]:
def put_profile_rating_log(
self, aime_id: int, data_version: str, highest_rating: int
) -> Optional[int]:
sql = insert(rating_log).values(
user=aime_id,
dataVersion=data_version,
highestRating=highest_rating
user=aime_id, dataVersion=data_version, highestRating=highest_rating
)
conflict = sql.on_duplicate_key_update(
highestRating=highest_rating
)
conflict = sql.on_duplicate_key_update(highestRating=highest_rating)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_profile_rating_log: failed to update rating log! aime_id {aime_id} data_version {data_version} highest_rating {highest_rating}")
self.logger.warn(
f"put_profile_rating_log: failed to update rating log! aime_id {aime_id} data_version {data_version} highest_rating {highest_rating}"
)
return None
return result.lastrowid
def put_profile_activity(self, aime_id: int, kind: int, activity_id: int, sort_num: int,
p1: int, p2: int, p3: int, p4: int) -> Optional[int]:
def put_profile_activity(
self,
aime_id: int,
kind: int,
activity_id: int,
sort_num: int,
p1: int,
p2: int,
p3: int,
p4: int,
) -> Optional[int]:
sql = insert(activity).values(
user=aime_id,
kind=kind,
@ -376,29 +440,24 @@ class OngekiProfileData(BaseData):
param1=p1,
param2=p2,
param3=p3,
param4=p4
param4=p4,
)
conflict = sql.on_duplicate_key_update(
sortNumber=sort_num,
param1=p1,
param2=p2,
param3=p3,
param4=p4
sortNumber=sort_num, param1=p1, param2=p2, param3=p3, param4=p4
)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_profile_activity: failed to put activity! aime_id {aime_id} kind {kind} activity_id {activity_id}")
self.logger.warn(
f"put_profile_activity: failed to put activity! aime_id {aime_id} kind {kind} activity_id {activity_id}"
)
return None
return result.lastrowid
def put_profile_region(self, aime_id: int, region: int, date: str) -> Optional[int]:
sql = insert(activity).values(
user=aime_id,
region=region,
playCount=1,
created=date
user=aime_id, region=region, playCount=1, created=date
)
conflict = sql.on_duplicate_key_update(
@ -407,10 +466,12 @@ class OngekiProfileData(BaseData):
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_profile_region: failed to update! aime_id {aime_id} region {region}")
self.logger.warn(
f"put_profile_region: failed to update! aime_id {aime_id} region {region}"
)
return None
return result.lastrowid
def put_training_room(self, aime_id: int, room_detail: Dict) -> Optional[int]:
room_detail["user"] = aime_id
@ -422,7 +483,7 @@ class OngekiProfileData(BaseData):
self.logger.warn(f"put_best_score: Failed to add score! aime_id: {aime_id}")
return None
return result.lastrowid
def put_kop(self, aime_id: int, kop_data: Dict) -> Optional[int]:
kop_data["user"] = aime_id
@ -434,17 +495,16 @@ class OngekiProfileData(BaseData):
self.logger.warn(f"put_kop: Failed to add score! aime_id: {aime_id}")
return None
return result.lastrowid
def put_rival(self, aime_id: int, rival_id: int) -> Optional[int]:
sql = insert(rival).values(
user = aime_id,
rivalUserId = rival_id
)
conflict = sql.on_duplicate_key_update(rival = rival_id)
def put_rival(self, aime_id: int, rival_id: int) -> Optional[int]:
sql = insert(rival).values(user=aime_id, rivalUserId=rival_id)
conflict = sql.on_duplicate_key_update(rival=rival_id)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_rival: failed to update! aime_id: {aime_id}, rival_id: {rival_id}")
self.logger.warn(
f"put_rival: failed to update! aime_id: {aime_id}, rival_id: {rival_id}"
)
return None
return result.lastrowid

View File

@ -11,14 +11,18 @@ score_best = Table(
"ongeki_score_best",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("musicId", Integer, nullable=False),
Column("level", Integer, nullable=False),
Column("playCount", Integer, nullable=False),
Column("playCount", Integer, nullable=False),
Column("techScoreMax", Integer, nullable=False),
Column("techScoreRank", Integer, nullable=False),
Column("battleScoreMax", Integer, nullable=False),
Column("battleScoreRank", Integer, nullable=False),
Column("battleScoreRank", Integer, nullable=False),
Column("maxComboCount", Integer, nullable=False),
Column("maxOverKill", Float, nullable=False),
Column("maxTeamOverKill", Float, nullable=False),
@ -30,14 +34,18 @@ score_best = Table(
Column("isStoryWatched", Boolean, nullable=False),
Column("platinumScoreMax", Integer),
UniqueConstraint("user", "musicId", "level", name="ongeki_best_score_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
playlog = Table(
"ongeki_score_playlog",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("sortNumber", Integer),
Column("placeId", Integer),
Column("placeName", String(255)),
@ -99,25 +107,30 @@ playlog = Table(
Column("battlePoint", Integer),
Column("platinumScore", Integer),
Column("platinumScoreMax", Integer),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
tech_count = Table(
"ongeki_score_tech_count",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"), nullable=False),
Column(
"user",
ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade"),
nullable=False,
),
Column("levelId", Integer, nullable=False),
Column("allBreakCount", Integer),
Column("allBreakPlusCount", Integer),
UniqueConstraint("user", "levelId", name="ongeki_tech_count_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
class OngekiScoreData(BaseData):
def get_tech_count(self, aime_id: int) -> Optional[List[Dict]]:
return []
def put_tech_count(self, aime_id: int, tech_count_data: Dict) -> Optional[int]:
tech_count_data["user"] = aime_id
@ -129,17 +142,20 @@ class OngekiScoreData(BaseData):
self.logger.warn(f"put_tech_count: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def get_best_scores(self, aime_id: int) -> Optional[List[Dict]]:
sql = select(score_best).where(score_best.c.user == aime_id)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_best_score(self, aime_id: int, song_id: int, chart_id: int = None) -> Optional[List[Dict]]:
def get_best_score(
self, aime_id: int, song_id: int, chart_id: int = None
) -> Optional[List[Dict]]:
return []
def put_best_score(self, aime_id: int, music_detail: Dict) -> Optional[int]:
music_detail["user"] = aime_id
@ -161,4 +177,4 @@ class OngekiScoreData(BaseData):
if result is None:
self.logger.warn(f"put_playlog: Failed to add playlog! aime_id: {aime_id}")
return None
return result.lastrowid
return result.lastrowid

View File

@ -18,7 +18,7 @@ events = Table(
Column("name", String(255)),
Column("enabled", Boolean, server_default="1"),
UniqueConstraint("version", "eventId", "type", name="ongeki_static_events_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
@ -34,7 +34,7 @@ music = Table(
Column("genre", String(255)),
Column("level", Float),
UniqueConstraint("version", "songId", "chartId", name="ongeki_static_music_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
gachas = Table(
@ -57,7 +57,7 @@ gachas = Table(
Column("noticeEndDate", TIMESTAMP, server_default="2038-01-01 00:00:00.0"),
Column("convertEndDate", TIMESTAMP, server_default="2038-01-01 00:00:00.0"),
UniqueConstraint("version", "gachaId", "gachaName", name="ongeki_static_gachas_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
gacha_cards = Table(
@ -71,7 +71,7 @@ gacha_cards = Table(
Column("isPickup", Boolean, server_default="0"),
Column("isSelect", Boolean, server_default="0"),
UniqueConstraint("gachaId", "cardId", name="ongeki_static_gacha_cards_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
cards = Table(
@ -92,16 +92,13 @@ cards = Table(
Column("choKaikaSkillId", Integer, nullable=False),
Column("cardNumber", String(255)),
UniqueConstraint("version", "cardId", name="ongeki_static_cards_uk"),
mysql_charset='utf8mb4'
mysql_charset="utf8mb4",
)
class OngekiStaticData(BaseData):
def put_card(self, version: int, card_id: int, **card_data) -> Optional[int]:
sql = insert(cards).values(
version=version,
cardId=card_id,
**card_data)
sql = insert(cards).values(version=version, cardId=card_id, **card_data)
conflict = sql.on_duplicate_key_update(**card_data)
@ -112,10 +109,7 @@ class OngekiStaticData(BaseData):
return result.lastrowid
def get_card(self, version: int, card_id: int) -> Optional[Dict]:
sql = cards.select(and_(
cards.c.version <= version,
cards.c.cardId == card_id
))
sql = cards.select(and_(cards.c.version <= version, cards.c.cardId == card_id))
result = self.execute(sql)
if result is None:
@ -126,10 +120,9 @@ class OngekiStaticData(BaseData):
if not card_number.startswith("[O.N.G.E.K.I.]"):
card_number = f"[O.N.G.E.K.I.]{card_number}"
sql = cards.select(and_(
cards.c.version <= version,
cards.c.cardNumber == card_number
))
sql = cards.select(
and_(cards.c.version <= version, cards.c.cardNumber == card_number)
)
result = self.execute(sql)
if result is None:
@ -137,10 +130,7 @@ class OngekiStaticData(BaseData):
return result.fetchone()
def get_card_by_name(self, version: int, name: str) -> Optional[Dict]:
sql = cards.select(and_(
cards.c.version <= version,
cards.c.name == name
))
sql = cards.select(and_(cards.c.version <= version, cards.c.name == name))
result = self.execute(sql)
if result is None:
@ -156,24 +146,27 @@ class OngekiStaticData(BaseData):
return result.fetchall()
def get_cards_by_rarity(self, version: int, rarity: int) -> Optional[List[Dict]]:
sql = cards.select(and_(
cards.c.version <= version,
cards.c.rarity == rarity
))
sql = cards.select(and_(cards.c.version <= version, cards.c.rarity == rarity))
result = self.execute(sql)
if result is None:
return None
return result.fetchall()
def put_gacha(self, version: int, gacha_id: int, gacha_name: int,
gacha_kind: int, **gacha_data) -> Optional[int]:
def put_gacha(
self,
version: int,
gacha_id: int,
gacha_name: int,
gacha_kind: int,
**gacha_data,
) -> Optional[int]:
sql = insert(gachas).values(
version=version,
gachaId=gacha_id,
gachaName=gacha_name,
kind=gacha_kind,
**gacha_data
**gacha_data,
)
conflict = sql.on_duplicate_key_update(
@ -181,7 +174,7 @@ class OngekiStaticData(BaseData):
gachaId=gacha_id,
gachaName=gacha_name,
kind=gacha_kind,
**gacha_data
**gacha_data,
)
result = self.execute(conflict)
@ -191,10 +184,9 @@ class OngekiStaticData(BaseData):
return result.lastrowid
def get_gacha(self, version: int, gacha_id: int) -> Optional[Dict]:
sql = gachas.select(and_(
gachas.c.version <= version,
gachas.c.gachaId == gacha_id
))
sql = gachas.select(
and_(gachas.c.version <= version, gachas.c.gachaId == gacha_id)
)
result = self.execute(sql)
if result is None:
@ -202,8 +194,7 @@ class OngekiStaticData(BaseData):
return result.fetchone()
def get_gachas(self, version: int) -> Optional[List[Dict]]:
sql = gachas.select(
gachas.c.version == version).order_by(
sql = gachas.select(gachas.c.version == version).order_by(
gachas.c.gachaId.asc()
)
@ -212,17 +203,13 @@ class OngekiStaticData(BaseData):
return None
return result.fetchall()
def put_gacha_card(self, gacha_id: int, card_id: int, **gacha_card) -> Optional[int]:
sql = insert(gacha_cards).values(
gachaId=gacha_id,
cardId=card_id,
**gacha_card
)
def put_gacha_card(
self, gacha_id: int, card_id: int, **gacha_card
) -> Optional[int]:
sql = insert(gacha_cards).values(gachaId=gacha_id, cardId=card_id, **gacha_card)
conflict = sql.on_duplicate_key_update(
gachaId=gacha_id,
cardId=card_id,
**gacha_card
gachaId=gacha_id, cardId=card_id, **gacha_card
)
result = self.execute(conflict)
@ -232,25 +219,25 @@ class OngekiStaticData(BaseData):
return result.lastrowid
def get_gacha_cards(self, gacha_id: int) -> Optional[List[Dict]]:
sql = gacha_cards.select(
gacha_cards.c.gachaId == gacha_id
)
sql = gacha_cards.select(gacha_cards.c.gachaId == gacha_id)
result = self.execute(sql)
if result is None:
return None
return result.fetchall()
def put_event(self, version: int, event_id: int, event_type: int, event_name: str) -> Optional[int]:
def put_event(
self, version: int, event_id: int, event_type: int, event_name: str
) -> Optional[int]:
sql = insert(events).values(
version = version,
eventId = event_id,
type = event_type,
name = event_name,
version=version,
eventId=event_id,
type=event_type,
name=event_name,
)
conflict = sql.on_duplicate_key_update(
name = event_name,
name=event_name,
)
result = self.execute(conflict)
@ -260,63 +247,88 @@ class OngekiStaticData(BaseData):
return result.lastrowid
def get_event(self, version: int, event_id: int) -> Optional[List[Dict]]:
sql = select(events).where(and_(events.c.version == version, events.c.eventId == event_id))
sql = select(events).where(
and_(events.c.version == version, events.c.eventId == event_id)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def get_events(self, version: int) -> Optional[List[Dict]]:
sql = select(events).where(events.c.version == version)
result = self.execute(sql)
if result is None: return None
return result.fetchall()
def get_enabled_events(self, version: int) -> Optional[List[Dict]]:
sql = select(events).where(and_(events.c.version == version, events.c.enabled == True))
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchall()
def put_chart(self, version: int, song_id: int, chart_id: int, title: str, artist: str, genre: str, level: float) -> Optional[int]:
def get_enabled_events(self, version: int) -> Optional[List[Dict]]:
sql = select(events).where(
and_(events.c.version == version, events.c.enabled == True)
)
result = self.execute(sql)
if result is None:
return None
return result.fetchall()
def put_chart(
self,
version: int,
song_id: int,
chart_id: int,
title: str,
artist: str,
genre: str,
level: float,
) -> Optional[int]:
sql = insert(music).values(
version = version,
songId = song_id,
chartId = chart_id,
title = title,
artist = artist,
genre = genre,
level = level,
version=version,
songId=song_id,
chartId=chart_id,
title=title,
artist=artist,
genre=genre,
level=level,
)
conflict = sql.on_duplicate_key_update(
title = title,
artist = artist,
genre = genre,
level = level,
title=title,
artist=artist,
genre=genre,
level=level,
)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"Failed to insert chart! song_id: {song_id}, chart_id: {chart_id}")
self.logger.warn(
f"Failed to insert chart! song_id: {song_id}, chart_id: {chart_id}"
)
return None
return result.lastrowid
def get_chart(self, version: int, song_id: int, chart_id: int = None) -> Optional[List[Dict]]:
def get_chart(
self, version: int, song_id: int, chart_id: int = None
) -> Optional[List[Dict]]:
pass
def get_music(self, version: int) -> Optional[List[Dict]]:
pass
def get_music_chart(self, version: int, song_id: int, chart_id: int) -> Optional[List[Row]]:
sql = select(music).where(and_(
music.c.version == version,
music.c.songId == song_id,
music.c.chartId == chart_id
))
def get_music_chart(
self, version: int, song_id: int, chart_id: int
) -> Optional[List[Row]]:
sql = select(music).where(
and_(
music.c.version == version,
music.c.songId == song_id,
music.c.chartId == chart_id,
)
)
result = self.execute(sql)
if result is None: return None
if result is None:
return None
return result.fetchone()

View File

@ -5,11 +5,12 @@ from titles.ongeki.base import OngekiBase
from titles.ongeki.const import OngekiConstants
from titles.ongeki.config import OngekiConfig
class OngekiSummer(OngekiBase):
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
super().__init__(core_cfg, game_cfg)
self.version = OngekiConstants.VER_ONGEKI_SUMMER
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
ret = super().handle_get_game_setting_api_request(data)
ret["gameSetting"]["dataVersion"] = "1.10.00"

View File

@ -5,11 +5,12 @@ from titles.ongeki.base import OngekiBase
from titles.ongeki.const import OngekiConstants
from titles.ongeki.config import OngekiConfig
class OngekiSummerPlus(OngekiBase):
def __init__(self, core_cfg: CoreConfig, game_cfg: OngekiConfig) -> None:
super().__init__(core_cfg, game_cfg)
self.version = OngekiConstants.VER_ONGEKI_SUMMER_PLUS
def handle_get_game_setting_api_request(self, data: Dict) -> Dict:
ret = super().handle_get_game_setting_api_request(data)
ret["gameSetting"]["dataVersion"] = "1.15.00"