Revert "Merge branch 'wrapper' of https://github.com/RedstonerServer/redstoner-utils into wrapper"

This reverts commit 4d5861fd36, reversing
changes made to 9d0e4c99ba.
This commit is contained in:
Dico200
2015-11-25 15:49:52 +01:00
parent 0172cf2feb
commit 1969584312
10 changed files with 120 additions and 222 deletions

View File

@@ -1,30 +1,26 @@
#pylint: disable = F0401
import org.bukkit as bukkit
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 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
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.event.entity as entity
import org.bukkit.command.ConsoleCommandSender
from org.bukkit.entity import *
from player import get_py_player
from player import py_players
#Imports for async query
import threading
import mysqlhack
from secrets import *
import mysqlhack
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
@@ -218,6 +214,31 @@ 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

View File

@@ -8,7 +8,7 @@ import mysqlhack
from com.ziclix.python.sql import zxJDBC
from java.lang import Runnable
wait_time = 60 #seconds
wait_time = 30 #seconds
admin_perm = "utils.loginsecurity.admin"
min_pass_length = 8
blocked_events = ["block.BlockBreakEvent", "block.BlockPlaceEvent", "player.PlayerMoveEvent","player.AsyncPlayerChatEvent"]
@@ -272,4 +272,4 @@ def pre_command_proccess(event):
args = event.getMessage().split(" ")
if not args[0].lower() == "/login":
msg(player.player, "&4You need to login before you do that!")
event.setCancelled(True)
event.setCancelled(True)

81
main.py
View File

@@ -11,9 +11,8 @@ 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 Wrapper:")
print("[RedstonerUtils] ERROR: Failed to import helpers:")
print(print_traceback())
@@ -25,17 +24,85 @@ 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"] = ["test"]
shared["load_modules"] = [
# Collection of tiny utilities
"misc",
# Adds chat for staff using /ac <text or ,<text>
"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 <n> 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["modules"] = {}
for module in shared["load_modules"]:
try:

View File

@@ -1,33 +0,0 @@
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)

View File

@@ -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 jarray
import java.net.URL
import java.io.File
from java.lang import Class
import java.net.URLClassLoader
import java.lang.reflect.Method
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import jarray
from java.lang import Class
# hacky code to add mysql-connector to java's classpath ('classPathHack')

View File

@@ -1,24 +0,0 @@
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

View File

@@ -1,11 +0,0 @@
"""
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 *

View File

@@ -1,11 +0,0 @@
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

View File

@@ -1,22 +0,0 @@
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

View File

@@ -1,89 +0,0 @@
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
#test
@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()])