Reformat project

This commit is contained in:
2022-07-21 13:40:05 +01:00
parent 4ecb37b179
commit 2fecd98978
44 changed files with 363 additions and 236 deletions

View File

@@ -2,16 +2,14 @@ from twisted.internet.protocol import ReconnectingClientFactory
from twisted.words.protocols.irc import IRCClient
from twisted.internet.defer import Deferred
from twisted.internet.task import LoopingCall
from twisted.internet import reactor, task
from twisted.internet import reactor
from twisted.words.protocols.irc import (
symbolic_to_numeric,
numeric_to_symbolic,
lowDequote,
IRCBadMessage,
)
import sys
from string import digits
from random import randint
from copy import deepcopy
from datetime import datetime
@@ -24,19 +22,13 @@ from modules import regproc
from core.relay import sendRelayNotification
from utils.dedup import dedup
from utils.get import getRelay
import main
from utils.logging.log import *
from utils.logging.debug import *
from utils.logging.send import *
from utils.logging.log import log, warn, error
from utils.logging.debug import debug
from utils.logging.send import sendAll
from utils.parsing import parsen
from twisted.internet.ssl import DefaultOpenSSLContextFactory
from utils.deliver_relay_commands import deliverRelayCommands
# Copied from the Twisted source so we can fix a bug
def parsemsg(s):
@@ -64,69 +56,6 @@ def parsemsg(s):
return prefix, command, args
class IRCRelay(IRCClient):
def __init__(self, num, relayCommands, user, stage2):
self.isconnected = False
self.buffer = ""
if user == None:
self.user = main.config["Relay"]["User"]
else:
self.user = user.lower()
password = main.config["Relay"]["Password"]
self.nickname = "relay"
self.realname = "relay"
self.username = self.user
self.password = self.user + ":" + password
self.relayCommands = relayCommands
self.num = num
self.stage2 = stage2
self.loop = None
def privmsg(self, user, channel, msg):
nick, ident, host = parsen(user)
for i in main.ZNCErrors:
if i in msg:
error("ZNC issue:", msg)
if nick[0] == main.config["Tweaks"]["ZNC"]["Prefix"]:
nick = nick[1:]
if nick in self.relayCommands.keys():
sendAll("[%s] %s -> %s" % (self.num, nick, msg))
def irc_ERR_PASSWDMISMATCH(self, prefix, params):
log("%s: relay password mismatch" % self.num)
sendAll("%s: relay password mismatch" % self.num)
def sendStage2(self):
# [["user", {"sasl": ["message1", "message2"]}], []]
if not len(self.stage2) == 0:
user = self.stage2[0].pop(0)
commands = self.stage2[0].pop(0)
del self.stage2[0]
deliverRelayCommands(self.num, commands, user, self.stage2)
def signedOn(self):
if not self.isconnected:
self.isconnected = True
# log("signed on as a relay: %s" % self.num)
sleeptime = 0
increment = 0.8
for i in self.relayCommands.keys():
for x in self.relayCommands[i]:
reactor.callLater(
sleeptime,
self.msg,
main.config["Tweaks"]["ZNC"]["Prefix"] + i,
x,
)
sleeptime += increment
increment += 0.8
if not self.stage2 == None:
reactor.callLater(sleeptime, self.sendStage2)
reactor.callLater(sleeptime + 5, self.transport.loseConnection)
return
class IRCBot(IRCClient):
def __init__(self, net, num):
self.isconnected = False
@@ -188,7 +117,7 @@ class IRCBot(IRCClient):
sleeptime = 0.0
increment = 0.8
for i in channels:
if not i in self.channels:
if i not in self.channels:
if self.net in main.blacklist.keys():
if i in main.blacklist[self.net]:
debug("Not joining blacklisted channel %s on %s - %i" % (i, self.net, self.num))
@@ -215,12 +144,12 @@ class IRCBot(IRCClient):
del main.TempChan[self.net]
def event(self, **cast):
if not "ts" in cast.keys():
if "ts" not in cast.keys():
cast["ts"] = str(datetime.now().isoformat())
# remove odd stuff
for i in list(cast.keys()): # Make a copy of the .keys() as Python 3 cannot handle iterating over
if cast[i] == "": # a dictionary that changes length with each iteration
if cast[i] == "": # a dictionary that changes length with each iteration
del cast[i]
# remove server stuff
if "muser" in cast.keys():
@@ -302,16 +231,16 @@ class IRCBot(IRCClient):
# we have been mentioned in a msg/notice/action/part/quit/topic message
if "msg" in cast.keys(): # Don't highlight queries
if not cast["msg"] == None:
if cast["msg"] is not None:
if self.nickname.lower() in cast["msg"].lower():
castDup = deepcopy(cast)
castDup["mtype"] = cast["type"]
castDup["type"] = "highlight"
self.event(**castDup)
if not "net" in cast.keys():
if "net" not in cast.keys():
cast["net"] = self.net
if not "num" in cast.keys():
if "num" not in cast.keys():
cast["num"] = self.num
if not self.authenticated:
regproc.registerTest(cast)
@@ -478,7 +407,7 @@ class IRCBot(IRCClient):
else:
if nocheck:
allRelays = True # override the system - if this is
else: # specified, we already did this
else: # specified, we already did this
allRelays = chankeep.allRelaysActive(self.net)
if not allRelays:
self.wantList = True
@@ -535,7 +464,7 @@ class IRCBot(IRCClient):
allRelays = chankeep.allRelaysActive(self.net)
if allRelays:
name = self.net + "1"
if main.IRCPool[name].wantList == True:
if main.IRCPool[name].wantList is True:
main.IRCPool[name].list(nocheck=True)
debug("Asking for a list for %s after final relay %i connected" % (self.net, self.num))
if self.num == 1: # Only one instance should do a list
@@ -559,7 +488,7 @@ class IRCBot(IRCClient):
try:
self.chanlimit = int(chanlimit)
except TypeError:
warn("Invalid chanlimit: %s" % i)
warn("Invalid chanlimit: %s" % chanlimit)
if self.chanlimit == 0:
self.chanlimit = 200 # don't take the piss if it's not limited
if not regproc.needToRegister(self.net): # if we need to register, only recheck on auth confirmation
@@ -625,7 +554,7 @@ class IRCBot(IRCClient):
self.userLeft(prefix, channel, message)
def irc_QUIT(self, prefix, params):
nick = prefix.split("!")[0]
# nick = prefix.split("!")[0]
self.userQuit(prefix, params[0])
def irc_NICK(self, prefix, params):
@@ -656,12 +585,12 @@ class IRCBot(IRCClient):
if not sinst:
error(f"Registration ping failed for {self.net} - {self.num}")
return
if not self._negativePass == True:
if negativepass == False:
if self._negativePass is not True:
if negativepass is False:
self._negativePass = False
return
if negativepass == True:
if self._negativePass == None:
if negativepass is True:
if self._negativePass is None:
self._negativePass = True
debug("Positive registration check - %s - %i" % (self.net, self.num))
if sinst["ping"]:
@@ -701,7 +630,7 @@ class IRCBot(IRCClient):
reactor.callLater(10, self.regPing)
def joined(self, channel):
if not channel in self.channels:
if channel not in self.channels:
self.channels.append(channel)
self.names(channel).addCallback(self.got_names)
if main.config["Toggles"]["Who"]:
@@ -723,7 +652,7 @@ class IRCBot(IRCClient):
# log("Can no longer cover %s, removing records" % channel)# as it will only be matched once --
# other bots have different nicknames so
def left(self, user, channel, message): # even if they saw it, they wouldn't react
def left(self, user, channel, message): # even if they saw it, they wouldn't react
self.event(type="part", muser=user, channel=channel, msg=message)
self.botLeft(channel)
@@ -749,7 +678,7 @@ class IRCBot(IRCClient):
# format
return # stop right there sir!
chans = userinfo.getChanList(self.net, cast["nick"])
if chans == None:
if chans is None:
error("No channels returned for chanless event: %s" % cast)
# self.event(**cast) -- no, should NEVER happen
return
@@ -780,9 +709,10 @@ class IRCBot(IRCClient):
)
# TODO: strip out relay functionality
class IRCBotFactory(ReconnectingClientFactory):
def __init__(self, net, num=None, relayCommands=None, user=None, stage2=None):
if net == None:
if net is None:
self.num = num
self.net = None
self.name = "relay - %i" % num
@@ -801,11 +731,9 @@ class IRCBotFactory(ReconnectingClientFactory):
self.relayCommands, self.user, self.stage2 = relayCommands, user, stage2
def buildProtocol(self, addr):
if self.relay == False:
if self.relay is False:
entry = IRCBot(self.net, self.num)
main.IRCPool[self.name] = entry
else:
entry = IRCRelay(self.num, self.relayCommands, self.user, self.stage2)
self.client = entry
return entry
@@ -813,7 +741,7 @@ class IRCBotFactory(ReconnectingClientFactory):
def clientConnectionLost(self, connector, reason):
if not self.relay:
userinfo.delChannels(self.net, self.client.channels)
if not self.client == None:
if self.client is not None:
self.client.isconnected = False
self.client.authenticated = False
self.client.channels = []
@@ -836,7 +764,7 @@ class IRCBotFactory(ReconnectingClientFactory):
# ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
def clientConnectionFailed(self, connector, reason):
if not self.client == None:
if self.client is not None:
self.client.isconnected = False
self.client.authenticated = False
self.client.channels = []

