Skip to content

Commit

Permalink
little enhancement
Browse files Browse the repository at this point in the history
  • Loading branch information
Hexalgo committed Jun 30, 2024
1 parent 3a2ee9b commit 417a9ec
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 51 deletions.
10 changes: 7 additions & 3 deletions pydofus2/Zaap/ZaapDecoy.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class ZaapDecoy(metaclass=ThreadSharedSingleton):
CONNECTED_ACCOUNTS = 0
SESSIONS_LAUNCH = 0
INITIALIZED = threading.Event()
ZAAP_VERSION = None

def __init__(self, mainAccountApiKey: str = ""):
self.kill_ankama_launcher()
Expand Down Expand Up @@ -163,6 +164,9 @@ def version(self):

@classmethod
def fetch_version(cls) -> str:
if cls.ZAAP_VERSION is not None:
return cls.ZAAP_VERSION

url = "https://launcher.cdn.ankama.com/installers/production/latest.yml?noCache=1hkaeforb"
response = requests.get(
url,
Expand Down Expand Up @@ -193,11 +197,11 @@ def fetch_version(cls) -> str:
file.write(response.content)

# Extract the version
version = data.get("version")
if not version:
cls.ZAAP_VERSION = data.get("version")
if not cls.ZAAP_VERSION:
raise ZaapError("Failed to extract ZAAP version from YAML file")

return version
return cls.ZAAP_VERSION

def get_dofus_launch_event(self, accountId):
return {
Expand Down
52 changes: 49 additions & 3 deletions pydofus2/Zaap/Zaapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ class HaapiException(Exception):
class Zaapi(metaclass=Singleton):
MAX_CREATE_API_KEY_RETRIES = 5

def __init__(self, zaap_version: str):
def __init__(self, zaap_version: str = None):
if not zaap_version:
from pydofus2.Zaap.ZaapDecoy import ZaapDecoy

zaap_version = ZaapDecoy.fetch_version()
Logger().debug(f"Zaap version: {zaap_version}")
self.BASE_URL = f"https://{XmlConfig().getEntry('config.haapiUrlAnkama')}"
self.zaap_session = requests.Session()
Expand All @@ -52,12 +56,13 @@ def __init__(self, zaap_version: str):
def getUrl(self, request, params={}):
queries = {
"SIGN_ON_WITH_APIKEY": "/Ankama/v5/Account/SignOnWithApiKey",
"GET_ACCOUNT": "/Ankama/v5/Account/Account",
"SET_NICKNAME": "/Ankama/v5/Account/SetNicknameWithApiKey",
"START_SESSION_WITH_API_KEY": "/Ankama/v5/Game/StartSessionWithApiKey",
"LIST_WITH_API_KEY": "/Ankama/v5/Game/ListWithApiKey",
"SEND_MAIL_VALIDATION": "/Ankama/v5/Account/SendMailValidation",
"SECURITY_CODE": "/Ankama/v5/Shield/SecurityCode",
"VALIDATE_CODE": "/Ankama/v5/Shield/ValidateCode",
"ANKAMA_SHIELD_SECURITY_CODE": "/Ankama/v5/Shield/SecurityCode",
"ANKAMA_SHIELD_VALIDATE_CODE": "/Ankama/v5/Shield/ValidateCode",
"DELETE_API_KEY": "/Ankama/v5/Api/DeleteApiKey",
"CREATE_GUEST": "/Ankama/v2/Account/CreateGuest",
"CREATE_TOKEN": "/Ankama/v5/Account/CreateToken",
Expand All @@ -78,6 +83,40 @@ def getUrl(self, request, params={}):
result += "?" + urlencode(params)
return result

def askSecurityCode(self, apikey, transportType="EMAIL"):
url = self.getUrl("ANKAMA_SHIELD_SECURITY_CODE", {"transportType": transportType})
response = self.zaap_session.get(url, headers={"apikey": apikey})
if response.status_code == 200:
return response.json()
else:
raise HaapiException(f"Failed to send code: {response.text}")

def shieldValidateCode(self, apikey, validationCode, hm1, hm2):
userName = "launcher-Merkator"
url = self.getUrl(
"ANKAMA_SHIELD_VALIDATE_CODE",
{"game_id": ZAAP_CONFIG.ZAAP_GAME_ID, "code": validationCode, "hm1": hm1, "hm2": hm2, "name": userName},
)
return self.zaap_session.get(url, headers={"apikey": apikey})

def exchange_code_for_token(self, code, code_verifier):
redirect_url = "http://127.0.0.1:9001/authorized"
url = "https://auth.ankama.com/token"
client_id = 102
data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_url,
"client_id": client_id,
"code_verifier": code_verifier,
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = self.zaap_session.post(url, data=data, headers=headers, verify=self.verify_ssl)
if response.status_code == 200:
return response.json()
else:
raise HaapiException(f"Failed to exchange code for token: {response.text}")

def sendDeviceInfos(self, session_id, connection_type, client_type, os, device, partner, device_uid, apikey=None):
if not apikey:
apikey = self.zaap_apikey
Expand Down Expand Up @@ -118,6 +157,13 @@ def getCarouselForLauncher(self, site, lang, page, count):
self.zaap_session.cookies.update(response.cookies)
return response.json()

def getAccount(self, apikey=None):
if not apikey:
apikey = self.zaap_apikey
url = self.getUrl("GET_ACCOUNT")
response = self.zaap_session.get(url, verify=self.verify_ssl, headers={"apikey": apikey})
return response.json()

def getLegalsTou(self, game, lang, knowVersion):
url = self.getUrl("GET_LEGALS_TOU", {"game": game, "lang": lang, "knowVersion": knowVersion})
response = self.zaap_session.get(url, verify=self.verify_ssl)
Expand Down
5 changes: 4 additions & 1 deletion pydofus2/com/DofusClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from pydofus2.com.ankamagames.dofus.misc.utils.HaapiEvent import HaapiEvent
from pydofus2.com.ankamagames.dofus.misc.utils.HaapiKeyManager import HaapiKeyManager
from pydofus2.com.ankamagames.dofus.network.enums.ChatActivableChannelsEnum import ChatActivableChannelsEnum
from pydofus2.com.ankamagames.dofus.network.enums.ServerStatusEnum import ServerStatusEnum
from pydofus2.com.ankamagames.jerakine.benchmark.BenchmarkTimer import BenchmarkTimer
from pydofus2.com.ankamagames.jerakine.data.ModuleReader import ModuleReader
from pydofus2.com.ankamagames.jerakine.logger.Logger import Logger
Expand Down Expand Up @@ -122,7 +123,7 @@ def onStatusUpdate(self, event, status: ClientStatusEnum, data=None):
data = {}
self._status = status
for listener in self._statusChangedListeners:
listener(self, status, data)
BenchmarkTimer(0.1, lambda: listener(self, status, data)).start()

def init(self):
Logger().info("Initializing ...")
Expand Down Expand Up @@ -229,6 +230,8 @@ def onCharacterImpossibleSelection(self, event):

def onServerSelectionRefused(self, event, serverId, err_type, server_status, error_text, selectableServers):
Logger().error(f"Server selection refused for reason : {error_text}, server status {server_status}")
if server_status == ServerStatusEnum.SAVING.value:
return
self._crashed = True
self.shutdown(reason=DisconnectionReasonEnum.EXCEPTION_THROWN, message=error_text)

Expand Down
2 changes: 1 addition & 1 deletion pydofus2/com/ankamagames/berilia/managers/Listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def delete(self):
self._deleted = True
self.cancelTimer()
if self.event_id not in self.manager._listeners:
return Logger().warning("Trying to delete Event not registred")
return Logger().warning("Trying to delete Event not registered")
listeners = self.manager._listeners[self.event_id][self.priority]
if self in listeners:
listeners.remove(self)
Expand Down
3 changes: 3 additions & 0 deletions pydofus2/com/ankamagames/dofus/kernel/Kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ def reset(
self,
reloadData: bool = False,
) -> None:
from pyd2bot.logic.roleplay.behaviors.AbstractBehavior import AbstractBehavior

from pydofus2.com.ankamagames.atouin.HaapiEventsManager import HaapiEventsManager
from pydofus2.com.ankamagames.berilia.managers.KernelEventsManager import KernelEventsManager
from pydofus2.com.ankamagames.dofus.kernel.net.ConnectionsHandler import ConnectionsHandler
Expand Down Expand Up @@ -121,6 +123,7 @@ def reset(
InactivityManager.clear()
InterClientManager().freeFlashKey()
SpellCastSequenceContext.reset()
AbstractBehavior.clearAllChildren()

if not reloadData:
self._worker.terminate()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ def process(self, msg: Message) -> bool:
return True

if isinstance(msg, SubscriptionLimitationMessage):
Logger().error("SubscriptionLimitationMessage reason " + msg.reason)
text = ""
payZonePopupMode = "payzone"
if msg.reason == SubscriptionRequiredEnum.LIMIT_ON_JOB_XP:
Expand All @@ -161,7 +160,7 @@ def process(self, msg: Message) -> bool:
else:
text = I18n.getUiText("ui.payzone.limit")

Logger().warning("SubscriptionLimitationMessage text " + text)
Logger().warning("SubscriptionLimitationMessage text : " + text)
KernelEventsManager().send(
KernelEvent.TextInformation,
text,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
GameContextDestroyMessage,
)
from pydofus2.com.ankamagames.dofus.network.messages.game.context.GameContextQuitMessage import GameContextQuitMessage
from pydofus2.com.ankamagames.jerakine.benchmark.BenchmarkTimer import BenchmarkTimer
from pydofus2.com.ankamagames.jerakine.messages.Frame import Frame
from pydofus2.com.ankamagames.jerakine.messages.Message import Message
from pydofus2.com.ankamagames.jerakine.types.enums.Priority import Priority
Expand All @@ -33,7 +34,10 @@ def pushed(self) -> bool:
def process(self, msg: Message) -> bool:

if isinstance(msg, GameContextDestroyMessage):
KernelEventsManager().send(KernelEvent.ClientStatusUpdate, ClientStatusEnum.CHANGING_CONTEXT)
BenchmarkTimer(
0.1,
lambda: KernelEventsManager().send(KernelEvent.ClientStatusUpdate, ClientStatusEnum.CHANGING_CONTEXT),
).start()
return True

elif isinstance(msg, GameContextCreateMessage):
Expand All @@ -45,15 +49,26 @@ def process(self, msg: Message) -> bool:

Kernel().worker.addFrame(RoleplayContextFrame())
KernelEventsManager().send(KernelEvent.RoleplayStarted)
KernelEventsManager().send(KernelEvent.ClientStatusUpdate, ClientStatusEnum.SWITCHED_TO_ROLEPLAY)
BenchmarkTimer(
0.1,
lambda: KernelEventsManager().send(
KernelEvent.ClientStatusUpdate, ClientStatusEnum.SWITCHED_TO_ROLEPLAY
),
).start()

elif self.currentContext == GameContextEnum.FIGHT:
from pydofus2.com.ankamagames.dofus.logic.game.fight.frames.FightContextFrame import FightContextFrame

if not Kernel().isMule:
Kernel().worker.addFrame(FightContextFrame())

KernelEventsManager().send(KernelEvent.FightStarted)
KernelEventsManager().send(KernelEvent.ClientStatusUpdate, ClientStatusEnum.SWITCHED_TO_FIGHTING)
BenchmarkTimer(
0.1,
lambda: KernelEventsManager().send(
KernelEvent.ClientStatusUpdate, ClientStatusEnum.SWITCHED_TO_FIGHTING
),
).start()
return True

elif isinstance(msg, GameContextQuitAction):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def onActivityTimerUp(self):
inactivity_message_text = InfoMessage.getInfoMessageById(
self.MESSAGE_TYPE_ID * 10000 + self.DISCONNECTED_FOR_INACTIVITY_MESSAGE_ID
).text
KernelEventsManager().send(KernelEvent.ClientCrashed, inactivity_message_text)
KernelEventsManager().send(KernelEvent.ClientRestart, inactivity_message_text)

def onServerActivityTimerUp(self):
if self._hasActivity:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -713,12 +713,7 @@ def process(self, msg: Message) -> bool:
if isinstance(msg, GameActionFightMultipleSummonMessage):
gafmsmsg = msg
gffinfos = GameFightFighterInformations()
self.pushStep(
FightUpdateStatStep(
0,
[],
)
)
self.pushStep(FightUpdateStatStep(gffinfos.contextualId, gffinfos.stats.characteristics.characteristics))
gffinfos = self.fighterSummonMultipleEntities(gafmsmsg, gffinfos)
return True

Expand Down Expand Up @@ -1085,14 +1080,14 @@ def fighterSummonMultipleEntities(
if isinstance(summons.spawnInformation, SpawnCharacterInformation):
gffninfos = GameFightFighterNamedInformations()
gffninfos.init(
sum.informations.contextualId,
sum.informations.disposition,
summons.look,
summons.spawnInformation.name,
sum,
summons.wave,
summons.stats,
None,
summons.spawnInformation,
summons.look,
sum.informations.contextualId,
sum.informations.disposition,
)
gffinfos = gffninfos

Expand Down Expand Up @@ -1416,33 +1411,21 @@ def onStepEnd(self, e, isEnd: bool = True) -> None:

def subSequenceInitDone(self) -> None:
self._subSequenceWaitingCount -= 1
# Logger().debug(
# f"\r[STEPS DEBUG] sequence #{self._instanceId} has {self._subSequenceWaitingCount} subsequences waiting and {self._scriptInit} script init"
# )
# Logger().debug(f"\r[STEPS DEBUG] init subsequence isWaiting {self.isWaiting}, sequencer {self._sequencer}")
if not self.isWaiting and self._sequencer and not self._sequencer.running:
# Logger().warn("Sub sequence init end -- Run main sequence")
self._sequencer.start()
else:
# Logger().warn(f"warning did not start sequener of sequence #{self._instanceId}")
pass

def pushTeleportStep(self, fighterId: float, destinationCell: int) -> None:
if destinationCell != -1:
step = FightTeleportStep(fighterId, MapPoint.fromCellId(destinationCell))
if self.context is not None:
self.castingSpellId = self.context.id
self._steps.append(step)
self.pushStep(step)

def pushSlideStep(self, fighterId: float, startCell: int, endCell: int) -> None:
if startCell < 0 or endCell < 0:
return
step: FightEntitySlideStep = FightEntitySlideStep(
fighterId, MapPoint.fromCellId(startCell), MapPoint.fromCellId(endCell)
)
if self.context is not None:
self.castingSpellId = self.context.id
self._steps.append(step)
self.pushStep(step)

def pushPointsVariationStep(self, fighterId: float, actionId: int, delta: int) -> None:
step: IFightStep = None
Expand All @@ -1461,9 +1444,7 @@ def pushPointsVariationStep(self, fighterId: float, actionId: int, delta: int) -
else:
Logger().warn(f"Points variation with unsupported action ({actionId}), skipping.")
return
if self.context is not None:
self.castingSpellId = self.context.id
self._steps.append(step)
self.pushStep(step)

def pushStep(self, step: AbstractSequencable) -> None:
if self.context is not None:
Expand All @@ -1479,14 +1460,9 @@ def pushPointsLossDodgeStep(self, fighterId: float, actionId: int, amount: int)
else:
Logger().warn(f"Points dodge with unsupported action ({actionId}), skipping.")
return
if self.context is not None:
step.castingSpellId = self.context.id
self._steps.append(step)
self.pushStep(step)

def pushPlaySpellScriptStep(self, castSequence: ISpellCastSequence) -> FightPlaySpellScriptStep:
# scriptTypes = SpellScriptManager().resolveScriptUsageFromCastContext(
# castSequence.context, specifictargetedCellId
# )
self._steps.append(FightPlaySpellScriptStep(castSequence.context))

def pushThrowCharacterStep(self, fighterId: float, carriedId: float, cellId: int) -> None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@ class GameFightFighterNamedInformations(GameFightFighterInformations):
def init(
self,
name_: str,
status_: "PlayerStatus",
leagueId_: int,
ladderPosition_: int,
hiddenInPrefight_: bool,
spawnInfo_: "GameContextBasicSpawnInformation",
wave_: int,
stats_: "GameFightCharacteristics",
previousPositions_: list[int],
look_: "EntityLook",
contextualId_: int,
disposition_: "EntityDispositionInformations",
status_: "PlayerStatus" = None,
leagueId_: int = 0,
ladderPosition_: int = 0,
hiddenInPrefight_: bool = False,
):
self.name = name_
self.status = status_
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ autoflake
poetry
pre-commit
pydantic
PyQt5

0 comments on commit 417a9ec

Please sign in to comment.