]> kaliko git repositories - sid.git/blob - sid/log.py
Bump version
[sid.git] / sid / log.py
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2020 kaliko <kaliko@azylum.org>
4
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.
8
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.
13
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/>.
16
17 from datetime import datetime
18 from os import fdopen
19 from tempfile import mkstemp
20 from time import time
21
22 from .plugin import Plugin, botcmd
23
24
25 class Log(Plugin):
26     """Logs group chat participant presence.
27
28     The account running the bot need at least room moderation right to log
29     participants JIDs (fallback to nickname).
30     """
31     throttle_ts = int(time())-30
32
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)
42
43     def _get_jid(self, pres):
44         nick = pres['muc']['nick']
45         jid = self.bot.plugin['xep_0045'].rooms[self.bot.room][nick]['jid']
46         if not jid:
47             self.log.debug('jid not found, is bot account moderating room?')
48             return nick
49         jid = jid.split('/')[0]  # strip ressource
50         return jid
51
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))
56
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))
61
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))
66
67     def _format_log(self):
68         log = [f'{d:%Y-%m-%d %H:%M}: {s:12} {n}' for d, s, n in self.presence]
69         return '\n'.join(log)
70
71     @botcmd(hidden=True)
72     def write(self, message, args):
73         """Dump/save room presences log
74
75         ``!write`` : Writes log to file (use mktemp and return file location as MUC message)"""
76         delay = int(time()) - Log.throttle_ts
77         if delay < 30:
78             self.log.debug('throttling file creation')
79             self.reply(message, f'wait {30-delay}s')
80             return
81         log = self._format_log()
82         mode = {'mode': 'w', 'encoding': 'utf-8'}
83         prefix = self.bot.room.split('@')[0] + '_'
84         tmp = mkstemp(prefix=prefix, text=True)
85         self.log.info('Writing to %s', tmp[1])
86         with fdopen(tmp[0], **mode) as fileo:
87             fileo.writelines(log)
88             Log.throttle_ts = int(time())
89         self.reply(message, tmp[1])
90
91     @botcmd(hidden=True)
92     def dump(self, message, args):
93         """``!dump``  : Dumps log as MUC message"""
94         self.reply(message, self._format_log())
95
96
97 # VIM MODLINE
98 # vim: ai ts=4 sw=4 sts=4 expandtab