77
core/factory.py Normal file
View File

@@ -0,0 +1,77 @@
class IRCBotFactory(ReconnectingClientFactory):
def __init__(self, net, num=None, relayCommands=None, user=None, stage2=None):
if net is None:
self.num = num
self.net = None
self.name = "relay - %i" % num
self.relay = True
else:
self.name = net + str(num)
self.num = num
self.net = net
self.relay = False
self.client = None
self.maxDelay = main.config["Tweaks"]["Delays"]["MaxDelay"]
self.initialDelay = main.config["Tweaks"]["Delays"]["InitialDelay"]
self.factor = main.config["Tweaks"]["Delays"]["Factor"]
self.jitter = main.config["Tweaks"]["Delays"]["Jitter"]
self.relayCommands, self.user, self.stage2 = relayCommands, user, stage2
def buildProtocol(self, addr):
if self.relay is False:
entry = IRCBot(self.net, self.num)
main.IRCPool[self.name] = entry
else:
entry = IRCRelay(self.num, self.relayCommands, self.user, self.stage2)
self.client = entry
return entry
def clientConnectionLost(self, connector, reason):
if not self.relay:
userinfo.delChannels(self.net, self.client.channels)
if self.client is not None:
self.client.isconnected = False
self.client.authenticated = False
self.client.channels = []
error = reason.getErrorMessage()
if not self.relay:
log("%s - %i: connection lost: %s" % (self.net, self.num, error))
sendAll("%s - %i: connection lost: %s" % (self.net, self.num, error))
ctime = str(datetime.now().isoformat())
sendRelayNotification(
{
"type": "conn",
"net": self.net,
"num": self.num,
"status": "lost",
"message": error,
"ts": ctime,
}
)
self.retry(connector)
# ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
def clientConnectionFailed(self, connector, reason):
if self.client is not None:
self.client.isconnected = False
self.client.authenticated = False
self.client.channels = []
error = reason.getErrorMessage()
log("%s - %i: connection failed: %s" % (self.net, self.num, error))
if not self.relay:
sendAll("%s - %s: connection failed: %s" % (self.net, self.num, error))
ctime = str(datetime.now().isoformat())
sendRelayNotification(
{
"type": "conn",
"net": self.net,
"num": self.num,
"status": "failed",
"message": error,
"ts": ctime,
}
)
self.retry(connector)
# ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

View File

@@ -1,9 +1,8 @@
import logstash
import logging
from json import dumps, loads
from json import dumps
import main
from utils.logging.log import *
logger = None
@@ -22,7 +21,7 @@ def init_logstash():
def sendLogstashNotification(text):
if not logger == None:
if logger is not None:
logger.info(dumps(text))
return True
return False

View File

@@ -1,6 +1,6 @@
import main
from utils.logging.log import *
from utils.logging.send import *
from utils.logging.log import warn
from utils.logging.send import sendSuccess, sendFailure, sendInfo, incorrectUsage
def parseCommand(addr, authed, data):
@@ -12,17 +12,12 @@ def parseCommand(addr, authed, data):
warn("Got connection object with no instance in the address pool")
return
success = lambda data: sendSuccess(addr, data)
failure = lambda data: sendFailure(addr, data)
info = lambda data: sendInfo(addr, data)
success = lambda data: sendSuccess(addr, data) # noqa: E731
failure = lambda data: sendFailure(addr, data) # noqa: E731
info = lambda data: sendInfo(addr, data) # noqa: E731
incUsage = lambda mode: incorrectUsage(addr, mode)
incUsage = lambda mode: incorrectUsage(addr, mode) # noqa: E731
length = len(spl)
if len(spl) > 0:
cmd = spl[0]
else:
failure("No text was sent")
return
if spl[0] in main.CommandMap.keys():
main.CommandMap[spl[0]](addr, authed, data, obj, spl, success, failure, info, incUsage, length)
return

View File

@@ -1,9 +1,7 @@
from twisted.internet.protocol import Protocol, Factory, ClientFactory
from twisted.internet.protocol import Protocol, Factory
from json import dumps, loads
from copy import deepcopy
import main
from utils.logging.log import *
from utils.logging.log import log, warn
validTypes = [
"msg",
@@ -47,10 +45,10 @@ class Relay(Protocol):
data = data.decode("utf-8", "replace")
try:
parsed = loads(data)
except:
except: # noqa: E722
self.sendErr("MALFORMED")
return
if not "type" in parsed.keys():
if "type" not in parsed.keys():
self.sendErr("NOTYPE")
return
if parsed["type"] == "hello":
@@ -87,7 +85,7 @@ class Relay(Protocol):
self.sendErr("NOTLIST")
return
for i in lst:
if not i in validTypes:
if i not in validTypes:
self.sendErr("NONEXISTANT")
return
if i in self.subscriptions:
@@ -102,10 +100,10 @@ class Relay(Protocol):
self.sendErr("NOTLIST")
return
for i in lst:
if not i in validTypes:
if i not in validTypes:
self.sendErr("NONEXISTANT")
return
if not i in self.subscriptions:
if i not in self.subscriptions:
self.sendErr("NOTSUBSCRIBED")
return
del self.subscriptions[i]

View File

@@ -1,6 +1,6 @@
from twisted.internet.protocol import Protocol, Factory, ClientFactory
from twisted.internet.protocol import Protocol, Factory
import main
from utils.logging.log import *
from utils.logging.log import log, warn
from core.parser import parseCommand
@@ -9,7 +9,7 @@ class Server(Protocol):
def __init__(self, addr):
self.addr = addr
self.authed = False
if main.config["UsePassword"] == False:
if main.config["UsePassword"] is False:
self.authed = True
def send(self, data):