1 """Core objects for the mudpy engine."""
3 # Copyright (c) 2005 mudpy, The Fungi <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
6 # import some things we need
7 from ConfigParser import RawConfigParser
8 from md5 import new as new_md5
9 from os import R_OK, access, chmod, makedirs, stat
10 from os.path import abspath, dirname, exists, isabs, join as path_join
11 from random import choice, randrange
12 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
13 from stat import S_IMODE, ST_MODE
14 from time import asctime, sleep
17 """An element of the universe."""
18 def __init__(self, key, universe, origin=""):
19 """Default values for the in-memory element variables."""
21 if self.key.find(":") > 0:
22 self.category, self.subkey = self.key.split(":", 1)
24 self.category = "other"
25 self.subkey = self.key
26 if not self.category in universe.categories: self.category = "other"
27 universe.categories[self.category][self.subkey] = self
29 if not self.origin: self.origin = universe.default_origins[self.category]
30 if not isabs(self.origin):
31 self.origin = abspath(self.origin)
32 universe.contents[self.key] = self
33 if not self.origin in universe.files:
34 DataFile(self.origin, universe)
35 if not universe.files[self.origin].data.has_section(self.key):
36 universe.files[self.origin].data.add_section(self.key)
38 """Remove an element from the universe and destroy it."""
39 log("Destroying: " + self.key + ".")
40 universe.files[self.origin].data.remove_section(self.key)
41 del universe.categories[self.category][self.subkey]
42 del universe.contents[self.key]
44 def delete(self, facet):
45 """Delete a facet from the element."""
46 if universe.files[self.origin].data.has_option(self.key, facet):
47 universe.files[self.origin].data.remove_option(self.key, facet)
49 """Return a list of facets for this element."""
50 return universe.files[self.origin].data.options(self.key)
51 def get(self, facet, default=None):
52 """Retrieve values."""
53 if default is None: default = ""
54 if universe.files[self.origin].data.has_option(self.key, facet):
55 return universe.files[self.origin].data.get(self.key, facet)
57 def getboolean(self, facet, default=None):
58 """Retrieve values as boolean type."""
59 if default is None: default=False
60 if universe.files[self.origin].data.has_option(self.key, facet):
61 return universe.files[self.origin].data.getboolean(self.key, facet)
63 def getint(self, facet, default=None):
64 """Return values as int/long type."""
65 if default is None: default = 0
66 if universe.files[self.origin].data.has_option(self.key, facet):
67 return universe.files[self.origin].data.getint(self.key, facet)
69 def getfloat(self, facet, default=None):
70 """Return values as float type."""
71 if default is None: default = 0.0
72 if universe.files[self.origin].data.has_option(self.key, facet):
73 return universe.files[self.origin].data.getfloat(self.key, facet)
75 def getlist(self, facet, default=None):
76 """Return values as list type."""
77 if default is None: default = []
78 value = self.get(facet)
79 if value: return makelist(value)
81 def getdict(self, facet, default=None):
82 """Return values as dict type."""
83 if default is None: default = {}
84 value = self.get(facet)
85 if value: return makedict(value)
87 def set(self, facet, value):
89 if type(value) is long: value = str(value)
90 elif not type(value) is str: value = repr(value)
91 universe.files[self.origin].data.set(self.key, facet, value)
94 """A file containing universe elements."""
95 def __init__(self, filename, universe):
96 self.data = RawConfigParser()
97 if access(filename, R_OK): self.data.read(filename)
98 self.filename = filename
99 universe.files[filename] = self
100 if self.data.has_option("control", "include_files"):
101 includes = makelist(self.data.get("control", "include_files"))
103 if self.data.has_option("control", "default_files"):
104 origins = makedict(self.data.get("control", "default_files"))
105 for key in origins.keys():
106 if not key in includes: includes.append(key)
107 universe.default_origins[key] = origins[key]
108 if not key in universe.categories:
109 universe.categories[key] = {}
110 if self.data.has_option("control", "private_files"):
111 for item in makelist(self.data.get("control", "private_files")):
112 if not item in includes: includes.append(item)
113 if not item in universe.private_files:
115 item = path_join(dirname(filename), item)
116 universe.private_files.append(item)
117 for section in self.data.sections():
118 if section != "control":
119 Element(section, universe, filename)
120 for include_file in includes:
121 if not isabs(include_file):
122 include_file = path_join(dirname(filename), include_file)
123 DataFile(include_file, universe)
125 if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ):
126 if not exists(dirname(self.filename)): makedirs(dirname(self.filename))
127 file_descriptor = file(self.filename, "w")
128 if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
129 chmod(self.filename, 0600)
130 self.data.write(file_descriptor)
131 file_descriptor.flush()
132 file_descriptor.close()
136 def __init__(self, filename=""):
137 """Initialize the universe."""
140 self.default_origins = {}
142 self.private_files = []
144 self.terminate_world = False
145 self.reload_modules = False
147 possible_filenames = [
153 "/usr/local/mudpy/mudpy.conf",
154 "/usr/local/mudpy/etc/mudpy.conf",
155 "/etc/mudpy/mudpy.conf",
158 for filename in possible_filenames:
159 if access(filename, R_OK): break
160 if not isabs(filename):
161 filename = abspath(filename)
162 DataFile(filename, self)
164 """Save the universe to persistent storage."""
165 for key in self.files: self.files[key].save()
167 def initialize_server_socket(self):
168 """Create and open the listening socket."""
170 # create a new ipv4 stream-type socket object
171 self.listening_socket = socket(AF_INET, SOCK_STREAM)
173 # set the socket options to allow existing open ones to be
174 # reused (fixes a bug where the server can't bind for a minute
175 # when restarting on linux systems)
176 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
178 # bind the socket to to our desired server ipa and port
179 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
181 # disable blocking so we can proceed whether or not we can
183 self.listening_socket.setblocking(0)
185 # start listening on the socket
186 self.listening_socket.listen(1)
188 # note that we're now ready for user connections
189 log("Waiting for connection(s)...")
192 """This is a connected user."""
195 """Default values for the in-memory user variables."""
197 self.last_address = ""
198 self.connection = None
199 self.authenticated = False
200 self.password_tries = 0
201 self.state = "entering_account_name"
202 self.menu_seen = False
204 self.input_queue = []
205 self.output_queue = []
206 self.partial_input = ""
212 """Log, close the connection and remove."""
213 if self.account: name = self.account.get("name")
215 if name: message = "User " + name
216 else: message = "An unnamed user"
217 message += " logged out."
219 self.connection.close()
223 """Save, load a new user and relocate the connection."""
225 # get out of the list
228 # create a new user object
231 # set everything else equivalent
248 exec("new_user." + attribute + " = self." + attribute)
251 universe.userlist.append(new_user)
253 # get rid of the old user object
256 def replace_old_connections(self):
257 """Disconnect active users with the same name."""
259 # the default return value
262 # iterate over each user in the list
263 for old_user in universe.userlist:
265 # the name is the same but it's not us
266 if old_user.account.get("name") == self.account.get("name") and old_user is not self:
269 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
270 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
271 self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
273 # close the old connection
274 old_user.connection.close()
276 # replace the old connection with this one
277 old_user.connection = self.connection
278 old_user.last_address = old_user.address
279 old_user.address = self.address
280 old_user.echoing = self.echoing
282 # take this one out of the list and delete
288 # true if an old connection was replaced, false if not
291 def authenticate(self):
292 """Flag the user as authenticated and disconnect duplicates."""
293 if not self.state is "authenticated":
294 log("User " + self.account.get("name") + " logged in.")
295 self.authenticated = True
298 """Send the user their current menu."""
299 if not self.menu_seen:
300 self.menu_choices = get_menu_choices(self)
301 self.send(get_menu(self.state, self.error, self.echoing, self.menu_choices), "")
302 self.menu_seen = True
304 self.adjust_echoing()
306 def adjust_echoing(self):
307 """Adjust echoing to match state menu requirements."""
308 if self.echoing and not menu_echo_on(self.state): self.echoing = False
309 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
312 """Remove a user from the list of connected users."""
313 universe.userlist.remove(self)
315 def send(self, output, eol="$(eol)"):
316 """Send arbitrary text to a connected user."""
318 # only when there is actual output
321 # start with a newline, append the message, then end
322 # with the optional eol string passed to this function
323 # and the ansi escape to return to normal text
324 output = "\r\n" + output + eol + chr(27) + "[0m"
326 # find and replace macros in the output
327 output = replace_macros(self, output)
329 # wrap the text at 80 characters
330 # TODO: prompt user for preferred wrap width
331 output = wrap_ansi_text(output, 80)
333 # drop the formatted output into the output queue
334 self.output_queue.append(output)
336 # try to send the last item in the queue, remove it and
337 # flag that menu display is not needed
339 self.connection.send(self.output_queue[0])
340 self.output_queue.remove(self.output_queue[0])
341 self.menu_seen = False
343 # but if we can't, that's okay too
348 """All the things to do to the user per increment."""
350 # if the world is terminating, disconnect
351 if universe.terminate_world:
352 self.state = "disconnecting"
353 self.menu_seen = False
355 # show the user a menu as needed
358 # disconnect users with the appropriate state
359 if self.state == "disconnecting":
362 # the user is unique and not flagged to disconnect
365 # check for input and add it to the queue
368 # there is input waiting in the queue
369 if self.input_queue: handle_user_input(self)
371 def enqueue_input(self):
372 """Process and enqueue any new input."""
374 # check for some input
376 input_data = self.connection.recv(1024)
383 # tack this on to any previous partial
384 self.partial_input += input_data
386 # separate multiple input lines
387 new_input_lines = self.partial_input.split("\n")
389 # if input doesn't end in a newline, replace the
390 # held partial input with the last line of it
391 if not self.partial_input.endswith("\n"):
392 self.partial_input = new_input_lines.pop()
394 # otherwise, chop off the extra null input and reset
395 # the held partial input
397 new_input_lines.pop()
398 self.partial_input = ""
400 # iterate over the remaining lines
401 for line in new_input_lines:
403 # filter out non-printables
404 line = filter(lambda x: x>=' ' and x<='~', line)
406 # strip off extra whitespace
409 # put on the end of the queue
410 self.input_queue.append(line)
412 def can_run(self, command):
413 """Check if the user can run this command object."""
415 # has to be in the commands category
416 if command not in universe.categories["command"].values(): result = False
418 # administrators can run any command
419 elif self.account.getboolean("administrator"): result = True
421 # everyone can run non-administrative commands
422 elif not command.getboolean("administrative"): result = True
424 # otherwise the command cannot be run by this user
427 # pass back the result
430 def new_avatar(self):
431 """Instantiate a new, unconfigured avatar for this user."""
433 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
434 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
435 avatars = self.account.getlist("avatars")
436 avatars.append(self.avatar.key)
437 self.account.set("avatars", avatars)
439 def delete_avatar(self, avatar):
440 """Remove an avatar from the world and from the user's list."""
441 if self.avatar is universe.contents[avatar]: self.avatar = None
442 universe.contents[avatar].destroy()
443 avatars = self.account.getlist("avatars")
444 avatars.remove(avatar)
445 self.account.set("avatars", avatars)
448 """Destroy the user and associated avatars."""
449 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
450 self.account.destroy()
452 def list_avatar_names(self):
453 """List names of assigned avatars."""
454 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
457 """Turn string into list type."""
458 if value[0] + value[-1] == "[]": return eval(value)
459 else: return [ value ]
462 """Turn string into dict type."""
463 if value[0] + value[-1] == "{}": return eval(value)
464 elif value.find(":") > 0: return eval("{" + value + "}")
465 else: return { value: None }
467 def broadcast(message):
468 """Send a message to all connected users."""
469 for each_user in universe.userlist: each_user.send("$(eol)" + message)
474 # the time in posix log timestamp format
475 timestamp = asctime()[4:19]
477 # send the timestamp and message to standard output
478 print(timestamp + " " + message)
480 def wrap_ansi_text(text, width):
481 """Wrap text with arbitrary width while ignoring ANSI colors."""
483 # the current position in the entire text string, including all
484 # characters, printable or otherwise
485 absolute_position = 0
487 # the current text position relative to the begining of the line,
488 # ignoring color escape sequences
489 relative_position = 0
491 # whether the current character is part of a color escape sequence
494 # iterate over each character from the begining of the text
495 for each_character in text:
497 # the current character is the escape character
498 if each_character == chr(27):
501 # the current character is within an escape sequence
504 # the current character is m, which terminates the
505 # current escape sequence
506 if each_character == "m":
509 # the current character is a newline, so reset the relative
510 # position (start a new line)
511 elif each_character == "\n":
512 relative_position = 0
514 # the current character meets the requested maximum line width,
515 # so we need to backtrack and find a space at which to wrap
516 elif relative_position == width:
518 # distance of the current character examined from the
522 # count backwards until we find a space
523 while text[absolute_position - wrap_offset] != " ":
526 # insert an eol in place of the space
527 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
529 # increase the absolute position because an eol is two
530 # characters but the space it replaced was only one
531 absolute_position += 1
533 # now we're at the begining of a new line, plus the
534 # number of characters wrapped from the previous line
535 relative_position = wrap_offset
537 # as long as the character is not a carriage return and the
538 # other above conditions haven't been met, count it as a
539 # printable character
540 elif each_character != "\r":
541 relative_position += 1
543 # increase the absolute position for every character
544 absolute_position += 1
546 # return the newly-wrapped text
549 def weighted_choice(data):
550 """Takes a dict weighted by value and returns a random key."""
552 # this will hold our expanded list of keys from the data
555 # create thee expanded list of keys
556 for key in data.keys():
557 for count in range(data[key]):
560 # return one at random
561 return choice(expanded)
564 """Returns a random character name."""
566 # the vowels and consonants needed to create romaji syllables
567 vowels = [ "a", "i", "u", "e", "o" ]
568 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
570 # this dict will hold our weighted list of syllables
573 # generate the list with an even weighting
574 for consonant in consonants:
576 syllables[consonant + vowel] = 1
578 # we'll build the name into this string
581 # create a name of random length from the syllables
582 for syllable in range(randrange(2, 6)):
583 name += weighted_choice(syllables)
585 # strip any leading quotemark, capitalize and return the name
586 return name.strip("'").capitalize()
588 def replace_macros(user, text, is_input=False):
589 """Replaces macros in text output."""
594 # third person pronouns
596 "female": { "obj": "her", "pos": "hers", "sub": "she" },
597 "male": { "obj": "him", "pos": "his", "sub": "he" },
598 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
601 # a dict of replacement macros
604 "$(bld)": chr(27) + "[1m",
605 "$(nrm)": chr(27) + "[0m",
606 "$(blk)": chr(27) + "[30m",
607 "$(grn)": chr(27) + "[32m",
608 "$(red)": chr(27) + "[31m",
611 # add dynamic macros where possible
613 account_name = user.account.get("name")
615 macros["$(account)"] = account_name
617 avatar_gender = user.avatar.get("gender")
619 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
620 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
621 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
623 # find and replace per the macros dict
624 macro_start = text.find("$(")
625 if macro_start == -1: break
626 macro_end = text.find(")", macro_start) + 1
627 macro = text[macro_start:macro_end]
628 if macro in macros.keys():
629 text = text.replace(macro, macros[macro])
631 # if we get here, log and replace it with null
633 text = text.replace(macro, "")
635 log("Unexpected replacement macro " + macro + " encountered.")
637 # replace the look-like-a-macro sequence
638 text = text.replace("$_(", "$(")
642 def escape_macros(text):
643 """Escapes replacement macros in text."""
644 return text.replace("$(", "$_(")
646 def check_time(frequency):
647 """Check for a factor of the current increment count."""
648 if type(frequency) is str:
649 frequency = universe.categories["internal"]["time"].getint(frequency)
650 if not "counters" in universe.categories["internal"]:
651 Element("internal:counters", universe)
652 return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
655 """The things which should happen on each pulse, aside from reloads."""
657 # open the listening socket if it hasn't been already
658 if not hasattr(universe, "listening_socket"):
659 universe.initialize_server_socket()
661 # assign a user if a new connection is waiting
662 user = check_for_connection(universe.listening_socket)
663 if user: universe.userlist.append(user)
665 # iterate over the connected users
666 for user in universe.userlist: user.pulse()
668 # update the log every now and then
669 if check_time("frequency_log"):
670 log(str(len(universe.userlist)) + " connection(s)")
672 # periodically save everything
673 if check_time("frequency_save"):
676 # pause for a configurable amount of time (decimal seconds)
677 sleep(universe.categories["internal"]["time"].getfloat("increment"))
679 # increment the elapsed increment counter
680 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
683 """Reload data into new persistent objects."""
684 for user in universe.userlist[:]: user.reload()
686 def check_for_connection(listening_socket):
687 """Check for a waiting connection and return a new user object."""
689 # try to accept a new connection
691 connection, address = listening_socket.accept()
695 # note that we got one
696 log("Connection from " + address[0])
698 # disable blocking so we can proceed whether or not we can send/receive
699 connection.setblocking(0)
701 # create a new user object
704 # associate this connection with it
705 user.connection = connection
707 # set the user's ipa from the connection's ipa
708 user.address = address[0]
710 # return the new user object
713 def get_menu(state, error=None, echoing=True, choices={}):
714 """Show the correct menu text to a user."""
716 # begin with a telnet echo command sequence if needed
717 message = get_echo_sequence(state, echoing)
719 # get the description or error text
720 message += get_menu_description(state, error)
722 # get menu choices for the current state
723 message += get_formatted_menu_choices(state, choices)
725 # try to get a prompt, if it was defined
726 message += get_menu_prompt(state)
728 # throw in the default choice, if it exists
729 message += get_formatted_default_menu_choice(state)
731 # display a message indicating if echo is off
732 message += get_echo_message(state)
734 # return the assembly of various strings defined above
737 def menu_echo_on(state):
738 """True if echo is on, false if it is off."""
739 return universe.categories["menu"][state].getboolean("echo", True)
741 def get_echo_sequence(state, echoing):
742 """Build the appropriate IAC ECHO sequence as needed."""
744 # if the user has echo on and the menu specifies it should be turned
745 # off, send: iac + will + echo + null
746 if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
748 # if echo is not set to off in the menu and the user curently has echo
749 # off, send: iac + wont + echo + null
750 elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
752 # default is not to send an echo control sequence at all
755 def get_echo_message(state):
756 """Return a message indicating that echo is off."""
757 if menu_echo_on(state): return ""
758 else: return "(won't echo) "
760 def get_default_menu_choice(state):
761 """Return the default choice for a menu."""
762 return universe.categories["menu"][state].get("default")
764 def get_formatted_default_menu_choice(state):
765 """Default menu choice foratted for inclusion in a prompt string."""
766 default_choice = get_default_menu_choice(state)
767 if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
770 def get_menu_description(state, error):
771 """Get the description or error text."""
773 # an error condition was raised by the handler
776 # try to get an error message matching the condition
778 description = universe.categories["menu"][state].get("error_" + error)
779 if not description: description = "That is not a valid choice..."
780 description = "$(red)" + description + "$(nrm)"
782 # there was no error condition
785 # try to get a menu description for the current state
786 description = universe.categories["menu"][state].get("description")
788 # return the description or error message
789 if description: description += "$(eol)$(eol)"
792 def get_menu_prompt(state):
793 """Try to get a prompt, if it was defined."""
794 prompt = universe.categories["menu"][state].get("prompt")
795 if prompt: prompt += " "
798 def get_menu_choices(user):
799 """Return a dict of choice:meaning."""
800 menu = universe.categories["menu"][user.state]
801 create_choices = menu.get("create")
802 if create_choices: choices = eval(create_choices)
807 for facet in menu.facets():
808 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
809 ignores.append(facet.split("_", 2)[1])
810 elif facet.startswith("create_"):
811 creates[facet] = facet.split("_", 2)[1]
812 elif facet.startswith("choice_"):
813 options[facet] = facet.split("_", 2)[1]
814 for facet in creates.keys():
815 if not creates[facet] in ignores:
816 choices[creates[facet]] = eval(menu.get(facet))
817 for facet in options.keys():
818 if not options[facet] in ignores:
819 choices[options[facet]] = menu.get(facet)
822 def get_formatted_menu_choices(state, choices):
823 """Returns a formatted string of menu choices."""
825 choice_keys = choices.keys()
827 for choice in choice_keys:
828 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
829 if choice_output: choice_output += "$(eol)"
832 def get_menu_branches(state):
833 """Return a dict of choice:branch."""
835 for facet in universe.categories["menu"][state].facets():
836 if facet.startswith("branch_"):
837 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
840 def get_default_branch(state):
841 """Return the default branch."""
842 return universe.categories["menu"][state].get("branch")
844 def get_choice_branch(user, choice):
845 """Returns the new state matching the given choice."""
846 branches = get_menu_branches(user.state)
847 if choice in branches.keys(): return branches[choice]
848 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
851 def get_menu_actions(state):
852 """Return a dict of choice:branch."""
854 for facet in universe.categories["menu"][state].facets():
855 if facet.startswith("action_"):
856 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
859 def get_default_action(state):
860 """Return the default action."""
861 return universe.categories["menu"][state].get("action")
863 def get_choice_action(user, choice):
864 """Run any indicated script for the given choice."""
865 actions = get_menu_actions(user.state)
866 if choice in actions.keys(): return actions[choice]
867 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
870 def handle_user_input(user):
871 """The main handler, branches to a state-specific handler."""
873 # check to make sure the state is expected, then call that handler
874 if "handler_" + user.state in globals():
875 exec("handler_" + user.state + "(user)")
877 generic_menu_handler(user)
879 # since we got input, flag that the menu/prompt needs to be redisplayed
880 user.menu_seen = False
882 # if the user's client echo is off, send a blank line for aesthetics
883 if not user.echoing: user.send("", "")
885 def generic_menu_handler(user):
886 """A generic menu choice handler."""
888 # get a lower-case representation of the next line of input
890 choice = user.input_queue.pop(0)
891 if choice: choice = choice.lower()
893 if not choice: choice = get_default_menu_choice(user.state)
894 if choice in user.menu_choices:
895 exec(get_choice_action(user, choice))
896 new_state = get_choice_branch(user, choice)
897 if new_state: user.state = new_state
898 else: user.error = "default"
900 def handler_entering_account_name(user):
901 """Handle the login account name."""
903 # get the next waiting line of input
904 input_data = user.input_queue.pop(0)
906 # did the user enter anything?
909 # keep only the first word and convert to lower-case
910 name = input_data.lower()
912 # fail if there are non-alphanumeric characters
913 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
914 user.error = "bad_name"
916 # if that account exists, time to request a password
917 elif name in universe.categories["account"]:
918 user.account = universe.categories["account"][name]
919 user.state = "checking_password"
921 # otherwise, this could be a brand new user
923 user.account = Element("account:" + name, universe)
924 user.account.set("name", name)
925 log("New user: " + name)
926 user.state = "checking_new_account_name"
928 # if the user entered nothing for a name, then buhbye
930 user.state = "disconnecting"
932 def handler_checking_password(user):
933 """Handle the login account password."""
935 # get the next waiting line of input
936 input_data = user.input_queue.pop(0)
938 # does the hashed input equal the stored hash?
939 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
941 # if so, set the username and load from cold storage
942 if not user.replace_old_connections():
944 user.state = "main_utility"
946 # if at first your hashes don't match, try, try again
947 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
948 user.password_tries += 1
949 user.error = "incorrect"
951 # we've exceeded the maximum number of password failures, so disconnect
953 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
954 user.state = "disconnecting"
956 def handler_entering_new_password(user):
957 """Handle a new password entry."""
959 # get the next waiting line of input
960 input_data = user.input_queue.pop(0)
962 # make sure the password is strong--at least one upper, one lower and
963 # one digit, seven or more characters in length
964 if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
966 # hash and store it, then move on to verification
967 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
968 user.state = "verifying_new_password"
970 # the password was weak, try again if you haven't tried too many times
971 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
972 user.password_tries += 1
975 # too many tries, so adios
977 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
978 user.account.destroy()
979 user.state = "disconnecting"
981 def handler_verifying_new_password(user):
982 """Handle the re-entered new password for verification."""
984 # get the next waiting line of input
985 input_data = user.input_queue.pop(0)
987 # hash the input and match it to storage
988 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
991 # the hashes matched, so go active
992 if not user.replace_old_connections(): user.state = "main_utility"
994 # go back to entering the new password as long as you haven't tried
996 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
997 user.password_tries += 1
998 user.error = "differs"
999 user.state = "entering_new_password"
1001 # otherwise, sayonara
1003 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1004 user.account.destroy()
1005 user.state = "disconnecting"
1007 def handler_active(user):
1008 """Handle input for active users."""
1010 # get the next waiting line of input
1011 input_data = user.input_queue.pop(0)
1013 # split out the command (first word) and parameters (everything else)
1014 if input_data.find(" ") > 0:
1015 command_name, parameters = input_data.split(" ", 1)
1017 command_name = input_data
1020 # lowercase the command
1021 command_name = command_name.lower()
1023 # the command matches a command word for which we have data
1024 if command_name in universe.categories["command"]:
1025 command = universe.categories["command"][command_name]
1026 else: command = None
1028 # if it's allowed, do it
1029 if user.can_run(command): exec(command.get("action"))
1031 # otherwise, give an error
1032 elif command_name: command_error(user, input_data)
1034 def command_halt(user, parameters):
1035 """Halt the world."""
1037 # see if there's a message or use a generic one
1038 if parameters: message = "Halting: " + parameters
1039 else: message = "User " + user.account.get("name") + " halted the world."
1045 # set a flag to terminate the world
1046 universe.terminate_world = True
1048 def command_reload(user):
1049 """Reload all code modules, configs and data."""
1051 # let the user know and log
1052 user.send("Reloading all code modules, configs and data.")
1053 log("User " + user.account.get("name") + " reloaded the world.")
1055 # set a flag to reload
1056 universe.reload_modules = True
1058 def command_help(user, parameters):
1059 """List available commands and provide help for commands."""
1061 # did the user ask for help on a specific command word?
1064 # is the command word one for which we have data?
1065 if parameters in universe.categories["command"]:
1066 command = universe.categories["command"][parameters]
1067 else: command = None
1069 # only for allowed commands
1070 if user.can_run(command):
1072 # add a description if provided
1073 description = command.get("description")
1075 description = "(no short description provided)"
1076 if command.getboolean("administrative"): output = "$(red)"
1077 else: output = "$(grn)"
1078 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1080 # add the help text if provided
1081 help_text = command.get("help")
1083 help_text = "No help is provided for this command."
1086 # no data for the requested command word
1088 output = "That is not an available command."
1090 # no specific command word was indicated
1093 # give a sorted list of commands with descriptions if provided
1094 output = "These are the commands available to you:$(eol)$(eol)"
1095 sorted_commands = universe.categories["command"].keys()
1096 sorted_commands.sort()
1097 for item in sorted_commands:
1098 command = universe.categories["command"][item]
1099 if user.can_run(command):
1100 description = command.get("description")
1102 description = "(no short description provided)"
1103 if command.getboolean("administrative"): output += " $(red)"
1104 else: output += " $(grn)"
1105 output += item + "$(nrm) - " + description + "$(eol)"
1106 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1108 # send the accumulated output to the user
1111 def command_say(user, parameters):
1112 """Speak to others in the same room."""
1114 # check for replacement macros
1115 if replace_macros(user, parameters, True) != parameters:
1116 user.send("You cannot speak $_(replacement macros).")
1118 # the user entered a message
1121 # get rid of quote marks on the ends of the message and
1122 # capitalize the first letter
1123 message = parameters.strip("\"'`").capitalize()
1125 # a dictionary of punctuation:action pairs
1127 for facet in universe.categories["internal"]["language"].facets():
1128 if facet.startswith("punctuation_"):
1129 action = facet.split("_")[1]
1130 for mark in universe.categories["internal"]["language"].getlist(facet):
1131 actions[mark] = action
1133 # match the punctuation used, if any, to an action
1134 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1135 action = actions[default_punctuation]
1136 for mark in actions.keys():
1137 if message.endswith(mark) and mark != default_punctuation:
1138 action = actions[mark]
1141 # if the action is default and there is no mark, add one
1142 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1143 message += default_punctuation
1145 # capitalize a list of words within the message
1146 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1147 for word in capitalize_words:
1148 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1151 # TODO: we won't be using broadcast once there are actual rooms
1152 broadcast(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
1154 # there was no message
1156 user.send("What do you want to say?")
1158 def command_show(user, parameters):
1159 """Show program data."""
1161 if parameters.find(" ") < 1:
1162 if parameters == "time":
1163 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1164 elif parameters == "categories":
1165 message = "These are the element categories:$(eol)"
1166 categories = universe.categories.keys()
1168 for category in categories: message += "$(eol) $(grn)" + category + "$(nrm)"
1169 elif parameters == "files":
1170 message = "These are the current files containing the universe:$(eol)"
1171 filenames = universe.files.keys()
1173 for filename in filenames: message += "$(eol) $(grn)" + filename + "$(nrm)"
1176 arguments = parameters.split()
1177 if arguments[0] == "category":
1178 if arguments[1] in universe.categories:
1179 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1180 elements = universe.categories[arguments[1]].keys()
1182 for element in elements:
1183 message += "$(eol) $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
1184 elif arguments[0] == "element":
1185 if arguments[1] in universe.contents:
1186 message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
1187 element = universe.contents[arguments[1]]
1188 facets = element.facets()
1190 for facet in facets:
1191 message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1193 if parameters: message = "I don't know what \"" + parameters + "\" is."
1194 else: message = "What do you want to show?"
1197 def command_create(user, parameters):
1198 """Create an element if it does not exist."""
1199 if not parameters: message = "You must at least specify an element to create."
1201 arguments = parameters.split()
1202 if len(arguments) == 1: arguments.append("")
1203 if len(arguments) == 2:
1204 element, filename = arguments
1205 if element in universe.contents: message = "The \"" + element + "\" element already exists."
1207 message = "You create \"" + element + "\" within the universe."
1208 logline = user.account.get("name") + " created an element: " + element
1210 logline += " in file " + filename
1211 if filename not in universe.files:
1212 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1213 Element(element, universe, filename)
1215 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1218 def command_destroy(user, parameters):
1219 """Destroy an element if it exists."""
1220 if not parameters: message = "You must specify an element to destroy."
1222 if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1224 universe.contents[parameters].destroy()
1225 message = "You destroy \"" + parameters + "\" within the universe."
1226 log(user.account.get("name") + " destroyed an element: " + parameters)
1229 def command_set(user, parameters):
1230 """Set a facet of an element."""
1231 if not parameters: message = "You must specify an element, a facet and a value."
1233 arguments = parameters.split(" ", 2)
1234 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1235 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1237 element, facet, value = arguments
1238 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1240 universe.contents[element].set(facet, value)
1241 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1244 def command_delete(user, parameters):
1245 """Delete a facet from an element."""
1246 if not parameters: message = "You must specify an element and a facet."
1248 arguments = parameters.split(" ")
1249 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1250 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1252 element, facet = arguments
1253 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1254 elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1256 universe.contents[element].delete(facet)
1257 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1260 def command_error(user, input_data):
1261 """Generic error for an unrecognized command word."""
1263 # 90% of the time use a generic error
1265 message = "I'm not sure what \"" + input_data + "\" means..."
1267 # 10% of the time use the classic diku error
1269 message = "Arglebargle, glop-glyf!?!"
1271 # send the error message
1274 # if there is no universe, create an empty one
1275 if not "universe" in locals(): universe = Universe()