Skip to content

Commit

Permalink
Merge pull request #113 from tanishqmanuja/feat/mobile
Browse files Browse the repository at this point in the history
Support for Mobile Client
  • Loading branch information
OwOHamper authored Sep 25, 2023
2 parents d1297ae + dcd6092 commit 1c4ec23
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 46 deletions.
148 changes: 113 additions & 35 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,40 @@
import traceback
import requests
import urllib3
import asyncio
import os
import socket
import sys
import time
import asyncio
import traceback

import requests
import urllib3
from colr import color as colr
from InquirerPy import inquirer
from rich.console import Console as RichConsole

from src.constants import *
from src.requestsV import Requests
from src.logs import Logging
from src.config import Config
from src.chatlogs import ChatLogging
from src.colors import Colors
from src.rank import Rank
from src.config import Config
from src.configurator import configure
from src.constants import *
from src.content import Content
from src.errors import Error
from src.Loadouts import Loadouts
from src.logs import Logging
from src.names import Names
from src.player_stats import PlayerStats
from src.presences import Presences
from src.Loadouts import Loadouts
from src.websocket import Ws

from src.rank import Rank
from src.requestsV import Requests
from src.rpc import Rpc
from src.server import Server
from src.states.coregame import Coregame
from src.states.menu import Menu
from src.states.pregame import Pregame
from src.states.coregame import Coregame

from src.table import Table
from src.server import Server
from src.errors import Error

from src.stats import Stats
from src.configurator import configure
from src.player_stats import PlayerStats

from src.chatlogs import ChatLogging

from src.rpc import Rpc

from src.table import Table
from src.websocket import Ws
from src.os import get_os

from colr import color as colr

from rich.console import Console as RichConsole

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# os.system('cls')
Expand All @@ -53,7 +47,18 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
log(f"exited program with error code {status}")
raise sys.exit(status)


def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0)
try:
# doesn't even have to be reachable
s.connect(('10.254.254.254', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP

try:
Logging = Logging()
Expand Down Expand Up @@ -138,8 +143,7 @@ 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, Server, rpc)
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
# loop.run_forever()
Expand All @@ -153,6 +157,8 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
previousSeasonID = content.get_previous_season_id(gameContent)
lastGameState = ""

print(color(f"\nWs Server - {get_ip()}:{cfg.port}", fore=(255, 127, 80)))

print(color("\nVisit https://vry.netlify.app/matchLoadouts to view full player inventories\n", fore=(255, 253, 205)))
chatlog(color("\nVisit https://vry.netlify.app/matchLoadouts to view full player inventories\n", fore=(255, 253, 205)))

Expand Down Expand Up @@ -223,6 +229,20 @@ def program_exit(status: int): # so we don't need to import the entire sys modu

is_leaderboard_needed = False

priv_presence = presences.get_private_presence(presence)
if priv_presence["provisioningFlow"] == "CustomGame" or priv_presence["partyState"] == "CUSTOM_GAME_SETUP":
gamemode = "Custom Game"
else:
gamemode = gamemodes.get(priv_presence['queueId'])

heartbeat_data = {
"time": int(time.time()),
"state": game_state,
"mode": gamemode,
"puuid": Requests.puuid,
"players": {}
}

if game_state == "INGAME":
coregame_stats = coregame.get_coregame_stats()
if coregame_stats == None:
Expand All @@ -248,16 +268,21 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
server = "New server"
presences.wait_for_presence(namesClass.get_players_puuid(Players))
names = namesClass.get_names_from_puuids(Players)
loadouts = loadoutsClass.get_match_loadouts(coregame.get_coregame_match_id(), Players, cfg.weapon, valoApiSkins, names, state="game")
loadouts_arr = loadoutsClass.get_match_loadouts(coregame.get_coregame_match_id(), Players, cfg.weapon, valoApiSkins, names, state="game")
loadouts = loadouts_arr[0]
loadouts_data = loadouts_arr[1]
# with alive_bar(total=len(Players), title='Fetching Players', bar='classic2') as bar:
isRange = False
playersLoaded = 1
with richConsole.status("Loading Players...") as status:

heartbeat_data["map"] = map_dict[coregame_stats["MapID"].lower()],
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)
Players.sort(key=lambda Players: Players["TeamID"], reverse=True)
partyCount = 0
partyNum = 0
partyIcons = {}
lastTeamBoolean = False
lastTeam = "Red"
Expand Down Expand Up @@ -311,14 +336,14 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
})

