text
stringlengths
1
93.6k
results = [data] # single battle/job - make into a list
# filter down to one battle at a time
for i in range(len(results)):
if "vsHistoryDetail" in results[i]["data"]: # ink battle
payload = prepare_battle_result(results[i]["data"], ismonitoring, isblackout, overview_data)
which = "ink"
elif "coopHistoryDetail" in results[i]["data"]: # salmon run job
prevresult = results[i-1]["data"] if i > 0 else None
payload = prepare_job_result(results[i]["data"], ismonitoring, isblackout, overview_data, prevresult=prevresult)
which = "salmon"
else: # shouldn't happen
print("Ill-formatted JSON while uploading. Exiting.")
print('\nDebug info:')
print(json.dumps(results))
sys.exit(1) # always exit here - something is seriously wrong
if not payload: # empty payload
return
if len(payload) == 0: # received blank payload from prepare_job_result() - skip unsupported battle
continue
# should have been taken care of in fetch_json() but just in case...
if payload.get("lobby") == "private" and utils.custom_key_exists("ignore_private", CONFIG_DATA) or \
payload.get("private") == "yes" and utils.custom_key_exists("ignore_private_jobs", CONFIG_DATA): # SR version
continue
s3s_values = {'agent': '\u0073\u0033\u0073', 'agent_version': f'v{A_VERSION}'} # lol
s3s_values["agent_variables"] = {'Upload Mode': "Monitoring" if ismonitoring else "Manual"}
payload.update(s3s_values)
if payload["agent"][0:3] != os.path.basename(__file__)[:-3]:
print("Could not upload. Please contact @frozenpandaman on GitHub for assistance.")
sys.exit(0)
if istestrun:
payload["test"] = "yes"
# POST
url = "https://stat.ink/api/v3"
if which == "ink":
url += "/battle"
elif which == "salmon":
url += "/salmon"
auth = {'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/x-msgpack'}
postbattle = requests.post(url, headers=auth, data=msgpack.packb(payload), allow_redirects=False)
# response
headerloc = postbattle.headers.get('location')
time_now = int(time.time())
try:
time_uploaded = json.loads(postbattle.text)["created_at"]["time"]
except KeyError:
time_uploaded = None
except json.decoder.JSONDecodeError: # retry once
postbattle = requests.post(url, headers=auth, data=msgpack.packb(payload), allow_redirects=False)
headerloc = postbattle.headers.get('location')
time_now = int(time.time())
try:
time_uploaded = json.loads(postbattle.text)["created_at"]["time"]
except:
print("Error with stat.ink. Please try again.")
detail_type = "vsHistoryDetail" if which == "ink" else "coopHistoryDetail"
result_id = results[i]["data"][detail_type]["id"]
noun = utils.set_noun(which)[:-1]
if DEBUG:
print(f"* time uploaded: {time_uploaded}; time now: {time_now}")
if istestrun and postbattle.status_code == 200:
print(f"Successfully validated {noun} ID {result_id} with stat.ink.")
elif postbattle.status_code != 201: # Created (or already exists)
print(f"Error uploading {noun}. (ID: {result_id})")
print("Message from server:")
print(postbattle.content.decode('utf-8'))
elif time_uploaded <= time_now - 7: # give some leeway
print(f"{noun.capitalize()} already uploaded - {headerloc}")
else: # 200 OK
print(f"{noun.capitalize()} uploaded to {headerloc}")
def check_for_updates():
'''Checks the script version against the repo, reminding users to update if available.'''
try:
latest_script = requests.get("https://raw.githubusercontent.com/frozenpandaman/s3s/master/s3s.py")
new_version = re.search(r'A_VERSION = "([\d.]*)"', latest_script.text).group(1)
update_available = version.parse(new_version) > version.parse(A_VERSION)
if update_available:
print(f"\nThere is a new version (v{new_version}) available.", end='')
if os.path.isdir(".git"):
update_now = input("\nWould you like to update now? [Y/n] ")
if update_now == "" or update_now[0].lower() == "y":
FNULL = open(os.devnull, "w")
call(["git", "checkout", "."], stdout=FNULL, stderr=FNULL)