From 70b4db5318075c6f15eae65f7a75488964ec0390 Mon Sep 17 00:00:00 2001 From: BuildTools Date: Mon, 23 Nov 2015 22:17:40 +0100 Subject: added wrappers, temp disabled all modules --- helpers.py | 51 +++++++++---------------------- main.py | 81 +++++-------------------------------------------- mysql_utils.py | 33 ++++++++++++++++++++ mysqlhack.py | 8 ++--- thread_utils.py | 24 +++++++++++++++ wrapper.py | 11 +++++++ wrapper_command.py | 11 +++++++ wrapper_event.py | 22 ++++++++++++++ wrapper_player.py | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 216 insertions(+), 114 deletions(-) create mode 100644 mysql_utils.py create mode 100644 thread_utils.py create mode 100644 wrapper.py create mode 100644 wrapper_command.py create mode 100644 wrapper_event.py create mode 100644 wrapper_player.py diff --git a/helpers.py b/helpers.py index 79af3a0..f7e125e 100644 --- a/helpers.py +++ b/helpers.py @@ -1,26 +1,30 @@ #pylint: disable = F0401 -from re import sub -from java.util.UUID import fromString as juuid -from json import dumps as json_dumps, loads as json_loads + import org.bukkit as bukkit -import org.bukkit.Location as Location -import org.bukkit.entity.Player as Player -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause as TeleportCause -import org.bukkit.event.block.BlockBreakEvent as BlockBreakEvent import org.bukkit.block as bblock +import org.bukkit.Location as Location import org.bukkit.event.entity as entity +import org.bukkit.entity.Player as Player import org.bukkit.command.ConsoleCommandSender +import org.bukkit.event.block.BlockBreakEvent as BlockBreakEvent +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause as TeleportCause + +from re import sub +from thread_utils import * +from player import py_players from org.bukkit.entity import * from player import get_py_player -from player import py_players +from traceback import format_exc as trace +from java.util.UUID import fromString as juuid +from json import dumps as json_dumps, loads as json_loads #Imports for async query -from secrets import * +import threading import mysqlhack + +from secrets import * from com.ziclix.python.sql import zxJDBC -import threading -from traceback import format_exc as trace shared = {} # this dict can be used to share stuff across modules @@ -214,31 +218,6 @@ def known_player(player): """ return player.hasPlayedBefore() -""" -Runs a async query, calls target function with fetchall as an argument, it will be an empty list if there is nothing to fetch. -(So make sure your function takes that argument.) - -If you want your function to run sync in the case you are doing something spigot wouldn't like to be async use the bukkit scheduler. -Example can be found in loginsecurity.py - -""" -def async_query(mysql_database,query,query_args,target,*target_args,**target_kwargs): - - def async_query_t(mysql_database,query,query_args,target,target_args,target_kwargs): - db_conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver") - db_curs = db_conn.cursor() - db_curs.execute(query,query_args) - db_conn.commit() - fetchall = db_curs.fetchall() - db_curs.close() - db_conn.close() - target(fetchall,target_args,target_kwargs) - - t = threading.Thread(target=async_query_t,args=(mysql_database,query,query_args,target,target_args,target_kwargs)) - t.daemon = True - t.start() - - def open_json_file(filename, default = None): """ opens the given json file and returns an object or returns None on error diff --git a/main.py b/main.py index 7411d17..3e1319d 100644 --- a/main.py +++ b/main.py @@ -11,8 +11,9 @@ sys.path += ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/l try: # Library that adds a bunch of re-usable methods which are used in nearly all other modules from helpers import * + from wrapper import * except: - print("[RedstonerUtils] ERROR: Failed to import helpers:") + print("[RedstonerUtils] ERROR: Failed to import Wrapper:") print(print_traceback()) @@ -24,85 +25,17 @@ def on_enable(): @hook.disable def on_disable(): - shared["modules"]["reports"].stop_reporting() + #shared["modules"]["reports"].stop_reporting() info("RedstonerUtils disabled!") info("Loading RedstonerUtils...") + + # Import all modules, in this order -shared["load_modules"] = [ - # Collection of tiny utilities - "misc", - # Adds chat for staff using /ac - "adminchat", - # Adds /badge, allows to give players achievements - "badges", - # Adds a few block placement corrections/mods - "blockplacemods", - # Adds /calc, toggles automatic solving of Math expressions in chat - "calc", - # Adds aliasing of chat words - #"chatalias", - # Plugin to locate laggy chunks. /lc lists chunks with more than n entities - "lagchunks", - # Adds /report and /rp, Stores reports with time and location - "reports", - # Adds group-chat with /chatgroup and /cgt to toggle normal chat into group mode - "chatgroups", - # Adds /token, reads and writes from the database to generate pronouncable (and thus memorable) registration-tokens for the website - "webtoken", - # Adds /lol, broadcasts random funyy messages. A bit like the splash text in the menu - "saylol", - # Adds /signalstrength, lets you request a signal strength and an amount of items will be inserted into target container to meet that strength. - "signalstrength", - # Shows the owner of a skull when right-clicked - "skullclick", - # Adds /listen, highlights chat and plays a sound when your name was mentioned - "mentio", - # Adds /cycler, swaps the hotbar with inventory when player changes slot from right->left or left->right - "cycle", - # Adds /getmotd & /setmotd to update the motd on the fly (no reboot) - "motd", - # AnswerBot. Hides stupid questions from chat and tells the sender about /faq or the like - "abot", - # Adds '/forcefield', creates forcefield for players who want it. - "forcefield", - # Adds /damnspam, creates timeout for buttons/levers to mitigate button spam. - "damnspam", - # Adds /check, useful to lookup details about a player - "check", - # Adds /an, a command you can use to share thoughts/plans/news - "adminnotes", - # Adds busy status to players - "imbusy", - # Adds /imout, displays fake leave/join messages - "imout", - #adds snowbrawl minigame - "snowbrawl", - # Adds /tm [player] for a messages to be sent to this player via /msg - "pmtoggle", - # Replacement for LoginSecurity - "loginsecurity", - # Centralized Player class - "player", - # Servercontrol extension for telnet access to logs/AC - #"servercontrol", - # Script helper plugin - "scriptutils", - # Per-player notes - "tag", - # vanish toggle module - temporary fix - #"vanishfix", - # obisidian mining punishment plugin - "punishments", - # a simple replacement for the buggy essentials /vanish - "vanish", - # ip-tracking utility - "iptracker", - #server signs for everyone - "serversigns" -] +shared["load_modules"] = ["test"] + shared["modules"] = {} for module in shared["load_modules"]: try: diff --git a/mysql_utils.py b/mysql_utils.py new file mode 100644 index 0000000..e59c3d9 --- /dev/null +++ b/mysql_utils.py @@ -0,0 +1,33 @@ +import mysqlhack +from secrets import * +from thread_utils import * +from com.ziclix.python.sql import zxJDBC +from traceback import format_exc as trace + +class mysql_connect: + def __init__(self): + self.conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver") + self.curs = self.conn.cursor() + + def execute(self, query, args=None): + if args is None: + return self.curs.execute(query) + else: + return self.curs.execute(query, args) + + def fetchall(self): + return self.curs.fetchall() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_inst, exc_tb): + if exc_type is None: + try: + self.conn.commit() + self.curs.close() + self.conn.close() + except: + print(trace()) + else: + print(exc_tb) diff --git a/mysqlhack.py b/mysqlhack.py index 7153bdf..5d45c52 100644 --- a/mysqlhack.py +++ b/mysqlhack.py @@ -4,12 +4,12 @@ A library that makes use of the so called ClassPathHack for jython to allow proper loading of mysql-connector.jar at runtime. Import only, no methods. """ -import java.lang.reflect.Method -import java.io.File -import java.net.URL -import java.net.URLClassLoader import jarray +import java.net.URL +import java.io.File from java.lang import Class +import java.net.URLClassLoader +import java.lang.reflect.Method # hacky code to add mysql-connector to java's classpath ('classPathHack') diff --git a/thread_utils.py b/thread_utils.py new file mode 100644 index 0000000..ec13c6f --- /dev/null +++ b/thread_utils.py @@ -0,0 +1,24 @@ +import threading +""" +Quick implementation of a @synchronized and @asynchronized decorators +""" + +#To be replaced by bukkit scheduler. +""" +def sync(lock=None): + def decorator(wrapped): + def wrapper(*args, **kwargs): + with lock: + return wrapped(*args, **kwargs) + return wrapper + return decorator +""" + +def async(daemon = True): + def decorator(function): + def wrapper(*args,**kwargs): + thread = threading.Thread(target=function,args=args,kwargs=kwargs) + thread.daemon = daemon + thread.start() + return wrapper + return decorator \ No newline at end of file diff --git a/wrapper.py b/wrapper.py new file mode 100644 index 0000000..ddca5b5 --- /dev/null +++ b/wrapper.py @@ -0,0 +1,11 @@ +""" +Adapter classes for spigot api for more idiomatic python code. + +Before you run away from this if the class you need to use isn't here, please create it. + + +""" +from helpers import * +from wrapper_event import * +from wrapper_player import * +from wrapper_command import * \ No newline at end of file diff --git a/wrapper_command.py b/wrapper_command.py new file mode 100644 index 0000000..dd51534 --- /dev/null +++ b/wrapper_command.py @@ -0,0 +1,11 @@ +from wrapper_player import * + +def command(command = "help"): + def decorator(wrapped): + @hook.command(command) + def wrapper(sender, command, label, args): + try: + return wrapped(sender = py_players[sender], command = command, label = label, args = args) + except: + print(print_traceback()) + return decorator \ No newline at end of file diff --git a/wrapper_event.py b/wrapper_event.py new file mode 100644 index 0000000..083bf33 --- /dev/null +++ b/wrapper_event.py @@ -0,0 +1,22 @@ +from wrapper import * +from wrapper_player import * +from traceback import format_exc as print_traceback + +class py_event: + def __init__(self,event): + self.event = event + try: + self.player = py_players[event.getPlayer()] + except: + warn("Player doesn't exist") + +def event_handler(event_name = None, priority = "normal"): + def decorator(wrapped): + @hook.event(event_name, priority) + def wrapper(event): + try: + wrapped(py_event(event)) + except: + print(print_traceback()) + return decorator + diff --git a/wrapper_player.py b/wrapper_player.py new file mode 100644 index 0000000..aca0e60 --- /dev/null +++ b/wrapper_player.py @@ -0,0 +1,89 @@ +import time +import mysqlhack +from mysql_utils import * +from thread_utils import * +from players_secret import * +from datetime import datetime +from com.ziclix.python.sql import zxJDBC + +class py_player: + def __init__(self,player): + self.player = player + self.login_time = time.time() + self.logging_in = False + + self.nickname = self.name + self.registered = False + self.password = "None" + self.banned = False + self.banned_reason = "You have been banned!" + self.played_time = time.time() - self.login_time + self.last_login = datetime.now() + self.first_seen = datetime.now() + + def kick(self, kick_message = "You have been kicked from the server!"): + self.player.KickPlayer(kick_message) + + @property + def name(self): + return self.player.getName() + + @property + def uuid(self): + return str(self.player.getUniqueId()) + + +class Py_players: + def __init__(self): + self.players = [] + + def __len__(self): + return len(self.players) + + def __getitem__(self, player): + for py_player in self.players: + if py_player.name == player.getName(): + return py_player + else: + return None + + def remove(self, player): + self.players.remove(player) + + def append(self, player): + self.players.append(player) + +py_players = Py_players() + +@async(daemon=True) +def fetch_player(player): + with mysql_connect() as sql: + sql.execute("SELECT * FROM utils_players WHERE uuid = ?", (player.uuid,)) + result = sql.fetchall() + + if len(result) is 0: + with mysql_connect() as sql: + sql.execute("INSERT INTO utils_players \ + (uuid, name, nickname, registered, password, banned, \ + banned_reason, played_time, last_login, first_seen) \ + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + args=(player.uuid, player.name, player.nickname, player.registered, + player.password, player.banned, + player.banned_reason, player.played_time, + player.last_login, player.first_seen)) + else: + pass + + + +@hook.event("player.PlayerJoinEvent","lowest") +def on_join(event): + player = py_player(event.getPlayer()) + py_players.append(player) + fetch_player(player) + + +@hook.event("player.PlayerQuitEvent","highest") +def on_leave(event): + py_players.remove(py_players[event.getPlayer()]) -- cgit v1.2.3