Merge branch 'online' into idac

This commit is contained in:
Dniel97 2024-01-08 16:42:46 +01:00
commit 62937584bc
Signed by untrusted user: Dniel97
GPG Key ID: 6180B3C768FB2E08
4 changed files with 274 additions and 110 deletions

View File

@ -6,6 +6,9 @@ class IDACConstants():
VER_IDAC_SEASON_1 = 0 VER_IDAC_SEASON_1 = 0
VER_IDAC_SEASON_2 = 1 VER_IDAC_SEASON_2 = 1
BATTLE_MODE_ONLINE = 0
BATTLE_MODE_OFFLINE = 1
VERSION_STRING = ( VERSION_STRING = (
"Initial D THE ARCADE Season 1", "Initial D THE ARCADE Season 1",
"Initial D THE ARCADE Season 2", "Initial D THE ARCADE Season 2",

View File

@ -8,58 +8,82 @@ from core import CoreConfig
from titles.idac.season2 import IDACBase from titles.idac.season2 import IDACBase
from titles.idac.config import IDACConfig from titles.idac.config import IDACConfig
from random import randint
class IDACMatching(resource.Resource): class IDACMatching(resource.Resource):
isLeaf = True isLeaf = True
SessionQueue = {}
Rooms = {}
def __init__(self, cfg: CoreConfig, game_cfg: IDACConfig) -> None: def __init__(self, cfg: CoreConfig, game_cfg: IDACConfig) -> None:
self.core_config = cfg self.core_config = cfg
self.game_config = game_cfg self.game_config = game_cfg
self.base = IDACBase(cfg, game_cfg) self.base = IDACBase(cfg, game_cfg)
self.logger = logging.getLogger("idac") self.logger = logging.getLogger("idac")
self.queue = 0 def getMatchingState(self, machineSerial): #We use official state code here
if len(self.SessionQueue) == 1:
def get_matching_state(self): self.logger.info(f"IDAC Matching queued player {machineSerial}: empty dict, returned by default")
if self.queue >= 1: return self.SessionQueue[machineSerial]
self.queue -= 1 elif self.SessionQueue[machineSerial] == 0:
return 0 self.logger.info(f"IDAC Matching queued player {machineSerial}: matched player, returned by default")
return self.SessionQueue[machineSerial]
else: else:
return 1 for sessionID in self.SessionQueue.keys():
if sessionID == machineSerial:
continue
if self.SessionQueue[sessionID] == 1:
#uncomment these to process into actual game
#self.SessionQueue[machineSerial] = 0
#self.SessionQueue[sessionID] = 0
self.joinRoom(machineSerial, sessionID)
self.logger.info(f"IDAC Matching queued player {machineSerial}: rival {sessionID} found!! return matched state")
return self.SessionQueue[machineSerial]
self.logger.info(f"IDAC Matching queued player {machineSerial}: cannot find any rival, returned by default")
return self.SessionQueue[machineSerial]
def joinRoom(self, machineSerial, sessionID): #Random room name, It should be handled by game itself in later process
roomName = "INDTA-Zenkoku-Room" #+randint(1, 1001)
self.Rooms[machineSerial] = roomName
self.Rooms[sessionID] = roomName
def render_POST(self, req) -> bytes: def render_POST(self, req) -> bytes:
url = req.uri.decode() url = req.uri.decode()
req_data = json.loads(req.content.getvalue().decode()) req_data = json.loads(req.content.getvalue().decode())
header_application = self.decode_header(req.getAllHeaders()) header_application = self.decode_header(req.getAllHeaders())
user_id = int(header_application["session"]) machineSerial = header_application["a_serial"]
# self.getMatchingStatus(user_id)
self.logger.info( self.logger.info(
f"IDAC Matching request from {req.getClientIP()}: {url} - {req_data}" f"IDAC Matching request from {req.getClientIP()}: {url} - {req_data}"
) )
resp = {"status_code": "0"}
if url == "/regist": if url == "/regist":
self.queue = self.queue + 1 self.SessionQueue[machineSerial] = 1
self.logger.info(f"IDAC Matching registed player {machineSerial}")
return json.dumps({"status_code": "0"}, ensure_ascii=False).encode("utf-8")
elif url == "/status": elif url == "/status":
if req_data.get("cancel_flag"): if req_data.get('cancel_flag'):
self.queue = self.queue - 1 if machineSerial in self.SessionQueue:
self.logger.info( self.SessionQueue.pop(machineSerial)
f"IDAC Matching endpoint {req.getClientIP()} had quited" self.logger.info(f"IDAC Matching endpoint {req.getClientIP()} had quited")
) return json.dumps({"status_code": "0", "host": "", "port": self.game_config.server.matching_p2p, "room_name": self.Rooms[machineSerial], "state": 1}, ensure_ascii=False).encode("utf-8")
if machineSerial not in self.Rooms.keys():
self.Rooms[machineSerial] = "None"
return json.dumps({"status_code": "0", "host": self.game_config.server.matching_host, "port": self.game_config.server.matching_p2p, "room_name": self.Rooms[machineSerial], "state": self.getMatchingState(machineSerial)}, ensure_ascii=False).encode("utf-8")
resp = { # resp = {
"status_code": "0", # "status_code": "0",
# Only IPv4 is supported # # Only IPv4 is supported
"host": self.game_config.server.matching_host, # "host": self.game_config.server.matching_host,
"port": self.game_config.server.matching_p2p, # "port": self.game_config.server.matching_p2p,
"room_name": "INDTA", # "room_name": "INDTA",
"state": 1, # "state": self.get_matching_state(),
} # }
#
self.logger.debug(f"Response {resp}") #self.logger.debug(f"Response {resp}")
return json.dumps(resp, ensure_ascii=False).encode("utf-8") #return json.dumps(resp, ensure_ascii=False).encode("utf-8")
def decode_header(self, data: Dict) -> Dict: def decode_header(self, data: Dict) -> Dict:
app: str = data[b"application"].decode() app: str = data[b"application"].decode()

View File

@ -224,26 +224,51 @@ vs_info = Table(
metadata, metadata,
Column("id", Integer, primary_key=True, nullable=False), Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")), Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("group_key", String(25)), Column("battle_mode", Integer),
Column("win_flg", Integer), Column("invalid", Integer),
Column("style_car_id", Integer), Column("str", Integer),
Column("course_id", Integer), Column("str_now", Integer),
Column("course_day", Integer), Column("lose_now", Integer),
Column("players_num", Integer),
Column("winning", Integer),
Column("advantage_1", Integer),
Column("advantage_2", Integer),
Column("advantage_3", Integer),
Column("advantage_4", Integer),
Column("select_course_id", Integer),
Column("select_course_day", Integer),
Column("select_course_random", Integer),
Column("matching_success_sec", Integer),
Column("boost_flag", Integer),
Column("vs_history", Integer),
Column("break_count", Integer), Column("break_count", Integer),
Column("break_penalty_flag", Integer), Column("break_penalty_flag", Boolean),
UniqueConstraint("user", "group_key", name="idac_user_vs_info_uk"), UniqueConstraint("user", "battle_mode", name="idac_user_vs_info_uk"),
mysql_charset="utf8mb4",
)
vs_course_info = Table(
"idac_user_vs_course_info",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("battle_mode", Integer),
Column("course_id", Integer),
Column("vs_cnt", Integer),
Column("vs_win", Integer),
UniqueConstraint("user", "battle_mode", "course_id", name="idac_user_vs_course_info_uk"),
mysql_charset="utf8mb4",
)
round_infos = Table(
"idac_round_info",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("name", String(64)),
Column("season", Integer),
Column("start_dt", TIMESTAMP, server_default=func.now()),
Column("end_dt", TIMESTAMP, server_default=func.now()),
mysql_charset="utf8mb4",
)
round_info = Table(
"idac_user_round_info",
metadata,
Column("id", Integer, primary_key=True, nullable=False),
Column("user", ForeignKey("aime_user.id", ondelete="cascade", onupdate="cascade")),
Column("round_id", Integer),
Column("count", Integer),
Column("win", Integer),
Column("points", Integer),
UniqueConstraint("user", "round_id", name="idac_user_round_info_uk"),
mysql_charset="utf8mb4", mysql_charset="utf8mb4",
) )
@ -772,6 +797,25 @@ class IDACItemData(BaseData):
return None return None
return result.fetchall() return result.fetchall()
def get_vs_info_by_mode(self, aime_id: int, battle_mode: int) -> Optional[List[Row]]:
sql = select(vs_info).where(
and_(vs_info.c.user == aime_id, vs_info.c.battle_mode == battle_mode)
)
result = self.execute(sql)
if result is None:
return None
return result.fetchone()
#This method returns a list of course_info
def get_vs_course_infos_by_mode(self, aime_id: int, battle_mode: int) -> Optional[List[Row]]:
sql = select(vs_course_info).where(vs_info.c.user == aime_id, vs_info.c.battle_mode == battle_mode)
result = self.execute(sql)
if result is None:
return None
return result.fetchall()
def get_stamps(self, aime_id: int) -> Optional[List[Row]]: def get_stamps(self, aime_id: int) -> Optional[List[Row]]:
sql = select(stamp).where( sql = select(stamp).where(
and_( and_(
@ -970,8 +1014,9 @@ class IDACItemData(BaseData):
return None return None
return result.lastrowid return result.lastrowid
def put_vs_info(self, aime_id: int, vs_info_data: Dict) -> Optional[int]: def put_vs_info(self, aime_id: int, battle_mode: int, vs_info_data: Dict) -> Optional[int]:
vs_info_data["user"] = aime_id vs_info_data["user"] = aime_id
vs_info_data["battle_mode"] = battle_mode
sql = insert(vs_info).values(**vs_info_data) sql = insert(vs_info).values(**vs_info_data)
conflict = sql.on_duplicate_key_update(**vs_info_data) conflict = sql.on_duplicate_key_update(**vs_info_data)
@ -982,7 +1027,22 @@ class IDACItemData(BaseData):
return None return None
return result.lastrowid return result.lastrowid
def put_stamp(self, aime_id: int, stamp_data: Dict) -> Optional[int]: def put_vs_course_info(self, aime_id: int, battle_mode: int, course_info_data: Dict) -> Optional[int]:
course_info_data["user"] = aime_id
course_info_data["battle_mode"] = battle_mode
sql = insert(vs_course_info).values(**course_info_data)
conflict = sql.on_duplicate_key_update(**course_info_data)
result = self.execute(conflict)
if result is None:
self.logger.warn(f"put_vs_course_info: Failed to update! aime_id: {aime_id}")
return None
return result.lastrowid
def put_stamp(
self, aime_id: int, stamp_data: Dict
) -> Optional[int]:
stamp_data["user"] = aime_id stamp_data["user"] = aime_id
sql = insert(stamp).values(**stamp_data) sql = insert(stamp).values(**stamp_data)

View File

@ -588,6 +588,94 @@ class IDACSeason2(IDACBase):
user_id, self.version, updated_stock_data user_id, self.version, updated_stock_data
) )
def _update_vs_info(self, user_id: int, battle_mode: int, data: Dict) -> Dict:
vs_info = self.data.item.get_vs_info_by_mode(user_id, battle_mode)
if vs_info is not None:
vs_info = vs_info._asdict()
del vs_info["id"]
del vs_info["user"]
vs_info["invalid"] = vs_info["invalid"] + data.get("result")
vs_info["str_now"] = vs_info["str_now"] + data.get("win_flg") if data.get("win_flg") == 1 else 0
vs_info["str"] = vs_info["str"] if vs_info["str"] > vs_info["str_now"] else vs_info["str_now"]
vs_info["lose_now"] += 1 if data.get("win_flg") == 0 else 0
vs_info["break_count"] += data.get("break_count")
vs_info["break_penalty_flag"] = data.get("break_penalty_flag")
self.data.item.put_vs_info(user_id, battle_mode, vs_info)
vs_info["vs_cnt"] = 0
vs_info["vs_win"] = 0
vs_info["vsinfo_course_data"] = []
vs_courses_info = self.data.item.get_vs_course_info_by_mode(user_id, battle_mode)
course_not_exists = True
if vs_courses_info is not None:
for course in vs_courses_info:
course = course._asdict()
del course["id"]
del course["user"]
if course["course_id"] == data.get("course_id"):
course["vs_cnt"] += 1
course["vs_win"] += data.get("win_flg")
vs_info["vs_cnt"] += course["vs_cnt"]
vs_info["vs_win"] += course["vs_win"]
self.data.item.put_vs_course_info(user_id, battle_mode, course)
course_not_exists = False
else:
vs_info["vs_cnt"] += course["vs_cnt"]
vs_info["vs_win"] += course["vs_win"]
vs_info["vsinfo_course_data"].append(course)
if course_not_exists:
course = {}
course["course_id"] = data.get("course_id")
course["vs_cnt"] = 1
course["vs_win"] = data.get("win_flg")
vs_info["vs_cnt"] += course["vs_cnt"]
vs_info["vs_win"] += course["vs_win"]
vs_info["vsinfo_course_data"].append(course)
self.data.item.put_vs_course_info(user_id, battle_mode, course)
else:
vs_info = {
"battle_mode": battle_mode,
#"vs_cnt": 1,
#"vs_win": data.get("win_flg"),
"invalid": data.get("result"),
"str": data.get("win_flg"),
"str_now": data.get("win_flg"),
"lose_now": 1 if data.get("win_flg") == 0 else 0,
"break_count": data.get("break_count"),
"break_penalty_flag": data.get("break_penalty_flag"),
#"vsinfo_course_data": [
# {
# "course_id": data.get("course_id"),
# "vs_cnt": 1,
# "vs_win": data.get("win_flg")
# }
#],
}
self.data.item.put_vs_info(user_id, battle_mode, vs_info)
course_info = {
"course_id": data.get("course_id"),
"vs_cnt": 1,
"vs_win": data.get("win_flg")
}
self.data.item.put_vs_course_info(user_id, battle_mode, course_info)
vs_info["vs_cnt"] = 1
vs_info["vs_win"] = data.get("win_flg")
vs_info["vsinfo_course_data"] = []
vs_info["vsinfo_course_data"].append(course_info)
vs_info["vs_history"] = data.get("vs_history")
vs_info["course_select_priority"] = data.get("course_select_priority")
return vs_info
def handle_user_getdata_request(self, data: Dict, headers: Dict): def handle_user_getdata_request(self, data: Dict, headers: Dict):
user_id = int(headers["session"]) user_id = int(headers["session"])
@ -713,27 +801,41 @@ class IDACSeason2(IDACBase):
# get the users vs info data # get the users vs info data
vs_info_data = [] vs_info_data = []
vs_info = self.data.item.get_vs_infos(user_id) vs_info = self.data.item.get_vs_infos(user_id)
for vs in vs_info: if vs_info is not None:
vs_info_data.append( for vs in vs_info:
{ vs = vs._asdict()
"battle_mode": 1, vs_courses_info = self.data.item.get_vs_course_info_by_mode(user_id, vs["battle_mode"])
"vs_cnt": 1, total_vs_win = 0
"vs_win": vs["win_flg"], total_vs_cnt = 0
"invalid": 0, courses_info = []
"str": 0, if vs_courses_info is not None:
"str_now": 0, for course in vs_courses_info:
"lose_now": 0, tmp = course._asdict()
"vs_history": vs["vs_history"], del tmp["id"]
"course_select_priority": 0, del tmp["user"]
"vsinfo_course_data": [ del tmp["battle_mode"]
{
"course_id": vs["course_id"], total_vs_win += tmp["vs_win"]
"vs_cnt": 1, total_vs_cnt += tmp["vs_cnt"]
"vs_win": vs["win_flg"],
} courses_info.append(tmp)
],
}
) vs_info_data.append(
{
"battle_mode": vs["battle_mode"],
"vs_cnt": total_vs_cnt,
"vs_win": total_vs_win,
"invalid": vs["invalid"],
"str": vs["str"],
"str_now": vs["str_now"],
"lose_now": vs["lose_now"],
"vs_history": 0,
"course_select_priority": 0,
"vsinfo_course_data": courses_info,
}
)
# get the user's car # get the user's car
cars = self.data.item.get_cars(self.version, user_id, only_pickup=True) cars = self.data.item.get_cars(self.version, user_id, only_pickup=True)
@ -1808,6 +1910,19 @@ class IDACSeason2(IDACBase):
"past_season_timetrial_data": past_timetrial_data, "past_season_timetrial_data": past_timetrial_data,
} }
def handle_user_getpastseasonrounddata_request(self, data: Dict, headers: Dict):
user_id = headers["session"]
season_id = data.get("season_id")
# so to get the season 1 data just subtract 1 from the season id
past_timetrial_data = self._generate_time_trial_data(season_id - 1, user_id)
return {
"status_code": "0",
"season_id": season_id,
"past_season_round_event_data": [{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "DAC稼働記念 1stラウンド","round_id": 0},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 2ndラウンド","round_id": 1},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 3rdラウンド","round_id": 2},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 4thラウンド","round_id": 3},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 5thラウンド","round_id": 4},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 6thラウンド","round_id": 5},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 7thラウンド","round_id": 6},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 8thラウンド","round_id": 7},{"count": 0,"win": 0,"rank": 0,"area_rank": 0,"point": 0,"total_round_point": 0,"round_name": "シーズン1 9thラウンド","round_id": 8}]
}
def handle_user_gettadata_request(self, data: Dict, headers: Dict): def handle_user_gettadata_request(self, data: Dict, headers: Dict):
user_id = headers["session"] user_id = headers["session"]
@ -2378,26 +2493,7 @@ class IDACSeason2(IDACBase):
}, },
) )
self.data.item.put_vs_info(user_id, data) vs_info = _update_vs_info(user_id, 0, data)
vs_info = {
"battle_mode": 0,
"vs_cnt": 1,
"vs_win": data.get("win_flg"),
"invalid": 0,
"str": 0,
"str_now": 0,
"lose_now": 0,
"vs_history": data.get("vs_history"),
"course_select_priority": data.get("course_select_priority"),
"vsinfo_course_data": [
{
"course_id": data.get("course_id"),
"vs_cnt": 1,
"vs_win": data.get("win_flg"),
}
],
}
return { return {
"status_code": "0", "status_code": "0",
@ -2476,26 +2572,7 @@ class IDACSeason2(IDACBase):
) )
# save vs_info in database # save vs_info in database
self.data.item.put_vs_info(user_id, data) vs_info = _update_vs_info(user_id, 1, data)
vs_info = {
"battle_mode": 0,
"vs_cnt": 1,
"vs_win": data.get("win_flg"),
"invalid": 0,
"str": 0,
"str_now": 0,
"lose_now": 0,
"vs_history": data.get("vs_history"),
"course_select_priority": 0,
"vsinfo_course_data": [
{
"course_id": data.get("course_id"),
"vs_cnt": 1,
"vs_win": data.get("win_flg"),
}
],
}
return { return {
"status_code": "0", "status_code": "0",