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 throttle_ts = int(time())-30
30 def __init__(self, bot):
31 Plugin.__init__(self, bot)
32 self.presence = list()
33 bot.add_event_handler("muc::%s::presence" %
34 self.bot.room, self.log_presence)
35 bot.add_event_handler("muc::%s::got_online" %
36 self.bot.room, self.log_online)
37 bot.add_event_handler("muc::%s::got_offline" %
38 self.bot.room, self.log_offline)
40 def _get_jid(self, pres):
41 nick = pres['muc']['nick']
42 jid = self.bot.plugin['xep_0045'].rooms[self.bot.room][nick]['jid']
44 self.log.debug('jid not found, is bot account moderating room?')
46 jid = jid.split('/')[0] # strip ressource
49 def log_online(self, pres):
50 nick = self._get_jid(pres)
51 self.log.info('got online: %s', nick)
52 self.presence.append((datetime.now(), 'online', nick))
54 def log_offline(self, pres):
55 nick = self._get_jid(pres)
56 self.log.info('got offline: %s', nick)
57 self.presence.append((datetime.now(), 'offline', nick))
59 def log_presence(self, pres):
60 nick = self._get_jid(pres)
61 self.log.debug('%s: %s', pres['muc']['nick'], pres['type'])
62 self.presence.append((datetime.now(), pres['type'], nick))
64 def _format_log(self):
65 log = [f'{d:%Y-%m-%d %H:%M}: {s:12} {n}' for d, s, n in self.presence]
69 def write(self, message, args):
71 **command** ``!write`` : Write log to file"""
72 delay = int(time()) - Log.throttle_ts
74 self.log.debug('throttling file creation')
75 self.reply(message, f'wait {30-delay}s')
77 log = self._format_log()
78 mode = {'mode': 'w', 'encoding': 'utf-8'}
79 prefix = self.bot.room.split('@')[0] + '_'
80 tmp = mkstemp(prefix=prefix, text=True)
81 self.log.info('Writing to %s', tmp[1])
82 with fdopen(tmp[0], **mode) as fileo:
84 Log.throttle_ts = int(time())
85 self.reply(message, tmp[1])
88 def dump(self, message, args):
89 """**command** ``!dump`` : dump log online!"""
90 self.reply(message, self._format_log())
94 # vim: ai ts=4 sw=4 sts=4 expandtab