Esempio n. 1
0
 def call(self, cmdobj, args, msg=None, cmdset=None, noansi=True):
     """
     Test a command by assigning all the needed
     properties to cmdobj and  running
         cmdobj.at_pre_cmd()
         cmdobj.parse()
         cmdobj.func()
         cmdobj.at_post_cmd()
     The msgreturn value is compared to eventual
     output sent to caller.msg in the game
     """
     cmdobj.caller = self.char1
     cmdobj.cmdstring = cmdobj.key
     cmdobj.args = args
     cmdobj.cmdset = cmdset
     cmdobj.raw_string = cmdobj.key + " " + args
     cmdobj.obj = self.char1
     cmdobj.sessid = 1
     # test
     self.char1.player.ndb.stored_msg = []
     cmdobj.at_pre_cmd()
     cmdobj.parse()
     cmdobj.func()
     cmdobj.at_post_cmd()
     # clean out prettytable sugar
     returned_msg = "|".join(_RE.sub("", mess) for mess in self.char1.player.ndb.stored_msg)
     #returned_msg = "|".join(self.char1.player.ndb.stored_msg)
     returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
     if msg != None:
         if msg == "" and returned_msg or not returned_msg.startswith(msg.strip()):
             sep1 = "\n" + "="*30 + "Wanted message" + "="*34 + "\n"
             sep2 = "\n" + "="*30 + "Returned message" + "="*32 + "\n"
             sep3 = "\n" + "="*78
             retval = sep1 + msg.strip() + sep2 + returned_msg + sep3
             raise AssertionError(retval)
Esempio n. 2
0
 def call(self,
          cmdobj,
          args,
          msg=None,
          cmdset=None,
          noansi=True,
          caller=None):
     """
     Test a command by assigning all the needed
     properties to cmdobj and  running
         cmdobj.at_pre_cmd()
         cmdobj.parse()
         cmdobj.func()
         cmdobj.at_post_cmd()
     The msgreturn value is compared to eventual
     output sent to caller.msg in the game
     """
     cmdobj.caller = caller if caller else self.char1
     #print "call:", cmdobj.key, cmdobj.caller, caller if caller else cmdobj.caller.player
     #print "perms:", cmdobj.caller.permissions.all()
     cmdobj.cmdstring = cmdobj.key
     cmdobj.args = args
     cmdobj.cmdset = cmdset
     cmdobj.sessid = self.CID
     cmdobj.session = SESSIONS.session_from_sessid(self.CID)
     cmdobj.player = self.player
     cmdobj.raw_string = cmdobj.key + " " + args
     cmdobj.obj = caller if caller else self.char1
     # test
     self.char1.player.ndb.stored_msg = []
     cmdobj.at_pre_cmd()
     cmdobj.parse()
     cmdobj.func()
     cmdobj.at_post_cmd()
     # clean out prettytable sugar
     stored_msg = self.char1.player.ndb.stored_msg if self.char1.player else self.char1.ndb.stored_msg
     returned_msg = "|".join(_RE.sub("", mess) for mess in stored_msg)
     #returned_msg = "|".join(self.char1.player.ndb.stored_msg)
     returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
     if msg != None:
         if msg == "" and returned_msg or not returned_msg.startswith(
                 msg.strip()):
             sep1 = "\n" + "=" * 30 + "Wanted message" + "=" * 34 + "\n"
             sep2 = "\n" + "=" * 30 + "Returned message" + "=" * 32 + "\n"
             sep3 = "\n" + "=" * 78
             retval = sep1 + msg.strip() + sep2 + returned_msg + sep3
             raise AssertionError(retval)
Esempio n. 3
0
from src.players.models import PlayerDB
from src.objects.models import ObjectDB
from src.server.models import ServerConfig
from src.comms.models import Channel

from src.utils import create, logger, utils, ansi
from src.commands.default.muxcommand import MuxCommand
from src.commands.cmdhandler import CMD_LOGINSTART

# limit symbol import for API
__all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", "CmdUnconnectedQuit", "CmdUnconnectedLook", "CmdUnconnectedHelp", "Magic")

CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE
CONNECTION_SCREEN = ""
try:
    CONNECTION_SCREEN = ansi.parse_ansi(utils.string_from_module(CONNECTION_SCREEN_MODULE))
