2005-01-19 14:14:38 +01:00
|
|
|
###
|
2005-01-19 14:33:05 +01:00
|
|
|
# Copyright (c) 2002-2005, Jeremiah Fincher
|
2015-02-19 03:35:57 +01:00
|
|
|
# Copyright (c) 2009-2010,2015, James McCoy
|
2005-01-19 14:14:38 +01:00
|
|
|
# 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.
|
|
|
|
###
|
|
|
|
|
|
|
|
"""
|
|
|
|
Includes wrappers for commands.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import time
|
|
|
|
import getopt
|
2005-02-07 02:04:33 +01:00
|
|
|
import inspect
|
2005-01-19 14:14:38 +01:00
|
|
|
import threading
|
2010-08-05 07:20:46 +02:00
|
|
|
import multiprocessing #python2.6 or later!
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2013-08-09 12:01:40 +02:00
|
|
|
try:
|
|
|
|
import resource
|
|
|
|
except ImportError: # Windows!
|
|
|
|
resource = None
|
|
|
|
|
2015-08-11 16:50:23 +02:00
|
|
|
from . import callbacks, conf, ircdb, ircmsgs, ircutils, log, \
|
2015-08-08 23:01:02 +02:00
|
|
|
utils, world
|
2015-08-11 16:50:23 +02:00
|
|
|
from .utils import minisix
|
2013-08-24 11:28:29 +02:00
|
|
|
from .i18n import PluginInternationalization, internationalizeDocstring
|
2010-10-20 18:27:58 +02:00
|
|
|
_ = PluginInternationalization()
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
###
|
|
|
|
# Non-arg wrappers -- these just change the behavior of a command without
|
|
|
|
# changing the arguments given to it.
|
|
|
|
###
|
|
|
|
|
|
|
|
# Thread has to be a non-arg wrapper because by the time we're parsing and
|
|
|
|
# validating arguments, we're inside the function we'd want to thread.
|
|
|
|
def thread(f):
|
|
|
|
"""Makes sure a command spawns a thread when called."""
|
|
|
|
def newf(self, irc, msg, args, *L, **kwargs):
|
|
|
|
if world.isMainThread():
|
2005-02-17 23:39:44 +01:00
|
|
|
targetArgs = (self.callingCommand, irc, msg, args) + tuple(L)
|
|
|
|
t = callbacks.CommandThread(target=self._callCommand,
|
|
|
|
args=targetArgs, kwargs=kwargs)
|
2005-01-19 14:14:38 +01:00
|
|
|
t.start()
|
|
|
|
else:
|
|
|
|
f(self, irc, msg, args, *L, **kwargs)
|
2014-01-21 10:40:18 +01:00
|
|
|
return utils.python.changeFunctionName(newf, f.__name__, f.__doc__)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2011-08-12 22:28:50 +02:00
|
|
|
class ProcessTimeoutError(Exception):
|
|
|
|
"""Gets raised when a process is killed due to timeout."""
|
|
|
|
pass
|
|
|
|
|
|
|
|
def process(f, *args, **kwargs):
|
|
|
|
"""Runs a function <f> in a subprocess.
|
|
|
|
|
|
|
|
Several extra keyword arguments can be supplied.
|
|
|
|
<pn>, the pluginname, and <cn>, the command name, are strings used to
|
|
|
|
create the process name, for identification purposes.
|
|
|
|
<timeout>, if supplied, limits the length of execution of target
|
|
|
|
function to <timeout> seconds."""
|
|
|
|
timeout = kwargs.pop('timeout', None)
|
2013-08-09 12:21:24 +02:00
|
|
|
heap_size = kwargs.pop('heap_size', None)
|
|
|
|
if resource and heap_size is None:
|
|
|
|
heap_size = resource.RLIM_INFINITY
|
2013-04-11 19:09:50 +02:00
|
|
|
|
2014-08-14 14:16:15 +02:00
|
|
|
if world.disableMultiprocessing:
|
2013-04-11 19:09:50 +02:00
|
|
|
pn = kwargs.pop('pn', 'Unknown')
|
|
|
|
cn = kwargs.pop('cn', 'unknown')
|
|
|
|
try:
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
except Exception as e:
|
2013-08-09 17:48:53 +02:00
|
|
|
raise e
|
2011-08-12 22:28:50 +02:00
|
|
|
|
2013-08-12 19:08:31 +02:00
|
|
|
try:
|
|
|
|
q = multiprocessing.Queue()
|
|
|
|
except OSError:
|
|
|
|
log.error('Using multiprocessing.Queue raised an OSError.\n'
|
|
|
|
'This is probably caused by your system denying semaphore\n'
|
|
|
|
'usage. You should run these two commands:\n'
|
|
|
|
'\tsudo rmdir /dev/shm\n'
|
|
|
|
'\tsudo ln -Tsf /{run,dev}/shm\n'
|
|
|
|
'(See https://github.com/travis-ci/travis-core/issues/187\n'
|
2014-07-31 19:51:44 +02:00
|
|
|
'for more information about this bug.)\n')
|
2013-08-12 19:08:31 +02:00
|
|
|
raise
|
2011-08-12 22:28:50 +02:00
|
|
|
def newf(f, q, *args, **kwargs):
|
2013-08-09 12:01:40 +02:00
|
|
|
if resource:
|
|
|
|
rsrc = resource.RLIMIT_DATA
|
|
|
|
resource.setrlimit(rsrc, (heap_size, heap_size))
|
2011-08-12 22:28:50 +02:00
|
|
|
try:
|
|
|
|
r = f(*args, **kwargs)
|
|
|
|
q.put(r)
|
|
|
|
except Exception as e:
|
|
|
|
q.put(e)
|
|
|
|
targetArgs = (f, q,) + args
|
|
|
|
p = callbacks.CommandProcess(target=newf,
|
|
|
|
args=targetArgs, kwargs=kwargs)
|
|
|
|
p.start()
|
|
|
|
p.join(timeout)
|
|
|
|
if p.is_alive():
|
|
|
|
p.terminate()
|
2014-08-14 14:18:47 +02:00
|
|
|
q.close()
|
2014-01-20 15:43:55 +01:00
|
|
|
raise ProcessTimeoutError("%s aborted due to timeout." % (p.name,))
|
2011-08-12 22:28:50 +02:00
|
|
|
try:
|
|
|
|
v = q.get(block=False)
|
2015-08-10 17:55:25 +02:00
|
|
|
except minisix.queue.Empty:
|
2013-08-09 12:01:40 +02:00
|
|
|
return None
|
2014-08-14 14:18:47 +02:00
|
|
|
finally:
|
|
|
|
q.close()
|
2011-08-12 22:28:50 +02:00
|
|
|
if isinstance(v, Exception):
|
2013-08-09 12:01:40 +02:00
|
|
|
raise v
|
|
|
|
else:
|
|
|
|
return v
|
2011-08-12 22:28:50 +02:00
|
|
|
|
2011-08-13 00:10:41 +02:00
|
|
|
def regexp_wrapper(s, reobj, timeout, plugin_name, fcn_name):
|
|
|
|
'''A convenient wrapper to stuff regexp search queries through a subprocess.
|
|
|
|
|
|
|
|
This is used because specially-crafted regexps can use exponential time
|
|
|
|
and hang the bot.'''
|
|
|
|
def re_bool(s, reobj):
|
|
|
|
"""Since we can't enqueue match objects into the multiprocessing queue,
|
|
|
|
we'll just wrap the function to return bools."""
|
|
|
|
if reobj.search(s) is not None:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
try:
|
|
|
|
v = process(re_bool, s, reobj, timeout=timeout, pn=plugin_name, cn=fcn_name)
|
|
|
|
return v
|
|
|
|
except ProcessTimeoutError:
|
|
|
|
return False
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
class UrlSnarfThread(world.SupyThread):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
assert 'url' in kwargs
|
|
|
|
kwargs['name'] = 'Thread #%s (for snarfing %s)' % \
|
|
|
|
(world.threadsSpawned, kwargs.pop('url'))
|
|
|
|
super(UrlSnarfThread, self).__init__(*args, **kwargs)
|
|
|
|
self.setDaemon(True)
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
try:
|
|
|
|
super(UrlSnarfThread, self).run()
|
2014-01-20 15:49:15 +01:00
|
|
|
except utils.web.Error as e:
|
2005-05-18 06:18:35 +02:00
|
|
|
log.debug('Exception in urlSnarfer: %s', utils.exnToString(e))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
class SnarfQueue(ircutils.FloodQueue):
|
|
|
|
timeout = conf.supybot.snarfThrottle
|
|
|
|
def key(self, channel):
|
|
|
|
return channel
|
|
|
|
|
|
|
|
_snarfed = SnarfQueue()
|
|
|
|
|
|
|
|
class SnarfIrc(object):
|
|
|
|
def __init__(self, irc, channel, url):
|
|
|
|
self.irc = irc
|
|
|
|
self.url = url
|
|
|
|
self.channel = channel
|
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
return getattr(self.irc, attr)
|
|
|
|
|
|
|
|
def reply(self, *args, **kwargs):
|
|
|
|
_snarfed.enqueue(self.channel, self.url)
|
|
|
|
return self.irc.reply(*args, **kwargs)
|
|
|
|
|
|
|
|
# This lock is used to serialize the calls to snarfers, so
|
|
|
|
# earlier snarfers are guaranteed to beat out later snarfers.
|
|
|
|
_snarfLock = threading.Lock()
|
|
|
|
def urlSnarfer(f):
|
|
|
|
"""Protects the snarfer from loops (with other bots) and whatnot."""
|
|
|
|
def newf(self, irc, msg, match, *L, **kwargs):
|
|
|
|
url = match.group(0)
|
|
|
|
channel = msg.args[0]
|
2010-01-28 14:14:44 +01:00
|
|
|
if not irc.isChannel(channel) or (ircmsgs.isCtcp(msg) and not
|
|
|
|
ircmsgs.isAction(msg)):
|
2005-01-19 14:14:38 +01:00
|
|
|
return
|
|
|
|
if ircdb.channels.getChannel(channel).lobotomized:
|
2010-01-28 14:14:44 +01:00
|
|
|
self.log.debug('Not snarfing in %s: lobotomized.', channel)
|
2005-01-19 14:14:38 +01:00
|
|
|
return
|
|
|
|
if _snarfed.has(channel, url):
|
|
|
|
self.log.info('Throttling snarf of %s in %s.', url, channel)
|
|
|
|
return
|
|
|
|
irc = SnarfIrc(irc, channel, url)
|
|
|
|
def doSnarf():
|
|
|
|
_snarfLock.acquire()
|
|
|
|
try:
|
2005-05-30 21:20:17 +02:00
|
|
|
# This has to be *after* we've acquired the lock so we can be
|
|
|
|
# sure that all previous urlSnarfers have already run to
|
|
|
|
# completion.
|
2005-01-19 14:14:38 +01:00
|
|
|
if msg.repliedTo:
|
|
|
|
self.log.debug('Not snarfing, msg is already repliedTo.')
|
|
|
|
return
|
|
|
|
f(self, irc, msg, match, *L, **kwargs)
|
|
|
|
finally:
|
|
|
|
_snarfLock.release()
|
|
|
|
if threading.currentThread() is not world.mainThread:
|
|
|
|
doSnarf()
|
|
|
|
else:
|
|
|
|
L = list(L)
|
|
|
|
t = UrlSnarfThread(target=doSnarf, url=url)
|
|
|
|
t.start()
|
2014-01-21 10:40:18 +01:00
|
|
|
newf = utils.python.changeFunctionName(newf, f.__name__, f.__doc__)
|
2005-01-19 14:14:38 +01:00
|
|
|
return newf
|
|
|
|
|
|
|
|
|
|
|
|
###
|
|
|
|
# Converters, which take irc, msg, args, and a state object, and build up the
|
|
|
|
# validated and converted args for the method in state.args.
|
|
|
|
###
|
|
|
|
|
|
|
|
# This is just so we can centralize this, since it may change.
|
|
|
|
def _int(s):
|
|
|
|
base = 10
|
|
|
|
if s.startswith('0x'):
|
|
|
|
base = 16
|
|
|
|
s = s[2:]
|
|
|
|
elif s.startswith('0b'):
|
|
|
|
base = 2
|
|
|
|
s = s[2:]
|
|
|
|
elif s.startswith('0') and len(s) > 1:
|
|
|
|
base = 8
|
|
|
|
s = s[1:]
|
|
|
|
try:
|
|
|
|
return int(s, base)
|
|
|
|
except ValueError:
|
2014-03-20 22:17:18 +01:00
|
|
|
if base == 10 and '.' not in s:
|
2013-08-24 05:36:44 +02:00
|
|
|
try:
|
|
|
|
return int(float(s))
|
|
|
|
except OverflowError:
|
|
|
|
raise ValueError('I don\'t understand numbers that large.')
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2010-10-20 18:27:58 +02:00
|
|
|
def getInt(irc, msg, args, state, type=_('integer'), p=None):
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
|
|
|
i = _int(args[0])
|
|
|
|
if p is not None:
|
|
|
|
if not p(i):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorInvalid(type, args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(i)
|
|
|
|
del args[0]
|
|
|
|
except ValueError:
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorInvalid(type, args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2010-10-20 18:27:58 +02:00
|
|
|
def getNonInt(irc, msg, args, state, type=_('non-integer value')):
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
2015-08-31 15:38:35 +02:00
|
|
|
_int(args[0])
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorInvalid(type, args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
except ValueError:
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
|
|
|
|
def getLong(irc, msg, args, state, type='long'):
|
|
|
|
getInt(irc, msg, args, state, type)
|
2015-08-08 23:01:02 +02:00
|
|
|
state.args[-1] = minisix.long(state.args[-1])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2010-10-20 18:27:58 +02:00
|
|
|
def getFloat(irc, msg, args, state, type=_('floating point number')):
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
|
|
|
state.args.append(float(args[0]))
|
|
|
|
del args[0]
|
|
|
|
except ValueError:
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorInvalid(type, args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getPositiveInt(irc, msg, args, state, *L):
|
|
|
|
getInt(irc, msg, args, state,
|
2010-11-14 14:36:02 +01:00
|
|
|
p=lambda i: i>0, type=_('positive integer'), *L)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getNonNegativeInt(irc, msg, args, state, *L):
|
|
|
|
getInt(irc, msg, args, state,
|
2010-10-20 18:27:58 +02:00
|
|
|
p=lambda i: i>=0, type=_('non-negative integer'), *L)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getIndex(irc, msg, args, state):
|
2010-10-20 18:27:58 +02:00
|
|
|
getInt(irc, msg, args, state, type=_('index'))
|
2005-01-19 14:14:38 +01:00
|
|
|
if state.args[-1] > 0:
|
|
|
|
state.args[-1] -= 1
|
|
|
|
|
|
|
|
def getId(irc, msg, args, state, kind=None):
|
|
|
|
type = 'id'
|
|
|
|
if kind is not None and not kind.endswith('id'):
|
|
|
|
type = kind + ' id'
|
|
|
|
original = args[0]
|
|
|
|
try:
|
|
|
|
args[0] = args[0].lstrip('#')
|
|
|
|
getInt(irc, msg, args, state, type=type)
|
2015-08-31 15:38:35 +02:00
|
|
|
except Exception:
|
2005-01-19 14:14:38 +01:00
|
|
|
args[0] = original
|
|
|
|
raise
|
|
|
|
|
|
|
|
def getExpiry(irc, msg, args, state):
|
|
|
|
now = int(time.time())
|
|
|
|
try:
|
|
|
|
expires = _int(args[0])
|
|
|
|
if expires:
|
|
|
|
expires += now
|
|
|
|
state.args.append(expires)
|
|
|
|
del args[0]
|
|
|
|
except ValueError:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('number of seconds'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getBoolean(irc, msg, args, state):
|
|
|
|
try:
|
2005-01-27 07:59:08 +01:00
|
|
|
state.args.append(utils.str.toBool(args[0]))
|
2005-01-19 14:14:38 +01:00
|
|
|
del args[0]
|
|
|
|
except ValueError:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('boolean'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getNetworkIrc(irc, msg, args, state, errorIfNoMatch=False):
|
|
|
|
if args:
|
|
|
|
for otherIrc in world.ircs:
|
|
|
|
if otherIrc.network.lower() == args[0].lower():
|
|
|
|
state.args.append(otherIrc)
|
|
|
|
del args[0]
|
|
|
|
return
|
|
|
|
if errorIfNoMatch:
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
else:
|
|
|
|
state.args.append(irc)
|
|
|
|
|
2011-07-01 15:58:39 +02:00
|
|
|
def getHaveVoice(irc, msg, args, state, action=_('do that')):
|
2014-04-05 22:54:51 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2011-07-01 15:58:39 +02:00
|
|
|
if state.channel not in irc.state.channels:
|
|
|
|
state.error(_('I\'m not even in %s.') % state.channel, Raise=True)
|
|
|
|
if not irc.state.channels[state.channel].isVoice(irc.nick):
|
|
|
|
state.error(_('I need to be voiced to %s.') % action, Raise=True)
|
|
|
|
|
2013-05-17 17:36:11 +02:00
|
|
|
def getHaveVoicePlus(irc, msg, args, state, action=_('do that')):
|
2014-04-05 22:54:51 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2011-07-01 15:58:39 +02:00
|
|
|
if state.channel not in irc.state.channels:
|
|
|
|
state.error(_('I\'m not even in %s.') % state.channel, Raise=True)
|
2013-05-17 17:47:43 +02:00
|
|
|
if not irc.state.channels[state.channel].isVoicePlus(irc.nick):
|
2013-05-17 17:36:11 +02:00
|
|
|
# isOp includes owners and protected users
|
|
|
|
state.error(_('I need to be at least voiced to %s.') % action,
|
|
|
|
Raise=True)
|
2011-07-01 15:58:39 +02:00
|
|
|
|
2013-05-17 17:36:11 +02:00
|
|
|
def getHaveHalfop(irc, msg, args, state, action=_('do that')):
|
2014-04-05 22:54:51 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2005-01-19 14:14:38 +01:00
|
|
|
if state.channel not in irc.state.channels:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('I\'m not even in %s.') % state.channel, Raise=True)
|
2013-05-17 17:36:11 +02:00
|
|
|
if not irc.state.channels[state.channel].isHalfop(irc.nick):
|
|
|
|
state.error(_('I need to be halfopped to %s.') % action, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2013-05-17 17:36:11 +02:00
|
|
|
def getHaveHalfopPlus(irc, msg, args, state, action=_('do that')):
|
2014-04-05 22:54:51 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2011-07-01 15:58:39 +02:00
|
|
|
if state.channel not in irc.state.channels:
|
|
|
|
state.error(_('I\'m not even in %s.') % state.channel, Raise=True)
|
2013-05-17 17:47:43 +02:00
|
|
|
if not irc.state.channels[state.channel].isHalfopPlus(irc.nick):
|
2011-07-01 15:58:39 +02:00
|
|
|
# isOp includes owners and protected users
|
2012-04-23 21:55:21 +02:00
|
|
|
state.error(_('I need to be at least halfopped to %s.') % action,
|
2011-07-01 15:58:39 +02:00
|
|
|
Raise=True)
|
|
|
|
|
2013-05-17 17:36:11 +02:00
|
|
|
def getHaveOp(irc, msg, args, state, action=_('do that')):
|
2013-10-11 00:54:50 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2013-05-17 17:36:11 +02:00
|
|
|
if state.channel not in irc.state.channels:
|
|
|
|
state.error(_('I\'m not even in %s.') % state.channel, Raise=True)
|
|
|
|
if not irc.state.channels[state.channel].isOp(irc.nick):
|
|
|
|
state.error(_('I need to be opped to %s.') % action, Raise=True)
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def validChannel(irc, msg, args, state):
|
|
|
|
if irc.isChannel(args[0]):
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2012-07-30 11:35:44 +02:00
|
|
|
state.errorInvalid(_('channel'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getHostmask(irc, msg, args, state):
|
2012-12-02 19:04:48 +01:00
|
|
|
if ircutils.isUserHostmask(args[0]) or \
|
|
|
|
(not conf.supybot.protocols.irc.strictRfc() and
|
|
|
|
args[0].startswith('$')):
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
hostmask = irc.state.nickToHostmask(args[0])
|
|
|
|
state.args.append(hostmask)
|
|
|
|
del args[0]
|
|
|
|
except KeyError:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('nick or hostmask'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getBanmask(irc, msg, args, state):
|
|
|
|
getHostmask(irc, msg, args, state)
|
2013-10-11 00:54:50 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2009-01-19 22:12:55 +01:00
|
|
|
banmaskstyle = conf.supybot.protocols.irc.banmask
|
2015-08-31 15:38:35 +02:00
|
|
|
state.args[-1] = banmaskstyle.makeBanmask(state.args[-1],
|
|
|
|
channel=state.channel)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getUser(irc, msg, args, state):
|
|
|
|
try:
|
|
|
|
state.args.append(ircdb.users.getUser(msg.prefix))
|
|
|
|
except KeyError:
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorNotRegistered(Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getOtherUser(irc, msg, args, state):
|
2009-09-24 00:29:49 +02:00
|
|
|
# Although ircdb.users.getUser could accept a hostmask, we're explicitly
|
|
|
|
# excluding that from our interface with this check
|
2005-01-19 14:14:38 +01:00
|
|
|
if ircutils.isUserHostmask(args[0]):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorNoUser(args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
try:
|
|
|
|
state.args.append(ircdb.users.getUser(args[0]))
|
|
|
|
del args[0]
|
|
|
|
except KeyError:
|
|
|
|
try:
|
|
|
|
getHostmask(irc, msg, [args[0]], state)
|
|
|
|
hostmask = state.args.pop()
|
|
|
|
state.args.append(ircdb.users.getUser(hostmask))
|
|
|
|
del args[0]
|
|
|
|
except (KeyError, callbacks.Error):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorNoUser(name=args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def _getRe(f):
|
|
|
|
def get(irc, msg, args, state, convert=True):
|
|
|
|
original = args[:]
|
|
|
|
s = args.pop(0)
|
|
|
|
def isRe(s):
|
|
|
|
try:
|
2015-08-31 15:38:35 +02:00
|
|
|
f(s)
|
2005-01-19 14:14:38 +01:00
|
|
|
return True
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
try:
|
|
|
|
while len(s) < 512 and not isRe(s):
|
|
|
|
s += ' ' + args.pop(0)
|
|
|
|
if len(s) < 512:
|
|
|
|
if convert:
|
|
|
|
state.args.append(f(s))
|
|
|
|
else:
|
|
|
|
state.args.append(s)
|
|
|
|
else:
|
2015-02-19 03:35:57 +01:00
|
|
|
raise ValueError
|
|
|
|
except (ValueError, IndexError):
|
2005-01-19 14:14:38 +01:00
|
|
|
args[:] = original
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('regular expression'), s)
|
2005-01-19 14:14:38 +01:00
|
|
|
return get
|
|
|
|
|
2005-01-27 07:59:08 +01:00
|
|
|
getMatcher = _getRe(utils.str.perlReToPythonRe)
|
2015-05-15 16:48:00 +02:00
|
|
|
getMatcherMany = _getRe(utils.str.perlReToFindall)
|
2005-01-27 07:59:08 +01:00
|
|
|
getReplacer = _getRe(utils.str.perlReToReplacer)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getNick(irc, msg, args, state):
|
2012-02-11 09:03:52 +01:00
|
|
|
if ircutils.isNick(args[0], conf.supybot.protocols.irc.strictRfc()):
|
2005-01-19 14:14:38 +01:00
|
|
|
if 'nicklen' in irc.state.supported:
|
|
|
|
if len(args[0]) > irc.state.supported['nicklen']:
|
2012-07-30 11:35:44 +02:00
|
|
|
state.errorInvalid(_('nick'), args[0],
|
2010-10-20 18:27:58 +02:00
|
|
|
_('That nick is too long for this server.'))
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2012-07-30 11:35:44 +02:00
|
|
|
state.errorInvalid(_('nick'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getSeenNick(irc, msg, args, state, errmsg=None):
|
|
|
|
try:
|
2015-08-31 15:38:35 +02:00
|
|
|
irc.state.nickToHostmask(args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
except KeyError:
|
|
|
|
if errmsg is None:
|
2012-07-30 11:35:44 +02:00
|
|
|
errmsg = _('I haven\'t seen %s.') % args[0]
|
2005-06-01 22:13:33 +02:00
|
|
|
state.error(errmsg, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getChannel(irc, msg, args, state):
|
2013-10-11 00:54:50 +02:00
|
|
|
if state.channel:
|
|
|
|
return
|
2005-01-19 14:14:38 +01:00
|
|
|
if args and irc.isChannel(args[0]):
|
|
|
|
channel = args.pop(0)
|
|
|
|
elif irc.isChannel(msg.args[0]):
|
|
|
|
channel = msg.args[0]
|
|
|
|
else:
|
|
|
|
state.log.debug('Raising ArgumentError because there is no channel.')
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
state.channel = channel
|
|
|
|
state.args.append(channel)
|
|
|
|
|
|
|
|
def getChannelDb(irc, msg, args, state, **kwargs):
|
|
|
|
channelSpecific = conf.supybot.databases.plugins.channelSpecific
|
|
|
|
try:
|
|
|
|
getChannel(irc, msg, args, state, **kwargs)
|
|
|
|
channel = channelSpecific.getChannelLink(state.channel)
|
|
|
|
state.channel = channel
|
|
|
|
state.args[-1] = channel
|
|
|
|
except (callbacks.ArgumentError, IndexError):
|
|
|
|
if channelSpecific():
|
|
|
|
raise
|
|
|
|
channel = channelSpecific.link()
|
|
|
|
if not conf.get(channelSpecific.link.allow, channel):
|
|
|
|
log.warning('channelSpecific.link is globally set to %s, but '
|
2005-05-18 06:18:35 +02:00
|
|
|
'%s disallowed linking to its db.', channel, channel)
|
2005-01-19 14:14:38 +01:00
|
|
|
raise
|
|
|
|
else:
|
|
|
|
channel = channelSpecific.getChannelLink(channel)
|
|
|
|
state.channel = channel
|
|
|
|
state.args.append(channel)
|
|
|
|
|
|
|
|
def inChannel(irc, msg, args, state):
|
2013-10-11 00:54:50 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2005-01-19 14:14:38 +01:00
|
|
|
if state.channel not in irc.state.channels:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('I\'m not in %s.') % state.channel, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def onlyInChannel(irc, msg, args, state):
|
|
|
|
if not (irc.isChannel(msg.args[0]) and msg.args[0] in irc.state.channels):
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('This command may only be given in a channel that I am '
|
|
|
|
'in.'), Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
state.channel = msg.args[0]
|
|
|
|
state.args.append(state.channel)
|
|
|
|
|
|
|
|
def callerInGivenChannel(irc, msg, args, state):
|
|
|
|
channel = args[0]
|
|
|
|
if irc.isChannel(channel):
|
|
|
|
if channel in irc.state.channels:
|
|
|
|
if msg.nick in irc.state.channels[channel].users:
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('You must be in %s.') % channel, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('I\'m not in %s.') % channel, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('channel'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def nickInChannel(irc, msg, args, state):
|
2005-01-29 22:23:37 +01:00
|
|
|
originalArgs = state.args[:]
|
2005-01-19 14:14:38 +01:00
|
|
|
inChannel(irc, msg, args, state)
|
2005-01-29 22:23:37 +01:00
|
|
|
state.args = originalArgs
|
2005-01-19 14:14:38 +01:00
|
|
|
if args[0] not in irc.state.channels[state.channel].users:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.error(_('%s is not in %s.') % (args[0], state.channel), Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
|
|
|
|
def getChannelOrNone(irc, msg, args, state):
|
|
|
|
try:
|
|
|
|
getChannel(irc, msg, args, state)
|
|
|
|
except callbacks.ArgumentError:
|
|
|
|
state.args.append(None)
|
|
|
|
|
2012-10-18 19:30:35 +02:00
|
|
|
def getChannelOrGlobal(irc, msg, args, state):
|
|
|
|
if args and args[0] == 'global':
|
|
|
|
channel = args.pop(0)
|
|
|
|
channel = 'global'
|
|
|
|
elif args and irc.isChannel(args[0]):
|
|
|
|
channel = args.pop(0)
|
|
|
|
state.channel = channel
|
|
|
|
elif irc.isChannel(msg.args[0]):
|
|
|
|
channel = msg.args[0]
|
|
|
|
state.channel = channel
|
|
|
|
else:
|
|
|
|
state.log.debug('Raising ArgumentError because there is no channel.')
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
state.args.append(channel)
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def checkChannelCapability(irc, msg, args, state, cap):
|
2013-10-11 00:54:50 +02:00
|
|
|
getChannel(irc, msg, args, state)
|
2005-01-19 14:14:38 +01:00
|
|
|
cap = ircdb.canonicalCapability(cap)
|
|
|
|
cap = ircdb.makeChannelCapability(state.channel, cap)
|
|
|
|
if not ircdb.checkCapability(msg.prefix, cap):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorNoCapability(cap, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2005-02-24 10:59:21 +01:00
|
|
|
def getOp(irc, msg, args, state):
|
|
|
|
checkChannelCapability(irc, msg, args, state, 'op')
|
|
|
|
|
|
|
|
def getHalfop(irc, msg, args, state):
|
|
|
|
checkChannelCapability(irc, msg, args, state, 'halfop')
|
|
|
|
|
|
|
|
def getVoice(irc, msg, args, state):
|
|
|
|
checkChannelCapability(irc, msg, args, state, 'voice')
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def getLowered(irc, msg, args, state):
|
|
|
|
state.args.append(ircutils.toLower(args.pop(0)))
|
|
|
|
|
|
|
|
def getSomething(irc, msg, args, state, errorMsg=None, p=None):
|
|
|
|
if p is None:
|
|
|
|
p = lambda _: True
|
|
|
|
if not args[0] or not p(args[0]):
|
|
|
|
if errorMsg is None:
|
2010-10-20 18:27:58 +02:00
|
|
|
errorMsg = _('You must not give the empty string as an argument.')
|
2005-06-01 22:13:33 +02:00
|
|
|
state.error(errorMsg, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
|
|
|
|
def getSomethingNoSpaces(irc, msg, args, state, *L):
|
|
|
|
def p(s):
|
|
|
|
return len(s.split(None, 1)) == 1
|
2013-08-15 22:25:36 +02:00
|
|
|
L = L or [_('You must not give a string containing spaces as an argument.')]
|
|
|
|
getSomething(irc, msg, args, state, p=p, *L)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def private(irc, msg, args, state):
|
|
|
|
if irc.isChannel(msg.args[0]):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorRequiresPrivacy(Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def public(irc, msg, args, state, errmsg=None):
|
|
|
|
if not irc.isChannel(msg.args[0]):
|
|
|
|
if errmsg is None:
|
2010-10-20 18:27:58 +02:00
|
|
|
errmsg = _('This message must be sent in a channel.')
|
2005-06-01 22:13:33 +02:00
|
|
|
state.error(errmsg, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def checkCapability(irc, msg, args, state, cap):
|
|
|
|
cap = ircdb.canonicalCapability(cap)
|
|
|
|
if not ircdb.checkCapability(msg.prefix, cap):
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errorNoCapability(cap, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2011-01-27 19:32:43 +01:00
|
|
|
def checkCapabilityButIgnoreOwner(irc, msg, args, state, cap):
|
|
|
|
cap = ircdb.canonicalCapability(cap)
|
|
|
|
if not ircdb.checkCapability(msg.prefix, cap, ignoreOwner=True):
|
|
|
|
state.errorNoCapability(cap, Raise=True)
|
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def owner(irc, msg, args, state):
|
|
|
|
checkCapability(irc, msg, args, state, 'owner')
|
|
|
|
|
|
|
|
def admin(irc, msg, args, state):
|
|
|
|
checkCapability(irc, msg, args, state, 'admin')
|
|
|
|
|
|
|
|
def anything(irc, msg, args, state):
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
|
|
|
|
def getGlob(irc, msg, args, state):
|
|
|
|
glob = args.pop(0)
|
|
|
|
if '*' not in glob and '?' not in glob:
|
|
|
|
glob = '*%s*' % glob
|
|
|
|
state.args.append(glob)
|
|
|
|
|
|
|
|
def getUrl(irc, msg, args, state):
|
2005-01-28 15:51:25 +01:00
|
|
|
if utils.web.urlRe.match(args[0]):
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2012-07-30 11:35:44 +02:00
|
|
|
state.errorInvalid(_('url'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
2005-02-01 08:08:13 +01:00
|
|
|
def getEmail(irc, msg, args, state):
|
|
|
|
if utils.net.emailRe.match(args[0]):
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2012-07-30 11:35:44 +02:00
|
|
|
state.errorInvalid(_('email'), args[0])
|
2005-02-01 08:08:13 +01:00
|
|
|
|
2005-01-19 14:14:38 +01:00
|
|
|
def getHttpUrl(irc, msg, args, state):
|
2005-01-28 15:51:25 +01:00
|
|
|
if utils.web.httpUrlRe.match(args[0]):
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
2008-06-26 18:30:23 +02:00
|
|
|
elif utils.web.httpUrlRe.match('http://' + args[0]):
|
|
|
|
state.args.append('http://' + args.pop(0))
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('http url'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getNow(irc, msg, args, state):
|
|
|
|
state.args.append(int(time.time()))
|
|
|
|
|
|
|
|
def getCommandName(irc, msg, args, state):
|
|
|
|
if ' ' in args[0]:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('command name'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
state.args.append(callbacks.canonicalName(args.pop(0)))
|
|
|
|
|
|
|
|
def getIp(irc, msg, args, state):
|
2005-01-27 07:59:08 +01:00
|
|
|
if utils.net.isIP(args[0]):
|
2005-01-19 14:14:38 +01:00
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('ip'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getLetter(irc, msg, args, state):
|
|
|
|
if len(args[0]) == 1:
|
|
|
|
state.args.append(args.pop(0))
|
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('letter'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getMatch(irc, msg, args, state, regexp, errmsg):
|
|
|
|
m = regexp.search(args[0])
|
|
|
|
if m is not None:
|
|
|
|
state.args.append(m)
|
|
|
|
del args[0]
|
|
|
|
else:
|
2005-06-01 22:13:33 +02:00
|
|
|
state.error(errmsg, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getLiteral(irc, msg, args, state, literals, errmsg=None):
|
|
|
|
# ??? Should we allow abbreviations?
|
2015-08-10 20:24:11 +02:00
|
|
|
if isinstance(literals, minisix.string_types):
|
2005-01-19 14:14:38 +01:00
|
|
|
literals = (literals,)
|
2005-02-15 14:57:57 +01:00
|
|
|
abbrevs = utils.abbrev(literals)
|
2005-01-19 14:14:38 +01:00
|
|
|
if args[0] in abbrevs:
|
|
|
|
state.args.append(abbrevs[args.pop(0)])
|
|
|
|
elif errmsg is not None:
|
2005-06-01 22:13:33 +02:00
|
|
|
state.error(errmsg, Raise=True)
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
|
|
|
|
def getTo(irc, msg, args, state):
|
|
|
|
if args[0].lower() == 'to':
|
|
|
|
args.pop(0)
|
|
|
|
|
|
|
|
def getPlugin(irc, msg, args, state, require=True):
|
|
|
|
cb = irc.getCallback(args[0])
|
|
|
|
if cb is not None:
|
|
|
|
state.args.append(cb)
|
|
|
|
del args[0]
|
|
|
|
elif require:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('plugin'), args[0])
|
2005-01-19 14:14:38 +01:00
|
|
|
else:
|
|
|
|
state.args.append(None)
|
|
|
|
|
|
|
|
def getIrcColor(irc, msg, args, state):
|
|
|
|
if args[0] in ircutils.mircColors:
|
|
|
|
state.args.append(ircutils.mircColors[args.pop(0)])
|
|
|
|
else:
|
2010-10-20 18:27:58 +02:00
|
|
|
state.errorInvalid(_('irc color'))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def getText(irc, msg, args, state):
|
|
|
|
if args:
|
|
|
|
state.args.append(' '.join(args))
|
|
|
|
args[:] = []
|
|
|
|
else:
|
|
|
|
raise IndexError
|
|
|
|
|
|
|
|
wrappers = ircutils.IrcDict({
|
2009-08-14 16:07:26 +02:00
|
|
|
'admin': admin,
|
|
|
|
'anything': anything,
|
|
|
|
'banmask': getBanmask,
|
|
|
|
'boolean': getBoolean,
|
|
|
|
'callerInGivenChannel': callerInGivenChannel,
|
2013-05-17 17:36:11 +02:00
|
|
|
'isGranted': getHaveHalfopPlus, # Backward compatibility
|
2009-08-14 16:07:26 +02:00
|
|
|
'capability': getSomethingNoSpaces,
|
|
|
|
'channel': getChannel,
|
2012-10-18 19:30:35 +02:00
|
|
|
'channelOrGlobal': getChannelOrGlobal,
|
2009-08-14 16:07:26 +02:00
|
|
|
'channelDb': getChannelDb,
|
|
|
|
'checkCapability': checkCapability,
|
2011-01-27 19:32:43 +01:00
|
|
|
'checkCapabilityButIgnoreOwner': checkCapabilityButIgnoreOwner,
|
2009-08-14 16:07:26 +02:00
|
|
|
'checkChannelCapability': checkChannelCapability,
|
2005-01-19 14:14:38 +01:00
|
|
|
'color': getIrcColor,
|
2009-08-14 16:07:26 +02:00
|
|
|
'commandName': getCommandName,
|
2005-02-01 08:08:13 +01:00
|
|
|
'email': getEmail,
|
2009-08-14 16:07:26 +02:00
|
|
|
'expiry': getExpiry,
|
|
|
|
'filename': getSomething, # XXX Check for validity.
|
2005-01-19 14:14:38 +01:00
|
|
|
'float': getFloat,
|
2009-08-14 16:07:26 +02:00
|
|
|
'glob': getGlob,
|
|
|
|
'halfop': getHalfop,
|
2011-07-01 16:11:37 +02:00
|
|
|
'haveHalfop': getHaveHalfop,
|
2013-05-17 17:36:11 +02:00
|
|
|
'haveHalfop+': getHaveHalfopPlus,
|
2005-01-19 14:14:38 +01:00
|
|
|
'haveOp': getHaveOp,
|
2013-05-17 17:36:11 +02:00
|
|
|
'haveOp+': getHaveOp, # We don't handle modes greater than op.
|
2011-07-01 16:11:37 +02:00
|
|
|
'haveVoice': getHaveVoice,
|
2013-05-17 17:36:11 +02:00
|
|
|
'haveVoice+': getHaveVoicePlus,
|
2009-08-14 16:07:26 +02:00
|
|
|
'hostmask': getHostmask,
|
|
|
|
'httpUrl': getHttpUrl,
|
|
|
|
'id': getId,
|
|
|
|
'inChannel': inChannel,
|
|
|
|
'index': getIndex,
|
|
|
|
'int': getInt,
|
|
|
|
'ip': getIp,
|
|
|
|
'letter': getLetter,
|
2005-01-19 14:14:38 +01:00
|
|
|
'literal': getLiteral,
|
2009-08-14 16:07:26 +02:00
|
|
|
'long': getLong,
|
|
|
|
'lowered': getLowered,
|
|
|
|
'matches': getMatch,
|
|
|
|
'networkIrc': getNetworkIrc,
|
2005-01-19 14:14:38 +01:00
|
|
|
'nick': getNick,
|
|
|
|
'nickInChannel': nickInChannel,
|
2009-08-14 16:07:26 +02:00
|
|
|
'nonInt': getNonInt,
|
|
|
|
'nonNegativeInt': getNonNegativeInt,
|
|
|
|
'now': getNow,
|
|
|
|
'onlyInChannel': onlyInChannel,
|
|
|
|
'op': getOp,
|
|
|
|
'otherUser': getOtherUser,
|
|
|
|
'owner': owner,
|
2005-01-19 14:14:38 +01:00
|
|
|
'plugin': getPlugin,
|
2009-08-14 16:07:26 +02:00
|
|
|
'positiveInt': getPositiveInt,
|
|
|
|
'private': private,
|
|
|
|
'public': public,
|
|
|
|
'regexpMatcher': getMatcher,
|
2015-05-15 16:48:00 +02:00
|
|
|
'regexpMatcherMany': getMatcherMany,
|
2009-08-14 16:07:26 +02:00
|
|
|
'regexpReplacer': getReplacer,
|
|
|
|
'seenNick': getSeenNick,
|
2005-01-19 14:14:38 +01:00
|
|
|
'something': getSomething,
|
|
|
|
'somethingWithoutSpaces': getSomethingNoSpaces,
|
2009-08-14 16:07:26 +02:00
|
|
|
'text': getText,
|
|
|
|
'to': getTo,
|
|
|
|
'url': getUrl,
|
2005-01-19 14:14:38 +01:00
|
|
|
'user': getUser,
|
|
|
|
'validChannel': validChannel,
|
2005-02-24 10:59:21 +01:00
|
|
|
'voice': getVoice,
|
2005-01-19 14:14:38 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
def addConverter(name, wrapper):
|
|
|
|
wrappers[name] = wrapper
|
|
|
|
|
|
|
|
class UnknownConverter(KeyError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def getConverter(name):
|
|
|
|
try:
|
|
|
|
return wrappers[name]
|
2014-01-20 15:49:15 +01:00
|
|
|
except KeyError as e:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise UnknownConverter(str(e))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def callConverter(name, irc, msg, args, state, *L):
|
|
|
|
getConverter(name)(irc, msg, args, state, *L)
|
|
|
|
|
|
|
|
###
|
|
|
|
# Contexts. These determine what the nature of conversions is; whether they're
|
|
|
|
# defaulted, or many of them are allowed, etc. Contexts should be reusable;
|
|
|
|
# i.e., they should not maintain state between calls.
|
|
|
|
###
|
|
|
|
def contextify(spec):
|
|
|
|
if not isinstance(spec, context):
|
|
|
|
spec = context(spec)
|
|
|
|
return spec
|
|
|
|
|
|
|
|
def setDefault(state, default):
|
|
|
|
if callable(default):
|
|
|
|
state.args.append(default())
|
|
|
|
else:
|
|
|
|
state.args.append(default)
|
|
|
|
|
|
|
|
class context(object):
|
|
|
|
def __init__(self, spec):
|
|
|
|
self.args = ()
|
|
|
|
self.spec = spec # for repr
|
|
|
|
if isinstance(spec, tuple):
|
|
|
|
assert spec, 'tuple spec must not be empty.'
|
|
|
|
self.args = spec[1:]
|
|
|
|
self.converter = getConverter(spec[0])
|
|
|
|
elif spec is None:
|
|
|
|
self.converter = getConverter('anything')
|
2015-08-10 20:24:11 +02:00
|
|
|
elif isinstance(spec, minisix.string_types):
|
2005-01-19 14:14:38 +01:00
|
|
|
self.args = ()
|
|
|
|
self.converter = getConverter(spec)
|
|
|
|
else:
|
|
|
|
assert isinstance(spec, context)
|
|
|
|
self.converter = spec
|
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
log.debug('args before %r: %r', self, args)
|
|
|
|
self.converter(irc, msg, args, state, *self.args)
|
|
|
|
log.debug('args after %r: %r', self, args)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<%s for %s>' % (self.__class__.__name__, self.spec)
|
|
|
|
|
|
|
|
class rest(context):
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
if args:
|
|
|
|
original = args[:]
|
|
|
|
args[:] = [' '.join(args)]
|
|
|
|
try:
|
|
|
|
super(rest, self).__call__(irc, msg, args, state)
|
2015-08-31 15:38:35 +02:00
|
|
|
except Exception:
|
2005-01-19 14:14:38 +01:00
|
|
|
args[:] = original
|
|
|
|
else:
|
2005-07-27 23:57:17 +02:00
|
|
|
raise IndexError
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
# additional means: Look for this (and make sure it's of this type). If
|
|
|
|
# there are no arguments for us to check, then use our default.
|
|
|
|
class additional(context):
|
|
|
|
def __init__(self, spec, default=None):
|
|
|
|
self.__parent = super(additional, self)
|
|
|
|
self.__parent.__init__(spec)
|
|
|
|
self.default = default
|
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
try:
|
|
|
|
self.__parent.__call__(irc, msg, args, state)
|
|
|
|
except IndexError:
|
|
|
|
log.debug('Got IndexError, returning default.')
|
|
|
|
setDefault(state, self.default)
|
|
|
|
|
|
|
|
# optional means: Look for this, but if it's not the type I'm expecting or
|
|
|
|
# there are no arguments for us to check, then use the default value.
|
|
|
|
class optional(additional):
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
try:
|
|
|
|
super(optional, self).__call__(irc, msg, args, state)
|
2014-01-20 15:49:15 +01:00
|
|
|
except (callbacks.ArgumentError, callbacks.Error) as e:
|
2005-02-15 14:57:57 +01:00
|
|
|
log.debug('Got %s, returning default.', utils.exnToString(e))
|
2005-06-01 22:13:33 +02:00
|
|
|
state.errored = False
|
2005-01-19 14:14:38 +01:00
|
|
|
setDefault(state, self.default)
|
|
|
|
|
|
|
|
class any(context):
|
|
|
|
def __init__(self, spec, continueOnError=False):
|
|
|
|
self.__parent = super(any, self)
|
|
|
|
self.__parent.__init__(spec)
|
|
|
|
self.continueOnError = continueOnError
|
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
st = state.essence()
|
|
|
|
try:
|
|
|
|
while args:
|
|
|
|
self.__parent.__call__(irc, msg, args, st)
|
|
|
|
except IndexError:
|
|
|
|
pass
|
2014-01-20 15:49:15 +01:00
|
|
|
except (callbacks.ArgumentError, callbacks.Error) as e:
|
2005-01-19 14:14:38 +01:00
|
|
|
if not self.continueOnError:
|
|
|
|
raise
|
|
|
|
else:
|
2005-02-15 14:57:57 +01:00
|
|
|
log.debug('Got %s, returning default.', utils.exnToString(e))
|
2005-01-19 14:14:38 +01:00
|
|
|
pass
|
|
|
|
state.args.append(st.args)
|
|
|
|
|
|
|
|
class many(any):
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
super(many, self).__call__(irc, msg, args, state)
|
|
|
|
if not state.args[-1]:
|
|
|
|
state.args.pop()
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
|
|
|
|
class first(context):
|
|
|
|
def __init__(self, *specs, **kw):
|
|
|
|
if 'default' in kw:
|
|
|
|
self.default = kw.pop('default')
|
|
|
|
assert not kw, 'Bad kwargs for first.__init__'
|
2005-02-21 02:04:45 +01:00
|
|
|
self.spec = specs # for __repr__
|
2014-01-21 10:57:38 +01:00
|
|
|
self.specs = list(map(contextify, specs))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, state):
|
2005-06-13 19:27:15 +02:00
|
|
|
errored = False
|
2005-01-19 14:14:38 +01:00
|
|
|
for spec in self.specs:
|
|
|
|
try:
|
|
|
|
spec(irc, msg, args, state)
|
|
|
|
return
|
2014-01-20 15:49:15 +01:00
|
|
|
except Exception as e:
|
2013-03-25 19:15:08 +01:00
|
|
|
e2 = e # 'e' is local.
|
2005-06-13 19:27:15 +02:00
|
|
|
errored = state.errored
|
|
|
|
state.errored = False
|
2005-01-19 14:14:38 +01:00
|
|
|
continue
|
|
|
|
if hasattr(self, 'default'):
|
|
|
|
state.args.append(self.default)
|
|
|
|
else:
|
2005-06-13 19:27:15 +02:00
|
|
|
state.errored = errored
|
2013-03-25 19:15:08 +01:00
|
|
|
raise e2
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
class reverse(context):
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
args[:] = args[::-1]
|
|
|
|
super(reverse, self).__call__(irc, msg, args, state)
|
|
|
|
args[:] = args[::-1]
|
|
|
|
|
|
|
|
class commalist(context):
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
original = args[:]
|
|
|
|
st = state.essence()
|
|
|
|
trailingComma = True
|
|
|
|
try:
|
|
|
|
while trailingComma:
|
|
|
|
arg = args.pop(0)
|
|
|
|
if not arg.endswith(','):
|
|
|
|
trailingComma = False
|
|
|
|
for part in arg.split(','):
|
|
|
|
if part: # trailing commas
|
|
|
|
super(commalist, self).__call__(irc, msg, [part], st)
|
|
|
|
state.args.append(st.args)
|
2015-08-31 15:38:35 +02:00
|
|
|
except Exception:
|
2005-01-19 14:14:38 +01:00
|
|
|
args[:] = original
|
|
|
|
raise
|
|
|
|
|
|
|
|
class getopts(context):
|
|
|
|
"""The empty string indicates that no argument is taken; None indicates
|
|
|
|
that there is no converter for the argument."""
|
|
|
|
def __init__(self, getopts):
|
|
|
|
self.spec = getopts # for repr
|
|
|
|
self.getopts = {}
|
|
|
|
self.getoptL = []
|
2014-01-06 23:03:25 +01:00
|
|
|
self.getoptLs = ''
|
2015-08-08 22:20:14 +02:00
|
|
|
for (name, spec) in getopts.items():
|
2005-01-19 14:14:38 +01:00
|
|
|
if spec == '':
|
2014-01-06 23:03:25 +01:00
|
|
|
if len(name) == 1:
|
|
|
|
self.getoptLs += name
|
|
|
|
self.getopts[name] = None
|
2005-01-19 14:14:38 +01:00
|
|
|
self.getoptL.append(name)
|
|
|
|
self.getopts[name] = None
|
|
|
|
else:
|
2014-01-06 23:03:25 +01:00
|
|
|
if len(name) == 1:
|
|
|
|
self.getoptLs += name + ':'
|
|
|
|
self.getopts[name] = contextify(spec)
|
2005-01-19 14:14:38 +01:00
|
|
|
self.getoptL.append(name + '=')
|
|
|
|
self.getopts[name] = contextify(spec)
|
|
|
|
log.debug('getopts: %r', self.getopts)
|
|
|
|
log.debug('getoptL: %r', self.getoptL)
|
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, state):
|
|
|
|
log.debug('args before %r: %r', self, args)
|
2014-01-06 23:03:25 +01:00
|
|
|
(optlist, rest) = getopt.getopt(args, self.getoptLs, self.getoptL)
|
2005-01-19 14:14:38 +01:00
|
|
|
getopts = []
|
|
|
|
for (opt, arg) in optlist:
|
2014-01-06 23:03:25 +01:00
|
|
|
if opt.startswith('--'):
|
|
|
|
opt = opt[2:] # Strip --
|
|
|
|
else:
|
|
|
|
opt = opt[1:]
|
2005-01-19 14:14:38 +01:00
|
|
|
log.debug('opt: %r, arg: %r', opt, arg)
|
|
|
|
context = self.getopts[opt]
|
|
|
|
if context is not None:
|
|
|
|
st = state.essence()
|
|
|
|
context(irc, msg, [arg], st)
|
|
|
|
assert len(st.args) == 1
|
|
|
|
getopts.append((opt, st.args[0]))
|
|
|
|
else:
|
|
|
|
getopts.append((opt, True))
|
|
|
|
state.args.append(getopts)
|
|
|
|
args[:] = rest
|
|
|
|
log.debug('args after %r: %r', self, args)
|
|
|
|
|
|
|
|
###
|
|
|
|
# This is our state object, passed to converters along with irc, msg, and args.
|
|
|
|
###
|
|
|
|
|
|
|
|
class State(object):
|
|
|
|
log = log
|
|
|
|
def __init__(self, types):
|
|
|
|
self.args = []
|
|
|
|
self.kwargs = {}
|
|
|
|
self.types = types
|
|
|
|
self.channel = None
|
2005-06-01 22:13:33 +02:00
|
|
|
self.errored = False
|
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
if attr.startswith('error'):
|
|
|
|
self.errored = True
|
|
|
|
return getattr(dynamic.irc, attr)
|
|
|
|
else:
|
2014-01-20 15:43:55 +01:00
|
|
|
raise AttributeError(attr)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def essence(self):
|
|
|
|
st = State(self.types)
|
2015-08-08 22:20:14 +02:00
|
|
|
for (attr, value) in self.__dict__.items():
|
2005-01-19 14:14:38 +01:00
|
|
|
if attr not in ('args', 'kwargs'):
|
|
|
|
setattr(st, attr, value)
|
|
|
|
return st
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '%s(args=%r, kwargs=%r, channel=%r)' % (self.__class__.__name__,
|
|
|
|
self.args, self.kwargs,
|
|
|
|
self.channel)
|
|
|
|
|
|
|
|
|
|
|
|
###
|
|
|
|
# This is a compiled Spec object.
|
|
|
|
###
|
|
|
|
class Spec(object):
|
|
|
|
def _state(self, types, attrs={}):
|
|
|
|
st = State(types)
|
|
|
|
st.__dict__.update(attrs)
|
|
|
|
st.allowExtra = self.allowExtra
|
|
|
|
return st
|
|
|
|
|
|
|
|
def __init__(self, types, allowExtra=False):
|
|
|
|
self.types = types
|
|
|
|
self.allowExtra = allowExtra
|
2005-01-27 07:59:08 +01:00
|
|
|
utils.seq.mapinto(contextify, self.types)
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
def __call__(self, irc, msg, args, stateAttrs={}):
|
|
|
|
state = self._state(self.types[:], stateAttrs)
|
|
|
|
while state.types:
|
|
|
|
context = state.types.pop(0)
|
|
|
|
try:
|
|
|
|
context(irc, msg, args, state)
|
|
|
|
except IndexError:
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
if args and not state.allowExtra:
|
|
|
|
log.debug('args and not self.allowExtra: %r', args)
|
|
|
|
raise callbacks.ArgumentError
|
|
|
|
return state
|
|
|
|
|
2013-06-01 17:13:55 +02:00
|
|
|
def _wrap(f, specList=[], name=None, checkDoc=True, **kw):
|
2014-01-21 10:40:18 +01:00
|
|
|
name = name or f.__name__
|
2013-06-01 17:13:55 +02:00
|
|
|
assert (not checkDoc) or (hasattr(f, '__doc__') and f.__doc__), \
|
2013-06-01 16:35:47 +02:00
|
|
|
'Command %r has no docstring.' % name
|
2005-01-19 14:14:38 +01:00
|
|
|
spec = Spec(specList, **kw)
|
|
|
|
def newf(self, irc, msg, args, **kwargs):
|
|
|
|
state = spec(irc, msg, args, stateAttrs={'cb': self, 'log': self.log})
|
2005-05-18 06:18:35 +02:00
|
|
|
self.log.debug('State before call: %s', state)
|
2005-06-01 22:13:33 +02:00
|
|
|
if state.errored:
|
|
|
|
self.log.debug('Refusing to call %s due to state.errored.', f)
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
f(self, irc, msg, args, *state.args, **state.kwargs)
|
|
|
|
except TypeError:
|
|
|
|
self.log.error('Spec: %s', specList)
|
|
|
|
self.log.error('Received args: %s', args)
|
2014-01-21 10:40:18 +01:00
|
|
|
code = f.__code__
|
2005-06-01 22:13:33 +02:00
|
|
|
funcArgs = inspect.getargs(code)[0][len(self.commandArgs):]
|
|
|
|
self.log.error('Extra args: %s', funcArgs)
|
2011-03-01 08:47:53 +01:00
|
|
|
self.log.debug('Make sure you did not wrap a wrapped '
|
|
|
|
'function ;)')
|
2005-06-01 22:13:33 +02:00
|
|
|
raise
|
2014-01-21 16:33:35 +01:00
|
|
|
newf2 = utils.python.changeFunctionName(newf, name, f.__doc__)
|
2014-05-31 14:53:15 +02:00
|
|
|
newf2.__module__ = f.__module__
|
2014-01-21 16:33:35 +01:00
|
|
|
return internationalizeDocstring(newf2)
|
2013-05-20 17:40:04 +02:00
|
|
|
|
|
|
|
def wrap(f, *args, **kwargs):
|
|
|
|
if callable(f):
|
|
|
|
# Old-style call OR decorator syntax with no converter.
|
|
|
|
# f is the command.
|
|
|
|
return _wrap(f, *args, **kwargs)
|
|
|
|
else:
|
|
|
|
# Call with the Python decorator syntax
|
|
|
|
assert isinstance(f, list) or isinstance(f, tuple)
|
|
|
|
specList = f
|
|
|
|
def decorator(f):
|
|
|
|
return _wrap(f, specList, *args, **kwargs)
|
|
|
|
return decorator
|
2013-02-01 20:38:18 +01:00
|
|
|
wrap.__doc__ = """Useful wrapper for plugin commands.
|
|
|
|
|
|
|
|
Valid converters are: %s.
|
|
|
|
|
|
|
|
:param f: A command, taking (self, irc, msg, args, ...) as arguments
|
|
|
|
:param specList: A list of converters and contexts""" % \
|
|
|
|
', '.join(sorted(wrappers.keys()))
|
2005-01-19 14:14:38 +01:00
|
|
|
|
|
|
|
__all__ = [
|
|
|
|
# Contexts.
|
|
|
|
'any', 'many',
|
|
|
|
'optional', 'additional',
|
|
|
|
'rest', 'getopts',
|
|
|
|
'first', 'reverse',
|
|
|
|
'commalist',
|
|
|
|
# Converter helpers.
|
|
|
|
'getConverter', 'addConverter', 'callConverter',
|
|
|
|
# Decorators.
|
|
|
|
'urlSnarfer', 'thread',
|
|
|
|
# Functions.
|
2012-10-24 06:23:25 +02:00
|
|
|
'wrap', 'process', 'regexp_wrapper',
|
2005-01-19 14:14:38 +01:00
|
|
|
# Stuff for testing.
|
|
|
|
'Spec',
|
|
|
|
]
|
|
|
|
|
|
|
|
# This doesn't work. Suck.
|
|
|
|
## if world.testing:
|
|
|
|
## __all__.append('Spec')
|
|
|
|
|
2006-02-11 16:52:51 +01:00
|
|
|
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|