Fixed bad indentation.

This commit is contained in:
loki77 2008-06-17 00:38:59 +00:00
parent 6b1662f370
commit 186dcc17c5
2 changed files with 278 additions and 278 deletions

View file

@ -14,245 +14,245 @@ import comsys
from util import functions_general from util import functions_general
class UnknownCommand(Exception): class UnknownCommand(Exception):
""" """
Throw this when a user enters an an invalid command. Throw this when a user enters an an invalid command.
""" """
def match_exits(pobject, searchstr): def match_exits(pobject, searchstr):
""" """
See if we can find an input match to exits. See if we can find an input match to exits.
""" """
exits = pobject.get_location().get_contents(filter_type=4) exits = pobject.get_location().get_contents(filter_type=4)
return Object.objects.list_search_object_namestr(exits, searchstr, match_type="exact") return Object.objects.list_search_object_namestr(exits, searchstr, match_type="exact")
def parse_command(command_string): def parse_command(command_string):
""" """
Tries to handle the most common command strings and returns a dictionary with various data. Tries to handle the most common command strings and returns a dictionary with various data.
Common command types: Common command types:
- Complex: - Complex:
@pemit[/option] <target>[/option]=<data> @pemit[/option] <target>[/option]=<data>
- Simple: - Simple:
look look
look <target> look <target>
I'm not married to either of these terms, but I couldn't think of anything better. If you can, lets change it :) I'm not married to either of these terms, but I couldn't think of anything better. If you can, lets change it :)
The only cases that I haven't handled is if someone enters something like: The only cases that I haven't handled is if someone enters something like:
@pemit <target> <target>/<switch>=<data> @pemit <target> <target>/<switch>=<data>
- Ends up considering both targets as one with a space between them, and the switch as a switch. - Ends up considering both targets as one with a space between them, and the switch as a switch.
@pemit <target>/<switch> <target>=<data> @pemit <target>/<switch> <target>=<data>
- Ends up considering the first target a target, and the second target as part of the switch. - Ends up considering the first target a target, and the second target as part of the switch.
""" """
# Each of the bits of data starts off as None, except for the raw, original # Each of the bits of data starts off as None, except for the raw, original
# command # command
parsed_command = dict( parsed_command = dict(
raw_command=command_string, raw_command=command_string,
data=None, data=None,
original_command=None, original_command=None,
original_targets=None, original_targets=None,
base_command=None, base_command=None,
command_switches=None, command_switches=None,
targets=None, targets=None,
target_switches=None target_switches=None
) )
try: try:
# If we make it past this next statement, then this is what we # If we make it past this next statement, then this is what we
# consider a complex command # consider a complex command
(command_parts, data) = command_string.split('=', 1) (command_parts, data) = command_string.split('=', 1)
parsed_command['data'] = data parsed_command['data'] = data
# First we deal with the command part of the command and break it # First we deal with the command part of the command and break it
# down into the base command, along with switches # down into the base command, along with switches
# If we make it past the next statement, then they must have # If we make it past the next statement, then they must have
# entered a command like: # entered a command like:
# p =<data> # p =<data>
# So we should probably just let it get caught by the ValueError # So we should probably just let it get caught by the ValueError
# again and consider it a simple command # again and consider it a simple command
(total_command, total_targets) = command_parts.split(' ', 1) (total_command, total_targets) = command_parts.split(' ', 1)
parsed_command['original_command'] = total_command parsed_command['original_command'] = total_command
parsed_command['original_targets'] = total_targets parsed_command['original_targets'] = total_targets
split_command = total_command.split('/') split_command = total_command.split('/')
parsed_command['base_command'] = split_command[0] parsed_command['base_command'] = split_command[0]
parsed_command['command_switches'] = split_command[1:] parsed_command['command_switches'] = split_command[1:]
# Now we move onto the target data # Now we move onto the target data
try: try:
# Look for switches- if they give target switches, then we don't # Look for switches- if they give target switches, then we don't
# accept multiple targets # accept multiple targets
(target, switch_string) = total_targets.split('/', 1) (target, switch_string) = total_targets.split('/', 1)
parsed_command['targets'] = [target] parsed_command['targets'] = [target]
parsed_command['target_switches'] = switch_string.split('/') parsed_command['target_switches'] = switch_string.split('/')
except ValueError: except ValueError:
# Alright, no switches, so lets consider multiple targets # Alright, no switches, so lets consider multiple targets
parsed_command['targets'] = total_targets.split() parsed_command['targets'] = total_targets.split()
except ValueError: except ValueError:
# Ok, couldn't find an =, so not a complex command # Ok, couldn't find an =, so not a complex command
try: try:
(command, data) = command_string.split(' ', 1) (command, data) = command_string.split(' ', 1)
parsed_command['base_command'] = command parsed_command['base_command'] = command
parsed_command['data'] = data parsed_command['data'] = data
except ValueError: except ValueError:
# No arguments # No arguments
# ie: # ie:
# - look # - look
parsed_command['base_command'] = command_string parsed_command['base_command'] = command_string
return parsed_command return parsed_command
def handle(cdat): def handle(cdat):
""" """
Use the spliced (list) uinput variable to retrieve the correct Use the spliced (list) uinput variable to retrieve the correct
command, or return an invalid command error. command, or return an invalid command error.
We're basically grabbing the player's command by tacking We're basically grabbing the player's command by tacking
their input on to 'cmd_' and looking it up in the GenCommands their input on to 'cmd_' and looking it up in the GenCommands
class. class.
""" """
session = cdat['session'] session = cdat['session']
server = cdat['server'] server = cdat['server']
try: try:
# TODO: Protect against non-standard characters. # TODO: Protect against non-standard characters.
if cdat['uinput'] == '': if cdat['uinput'] == '':
return
parsed_input = {}
parsed_input['parsed_command'] = parse_command(cdat['uinput'])
# First we split the input up by spaces.
parsed_input['splitted'] = cdat['uinput'].split()
# Now we find the root command chunk (with switches attached).
parsed_input['root_chunk'] = parsed_input['splitted'][0].split('/')
# And now for the actual root command. It's the first entry in root_chunk.
parsed_input['root_cmd'] = parsed_input['root_chunk'][0].lower()
# Keep around the full, raw input in case a command needs it
cdat['raw_input'] = cdat['uinput']
# Now we'll see if the user is using an alias. We do a dictionary lookup,
# if the key (the player's root command) doesn't exist on the dict, we
# don't replace the existing root_cmd. If the key exists, its value
# replaces the previously splitted root_cmd. For example, sa -> say.
alias_list = server.cmd_alias_list
parsed_input['root_cmd'] = alias_list.get(parsed_input['root_cmd'],parsed_input['root_cmd'])
# This will hold the reference to the command's function.
cmd = None
if session.logged_in:
# Store the timestamp of the user's last command.
session.cmd_last = time.time()
# Lets the users get around badly configured NAT timeouts.
if parsed_input['root_cmd'] == 'idle':
return return
parsed_input = {} # Increment our user's command counter.
parsed_input['parsed_command'] = parse_command(cdat['uinput']) session.cmd_total += 1
# Player-visible idle time, not used in idle timeout calcs.
session.cmd_last_visible = time.time()
# First we split the input up by spaces. # Just in case. Prevents some really funky-case crashes.
parsed_input['splitted'] = cdat['uinput'].split() if len(parsed_input['root_cmd']) == 0:
# Now we find the root command chunk (with switches attached). raise UnknownCommand
parsed_input['root_chunk'] = parsed_input['splitted'][0].split('/')
# And now for the actual root command. It's the first entry in root_chunk.
parsed_input['root_cmd'] = parsed_input['root_chunk'][0].lower()
# Keep around the full, raw input in case a command needs it
cdat['raw_input'] = cdat['uinput']
# Now we'll see if the user is using an alias. We do a dictionary lookup, # Shortened say alias.
# if the key (the player's root command) doesn't exist on the dict, we if parsed_input['root_cmd'][0] == '"':
# don't replace the existing root_cmd. If the key exists, its value parsed_input['splitted'].insert(0, "say")
# replaces the previously splitted root_cmd. For example, sa -> say. parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
alias_list = server.cmd_alias_list parsed_input['root_cmd'] = 'say'
parsed_input['root_cmd'] = alias_list.get(parsed_input['root_cmd'],parsed_input['root_cmd']) # Shortened pose alias.
elif parsed_input['root_cmd'][0] == ':':
parsed_input['splitted'].insert(0, "pose")
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'pose'
# Pose without space alias.
elif parsed_input['root_cmd'][0] == ';':
parsed_input['splitted'].insert(0, "pose/nospace")
parsed_input['root_chunk'] = ['pose', 'nospace']
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'pose'
# Channel alias match.
elif comsys.plr_has_channel(session,
parsed_input['root_cmd'],
alias_search=True,
return_muted=True):
# This will hold the reference to the command's function. calias = parsed_input['root_cmd']
cmd = None cname = comsys.plr_cname_from_alias(session, calias)
cmessage = ' '.join(parsed_input['splitted'][1:])
if session.logged_in: if cmessage == "who":
# Store the timestamp of the user's last command. comsys.msg_cwho(session, cname)
session.cmd_last = time.time() return
elif cmessage == "on":
comsys.plr_chan_on(session, calias)
return
elif cmessage == "off":
comsys.plr_chan_off(session, calias)
return
elif cmessage == "last":
comsys.msg_chan_hist(session, cname)
return
# Lets the users get around badly configured NAT timeouts. second_arg = "%s=%s" % (cname, cmessage)
if parsed_input['root_cmd'] == 'idle': parsed_input['splitted'] = ["@cemit/sendername", second_arg]
return parsed_input['root_chunk'] = ['@cemit', 'sendername', 'quiet']
parsed_input['root_cmd'] = '@cemit'
# Increment our user's command counter. # Get the command's function reference (Or False)
session.cmd_total += 1 cmdtuple = cmdtable.return_cmdtuple(parsed_input['root_cmd'])
# Player-visible idle time, not used in idle timeout calcs. if cmdtuple:
session.cmd_last_visible = time.time() # If there is a permissions element to the entry, check perms.
if cmdtuple[1]:
if not session.get_pobject().user_has_perm_list(cmdtuple[1]):
session.msg(defines_global.NOPERMS_MSG)
return
# If flow reaches this point, user has perms and command is ready.
cmd = cmdtuple[0]
# Just in case. Prevents some really funky-case crashes. else:
if len(parsed_input['root_cmd']) == 0: # Not logged in, look through the unlogged-in command table.
raise UnknownCommand cmdtuple = cmdtable.return_cmdtuple(parsed_input['root_cmd'], unlogged_cmd=True)
if cmdtuple:
cmd = cmdtuple[0]
# Shortened say alias. # Debugging stuff.
if parsed_input['root_cmd'][0] == '"': #session.msg("ROOT : %s" % (parsed_input['root_cmd'],))
parsed_input['splitted'].insert(0, "say") #session.msg("SPLIT: %s" % (parsed_input['splitted'],))
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'say'
# Shortened pose alias.
elif parsed_input['root_cmd'][0] == ':':
parsed_input['splitted'].insert(0, "pose")
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'pose'
# Pose without space alias.
elif parsed_input['root_cmd'][0] == ';':
parsed_input['splitted'].insert(0, "pose/nospace")
parsed_input['root_chunk'] = ['pose', 'nospace']
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'pose'
# Channel alias match.
elif comsys.plr_has_channel(session,
parsed_input['root_cmd'],
alias_search=True,
return_muted=True):
calias = parsed_input['root_cmd'] if callable(cmd):
cname = comsys.plr_cname_from_alias(session, calias) cdat['uinput'] = parsed_input
cmessage = ' '.join(parsed_input['splitted'][1:]) try:
cmd(cdat)
except:
session.msg("Untrapped error, please file a bug report:\n%s" % (format_exc(),))
logger.log_errmsg("Untrapped error, evoker %s: %s" %
(session, format_exc()))
return
if cmessage == "who": if session.logged_in:
comsys.msg_cwho(session, cname) # If we're not logged in, don't check exits.
return pobject = session.get_pobject()
elif cmessage == "on": exit_matches = match_exits(pobject, ' '.join(parsed_input['splitted']))
comsys.plr_chan_on(session, calias) if exit_matches:
return targ_exit = exit_matches[0]
elif cmessage == "off": if targ_exit.get_home():
comsys.plr_chan_off(session, calias) cdat['uinput'] = parsed_input
return
elif cmessage == "last":
comsys.msg_chan_hist(session, cname)
return
second_arg = "%s=%s" % (cname, cmessage) # SCRIPT: See if the player can traverse the exit
parsed_input['splitted'] = ["@cemit/sendername", second_arg] if not targ_exit.get_scriptlink().default_lock({
parsed_input['root_chunk'] = ['@cemit', 'sendername', 'quiet'] "pobject": pobject
parsed_input['root_cmd'] = '@cemit' }):
session.msg("You can't traverse that exit.")
# Get the command's function reference (Or False) else:
cmdtuple = cmdtable.return_cmdtuple(parsed_input['root_cmd']) pobject.move_to(targ_exit.get_home())
if cmdtuple: session.execute_cmd("look")
# If there is a permissions element to the entry, check perms. else:
if cmdtuple[1]: session.msg("That exit leads to nowhere.")
if not session.get_pobject().user_has_perm_list(cmdtuple[1]):
session.msg(defines_global.NOPERMS_MSG)
return
# If flow reaches this point, user has perms and command is ready.
cmd = cmdtuple[0]
else:
# Not logged in, look through the unlogged-in command table.
cmdtuple = cmdtable.return_cmdtuple(parsed_input['root_cmd'], unlogged_cmd=True)
if cmdtuple:
cmd = cmdtuple[0]
# Debugging stuff.
#session.msg("ROOT : %s" % (parsed_input['root_cmd'],))
#session.msg("SPLIT: %s" % (parsed_input['splitted'],))
if callable(cmd):
cdat['uinput'] = parsed_input
try:
cmd(cdat)
except:
session.msg("Untrapped error, please file a bug report:\n%s" % (format_exc(),))
logger.log_errmsg("Untrapped error, evoker %s: %s" %
(session, format_exc()))
return return
if session.logged_in: # If we reach this point, we haven't matched anything.
# If we're not logged in, don't check exits. raise UnknownCommand
pobject = session.get_pobject()
exit_matches = match_exits(pobject, ' '.join(parsed_input['splitted']))
if exit_matches:
targ_exit = exit_matches[0]
if targ_exit.get_home():
cdat['uinput'] = parsed_input
# SCRIPT: See if the player can traverse the exit except UnknownCommand:
if not targ_exit.get_scriptlink().default_lock({ session.msg("Huh? (Type \"help\" for help.)")
"pobject": pobject
}):
session.msg("You can't traverse that exit.")
else:
pobject.move_to(targ_exit.get_home())
session.execute_cmd("look")
else:
session.msg("That exit leads to nowhere.")
return
# If we reach this point, we haven't matched anything.
raise UnknownCommand
except UnknownCommand:
session.msg("Huh? (Type \"help\" for help.)")