except Exception:
    pass
if not CONNECTION_SCREEN:
    CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."

class Magic(MuxCommand):
    """
    Hidden command for the web client's magic cookie authenticator.
    """
    key = "magic"
    def func(self):
        session = self.caller
        player = PlayerDB.objects.player_search(self.lhs)
        if len(player) != 1:
            player = None
Esempio n. 4
0
def parse_ansi(*args, **kwargs):
    """
    Shortcut to use the IMC2 ANSI parser.
    """
    return ansi.parse_ansi(parser=IMCANSIParser(), *args, **kwargs)
Esempio n. 5
0
                    #print "cmdname, args, kwargs:", cmdname, args, kwargs
                    msdp_string = self.msdp.evennia_to_msdp(cmdname, *args, **kwargs)
                    #print "msdp_string:", msdp_string
                    self.msdp.data_out(msdp_string)

        # parse **kwargs, falling back to ttype if nothing is given explicitly
        ttype = self.protocol_flags.get('TTYPE', {})
        xterm256 = kwargs.get("xterm256", ttype.get('256 COLORS', False) if ttype.get("init_done") else True)
        useansi = kwargs.get("ansi", ttype and ttype.get('ANSI', False) if ttype.get("init_done") else True)
        raw = kwargs.get("raw", False)
        nomarkup = kwargs.get("nomarkup", not (xterm256 or useansi))
        prompt = kwargs.get("prompt")

        if prompt:
            # Send prompt separately
            prompt = ansi.parse_ansi(_RE_N.sub("", text) + "{n", strip_ansi=nomarkup, xterm256=xterm256)
            prompt = prompt.replace(IAC, IAC + IAC).replace('\n', '\r\n')
            prompt += IAC + GA
            self.transport.write(mccp_compress(self, prompt))

        #print "telnet kwargs=%s, message=%s" % (kwargs, text)
        #print "xterm256=%s, useansi=%s, raw=%s, nomarkup=%s, init_done=%s" % (xterm256, useansi, raw, nomarkup, ttype.get("init_done"))
        if raw:
            # no processing whatsoever
            self.sendLine(text)
        else:
            # we need to make sure to kill the color at the end in order
            # to match the webclient output.
            #print "telnet data out:", self.protocol_flags, id(self.protocol_flags), id(self), "nomarkup: %s, xterm256: %s" % (nomarkup, xterm256)
            self.sendLine(ansi.parse_ansi(_RE_N.sub("", text) + "{n", strip_ansi=nomarkup, xterm256=xterm256))
Esempio n. 6
0
                for cmdname, args, kwargs in oobstruct:
                    #print "cmdname, args, kwargs:", cmdname, args, kwargs
                    msdp_string = self.msdp.evennia_to_msdp(
                        cmdname, *args, **kwargs)
                    #print "msdp_string:", msdp_string
                    self.msdp.data_out(msdp_string)

        # parse **kwargs, falling back to ttype if nothing is given explicitly
        ttype = self.protocol_flags.get('TTYPE', {})
        xterm256 = kwargs.get("xterm256", ttype
                              and ttype.get('256 COLORS', False))
        useansi = kwargs.get("ansi", ttype and ttype.get('ANSI', False))
        raw = kwargs.get("raw", False)
        nomarkup = kwargs.get(
            "nomarkup", not (xterm256 or useansi)
            or not ttype.get("init_done"))

        #print "telnet kwargs=%s, message=%s" % (kwargs, text)
        #print "xterm256=%s, useansi=%s, raw=%s, nomarkup=%s, init_done=%s" % (xterm256, useansi, raw, nomarkup, ttype.get("init_done"))
        if raw:
            # no processing whatsoever
            self.sendLine(text)
        else:
            # we need to make sure to kill the color at the end in order
            # to match the webclient output.
            # print "telnet data out:", self.protocol_flags, id(self.protocol_flags), id(self)
            self.sendLine(
                ansi.parse_ansi(_RE_N.sub("", text) + "{n",
                                strip_ansi=nomarkup,
                                xterm256=xterm256))