party_icon = ''

# set party premade icon
for party in partyOBJ:
if player["Subject"] in partyOBJ[party]:
if party not in partyIcons:
partyIcons.update({party: PARTYICONLIST[partyCount]})
# PARTY_ICON
party_icon = PARTYICONLIST[partyCount]
partyNum = partyCount + 1
partyCount += 1
else:
# PARTY_ICON
Expand Down Expand Up @@ -426,6 +451,28 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
kd,
level
])

heartbeat_data["players"][player["Subject"]] = {
"puuid": player["Subject"],
"name": names[player["Subject"]],
"partyNumber": partyNum if party_icon != "" else 0,
"agent": agent_dict[player["CharacterID"].lower()],
"rank": playerRank["rank"],
"peakRank": playerRank["peakrank"],
"peakRankAct": peakRankAct,
"rr": rr,
"kd": ppstats["kd"],
"headshotPercentage": ppstats["hs"],
"winPercentage": f"{playerRank['wr']} ({playerRank['numberofgames']})",
"level": player_level,
"agentImgLink": loadouts_data["Players"][player["Subject"]].get("Agent",None),
"team": loadouts_data["Players"][player["Subject"]].get("Team",None),
"sprays": loadouts_data["Players"][player["Subject"]].get("Sprays",None),
"title": loadouts_data["Players"][player["Subject"]].get("Title",None),
"playerCard": loadouts_data["Players"][player["Subject"]].get("PlayerCard",None),
"weapons": loadouts_data["Players"][player["Subject"]].get("Weapons",None)
}

stats.save_data(
{
player["Subject"]: {
Expand Down Expand Up @@ -478,6 +525,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
partyIcons.update({party: PARTYICONLIST[partyCount]})
# PARTY_ICON
party_icon = PARTYICONLIST[partyCount]
partyNum = partyCount + 1
else:
# PARTY_ICON
party_icon = partyIcons[party]
Expand Down Expand Up @@ -585,6 +633,21 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
kd,
level,
])

heartbeat_data["players"][player["Subject"]] = {
"name": names[player["Subject"]],
"partyNumber": partyNum if party_icon != "" else 0,
"agent": agent_dict[player["CharacterID"].lower()],
"rank": playerRank["rank"],
"peakRank": playerRank["peakrank"],
"peakRankAct": peakRankAct,
"level": player_level,
"rr": rr,
"kd": ppstats["kd"],
"headshotPercentage": ppstats["hs"],
"winPercentage": f"{playerRank['wr']} ({playerRank['numberofgames']})",
}

# bar()
if game_state == "MENUS":
already_played_with = []
Expand Down Expand Up @@ -675,6 +738,20 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
kd,
level
])

heartbeat_data["players"][player["Subject"]] = {
"name": names[player["Subject"]],
"rank": playerRank["rank"],
"peakRank": playerRank["peakrank"],
"peakRankAct": peakRankAct,
"level": player_level,
"rr": rr,
"kd": ppstats["kd"],
"headshotPercentage": ppstats["hs"],
"winPercentage": f"{playerRank['wr']} ({playerRank['numberofgames']})",
}

