Make scripts/objects lists use EvMore. Change EvMore to not justify by default.

This commit is contained in:
Griatch 2020-01-11 15:49:12 +01:00
parent b5aee2c41e
commit 69d85bd184
221 changed files with 2190 additions and 6810 deletions

View file

@ -87,9 +87,7 @@ class AMPClientFactory(protocol.ReconnectingClientFactory):
"""
logger.log_msg("Attempting to reconnect to Portal ...")
protocol.ReconnectingClientFactory.clientConnectionFailed(
self, connector, reason
)
protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
class AMPServerClientProtocol(amp.AMPMultiConnectionProtocol):
@ -135,9 +133,9 @@ class AMPServerClientProtocol(amp.AMPMultiConnectionProtocol):
"""
# print("server data_to_portal: {}, {}, {}".format(command, sessid, kwargs))
return self.callRemote(
command, packed_data=amp.dumps((sessid, kwargs))
).addErrback(self.errback, command.key)
return self.callRemote(command, packed_data=amp.dumps((sessid, kwargs))).addErrback(
self.errback, command.key
)
def send_MsgServer2Portal(self, session, **kwargs):
"""

View file

@ -231,9 +231,7 @@ def node_game_index_fields(wizard, status=None):
options = ["pre-alpha", "alpha", "beta", "launched"]
wizard.display(text)
wizard.game_index_listing["game_status"] = wizard.ask_choice(
"Select one: ", options
)
wizard.game_index_listing["game_status"] = wizard.ask_choice("Select one: ", options)
# short desc
@ -252,9 +250,7 @@ def node_game_index_fields(wizard, status=None):
tmax = 255
tlen = len(inp)
if tlen > 255:
print(
f"The short desc must be shorter than {tmax} characters (was {tlen})."
)
print(f"The short desc must be shorter than {tmax} characters (was {tlen}).")
wizard.ask_continue()
return False
return True
@ -278,9 +274,7 @@ def node_game_index_fields(wizard, status=None):
"""
wizard.display(text)
wizard.game_index_listing["long_description"] = wizard.ask_input(
default=long_default
)
wizard.game_index_listing["long_description"] = wizard.ask_input(default=long_default)
# listing contact
@ -322,9 +316,7 @@ def node_game_index_fields(wizard, status=None):
"""
wizard.display(text)
wizard.game_index_listing["telnet_hostname"] = wizard.ask_input(
default=hostname_default
)
wizard.game_index_listing["telnet_hostname"] = wizard.ask_input(default=hostname_default)
# telnet port
@ -356,9 +348,7 @@ def node_game_index_fields(wizard, status=None):
"""
wizard.display(text)
wizard.game_index_listing["game_website"] = wizard.ask_input(
default=website_default
)
wizard.game_index_listing["game_website"] = wizard.ask_input(default=website_default)
# webclient
@ -376,9 +366,7 @@ def node_game_index_fields(wizard, status=None):
"""
wizard.display(text)
wizard.game_index_listing["web_client_url"] = wizard.ask_input(
default=webclient_default
)
wizard.game_index_listing["web_client_url"] = wizard.ask_input(default=webclient_default)
if not (
wizard.game_index_listing.get("web_client_url")
@ -449,9 +437,7 @@ def _save_changes(wizard):
" pass"
)
connect_settings_file = path.join(
settings.GAME_DIR, "server", "conf", "connection_settings.py"
)
connect_settings_file = path.join(settings.GAME_DIR, "server", "conf", "connection_settings.py")
with open(connect_settings_file, "w") as f:
f.write(
"# This file is auto-generated by the `evennia connections` wizard.\n"
@ -475,9 +461,8 @@ def node_view_and_apply_settings(wizard):
if wizard.game_index_listing != settings.GAME_INDEX_LISTING:
game_index_txt = "No changes to save for Game Index."
else:
game_index_txt = (
"GAME_INDEX_ENABLED = True\n"
"GAME_INDEX_LISTING = \\\n" + pp.pformat(wizard.game_index_listing)
game_index_txt = "GAME_INDEX_ENABLED = True\n" "GAME_INDEX_LISTING = \\\n" + pp.pformat(
wizard.game_index_listing
)
saves = True

View file

@ -27,21 +27,14 @@ def check_errors(settings):
raise DeprecationWarning(deprstring % ("CMDSET_DEFAULT", "CMDSET_CHARACTER"))
if hasattr(settings, "CMDSET_OOC"):
raise DeprecationWarning(deprstring % ("CMDSET_OOC", "CMDSET_ACCOUNT"))
if settings.WEBSERVER_ENABLED and not isinstance(
settings.WEBSERVER_PORTS[0], tuple
):
if settings.WEBSERVER_ENABLED and not isinstance(settings.WEBSERVER_PORTS[0], tuple):
raise DeprecationWarning(
"settings.WEBSERVER_PORTS must be on the form "
"[(proxyport, serverport), ...]"
"settings.WEBSERVER_PORTS must be on the form " "[(proxyport, serverport), ...]"
)
if hasattr(settings, "BASE_COMM_TYPECLASS"):
raise DeprecationWarning(
deprstring % ("BASE_COMM_TYPECLASS", "BASE_CHANNEL_TYPECLASS")
)
raise DeprecationWarning(deprstring % ("BASE_COMM_TYPECLASS", "BASE_CHANNEL_TYPECLASS"))
if hasattr(settings, "COMM_TYPECLASS_PATHS"):
raise DeprecationWarning(
deprstring % ("COMM_TYPECLASS_PATHS", "CHANNEL_TYPECLASS_PATHS")
)
raise DeprecationWarning(deprstring % ("COMM_TYPECLASS_PATHS", "CHANNEL_TYPECLASS_PATHS"))
if hasattr(settings, "CHARACTER_DEFAULT_HOME"):
raise DeprecationWarning(
"settings.CHARACTER_DEFAULT_HOME should be renamed to "
@ -49,8 +42,7 @@ def check_errors(settings):
"(see evennia/settings_default.py)."
)
deprstring = (
"settings.%s is now merged into settings.TYPECLASS_PATHS. "
"Update your settings file."
"settings.%s is now merged into settings.TYPECLASS_PATHS. " "Update your settings file."
)
if hasattr(settings, "OBJECT_TYPECLASS_PATHS"):
raise DeprecationWarning(deprstring % "OBJECT_TYPECLASS_PATHS")

View file

@ -33,9 +33,7 @@ SIG = signal.SIGINT
CTRL_C_EVENT = 0 # Windows SIGINT-like signal
# Set up the main python paths to Evennia
EVENNIA_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
EVENNIA_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import evennia # noqa
@ -537,19 +535,11 @@ def _get_twistd_cmdline(pprofiler, sprofiler):
if pprofiler:
portal_cmd.extend(
[
"--savestats",
"--profiler=cprofile",
"--profile={}".format(PPROFILER_LOGFILE),
]
["--savestats", "--profiler=cprofile", "--profile={}".format(PPROFILER_LOGFILE)]
)
if sprofiler:
server_cmd.extend(
[
"--savestats",
"--profiler=cprofile",
"--profile={}".format(SPROFILER_LOGFILE),
]
["--savestats", "--profiler=cprofile", "--profile={}".format(SPROFILER_LOGFILE)]
)
return portal_cmd, server_cmd
@ -696,13 +686,9 @@ def query_status(callback=None):
print(
"Portal: {}{}\nServer: {}{}".format(
wmap[pstatus],
" (pid {})".format(get_pid(PORTAL_PIDFILE, ppid))
if pstatus
else "",
" (pid {})".format(get_pid(PORTAL_PIDFILE, ppid)) if pstatus else "",
wmap[sstatus],
" (pid {})".format(get_pid(SERVER_PIDFILE, spid))
if sstatus
else "",
" (pid {})".format(get_pid(SERVER_PIDFILE, spid)) if sstatus else "",
)
)
_reactor_stop()
@ -726,12 +712,7 @@ def wait_for_status_reply(callback):
def wait_for_status(
portal_running=True,
server_running=True,
callback=None,
errback=None,
rate=0.5,
retries=20,
portal_running=True, server_running=True, callback=None, errback=None, rate=0.5, retries=20
):
"""
Repeat the status ping until the desired state combination is achieved.
@ -852,22 +833,12 @@ def start_evennia(pprofiler=False, sprofiler=False):
def _portal_running(response):
prun, srun, ppid, spid, _, _ = _parse_status(response)
print(
"Portal is already running as process {pid}. Not restarted.".format(
pid=ppid
)
)
print("Portal is already running as process {pid}. Not restarted.".format(pid=ppid))
if srun:
print(
"Server is already running as process {pid}. Not restarted.".format(
pid=spid
)
)
print("Server is already running as process {pid}. Not restarted.".format(pid=spid))
_reactor_stop()
else:
print(
"Server starting {}...".format("(under cProfile)" if sprofiler else "")
)
print("Server starting {}...".format("(under cProfile)" if sprofiler else ""))
send_instruction(SSTART, server_cmd, _server_started, _fail)
def _portal_not_running(fail):
@ -876,9 +847,7 @@ def start_evennia(pprofiler=False, sprofiler=False):
if _is_windows():
# Windows requires special care
create_no_window = 0x08000000
Popen(
portal_cmd, env=getenv(), bufsize=-1, creationflags=create_no_window
)
Popen(portal_cmd, env=getenv(), bufsize=-1, creationflags=create_no_window)
else:
Popen(portal_cmd, env=getenv(), bufsize=-1)
except Exception as e:
@ -1057,12 +1026,7 @@ def start_portal_interactive():
if _is_windows():
# Windows requires special care
create_no_window = 0x08000000
Popen(
server_twistd_cmd,
env=getenv(),
bufsize=-1,
creationflags=create_no_window,
)
Popen(server_twistd_cmd, env=getenv(), bufsize=-1, creationflags=create_no_window)
else:
Popen(server_twistd_cmd, env=getenv(), bufsize=-1)
@ -1075,9 +1039,7 @@ def start_portal_interactive():
print("... Portal stopped (leaving interactive mode).")
def _portal_running(response):
print(
"Evennia must be shut down completely before running Portal in interactive mode."
)
print("Evennia must be shut down completely before running Portal in interactive mode.")
_reactor_stop()
send_instruction(PSTATUS, None, _portal_running, _iportal)
@ -1121,9 +1083,7 @@ def stop_server_only(when_stopped=None, interactive=False):
def _portal_not_running(fail):
print("Evennia is not running.")
if interactive:
print(
"Start Evennia normally first, then use `istart` to switch to interactive mode."
)
print("Start Evennia normally first, then use `istart` to switch to interactive mode.")
_reactor_stop()
send_instruction(PSTATUS, None, _portal_running, _portal_not_running)
@ -1247,9 +1207,7 @@ def tail_log_files(filename1, filename2, start_lines1=20, start_lines2=20, rate=
sys.stdout.flush()
# set up the next poll
reactor.callLater(
rate, _tail_file, filename, file_size, line_count, max_lines=100
)
reactor.callLater(rate, _tail_file, filename, file_size, line_count, max_lines=100)
reactor.callLater(0, _tail_file, filename1, 0, 0, max_lines=start_lines1)
reactor.callLater(0, _tail_file, filename2, 0, 0, max_lines=start_lines2)
@ -1277,12 +1235,7 @@ def evennia_version():
pass
try:
rev = (
check_output(
"git rev-parse --short HEAD",
shell=True,
cwd=EVENNIA_ROOT,
stderr=STDOUT,
)
check_output("git rev-parse --short HEAD", shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT)
.strip()
.decode()
)
@ -1318,9 +1271,7 @@ def check_main_evennia_dependencies():
tversion = twisted.version.short()
if LooseVersion(tversion) < LooseVersion(TWISTED_MIN):
print(
ERROR_TWISTED_VERSION.format(tversion=tversion, twisted_min=TWISTED_MIN)
)
print(ERROR_TWISTED_VERSION.format(tversion=tversion, twisted_min=TWISTED_MIN))
error = True
except ImportError:
print(ERROR_NOTWISTED)
@ -1331,15 +1282,9 @@ def check_main_evennia_dependencies():
# only the main version (1.5, not 1.5.4.0)
dversion_main = ".".join(dversion.split(".")[:3])
if LooseVersion(dversion) < LooseVersion(DJANGO_MIN):
print(
ERROR_DJANGO_MIN.format(dversion=dversion_main, django_min=DJANGO_MIN)
)
print(ERROR_DJANGO_MIN.format(dversion=dversion_main, django_min=DJANGO_MIN))
error = True
elif (
LooseVersion(DJANGO_MIN)
<= LooseVersion(dversion)
< LooseVersion(DJANGO_REC)
):
elif LooseVersion(DJANGO_MIN) <= LooseVersion(dversion) < LooseVersion(DJANGO_REC):
print(NOTE_DJANGO_MIN.format(dversion=dversion_main, django_rec=DJANGO_REC))
elif LooseVersion(DJANGO_REC) < LooseVersion(dversion_main):
print(NOTE_DJANGO_NEW.format(dversion=dversion_main, django_rec=DJANGO_REC))
@ -1422,12 +1367,7 @@ def create_settings_file(init=True, secret_settings=False):
if not init:
# if not --init mode, settings file may already exist from before
if os.path.exists(settings_path):
inp = eval(
input(
"%s already exists. Do you want to reset it? y/[N]> "
% settings_path
)
)
inp = eval(input("%s already exists. Do you want to reset it? y/[N]> " % settings_path))
if not inp.lower() == "y":
print("Aborted.")
return
@ -1439,9 +1379,7 @@ def create_settings_file(init=True, secret_settings=False):
EVENNIA_TEMPLATE, "server", "conf", "secret_settings.py"
)
else:
default_settings_path = os.path.join(
EVENNIA_TEMPLATE, "server", "conf", "settings.py"
)
default_settings_path = os.path.join(EVENNIA_TEMPLATE, "server", "conf", "settings.py")
shutil.copy(default_settings_path, settings_path)
with open(settings_path, "r") as f:
@ -1528,9 +1466,7 @@ def check_database():
other = other_superuser[0]
other_id = other.id
other_key = other.username
print(
WARNING_MOVING_SUPERUSER.format(other_key=other_key, other_id=other_id)
)
print(WARNING_MOVING_SUPERUSER.format(other_key=other_key, other_id=other_id))
res = ""
while res.upper() != "Y":
# ask for permission
@ -1836,8 +1772,7 @@ def init_game_directory(path, check_db=True, need_gamedir=True):
# verify existence of log file dir (this can be missing e.g.
# if the game dir itself was cloned since log files are in .gitignore)
logdirs = [
logfile.rsplit(os.path.sep, 1)
for logfile in (SERVER_LOGFILE, PORTAL_LOGFILE, HTTP_LOGFILE)
logfile.rsplit(os.path.sep, 1) for logfile in (SERVER_LOGFILE, PORTAL_LOGFILE, HTTP_LOGFILE)
]
if not all(os.path.isdir(pathtup[0]) for pathtup in logdirs):
errstr = "\n ".join(
@ -1884,13 +1819,7 @@ def init_game_directory(path, check_db=True, need_gamedir=True):
# of its executable from 'twistd.py' to 'twistd.exe'.
twistd_path = os.path.abspath(
os.path.join(
twistd_dir,
os.pardir,
os.pardir,
os.pardir,
os.pardir,
"scripts",
"twistd.exe",
twistd_dir, os.pardir, os.pardir, os.pardir, os.pardir, "scripts", "twistd.exe"
)
)
@ -1962,9 +1891,7 @@ def list_settings(keys):
# a specific key
table = evtable.EvTable(width=131)
keys = [key.upper() for key in keys]
confs = dict(
(key, var) for key, var in evsettings.__dict__.items() if key in keys
)
confs = dict((key, var) for key, var in evsettings.__dict__.items() if key in keys)
for key, val in confs.items():
table.add_row(key, str(val))
print(table)
@ -2041,8 +1968,7 @@ def run_menu():
elif inp == 12:
print("Running 'evennia --settings settings.py test .' ...")
Popen(
[sys.executable, __file__, "--settings", "settings.py", "test", "."],
env=getenv(),
[sys.executable, __file__, "--settings", "settings.py", "test", "."], env=getenv()
).wait()
elif inp == 13:
print("Running 'evennia test evennia' ...")
@ -2060,9 +1986,7 @@ def main():
"""
# set up argument parser
parser = ArgumentParser(
description=CMDLINE_HELP, formatter_class=argparse.RawTextHelpFormatter
)
parser = ArgumentParser(description=CMDLINE_HELP, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"--gamedir",
nargs=1,
@ -2217,17 +2141,13 @@ def main():
settings_path = os.path.join(CONFDIR, "secret_settings.py")
if not os.path.exists(settings_path):
create_settings_file(init=False, secret_settings=True)
print(
f" ... Created missing secret_settings.py file as {settings_path}."
)
print(f" ... Created missing secret_settings.py file as {settings_path}.")
created = True
if created:
print(RECREATED_MISSING)
else:
print(
" ... No missing resources to create/init. You are good to go."
)
print(" ... No missing resources to create/init. You are good to go.")
except IOError:
print(ERROR_INITMISSING)
sys.exit()

View file

@ -269,18 +269,10 @@ def main():
help="Portal in interactive mode",
)
parser.add_argument(
"--pserver",
action="store_true",
dest="pserver",
default=False,
help="Profile Server",
"--pserver", action="store_true", dest="pserver", default=False, help="Profile Server"
)
parser.add_argument(
"--pportal",
action="store_true",
dest="pportal",
default=False,
help="Profile Portal",
"--pportal", action="store_true", dest="pportal", default=False, help="Profile Portal"
)
parser.add_argument(
"--nologcycle",
@ -341,24 +333,15 @@ def main():
# Profiling settings (read file from python shell e.g with
# p = pstats.Stats('server.prof')
pserver_argv = [
"--savestats",
"--profiler=cprofile",
"--profile=%s" % SPROFILER_LOGFILE,
]
pportal_argv = [
"--savestats",
"--profiler=cprofile",
"--profile=%s" % PPROFILER_LOGFILE,
]
pserver_argv = ["--savestats", "--profiler=cprofile", "--profile=%s" % SPROFILER_LOGFILE]
pportal_argv = ["--savestats", "--profiler=cprofile", "--profile=%s" % PPROFILER_LOGFILE]
# Server
pid = get_pid(SERVER_PIDFILE)
if pid and not args.noserver:
print(
"\nEvennia Server is already running as process %(pid)s. Not restarted."
% {"pid": pid}
"\nEvennia Server is already running as process %(pid)s. Not restarted." % {"pid": pid}
)
args.noserver = True
if args.noserver:
@ -382,8 +365,7 @@ def main():
pid = get_pid(PORTAL_PIDFILE)
if pid and not args.noportal:
print(
"\nEvennia Portal is already running as process %(pid)s. Not restarted."
% {"pid": pid}
"\nEvennia Portal is already running as process %(pid)s. Not restarted." % {"pid": pid}
)
args.noportal = True
if args.noportal:
@ -399,9 +381,7 @@ def main():
cycle_logfile(PORTAL_LOGFILE)
cycle_logfile(HTTP_LOGFILE)
set_restart_mode(PORTAL_RESTART, False)
print(
"\nStarting Evennia Portal in Daemon mode (output to portal logfile)."
)
print("\nStarting Evennia Portal in Daemon mode (output to portal logfile).")
if args.pportal:
portal_argv.extend(pportal_argv)
print("\nRunning Evennia Portal under cProfile.")

View file

@ -56,9 +56,7 @@ class EvenniaGameIndexClient(object):
status_code, response_body = yield self._form_and_send_request()
if status_code == 200:
if not self.logged_first_connect:
logger.log_infomsg(
"Successfully sent game details to Evennia Game Index."
)
logger.log_infomsg("Successfully sent game details to Evennia Game Index.")
self.logged_first_connect = True
return
# At this point, either EGD is having issues or the payload we sent

View file

@ -53,7 +53,6 @@ class EvenniaGameIndexService(Service):
Stop the service so we're not wasting resources.
"""
logger.log_infomsg(
"Shutting down Evennia Game Index client service due to "
"invalid configuration."
"Shutting down Evennia Game Index client service due to " "invalid configuration."
)
self.stopService()

View file

@ -87,9 +87,7 @@ def create_objects():
# Create the in-game god-character for account #1 and set
# it to exist in Limbo.
character_typeclass = settings.BASE_CHARACTER_TYPECLASS
god_character = create.create_object(
character_typeclass, key=god_account.username, nohome=True
)
god_character = create.create_object(character_typeclass, key=god_account.username, nohome=True)
god_character.id = 1
god_character.save()
@ -212,13 +210,7 @@ def handle_setup(last_step):
last_step = last_step or 0
# setting up the list of functions to run
setup_queue = [
create_objects,
create_channels,
at_initial_setup,
collectstatic,
reset_server,
]
setup_queue = [create_objects, create_channels, at_initial_setup, collectstatic, reset_server]
# step through queue, from last completed function
for num, setup_func in enumerate(setup_queue[last_step:]):

View file

@ -185,9 +185,7 @@ def client_options(session, *args, **kwargs):
old_flags = session.protocol_flags
if not kwargs or kwargs.get("get", False):
# return current settings
options = dict(
(key, old_flags[key]) for key in old_flags if key.upper() in _CLIENT_OPTIONS
)
options = dict((key, old_flags[key]) for key in old_flags if key.upper() in _CLIENT_OPTIONS)
session.msg(client_options=options)
return
@ -257,9 +255,7 @@ def client_options(session, *args, **kwargs):
session.protocol_flags.update(flags)
# we must update the protocol flags on the portal session copy as well
session.sessionhandler.session_portal_partial_sync(
{session.sessid: {"protocol_flags": flags}}
)
session.sessionhandler.session_portal_partial_sync({session.sessid: {"protocol_flags": flags}})
def get_client_options(session, *args, **kwargs):
@ -276,8 +272,7 @@ def get_inputfuncs(session, *args, **kwargs):
So we get it from the sessionhandler.
"""
inputfuncsdict = dict(
(key, func.__doc__)
for key, func in session.sessionhandler.get_inputfuncs().items()
(key, func.__doc__) for key, func in session.sessionhandler.get_inputfuncs().items()
)
session.msg(get_inputfuncs=inputfuncsdict)

View file

@ -15,10 +15,7 @@ class Migration(migrations.Migration):
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
verbose_name="ID", serialize=False, auto_created=True, primary_key=True
),
),
("db_key", models.CharField(unique=True, max_length=64)),

View file

@ -13,9 +13,7 @@ def forwards(apps, schema_editor):
ServerConfig = apps.get_model("server", "ServerConfig")
for conf in ServerConfig.objects.all():
# picklefield requires base64 encoding
value = loads(
to_bytes(conf.db_value), encoding="bytes"
) # py2->py3 byte encoding
value = loads(to_bytes(conf.db_value), encoding="bytes") # py2->py3 byte encoding
conf.db_value = b64encode(dumps(deepcopy(value), protocol=4)).decode()
conf.save(update_fields=["db_value"])

View file

@ -44,9 +44,7 @@ SRESET = chr(19) # server shutdown in reset mode
NUL = b"\x00"
NULNUL = b"\x00\x00"
AMP_MAXLEN = (
amp.MAX_VALUE_LENGTH
) # max allowed data length in AMP protocol (cannot be changed)
AMP_MAXLEN = amp.MAX_VALUE_LENGTH # max allowed data length in AMP protocol (cannot be changed)
# buffers
_SENDBATCH = defaultdict(list)
@ -316,9 +314,7 @@ class AMPMultiConnectionProtocol(amp.AMP):
try:
super(AMPMultiConnectionProtocol, self).dataReceived(data)
except KeyError:
_get_logger().log_trace(
"Discarded incoming partial data: {}".format(to_str(data))
)
_get_logger().log_trace("Discarded incoming partial data: {}".format(to_str(data)))
elif self.multibatches:
# invalid AMP, but we have a pending multi-batch that is not yet complete
if data[-2:] == NULNUL:
@ -327,17 +323,12 @@ class AMPMultiConnectionProtocol(amp.AMP):
try:
super(AMPMultiConnectionProtocol, self).dataReceived(data)
except KeyError:
_get_logger().log_trace(
"Discarded incoming multi-batch data:".format(to_str(data))
)
_get_logger().log_trace("Discarded incoming multi-batch data:".format(to_str(data)))
else:
# not an AMP communication, return warning
self.transport.write(_HTTP_WARNING)
self.transport.loseConnection()
print(
"HTTP received (the AMP port should not receive http, only AMP!) %s"
% data
)
print("HTTP received (the AMP port should not receive http, only AMP!) %s" % data)
def makeConnection(self, transport):
"""
@ -429,9 +420,7 @@ class AMPMultiConnectionProtocol(amp.AMP):
for protcl in self.factory.broadcasts:
deferreds.append(
protcl.callRemote(command, **kwargs).addErrback(
self.errback, command.key
)
protcl.callRemote(command, **kwargs).addErrback(self.errback, command.key)
)
return DeferredList(deferreds)

View file

@ -98,9 +98,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
if self.factory.launcher_connection == self:
self.factory.launcher_connection = None
callback, args, kwargs = self.factory.disconnect_callbacks.pop(
self, (None, None, None)
)
callback, args, kwargs = self.factory.disconnect_callbacks.pop(self, (None, None, None))
if callback:
try:
callback(*args, **kwargs)
@ -117,21 +115,13 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
"""
server_connected = bool(
self.factory.server_connection
and self.factory.server_connection.transport.connected
self.factory.server_connection and self.factory.server_connection.transport.connected
)
portal_info_dict = self.factory.portal.get_info_dict()
server_info_dict = self.factory.portal.server_info_dict
server_pid = self.factory.portal.server_process_id
portal_pid = os.getpid()
return (
True,
server_connected,
portal_pid,
server_pid,
portal_info_dict,
server_info_dict,
)
return (True, server_connected, portal_pid, server_pid, portal_info_dict, server_info_dict)
def data_to_server(self, command, sessid, **kwargs):
"""
@ -157,9 +147,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
).addErrback(self.errback, command.key)
else:
# if no server connection is available, broadcast
return self.broadcast(
command, sessid, packed_data=amp.dumps((sessid, kwargs))
)
return self.broadcast(command, sessid, packed_data=amp.dumps((sessid, kwargs)))
def start_server(self, server_twistd_cmd):
"""
@ -192,11 +180,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
else:
process = Popen(
server_twistd_cmd,
env=getenv(),
bufsize=-1,
stdout=logfile,
stderr=STDOUT,
server_twistd_cmd, env=getenv(), bufsize=-1, stdout=logfile, stderr=STDOUT
)
except Exception:
logger.log_trace()
@ -345,9 +329,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
elif operation == amp.SRELOAD: # reload server #14
if server_connected:
# We let the launcher restart us once they get the signal
self.factory.server_connection.wait_for_disconnect(
self.send_Status2Launcher
)
self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher)
self.stop_server(mode="reload")
else:
self.wait_for_server_connect(self.send_Status2Launcher)
@ -355,9 +337,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
elif operation == amp.SRESET: # reload server #19
if server_connected:
self.factory.server_connection.wait_for_disconnect(
self.send_Status2Launcher
)
self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher)
self.stop_server(mode="reset")
else:
self.wait_for_server_connect(self.send_Status2Launcher)
@ -365,16 +345,12 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
elif operation == amp.SSHUTD: # server-only shutdown #17
if server_connected:
self.factory.server_connection.wait_for_disconnect(
self.send_Status2Launcher
)
self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher)
self.stop_server(mode="shutdown")
elif operation == amp.PSHUTD: # portal + server shutdown #16
if server_connected:
self.factory.server_connection.wait_for_disconnect(
self.factory.portal.shutdown
)
self.factory.server_connection.wait_for_disconnect(self.factory.portal.shutdown)
else:
self.factory.portal.shutdown()
@ -429,17 +405,13 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
# a session has authenticated; sync it.
session = portal_sessionhandler.get(sessid)
if session:
portal_sessionhandler.server_logged_in(
session, kwargs.get("sessiondata")
)
portal_sessionhandler.server_logged_in(session, kwargs.get("sessiondata"))
elif operation == amp.SDISCONN: # server_session_disconnect
# the server is ordering to disconnect the session
session = portal_sessionhandler.get(sessid)
if session:
portal_sessionhandler.server_disconnect(
session, reason=kwargs.get("reason")
)
portal_sessionhandler.server_disconnect(session, reason=kwargs.get("reason"))
elif operation == amp.SDISCONNALL: # server_session_disconnect_all
# server orders all sessions to disconnect
@ -461,9 +433,7 @@ class AMPServerProtocol(amp.AMPMultiConnectionProtocol):
self.stop_server(mode="shutdown")
elif operation == amp.PSHUTD: # full server+server shutdown
self.factory.server_connection.wait_for_disconnect(
self.factory.portal.shutdown
)
self.factory.server_connection.wait_for_disconnect(self.factory.portal.shutdown)
self.stop_server(mode="shutdown")
elif operation == amp.PSYNC: # portal sync

View file

@ -15,11 +15,7 @@ from django.conf import settings
from evennia.server.session import Session
from evennia.utils import get_evennia_version
from evennia.utils.logger import log_info, log_err
from autobahn.twisted.websocket import (
WebSocketClientProtocol,
WebSocketClientFactory,
connectWS,
)
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory, connectWS
# There is only one at this time
GRAPEVINE_URI = "wss://grapevine.haus/socket"
@ -34,9 +30,7 @@ GRAPEVINE_AUTH_ERROR = 4000
GRAPEVINE_HEARTBEAT_FAILURE = 4001
class RestartingWebsocketServerFactory(
WebSocketClientFactory, protocol.ReconnectingClientFactory
):
class RestartingWebsocketServerFactory(WebSocketClientFactory, protocol.ReconnectingClientFactory):
"""
A variant of the websocket-factory that auto-reconnects.

