from os import R_OK, access, chmod, makedirs, stat
from os.path import abspath, dirname, exists, isabs, join as path_join
from random import choice, randrange
+from re import match
from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
from stat import S_IMODE, ST_MODE
from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
"""An element of the universe."""
def __init__(self, key, universe, origin=""):
"""Default values for the in-memory element variables."""
+ self.owner = None
+ self.contents = {}
self.key = key
if self.key.find(":") > 0:
self.category, self.subkey = self.key.split(":", 1)
if universe.files[self.origin].data.has_option(self.key, facet):
universe.files[self.origin].data.remove_option(self.key, facet)
def facets(self):
- """Return a list of facets for this element."""
+ """Return a list of non-inherited facets for this element."""
return universe.files[self.origin].data.options(self.key)
+ def has_facet(self, facet):
+ """Return whether the non-inherited facet exists."""
+ return facet in self.facets()
+ def remove_facet(self, facet):
+ """Remove a facet from the element."""
+ if self.has_facet(facet): universe.files[self.origin].data.remove_option(self.key, facet)
+ def ancestry(self):
+ """Return a list of the element's inheritance lineage."""
+ if self.has_facet("inherit"):
+ ancestry = self.getlist("inherit")
+ for parent in ancestry[:]:
+ ancestors = universe.contents[parent].ancestry()
+ for ancestor in ancestors:
+ if ancestor not in ancestry: ancestry.append(ancestor)
+ return ancestry
+ else: return []
def get(self, facet, default=None):
"""Retrieve values."""
if default is None: default = ""
if universe.files[self.origin].data.has_option(self.key, facet):
return universe.files[self.origin].data.get(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if universe.contents[ancestor].has_facet(facet):
+ return universe.contents[ancestor].get(facet)
else: return default
def getboolean(self, facet, default=None):
"""Retrieve values as boolean type."""
if default is None: default=False
if universe.files[self.origin].data.has_option(self.key, facet):
return universe.files[self.origin].data.getboolean(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if universe.contents[ancestor].has_facet(facet):
+ return universe.contents[ancestor].getboolean(facet)
else: return default
def getint(self, facet, default=None):
"""Return values as int/long type."""
if default is None: default = 0
if universe.files[self.origin].data.has_option(self.key, facet):
return universe.files[self.origin].data.getint(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if universe.contents[ancestor].has_facet(facet):
+ return universe.contents[ancestor].getint(facet)
else: return default
def getfloat(self, facet, default=None):
"""Return values as float type."""
if default is None: default = 0.0
if universe.files[self.origin].data.has_option(self.key, facet):
return universe.files[self.origin].data.getfloat(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if universe.contents[ancestor].has_facet(facet):
+ return universe.contents[ancestor].getfloat(facet)
else: return default
def getlist(self, facet, default=None):
"""Return values as list type."""
if type(value) is long: value = str(value)
elif not type(value) is str: value = repr(value)
universe.files[self.origin].data.set(self.key, facet, value)
+ def append(self, facet, value):
+ """Append value tp a list."""
+ if type(value) is long: value = str(value)
+ elif not type(value) is str: value = repr(value)
+ newlist = self.getlist(facet)
+ newlist.append(value)
+ self.set(facet, newlist)
+ def send(self, message, eol="$(eol)"):
+ """Convenience method to pass messages to an owner."""
+ if self.owner: self.owner.send(message, eol)
+ def go_to(self, location):
+ """Relocate the element to a specific location."""
+ current = self.get("location")
+ if current and current in universe.contents[current].contents:
+ del universe.contents[current].contents[self.key]
+ if location in universe.contents: self.set("location", location)
+ universe.contents[location].contents[self.key] = self
+ self.look_at(location)
+ def go_home(self):
+ """Relocate the element to its default location."""
+ self.go_to(self.get("default_location"))
+ def move_direction(self, direction):
+ """Relocate the element in a specified direction."""
+ self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
+ def look_at(self, key):
+ """Show an element to another element."""
+ if self.owner:
+ element = universe.contents[key]
+ message = ""
+ name = element.get("name")
+ if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
+ description = element.get("description")
+ if description: message += description + "$(eol)"
+ portal_list = element.portals().keys()
+ if portal_list:
+ portal_list.sort()
+ message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
+ for element in universe.contents[self.get("location")].contents.values():
+ if element.getboolean("is_actor") and element is not self:
+ message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
+ self.send(message)
+ def portals(self):
+ """Map the portal directions for a room to neighbors."""
+ portals = {}
+ if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
+ coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
+ offsets = {
+ "down": (0,0,-1),
+ "east": (1,0,0),
+ "north": (0,1,0),
+ "south": (0,-1,0),
+ "up": (0,0,1),
+ "west": (-1,0,0)
+ }
+ for portal in self.getlist("gridlinks"):
+ adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
+ neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
+ if neighbor in universe.contents: portals[portal] = neighbor
+ for facet in self.facets():
+ if facet.startswith("link_"):
+ neighbor = self.get(facet)
+ if neighbor in universe.contents:
+ portal = facet.split("_")[1]
+ portals[portal] = neighbor
+ return portals
+ def link_neighbor(self, direction):
+ """Return the element linked in a given direction."""
+ portals = self.portals()
+ if direction in portals: return portals[direction]
+ def echo_to_location(self, message):
+ """Show a message to other elements in the current location."""
+ for element in universe.contents[self.get("location")].contents.values():
+ if element is not self: element.send(message)
class DataFile:
"""A file containing universe elements."""
if access(filename, R_OK): self.data.read(filename)
self.filename = filename
universe.files[filename] = self
- if self.data.has_option("control", "include_files"):
- includes = makelist(self.data.get("control", "include_files"))
+ if self.data.has_option("__control__", "include_files"):
+ includes = makelist(self.data.get("__control__", "include_files"))
else: includes = []
- if self.data.has_option("control", "default_files"):
- origins = makedict(self.data.get("control", "default_files"))
+ if self.data.has_option("__control__", "default_files"):
+ origins = makedict(self.data.get("__control__", "default_files"))
for key in origins.keys():
if not key in includes: includes.append(key)
universe.default_origins[key] = origins[key]
if not key in universe.categories:
universe.categories[key] = {}
- if self.data.has_option("control", "private_files"):
- for item in makelist(self.data.get("control", "private_files")):
+ if self.data.has_option("__control__", "private_files"):
+ for item in makelist(self.data.get("__control__", "private_files")):
if not item in includes: includes.append(item)
if not item in universe.private_files:
if not isabs(item):
item = path_join(dirname(filename), item)
universe.private_files.append(item)
for section in self.data.sections():
- if section != "control":
+ if section != "__control__":
Element(section, universe, filename)
for include_file in includes:
if not isabs(include_file):
include_file = path_join(dirname(filename), include_file)
DataFile(include_file, universe)
def save(self):
- if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ):
- if not exists(dirname(self.filename)): makedirs(dirname(self.filename))
+ """Write the data, if necessary."""
+
+ # when there is content or the file exists, but is not read-only
+ if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("__control__", "read_only") and self.data.getboolean("__control__", "read_only") ):
+
+ # make parent directories if necessary
+ if not exists(dirname(self.filename)):
+ makedirs(dirname(self.filename))
+
+ # our data file
file_descriptor = file(self.filename, "w")
+
+ # if it's marked private, chmod it appropriately
if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
chmod(self.filename, 0600)
- self.data.write(file_descriptor)
+
+ # write it back sorted, instead of using ConfigParser
+ sections = self.data.sections()
+ sections.sort()
+ for section in sections:
+ file_descriptor.write("[" + section + "]\n")
+ options = self.data.options(section)
+ options.sort()
+ for option in options:
+ file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
+ file_descriptor.write("\n")
+
+ # flush and close the file
file_descriptor.flush()
file_descriptor.close()
else: message = "An unnamed user"
message += " logged out."
log(message)
+ self.deactivate_avatar()
self.connection.close()
self.remove()
"output_queue",
"partial_input",
"echoing",
+ "terminator",
+ "negotiation_pause",
"avatar",
"account"
]:
# make a note of it
log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
- old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
- self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
+ old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
# close the old connection
old_user.connection.close()
# replace the old connection with this one
+ old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
old_user.connection = self.connection
old_user.last_address = old_user.address
old_user.address = self.address
if not self.state is "authenticated":
log("User " + self.account.get("name") + " logged in.")
self.authenticated = True
+ if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
+ self.account.set("administrator", "True")
def show_menu(self):
"""Send the user their current menu."""
"""Remove a user from the list of connected users."""
universe.userlist.remove(self)
- def send(self, output, eol="$(eol)", raw=False):
+ def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True):
"""Send arbitrary text to a connected user."""
# unless raw mode is on, clean it up all nice and pretty
if not raw:
+ # strip extra $(eol) off if present
+ while output.startswith("$(eol)"): output = output[6:]
+ while output.endswith("$(eol)"): output = output[:-6]
+
# we'll take out GA or EOR and add them back on the end
if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
terminate = True
# start with a newline, append the message, then end
# with the optional eol string passed to this function
# and the ansi escape to return to normal text
- output = "\r\n" + output + eol + chr(27) + "[0m"
+ output = "$(eol)" + output + eol + chr(27) + "[0m"
+
+ # tack on a prompt if active
+ if self.state == "active" and add_prompt: output += "$(eol)> "
# find and replace macros in the output
output = replace_macros(self, output)
# drop the output into the user's output queue
self.output_queue.append(output)
+ # if this is urgent, flush all pending output
+ if flush: self.flush()
+
def pulse(self):
"""All the things to do to the user per increment."""
else: self.state = "entering_account_name"
# show the user a menu as needed
- else: self.show_menu()
+ elif not self.state == "active": self.show_menu()
+
+ # flush any pending output in teh queue
+ self.flush()
# disconnect users with the appropriate state
if self.state == "disconnecting": self.quit()
- # the user is unique and not flagged to disconnect
- else:
-
- # try to send the last item in the queue and remove it
- if self.output_queue:
- try:
- self.connection.send(self.output_queue[0])
- del self.output_queue[0]
+ # check for input and add it to the queue
+ self.enqueue_input()
- # but if we can't, that's okay too
- except:
- pass
+ # there is input waiting in the queue
+ if self.input_queue: handle_user_input(self)
- # check for input and add it to the queue
- self.enqueue_input()
+ def flush(self):
+ """Try to send the last item in the queue and remove it."""
+ if self.output_queue:
+ try:
+ self.connection.send(self.output_queue[0])
+ del self.output_queue[0]
+ except:
+ pass
- # there is input waiting in the queue
- if self.input_queue: handle_user_input(self)
def enqueue_input(self):
"""Process and enqueue any new input."""
counter = 0
while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
- avatars = self.account.getlist("avatars")
- avatars.append(self.avatar.key)
- self.account.set("avatars", avatars)
+ self.avatar.append("inherit", "template:actor")
+ self.account.append("avatars", self.avatar.key)
def delete_avatar(self, avatar):
"""Remove an avatar from the world and from the user's list."""
avatars.remove(avatar)
self.account.set("avatars", avatars)
+ def activate_avatar_by_index(self, index):
+ """Enter the world with a particular indexed avatar."""
+ self.avatar = universe.contents[self.account.getlist("avatars")[index]]
+ self.avatar.owner = self
+ self.state = "active"
+ self.avatar.go_home()
+
+ def deactivate_avatar(self):
+ """Have the active avatar leave the world."""
+ if self.avatar:
+ current = self.avatar.get("location")
+ self.avatar.set("default_location", current)
+ del universe.contents[current].contents[self.avatar.key]
+ self.avatar.remove_facet("location")
+ self.avatar.owner = None
+ self.avatar = None
+
def destroy(self):
"""Destroy the user and associated avatars."""
for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
"$(bld)": chr(27) + "[1m",
"$(nrm)": chr(27) + "[0m",
"$(blk)": chr(27) + "[30m",
+ "$(blu)": chr(27) + "[34m",
+ "$(cyn)": chr(27) + "[36m",
"$(grn)": chr(27) + "[32m",
+ "$(mgt)": chr(27) + "[35m",
"$(red)": chr(27) + "[31m",
+ "$(yel)": chr(27) + "[33m",
}
# add dynamic macros where possible
# set a flag to reload
universe.reload_modules = True
+def command_quit(user):
+ """Leave the world and go back to the main menu."""
+ user.deactivate_avatar()
+ user.state = "main_utility"
+
def command_help(user, parameters):
"""List available commands and provide help for commands."""
# send the accumulated output to the user
user.send(output)
+def command_move(user, parameters):
+ """Move the avatar in a given direction."""
+ if parameters in universe.contents[user.avatar.get("location")].portals():
+ user.avatar.move_direction(parameters)
+ else: user.send("You cannot go that way.")
+
def command_say(user, parameters):
"""Speak to others in the same room."""
message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
# tell the room
- # TODO: we won't be using broadcast once there are actual rooms
- broadcast(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
+ user.avatar.echo_to_location(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
+ user.send("You " + action + ", \"" + message + "\"")
# there was no message
else:
facets.sort()
for facet in facets:
message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
+ elif arguments[0] == "result":
+ if len(arguments) > 1:
+ try:
+ message = repr(eval(" ".join(arguments[1:])))
+ except:
+ message = "Your expression raised an exception!"
if not message:
if parameters: message = "I don't know what \"" + parameters + "\" is."
else: message = "What do you want to show?"