# bar()
seen.append(player["Subject"])
if (title := game_state_dict.get(game_state)) is None:
# program_exit(1)
Expand Down Expand Up @@ -702,6 +779,7 @@ def program_exit(status: int): # so we don't need to import the entire sys modu
table.set_runtime_col_flag('RR', cfg.table.get("rr") and not cfg.get_feature_flag("aggregate_rank_rr"))

table.set_caption(f"VALORANT rank yoinker v{version}")
Server.send_payload("heartbeat",heartbeat_data)
table.display()
firstPrint = False

Expand Down
5 changes: 3 additions & 2 deletions src/Loadouts.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ 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.Server.send_message(json.dumps(final_json))
return weaponLists
# self.log(f"json for website: {final_json}")
self.Server.send_payload("matchLoadout",final_json)
return [weaponLists,final_json]

#this will convert valorant loadouts to json with player names
def convertLoadoutToJsonArray(self, PlayerInventorys, players, state, names):
Expand Down
28 changes: 21 additions & 7 deletions src/server.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,44 @@
import json
import logging
from websocket_server import WebsocketServer

from src.constants import version

logging.getLogger('websocket_server.websocket_server').disabled = True

# websocket.enableTrace(True)

class Server:
def __init__(self, log, Error):
self.Error = Error
self.log = log
self.lastMessage = ""
self.lastMessages = {}

def start_server(self):
try:
# print(self.lastMessage)
with open('config.json', "r") as conf:
with open("config.json", "r") as conf:
port = json.load(conf)["port"]
self.server = WebsocketServer(host='127.0.0.1', port=port)
self.server = WebsocketServer(host="0.0.0.0", 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:
self.Error.PortError(port)

def handle_new_client(self, client, server):
if self.lastMessage != "":
self.send_message(self.lastMessage)

self.send_payload("version",{
"core": version
})
for key in self.lastMessages:
if key not in ["chat","version"]:
self.send_message(self.lastMessages[key])

def send_message(self, message):
self.lastMessage = message
self.server.send_message_to_all(message)

def send_payload(self, type, payload):
payload["type"] = type
msg_str = json.dumps(payload)
self.lastMessages[type] = msg_str
self.server.send_message_to_all(msg_str)
22 changes: 20 additions & 2 deletions src/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@


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


self.lockfile = lockfile
self.Requests = Requests
Expand All @@ -26,6 +26,7 @@ def __init__(self, lockfile, Requests, cfg, colors, hide_names, chatlog,
self.up = "\033[A"
self.chat_limit = cfg.chat_limit
self.chatlog = chatlog
self.server = server
if self.cfg.get_feature_flag("discord_rpc"):
self.rpc = rpc

Expand Down Expand Up @@ -92,12 +93,29 @@ def handle(self, m, initial_game_state):
name = f"{message['game_name']}#{message['game_tag']}"
if self.player_data[message['puuid']]['streamer_mode'] and self.hide_names and message['puuid'] not in self.player_data["ignore"]:
self.print_message(f"{chat_prefix} {color(self.colors.escape_ansi(agent), clr)}: {message['body']}")
self.server.send_payload("chat",{
"time": message["time"],
"puuid": player,
"self": message["puuid"] == self.Requests.puuid,
"group":re.sub("\[|\]","",self.colors.escape_ansi(chat_prefix)),
"agent": self.colors.escape_ansi(agent),
"text": message['body']
})
else:
if agent == "":
agent_str = ""
else:
agent_str = f" ({agent})"
self.print_message(f"{chat_prefix} {color(name, clr)}{agent_str}: {message['body']}")
self.server.send_payload("chat",{
"time": message["time"],
"puuid": player,
"self": message["puuid"] == self.Requests.puuid,
"group":re.sub("\[|\]","",self.colors.escape_ansi(chat_prefix)),
"player": name,
"agent": self.colors.escape_ansi(agent),
"text": message['body']
})
self.id_seen.append(message['id'])

def print_message(self, message):
Expand Down

0 comments on commit 1c4ec23

Please sign in to comment.