View file

@ -87,22 +87,16 @@ IRC_COLOR_MAP = dict(
)
)
# ansi->irc
RE_ANSI_COLOR = re.compile(
r"|".join([re.escape(key) for key in IRC_COLOR_MAP.keys()]), re.DOTALL
)
RE_ANSI_COLOR = re.compile(r"|".join([re.escape(key) for key in IRC_COLOR_MAP.keys()]), re.DOTALL)
RE_MXP = re.compile(r"\|lc(.*?)\|lt(.*?)\|le", re.DOTALL)
RE_ANSI_ESCAPES = re.compile(r"(%s)" % "|".join(("{{", "%%", "\\\\")), re.DOTALL)
# irc->ansi
_CLR_LIST = [
re.escape(val)
for val in sorted(IRC_COLOR_MAP.values(), key=len, reverse=True)
if val.strip()
re.escape(val) for val in sorted(IRC_COLOR_MAP.values(), key=len, reverse=True) if val.strip()
]
_CLR_LIST = _CLR_LIST[-2:] + _CLR_LIST[:-2]
RE_IRC_COLOR = re.compile(r"|".join(_CLR_LIST), re.DOTALL)
ANSI_COLOR_MAP = dict(
(tup[1], tup[0]) for tup in IRC_COLOR_MAP.items() if tup[1].strip()
)
ANSI_COLOR_MAP = dict((tup[1], tup[0]) for tup in IRC_COLOR_MAP.items() if tup[1].strip())
def parse_ansi_to_irc(string):
@ -262,11 +256,7 @@ class IRCBot(irc.IRCClient, Session):
if channel != self.channel.lower():
return
self.data_in(
text="",
type="nicklist",
user="server",
channel=channel,
nicklist=self.nicklist,
text="", type="nicklist", user="server", channel=channel, nicklist=self.nicklist
)
self.nicklist = []
@ -279,9 +269,7 @@ class IRCBot(irc.IRCClient, Session):
time (float): Ping time in secs.
"""
self.data_in(
text="", type="ping", user="server", channel=self.channel, timing=time
)
self.data_in(text="", type="ping", user="server", channel=self.channel, timing=time)
def data_in(self, text=None, **kwargs):
"""
@ -484,9 +472,7 @@ class IRCBotFactory(protocol.ReconnectingClientFactory):
self.network, int(self.port), self, ssl.ClientContextFactory()
)
except ImportError:
logger.log_err(
"To use SSL, the PyOpenSSL module must be installed."
)
logger.log_err("To use SSL, the PyOpenSSL module must be installed.")
else:
service = internet.TCPClient(self.network, int(self.port), self)
self.sessionhandler.portal.services.addService(service)

