1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2020 kaliko <kaliko@azylum.org>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, version 3 only.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 from datetime import datetime
19 from tempfile import mkstemp
22 from .plugin import Plugin, botcmd
28 The account running the bot need at least room moderation right to log
29 participants JIDs (fallback to nickname).
31 throttle_ts = int(time())-30
33 def __init__(self, bot):
34 Plugin.__init__(self, bot)
35 self.presence = list()
36 bot.add_event_handler("muc::%s::presence" %
37 self.bot.room, self.log_presence)
38 bot.add_event_handler("muc::%s::got_online" %
39 self.bot.room, self.log_online)
40 bot.add_event_handler("muc::%s::got_offline" %
41 self.bot.room, self.log_offline)
43 def _get_jid(self, pres):
44 nick = pres['muc']['nick']
45 jid = self.bot.plugin['xep_0045'].rooms[self.bot.room][nick]['jid']
47 self.log.debug('jid not found, is bot account moderating room?')
49 jid = jid.split('/')[0] # strip ressource
52 def log_online(self, pres):
53 nick = self._get_jid(pres)
54 self.log.info('got online: %s', nick)
55 self.presence.append((datetime.now(), 'online', nick))
57 def log_offline(self, pres):
58 nick = self._get_jid(pres)
59 self.log.info('got offline: %s', nick)
60 self.presence.append((datetime.now(), 'offline', nick))
62 def log_presence(self, pres):
63 nick = self._get_jid(pres)
64 self.log.debug('%s: %s', pres['muc']['nick'], pres['type'])
65 self.presence.append((datetime.now(), pres['type'], nick))
67 def _format_log(self):
68 log = [f'{d:%Y-%m-%d %H:%M}: {s:12} {n}' for d, s, n in self.presence]
72 def write(self, message, args):
74 **command** (hidden) ``!write`` : Writes log to file (use mktemp and return file location as MUC message)"""
75 delay = int(time()) - Log.throttle_ts
77 self.log.debug('throttling file creation')
78 self.reply(message, f'wait {30-delay}s')
80 log = self._format_log()
81 mode = {'mode': 'w', 'encoding': 'utf-8'}
82 prefix = self.bot.room.split('@')[0] + '_'
83 tmp = mkstemp(prefix=prefix, text=True)
84 self.log.info('Writing to %s', tmp[1])
85 with fdopen(tmp[0], **mode) as fileo:
87 Log.throttle_ts = int(time())
88 self.reply(message, tmp[1])
91 def dump(self, message, args):
92 """**command** (hidden) ``!dump`` : Dumps log as MUC message"""
93 self.reply(message, self._format_log())
97 # vim: ai ts=4 sw=4 sts=4 expandtab