Skip to content

Commit

Permalink
feat: push map to server
Browse files Browse the repository at this point in the history
As per request: #171 (comment)
  • Loading branch information
zay committed Aug 29, 2023
1 parent d15c20b commit 113d33f
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 69 deletions.
23 changes: 10 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu


ErrorSRC = Error(log)

Requests = Requests(version, log, ErrorSRC)
Requests.check_version()
Requests.check_status()
Expand Down Expand Up @@ -123,7 +123,8 @@ def program_exit(status: int): # so we don't need to import the entire sys modu

colors = Colors(hide_names, agent_dict, AGENTCOLORLIST)

loadoutsClass = Loadouts(Requests, log, colors, Server)
loadoutsClass = Loadouts(Requests, log, colors, Server,
coregame.get_current_map(map_dict))
table = Table(cfg, chatlog, log)

stats = Stats()
Expand All @@ -133,16 +134,15 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
else:
rpc = None

Wss = Ws(Requests.lockfile, Requests, cfg, colors, hide_names, chatlog, rpc)
Wss = Ws(Requests.lockfile, Requests, cfg, colors, hide_names, chatlog,
rpc)
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_forever()

log(f"VALORANT rank yoinker v{version}")




valoApiSkins = requests.get("https://valorant-api.com/v1/weapons/skins")
gameContent = content.get_content()
seasonID = content.get_latest_season_id(gameContent)
Expand All @@ -155,10 +155,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu

richConsole = RichConsole()

# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete(Wss.conntect_to_websocket(game_state))
# loop.close()

firstTime = True
firstPrint = True
while True:
Expand Down Expand Up @@ -251,7 +248,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
# with alive_bar(total=len(Players), title='Fetching Players', bar='classic2') as bar:
isRange = False
playersLoaded = 1
with richConsole.status("Loading Players...") as status:
with richConsole.status("Loading Players...") as status:
partyOBJ = menu.get_party_json(namesClass.get_players_puuid(Players), presence)
# log(f"retrieved names dict: {names}")
Players.sort(key=lambda Players: Players["PlayerIdentity"].get("AccountLevel"), reverse=True)
Expand Down Expand Up @@ -430,7 +427,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
player["Subject"]: {
"name": names[player["Subject"]],
"agent": agent_dict[player["CharacterID"].lower()],
"map": map_dict.get(coregame_stats["MapID"].lower()),
"map": coregame.get_current_map(map_dict),
"rank": playerRank["rank"],
"rr": rr,
"match_id": coregame.match_id,
Expand All @@ -455,7 +452,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
# loadouts = loadoutsClass.get_match_loadouts(pregame.get_pregame_match_id(), pregame_stats, cfg.weapon, valoApiSkins, names,
# state="pregame")
playersLoaded = 1
with richConsole.status("Loading Players...") as status:
with richConsole.status("Loading Players...") as status:
# with alive_bar(total=len(Players), title='Fetching Players', bar='classic2') as bar:
presence = presences.get_presence()
partyOBJ = menu.get_party_json(namesClass.get_players_puuid(Players), presence)
Expand Down Expand Up @@ -590,7 +587,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
Players = menu.get_party_members(Requests.puuid, presence)
names = namesClass.get_names_from_puuids(Players)
playersLoaded = 1
with richConsole.status("Loading Players...") as status:
with richConsole.status("Loading Players...") as status:
# with alive_bar(total=len(Players), title='Fetching Players', bar='classic2') as bar:
# log(f"retrieved names dict: {names}")
Players.sort(key=lambda Players: Players["PlayerIdentity"].get("AccountLevel"), reverse=True)
Expand Down
12 changes: 7 additions & 5 deletions src/Loadouts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
# import pyperclip

class Loadouts:
def __init__(self, Requests, log, colors, Server):
def __init__(self, Requests, log, colors, Server, current_map):
self.Requests = Requests
self.log = log
self.colors = colors
# self.namesClass = namesClass
self.Server = Server
self.current_map = current_map

def get_match_loadouts(self, match_id, players, weaponChoose, valoApiSkins, names, state="game"):
playersBackup = players
Expand Down Expand Up @@ -47,7 +48,6 @@ def get_match_loadouts(self, match_id, players, weaponChoose, valoApiSkins, name
# else:
# weaponLists.update({player["Subject"]: color(skin["Name"], fore=rgb_color)})
final_json = self.convertLoadoutToJsonArray(PlayerInventorys, playersBackup, state, names)
# self.log(f"json for website: {final_json}")
self.Server.send_message(json.dumps(final_json))
return weaponLists

Expand All @@ -65,6 +65,8 @@ def convertLoadoutToJsonArray(self, PlayerInventorys, players, state, names):
final_final_json = {"Players": {}}

final_final_json.update({"time": int(time.time())})
final_final_json.update({"map": self.current_map})

final_json = final_final_json["Players"]
if state == "game":
PlayerInventorys = PlayerInventorys["Loadouts"]
Expand Down Expand Up @@ -120,7 +122,7 @@ def convertLoadoutToJsonArray(self, PlayerInventorys, players, state, names):

#create weapons field
final_json[players[i]["Subject"]].update({"Weapons": {}})

for skin in PlayerInventory["Items"]:

#create skin field
Expand All @@ -131,7 +133,7 @@ def convertLoadoutToJsonArray(self, PlayerInventorys, players, state, names):
for var_socket in sockets:
if socket == sockets[var_socket]:
final_json[players[i]["Subject"]]["Weapons"][skin].update(
{
{
var_socket: PlayerInventory["Items"][skin]["Sockets"][socket]["Item"]["ID"]
}
)
Expand Down Expand Up @@ -194,4 +196,4 @@ def convertLoadoutToJsonArray(self, PlayerInventorys, players, state, names):
)
if skinValApi["displayName"].startswith("Standard") or skinValApi["displayName"].startswith("Melee"):
final_json[players[i]["Subject"]]["Weapons"][skin]["skinDisplayIcon"] = weapon["displayIcon"]
return final_final_json
return final_final_json
7 changes: 0 additions & 7 deletions src/server.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import json
from websocket_server import WebsocketServer
# from threading import Thread

# websocket.enableTrace(True)



class Server:
Expand All @@ -18,7 +14,6 @@ def start_server(self):
with open('config.json', "r") as conf:
port = json.load(conf)["port"]
self.server = WebsocketServer(host='127.0.0.1', port=port)
# server = websocket.WebSocketApp("wss://localhost:1100", on_open=on_open, on_message=on_message, on_close=on_close)
self.server.set_fn_new_client(self.handle_new_client)
self.server.run_forever(threaded=True)
except Exception as e:
Expand All @@ -33,5 +28,3 @@ def send_message(self, message):
self.lastMessage = message
self.server.send_message_to_all(message)



23 changes: 19 additions & 4 deletions src/states/coregame.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import time



class Coregame:
def __init__(self, Requests, log):
self.log = log
Expand All @@ -12,7 +11,9 @@ def __init__(self, Requests, log):

def get_coregame_match_id(self):
try:
self.response = self.Requests.fetch(url_type="glz", endpoint=f"/core-game/v1/players/{self.Requests.puuid}", method="get")
self.response = self.Requests.fetch(url_type="glz",
endpoint=f"/core-game/v1/players/{self.Requests.puuid}",
method="get")
if self.response.get("errorCode") == "RESOURCE_NOT_FOUND":
return 0
match_id = self.response['MatchID']
Expand All @@ -23,7 +24,9 @@ def get_coregame_match_id(self):
# print(f"No match id found. {self.response}")
time.sleep(5)
try:
self.response = self.Requests.fetch(url_type="glz", endpoint=f"/core-game/v1/players/{self.Requests.puuid}", method="get")
self.response = self.Requests.fetch(url_type="glz",
endpoint=f"/core-game/v1/players/{self.Requests.puuid}",
method="get")
match_id = self.response['MatchID']
self.log(f"retrieved coregame match id: '{match_id}'")
return match_id
Expand All @@ -37,4 +40,16 @@ def get_coregame_stats(self):
if self.match_id != 0:
return self.Requests.fetch(url_type="glz", endpoint=f"/core-game/v1/matches/{self.match_id}", method="get")
else:
return None
return None

def get_current_map(self, map_dict) -> str:
"""
Abstracts get_coregame_stats() to get the current map name.
:return: Map name.
"""
coregame_stats = self.get_coregame_stats()

if coregame_stats is None:
return 'N/A'

return map_dict.get(coregame_stats['MapID'].lower())
43 changes: 3 additions & 40 deletions src/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import base64
import json
from colr import color
import re


class Ws:
def __init__(self, lockfile, Requests, cfg, colors, hide_names, chatlog, rpc=None):
def __init__(self, lockfile, Requests, cfg, colors, hide_names, chatlog,
rpc=None):

self.lockfile = lockfile
self.Requests = Requests
Expand All @@ -32,23 +32,6 @@ def __init__(self, lockfile, Requests, cfg, colors, hide_names, chatlog, rpc=Non
def set_player_data(self, player_data):
self.player_data = player_data

# async def conntect_to_websocket(self, initial_game_state):


# local_headers = {}
# local_headers['Authorization'] = 'Basic ' + base64.b64encode(('riot:' + self.lockfile['password']).encode()).decode()
# url = f"wss://127.0.0.1:{self.lockfile['port']}"
# self.websocket_client = websockets.connect(url, ssl=self.ssl_context, extra_headers=local_headers)
# async with self.websocket_client as websocket:
# await websocket.send('[5, "OnJsonApiEvent_chat_v4_presences"]')
# return None
# # while True:
# # response = await websocket.recv()
# # h = self.handle(response, initial_game_state)
# # if h is not None:
# # return h


async def recconect_to_websocket(self, initial_game_state):
#wont actually recconect :)
local_headers = {}
Expand Down Expand Up @@ -76,7 +59,7 @@ def handle(self, m, initial_game_state):
state = None
else:
state = json.loads(base64.b64decode(presence['private']))["sessionLoopState"]

if state is not None:
if self.cfg.get_feature_flag("discord_rpc"):
self.rpc.set_rpc(json.loads(base64.b64decode(presence['private'])))
Expand Down Expand Up @@ -129,23 +112,3 @@ def print_message(self, message):
print(message)

self.message_history.append(message)



# if __name__ == "__main__":
# try:
# with open(os.path.join(os.getenv('LOCALAPPDATA'), R'Riot Games\Riot Client\Config\lockfile')) as lockfile:
# data = lockfile.read().split(':')
# keys = ['name', 'PID', 'port', 'password', 'protocol']
# lockfile = dict(zip(keys, data))
# except:
# raise Exception("Lockfile not found")


# ws = Ws(lockfile, "MENUS")
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete(ws.conntect_to_websocket("MENUS"))
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_forever()

0 comments on commit 113d33f

Please sign in to comment.