View file

@ -18,9 +18,7 @@ MSSP_VAR = b"\x01"
MSSP_VAL = b"\x02"
# try to get the customized mssp info, if it exists.
MSSPTable_CUSTOM = utils.variable_from_module(
settings.MSSP_META_MODULE, "MSSPTable", default={}
)
MSSPTable_CUSTOM = utils.variable_from_module(settings.MSSP_META_MODULE, "MSSPTable", default={})
class Mssp(object):
@ -121,18 +119,10 @@ class Mssp(object):
if utils.is_iter(value):
for partval in value:
varlist += (
MSSP_VAR
+ bytes(variable, "utf-8")
+ MSSP_VAL
+ bytes(partval, "utf-8")
MSSP_VAR + bytes(variable, "utf-8") + MSSP_VAL + bytes(partval, "utf-8")
)
else:
varlist += (
MSSP_VAR
+ bytes(variable, "utf-8")
+ MSSP_VAL
+ bytes(value, "utf-8")
)
varlist += MSSP_VAR + bytes(variable, "utf-8") + MSSP_VAL + bytes(value, "utf-8")
# send to crawler by subnegotiation
self.protocol.requestNegotiation(MSSP, varlist)

View file

@ -42,9 +42,7 @@ class Naws(object):
self.protocol.protocol_flags["SCREENWIDTH"] = {
0: DEFAULT_WIDTH
} # windowID (0 is root):width
self.protocol.protocol_flags["SCREENHEIGHT"] = {
0: DEFAULT_HEIGHT
} # windowID:width
self.protocol.protocol_flags["SCREENHEIGHT"] = {0: DEFAULT_HEIGHT} # windowID:width
self.protocol.negotiationMap[NAWS] = self.negotiate_sizes
self.protocol.do(NAWS).addCallbacks(self.do_naws, self.no_naws)
@ -80,10 +78,6 @@ class Naws(object):
if len(options) == 4:
# NAWS is negotiated with 16bit words
width = options[0] + options[1]
self.protocol.protocol_flags["SCREENWIDTH"][0] = int(
codecs_encode(width, "hex"), 16
)
self.protocol.protocol_flags["SCREENWIDTH"][0] = int(codecs_encode(width, "hex"), 16)
height = options[2] + options[3]
self.protocol.protocol_flags["SCREENHEIGHT"][0] = int(
codecs_encode(height, "hex"), 16
)
self.protocol.protocol_flags["SCREENHEIGHT"][0] = int(codecs_encode(height, "hex"), 16)

View file

@ -63,22 +63,16 @@ TELNET_INTERFACES = ["127.0.0.1"] if LOCKDOWN_MODE else settings.TELNET_INTERFAC
SSL_INTERFACES = ["127.0.0.1"] if LOCKDOWN_MODE else settings.SSL_INTERFACES
SSH_INTERFACES = ["127.0.0.1"] if LOCKDOWN_MODE else settings.SSH_INTERFACES
WEBSERVER_INTERFACES = ["127.0.0.1"] if LOCKDOWN_MODE else settings.WEBSERVER_INTERFACES
WEBSOCKET_CLIENT_INTERFACE = (
"127.0.0.1" if LOCKDOWN_MODE else settings.WEBSOCKET_CLIENT_INTERFACE
)
WEBSOCKET_CLIENT_INTERFACE = "127.0.0.1" if LOCKDOWN_MODE else settings.WEBSOCKET_CLIENT_INTERFACE
WEBSOCKET_CLIENT_URL = settings.WEBSOCKET_CLIENT_URL
TELNET_ENABLED = settings.TELNET_ENABLED and TELNET_PORTS and TELNET_INTERFACES
SSL_ENABLED = settings.SSL_ENABLED and SSL_PORTS and SSL_INTERFACES
SSH_ENABLED = settings.SSH_ENABLED and SSH_PORTS and SSH_INTERFACES
WEBSERVER_ENABLED = (
settings.WEBSERVER_ENABLED and WEBSERVER_PORTS and WEBSERVER_INTERFACES
)
WEBSERVER_ENABLED = settings.WEBSERVER_ENABLED and WEBSERVER_PORTS and WEBSERVER_INTERFACES
WEBCLIENT_ENABLED = settings.WEBCLIENT_ENABLED
WEBSOCKET_CLIENT_ENABLED = (
settings.WEBSOCKET_CLIENT_ENABLED
and WEBSOCKET_CLIENT_PORT
and WEBSOCKET_CLIENT_INTERFACE
settings.WEBSOCKET_CLIENT_ENABLED and WEBSOCKET_CLIENT_PORT and WEBSOCKET_CLIENT_INTERFACE
)
AMP_HOST = settings.AMP_HOST
@ -146,11 +140,7 @@ class Portal(object):
# set a callback if the server is killed abruptly,
# by Ctrl-C, reboot etc.
reactor.addSystemEventTrigger(
"before",
"shutdown",
self.shutdown,
_reactor_stopping=True,
_stop_server=True,
"before", "shutdown", self.shutdown, _reactor_stopping=True, _stop_server=True
)
def _get_backup_server_twistd_cmd(self):
@ -163,9 +153,7 @@ class Portal(object):
"""
server_twistd_cmd = [
"twistd",
"--python={}".format(
os.path.join(dirname(dirname(abspath(__file__))), "server.py")
),
"--python={}".format(os.path.join(dirname(dirname(abspath(__file__))), "server.py")),
]
if os.name != "nt":
gamedir = os.getcwd()
@ -225,8 +213,7 @@ application = service.Application("Portal")
if "--nodaemon" not in sys.argv:
logfile = logger.WeeklyLogFile(
os.path.basename(settings.PORTAL_LOG_FILE),
os.path.dirname(settings.PORTAL_LOG_FILE),
os.path.basename(settings.PORTAL_LOG_FILE), os.path.dirname(settings.PORTAL_LOG_FILE)
)
application.setComponent(ILogObserver, logger.PortalLogObserver(logfile).emit)
@ -308,8 +295,7 @@ if SSL_ENABLED:
INFO_DICT["telnet_ssl"].append("telnet+ssl%s: %s" % (ifacestr, port))
else:
INFO_DICT["telnet_ssl"].append(
"telnet+ssl%s: %s (deactivated - keys/cert unset)"
% (ifacestr, port)
"telnet+ssl%s: %s (deactivated - keys/cert unset)" % (ifacestr, port)
)
@ -371,10 +357,7 @@ if WEBSERVER_ENABLED:
w_interface = WEBSOCKET_CLIENT_INTERFACE
w_ifacestr = ""
if (
w_interface not in ("0.0.0.0", "::")
or len(WEBSERVER_INTERFACES) > 1
):
if w_interface not in ("0.0.0.0", "::") or len(WEBSERVER_INTERFACES) > 1:
w_ifacestr = "-%s" % interface
port = WEBSOCKET_CLIENT_PORT
@ -386,12 +369,8 @@ if WEBSERVER_ENABLED:
factory.noisy = False
factory.protocol = webclient.WebSocketClient
factory.sessionhandler = PORTAL_SESSIONS
websocket_service = internet.TCPServer(
port, factory, interface=w_interface
)
websocket_service.setName(
"EvenniaWebSocket%s:%s" % (w_ifacestr, port)
)
websocket_service = internet.TCPServer(port, factory, interface=w_interface)
websocket_service.setName("EvenniaWebSocket%s:%s" % (w_ifacestr, port))
PORTAL.services.addService(websocket_service)
websocket_started = True
webclientstr = "webclient-websocket%s: %s" % (w_ifacestr, port)
@ -402,9 +381,7 @@ if WEBSERVER_ENABLED:
proxy_service = internet.TCPServer(proxyport, web_root, interface=interface)
proxy_service.setName("EvenniaWebProxy%s:%s" % (ifacestr, proxyport))
PORTAL.services.addService(proxy_service)
INFO_DICT["webserver_proxy"].append(
"webserver-proxy%s: %s" % (ifacestr, proxyport)
)
INFO_DICT["webserver_proxy"].append("webserver-proxy%s: %s" % (ifacestr, proxyport))
INFO_DICT["webserver_internal"].append("webserver: %s" % serverport)

View file

@ -7,13 +7,7 @@ import time
from collections import deque, namedtuple
from twisted.internet import reactor
from django.conf import settings
from evennia.server.sessionhandler import (
SessionHandler,
PCONN,
PDISCONN,
PCONNSYNC,
PDISCONNALL,
)
from evennia.server.sessionhandler import SessionHandler, PCONN, PDISCONN, PCONNSYNC, PDISCONNALL
from evennia.utils.logger import log_trace
# module import
@ -256,9 +250,7 @@ class PortalSessionHandler(SessionHandler):
path, clsname = protocol_path.rsplit(".", 1)
cls = _MOD_IMPORT(path, clsname)
if not cls:
raise RuntimeError(
"ServerConnect: protocol factory '%s' not found." % protocol_path
)
raise RuntimeError("ServerConnect: protocol factory '%s' not found." % protocol_path)
protocol = cls(self, **config)
protocol.start()

View file

@ -302,9 +302,7 @@ class SshProtocol(Manhole, session.Session):
xterm256 = options.get("xterm256", flags.get("XTERM256", True))
useansi = options.get("ansi", flags.get("ANSI", True))
raw = options.get("raw", flags.get("RAW", False))
nocolor = options.get(
"nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi)
)
nocolor = options.get("nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi))
# echo = options.get("echo", None) # DEBUG
screenreader = options.get("screenreader", flags.get("SCREENREADER", False))

View file

@ -93,9 +93,7 @@ def verify_SSL_key_and_cert(keyfile, certfile):
subprocess.call(exestring)
except OSError as err:
raise OSError(
NO_AUTOCERT.format(
err=err, certfile=certfile, keyfile=keyfile, exestring=exestring
)
NO_AUTOCERT.format(err=err, certfile=certfile, keyfile=keyfile, exestring=exestring)
)
print("done.")

View file

@ -39,9 +39,7 @@ class SuppressGA(object):
self.protocol.protocol_flags["NOGOAHEAD"] = True
# tell the client that we prefer to suppress GA ...
self.protocol.will(SUPPRESS_GA).addCallbacks(
self.will_suppress_ga, self.wont_suppress_ga
)
self.protocol.will(SUPPRESS_GA).addCallbacks(self.will_suppress_ga, self.wont_suppress_ga)
def wont_suppress_ga(self, option):
"""