Esempio n. 7
0
        raw = kwargs.get("raw", False)
        nomarkup = kwargs.get("nomarkup", not (xterm256 or useansi))
        prompt = kwargs.get("prompt")
        echo = kwargs.get("echo", None)
        mxp = kwargs.get("mxp", self.protocol_flags.get("MXP", False))

        #print "telnet kwargs=%s, message=%s" % (kwargs, text)
        #print "xterm256=%s, useansi=%s, raw=%s, nomarkup=%s, init_done=%s" % (xterm256, useansi, raw, nomarkup, ttype.get("init_done"))
        if raw:
            # no processing whatsoever
            self.sendLine(text)
        elif text:
            # we need to make sure to kill the color at the end in order
            # to match the webclient output.
            #print "telnet data out:", self.protocol_flags, id(self.protocol_flags), id(self), "nomarkup: %s, xterm256: %s" % (nomarkup, xterm256)
            linetosend = ansi.parse_ansi(_RE_N.sub("", text) + "{n", strip_ansi=nomarkup, xterm256=xterm256, mxp=mxp)
            if mxp:
                linetosend = mxp_parse(linetosend)
            self.sendLine(linetosend)

        if prompt:
            # Send prompt separately
            prompt = ansi.parse_ansi(_RE_N.sub("", prompt) + "{n", strip_ansi=nomarkup, xterm256=xterm256)
            prompt = prompt.replace(IAC, IAC + IAC).replace('\n', '\r\n')
            prompt += IAC + GA
            self.transport.write(mccp_compress(self, prompt))
        if echo:
            self.transport.write(mccp_compress(self, IAC+WONT+ECHO))
        elif echo == False:
            self.transport.write(mccp_compress(self, IAC+WILL+ECHO))
from src.comms.models import ChannelDB

from src.commands.cmdset import CmdSet
from src.utils import create, logger, utils, ansi
from src.commands.default.muxcommand import MuxCommand
from src.commands.cmdhandler import CMD_LOGINSTART

# limit symbol import for API
__all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate",
           "CmdUnconnectedQuit", "CmdUnconnectedLook", "CmdUnconnectedHelp")

MULTISESSION_MODE = settings.MULTISESSION_MODE
CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE
CONNECTION_SCREEN = ""
try:
    CONNECTION_SCREEN = ansi.parse_ansi(
        utils.random_string_from_module(CONNECTION_SCREEN_MODULE))
except Exception:
    pass
if not CONNECTION_SCREEN:
    CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."


class CmdUnconnectedConnect(MuxCommand):
    """
    Connect to the game.

    Usage (at login screen):
      connect <email> <password>

    Use the create command to first create an account before logging in.
    """
Esempio n. 9
0
        nomarkup = kwargs.get("nomarkup", not (xterm256 or useansi))
        prompt = kwargs.get("prompt")
        echo = kwargs.get("echo", None)
        mxp = kwargs.get("mxp", self.protocol_flags.get("MXP", False))

        #print "telnet kwargs=%s, message=%s" % (kwargs, text)
        #print "xterm256=%s, useansi=%s, raw=%s, nomarkup=%s, init_done=%s" % (xterm256, useansi, raw, nomarkup, ttype.get("init_done"))
        if raw:
            # no processing whatsoever
            self.sendLine(text)
        elif text:
            # we need to make sure to kill the color at the end in order
            # to match the webclient output.
            #print "telnet data out:", self.protocol_flags, id(self.protocol_flags), id(self), "nomarkup: %s, xterm256: %s" % (nomarkup, xterm256)
            linetosend = ansi.parse_ansi(_RE_N.sub("", text) + "{n",
                                         strip_ansi=nomarkup,
                                         xterm256=xterm256,
                                         mxp=mxp)
            if mxp:
                linetosend = mxp_parse(linetosend)
            self.sendLine(linetosend)

        if prompt:
            # Send prompt separately
            prompt = ansi.parse_ansi(_RE_N.sub("", prompt) + "{n",
                                     strip_ansi=nomarkup,
                                     xterm256=xterm256)
            prompt = prompt.replace(IAC, IAC + IAC).replace('\n', '\r\n')
            prompt += IAC + GA
            self.transport.write(mccp_compress(self, prompt))
        if echo:
            self.transport.write(mccp_compress(self, IAC + WONT + ECHO))
