Browse Source

Updated: use twgs-proxy.py --config prison.yaml

This allows you to load in a configuration file.
This CHANGES logfile, to be the logfile where you
will save the log.
Adds base, which changes where galaxy saves/loads
the json files.  base_USERNAME_game.json
Steve Thielemann 5 years ago
parent
commit
afadd87b56
4 changed files with 62 additions and 32 deletions
  1. 35 25
      config.py
  2. 6 1
      galaxy.py
  3. 7 4
      proxy.py
  4. 14 2
      twgs-proxy.py

+ 35 - 25
config.py

@@ -1,44 +1,54 @@
 from subprocess import check_output
 import yaml
 import os
+import errno
 import logging, logging.handlers
 
+currentdir = os.path.dirname(os.path.abspath(__file__))
 
-def config_load(filename: str):
+# Load must be called
+config = {}
+
+
+def load(filename: str):
     global config
-    with open(filename, "r") as fp:
-        config = yaml.safe_load(fp)
 
+    if not os.path.isfile(filename):
+        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)
 
-if os.path.exists("config_dev.yaml"):
-    config_load("config_dev.yaml")
-else:
-    config_load("config.yaml")
+    with open(filename, "r") as fp:
+        config = yaml.safe_load(fp)
+    if "debug" in config and config["debug"]:
+        level = logging.DEBUG
+    else:
+        level = logging.INFO
 
-currentdir = os.path.dirname( os.path.abspath( __file__ ) )
+    root = logging.getLogger(None)
+    ch = logging.StreamHandler()
+    ch.setLevel(level)
+    formatter = logging.Formatter(
+        "%(asctime)s - %(filename)s (%(lineno)d) - %(name)s - %(levelname)s - %(message)s"
+    )
+    ch.setFormatter(formatter)
+    root.addHandler(ch)
 
-if 'debug' in config and config['debug']:
-    level = logging.DEBUG
-else:
-    level = logging.INFO
+    if "logfile" in config and config["logfile"]:
+        fhlog = logging.handlers.TimedRotatingFileHandler(
+            filename=os.path.join(currentdir, config["logfile"]),
+            when="midnight",
+            backupCount=7,
+        )
+        fhlog.setFormatter(formatter)
+        fhlog.setLevel(level)
+        root.addHandler(fhlog)
 
-root = logging.getLogger(None)
-ch = logging.StreamHandler()
-ch.setLevel( level )
-formatter = logging.Formatter( '%(asctime)s - %(filename)s (%(lineno)d) - %(name)s - %(levelname)s - %(message)s' )
-ch.setFormatter( formatter )
-root.addHandler( ch )
+    root.setLevel(level)
+    # print("config:", config)
 
-if 'logfile' in config and config['logfile']:
-    fhlog = logging.handlers.TimedRotatingFileHandler( filename = os.path.join( currentdir, 'twgs_proxy.log' ), when = 'midnight', backupCount = 7 )
-    fhlog.setFormatter( formatter )
-    fhlog.setLevel( level )
-    root.addHandler(fhlog)
 
-root.setLevel(level)
 # with open('logging.config', 'r') as fp:
 #     LOGGING_CONFIG = yaml.safe_load(fp)
-    
+
 # Extract the version information from git.
 # The match gives us only tags starting with v[0-9]*  Using anything else trips up on double digits.
 version = check_output(

+ 6 - 1
galaxy.py

@@ -6,6 +6,7 @@ import pendulum
 # from twisted.python import log
 from pprint import pprint
 from colorama import Fore, Back, Style
+import config
 
 log = logging.getLogger(__name__)
 
@@ -52,7 +53,11 @@ class GameData(object):
         username.lower _ game.upper.json
         """
         user, game = self.usergame
-        return "{0}_{1}.json".format(user.lower(), game.upper())
+        if "base" in config.config:
+            base = config.config["base"] + "_"
+        else:
+            base = ""
+        return "{0}{1}_{2}.json".format(base, user.lower(), game.upper())
 
     def reset_ports(self):
         self.ports = {}

+ 7 - 4
proxy.py

@@ -14,7 +14,8 @@ from colorama import Fore, Back, Style
 
 from pprint import pformat
 
-from config import config, version
+# from config import config, version
+import config
 
 log = logging.getLogger(__name__)
 
@@ -290,7 +291,7 @@ class Game(protocol.Protocol):
     def lineReceived(self, line: str):
         """ line received from the game. """
         self.received = True
-        if "log_lines" in config and config["log_lines"]:
+        if "log_lines" in config.config and config.config["log_lines"]:
             self.log.debug("<< [{0}]".format(line))
 
         if "TradeWars Game Server" in line and "Copyright (C) EIS" in line:
@@ -409,7 +410,9 @@ class Game(protocol.Protocol):
             if pos != -1:
                 # Found it!  Inject!
                 message = (
-                    "TWGS Proxy build " + version + ".  ~ to activate in game.\n\r"
+                    "TWGS Proxy build "
+                    + config.version
+                    + ".  ~ to activate in game.\n\r"
                 )
                 chunk = (
                     chunk[0 : pos + len(target)]
@@ -481,7 +484,7 @@ class Player(protocol.Protocol):
         self.glue = factory
 
         # Make connection to the game server
-        reactor.connectTCP(config["host"], config["port"], factory, 5)
+        reactor.connectTCP(config.config["host"], config.config["port"], factory, 5)
 
     def setGameReceived(self):
         """ Get deferred from client queue, callback clientDataReceived. """

+ 14 - 2
twgs-proxy.py

@@ -1,6 +1,7 @@
 #!/usr/bin/env python3
 
 import sys
+
 try:
     from twisted.internet import reactor
 except ImportError:
@@ -11,10 +12,21 @@ from twisted.internet import protocol
 import logging
 import logging.config
 from twisted.python import log
+from proxy import Player
+import argparse
+
+parser = argparse.ArgumentParser(description="TradeWars Proxy")
+parser.add_argument(
+    "--config", type=str, help="Configuration file to load", default="config.yaml"
+)
+parser.add_argument("--debug", action="store_true")
+args = parser.parse_args()
 
 # from twisted.python.logfile import DailyLogFile
-from config import config, version
-from proxy import Player
+from config import version, load
+
+load(args.config)
+from config import config
 
 logger = logging.getLogger(__name__)