View file

@ -42,8 +42,7 @@ _IDLE_COMMAND = str.encode(settings.IDLE_COMMAND + "\n")
# identify HTTP indata
_HTTP_REGEX = re.compile(
b"(GET|HEAD|POST|PUT|DELETE|TRACE|OPTIONS|CONNECT|PATCH) (.*? HTTP/[0-9]\.[0-9])",
re.I,
b"(GET|HEAD|POST|PUT|DELETE|TRACE|OPTIONS|CONNECT|PATCH) (.*? HTTP/[0-9]\.[0-9])", re.I
)
_HTTP_WARNING = bytes(
@ -89,16 +88,10 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session):
client_address = client_address[0] if client_address else None
# this number is counted down for every handshake that completes.
# when it reaches 0 the portal/server syncs their data
self.handshakes = (
8
) # suppress-go-ahead, naws, ttype, mccp, mssp, msdp, gmcp, mxp
self.handshakes = 8 # suppress-go-ahead, naws, ttype, mccp, mssp, msdp, gmcp, mxp
self.init_session(
self.protocol_key, client_address, self.factory.sessionhandler
)
self.protocol_flags["ENCODING"] = (
settings.ENCODINGS[0] if settings.ENCODINGS else "utf-8"
)
self.init_session(self.protocol_key, client_address, self.factory.sessionhandler)
self.protocol_flags["ENCODING"] = settings.ENCODINGS[0] if settings.ENCODINGS else "utf-8"
# add this new connection to sessionhandler so
# the Server becomes aware of it.
self.sessionhandler.connect(self)
@ -188,8 +181,7 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session):
if option == LINEMODE:
# make sure to activate line mode with local editing for all clients
self.requestNegotiation(
LINEMODE,
MODE + bytes(chr(ord(LINEMODE_EDIT) + ord(LINEMODE_TRAPSIG)), "ascii"),
LINEMODE, MODE + bytes(chr(ord(LINEMODE_EDIT) + ord(LINEMODE_TRAPSIG)), "ascii")
)
return True
else:
@ -306,9 +298,7 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session):
# escape IAC in line mode, and correctly add \r\n (the TELNET end-of-line)
line = line.replace(IAC, IAC + IAC)
line = line.replace(b"\n", b"\r\n")
if not line.endswith(b"\r\n") and self.protocol_flags.get(
"FORCEDENDLINE", True
):
if not line.endswith(b"\r\n") and self.protocol_flags.get("FORCEDENDLINE", True):
line += b"\r\n"
if not self.protocol_flags.get("NOGOAHEAD", True):
line += IAC + GA
@ -382,16 +372,13 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session):
options = kwargs.get("options", {})
flags = self.protocol_flags
xterm256 = options.get(
"xterm256",
flags.get("XTERM256", False) if flags.get("TTYPE", False) else True,
"xterm256", flags.get("XTERM256", False) if flags.get("TTYPE", False) else True
)
useansi = options.get(
"ansi", flags.get("ANSI", False) if flags.get("TTYPE", False) else True
)
raw = options.get("raw", flags.get("RAW", False))
nocolor = options.get(
"nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi)
)
nocolor = options.get("nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi))
echo = options.get("echo", None)
mxp = options.get("mxp", flags.get("MXP", False))
screenreader = options.get("screenreader", flags.get("SCREENREADER", False))

View file

@ -48,13 +48,11 @@ from twisted.conch.telnet import IAC, SB, SE
# pre-compiled regexes
# returns 2-tuple
msdp_regex_table = re.compile(
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s"
% (MSDP_VAR, MSDP_VAL, MSDP_TABLE_OPEN, MSDP_TABLE_CLOSE)
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_TABLE_OPEN, MSDP_TABLE_CLOSE)
)
# returns 2-tuple
msdp_regex_array = re.compile(
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s"
% (MSDP_VAR, MSDP_VAL, MSDP_ARRAY_OPEN, MSDP_ARRAY_CLOSE)
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_ARRAY_OPEN, MSDP_ARRAY_CLOSE)
)
msdp_regex_var = re.compile(br"%s" % MSDP_VAR)
msdp_regex_val = re.compile(br"%s" % MSDP_VAL)
@ -190,9 +188,7 @@ class TelnetOOB(object):
"{msdp_array_close}".format(
msdp_array_open=MSDP_ARRAY_OPEN,
msdp_array_close=MSDP_ARRAY_CLOSE,
msdp_args="".join(
"%s%s" % (MSDP_VAL, json.dumps(val)) for val in args
),
msdp_args="".join("%s%s" % (MSDP_VAL, json.dumps(val)) for val in args),
)
)

