]> kaliko git repositories - sid.git/blobdiff - sid/rtbl.py
Keep track of MUC participant in the sid.MUCBot
[sid.git] / sid / rtbl.py
index 44f5ca4bb0d11b26519df43f7a924204edd5c406..6b33344800fbbc0022d479d2af257171ab667c6d 100644 (file)
@@ -1,6 +1,5 @@
 # -*- coding: utf-8 -*-
-# SPDX-FileCopyrightText: 2014, 2020, 2023 kaliko <kaliko@azylum.org>
-# SPDX-FileCopyrightText: 2007-2012 Thomas Perl <thp.io/about>
+# SPDX-FileCopyrightText: 2023 kaliko <kaliko@azylum.org>
 # SPDX-License-Identifier: GPL-3.0-or-later
 """A Real Time Block List plugin"""
 
@@ -11,7 +10,7 @@ from slixmpp import JID
 from slixmpp.exceptions import XMPPError
 from slixmpp.xmlstream import tostring
 
-from .plugin import Plugin
+from .plugin import Plugin, botcmd
 
 
 def jid_to_sha256(jid: JID) -> str:
@@ -20,10 +19,13 @@ def jid_to_sha256(jid: JID) -> str:
 
 
 class BL:
-    """Plain object to keep track of block list items"""
+    """Plain object to keep track of block list items.
+    Only used in RTBL plugin."""
+    #: Initial seed to ease testing
+    init = {}
 
     def __init__(self, initial_bl):
-        self.sha256_jids: Dict[str, Optional[str]] = {}
+        self.sha256_jids: Dict[str, Optional[str]] = dict(BL.init)
         for item in initial_bl:
             self.insert_item(item)
 
@@ -59,9 +61,11 @@ class BL:
 
 
 class RTBL(Plugin):
-    """Spam guard for MUC
+    """Spam guard plugin for MUC.
     """
+    #: Pubsub server
     pubsub_server = 'example.org'
+    #: Pubsub server node to subscribe to
     node = 'muc_bans_sha256'
 
     def __init__(self, bot):
@@ -73,14 +77,14 @@ class RTBL(Plugin):
                 ('pubsub_retract', self._retract),
                 ('pubsub_publish', self._publish),
                 (f'muc::{self.bot.room}::presence', self.got_presence),
-                (f'muc::{self.bot.room}::got_offline', self.got_offline),
                 (f'muc::{self.bot.room}::got_online', self.got_online)
         ]
         self.add_handlers()
         self.bot = bot
-        self.participants = set()
         self.moderator = False
         self.blocklist: BL = None
+        self.hits = 0
+        self.presences = bot.muc_presences
 
     def _exit(self):
         self.rm_handlers()
@@ -106,6 +110,9 @@ class RTBL(Plugin):
         self.blocklist = BL(node_blocklist['pubsub']['items'])
         mess = f'Got {len(self.blocklist)} items in block list'
         self.log.info(mess)
+        # Are current participants in the block list
+        for jid in [pres['muc']['jid'] for pres in self.presences.values()]:
+            await self.rtbl_ban(jid)
 
     async def _create(self):
         """Try to create node"""
@@ -121,7 +128,7 @@ class RTBL(Plugin):
         self.log.debug('Retracted item %s from %s' % (
             msg['pubsub_event']['items']['retract']['id'],
             msg['pubsub_event']['items']['node']))
-        self.blocklist.retract_item(msg['pubsub_event']['items']['retract']['id'])
+        self.blocklist.retract_item(msg['pubsub_event']['items']['retract'])
 
     async def _publish(self, msg):
         """Handler receiving a publish item event."""
@@ -134,17 +141,17 @@ class RTBL(Plugin):
         else:
             self.log.debug('No item content')
             return
-        self.blocklist.insert_item(msg['pubsub_event']['items']['item']['id'])
+        self.blocklist.insert_item(msg['pubsub_event']['items']['item'])
         # Are current participants in the block list
-        for jid in self.participants:
-            self.rtbl_ban(jid)
+        for jid in [pres['muc']['jid'] for pres in self.presences.values()]:
+            await self.rtbl_ban(jid)
 
     async def rtbl_ban(self, jid):
         """Ban jid in RTBL"""
         if not self.moderator:
             return
-        if not self.blocklist:
-            self.log.debug("block list not populated yet")
+        if self.blocklist is None:
+            self.log.info('Not checking %s, block list not populated yet', jid)
             return
         if self.blocklist.check(jid):
             self.log.debug(f'About to ban {jid}')
@@ -152,16 +159,8 @@ class RTBL(Plugin):
             if reason is not None:
                 reason = f'rtbl {reason}'
             await self.ban(jid.bare, reason=reason)
-
-    def got_offline(self, pres):
-        """Handler method for laving MUC participants"""
-        fjid = pres['muc']['jid']
-        user = fjid if fjid.full else pres['muc']['nick']
-        try:
-            self.participants.remove(user)
-        except KeyError:
-            self.log.error('KeyError removing participant: "%s"', user)
-        self.log.debug(f'participants: -{user} (len:{len(self.participants)})')
+            self.hits += 1
+            self.log.info(f'{jid} banned!')
 
     def got_presence(self, pres):
         """Does bot have required permissions"""
@@ -179,10 +178,29 @@ class RTBL(Plugin):
     async def got_online(self, pres):
         """Handler method for new MUC participants"""
         fjid = pres['muc']['jid']
-        user = fjid if fjid.full else pres['muc']['nick']
-        self.participants.add(user)
-        self.log.debug(f'participants: +{user} (len:{len(self.participants)})')
+        nick = pres['muc']['nick']
+        user = fjid if fjid.full else nick
         await self.rtbl_ban(user)
 
+    @botcmd(name="rtbl-info")
+    def rtbl_info(self, rcv, _):
+        """Show RTBL info"""
+        if self.blocklist is None:
+            msg = 'Block list not populated yet'
+            self.log.warning(msg)
+            self.reply(rcv, msg)
+            return
+        msg = f'Got {len(self.blocklist)} items in {RTBL.pubsub_server}/{RTBL.node}'
+        if self.hits > 0:
+            msg+=f' (hits {self.hits})'
+        if not self.moderator:
+            msg+='\nBot has no moderator permissions!'
+        self.reply(rcv, msg)
+
+
+if __name__ == '__main__':
+    from .cli.rtbl import main
+    main()
+
 # VIM MODLINE
 # vim: ai ts=4 sw=4 sts=4 expandtab