From 27c66ba593683aa167d364964b5385b9a0d0bdd8 Mon Sep 17 00:00:00 2001 From: Jesusaves Date: Wed, 4 Aug 2021 15:26:49 -0300 Subject: Add another verbosity level, otherwise debug.txt will be a monster --- battle/main.py | 56 ++++++++++++++++++++++++++++---------------------------- server.py | 19 +++++++++++-------- sql.py | 19 ++++++++++--------- utils.py | 13 ++++++++----- 4 files changed, 57 insertions(+), 50 deletions(-) diff --git a/battle/main.py b/battle/main.py index f3b13f9..4cd5f7c 100644 --- a/battle/main.py +++ b/battle/main.py @@ -47,7 +47,7 @@ def advance_wave(token, world, quest_id, next_wave): quest=dl_search(allquests[world], "quest_id", quest_id) if quest == "ERROR": - stdout("ERROR, INVALID QUEST: %d" % (quest_id)) + stdout("ERROR, INVALID QUEST: %d" % (quest_id), 0) # TODO: HANDLE THIS ERROR (FIXME) for en in quest["waves"][next_wave]: @@ -56,7 +56,7 @@ def advance_wave(token, world, quest_id, next_wave): mil*=5.5 mil=mil - stdout("Recording new enemy with mil: %d" % mil) + stdout("Recording new enemy with mil: %d" % mil, 2) Battle[token]["enemy"].append({ "name": en["name"], "unit_id": en["sprite"], @@ -68,7 +68,7 @@ def advance_wave(token, world, quest_id, next_wave): }) # Update wave - stdout("Advancing wave") + stdout("Advancing wave", 2) Battle[token]["wave"]+=1 return True @@ -85,7 +85,7 @@ def get_result(token, victory, world, quest_id): "log": Battle[token]["log"] } - stdout("GR: Begin") + stdout("GR: Begin", 2) # You lost? if not victory: result["result"]="DEFEAT" @@ -96,11 +96,11 @@ def get_result(token, victory, world, quest_id): quest=dl_search(allquests[world], "quest_id", quest_id) if quest == "ERROR": print("ERROR, INVALID QUEST") - stdout("Quest %d is invalid", str(quest_id)) + stdout("Quest %d is invalid" % quest_id, 0) # TODO: HANDLE THIS ERROR (FIXME) return result - stdout("GR: Rolling") + stdout("GR: Rolling", 2) # Roll each wave # Base quest experience gain result["exp"]+=quest["difficulty"]*10 @@ -117,7 +117,7 @@ def get_result(token, victory, world, quest_id): # TODO: Roll the loots for every enemy in every death result["exp"]=int(result["exp"]) - stdout("GR: Looting") + stdout("GR: Looting", 2) # For now, loots are rolled for quest # 2- Roll loot list for loot, chance in quest["loot"]: @@ -135,7 +135,7 @@ def get_result(token, victory, world, quest_id): else: result["loot"].append(int(loot)*100) # Fix Unit ID from base to ID - stdout("GR: Flagging") + stdout("GR: Flagging", 2) # Mark the quest as complete and grant you crystals for first clear # But this is based on the flags (we can have special quests) if (not (quest["flags"] & SFLAG_SPECIAL) and Player[token]["quest"] < quest["quest_id"]): @@ -156,7 +156,7 @@ def get_result(token, victory, world, quest_id): if (quest["flags"] & SFLAG_DOUBLEGP): result["gp"]*=2 - stdout("GR: Applying") + stdout("GR: Applying", 2) # Apply the results to player data Player[token]["gp"]+=result["gp"] Player[token]["exp"]+=result["exp"] @@ -174,7 +174,7 @@ def get_result(token, victory, world, quest_id): result["loot"].remove(it) # TODO: Send result ERR_FULL - stdout("GR: EXPing") + stdout("GR: EXPing", 2) # Grant to party the same amount of experience pid=Battle[token]["party_id"] for m in Player[token]["party_"+str(pid)]: @@ -187,7 +187,7 @@ def get_result(token, victory, world, quest_id): stdout("Unit %d levelled up %d times" % (m["inv_id"], v5)) - stdout("GR: Ranking") + stdout("GR: Ranking", 2) # Player rank up rk=player.check_rank_up(token) if rk["code"]: @@ -210,7 +210,7 @@ def begin_quest(args, token, client_side=True): try: stdout("Begin Quest: %s" % args) bq=json.loads(args) - stdout("JSON loaded") + stdout("JSON loaded", 2) # Validation tmp=int(bq["quest_id"]) tmp=int(bq["party_id"]) @@ -223,9 +223,9 @@ def begin_quest(args, token, client_side=True): break if (quest["quest_id"] != bq["quest_id"]): raise Exception("Quest not found") - stdout("All fine thus far") + stdout("All fine thus far", 2) except: - stdout(traceback.format_exc()) + stdout(traceback.format_exc(), 0) # Invalid data return ERR_BAD @@ -238,7 +238,7 @@ def begin_quest(args, token, client_side=True): return ERR_BAD if (Player[token]["ap"] < quest["cost"] and client_side): return ERR_BAD - stdout("You can begin it!") + stdout("You can begin it!", 2) Player[token]["status"]=int(quest["quest_id"]) @@ -262,7 +262,7 @@ def begin_quest(args, token, client_side=True): "log": [], "turn": 1} - stdout("Data set") + stdout("Data set", 2) # Write the current wave enemies data advance_wave(token, bq["world"], quest["quest_id"], 0) @@ -287,7 +287,7 @@ def begin_quest(args, token, client_side=True): print("Error, un and ux differs: %s vs %s" % (str(un["unit_id"]), str(ux["unit_id"]))) return ERR_ERR - stdout("Preparing party member") + stdout("Preparing party member", 2) # How much HP/ATK bonus per level you'll get? # Each level boosts your stats in 1% @@ -337,7 +337,7 @@ def battle_endturn(token, spheres): stdout("Turn has ended") # Resave spheres - stdout("Sphere list: "+str(spheres)) + stdout("Sphere list: "+str(spheres), 2) Battle[token]["spheres"]=[] for i in spheres: Battle[token]["spheres"].append(int(i)) @@ -345,7 +345,7 @@ def battle_endturn(token, spheres): # Remove an eventual none spheres while (Battle[token]["spheres"].count(SPH_NONE)): Battle[token]["spheres"].remove(SPH_NONE) - stdout("Exceeding spheres removed") + stdout("Exceeding spheres removed", 2) # Add 1~3 random spheres; But never go over 5 spheres i=min(random.randint(1,3), len(Battle[token]["spheres"]) - 5) @@ -363,7 +363,7 @@ def battle_endturn(token, spheres): Battle[token]["log"].append(["SP", len(Battle[token]["spheres"]), sp, "", 0]) Battle[token]["spheres"].append(sp) - stdout("Spheres added; Status before adjust: %s" % (str(Battle[token]["spheres"]))) + stdout("Spheres added; Status before adjust: %s" % (str(Battle[token]["spheres"])), 2) # Add empty spheres to keep length while (len(Battle[token]["spheres"]) < 5): @@ -376,7 +376,7 @@ def battle_endturn(token, spheres): pass # Send data to client - stdout("Sending data") + stdout("Sending data", 2) sjson=compress(Battle[token]) stdout("Data sent: %s" % sjson) return sjson @@ -445,7 +445,7 @@ def battle(args, token): # Erase temporary variables del tmp - stdout("Party reordered (SKIPPED)") + stdout("Party reordered (SKIPPED)", 2) Battle[token]["log"]=[] ####################################### @@ -467,7 +467,7 @@ def battle(args, token): # Will you use a sphere? idx=Battle[token]["party"].index(bat) - stdout("Check index %d" % idx) + stdout("Check index %d" % idx, 2) if (bt["sphere"][idx] == ACT_SPHERE): # Remove the sphere spheres[idx]=SPH_NONE @@ -476,7 +476,7 @@ def battle(args, token): else: sphere_attack(token, bat, SPH_NONE, idx) Battle[token]["bp"]+=1 - stdout("Attack performed") + stdout("Attack performed", 2) # If HP ends up broken if (bat["hp"] > bat["max_hp"]): @@ -500,7 +500,7 @@ def battle(args, token): del Battle[token] return compress(result) - stdout("Friends executed") + stdout("Friends executed", 2) # It never harms checking for suicide... if (not check_player_alive(token)): @@ -519,13 +519,13 @@ def battle(args, token): # Simple Attack target_id=find_target(token, "party") - stdout("ENEMY: Perform attack against %d" % target_id) + stdout("ENEMY: Perform attack against %d" % target_id, 2) target=Battle[token]["party"][target_id] target["hp"]-=calc_dmg(token, bat, target, bat["atk"]) Battle[token]["bp"]+=1 Battle[token]["log"].append(["enemy", idx, SPH_NONE, "party", target_id]) - stdout("ENEMY: Attack performed") + stdout("ENEMY: Attack performed", 2) # If HP ends up broken if (bat["hp"] > bat["max_hp"]): @@ -541,7 +541,7 @@ def battle(args, token): return compress(result) - stdout("Enemies executed") + stdout("Enemies executed", 2) return battle_endturn(token, spheres) # Reload battle will only inform the client again of the battle status diff --git a/server.py b/server.py index 2dee2ba..84ab8b1 100755 --- a/server.py +++ b/server.py @@ -54,8 +54,8 @@ class WebSocketConn(WebSocket): print("Message received from %s - %s" % (self.address[0], self.data)) try: r=protocol.parse(self.data, self) - print("Status: %s" % str(r[0])) - print("Reply: %s" % r[1]) + stdout("Status: %s" % str(r[0]), 2) + stdout("Reply: %s" % r[1], 2) if r[0] < PACKET_ACK: stdout("%s - %s" % (self.address[0], r[1])) syslog.syslog(LOG_AUTH, "%s - %s" % (self.address[0], r[1])) @@ -67,7 +67,7 @@ class WebSocketConn(WebSocket): traceback.print_exc() self.send_message("ERROR\n") - print("Message sent") + stdout("Message sent", 2) #stdout(self.address[0] + u' - %s' % (self.data)) #self.send_message('ACK') @@ -127,7 +127,7 @@ class WebSocketConn(WebSocket): player.clear(self.token) except: traceback.print_exc() - stdout("Error at player.clear") + stdout("Error at player.clear", 0) ########################## # Useful functions: @@ -179,7 +179,7 @@ def disconnect(ip): ############################################################### # Begin stuff -stdout("Starting at: T-%d" % (now())) +stdout("Starting at: T-%d" % (now()), 0) syslog.openlog() MainWebsocket() try: @@ -218,8 +218,11 @@ try: sendmsg("NOTICE:Server is going down for scheduled maintenance. Please close, wait five minutes, and then re-open the app.") break elif cmd in ["dbg", "debug"]: - debug = not debug - stdout("Changed debug mode to %s" % str(debug)) + if debug == 2: + debug = 0 + else: + debug += 1 + stdout("Changed debug mode to %d" % debug) elif cmd in ["raw", "eval"] and debug: try: print(eval(com)) @@ -259,7 +262,7 @@ try: else: stdout("ERROR: Unknown command.") except: - stdout("Abrupt error: Terminating!") + stdout("Abrupt error: Terminating!", 0) traceback.print_exc() # Wait a bit before disconnecting all clients diff --git a/sql.py b/sql.py index 89e5c5d..90befa9 100644 --- a/sql.py +++ b/sql.py @@ -71,11 +71,12 @@ def save_player(token, mask=SQL_NONE): Player[token]["aptime"], Player[token]["userid"]) - stdout(sqlx) + stdout(sqlx, 2) try: w.execute(sqlx) except: - stdout("SQL.ERR: Error happened (save.player), commiting anyway due MyISAM...") + stdout("SQL.ERR: Error happened (save.player), commiting anyway due MyISAM...", 0) + stdout("Faulty: %s" % sqlx, 0) #w.execute("INSERT INTO ....") # <- Not in save_player #w.execute("REPLACE DELAYED....") # <- Not where you can't delete, but for inv @@ -128,7 +129,7 @@ def save_inv(token, mask=SQL_NONE, force=False): w.execute("""DELETE FROM `inventory` WHERE `userid` = %d AND `index` = %d""" % (uid, i)) - stdout("SQL.INV: Delete where uid %d and index %d" % (uid, i)) + stdout("SQL.INV: Delete where uid %d and index %d" % (uid, i), 2) i+=1 continue @@ -140,7 +141,7 @@ def save_inv(token, mask=SQL_NONE, force=False): % (m, uid, i, it["unit_id"], it["level"], it["exp"])) except: # Something went wrong! - print("ERROR Saving item index %d for player %d: %s\n%s" % (i, uid, str(it), fatalmsg)) + stdout("ERROR Saving item index %d for player %d: %s\n%s" % (i, uid, str(it), fatalmsg), 0) if not force: revert=True finally: @@ -149,14 +150,14 @@ def save_inv(token, mask=SQL_NONE, force=False): # If something went wrong, don't save inventory if revert: #db.rollback() - stdout("SQL.ERR: Error happened, commiting anyway due MyISAM...") + stdout("SQL.ERR: Error happened, commiting anyway due MyISAM...", 0) # We should now remove every item with an index higher than length # In case the inventory shrink without None's taking the place... w.execute("""DELETE FROM `inventory` WHERE `userid` = %d AND `index` >= %d""" % (uid, len(inv))) - stdout("SQL.INV: delete indexes >= %d, committing changes" % len(inv)) + stdout("SQL.INV: delete indexes >= %d, committing changes" % len(inv), 2) db.commit() w.close() @@ -190,10 +191,10 @@ def save_party(token, mask=SQL_NONE): Player[token]["party_%d" % i][3]["inv_id"], Player[token]["userid"], i) - stdout(sqlx) + stdout(sqlx, 2) w.execute(sqlx) except: - print("[SQL ERROR] Impossible to save party %d" % i) + stdout("[SQL ERROR] Impossible to save party %d" % i, 0) db.rollback() i+=1 @@ -354,7 +355,7 @@ def keep_alive(): db.ping(reconnect=True, attempts=10, delay=1) except: # SQL error - stdout("keep_alive: INTERNAL ERROR") + stdout("keep_alive: INTERNAL ERROR", 0) db.reconnect(attempts=12, delay=10) sql_keep_alive=threading.Timer(SQL_PINGTIME, keep_alive) sql_keep_alive.daemon=True diff --git a/utils.py b/utils.py index c4f94c4..447eef9 100644 --- a/utils.py +++ b/utils.py @@ -21,8 +21,11 @@ import time, hashlib, datetime, uuid import json, zlib, base64 -# Be verbose -debug=True +# Set server debug level +# 0 - Production/Stable, Silent +# 1 - Production/Unstable +# 2 - Development/Debug +debug=1 # Create a variable called "salt", which contains the token saltening sequence s=open("salt.txt", "r") @@ -77,8 +80,8 @@ def date_from_now(): def stdout(mx, verbose=1): - print(mx) if (debug >= verbose): + print(mx) dfile=open("debug.txt", 'a') dt=datetime.datetime.now().timetuple() date="[%04d-%02d-%02d %02d:%02d:%02d]" % (dt[0], dt[1], dt[2], dt[3], dt[4], dt[5]) @@ -86,13 +89,13 @@ def stdout(mx, verbose=1): dfile.close() def compress(string): - stdout("Compress: Received JSON data: %s" % (string)) + stdout("Compress: Received JSON data: %s" % (string), 1) sjs=json.dumps(string) sjs=sjs.encode("ascii") sjs=zlib.compress(sjs) sjs=base64.b64encode(sjs) sjs=sjs.decode("ascii") - stdout("Compress: Sending base64+zlib JSON ASCII data: %s" % (sjs)) + stdout("Compress: Sending base64+zlib JSON ASCII data: %s" % (sjs), 2) return sjs # Search for array[?][key]==search in an array of dicts -- cgit v1.2.3-60-g2f50