View file

@ -150,8 +150,6 @@ def getSSLContext():
"""
if verify_or_create_SSL_key_and_cert(_PRIVATE_KEY_FILE, _CERTIFICATE_FILE):
return twisted_ssl.DefaultOpenSSLContextFactory(
_PRIVATE_KEY_FILE, _CERTIFICATE_FILE
)
return twisted_ssl.DefaultOpenSSLContextFactory(_PRIVATE_KEY_FILE, _CERTIFICATE_FILE)
else:
return None

View file

@ -28,12 +28,7 @@ from .mssp import MSSP
from .mxp import MXP
from .telnet_oob import MSDP, MSDP_VAL, MSDP_VAR
from .amp import (
AMPMultiConnectionProtocol,
MsgServer2Portal,
MsgPortal2Server,
AMP_MAXLEN,
)
from .amp import AMPMultiConnectionProtocol, MsgServer2Portal, MsgPortal2Server, AMP_MAXLEN
from .amp_server import AMPServerFactory
@ -61,9 +56,7 @@ class TestAMPServer(TwistedTestCase):
b"\x8bK\xa6x3\x15\xb7M\xd1\x03\x00V:\x07t\x00\x00"
)
self.transport.write.assert_called_with(byte_out)
with mock.patch(
"evennia.server.portal.amp.amp.AMP.dataReceived"
) as mocked_amprecv:
with mock.patch("evennia.server.portal.amp.amp.AMP.dataReceived") as mocked_amprecv:
self.proto.dataReceived(byte_out)
mocked_amprecv.assert_called_with(byte_out)
@ -77,9 +70,7 @@ class TestAMPServer(TwistedTestCase):
b"\x8bK\xa6x3\x15\xb7M\xd1\x03\x00V:\x07t\x00\x00"
)
self.transport.write.assert_called_with(byte_out)
with mock.patch(
"evennia.server.portal.amp.amp.AMP.dataReceived"
) as mocked_amprecv:
with mock.patch("evennia.server.portal.amp.amp.AMP.dataReceived") as mocked_amprecv:
self.proto.dataReceived(byte_out)
mocked_amprecv.assert_called_with(byte_out)
@ -221,9 +212,7 @@ class TestTelnet(TwistedTestCase):
self.assertEqual(self.proto.protocol_flags["SCREENWIDTH"], {0: DEFAULT_WIDTH})
self.assertEqual(self.proto.protocol_flags["SCREENHEIGHT"], {0: DEFAULT_HEIGHT})
self.proto.dataReceived(IAC + WILL + NAWS)
self.proto.dataReceived(
b"".join([IAC, SB, NAWS, b"", b"x", b"", b"d", IAC, SE])
)
self.proto.dataReceived(b"".join([IAC, SB, NAWS, b"", b"x", b"", b"d", IAC, SE]))
self.assertEqual(self.proto.protocol_flags["SCREENWIDTH"][0], 78)
self.assertEqual(self.proto.protocol_flags["SCREENHEIGHT"][0], 45)
self.assertEqual(self.proto.handshakes, 6)

View file

@ -172,9 +172,7 @@ class Ttype(object):
# a number - determine the actual capabilities
option = int(option)
support = dict(
(capability, True)
for bitval, capability in MTTS
if option & bitval > 0
(capability, True) for bitval, capability in MTTS if option & bitval > 0
)
self.protocol.protocol_flags.update(support)
else:

View file

@ -418,9 +418,7 @@ class AjaxWebClientSession(session.Session):
raw = options.get("raw", flags.get("RAW", False))
xterm256 = options.get("xterm256", flags.get("XTERM256", True))
useansi = options.get("ansi", flags.get("ANSI", True))
nocolor = options.get(
"nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi)
)
nocolor = options.get("nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi))
screenreader = options.get("screenreader", flags.get("SCREENREADER", False))
prompt = options.get("send_prompt", False)

View file

@ -333,10 +333,7 @@ class DummyClient(telnet.StatefulTelnetProtocol):
# get the login commands
self._cmdlist = list(makeiter(self._login(self)))
NLOGGED_IN += 1 # this is for book-keeping
print(
"connecting client %s (%i/%i)..."
% (self.key, NLOGGED_IN, NCLIENTS)
)
print("connecting client %s (%i/%i)..." % (self.key, NLOGGED_IN, NCLIENTS))
self._loggedin = True
else:
# no login yet, so cmdlist not yet set

View file

@ -188,10 +188,7 @@ def c_creates_button(client):
"creates example button, storing name on client"
objname = TOBJ_TEMPLATE % client.counter()
client.objs.append(objname)
cmds = (
"@create %s:%s" % (objname, TOBJ_TYPECLASS),
"@desc %s = test red button!" % objname,
)
cmds = ("@create %s:%s" % (objname, TOBJ_TYPECLASS), "@desc %s = test red button!" % objname)
return cmds
@ -268,14 +265,7 @@ def c_moves_s(client):
# c_logout,
# (1.0, c_idles))
# "normal account" definition
ACTIONS = (
c_login,
c_logout,
(0.01, c_digs),
(0.39, c_looks),
(0.2, c_help),
(0.4, c_moves),
)
ACTIONS = (c_login, c_logout, (0.01, c_digs), (0.39, c_looks), (0.2, c_help), (0.4, c_moves))
# walking tester. This requires a pre-made
# "loop" of multiple rooms that ties back
# to limbo (using @tunnel and @open)

View file

@ -87,9 +87,7 @@ class TestDummyrunnerSettings(TestCase):
)
def test_c_digs(self):
self.assertEqual(
c_digs(self.client), ("@dig/tel testing_room_1 = exit_1, exit_1")
)
self.assertEqual(c_digs(self.client), ("@dig/tel testing_room_1 = exit_1, exit_1"))
self.assertEqual(self.client.exits, ["exit_1", "exit_1"])
self.clear_client_lists()
@ -112,10 +110,7 @@ class TestDummyrunnerSettings(TestCase):
typeclass_name = "contrib.tutorial_examples.red_button.RedButton"
self.assertEqual(
c_creates_button(self.client),
(
"@create %s:%s" % (objname, typeclass_name),
"@desc %s = test red button!" % objname,
),
("@create %s:%s" % (objname, typeclass_name), "@desc %s = test red button!" % objname),
)
self.assertEqual(self.client.objs, [objname])
self.clear_client_lists()
@ -150,9 +145,7 @@ class TestMemPlot(TestCase):
@patch.object(memplot, "os")
@patch.object(memplot, "open", new_callable=mock_open, create=True)
@patch.object(memplot, "time")
@patch(
"evennia.utils.idmapper.models.SharedMemoryModel.flush_from_cache", new=Mock()
)
@patch("evennia.utils.idmapper.models.SharedMemoryModel.flush_from_cache", new=Mock())
def test_memplot(self, mock_time, mocked_open, mocked_os, mocked_idmapper):
if isinstance(memplot, Mock):
return

View file

@ -70,9 +70,7 @@ WEBSERVER_INTERFACES = settings.WEBSERVER_INTERFACES
GUEST_ENABLED = settings.GUEST_ENABLED
# server-channel mappings
WEBSERVER_ENABLED = (
settings.WEBSERVER_ENABLED and WEBSERVER_PORTS and WEBSERVER_INTERFACES
)
WEBSERVER_ENABLED = settings.WEBSERVER_ENABLED and WEBSERVER_PORTS and WEBSERVER_INTERFACES
IRC_ENABLED = settings.IRC_ENABLED
RSS_ENABLED = settings.RSS_ENABLED
GRAPEVINE_ENABLED = settings.GRAPEVINE_ENABLED
@ -126,9 +124,7 @@ def _server_maintenance():
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
)
_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
@ -267,9 +263,7 @@ class Evennia(object):
)
)
mismatches = [
i
for i, tup in enumerate(settings_compare)
if tup[0] and tup[1] and tup[0] != tup[1]
i for i, tup in enumerate(settings_compare) if tup[0] and tup[1] and tup[0] != tup[1]
]
if len(
mismatches
@ -281,9 +275,7 @@ class Evennia(object):
# from evennia.accounts.models import AccountDB
for i, prev, curr in (
(i, tup[0], tup[1])
for i, tup in enumerate(settings_compare)
if i in mismatches
(i, tup[0], tup[1]) for i, tup in enumerate(settings_compare) if i in mismatches
):
# update the database
INFO_DICT["info"] = (
@ -435,22 +427,13 @@ class Evennia(object):
else:
if mode == "reset":
# like shutdown but don't unset the is_connected flag and don't disconnect sessions
yield [
o.at_server_shutdown() for o in ObjectDB.get_all_cached_instances()
]
yield [
p.at_server_shutdown() for p in AccountDB.get_all_cached_instances()
]
yield [o.at_server_shutdown() for o in ObjectDB.get_all_cached_instances()]
yield [p.at_server_shutdown() for p in AccountDB.get_all_cached_instances()]
if self.amp_protocol:
yield self.sessions.all_sessions_portal_sync()
else: # shutdown
yield [
_SA(p, "is_connected", False)
for p in AccountDB.get_all_cached_instances()
]
yield [
o.at_server_shutdown() for o in ObjectDB.get_all_cached_instances()
]
yield [_SA(p, "is_connected", False) for p in AccountDB.get_all_cached_instances()]
yield [o.at_server_shutdown() for o in ObjectDB.get_all_cached_instances()]
yield [
(p.unpuppet_all(), p.at_server_shutdown())
for p in AccountDB.get_all_cached_instances()
@ -629,8 +612,7 @@ application = service.Application("Evennia")
if "--nodaemon" not in sys.argv:
# custom logging, but only if we are not running in interactive mode
logfile = logger.WeeklyLogFile(
os.path.basename(settings.SERVER_LOG_FILE),
os.path.dirname(settings.SERVER_LOG_FILE),
os.path.basename(settings.SERVER_LOG_FILE), os.path.dirname(settings.SERVER_LOG_FILE)
)
application.setComponent(ILogObserver, logger.ServerLogObserver(logfile).emit)

View file

@ -140,11 +140,7 @@ class NAttributeHandler(object):
"""
if return_tuples:
return [
(key, value)
for (key, value) in self._store.items()
if not key.startswith("_")
]
return [(key, value) for (key, value) in self._store.items() if not key.startswith("_")]
return [key for key in self._store if not key.startswith("_")]
@ -175,9 +171,7 @@ class ServerSession(Session):
return [path.strip() for path in self.cmdset_storage_string.split(",")]
def __cmdset_storage_set(self, value):
self.cmdset_storage_string = ",".join(
str(val).strip() for val in make_iter(value)
)
self.cmdset_storage_string = ",".join(str(val).strip() for val in make_iter(value))
cmdset_storage = property(__cmdset_storage_get, __cmdset_storage_set)
@ -514,9 +508,7 @@ class ServerSession(Session):
try:
return self._ndb_holder
except AttributeError:
self._ndb_holder = NDbHolder(
self, "nattrhandler", manager_name="nattributes"
)
self._ndb_holder = NDbHolder(self, "nattrhandler", manager_name="nattributes")
return self._ndb_holder
# @ndb.setter

