~mgorven/ibid/dialing-codes-factpack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
from copy import copy
from datetime import timedelta
from inspect import getargspec, getmembers, ismethod
import logging
import re

from twisted.spread import pb
from twisted.plugin import pluginPackagePaths
from twisted.web import resource

import ibid
from ibid.compat import json

__path__.extend(pluginPackagePaths(__name__))

class Processor(object):
    """Base class for Ibid plugins.
    Processors receive events and (optionally) do things with them.

    Events are filtered in process() by to the following attributes:
    event_types: Only these types of events
    addressed: Require the bot to be addressed for public messages
    processed: Process events marked as already having been handled
    permission: The permission to check when calling @authorised handlers

    priority: Low priority Processors are handled first

    autoload: Load this Processor, when loading the plugin, even if not
    explicitly required in the configuration file
    """

    event_types = (u'message',)
    addressed = True
    processed = False
    priority = 0
    autoload = True

    __log = logging.getLogger('plugins')

    def __new__(cls, *args):
        if cls.processed and cls.priority == 0:
            cls.priority = 1500

        for name, option in options.items():
            new = copy(option)
            new.default = getattr(cls, name)
            setattr(cls, name, new)

        return super(Processor, cls).__new__(cls)

    def __init__(self, name):
        self.name = name
        self.setup()

    def setup(self):
        "Apply configuration. Called on every config reload"
        for name, method in getmembers(self, ismethod):
            if hasattr(method, 'run_every_config_key'):
                method.im_func.interval = timedelta(
                        seconds=getattr(self, method.run_every_config_key, 0))

    def shutdown(self):
        pass

    def process(self, event):
        "Process a single event"
        if event.type == 'clock':
            for name, method in getmembers(self, ismethod):
                if (hasattr(method, 'run_every')
                        and method.interval.seconds > 0
                        and not method.running):
                    method.im_func.running = True
                    if method.last_called is None:
                        # Don't fire first time
                        # Give sources a chance to connect
                        method.im_func.last_called = event.time
                    elif event.time - method.last_called >= method.interval:
                        method.im_func.last_called = event.time
                        try:
                            method(event)
                            if method.failing:
                                self.__log.info(u'No longer failing: %s.%s',
                                        self.__class__.__name__, name)
                                method.im_func.failing = False
                        except:
                            if not method.failing:
                                method.im_func.failing = True
                                self.__log.exception(
                                        u'Periodic method failing: %s.%s',
                                        self.__class__.__name__, name)
                            else:
                                self.__log.debug(u'Still failing: %s.%s',
                                        self.__class__.__name__, name)
                    method.im_func.running = False

        if event.type not in self.event_types:
            return

        if self.addressed and ('addressed' not in event or not event.addressed):
            return

        if not self.processed and event.processed:
            return

        found = False
        for name, method in getmembers(self, ismethod):
            if hasattr(method, 'handler'):
                if not hasattr(method, 'pattern'):
                    found = True
                    method(event)
                elif hasattr(event, 'message'):
                    found = True
                    match = method.pattern.search(
                            event.message[method.message_version])
                    if match is not None:
                        if (not getattr(method, 'auth_required', False)
                                or auth_responses(event, self.permission)):
                            method(event, *match.groups())
                        elif not getattr(method, 'auth_fallthrough', True):
                            event.processed = True

        if not found:
            raise RuntimeError(u'No handlers found in %s' % self)

        return event

# This is a bit yucky, but necessary since ibid.config imports Processor
from ibid.config import BoolOption, IntOption
options = {
    'addressed': BoolOption('addressed',
        u'Only process events if bot was addressed'),
    'processed': BoolOption('processed',
        u"Process events even if they've already been processed"),
    'priority': IntOption('priority', u'Processor priority'),
}

def handler(function):
    "Wrapper: Handle all events"
    function.handler = True
    function.message_version = 'clean'
    return function

def match(regex, version='clean'):
    "Wrapper: Handle all events where the message matches the regex"
    pattern = re.compile(regex, re.I | re.DOTALL)
    def wrap(function):
        function.handler = True
        function.pattern = pattern
        function.message_version = version
        return function
    return wrap

def auth_responses(event, permission):
    """Mark an event as having required authorisation, and return True if the
    event sender has permission.
    """
    if not ibid.auth.authorise(event, permission):
        event.complain = u'notauthed'
        return False

    return True

def authorise(fallthrough=True):
    """Require the permission specified in Processer.permission for the sender
    On failure, flags the event for Complain to respond appropriatly.
    If fallthrough=False, set the processed Flag to bypass later plugins.
    """
    def wrap(function):
        function.auth_required = True
        function.auth_fallthrough = fallthrough
        return function
    return wrap

def run_every(interval=0, config_key=None):
    "Wrapper: Run this handler every interval seconds"
    def wrap(function):
        function.run_every = True
        function.running = False
        function.last_called = None
        function.interval = timedelta(seconds=interval)
        if config_key is not None:
            function.run_every_config_key = config_key
        function.failing = False
        return function
    return wrap

from ibid.source.http import templates

class RPC(pb.Referenceable, resource.Resource):
    isLeaf = True

    def __init__(self):
        ibid.rpc[self.feature] = self
        self.form = templates.get_template('plugin_form.html')
        self.list = templates.get_template('plugin_functions.html')

    def get_function(self, request):
        method = request.postpath[0]

        if hasattr(self, 'remote_%s' % method):
            return getattr(self, 'remote_%s' % method)

        return None

    def render_POST(self, request):
        args = []
        for arg in request.postpath[1:]:
            try:
                arg = json.loads(arg)
            except ValueError, e:
                pass
            args.append(arg)

        kwargs = {}
        for key, value in request.args.items():
            try:
                value = json.loads(value[0])
            except ValueError, e:
                value = value[0]
            kwargs[key] = value

        function = self.get_function(request)
        if not function:
            return "Not found"

        try:
            result = function(*args, **kwargs)
            return json.dumps(result)
        except Exception, e:
            return json.dumps({'exception': True, 'message': unicode(e)})

    def render_GET(self, request):
        function = self.get_function(request)
        if not function:
            functions = []
            for name, method in getmembers(self, ismethod):
                if name.startswith('remote_'):
                    functions.append(name.replace('remote_', '', 1))

            return self.list.render(object=self.feature, functions=functions) \
                    .encode('utf-8')

        args, varargs, varkw, defaults = getargspec(function)
        del args[0]
        if len(args) == 0 or len(request.postpath) > 1 or len(request.args) > 0:
            return self.render_POST(request)

        return self.form.render(args=args).encode('utf-8')

# vi: set et sta sw=4 ts=4: