wrapify. I don't feel like converting the db properly (i.e., using

data/Todo/<user>.db), so I'll leave alone the current db.
This commit is contained in:
James Vega 2004-12-15 18:43:09 +00:00
parent cedd6a2b59
commit cee0dc3463
2 changed files with 66 additions and 145 deletions

View File

@ -37,8 +37,6 @@ import supybot
__revision__ = "$Id$" __revision__ = "$Id$"
__author__ = supybot.authors.strike __author__ = supybot.authors.strike
import supybot.plugins as plugins
import glob import glob
import time import time
import getopt import getopt
@ -48,7 +46,8 @@ import os.path
import supybot.conf as conf import supybot.conf as conf
import supybot.ircdb as ircdb import supybot.ircdb as ircdb
import supybot.utils as utils import supybot.utils as utils
import supybot.privmsgs as privmsgs from supybot.commands import *
import supybot.plugins as plugins
import supybot.callbacks as callbacks import supybot.callbacks as callbacks
try: try:
@ -90,131 +89,81 @@ class Todo(callbacks.Privmsg):
def _shrink(self, s): def _shrink(self, s):
return utils.ellipsisify(s, 50) return utils.ellipsisify(s, 50)
def todo(self, irc, msg, args): def todo(self, irc, msg, args, user, taskid):
"""[<username>|<task id>] """[<username>|<task id>]
Retrieves a task for the given task id. If no task id is given, it Retrieves a task for the given task id. If no task id is given, it
will return a list of task ids that that user has added to their todo will return a list of task ids that that user has added to their todo
list. list.
""" """
arg = privmsgs.getArgs(args, required=0, optional=1)
userid = None
taskid = None
# Figure out what userid and taskid need to be set to (if anything) # Figure out what userid and taskid need to be set to (if anything)
if not arg:
pass
else:
try:
taskid = int(arg)
except ValueError:
try:
userid = ircdb.users.getUserId(arg)
except KeyError:
irc.errorInvalid('task id or username', arg)
return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
if not userid and not taskid: if not taskid:
try:
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
cursor.execute("""SELECT id, task FROM todo cursor.execute("""SELECT id, task FROM todo
WHERE userid = %s AND active = 1 WHERE userid = %s AND active = 1
ORDER BY priority, id""", id) ORDER BY priority, id""", user.id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.reply('You have no tasks in your todo list.') irc.reply('That user has no todos.')
return
L = ['#%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()]
if len(L) == 1:
s = 'Todo for %s: %s' % (user.name, L[0])
else: else:
L = ['#%s: %s' % (item[0], self._shrink(item[1])) s = 'Todos for %s: %s' % (user.name, utils.commaAndify(L))
for item in cursor.fetchall()] irc.reply(s)
irc.reply(utils.commaAndify(L))
else: else:
if userid: cursor.execute("""SELECT userid,priority,added_at,task,active
cursor.execute("""SELECT id, task FROM todo FROM todo WHERE id = %s""", taskid)
WHERE userid = %s AND active = 1 if cursor.rowcount == 0:
ORDER BY priority, id""", userid) irc.errorInvalid('task id', taskid)
if cursor.rowcount == 0: return
irc.reply('That user has no todos.') (userid, pri, added_at, task, active) = cursor.fetchone()
return # Construct and return the reply
L = ['#%s: %s' % (item[0], self._shrink(item[1])) user = plugins.getUserName(userid)
for item in cursor.fetchall()] if int(active):
if len(L) == 1: active = 'Active'
s = 'Todo for %s: %s' % (arg, L[0])
else:
s = 'Todos for %s: %s' % (arg, utils.commaAndify(L))
irc.reply(s)
else: else:
cursor.execute("""SELECT userid,priority,added_at,task,active active = 'Inactive'
FROM todo WHERE id = %s""", taskid) if pri:
if cursor.rowcount == 0: task += ', priority: %s' % pri
irc.errorInvalid('task id', taskid) added_at = time.strftime(conf.supybot.reply.format.time(),
return time.localtime(int(added_at)))
(userid, pri, added_at, task, active) = cursor.fetchone() s = "%s todo for %s: %s (Added at %s)" % \
# Construct and return the reply (active, user, task, added_at)
user = ircdb.users.getUser(userid) irc.reply(s)
if user is None: todo = wrap(todo, [first('otherUser', 'user'), additional(('id', 'task'))])
name = 'a removed user'
else:
name = user.name
if int(active):
active = 'Active'
else:
active = 'Inactive'
if pri:
task += ', priority: %s' % pri
added_at = time.strftime(conf.supybot.reply.format.time(),
time.localtime(int(added_at)))
s = "%s todo for %s: %s (Added at %s)" % \
(active, name, task, added_at)
irc.reply(s)
def add(self, irc, msg, args): def add(self, irc, msg, args, user, optlist, text, now):
"""[--priority=<num>] <text> """[--priority=<num>] <text>
Adds <text> as a task in your own personal todo list. The optional Adds <text> as a task in your own personal todo list. The optional
priority argument allows you to set a task as a high or low priority. priority argument allows you to set a task as a high or low priority.
Any integer is valid. Any integer is valid.
""" """
try:
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
(optlist, rest) = getopt.getopt(args, '', ['priority='])
priority = 0 priority = 0
for (option, arg) in optlist: for (option, arg) in optlist:
if option == '--priority': if option == 'priority':
try: priority = arg
priority = int(arg)
except ValueError, e:
irc.errorInvalid('priority', arg)
return
text = privmsgs.getArgs(rest)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
now = int(time.time())
cursor.execute("""INSERT INTO todo cursor.execute("""INSERT INTO todo
VALUES (NULL, %s, %s, %s, %s, 1)""", VALUES (NULL, %s, %s, %s, %s, 1)""",
priority, now, id, text) priority, now, user.id, text)
db.commit() db.commit()
cursor.execute("""SELECT id FROM todo cursor.execute("""SELECT id FROM todo
WHERE added_at=%s AND userid=%s""", now, id) WHERE added_at=%s AND userid=%s""", now, user.id)
todoId = cursor.fetchone()[0] todoId = cursor.fetchone()[0]
irc.replySuccess('(Todo #%s added)' % (todoId)) irc.replySuccess('(Todo #%s added)' % (todoId))
add = wrap(add, ['user', getopts({'priority': ('int', 'priority')}),
'text', 'now'])
def remove(self, irc, msg, args): def remove(self, irc, msg, args, user, tasks):
"""<task id> [<task id> ...] """<task id> [<task id> ...]
Removes <task id> from your personal todo list. Removes <task id> from your personal todo list.
""" """
try:
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
taskids = privmsgs.getArgs(args)
tasks = taskids.split()
#print 'Tasks: %s' % repr(tasks) #print 'Tasks: %s' % repr(tasks)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
@ -222,7 +171,7 @@ class Todo(callbacks.Privmsg):
for taskid in tasks: for taskid in tasks:
cursor.execute("""SELECT * FROM todo cursor.execute("""SELECT * FROM todo
WHERE id = %s AND userid = %s WHERE id = %s AND userid = %s
AND active = 1""", taskid, id) AND active = 1""", taskid, user.id)
#print 'Rowcount: %s' % cursor.rowcount #print 'Rowcount: %s' % cursor.rowcount
if cursor.rowcount == 0: if cursor.rowcount == 0:
invalid.append(taskid) invalid.append(taskid)
@ -242,43 +191,31 @@ class Todo(callbacks.Privmsg):
taskid) taskid)
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
remove = wrap(remove, ['user', many(('id', 'task'))])
_sqlTrans = string.maketrans('*?', '%_') _sqlTrans = string.maketrans('*?', '%_')
def search(self, irc, msg, args): def search(self, irc, msg, args, user, optlist, globs):
"""[--{regexp}=<value>] [<glob>] """[--{regexp}=<value>] [<glob> <glob> ...]
Searches the todos for tasks matching <glob>. If --regexp is given, Searches your todos for tasks matching <glob>. If --regexp is given,
its associated value is taken as a regexp and matched against the its associated value is taken as a regexp and matched against the
tasks. tasks.
""" """
try: if not optlist and not globs:
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
(optlist, rest) = getopt.getopt(args, '', ['regexp='])
if not optlist and not rest:
raise callbacks.ArgumentError raise callbacks.ArgumentError
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
criteria = ['userid=%s' % id, 'active=1'] criteria = ['userid=%s' % user.id, 'active=1']
formats = [] formats = []
predicateName = 'p' predicateName = 'p'
for (option, arg) in optlist: for (option, arg) in optlist:
if option == '--regexp': if option == 'regexp':
criteria.append('%s(task)' % predicateName) criteria.append('%s(task)' % predicateName)
try: def p(s, r=arg):
r = utils.perlReToPythonRe(arg)
except ValueError, e:
irc.errorInvalid('regular expression', arg)
return
def p(s, r=r):
return int(bool(r.search(s))) return int(bool(r.search(s)))
db.create_function(predicateName, 1, p) db.create_function(predicateName, 1, p)
predicateName += 'p' predicateName += 'p'
for glob in rest: for glob in globs:
criteria.append('task LIKE %s') criteria.append('task LIKE %s')
if '?' not in glob and '*' not in glob:
glob = '*%s*' % glob
formats.append(glob.translate(self._sqlTrans)) formats.append(glob.translate(self._sqlTrans))
cursor = db.cursor() cursor = db.cursor()
sql = """SELECT id, task FROM todo WHERE %s""" % ' AND '.join(criteria) sql = """SELECT id, task FROM todo WHERE %s""" % ' AND '.join(criteria)
@ -289,65 +226,49 @@ class Todo(callbacks.Privmsg):
tasks = ['#%s: %s' % (item[0], self._shrink(item[1])) tasks = ['#%s: %s' % (item[0], self._shrink(item[1]))
for item in cursor.fetchall()] for item in cursor.fetchall()]
irc.reply(utils.commaAndify(tasks)) irc.reply(utils.commaAndify(tasks))
search = wrap(search,
['user', getopts({'regexp': 'regexpMatcher'}), any('glob')])
def setpriority(self, irc, msg, args): def setpriority(self, irc, msg, args, user, id, priority):
"""<id> <priority> """<id> <priority>
Sets the priority of the todo with the given id to the specified value. Sets the priority of the todo with the given id to the specified value.
""" """
try:
user_id = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
(id, priority) = privmsgs.getArgs(args, required=2)
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT userid, priority FROM todo cursor.execute("""SELECT userid, priority FROM todo
WHERE id = %s AND active = 1""", id) WHERE id = %s AND active = 1""", id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.error('No note with id %s' % id) irc.error('No note with id %s' % id, Raise=True)
return
(userid, oldpriority) = cursor.fetchone() (userid, oldpriority) = cursor.fetchone()
if userid != user_id: if userid != user.id:
irc.error('Todo #%s does not belong to you.' % id) irc.error('Todo #%s does not belong to you.' % id, Raise=True)
return
# If we make it here, we're okay # If we make it here, we're okay
cursor.execute("""UPDATE todo SET priority = %s cursor.execute("""UPDATE todo SET priority = %s
WHERE id = %s""", priority, id) WHERE id = %s""", priority, id)
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
setpriority = wrap(setpriority,
['user', ('id', 'task'), ('int', 'priority')])
def change(self, irc, msg, args): def change(self, irc, msg, args, user, id, replacer):
"""<task id> <regexp> """<task id> <regexp>
Modify the task with the given id using the supplied regexp. Modify the task with the given id using the supplied regexp.
""" """
try:
userid = ircdb.users.getUserId(msg.prefix)
except KeyError:
irc.errorNotRegistered()
return
taskid, regexp = privmsgs.getArgs(args, required=2)
# Check the regexp first, it's easier and doesn't require a db query
try:
replacer = utils.perlReToReplacer(regexp)
except ValueError:
irc.errorInvalid('regexp', regexp)
return
db = self.dbHandler.getDb() db = self.dbHandler.getDb()
cursor = db.cursor() cursor = db.cursor()
cursor.execute("""SELECT task FROM todo cursor.execute("""SELECT task FROM todo
WHERE userid = %s AND id = %s WHERE userid = %s AND id = %s
AND active = 1""", userid, taskid) AND active = 1""", user.id, id)
if cursor.rowcount == 0: if cursor.rowcount == 0:
irc.errorInvalid('task id', taskid) irc.errorInvalid('task id', id)
return
newtext = replacer(cursor.fetchone()[0]) newtext = replacer(cursor.fetchone()[0])
cursor.execute("""UPDATE todo SET task = %s cursor.execute("""UPDATE todo SET task = %s
WHERE id = %s""", newtext, taskid) WHERE id = %s""", newtext, id)
db.commit() db.commit()
irc.replySuccess() irc.replySuccess()
change = wrap(change, ['user', ('id', 'task'), 'regexpReplacer'])
Class = Todo Class = Todo

View File

@ -50,10 +50,10 @@ if sqlite is not None:
def testTodo(self): def testTodo(self):
# Should not error, but no tasks yet. # Should not error, but no tasks yet.
self.assertNotError('todo') self.assertNotError('todo')
self.assertResponse('todo', 'You have no tasks in your todo list.') self.assertRegexp('todo', 'has no Todos')
# Add a task # Add a task
self.assertNotError('todo add wash my car') self.assertNotError('todo add wash my car')
self.assertResponse('todo', '#1: wash my car') self.assertRegexp('todo', '#1: wash my car')
# Check that task # Check that task
self.assertRegexp('todo 1', self.assertRegexp('todo 1',
'Todo for tester: wash my car \(Added .*?\)') 'Todo for tester: wash my car \(Added .*?\)')
@ -71,7 +71,7 @@ if sqlite is not None:
# Check priority sorting # Check priority sorting
self.assertNotError('todo setpriority 1 100') self.assertNotError('todo setpriority 1 100')
self.assertNotError('todo setpriority 2 10') self.assertNotError('todo setpriority 2 10')
self.assertResponse('todo', '#2: moo and #1: wash my car') self.assertRegexp('todo', '#2: moo and #1: wash my car')
def testAddtodo(self): def testAddtodo(self):
self.assertNotError('todo add code a new plugin') self.assertNotError('todo add code a new plugin')