Limnoria/plugins/Note.py

459 lines
17 KiB
Python
Raw Normal View History

###
2004-08-26 09:42:58 +02:00
# Copyright (c) 2004, Brett Kelly
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
2003-04-08 09:07:54 +02:00
"""
A complete messaging system that allows users to leave 'notes' for other
users that can be retrieved later.
"""
2003-11-25 09:23:47 +01:00
__revision__ = "$Id$"
import re
import time
import fnmatch
2004-08-11 07:14:15 +02:00
import operator
2004-08-11 07:14:15 +02:00
import supybot.dbi as dbi
import supybot.log as log
2004-07-24 07:18:26 +02:00
import supybot.conf as conf
import supybot.utils as utils
import supybot.ircdb as ircdb
2004-10-26 23:07:53 +02:00
from supybot.commands import *
2004-07-24 07:18:26 +02:00
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
2003-04-08 09:07:54 +02:00
conf.registerPlugin('Note')
2004-08-17 00:43:10 +02:00
conf.registerGroup(conf.supybot.plugins.Note, 'notify')
conf.registerGlobalValue(conf.supybot.plugins.Note.notify, 'onJoin',
registry.Boolean(False, """Determines whether the bot will notify people of
their new messages when they join the channel. Normally it will notify
them when they send a message to the channel, since oftentimes joins are
the result of netsplits and not the actual presence of the user."""))
2004-08-17 00:43:10 +02:00
conf.registerGlobalValue(conf.supybot.plugins.Note.notify.onJoin, 'repeatedly',
registry.Boolean(False, """Determines whether the bot will repeatedly
notify people of their new messages when they join the channel. That means
when they join the channel, the bot will tell them they have unread
messages, even if it's told them before."""))
2004-08-17 00:43:10 +02:00
conf.registerGlobalValue(conf.supybot.plugins.Note.notify, 'autoSend',
registry.NonNegativeInteger(0, """Determines the upper limit for
automatically sending messages instead of notifications. I.e., if this
value is 2 and there are 2 new messages to notify a user about, instead of
sending a notification message, the bot will simply send those new messages.
If there are 3 new messages, however, the bot will send a notification
message."""))
2004-04-30 21:19:59 +02:00
class Ignores(registry.SpaceSeparatedListOfStrings):
List = ircutils.IrcSet
class NoteRecord(dbi.Record):
__fields__ = [
'frm',
'to',
'at',
'notified',
'read',
'public',
'text',
]
2004-08-11 07:14:15 +02:00
class DbiNoteDB(dbi.DB):
Mapping = 'flat'
Record = NoteRecord
2004-08-07 02:41:55 +02:00
def __init__(self, *args, **kwargs):
dbi.DB.__init__(self, *args, **kwargs)
self.unRead = {}
self.unNotified = {}
for record in self:
self._addCache(record)
def _addCache(self, record):
if not record.read:
self.unRead.setdefault(record.to, []).append(record.id)
if not record.notified:
self.unNotified.setdefault(record.to, []).append(record.id)
def _removeCache(self, record):
if record.notified:
try:
self.unNotified[record.to].remove(record.id)
except (KeyError, ValueError):
pass
if record.read:
try:
self.unRead[record.to].remove(record.id)
except (KeyError, ValueError):
pass
2004-08-07 02:41:55 +02:00
def setRead(self, id):
2004-08-11 07:14:15 +02:00
n = self.get(id)
2004-08-07 02:41:55 +02:00
n.read = True
n.notified = True
self._removeCache(n)
2004-08-11 07:14:15 +02:00
self.set(id, n)
2004-08-07 02:41:55 +02:00
def setNotified(self, id):
2004-08-11 07:14:15 +02:00
n = self.get(id)
2004-08-07 02:41:55 +02:00
n.notified = True
self._removeCache(n)
2004-08-11 07:14:15 +02:00
self.set(id, n)
2004-08-07 02:41:55 +02:00
def getUnnotifiedIds(self, to):
## def p(note):
## return not note.notified and note.to == to
## return [note.id for note in self.select(p)]
return self.unNotified.get(to, [])
2004-08-07 02:41:55 +02:00
def getUnreadIds(self, to):
## def p(note):
## return not note.read and note.to == to
## return [note.id for note in self.select(p)]
return self.unRead.get(to, [])
2004-08-11 07:14:15 +02:00
def send(self, frm, to, public, text):
n = self.Record(frm=frm, to=to, text=text,
at=time.time(), public=public)
id = self.add(n)
self._addCache(n)
return id
2004-09-22 23:29:23 +02:00
def unsend(self, id):
self.remove(id)
for cache in self.unRead, self.unNotified:
for (to, ids) in cache.items():
while id in ids:
ids.remove(id)
2004-09-11 22:24:52 +02:00
NoteDB = plugins.DB('Note', {'flat': DbiNoteDB})
2004-08-07 02:41:55 +02:00
class Note(callbacks.Privmsg):
def __init__(self):
2004-09-20 01:51:21 +02:00
self.__parent= super(Note, self)
self.__parent.__init__()
2004-08-07 02:41:55 +02:00
self.db = NoteDB()
def die(self):
2004-09-20 01:51:21 +02:00
self.__parent.die()
2004-08-07 02:41:55 +02:00
self.db.close()
2003-08-20 18:26:23 +02:00
def doPrivmsg(self, irc, msg):
self._notify(irc, msg)
def doJoin(self, irc, msg):
2004-08-17 00:43:10 +02:00
if self.registryValue('notify.onJoin'):
repeatedly = self.registryValue('notify.onJoin.repeatedly')
self._notify(irc, msg, repeatedly)
def _notify(self, irc, msg, repeatedly=False):
2004-09-01 12:57:17 +02:00
irc = callbacks.SimpleProxy(irc, msg)
try:
2004-08-07 02:41:55 +02:00
to = ircdb.users.getUserId(msg.prefix)
except KeyError:
return
2004-08-17 00:43:10 +02:00
ids = self.db.getUnnotifiedIds(to)
if len(ids) <= self.registryValue('notify.autoSend'):
for id in ids:
s = '#%s: %s' % (id, self._formatNote(self.db.get(id), to))
irc.reply(s, private=True)
2004-08-17 00:43:10 +02:00
self.db.setRead(id)
return
unnotifiedIds = ['#%s' % nid for nid in ids]
unnotified = len(unnotifiedIds)
2004-08-07 02:41:55 +02:00
if unnotified or repeatedly:
unreadIds = ['#%s' % nid for nid in self.db.getUnreadIds(to)]
unread = len(unreadIds)
s = 'You have %s; %s that I haven\'t told you about before now. '\
'%s %s still unread.' % \
(utils.nItems('note', unread, 'unread'), unnotified,
utils.commaAndify(unreadIds), utils.be(unread))
2004-08-17 00:43:10 +02:00
# Later we'll have a user value for allowing this to be a NOTICE.
2004-09-01 12:57:17 +02:00
irc.reply(s, private=True)
2004-08-07 02:41:55 +02:00
for nid in unnotifiedIds:
id = int(nid[1:])
self.db.setNotified(id)
2004-08-07 02:41:55 +02:00
def _getUserId(self, irc, name):
if ircdb.users.hasUser(name):
2004-07-20 09:03:15 +02:00
return ircdb.users.getUserId(name)
else:
2003-09-14 04:43:17 +02:00
try:
hostmask = irc.state.nickToHostmask(name)
2004-07-20 09:03:15 +02:00
return ircdb.users.getUserId(hostmask)
2003-09-14 04:43:17 +02:00
except KeyError:
2004-07-20 09:03:15 +02:00
return None
2004-10-26 23:07:53 +02:00
def send(self, irc, msg, args, user, targets, text):
2004-07-20 09:03:15 +02:00
"""<recipient>,[<recipient>,[...]] <text>
Sends a new note to the user specified. Multiple recipients may be
2004-10-26 23:07:53 +02:00
specified by separating their names by commas.
2004-07-20 09:03:15 +02:00
"""
# Let's get the from user.
public = irc.isChannel(msg.args[0])
2004-07-20 09:03:15 +02:00
sent = []
2004-10-26 23:07:53 +02:00
for target in targets:
id = self.db.send(user.id, target.id, public, text)
s = 'note #%s sent to %s' % (id, target.name)
2004-07-20 09:03:15 +02:00
sent.append(s)
irc.reply(utils.commaAndify(sent).capitalize() + '.')
2004-10-26 23:07:53 +02:00
send = wrap(send, ['user', commalist('otherUser'), 'text'])
2004-10-26 23:07:53 +02:00
def reply(self, irc, msg, args, user, id, text):
2004-08-08 18:50:09 +02:00
"""<id> <text>
Sends a note in reply to <id>.
"""
2004-10-26 23:07:53 +02:00
try:
note = self.db.get(id)
except KeyError:
irc.error('That\'s not a note in my database.', Raise=True)
if note.to != user.id:
irc.error('You may only reply to notes '
'that have been sent to you.', Raise=True)
2004-08-08 18:50:09 +02:00
self.db.setRead(id)
2004-10-26 23:07:53 +02:00
text += ' (in reply to #%s)' % id
public = irc.isChannel(msg.args[0])
2004-08-08 18:50:09 +02:00
try:
2004-10-26 23:07:53 +02:00
target = ircdb.users.getUser(note.frm)
2004-08-08 18:50:09 +02:00
except KeyError:
2004-10-26 23:07:53 +02:00
irc.error('The user who sent you that note '
'is no longer in my user database.', Raise=True)
id = self.db.send(user.id, note.frm, public, text)
irc.reply('Note #%s sent to %s.' % (id, target.name))
reply = wrap(reply, ['user', ('id', 'note'), 'text'])
2004-08-08 18:50:09 +02:00
2004-10-26 23:07:53 +02:00
def unsend(self, irc, msg, args, user, id):
2003-12-03 22:00:56 +01:00
"""<id>
Unsends the note with the id given. You must be the
author of the note, and it must be unread.
"""
2004-08-07 02:41:55 +02:00
note = self.db.get(id)
2004-10-26 23:07:53 +02:00
if note.frm == user.id:
2004-08-07 02:41:55 +02:00
if not note.read:
2004-09-22 23:29:23 +02:00
self.db.unsend(id)
irc.replySuccess()
2003-12-03 22:00:56 +01:00
else:
irc.error('That note has been read already.')
2003-12-03 22:00:56 +01:00
else:
irc.error('That note wasn\'t sent by you.')
2004-10-26 23:07:53 +02:00
unsend = wrap(unsend, ['user', ('id', 'note')])
2004-08-17 00:43:10 +02:00
def _formatNote(self, note, to):
elapsed = utils.timeElapsed(time.time() - note.at)
if note.to == to:
author = plugins.getUserName(note.frm)
2004-08-17 00:43:10 +02:00
return '%s (Sent by %s %s ago)' % (note.text, author, elapsed)
else:
assert note.frm == to, 'Odd, userid isn\'t frm either.'
recipient = plugins.getUserName(note.to)
2004-08-17 00:43:10 +02:00
return '%s (Sent to %s %s ago)' % (note.text, recipient, elapsed)
2004-10-26 23:07:53 +02:00
def note(self, irc, msg, args, user, id):
"""<id>
2003-08-20 18:26:23 +02:00
2004-06-25 16:14:39 +02:00
Retrieves a single note by its unique note id. Use the 'note list'
command to see what unread notes you have.
2003-04-08 09:07:54 +02:00
"""
try:
2004-08-07 02:41:55 +02:00
note = self.db.get(id)
except KeyError:
irc.error('That\'s not a valid note id.')
return
2004-10-26 23:07:53 +02:00
if user.id != note.frm and user.id != note.to:
s = 'You may only retrieve notes you\'ve sent or received.'
irc.error(s)
2003-04-14 17:10:38 +02:00
return
2004-10-26 23:07:53 +02:00
newnote = self._formatNote(note, user.id)
2004-08-07 02:41:55 +02:00
irc.reply(newnote, private=(not note.public))
self.db.setRead(id)
2004-10-26 23:07:53 +02:00
note = wrap(note, ['user', ('id', 'note')])
2004-08-11 07:14:15 +02:00
def _formatNoteId(self, msg, note, sent=False):
if note.public or not ircutils.isChannel(msg.args[0]):
2004-08-07 02:41:55 +02:00
if sent:
sender = plugins.getUserName(note.to)
2004-08-11 07:14:15 +02:00
return '#%s to %s' % (note.id, sender)
2004-08-07 02:41:55 +02:00
else:
sender = plugins.getUserName(note.frm)
2004-08-11 07:14:15 +02:00
return '#%s from %s' % (note.id, sender)
2004-08-07 02:41:55 +02:00
else:
2004-08-11 07:14:15 +02:00
return '#%s (private)' % note.id
2004-08-07 02:41:55 +02:00
def search(self, irc, msg, args, user, optlist, glob):
"""[--{regexp} <value>] [--sent] [<glob>]
Searches your received notes for ones matching <glob>. If --regexp is
given, its associated value is taken as a regexp and matched against
the notes. If --sent is specified, only search sent notes.
"""
criteria = []
def to(note):
return note.to == user.id
def frm(note):
return note.frm == user.id
own = to
for (option, arg) in optlist:
if option == 'regexp':
criteria.append(arg.search)
elif option == 'sent':
own = frm
if glob:
glob = fnmatch.translate(glob)
# ignore the trailing $ fnmatch.translate adds to the regexp
criteria.append(re.compile(glob[:-1]).search)
def match(note):
for p in criteria:
if not p(note.text):
return False
return True
notes = list(self.db.select(lambda n: match(n) and own(n)))
if not notes:
irc.reply('No matching notes were found.')
else:
utils.sortBy(operator.attrgetter('id'), notes)
ids = [self._formatNoteId(msg, note) for note in notes]
ids = self._condense(ids)
irc.reply(utils.commaAndify(ids))
search = wrap(search,
['user', getopts({'regexp': ('regexpMatcher', True),
'sent': ''}),
additional('glob')])
2004-10-26 23:07:53 +02:00
def list(self, irc, msg, args, user, optlist):
"""[--{old,sent}] [--{from,to} <user>]
2003-08-20 18:26:23 +02:00
Retrieves the ids of all your unread notes. If --old is given, list
read notes. If --sent is given, list notes that you have sent. If
--from is specified, only lists notes sent to you from <user>. If
--to is specified, only lists notes sent by you to <user>.
2003-04-08 11:11:33 +02:00
"""
2004-10-26 23:07:53 +02:00
(sender, receiver, old, sent) = (None, None, False, False)
for (option, arg) in optlist:
2004-10-26 23:07:53 +02:00
if option == 'old':
old = True
2004-10-26 23:07:53 +02:00
if option == 'sent':
sent = True
2004-10-26 23:07:53 +02:00
if option == 'from':
sender = arg
2004-10-26 23:07:53 +02:00
if option == 'to':
receiver = arg
sent = True
if old:
return self._oldnotes(irc, msg, sender)
if sent:
return self._sentnotes(irc, msg, receiver)
2004-08-07 02:41:55 +02:00
def p(note):
2004-10-26 23:07:53 +02:00
return not note.read and note.to == user.id
if sender:
2004-10-26 23:07:53 +02:00
originalP = p
def p(note):
return originalP(note) and note.frm == sender.id
2004-08-11 07:14:15 +02:00
notes = list(self.db.select(p))
if not notes:
irc.reply('You have no unread notes.')
else:
2004-08-11 07:14:15 +02:00
utils.sortBy(operator.attrgetter('id'), notes)
ids = [self._formatNoteId(msg, note) for note in notes]
ids = self._condense(ids)
irc.reply(utils.commaAndify(ids))
2004-10-26 23:07:53 +02:00
list = wrap(list, ['user', getopts({'old': '', 'sent': '',
'from': 'otherUser',
'to': 'otherUser'})])
def _condense(self, notes):
temp = {}
for note in notes:
note = note.split(' ', 1)
if note[1] in temp:
temp[note[1]].append(note[0])
else:
temp[note[1]] = [note[0]]
notes = []
for (k,v) in temp.iteritems():
if '(private)' in k:
k = k.replace('(private)', '%s private' % utils.be(len(v)))
2004-02-17 03:41:09 +01:00
notes.append('%s %s' % (utils.commaAndify(v), k))
return notes
def _sentnotes(self, irc, msg, receiver):
try:
2004-10-26 23:07:53 +02:00
user = ircdb.users.getUser(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
2004-08-07 02:41:55 +02:00
def p(note):
2004-10-26 23:07:53 +02:00
return note.frm == user.id
if receiver:
2004-08-07 02:41:55 +02:00
originalP = p
def p(note):
return originalP(note) and note.to == receiver.id
2004-08-11 07:14:15 +02:00
notes = list(self.db.select(p))
if not notes:
2004-08-07 02:41:55 +02:00
irc.error('I couldn\'t find any sent notes for your user.')
else:
2004-08-11 07:14:15 +02:00
utils.sortBy(operator.attrgetter('id'), notes)
notes.reverse() # Most recently sent first.
ids = [self._formatNoteId(msg, note, sent=True) for note in notes]
ids = self._condense(ids)
irc.reply(utils.commaAndify(ids))
def _oldnotes(self, irc, msg, sender):
try:
2004-10-26 23:07:53 +02:00
user = ircdb.users.getUser(msg.prefix)
except KeyError:
2004-01-08 22:49:10 +01:00
irc.errorNotRegistered()
return
2004-08-07 02:41:55 +02:00
def p(note):
2004-10-26 23:07:53 +02:00
return note.to == user.id and note.read
if sender:
2004-08-07 02:41:55 +02:00
originalP = p
def p(note):
2004-10-26 23:07:53 +02:00
return originalP(note) and note.frm == sender.id
2004-08-11 07:14:15 +02:00
notes = list(self.db.select(p))
if not notes:
2004-08-07 02:41:55 +02:00
irc.reply('I couldn\'t find any matching read notes for your user.')
else:
2004-08-11 07:14:15 +02:00
utils.sortBy(operator.attrgetter('id'), notes)
notes.reverse()
ids = [self._formatNoteId(msg, note) for note in notes]
ids = self._condense(ids)
irc.reply(utils.commaAndify(ids))
2003-08-20 18:26:23 +02:00
Class = Note
2003-04-08 09:07:54 +02:00
# vim: shiftwidth=4 tabstop=8 expandtab textwidth=78: