Reformat legacy project

This commit is contained in:
2022-09-05 07:20:30 +01:00
parent 19ee7071f5
commit a198f2a487
59 changed files with 538 additions and 198 deletions

View File

@@ -3,6 +3,9 @@ from copy import deepcopy
from datetime import datetime
from random import randint
import main
from core.relay import sendRelayNotification
from modules import chankeep, counters, helpers, monitor, regproc, userinfo
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import ReconnectingClientFactory
@@ -13,10 +16,6 @@ from twisted.words.protocols.irc import (
lowDequote,
numeric_to_symbolic,
)
import main
from core.relay import sendRelayNotification
from modules import chankeep, counters, helpers, monitor, regproc, userinfo
from utils.dedup import dedup
from utils.logging.debug import debug, trace
from utils.logging.log import error, log, warn
@@ -83,7 +82,9 @@ class IRCBot(IRCClient):
self.listAttempted = False # we asked for a list
self.listSimple = False # after asking again we got the list, so use the simple
# syntax from now on
self.wantList = False # we want to send a LIST, but not all relays are active yet
self.wantList = (
False # we want to send a LIST, but not all relays are active yet
)
self.chanlimit = 0
self.prefix = {}
self.servername = None
@@ -115,9 +116,14 @@ class IRCBot(IRCClient):
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))
debug(
"Not joining blacklisted channel %s on %s - %i"
% (i, self.net, self.num)
)
continue
trace(self.net, "-", self.num, ": joining", i, "in", sleeptime, "seconds")
trace(
self.net, "-", self.num, ": joining", i, "in", sleeptime, "seconds"
)
reactor.callLater(sleeptime, self.join, i)
sleeptime += increment
if sleeptime == 10:
@@ -125,13 +131,19 @@ class IRCBot(IRCClient):
increment = 0.7
increment += 0.1
else:
error("%s - Cannot join channel we are already on: %s - %i" % (i, self.net, self.num))
error(
"%s - Cannot join channel we are already on: %s - %i"
% (i, self.net, self.num)
)
def checkChannels(self):
if chankeep.allRelaysActive(self.net):
debug(f"checkChannels() all relays active for {self.net}")
else:
debug("checkChannels() skipping channel check as we have inactive relays: %s - %i" % (self.net, self.num))
debug(
"checkChannels() skipping channel check as we have inactive relays: %s - %i"
% (self.net, self.num)
)
return
if self.net in main.TempChan.keys():
if self.num in main.TempChan[self.net].keys():
@@ -145,7 +157,9 @@ class IRCBot(IRCClient):
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
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
del cast[i]
# remove server stuff
@@ -201,7 +215,9 @@ class IRCBot(IRCClient):
castDup["type"] = "highlight"
self.event(**castDup)
else:
if cast["channel"].lower() == self.nickname.lower() or not cast["channel"].startswith("#"):
if cast["channel"].lower() == self.nickname.lower() or not cast[
"channel"
].startswith("#"):
cast["mtype"] = cast["type"]
cast["type"] = "query"
# self.event(**castDup)
@@ -277,10 +293,33 @@ class IRCBot(IRCClient):
nick, ident, host = parsen(hostmask)
# We sent someone a query reply
if in_query:
self.event(type="self", mtype="msg", channel=self.nickname, nick=channel, ident=ident, host=host, msg=msg)
self.event(
type="self",
mtype="msg",
channel=self.nickname,
nick=channel,
ident=ident,
host=host,
msg=msg,
)
else:
self.event(type="self", mtype="msg", channel=channel, nick=self.nickname, ident=ident, host=host, msg=msg)
self.event(type="msg", channel=channel, nick=self.nickname, ident=ident, host=host, msg=msg)
self.event(
type="self",
mtype="msg",
channel=channel,
nick=self.nickname,
ident=ident,
host=host,
msg=msg,
)
self.event(
type="msg",
channel=channel,
nick=self.nickname,
ident=ident,
host=host,
msg=msg,
)
self.msg(channel, msg)
def get(self, var):
@@ -309,7 +348,9 @@ class IRCBot(IRCClient):
def irc_ERR_PASSWDMISMATCH(self, prefix, params):
log("%s - %i: password mismatch as %s" % (self.net, self.num, self.username))
sendAll("%s - %i: password mismatch as %s" % (self.net, self.num, self.username))
sendAll(
"%s - %i: password mismatch as %s" % (self.net, self.num, self.username)
)
def _who(self, channel):
d = Deferred()
@@ -424,12 +465,17 @@ class IRCBot(IRCClient):
debug("Will not send LIST, unauthenticated: %s - %i" % (self.net, self.num))
return
if self.listAttempted:
debug("List request dropped, already asked for LIST - %s - %i" % (self.net, self.num))
debug(
"List request dropped, already asked for LIST - %s - %i"
% (self.net, self.num)
)
return
else:
self.listAttempted = True
if self.listOngoing:
debug("LIST request dropped, already ongoing - %s - %i" % (self.net, self.num))
debug(
"LIST request dropped, already ongoing - %s - %i" % (self.net, self.num)
)
return
else:
if nocheck:
@@ -454,7 +500,9 @@ class IRCBot(IRCClient):
self._tempList[1].append([channel, users, topic])
def irc_RPL_LISTEND(self, prefix, params):
if not len(self._tempList[0]) > 0: # there are no callbacks, can't do anything there
if (
not len(self._tempList[0]) > 0
): # there are no callbacks, can't do anything there
debug("We didn't ask for this LIST, discarding")
self._tempList[0].clear()
self._tempList[1].clear()
@@ -479,7 +527,10 @@ class IRCBot(IRCClient):
else:
if self.listRetried:
self.listRetried = False
debug("List received after retry - defaulting to simple list syntax: %s - %i" % (self.net, self.num))
debug(
"List received after retry - defaulting to simple list syntax: %s - %i"
% (self.net, self.num)
)
self.listSimple = True
def got_list(self, listinfo):
@@ -500,9 +551,13 @@ class IRCBot(IRCClient):
if first_relay:
if first_relay.wantList is True:
first_relay.list(nocheck=True)
debug(f"recheckList() asking for a list for {self.net} after final relay {self.num} connected")
debug(
f"recheckList() asking for a list for {self.net} after final relay {self.num} connected"
)
else:
debug(f"recheckList() first relay wantList is False for {self.net} ({first_relay.num})")
debug(
f"recheckList() first relay wantList is False for {self.net} ({first_relay.num})"
)
# name = self.net + "1"
# if self.num == 1: # Only one instance should do a list
@@ -511,7 +566,9 @@ class IRCBot(IRCClient):
if self.chanlimit:
if allRelays:
self.list()
debug(f"recheckList() requested a list for {self.net} from {self.num}")
debug(
f"recheckList() requested a list for {self.net} from {self.num}"
)
else:
debug(f"recheckList() not all relays active for {self.net}")
self.wantList = True
@@ -525,7 +582,9 @@ class IRCBot(IRCClient):
]: # TODO: add check for register request sent, only send it once
if main.config["AutoReg"]:
if not self.authenticated:
self._regAttempt = reactor.callLater(5, regproc.registerAccount, self.net, self.num)
self._regAttempt = reactor.callLater(
5, regproc.registerAccount, self.net, self.num
)
# regproc.registerAccount(self.net, self.num)
try:
self.chanlimit = int(chanlimit)
@@ -539,7 +598,9 @@ class IRCBot(IRCClient):
self.chanlimit = net_inst_chanlimit
# warn(f"Chanlimit on {self.net} too high, setting to {self.chanlimit}")
if not regproc.needToRegister(self.net): # if we need to register, only recheck on auth confirmation
if not regproc.needToRegister(
self.net
): # if we need to register, only recheck on auth confirmation
if main.config["ChanKeep"]["Enabled"]:
self.recheckList()
@@ -642,7 +703,9 @@ class IRCBot(IRCClient):
if reset:
self._negativePass = None
debug(f"regPing() {self.net} - {self.num}: _negativePass:{self._negativePass} negativepass:{negativepass}")
debug(
f"regPing() {self.net} - {self.num}: _negativePass:{self._negativePass} negativepass:{negativepass}"
)
if self._negativePass is None:
# We have failed, the blacklisted message has been found
if negativepass is False:
@@ -665,7 +728,9 @@ class IRCBot(IRCClient):
)
)
else:
debug(f"regPing() {self.net}: negative registration check - {self.num}")
debug(
f"regPing() {self.net}: negative registration check - {self.num}"
)
return
else:
if sinst["negative"]:
@@ -678,14 +743,18 @@ class IRCBot(IRCClient):
)
return
else:
self._negativePass = True # if it's disabled, we still want the next block to run
self._negativePass = (
True # if it's disabled, we still want the next block to run
)
# Only run if negativepass has completed, or exempted as above
if self._negativePass:
if sinst["check"]:
if sinst["ping"]:
self.msg(sinst["entity"], sinst["pingmsg"])
debug(f"regPing() {self.net}: sent ping '{sinst['pingmsg']}' to {sinst['entity']} - {self.num}")
debug(
f"regPing() {self.net}: sent ping '{sinst['pingmsg']}' to {sinst['entity']} - {self.num}"
)
return
else:
self.authenticated = True
@@ -719,7 +788,11 @@ class IRCBot(IRCClient):
self.channels.append(channel)
self.names(channel).addCallback(self.got_names)
if main.config["Toggles"]["Who"]:
reactor.callLater(main.config["Tweaks"]["Delays"]["WhoDelay"], self.setup_who_loop, channel)
reactor.callLater(
main.config["Tweaks"]["Delays"]["WhoDelay"],
self.setup_who_loop,
channel,
)
# lc = LoopingCall(self.who, channel)
# self._getWho[channel] = lc
# intrange = main.config["Tweaks"]["Delays"]["WhoRange"]
@@ -734,7 +807,9 @@ class IRCBot(IRCClient):
lc = self._getWho[channel]
lc.stop()
del self._getWho[channel]
userinfo.delChannels(self.net, [channel]) # < we do not need to deduplicate this
userinfo.delChannels(
self.net, [channel]
) # < we do not need to deduplicate this
# log("Can no longer cover %s, removing records" % channel)# as it will only be matched once --
# other bots have different nicknames so

View File

@@ -2,7 +2,6 @@ import logging
from json import dumps
import logstash
import main
logger = None

View File

@@ -19,7 +19,9 @@ def parseCommand(addr, authed, data):
incUsage = lambda mode: incorrectUsage(addr, mode) # noqa: E731
length = len(spl)
if spl[0] in main.CommandMap.keys():
main.CommandMap[spl[0]](addr, authed, data, obj, spl, success, failure, info, incUsage, length)
main.CommandMap[spl[0]](
addr, authed, data, obj, spl, success, failure, info, incUsage, length
)
return
incUsage(None)
return

View File

@@ -1,8 +1,7 @@
from json import dumps, loads
from twisted.internet.protocol import Factory, Protocol
import main
from twisted.internet.protocol import Factory, Protocol
from utils.logging.log import log, warn
validTypes = [
@@ -118,7 +117,9 @@ class Relay(Protocol):
parsed["hello"] == main.tokens[parsed["key"]]["hello"]
and main.tokens[parsed["key"]]["usage"] == "relay"
):
self.sendMsg({"type": "hello", "hello": main.tokens[parsed["key"]]["counter"]})
self.sendMsg(
{"type": "hello", "hello": main.tokens[parsed["key"]]["counter"]}
)
self.authed = True
else:
self.transport.loseConnection()
@@ -133,7 +134,10 @@ class Relay(Protocol):
def connectionLost(self, reason):
self.authed = False
log("Relay connection lost from %s:%s -- %s" % (self.addr.host, self.addr.port, reason.getErrorMessage()))
log(
"Relay connection lost from %s:%s -- %s"
% (self.addr.host, self.addr.port, reason.getErrorMessage())
)
if self.addr in main.relayConnections.keys():
del main.relayConnections[self.addr]
else:

View File

@@ -1,7 +1,6 @@
from twisted.internet.protocol import Factory, Protocol
import main
from core.parser import parseCommand
from twisted.internet.protocol import Factory, Protocol
from utils.logging.log import log, warn
@@ -34,7 +33,10 @@ class Server(Protocol):
def connectionLost(self, reason):
self.authed = False
log("Connection lost from %s:%s -- %s" % (self.addr.host, self.addr.port, reason.getErrorMessage()))
log(
"Connection lost from %s:%s -- %s"
% (self.addr.host, self.addr.port, reason.getErrorMessage())
)
if self.addr in main.connections.keys():
del main.connections[self.addr]
else: