Esempio n. 1
0
    def setUp(self):
        """
        Sets up testing environment
        """
        self.player = create.create_player("TestPlayer", email="*****@*****.**", password="******", typeclass=self.player_typeclass)
        self.player2 = create.create_player("TestPlayer2", email="*****@*****.**", password="******", typeclass=self.player_typeclass)
        self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True)
        self.room1.db.desc = "room_desc"
        settings.DEFAULT_HOME = "#%i" % self.room1.id  # we must have a default home
        self.room2 = create.create_object(self.room_typeclass, key="Room2")
        self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2)
        self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1)
        self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1)
        self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1)
        self.char1.permissions.add("Immortals")
        self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1)
        self.char1.player = self.player
        self.player.db._last_puppet = self.char1
        self.char2.player = self.player2
        self.player2.db._last_puppet = self.char2
        self.script = create.create_script(self.script_typeclass, key="Script")
        self.player.permissions.add("Immortals")

        # set up a fake session

        session = ServerSession()
        session.init_session("telnet", ("localhost", "testmode"), SESSIONS)
        session.sessid = 1
        SESSIONS.portal_connect(session.get_sync_data())
        SESSIONS.login(SESSIONS.session_from_sessid(1), self.player, testmode=True)
        self.session = session
Esempio n. 2
0
 def func(self):
     """returns the list of online characters"""
     count_accounts = (SESSIONS.account_count())
     self.caller.msg("[%s] Through the fog you see:" % self.key)
     session_list = SESSIONS.get_sessions()
     table = evtable.EvTable(border='none')
     table.add_row('Character', 'On for', 'Idle',  'Location')
     for session in session_list:
         if not session.logged_in:
             continue
         delta_cmd = time.time() - session.cmd_last_visible
         delta_conn = time.time() - session.conn_time
         puppet = session.get_puppet()
         location = puppet.location.key if puppet and puppet.location else 'Nothingness'
         table.add_row(puppet.key if puppet else 'None', utils.time_format(delta_conn, 0),
                       utils.time_format(delta_cmd, 1), location)
     table.reformat_column(0, width=25, align='l')
     table.reformat_column(1, width=12, align='l')
     table.reformat_column(2, width=7, align='l')
     table.reformat_column(3, width=25, align='l')
     is_one = count_accounts == 1
     string = '%s' % 'A' if is_one else str(count_accounts)
     string += ' single ' if is_one else ' unique '
     plural = ' is' if is_one else 's are'
     string += 'account%s logged in.' % plural
     self.caller.msg(table)
     self.caller.msg(string)
Esempio n. 3
0
    def setUp(self):
        """
        Sets up testing environment
        """
        self.account = create.create_account("TestAccount", email="*****@*****.**", password="******", typeclass=self.account_typeclass)
        self.account2 = create.create_account("TestAccount2", email="*****@*****.**", password="******", typeclass=self.account_typeclass)
        self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True)
        self.room1.db.desc = "room_desc"
        settings.DEFAULT_HOME = "#%i" % self.room1.id  # we must have a default home
        # Set up fake prototype module for allowing tests to use named prototypes.
        settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example"
        self.room2 = create.create_object(self.room_typeclass, key="Room2")
        self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2)
        self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1)
        self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1)
        self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1)
        self.char1.permissions.add("Developer")
        self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1)
        self.char1.account = self.account
        self.account.db._last_puppet = self.char1
        self.char2.account = self.account2
        self.account2.db._last_puppet = self.char2
        self.script = create.create_script(self.script_typeclass, key="Script")
        self.account.permissions.add("Developer")

        # set up a fake session

        dummysession = ServerSession()
        dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS)
        dummysession.sessid = 1
        SESSIONS.portal_connect(dummysession.get_sync_data())  # note that this creates a new Session!
        session = SESSIONS.session_from_sessid(1)  # the real session
        SESSIONS.login(session, self.account, testmode=True)
        self.session = session
Esempio n. 4
0
    def start(self, ev_channel=None, rss_url=None, rss_rate=None):
        """
        Start by telling the portal to start a new RSS session

        ev_channel - key of the Evennia channel to connect to
        rss_url - full URL to the RSS feed to subscribe to
        rss_update_rate - how often for the feedreader to update
        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            self.db.ev_channel = channel
        if rss_url:
            self.db.rss_url = rss_url
        if rss_rate:
            self.db.rss_rate = rss_rate
        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {
            "uid": self.dbid,
            "url": self.db.rss_url,
            "rate": self.db.rss_rate
        }
        _SESSIONS.start_bot_session("evennia.server.portal.rss.RSSBotFactory",
                                    configdict)
Esempio n. 5
0
    def start(self, ev_channel=None, grapevine_channel=None):
        """
        Start by telling the portal to connect to the grapevine network.

        """
        if not _GRAPEVINE_ENABLED:
            self.delete()
            return

        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # connect to Evennia channel
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError(
                    f"Evennia Channel '{ev_channel}' not found.")
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel

        if grapevine_channel:
            self.db.grapevine_channel = grapevine_channel

        # these will be made available as properties on the protocol factory
        configdict = {
            "uid": self.dbid,
            "grapevine_channel": self.db.grapevine_channel
        }

        _SESSIONS.start_bot_session(self.factory_path, configdict)
Esempio n. 6
0
 def finish_event(self, event):
     loc = self.get_event_location(event)
     if loc:
         try:
             loc.stop_event_logging()
         except AttributeError:
             loc.db.current_event = None
             loc.msg_contents("{rEvent logging is now off for this room.{n")
             loc.tags.remove("logging event")
         end_str = "%s has ended at %s." % (event.name, loc.name)
     else:
         end_str = "%s has ended." % event.name
     if event.public_event:
         SESSIONS.announce_all(end_str)
     else:
         if loc:
             loc.msg_contents(end_str)
     event.finished = True
     event.clear_room()
     event.save()
     if event.id in self.db.active_events:
         self.db.active_events.remove(event.id)
     if event.id in self.db.idle_events:
         del self.db.idle_events[event.id]
     self.do_awards(event)
     # noinspection PyBroadException
     self.delete_event_post(event)
Esempio n. 7
0
def apply_changes(request):
    """
    Apply the game world's data.
    """
    try:
        # load system localized strings
        importer.import_system_localized_strings(settings.LANGUAGE_CODE)

        # reload localized strings
        LOCALIZED_STRINGS_HANDLER.reload()

        # rebuild the world
        build_all()

        # send client settings
        CLIENT_SETTINGS.reset()
        text = json.dumps({"settings": CLIENT_SETTINGS.all_values()})
        SESSIONS.announce_all(text)

        # restart the server
        SESSIONS.announce_all(" Server restarting ...")
        SESSIONS.server.shutdown(mode='reload')
    except Exception, e:
        message = "Can't build world: %s" % e
        logger.log_tracemsg(message)
        return render(request, 'fail.html', {"message": message})
Esempio n. 8
0
    def start(self, ev_channel=None, rss_url=None, rss_rate=None):
        """
        Start by telling the portal to start a new RSS session

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            rss_url (str): Full URL to the RSS feed to subscribe to.
            rss_update_rate (int): How often for the feedreader to update.

        Raises:
            RuntimeError: If `ev_channel` does not exist.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            self.db.ev_channel = channel
        if rss_url:
            self.db.rss_url = rss_url
        if rss_rate:
            self.db.rss_rate = rss_rate
        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid": self.dbid,
                      "url": self.db.rss_url,
                      "rate": self.db.rss_rate}
        _SESSIONS.start_bot_session("evennia.server.portal.rss.RSSBotFactory", configdict)
Esempio n. 9
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring(
                "Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable([
                "{wPlayer Name", "{wOn for", "{wIdle", "{wPuppeting", "{wRoom",
                "{wCmds", "{wProtocol", "{wHost"
            ])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet else "None"
                table.add_row([
                    utils.crop(player.name, width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1),
                    utils.crop(puppet.key if puppet else "None", width=25),
                    utils.crop(location, width=25), session.cmd_total,
                    session.protocol_key,
                    isinstance(session.address, tuple) and session.address[0]
                    or session.address
                ])
        else:
            # unprivileged
            table = prettytable.PrettyTable(
                ["{wPlayer name", "{wOn for", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([
                    utils.crop(player.key, width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1)
                ])

        isone = nplayers == 1
        string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (
            table, "One" if isone else nplayers, "" if isone else "s")
        self.msg(string)
Esempio n. 10
0
    def start(self,
              ev_channel=None,
              imc2_network=None,
              imc2_mudname=None,
              imc2_port=None,
              imc2_client_pwd=None,
              imc2_server_pwd=None):
        """
        Start by telling the portal to start a new session

        Args:
            ev_channel (str, optional): Key of the Evennia channel to connect to.
            imc2_network (str, optional): IMC2 network name.
            imc2_mudname (str, optional): Registered mudname (if not given, use settings.SERVERNAME).
            imc2_port (int, optional): Port number of the IMC2 network.
            imc2_client_pwd (str, optional): Client password registered with IMC2 network.
            imc2_server_pwd (str, optional): Server password registered with IMC2 network.

        Raises:
            RuntimeError: If `ev_channel` was not found.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if imc2_network:
            self.db.imc2_network = imc2_network
        if imc2_port:
            self.db.imc2_port = imc2_port
        if imc2_mudname:
            self.db.imc2_mudname = imc2_mudname
        elif not self.db.imc2_mudname:
            self.db.imc2_mudname = settings.SERVERNAME
        # storing imc2 passwords in attributes - a possible
        # security issue?
        if imc2_server_pwd:
            self.db.imc2_server_pwd = imc2_server_pwd
        if imc2_client_pwd:
            self.db.imc2_client_pwd = imc2_client_pwd

        configdict = {
            "uid": self.dbid,
            "mudname": self.db.imc2_mudname,
            "network": self.db.imc2_network,
            "port": self.db.imc2_port,
            "client_pwd": self.db.client_pwd,
            "server_pwd": self.db.server_pwd
        }

        _SESSIONS.start_bot_session(
            "evennia.server.portal.imc2.IMC2BotFactory", configdict)
Esempio n. 11
0
    def setUp(self):
        """
        Sets up testing environment
        """
        self.player = create.create_player("TestPlayer", email="*****@*****.**", password="******", typeclass=self.player_typeclass)
        self.player2 = create.create_player("TestPlayer2", email="*****@*****.**", password="******", typeclass=self.player_typeclass)
        self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True)
        self.room1.db.desc = "room_desc"
        settings.DEFAULT_HOME = "#%i" % self.room1.id  # we must have a default home
        self.room2 = create.create_object(self.room_typeclass, key="Room2")
        self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2)
        self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1)
        self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1)
        self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1)
        self.char1.permissions.add("Immortals")
        self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1)
        self.char1.player = self.player
        self.player.db._last_puppet = self.char1
        self.char2.player = self.player2
        self.player2.db._last_puppet = self.char2
        self.script = create.create_script(self.script_typeclass, key="Script")
        self.player.permissions.add("Immortals")

        # set up a fake session

        dummysession = ServerSession()
        dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS)
        dummysession.sessid = 1
        SESSIONS.portal_connect(dummysession.get_sync_data()) # note that this creates a new Session!
        session = SESSIONS.session_from_sessid(1) # the real session
        SESSIONS.login(session, self.player, testmode=True)
        self.session = session
Esempio n. 12
0
 def func(self):
     """returns the list of online characters"""
     count_accounts = (SESSIONS.account_count())
     self.caller.msg('[%s] Through the fog you see:' % self.key)
     session_list = SESSIONS.get_sessions()
     table = evtable.EvTable(border='none')
     table.add_row('Character', 'On for', 'Idle',  'Location')
     for session in session_list:
         puppet = session.get_puppet()
         if not session.logged_in or not puppet:
             continue
         delta_cmd = time.time() - session.cmd_last_visible
         delta_conn = time.time() - session.conn_time
         location = puppet.location.key if puppet and puppet.location else 'Nothingness'
         table.add_row(puppet.key if puppet else 'None', utils.time_format(delta_conn, 0),
                       utils.time_format(delta_cmd, 1), location)
     table.reformat_column(0, width=25, align='l')
     table.reformat_column(1, width=12, align='l')
     table.reformat_column(2, width=7, align='l')
     table.reformat_column(3, width=25, align='l')
     is_one = count_accounts == 1
     string = '%s' % 'A' if is_one else str(count_accounts)
     string += ' single ' if is_one else ' unique '
     plural = ' is' if is_one else 's are'
     string += 'account%s logged in.' % plural
     self.caller.msg(table)
     self.caller.msg(string)
Esempio n. 13
0
def apply_changes(request):
    """
    Apply the game world's data.
    """
    try:
        # reload localized strings
        LOCALIZED_STRINGS_HANDLER.reload()

        # rebuild the world
        build_all()

        # send client settings
        CLIENT_SETTINGS.reset()
        client_settings = CLIENT_SETTINGS.all_values()
        client_settings["game_name"] = GAME_SETTINGS.get("game_name")
        client_settings["show_social_box"] = not GAME_SETTINGS.get("solo_mode")
        text = json.dumps({"settings": client_settings})
        SESSIONS.announce_all(text)

        # restart the server
        SESSIONS.announce_all(" Server restarting ...")
        SESSIONS.server.shutdown(mode='reload')
    except Exception, e:
        message = "Can't build world: %s" % e
        logger.log_tracemsg(message)
        return render(request, 'fail.html', {"message": message})
Esempio n. 14
0
    def setUp(self):
        """
        Sets up testing environment
        """
        self.account = create.create_account("TestAccount",
                                             email="*****@*****.**",
                                             password="******",
                                             typeclass=self.account_typeclass)
        self.account2 = create.create_account("TestAccount2",
                                              email="*****@*****.**",
                                              password="******",
                                              typeclass=self.account_typeclass)
        self.room1 = create.create_object(self.room_typeclass,
                                          key="Room",
                                          nohome=True)
        self.room1.db.desc = "room_desc"
        settings.DEFAULT_HOME = "#%i" % self.room1.id  # we must have a default home
        # Set up fake prototype module for allowing tests to use named prototypes.
        settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example"
        self.room2 = create.create_object(self.room_typeclass, key="Room2")
        self.exit = create.create_object(self.exit_typeclass,
                                         key='out',
                                         location=self.room1,
                                         destination=self.room2)
        self.obj1 = create.create_object(self.object_typeclass,
                                         key="Obj",
                                         location=self.room1,
                                         home=self.room1)
        self.obj2 = create.create_object(self.object_typeclass,
                                         key="Obj2",
                                         location=self.room1,
                                         home=self.room1)
        self.char1 = create.create_object(self.character_typeclass,
                                          key="Char",
                                          location=self.room1,
                                          home=self.room1)
        self.char1.permissions.add("Developer")
        self.char2 = create.create_object(self.character_typeclass,
                                          key="Char2",
                                          location=self.room1,
                                          home=self.room1)
        self.char1.account = self.account
        self.account.db._last_puppet = self.char1
        self.char2.account = self.account2
        self.account2.db._last_puppet = self.char2
        self.script = create.create_script(self.script_typeclass, key="Script")
        self.account.permissions.add("Developer")

        # set up a fake session

        dummysession = ServerSession()
        dummysession.init_session("telnet", ("localhost", "testmode"),
                                  SESSIONS)
        dummysession.sessid = 1
        SESSIONS.portal_connect(dummysession.get_sync_data()
                                )  # note that this creates a new Session!
        session = SESSIONS.session_from_sessid(1)  # the real session
        SESSIONS.login(session, self.account, testmode=True)
        self.session = session
Esempio n. 15
0
 def func(self):
     """Implements command"""
     if not self.args:
         self.caller.msg("Usage: wall <message>")
         return
     message = '%s shouts "%s"' % (self.caller.name, self.args)
     self.msg("Announcing to all connected sessions ...")
     SESSIONS.announce_all(message)
Esempio n. 16
0
 def at_repeat(self):
     "called every 60 seconds"
     global _SESSIONS
     if not _SESSIONS:
         from evennia.server.sessionhandler import SESSIONS as _SESSIONS
     # print "session check!"
     # print "ValidateSessions run"
     _SESSIONS.validate_sessions()
Esempio n. 17
0
 def func(self):
     """Implements command"""
     if not self.args:
         self.caller.msg("Usage: @wall <message>")
         return
     message = "%s shouts \"%s\"" % (self.caller.name, self.args)
     self.msg("Announcing to all connected players ...")
     SESSIONS.announce_all(message)
Esempio n. 18
0
 def func(self):
     "Implements command"
     if not self.args:
         self.caller.msg("Usage: @wall <message>")
         return
     message = "%s shouts \"%s\"" % (self.caller.name, self.args)
     self.msg("Announcing to all connected players ...")
     SESSIONS.announce_all(message)
Esempio n. 19
0
    def func(self):
        "Implementing the function"
        caller = self.caller
        args = self.args

        if not args:
            caller.msg("Usage: @boot[/switches] <player> [:reason]")
            return

        if ':' in args:
            args, reason = [a.strip() for a in args.split(':', 1)]
        else:
            args, reason = args, ""

        boot_list = []

        if 'sid' in self.switches:
            # Boot a particular session id.
            sessions = SESSIONS.get_sessions(True)
            for sess in sessions:
                # Find the session with the matching session id.
                if sess.sessid == int(args):
                    boot_list.append(sess)
                    break
        else:
            # Boot by player object
            pobj = search.player_search(args)
            if not pobj:
                caller.msg("Player %s was not found." % args)
                return
            pobj = pobj[0]
            if not pobj.access(caller, 'boot'):
                string = "You don't have the permission to boot %s." % (
                    pobj.key, )
                caller.msg(string)
                return
            # we have a bootable object with a connected user
            matches = SESSIONS.sessions_from_player(pobj)
            for match in matches:
                boot_list.append(match)

        if not boot_list:
            caller.msg(
                "No matching sessions found. The Player does not seem to be online."
            )
            return

        # Carry out the booting of the sessions in the boot list.

        feedback = None
        if not 'quiet' in self.switches:
            feedback = "You have been disconnected by %s.\n" % caller.name
            if reason:
                feedback += "\nReason given: %s" % reason

        for session in boot_list:
            session.msg(feedback)
            session.player.disconnect_session_from_player(session)
Esempio n. 20
0
    def start(self, ev_channel=None, irc_botname=None, irc_channel=None,
              irc_network=None, irc_port=None, irc_ssl=None):
        """
        Start by telling the portal to start a new session.

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            irc_botname (str): Name of bot to connect to irc channel. If
                not set, use `self.key`.
            irc_channel (str): Name of channel on the form `#channelname`.
            irc_network (str): URL of the IRC network, like `irc.freenode.net`.
            irc_port (str): Port number of the irc network, like `6667`.
            irc_ssl (bool): Indicates whether to use SSL connection.

        """
        if not _IRC_ENABLED:
            # the bot was created, then IRC was turned off. We delete
            # ourselves (this will also kill the start script)
            self.delete()
            return

        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError(f"Evennia Channel '{ev_channel}' not found.")
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port
        if irc_ssl:
            self.db.irc_ssl = irc_ssl

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid": self.dbid,
                      "botname": self.db.irc_botname,
                      "channel": self.db.irc_channel,
                      "network": self.db.irc_network,
                      "port": self.db.irc_port,
                      "ssl": self.db.irc_ssl}
        _SESSIONS.start_bot_session(self.factory_path, configdict)
Esempio n. 21
0
def _server_maintenance():
    """
    This maintenance function handles repeated checks and updates that
    the server needs to do. It is called every minute.
    """
    global EVENNIA, _MAINTENANCE_COUNT, _FLUSH_CACHE, _GAMETIME_MODULE
    global _LAST_SERVER_TIME_SNAPSHOT

    if not _FLUSH_CACHE:
        from evennia.utils.idmapper.models import conditional_flush as _FLUSH_CACHE
    if not _GAMETIME_MODULE:
        from evennia.utils import gametime as _GAMETIME_MODULE

    _MAINTENANCE_COUNT += 1

    now = time.time()
    if _MAINTENANCE_COUNT == 1:
        # first call after a reload
        _GAMETIME_MODULE.SERVER_START_TIME = now
        _GAMETIME_MODULE.SERVER_RUNTIME = ServerConfig.objects.conf(
            "runtime", default=0.0)
        _LAST_SERVER_TIME_SNAPSHOT = now
    else:
        # adjust the runtime not with 60s but with the actual elapsed time
        # in case this may varies slightly from 60s.
        _GAMETIME_MODULE.SERVER_RUNTIME += now - _LAST_SERVER_TIME_SNAPSHOT
    _LAST_SERVER_TIME_SNAPSHOT = now

    # update game time and save it across reloads
    _GAMETIME_MODULE.SERVER_RUNTIME_LAST_UPDATED = now
    ServerConfig.objects.conf("runtime", _GAMETIME_MODULE.SERVER_RUNTIME)

    if _MAINTENANCE_COUNT % 300 == 0:
        # check cache size every 5 minutes
        _FLUSH_CACHE(_IDMAPPER_CACHE_MAXSIZE)
    if _MAINTENANCE_COUNT % 3600 == 0:
        # validate scripts every hour
        evennia.ScriptDB.objects.validate()
    if _MAINTENANCE_COUNT % 3700 == 0:
        # validate channels off-sync with scripts
        evennia.CHANNEL_HANDLER.update()
    if _MAINTENANCE_COUNT % (3600 * 7) == 0:
        # drop database connection every 7 hrs to avoid default timeouts on MySQL
        # (see https://github.com/evennia/evennia/issues/1376)
        connection.close()

    # handle idle timeouts
    if _IDLE_TIMEOUT > 0:
        reason = _("idle timeout exceeded")
        to_disconnect = []
        for session in (sess for sess in SESSIONS.values()
                        if (now - sess.cmd_last) > _IDLE_TIMEOUT):
            if not session.account or not session.account.access(
                    session.account, "noidletimeout", default=False):
                to_disconnect.append(session)

        for session in to_disconnect:
            SESSIONS.disconnect(session, reason=reason)
Esempio n. 22
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable(["{wИмя игрока",
                                             "{wВ игре",
                                             "{wIdle",
                                             "{wУправляет",
                                             "{wКомната",
                                             "{wCmds",
                                             "{wПротокол",
                                             "{wХост"])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet and puppet.location else "None"
                table.add_row([utils.crop(player.name, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1),
                               utils.crop(puppet.key if puppet else "None", width=25),
                               utils.crop(location, width=25),
                               session.cmd_total,
                               session.protocol_key,
                               isinstance(session.address, tuple) and session.address[0] or session.address])
        else:
            # unprivileged
            table = prettytable.PrettyTable(["{wИмя игрока", "{wВ игре", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([utils.crop(player.key, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1)])

        isone = nplayers == 1
        string = "{wИгроков:{n\n%s\n%s уникальных аккаунтов%s залогинено." % (table, "Один" if isone else nplayers, "" if isone else "")
        self.msg(string)
Esempio n. 23
0
    def func(self):
        """
        Get all connected accounts by polling session.
        """

        account = self.account
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.account.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = account.check_permstring(
                "Developer") or account.check_permstring("Admins")

        naccounts = SESSIONS.account_count()
        if show_session_data:
            # privileged info
            table = self.styled_table("|wAccount Name", "|wOn for", "|wIdle",
                                      "|wPuppeting", "|wRoom", "|wCmds",
                                      "|wProtocol", "|wHost")
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                account = session.get_account()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet and puppet.location else "None"
                table.add_row(
                    utils.crop(account.get_display_name(account), width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1),
                    utils.crop(
                        puppet.get_display_name(account) if puppet else "None",
                        width=25), utils.crop(location, width=25),
                    session.cmd_total, session.protocol_key,
                    isinstance(session.address, tuple) and session.address[0]
                    or session.address)
        else:
            # unprivileged
            table = self.styled_table("|wAccount name", "|wOn for", "|wIdle")
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                account = session.get_account()
                table.add_row(
                    utils.crop(account.get_display_name(account), width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1))
        is_one = naccounts == 1
        self.msg(
            "|wAccounts:|n\n%s\n%s unique account%s logged in." %
            (table, "One" if is_one else naccounts, "" if is_one else "s"))
Esempio n. 24
0
 def func(self):
     """Implements command"""
     if not self.args:
         self.caller.msg('Usage: {} <message>'.format(self.cmdstring))
         return
     message = '### %s%s|n shouts "|w%s|n"' % (self.caller.STYLE,
                                               self.caller.name, self.args)
     self.msg("Announcing to all connections ...")
     SESSIONS.announce_all(message)
Esempio n. 25
0
    def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
        """
        Start by telling the portal to start a new session.

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            irc_botname (str): Name of bot to connect to irc channel. If
                not set, use `self.key`.
            irc_channel (str): Name of channel on the form `#channelname`.
            irc_network (str): URL of the IRC network, like `irc.freenode.net`.
            irc_port (str): Port number of the irc network, like `6667`.
            irc_ssl (bool): Indicates whether to use SSL connection.

        """
        if not _IRC_ENABLED:
            # the bot was created, then IRC was turned off. We delete
            # ourselves (this will also kill the start script)
            self.delete()
            return

        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port
        if irc_ssl:
            self.db.irc_ssl = irc_ssl

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid": self.dbid,
                      "botname": self.db.irc_botname,
                      "channel": self.db.irc_channel,
                      "network": self.db.irc_network,
                      "port": self.db.irc_port,
                      "ssl": self.db.irc_ssl}
        _SESSIONS.start_bot_session("evennia.server.portal.irc.IRCBotFactory", configdict)
Esempio n. 26
0
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Time slows as Ashlan mauls the fabric of reality...")
     SESSIONS.server.shutdown(mode='reload')
Esempio n. 27
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable(["{wPlayer Name",
                                             "{wOn for",
                                             "{wIdle",
                                             "{wPuppeting",
                                             "{wRoom",
                                             "{wCmds",
                                             "{wProtocol",
                                             "{wHost"])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet else "None"
                table.add_row([utils.crop(player.name, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1),
                               utils.crop(puppet.key if puppet else "None", width=25),
                               utils.crop(location, width=25),
                               session.cmd_total,
                               session.protocol_key,
                               isinstance(session.address, tuple) and session.address[0] or session.address])
        else:
            # unprivileged
            table = prettytable.PrettyTable(["{wPlayer name", "{wOn for", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([utils.crop(player.key, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1)])

        isone = nplayers == 1
        string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (table, "One" if isone else nplayers, "" if isone else "s")
        self.msg(string)
Esempio n. 28
0
 def announce_upcoming_event(event, diff):
     mins = int(diff / 60)
     secs = diff % 60
     announce_msg = "{wEvent: '%s'(#%s) will start in %s minutes and %s seconds.{n" % (
         event.name, event.id, mins, secs)
     if event.public_event:
         SESSIONS.announce_all(announce_msg)
     else:
         event.make_announcement(announce_msg)
Esempio n. 29
0
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Server restart initiated %s..." % reason)
     SESSIONS.server.shutdown(mode='reload')
Esempio n. 30
0
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Server restart initiated %s..." % reason)
     SESSIONS.portal_restart_server()
Esempio n. 31
0
    def func(self):
        """
        Get all connected accounts by polling session.
        """

        account = self.account
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.account.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = account.check_permstring("Developer") or account.check_permstring("Admins")

        naccounts = (SESSIONS.account_count())
        if show_session_data:
            # privileged info
            table = evtable.EvTable("|wAccount Name",
                                    "|wOn for",
                                    "|wIdle",
                                    "|wPuppeting",
                                    "|wRoom",
                                    "|wCmds",
                                    "|wProtocol",
                                    "|wHost")
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                account = session.get_account()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet and puppet.location else "None"
                table.add_row(utils.crop(account.name, width=25),
                              utils.time_format(delta_conn, 0),
                              utils.time_format(delta_cmd, 1),
                              utils.crop(puppet.key if puppet else "None", width=25),
                              utils.crop(location, width=25),
                              session.cmd_total,
                              session.protocol_key,
                              isinstance(session.address, tuple) and session.address[0] or session.address)
        else:
            # unprivileged
            table = evtable.EvTable("|wAccount name", "|wOn for", "|wIdle")
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                account = session.get_account()
                table.add_row(utils.crop(account.key, width=25),
                              utils.time_format(delta_conn, 0),
                              utils.time_format(delta_cmd, 1))
        is_one = naccounts == 1
        self.msg("|wAccounts:|n\n%s\n%s unique account%s logged in."
                 % (table, "One" if is_one else naccounts, "" if is_one else "s"))
Esempio n. 32
0
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Server restart initiated %s..." % reason)
     SESSIONS.server.shutdown(mode='reload')
Esempio n. 33
0
    def start(self,
              ev_channel=None,
              irc_botname=None,
              irc_channel=None,
              irc_network=None,
              irc_port=None):
        """
        Start by telling the portal to start a new session.

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            irc_botname (str): Name of bot to connect to irc channel. If
                not set, use `self.key`.
            irc_channel (str): Name of channel on the form `#channelname`.
            irc_network (str): URL of the IRC network, like `irc.freenode.net`.
            irc_port (str): Port number of the irc network, like `6667`.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {
            "uid": self.dbid,
            "botname": self.db.irc_botname,
            "channel": self.db.irc_channel,
            "network": self.db.irc_network,
            "port": self.db.irc_port
        }
        _SESSIONS.start_bot_session("evennia.server.portal.irc.IRCBotFactory",
                                    configdict)
Esempio n. 34
0
 def at_post_puppet(self):
     self.location.msg_contents("%s has connected" % self.key)
     loginmsg = "[************--Rumour Monger--************]|/" \
                "%s arrives in Mercadia.|/" \
                "[*****************************************]|/" % self.key
     SESSIONS.announce_all(loginmsg)
     tickerhandler.add(interval=randint(10, 15),
                       callback=self.at_regen,
                       persistent=True)
     self.execute_cmd("look")
Esempio n. 35
0
    def func(self):
        """Implementing the function"""
        caller = self.caller
        args = self.args

        if not args:
            caller.msg("Usage: @boot[/switches] <player> [:reason]")
            return

        if ':' in args:
            args, reason = [a.strip() for a in args.split(':', 1)]
        else:
            args, reason = args, ""

        boot_list = []

        if 'sid' in self.switches:
            # Boot a particular session id.
            sessions = SESSIONS.get_sessions(True)
            for sess in sessions:
                # Find the session with the matching session id.
                if sess.sessid == int(args):
                    boot_list.append(sess)
                    break
        else:
            # Boot by player object
            pobj = search.player_search(args)
            if not pobj:
                caller.msg("Player %s was not found." % args)
                return
            pobj = pobj[0]
            if not pobj.access(caller, 'boot'):
                string = "You don't have the permission to boot %s." % (pobj.key, )
                caller.msg(string)
                return
            # we have a bootable object with a connected user
            matches = SESSIONS.sessions_from_player(pobj)
            for match in matches:
                boot_list.append(match)

        if not boot_list:
            caller.msg("No matching sessions found. The Player does not seem to be online.")
            return

        # Carry out the booting of the sessions in the boot list.

        feedback = None
        if 'quiet' not in self.switches:
            feedback = "You have been disconnected by %s.\n" % caller.name
            if reason:
                feedback += "\nReason given: %s" % reason

        for session in boot_list:
            session.msg(feedback)
            session.player.disconnect_session_from_player(session)
Esempio n. 36
0
 def func(self):
     """Define function"""
     # Only allow shutdown if caller has session
     if not self.caller.sessions.get():
         return
     self.msg("Shutting down server ...")
     announcement = "\nServer is being SHUT DOWN!\n"
     if self.args:
         announcement += "%s\n" % self.args
     logger.log_info("Server shutdown by %s." % self.caller.name)
     SESSIONS.announce_all(announcement)
     SESSIONS.portal_shutdown()
Esempio n. 37
0
def reset_server():
    """
    We end the initialization by resetting the server. This makes sure
    the first login is the same as all the following ones,
    particularly it cleans all caches for the special objects.  It
    also checks so the warm-reset mechanism works as it should.

    """
    ServerConfig.objects.conf("server_epoch", time.time())
    from evennia.server.sessionhandler import SESSIONS
    logger.log_info("Initial setup complete. Restarting Server once.")
    SESSIONS.portal_reset_server()
Esempio n. 38
0
def reset_server():
    """
    We end the initialization by resetting the server. This makes sure
    the first login is the same as all the following ones,
    particularly it cleans all caches for the special objects.  It
    also checks so the warm-reset mechanism works as it should.

    """
    ServerConfig.objects.conf("server_epoch", time.time())
    from evennia.server.sessionhandler import SESSIONS
    logger.log_info("Initial setup complete. Restarting Server once.")
    SESSIONS.portal_reset_server()
Esempio n. 39
0
 def func(self):
     """Define function"""
     # Only allow shutdown if caller has session
     if not self.caller.sessions.get():
         return
     self.msg('Shutting down server ...')
     announcement = "\nServer is being SHUT DOWN!\n"
     if self.args:
         announcement += "%s\n" % self.args
     logger.log_info('Server shutdown by %s.' % self.caller.name)
     SESSIONS.announce_all(announcement)
     SESSIONS.server.shutdown(mode='shutdown')
     SESSIONS.portal_shutdown()
Esempio n. 40
0
 def at_repeat(self):
     """
     Called every minute to update the timers.
     """
     if self.check_event():
         # check if we've been tagged to not reset next time we run
         self.do_weekly_events()
     else:
         hour = timedelta(minutes=65)
         if self.time_remaining < hour:
             from evennia.server.sessionhandler import SESSIONS
             cron_msg = "{wReminder: Weekly Updates will be running in about an hour.{n"
             SESSIONS.announce_all(cron_msg)
Esempio n. 41
0
    def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None,
              imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None):
        """
        Start by telling the portal to start a new session

        Args:
            ev_channel (str, optional): Key of the Evennia channel to connect to.
            imc2_network (str, optional): IMC2 network name.
            imc2_mudname (str, optional): Registered mudname (if not given, use settings.SERVERNAME).
            imc2_port (int, optional): Port number of the IMC2 network.
            imc2_client_pwd (str, optional): Client password registered with IMC2 network.
            imc2_server_pwd (str, optional): Server password registered with IMC2 network.

        Raises:
            RuntimeError: If `ev_channel` was not found.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if imc2_network:
            self.db.imc2_network = imc2_network
        if imc2_port:
            self.db.imc2_port = imc2_port
        if imc2_mudname:
            self.db.imc2_mudname = imc2_mudname
        elif not self.db.imc2_mudname:
            self.db.imc2_mudname = settings.SERVERNAME
        # storing imc2 passwords in attributes - a possible
        # security issue?
        if imc2_server_pwd:
            self.db.imc2_server_pwd = imc2_server_pwd
        if imc2_client_pwd:
            self.db.imc2_client_pwd = imc2_client_pwd

        configdict = {"uid": self.dbid,
                      "mudname": self.db.imc2_mudname,
                      "network": self.db.imc2_network,
                      "port": self.db.imc2_port,
                      "client_pwd": self.db.client_pwd,
                      "server_pwd": self.db.server_pwd}

        _SESSIONS.start_bot_session("evennia.server.portal.imc2.IMC2BotFactory", configdict)
Esempio n. 42
0
    def func(self):
        session_list = SESSIONS.get_sessions()

        table = evtable.EvTable(" |w|uName:|n",
                                "|w|uIdle:|n",
                                "|w|uConn:|n",
                                "|w|uClearance:|n",
                                table=None,
                                border=None,
                                width=78)

        for session in session_list:
            player = session.get_account()
            idle = time.time() - session.cmd_last_visible
            conn = time.time() - session.conn_time
            clearance = session.get_puppet().db.clearance
            flag = None
            if player.locks.check_lockstring(player, "dummy:perm(Admin)"):
                flag = "|y!|n"
            elif player.locks.check_lockstring(player, "dummy:perm(Builder)"):
                flag = "|g&|n"
            elif player.locks.check_lockstring(player, "dummy:perm(Helper)"):
                flag = "|r$|n"
            else:
                flag = " "
            table.add_row(
                flag + utils.crop(player.name), utils.time_format(idle, 0),
                utils.time_format(conn, 0),
                "|{}{}|n".format(clearance_color(CLEARANCE.get(clearance)),
                                 CLEARANCE.get(clearance)))

        table.reformat_column(0, width=24)
        table.reformat_column(1, width=12)
        table.reformat_column(2, width=12)
        table.reformat_column(3, width=30)

        self.caller.msg("|w_|n" * 78)
        title = ansi.ANSIString("|[002|w|u{}|n".format(settings.SERVERNAME))
        self.caller.msg(title.center(78, '^').replace('^', "|[002|w_|n"))

        self.caller.msg(table)
        self.caller.msg("|w_|n" * 78)
        self.caller.msg("Total Connected: %s" % SESSIONS.account_count())
        whotable = evtable.EvTable("", "", "", header=False, border=None)
        whotable.reformat_column(0, width=26)
        whotable.reformat_column(1, width=26)
        whotable.reformat_column(2, width=26)
        whotable.add_row("|y!|n - Administrators", "|g&|n - Storytellers",
                         "|r$|n - Player Helpers")
        self.caller.msg(whotable)
        self.caller.msg("|w_|n" * 78 + "\n")
Esempio n. 43
0
    def disconnect_session_from_player(self, session):
        """
        Access method for disconnecting a given session from the
        player (connection happens automatically in the
        sessionhandler)

        Args:
            session (Session): Session to disconnect.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        _SESSIONS.disconnect(session)
Esempio n. 44
0
    def disconnect_session_from_player(self, session):
        """
        Access method for disconnecting a given session from the
        player (connection happens automatically in the
        sessionhandler)

        Args:
            session (Session): Session to disconnect.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        _SESSIONS.disconnect(session)
Esempio n. 45
0
    def disconnect_session_from_account(self, session, reason=None):
        """
        Access method for disconnecting a given session from the
        account (connection happens automatically in the
        sessionhandler)

        Args:
            session (Session): Session to disconnect.
            reason (str, optional): Eventual reason for the disconnect.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        _SESSIONS.disconnect(session, reason)
Esempio n. 46
0
def apply_changes(request):
    """
    Apply the game world's data.
    """
    try:
        # rebuild the world
        build_all()

        # reload
        SESSIONS.announce_all(" Server restarting ...")
        SESSIONS.server.shutdown(mode='reload')
    except Exception, e:
        ostring = "Can't build world: %s" % e
        logger.log_tracemsg(ostring)
        raise http.HttpResponseServerError(ostring)
Esempio n. 47
0
    def disconnect_session_from_account(self, session, reason=None):
        """
        Access method for disconnecting a given session from the
        account (connection happens automatically in the
        sessionhandler)

        Args:
            session (Session): Session to disconnect.
            reason (str, optional): Eventual reason for the disconnect.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        _SESSIONS.disconnect(session, reason)
Esempio n. 48
0
 def update_weather(self, *args, **kwargs):
     """
     Called by the tickerhandler at regular intervals. Even so, we
     only update 20% of the time, picking a random weather message
     when we do. The tickerhandler requires that this hook accepts
     any arguments and keyword arguments (hence the *args, **kwargs
     even though we don't actually use them in this example)
     """
     slow_room = True
     empty_room = True
     session_list = SESSIONS.get_sessions()
     for session in session_list:
         character = session.get_puppet()
         if not session.logged_in or not character or character.location != self:
             continue
         empty_room = False
         if session.cmd_last_visible > self.ndb.weather_time:
             slow_room = False
             break
     if empty_room:
         return
     if slow_room:
         self.attempt_weather_update(0.05)  # only attempt update 5% of the time
     else:
         self.attempt_weather_update(0.20)
Esempio n. 49
0
    def call(self, cmdobj, args, msg=None, cmdset=None, noansi=True, caller=None, receiver=None, cmdstring=None, obj=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

        Returns:
            msg (str): The received message that was sent to the caller.

        """
        caller = caller if caller else self.char1
        receiver = receiver if receiver else caller
        cmdobj.caller = caller
        cmdobj.cmdstring = cmdstring if cmdstring else cmdobj.key
        cmdobj.args = args
        cmdobj.cmdset = cmdset
        cmdobj.session = SESSIONS.session_from_sessid(1)
        cmdobj.player = self.player
        cmdobj.raw_string = cmdobj.key + " " + args
        cmdobj.obj = obj or (caller if caller else self.char1)
        # test
        old_msg = receiver.msg
        returned_msg = ""
        try:
            receiver.msg = Mock()
            cmdobj.at_pre_cmd()
            cmdobj.parse()
            cmdobj.func()
            cmdobj.at_post_cmd()
        except InterruptCommand:
            pass
        finally:
            # clean out prettytable sugar. We only operate on text-type
            stored_msg = [args[0] if args and args[0] else kwargs.get("text",utils.to_str(kwargs, force_string=True))
                    for name, args, kwargs in receiver.msg.mock_calls]
            # Get the first element of a tuple if msg received a tuple instead of a string
            stored_msg = [smsg[0] if isinstance(smsg, tuple) else smsg for smsg in stored_msg]
            if msg is not None:
                returned_msg = "||".join(_RE.sub("", mess) for mess in stored_msg)
                returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
                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)
            else:
                returned_msg = "\n".join(str(msg) for msg in stored_msg)
                returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
            receiver.msg = old_msg

        return returned_msg
Esempio n. 50
0
 def get_session(self, sessid):
     """
     Return session with given sessid connected to this player.
     note that the sessionhandler also accepts sessid as an iterable.
     """
     global _SESSIONS
     if not _SESSIONS:
         from evennia.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.session_from_player(self, sessid)
Esempio n. 51
0
    def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None):
        """
        Start by telling the portal to start a new session.

        ev_channel - key of the Evennia channel to connect to
        irc_botname - name of bot to connect to irc channel. If not set, use self.key
        irc_channel - name of channel on the form #channelname
        irc_network - url of network, like irc.freenode.net
        irc_port - port number of irc network, like 6667
        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid":self.dbid,
                      "botname": self.db.irc_botname,
                      "channel": self.db.irc_channel ,
                      "network": self.db.irc_network,
                      "port": self.db.irc_port}
        _SESSIONS.start_bot_session("evennia.server.portal.irc.IRCBotFactory", configdict)
Esempio n. 52
0
def _server_maintenance():
    """
    This maintenance function handles repeated checks and updates that
    the server needs to do. It is called every minute.
    """
    global EVENNIA, _MAINTENANCE_COUNT, _FLUSH_CACHE, _GAMETIME_MODULE
    if not _FLUSH_CACHE:
        from evennia.utils.idmapper.models import conditional_flush as _FLUSH_CACHE
    if not _GAMETIME_MODULE:
        from evennia.utils import gametime as _GAMETIME_MODULE

    _MAINTENANCE_COUNT += 1

    now = time.time()
    if _MAINTENANCE_COUNT == 1:
        # first call after a reload
        _GAMETIME_MODULE.SERVER_START_TIME = now
        _GAMETIME_MODULE.SERVER_RUNTIME = ServerConfig.objects.conf("runtime", default=0.0)
    else:
        _GAMETIME_MODULE.SERVER_RUNTIME += 60.0
    # update game time and save it across reloads
    _GAMETIME_MODULE.SERVER_RUNTIME_LAST_UPDATED = now
    ServerConfig.objects.conf("runtime", _GAMETIME_MODULE.SERVER_RUNTIME)

    if _MAINTENANCE_COUNT % 300 == 0:
        # check cache size every 5 minutes
        _FLUSH_CACHE(_IDMAPPER_CACHE_MAXSIZE)
    if _MAINTENANCE_COUNT % 3600 == 0:
        # validate scripts every hour
        evennia.ScriptDB.objects.validate()
    if _MAINTENANCE_COUNT % 3700 == 0:
        # validate channels off-sync with scripts
        evennia.CHANNEL_HANDLER.update()

    # handle idle timeouts
    if _IDLE_TIMEOUT > 0:
        reason = _("idle timeout exceeded")
        for session in (sess for sess in SESSIONS.values()
                        if (now - sess.cmd_last) > _IDLE_TIMEOUT):
            if not session.account or not \
                    session.account.access(session.account, "noidletimeout", default=False):
                SESSIONS.disconnect(session, reason=reason)
Esempio n. 53
0
def apply_changes(request):
    """
    Apply the game world's data.
    """
    try:
        # rebuild the world
        build_all()

        # send client settings
        CLIENT_SETTINGS.reset()
        text = json.dumps({"settings": CLIENT_SETTINGS.all_values()})
        SESSIONS.announce_all(text)

        # reload
        SESSIONS.announce_all(" Server restarting ...")
        SESSIONS.server.shutdown(mode='reload')
    except Exception, e:
        message = "Can't build world: %s" % e
        logger.log_tracemsg(message)
        return render(request, 'fail.html', {"message": message})
Esempio n. 54
0
    def get(self, sessid=None):
        """
        Get the sessions linked to this object.

        Args:
            sessid (int, optional): Specify a given session by
                session id.

        Returns:
            sessions (list): A list of Session objects. If `sessid`
                is given, this is a list with one (or zero) elements.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        if sessid:
            return make_iter(_SESSIONS.session_from_player(self.player, sessid))
        else:
            return _SESSIONS.sessions_from_player(self.player)
