Completely refactor the codebase and make everything object-oriented and pythonic

Ensure 100% compliance with the pylint and flake8 linters
master
Tristan Gosselin-Hane 6 years ago
parent 3f9a938474
commit c801ced15c
No known key found for this signature in database
GPG Key ID: 0B7E55B60DCA15D5
  1. 75
      minecraft_discord_bridge/auth_server.py
  2. 11
      minecraft_discord_bridge/config.py
  3. 20
      minecraft_discord_bridge/database_session.py
  4. 10
      minecraft_discord_bridge/elasticsearch_logger.py
  5. 1147
      minecraft_discord_bridge/minecraft_discord_bridge.py
  6. 38
      tox.ini

@ -3,7 +3,8 @@ from datetime import datetime
from quarry.net.server import ServerFactory, ServerProtocol
from .database import AccountLinkToken, MinecraftAccount, DiscordAccount
from . import database_session
DATABASE_SESSION = None
class AuthProtocol(ServerProtocol):
@ -32,46 +33,42 @@ class AuthProtocol(ServerProtocol):
self.logger.info("[AUTH SERVER] %s (%s) connected to address %s:%s",
display_name, uuid, ip_addr, connect_port)
try:
connection_token = ip_addr.split(".")[0]
session = database_session.get_session()
token = session.query(AccountLinkToken).filter_by(token=connection_token).first()
if not token:
self.close("You have connected with an invalid token!")
session.close()
return
discord_account = session.query(DiscordAccount).filter_by(link_token_id=token.id).first()
if not discord_account:
self.close("You have connected with an invalid token!")
session.close()
return
if datetime.utcnow() < token.expiry:
# Check if they already have a linked account and are re-linking
if discord_account.minecraft_account_id is not None:
existing_account = session.query(MinecraftAccount).filter_by(
id=discord_account.minecraft_account_id).first()
self.logger.info("unlinking existing %s account and replacing it with %s",
existing_account.minecraft_uuid, str(uuid))
session.delete(existing_account)
mc_account = MinecraftAccount(str(uuid), discord_account.id)
discord_account.minecraft_account = mc_account
session.add(mc_account)
session.delete(token)
session.commit()
session.close()
self.close("Your minecraft account has successfully been linked to your discord account!")
return
else:
session.delete(token)
session.commit()
session.close()
self.close("You have connected with an expired token! "
"Please run the mc!register command again to get a new token.")
return
except Exception as e:
self.logger.error(e)
connection_token = ip_addr.split(".")[0]
session = DATABASE_SESSION.get_session()
token = session.query(AccountLinkToken).filter_by(token=connection_token).first()
if not token:
self.close("You have connected with an invalid token!")
session.close()
return
discord_account = session.query(DiscordAccount).filter_by(link_token_id=token.id).first()
if not discord_account:
self.close("You have connected with an invalid token!")
session.close()
return
if datetime.utcnow() < token.expiry:
# Check if they already have a linked account and are re-linking
if discord_account.minecraft_account_id is not None:
existing_account = session.query(MinecraftAccount).filter_by(
id=discord_account.minecraft_account_id).first()
self.logger.info("unlinking existing %s account and replacing it with %s",
existing_account.minecraft_uuid, str(uuid))
session.delete(existing_account)
mc_account = MinecraftAccount(str(uuid), discord_account.id)
discord_account.minecraft_account = mc_account
session.add(mc_account)
session.delete(token)
session.commit()
session.close()
self.close("Your minecraft account has successfully been linked to your discord account!")
return
else:
session.delete(token)
session.commit()
session.close()
self.close("You have connected with an expired token! "
"Please run the mc!register command again to get a new token.")
return
# Kick the player.
self.close("This shouldn't happen!")

@ -1,14 +1,13 @@
import json
import logging
log = logging.getLogger("bridge.config")
class Configuration(object):
def __init__(self, path):
self.logger = logging.getLogger("bridge.config")
try:
with open(path, 'r') as f:
self._config = json.load(f)
with open(path, 'r') as file:
self._config = json.load(file)
if self._config:
self.mc_username = self._config["MAIN"]["MC_USERNAME"]
self.mc_password = self._config["MAIN"]["MC_PASSWORD"]
@ -29,8 +28,8 @@ class Configuration(object):
self.es_username = self._config["ELASTICSEARCH"]["USERNAME"]
self.es_password = self._config["ELASTICSEARCH"]["PASSWORD"]
else:
logging.error("error reading config")
self.logger.error("error reading config")
exit(1)
except IOError:
logging.error("error reading config")
self.logger.error("error reading config")
exit(1)

@ -2,17 +2,19 @@ from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
_engine = None
Base = declarative_base()
def initialize(config):
global _engine
_connection_string = config.database_connection_string
_engine = create_engine(_connection_string)
Base.metadata.create_all(_engine)
class DatabaseSession():
def __init__(self):
self._engine = None
self.connection_string = None
def initialize(self, config):
self.connection_string = config.database_connection_string
self._engine = create_engine(self.connection_string)
Base.metadata.create_all(self._engine)
def get_session():
Session = sessionmaker(bind=_engine)()
return Session
def get_session(self):
session = sessionmaker(bind=self._engine)()
return session

@ -38,20 +38,20 @@ class ElasticsearchLogger():
}
self.post_request("chat_messages/_doc/", es_payload)
def log_raw_message(self, type, message):
def log_raw_message(self, msg_type, message):
es_payload = {
"time": (lambda: int(round(time.time() * 1000)))(),
"type": type,
"type": msg_type,
"message": message,
}
self.post_request("raw_messages/_doc/", es_payload)
def post_request(self, endpoint, payload):
theURL = "{}{}".format(self.url, endpoint)
the_url = "{}{}".format(self.url, endpoint)
if self.username and self.password:
post = requests.post(theURL, auth=(self.username, self.password), json=payload)
post = requests.post(the_url, auth=(self.username, self.password), json=payload)
else:
post = requests.post(theURL, json=payload)
post = requests.post(the_url, json=payload)
self.log.debug(post.text)

File diff suppressed because it is too large Load Diff

@ -1,8 +1,9 @@
[tox]
envlist = flake8
envlist = flake8, pylint
[flake8]
max-line-length = 120
exclude = .tox
[testenv:flake8]
deps =
@ -10,3 +11,38 @@ deps =
commands =
pipenv install --dev
flake8
[testenv:pylint]
deps =
pipenv
commands =
pipenv install --dev
pylint --rcfile=tox.ini minecraft_discord_bridge
[FORMAT]
max-line-length=120
[MESSAGES CONTROL]
; C0111 Missing docstring
; I0011: Locally disabling %s
; I0012: Locally enabling %s
; W0704 Except doesn't do anything Used when an except clause does nothing but "pass" and there is no "else" clause
; W0142 Used * or * magic* Used when a function or method is called using *args or **kwargs to dispatch arguments.
; W0212 Access to a protected member %s of a client class
; W0232 Class has no __init__ method Used when a class has no __init__ method, neither its parent classes.
; W0613 Unused argument %r Used when a function or method argument is not used.
; W0702 No exception's type specified Used when an except clause doesn't specify exceptions type to catch.
; R0201 Method could be a function
; W0614 Unused import XYZ from wildcard import
; R0903 Too few public methods
; R0904 Too many public methods
; R0914 Too many local variables
; R0912 Too many branches
; R0915 Too many statements
; R0913 Too many arguments
; R0923: Interface not implemented
disable=I0011,I0012,C0111,W0142,R
[TYPECHECK]
; https://stackoverflow.com/questions/17142236/how-do-i-make-pylint-recognize-twisted-and-ephem-members
ignored-classes=twisted.internet.reactor
Loading…
Cancel
Save