View file

@ -122,9 +122,7 @@ class Session(object):
"""
return dict(
(key, value)
for key, value in self.__dict__.items()
if key in self._attrs_to_sync
(key, value) for key, value in self.__dict__.items() if key in self._attrs_to_sync
)
def load_sync_data(self, sessdata):

View file

@ -25,10 +25,7 @@ from evennia.utils.utils import (
callables_from_module,
)
from evennia.server.signals import SIGNAL_ACCOUNT_POST_LOGIN, SIGNAL_ACCOUNT_POST_LOGOUT
from evennia.server.signals import (
SIGNAL_ACCOUNT_POST_FIRST_LOGIN,
SIGNAL_ACCOUNT_POST_LAST_LOGOUT,
)
from evennia.server.signals import SIGNAL_ACCOUNT_POST_FIRST_LOGIN, SIGNAL_ACCOUNT_POST_LAST_LOGOUT
from evennia.utils.inlinefuncs import parse_inlinefunc
from codecs import decode as codecs_decode
@ -224,15 +221,9 @@ class SessionHandler(dict):
elif isinstance(data, (str, bytes)):
data = _utf8(data)
if (
_INLINEFUNC_ENABLED
and not raw
and isinstance(self, ServerSessionHandler)
):
if _INLINEFUNC_ENABLED and not raw and isinstance(self, ServerSessionHandler):
# only parse inlinefuncs on the outgoing path (sessionhandler->)
data = parse_inlinefunc(
data, strip=strip_inlinefunc, session=session
)
data = parse_inlinefunc(data, strip=strip_inlinefunc, session=session)
return str(data)
elif (
@ -460,10 +451,7 @@ class ServerSessionHandler(SessionHandler):
"""
self.server.amp_protocol.send_AdminServer2Portal(
DUMMYSESSION,
operation=SCONN,
protocol_path=protocol_path,
config=configdict,
DUMMYSESSION, operation=SCONN, protocol_path=protocol_path, config=configdict
)
def portal_restart_server(self):
@ -471,9 +459,7 @@ class ServerSessionHandler(SessionHandler):
Called by server when reloading. We tell the portal to start a new server instance.
"""
self.server.amp_protocol.send_AdminServer2Portal(
DUMMYSESSION, operation=SRELOAD
)
self.server.amp_protocol.send_AdminServer2Portal(DUMMYSESSION, operation=SRELOAD)
def portal_reset_server(self):
"""
@ -530,17 +516,13 @@ class ServerSessionHandler(SessionHandler):
nsess = len(self.sessions_from_account(account))
string = "Logged in: {account} {address} ({nsessions} session(s) total)"
string = string.format(
account=account, address=session.address, nsessions=nsess
)
string = string.format(account=account, address=session.address, nsessions=nsess)
session.log(string)
session.logged_in = True
# sync the portal to the session
if not testmode:
self.server.amp_protocol.send_AdminServer2Portal(
session,
operation=SLOGIN,
sessiondata={"logged_in": True, "uid": session.uid},
session, operation=SLOGIN, sessiondata={"logged_in": True, "uid": session.uid}
)
account.at_post_login(session=session)
if nsess < 2:
@ -570,17 +552,12 @@ class ServerSessionHandler(SessionHandler):
sreason = " ({})".format(reason) if reason else ""
string = "Logged out: {account} {address} ({nsessions} sessions(s) remaining){reason}"
string = string.format(
reason=sreason,
account=session.account,
address=session.address,
nsessions=nsess,
reason=sreason, account=session.account, address=session.address, nsessions=nsess
)
session.log(string)
if nsess == 0:
SIGNAL_ACCOUNT_POST_LAST_LOGOUT.send(
sender=session.account, session=session
)
SIGNAL_ACCOUNT_POST_LAST_LOGOUT.send(sender=session.account, session=session)
session.at_disconnect(reason)
SIGNAL_ACCOUNT_POST_LOGOUT.send(sender=session.account, session=session)
@ -660,9 +637,7 @@ class ServerSessionHandler(SessionHandler):
# mean connecting from the same host would not catch duplicates
sid = id(curr_session)
doublet_sessions = [
sess
for sess in self.values()
if sess.logged_in and sess.uid == uid and id(sess) != sid
sess for sess in self.values() if sess.logged_in and sess.uid == uid and id(sess) != sid
]
for session in doublet_sessions:
@ -762,11 +737,7 @@ class ServerSessionHandler(SessionHandler):
"""
uid = account.uid
return [
session
for session in self.values()
if session.logged_in and session.uid == uid
]
return [session for session in self.values() if session.logged_in and session.uid == uid]
def sessions_from_puppet(self, puppet):
"""
@ -799,9 +770,7 @@ class ServerSessionHandler(SessionHandler):
if csessid:
return []
return [
session
for session in self.values()
if session.csessid and session.csessid == csessid
session for session in self.values() if session.csessid and session.csessid == csessid
]
def announce_all(self, message):