Esempio n. 55
0
    def get_all_sessions(self):
        """
        Get all sessions connected to this player.

        Returns:
            sessions (list): All Sessions currently connected to this
                player.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        return _SESSIONS.sessions_from_player(self)
Esempio n. 56
0
 def at_repeat(self):
     """
     Called self.interval seconds to keep connection. We cannot use
     the IDLE command from inside the game since the system will
     not catch it (commands executed from the server side usually
     has no sessions). So we update the idle counter manually here
     instead. This keeps the bot getting hit by IDLE_TIMEOUT.
     """
     global _SESSIONS
     if not _SESSIONS:
         from evennia.server.sessionhandler import SESSIONS as _SESSIONS
     for session in _SESSIONS.sessions_from_player(self.player):
         session.update_session_counters(idle=True)
Esempio n. 57
0
def apply_changes(request):
    """
    Apply the game world's data.
    """
    try:
        # reload localized strings
        LOCALIZED_STRINGS_HANDLER.reload()

        # rebuild the world
        build_all()

        # send client settings
        client_settings = GAME_SETTINGS.get_client_settings()
        text = json.dumps({"settings": client_settings})
        SESSIONS.announce_all(text)

        # restart the server
        SESSIONS.announce_all(" Server restarting ...")
        SESSIONS.server.shutdown(mode='reload')
    except Exception, e:
        message = "Can't build world: %s" % e
        logger.log_tracemsg(message)
        return render(request, 'fail.html', {"message": message})
Esempio n. 58
0
    def get_session(self, sessid):
        """
        Retrieve given session.

        Args:
            sessid (int or list): A session id or list of such to retrieve.

        Returns:
            session (Session or list): One or more Sessions matching
                the given `sessid`s while also being connected to this
                Player.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        return _SESSIONS.session_from_player(self, sessid)