Esempio n. 10
0
class SshProtocol(Manhole, session.Session):
    """
    Each player connecting over ssh gets this protocol assigned to
    them.  All communication between game and player goes through
    here.
    """
    def __init__(self, starttuple):
        """
        For setting up the player.  If player is not None then we'll
        login automatically.
        """
        self.authenticated_player = starttuple[0]
        # obs must not be called self.factory, that gets overwritten!
        self.cfactory = starttuple[1]

    def terminalSize(self, width, height):
        """
        Initialize the terminal and connect to the new session.
        """
        # Clear the previous input line, redraw it at the new
        # cursor position
        self.terminal.eraseDisplay()
        self.terminal.cursorHome()
        self.width = width
        self.height = height

        # initialize the session
        client_address = self.getClientAddress()
        self.init_session("ssh", client_address, self.cfactory.sessionhandler)

        # since we might have authenticated already, we might set this here.
        if self.authenticated_player:
            self.logged_in = True
            self.uid = self.authenticated_player.user.id
        self.sessionhandler.connect(self)

    def connectionMade(self):
        """
        This is called when the connection is first
        established.
        """
        recvline.HistoricRecvLine.connectionMade(self)
        self.keyHandlers[CTRL_C] = self.handle_INT
        self.keyHandlers[CTRL_D] = self.handle_EOF
        self.keyHandlers[CTRL_L] = self.handle_FF
        self.keyHandlers[CTRL_BACKSLASH] = self.handle_QUIT

        # initalize

    def handle_INT(self):
        """
        Handle ^C as an interrupt keystroke by resetting the current input
        variables to their initial state.
        """
        self.lineBuffer = []
        self.lineBufferIndex = 0

        self.terminal.nextLine()
        self.terminal.write("KeyboardInterrupt")
        self.terminal.nextLine()

    def handle_EOF(self):
        """
        Handles EOF generally used to exit.
        """
        if self.lineBuffer:
            self.terminal.write('\a')
        else:
            self.handle_QUIT()

    def handle_FF(self):
        """
        Handle a 'form feed' byte - generally used to request a screen
        refresh/redraw.
        """
        self.terminal.eraseDisplay()
        self.terminal.cursorHome()

    def handle_QUIT(self):
        """
        Quit, end, and lose the connection.
        """
        self.terminal.loseConnection()

    def connectionLost(self, reason=None):
        """
        This is executed when the connection is lost for
        whatever reason. It can also be called directly,
        from the disconnect method.

        """
        insults.TerminalProtocol.connectionLost(self, reason)
        self.sessionhandler.disconnect(self)
        self.terminal.loseConnection()

    def getClientAddress(self):
        """
        Returns the client's address and port in a tuple. For example
        ('127.0.0.1', 41917)
        """
        return self.terminal.transport.getPeer()

    def lineReceived(self, string):
        """
        Communication Player -> Evennia. Any line return indicates a
        command for the purpose of the MUD.  So we take the user input
        and pass it on to the game engine.
        """
        self.sessionhandler.data_in(self, string)

    def lineSend(self, string):
        """
        Communication Evennia -> Player
        Any string sent should already have been
        properly formatted and processed
        before reaching this point.

        """
        for line in string.split('\n'):
            #this is the telnet-specific method for sending
            self.terminal.write(line)
            self.terminal.nextLine()

    # session-general method hooks

    def disconnect(self, reason="Connection closed. Goodbye for now."):
        """
        Disconnect from server
        """
        if reason:
            self.data_out(reason)
        self.connectionLost(reason)

    def data_out(self, text=None, **kwargs):
        """
        Data Evennia -> Player access hook. 'data' argument is a dict
        parsed for string settings.

        ssh flags:
            raw=True - leave all ansi markup and tokens unparsed
            nomarkup=True - remove all ansi markup

        """
        try:
            text = utils.to_str(text if text else "", encoding=self.encoding)
        except Exception, e:
            self.lineSend(str(e))
            return
        raw = kwargs.get("raw", False)
        nomarkup = kwargs.get("nomarkup", False)
        if raw:
            self.lineSend(text)
        else:
            self.lineSend(
                ansi.parse_ansi(text.strip("{r") + "{r", strip_ansi=nomarkup))