View file

@ -19,71 +19,71 @@ import commands.objmanip
# -- Unlogged-in Command Table -- # -- Unlogged-in Command Table --
# Command Name Command Function Privilege Tuple # Command Name Command Function Privilege Tuple
uncon_ctable = { uncon_ctable = {
"connect": (commands.unloggedin.cmd_connect, None), "connect": (commands.unloggedin.cmd_connect, None),
"create": (commands.unloggedin.cmd_create, None), "create": (commands.unloggedin.cmd_create, None),
"quit": (commands.unloggedin.cmd_quit, None), "quit": (commands.unloggedin.cmd_quit, None),
} }
# -- Command Table -- # -- Command Table --
# Command Name Command Function Privilege Tuple # Command Name Command Function Privilege Tuple
ctable = { ctable = {
"addcom": (commands.comsys.cmd_addcom, None), "addcom": (commands.comsys.cmd_addcom, None),
"comlist": (commands.comsys.cmd_comlist, None), "comlist": (commands.comsys.cmd_comlist, None),
"delcom": (commands.comsys.cmd_delcom, None), "delcom": (commands.comsys.cmd_delcom, None),
"drop": (commands.general.cmd_drop, None), "drop": (commands.general.cmd_drop, None),
"examine": (commands.general.cmd_examine, None), "examine": (commands.general.cmd_examine, None),
"get": (commands.general.cmd_get, None), "get": (commands.general.cmd_get, None),
"help": (commands.general.cmd_help, None), "help": (commands.general.cmd_help, None),
"idle": (commands.general.cmd_idle, None), "idle": (commands.general.cmd_idle, None),
"inventory": (commands.general.cmd_inventory, None), "inventory": (commands.general.cmd_inventory, None),
"look": (commands.general.cmd_look, None), "look": (commands.general.cmd_look, None),
"page": (commands.general.cmd_page, None), "page": (commands.general.cmd_page, None),
"pose": (commands.general.cmd_pose, None), "pose": (commands.general.cmd_pose, None),
"quit": (commands.general.cmd_quit, None), "quit": (commands.general.cmd_quit, None),
"say": (commands.general.cmd_say, None), "say": (commands.general.cmd_say, None),
"time": (commands.info.cmd_time, None), "time": (commands.info.cmd_time, None),
"uptime": (commands.info.cmd_uptime, None), "uptime": (commands.info.cmd_uptime, None),
"version": (commands.info.cmd_version, None), "version": (commands.info.cmd_version, None),
"who": (commands.general.cmd_who, None), "who": (commands.general.cmd_who, None),
"@alias": (commands.objmanip.cmd_alias, None), "@alias": (commands.objmanip.cmd_alias, None),
"@boot": (commands.privileged.cmd_boot, ("genperms.manage_players")), "@boot": (commands.privileged.cmd_boot, ("genperms.manage_players")),
"@ccreate": (commands.comsys.cmd_ccreate, ("objects.add_commchannel")), "@ccreate": (commands.comsys.cmd_ccreate, ("objects.add_commchannel")),
"@cdestroy": (commands.comsys.cmd_cdestroy, ("objects.delete_commchannel")), "@cdestroy": (commands.comsys.cmd_cdestroy, ("objects.delete_commchannel")),
"@cemit": (commands.comsys.cmd_cemit, None), "@cemit": (commands.comsys.cmd_cemit, None),
"@clist": (commands.comsys.cmd_clist, None), "@clist": (commands.comsys.cmd_clist, None),
"@create": (commands.objmanip.cmd_create, ("genperms.builder")), "@create": (commands.objmanip.cmd_create, ("genperms.builder")),
"@describe": (commands.objmanip.cmd_description, None), "@describe": (commands.objmanip.cmd_description, None),
"@destroy": (commands.objmanip.cmd_destroy, ("genperms.builder")), "@destroy": (commands.objmanip.cmd_destroy, ("genperms.builder")),
"@dig": (commands.objmanip.cmd_dig, ("genperms.builder")), "@dig": (commands.objmanip.cmd_dig, ("genperms.builder")),
"@emit": (commands.general.cmd_emit, ("genperms.announce")), "@emit": (commands.general.cmd_emit, ("genperms.announce")),
# "@pemit": (commands.general.cmd_pemit, None), # "@pemit": (commands.general.cmd_pemit, None),
"@find": (commands.objmanip.cmd_find, ("genperms.builder")), "@find": (commands.objmanip.cmd_find, ("genperms.builder")),
"@link": (commands.objmanip.cmd_link, ("genperms.builder")), "@link": (commands.objmanip.cmd_link, ("genperms.builder")),
"@list": (commands.info.cmd_list, ("genperms.process_control")), "@list": (commands.info.cmd_list, ("genperms.process_control")),
"@name": (commands.objmanip.cmd_name, None), "@name": (commands.objmanip.cmd_name, None),
"@nextfree": (commands.objmanip.cmd_nextfree, ("genperms.builder")), "@nextfree": (commands.objmanip.cmd_nextfree, ("genperms.builder")),
"@newpassword": (commands.privileged.cmd_newpassword, ("genperms.manage_players")), "@newpassword": (commands.privileged.cmd_newpassword, ("genperms.manage_players")),
"@open": (commands.objmanip.cmd_open, ("genperms.builder")), "@open": (commands.objmanip.cmd_open, ("genperms.builder")),
"@password": (commands.general.cmd_password, None), "@password": (commands.general.cmd_password, None),
"@ps": (commands.info.cmd_ps, ("genperms.process_control")), "@ps": (commands.info.cmd_ps, ("genperms.process_control")),
"@reload": (commands.privileged.cmd_reload, ("genperms.process_control")), "@reload": (commands.privileged.cmd_reload, ("genperms.process_control")),
"@set": (commands.objmanip.cmd_set, None), "@set": (commands.objmanip.cmd_set, None),
"@shutdown": (commands.privileged.cmd_shutdown, ("genperms.process_control")), "@shutdown": (commands.privileged.cmd_shutdown, ("genperms.process_control")),
"@stats": (commands.info.cmd_stats, None), "@stats": (commands.info.cmd_stats, None),
"@teleport": (commands.objmanip.cmd_teleport, ("genperms.builder")), "@teleport": (commands.objmanip.cmd_teleport, ("genperms.builder")),
"@unlink": (commands.objmanip.cmd_unlink, ("genperms.builder")), "@unlink": (commands.objmanip.cmd_unlink, ("genperms.builder")),
"@wall": (commands.general.cmd_wall, ("genperms.announce")), "@wall": (commands.general.cmd_wall, ("genperms.announce")),
"@wipe": (commands.objmanip.cmd_wipe, None), "@wipe": (commands.objmanip.cmd_wipe, None),
} }
def return_cmdtuple(func_name, unlogged_cmd=False): def return_cmdtuple(func_name, unlogged_cmd=False):
""" """
Returns a reference to the command's tuple. If there are no matches, Returns a reference to the command's tuple. If there are no matches,
returns false. returns false.
""" """
if not unlogged_cmd: if not unlogged_cmd:
cfunc = ctable.get(func_name, False) cfunc = ctable.get(func_name, False)
else: else:
cfunc = uncon_ctable.get(func_name, False) cfunc = uncon_ctable.get(func_name, False)
return cfunc return cfunc