Esempio n. 59
0
    def __call__(self, fieldname):
        """
        Called by the save() mechanism when the given field has
        updated.

        Args:
            fieldname (str): The field to monitor

        """
        for sessid, oobtuples in self.subscribers.items():
            # oobtuples is a list [(oobfuncname, args, kwargs), ...],
            # a potential list of oob commands to call when this
            # field changes.
            sessid = SESSIONS.get(sessid)
            if sessid:
                for (oobfuncname, args, kwargs) in oobtuples:
                    OOB_HANDLER.execute_cmd(sessid, oobfuncname, fieldname, self.obj, *args, **kwargs)
Esempio n. 60
0
def verify_online_player(caller, value):
    """
    Example 'verify function' that matches player input to an online character
    or else rejects their input as invalid.

    Args:
        caller (obj): Player entering the form data.
        value (str): String player entered into the form, to be verified.

    Returns:
        matched_character (obj or False): dbref to a currently logged in
            character object - reference to the object will be stored in
            the form instead of a string. Returns False if no match is
            made.
    """
    # Get a list of sessions
    session_list = SESSIONS.get_sessions()
    char_list = []
    matched_character = None

    # Get a list of online characters
    for session in session_list:
        if not session.logged_in:
            # Skip over logged out characters
            continue
        # Append to our list of online characters otherwise
        char_list.append(session.get_puppet())

    # Match player input to a character name
    for character in char_list:
        if value.lower() == character.key.lower():
            matched_character = character

    # If input didn't match to a character
    if not matched_character:
        # Send the player an error message unique to this function
        caller.msg("No character matching '%s' is online." % value)
        # Returning False indicates the new value is not valid
        return False

    # Returning anything besides True or False will replace the player's input with the returned
    # value. In this case, the value becomes a reference to the character object. You can store data
    # besides strings and integers in the 'formdata' dictionary this way!
    return matched_character