View file

@ -85,9 +85,7 @@ class TestAMPClientSend(_TestAMP):
self._connect_server(mocktransport)
self.amp_server.dataReceived(wire_data)
self.portal.sessions.data_out.assert_called_with(
self.portalsession, text={"foo": "bar"}
)
self.portal.sessions.data_out.assert_called_with(self.portalsession, text={"foo": "bar"})
def test_adminserver2portal(self, mocktransport):
self._connect_client(mocktransport)
@ -114,9 +112,7 @@ class TestAMPClientRecv(_TestAMP):
self._connect_client(mocktransport)
self.amp_client.dataReceived(wire_data)
self.server.sessions.data_in.assert_called_with(
self.session, text={"foo": "bar"}
)
self.server.sessions.data_in.assert_called_with(self.session, text={"foo": "bar"})
def test_adminportal2server(self, mocktransport):
self._connect_server(mocktransport)

View file

@ -132,9 +132,7 @@ class TestLauncher(TwistedTestCase):
@patch("evennia.server.evennia_launcher.print")
def test_query_status_run(self, mprint):
evennia_launcher.query_status()
mprint.assert_called_with(
"Portal: RUNNING (pid 100)\nServer: RUNNING (pid 100)"
)
mprint.assert_called_with("Portal: RUNNING (pid 100)\nServer: RUNNING (pid 100)")
@patch("evennia.server.evennia_launcher.send_instruction", _msend_status_err)
@patch("evennia.server.evennia_launcher.NO_REACTOR_STOP", True)

View file

@ -66,9 +66,7 @@ class TestDeprecations(TestCase):
self.assertRaises(DeprecationWarning, check_errors, MockSettings(setting))
# test check for WEBSERVER_PORTS having correct value
self.assertRaises(
DeprecationWarning,
check_errors,
MockSettings("WEBSERVER_PORTS", value=["not a tuple"]),
DeprecationWarning, check_errors, MockSettings("WEBSERVER_PORTS", value=["not a tuple"])
)
@ -83,9 +81,7 @@ class ValidatorTest(EvenniaTest):
# This password contains illegal characters and should raise an Exception.
from django.core.exceptions import ValidationError
self.assertRaises(
ValidationError, validator.validate, "(#)[#]<>", user=self.account
)
self.assertRaises(ValidationError, validator.validate, "(#)[#]<>", user=self.account)
class ThrottleTest(EvenniaTest):
@ -127,6 +123,4 @@ class ThrottleTest(EvenniaTest):
self.assertEqual(len(ips), len(cache.keys()))
# There should only be (cache_size * num_ips) total in the Throttle cache
self.assertEqual(
sum([len(cache[x]) for x in cache.keys()]), throttle.cache_size * len(ips)
)
self.assertEqual(sum([len(cache[x]) for x in cache.keys()]), throttle.cache_size * len(ips))

View file

@ -70,9 +70,7 @@ class TestServer(TestCase):
) as mocks:
mocks["connection"].close = MagicMock()
mocks["ServerConfig"].objects.conf = MagicMock(return_value=100)
with patch(
"evennia.server.server.evennia.ScriptDB.objects.validate"
) as mock:
with patch("evennia.server.server.evennia.ScriptDB.objects.validate") as mock:
self.server._server_maintenance()
mocks["_FLUSH_CACHE"].assert_called_with(1000)
mock.assert_called()
@ -141,9 +139,7 @@ class TestServer(TestCase):
mocks["time"].time = MagicMock(return_value=1000)
mocks["ServerConfig"].objects.conf = MagicMock(return_value=100)
mocks["SESSIONS"].values = MagicMock(
return_value=[sess1, sess2, sess3, sess4]
)
mocks["SESSIONS"].values = MagicMock(return_value=[sess1, sess2, sess3, sess4])
mocks["SESSIONS"].disconnect = MagicMock()
self.server._server_maintenance()
@ -152,9 +148,7 @@ class TestServer(TestCase):
mocks["SESSIONS"].disconnect.assert_has_calls(calls, any_order=True)
def test_evennia_start(self):
with patch.multiple(
"evennia.server.server", time=DEFAULT, service=DEFAULT
) as mocks:
with patch.multiple("evennia.server.server", time=DEFAULT, service=DEFAULT) as mocks:
mocks["time"].time = MagicMock(return_value=1000)
evennia = self.server.Evennia(MagicMock())
@ -202,9 +196,7 @@ class TestServer(TestCase):
def test_initial_setup(self):
from evennia.utils.create import create_account
acct = create_account(
"TestSuperuser", "test@test.com", "testpassword", is_superuser=True
)
acct = create_account("TestSuperuser", "test@test.com", "testpassword", is_superuser=True)
with patch.multiple(
"evennia.server.initial_setup", reset_server=DEFAULT, AccountDB=DEFAULT
@ -217,9 +209,7 @@ class TestServer(TestCase):
def test_initial_setup_retry(self):
from evennia.utils.create import create_account
acct = create_account(
"TestSuperuser2", "test@test.com", "testpassword", is_superuser=True
)
acct = create_account("TestSuperuser2", "test@test.com", "testpassword", is_superuser=True)
with patch.multiple(
"evennia.server.initial_setup",
@ -246,9 +236,7 @@ class TestServer(TestCase):
with patch("evennia.objects.models.ObjectDB") as mockobj:
with patch("evennia.server.server.AccountDB") as mockacct:
mockacct.get_all_cached_instances = MagicMock(
return_value=[acct1, acct2]
)
mockacct.get_all_cached_instances = MagicMock(return_value=[acct1, acct2])
mockobj.get_all_cached_instances = MagicMock(return_value=[obj1, obj2])
mockobj.objects.clear_all_sessids = MagicMock()

View file

@ -16,9 +16,7 @@ class Throttle(object):
no recent failures have been recorded.
"""
error_msg = (
"Too many failed attempts; you must wait a few minutes before trying again."
)
error_msg = "Too many failed attempts; you must wait a few minutes before trying again."
def __init__(self, **kwargs):
"""

View file

@ -35,8 +35,7 @@ class EvenniaUsernameAvailabilityValidator:
exists = AccountDB.objects.filter(username__iexact=username).exists()
if exists:
raise ValidationError(
_("Sorry, that username is already taken."),
code="evennia_username_taken",
_("Sorry, that username is already taken."), code="evennia_username_taken"
)

View file

@ -104,10 +104,7 @@ class EvenniaReverseProxyResource(ReverseProxyResource):
lambda f: logger.log_trace("%s\nCaught errback in webserver.py:75." % f)
)
return EvenniaReverseProxyResource(
self.host,
self.port,
self.path + "/" + urlquote(path, safe=""),
self.reactor,
self.host, self.port, self.path + "/" + urlquote(path, safe=""), self.reactor
)
def render(self, request):