~ubuntu-branches/ubuntu/utopic/gozerbot/utopic

« back to all changes in this revision

Viewing changes to build/lib/gozerbot/xmpp/message.py

  • Committer: Package Import Robot
  • Author(s): Jeremy Malcolm
  • Date: 2012-04-03 21:58:28 UTC
  • mfrom: (3.1.11 sid)
  • Revision ID: package-import@ubuntu.com-20120403215828-6mik0tzug5na93la
Tags: 0.99.1-2
* Removes logfiles on purge (Closes: #668767)
* Reverted location of installed files back to /usr/lib/gozerbot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# gozerbot/xmpp/message.py
 
2
#
 
3
#
 
4
 
 
5
""" jabber message definition .. types can be normal, chat, groupchat, 
 
6
    headline or  error
 
7
"""
 
8
 
 
9
__copyright__ = 'this file is in the public domain'
 
10
 
 
11
# gozerbot imports
 
12
from gozerbot.utils.exception import handle_exception
 
13
from gozerbot.utils.log import rlog
 
14
from gozerbot.utils.trace import whichmodule
 
15
from gozerbot.utils.generic import toenc, fromenc, jabberstrip, makeargrest
 
16
from gozerbot.utils.locking import lockdec
 
17
from gozerbot.eventbase import EventBase
 
18
from gozerbot.config import config
 
19
 
 
20
# xmpp imports
 
21
from core import XMLDict
 
22
 
 
23
# basic imports
 
24
import types, time, thread
 
25
 
 
26
# locks
 
27
replylock = thread.allocate_lock()
 
28
replylocked = lockdec(replylock)
 
29
 
 
30
if config['dotchars']:
 
31
    dotchars = config['dotchars']
 
32
else:
 
33
    dotchars = ' .. '
 
34
 
 
35
class Message(EventBase):
 
36
 
 
37
    """ jabber message object. """
 
38
 
 
39
    def __init__(self, nodedict={}, bot=None):
 
40
        EventBase.__init__(self, nodedict, bot)
 
41
        self.element = "message"
 
42
        self.jabber = True
 
43
        rlog(2, whichmodule(1), 'MESSAGE: ' + str(self))
 
44
 
 
45
    def __copy__(self):
 
46
        return Message(self, self.bot)
 
47
 
 
48
    def __deepcopy__(self, bla):
 
49
        return Message(self, self.bot)
 
50
 
 
51
                 
 
52
    #@replylocked
 
53
    def reply(self, txt, result=None, nick=None, dot=False, nritems=False, nr=False, fromm=None, private=False):
 
54
 
 
55
        """ reply txt. """
 
56
 
 
57
        if result == []:
 
58
            return
 
59
 
 
60
        restxt = ""
 
61
 
 
62
        if type(result) == types.DictType:
 
63
 
 
64
            for i, j in result.iteritems():
 
65
                if type(j) == types.ListType:
 
66
                    try:
 
67
                        z = dotchars.join(j)
 
68
                    except TypeError:
 
69
                        z = unicode(j)
 
70
                else:
 
71
                    z = j
 
72
                if dot == True:
 
73
                    restxt += "%s: %s %s " % (i, z, dotchars)
 
74
                elif dot:
 
75
                    restxt += "%s: %s %s " % (i, z, dot)
 
76
                else:
 
77
                    restxt += "%s: %s " % (i, z)
 
78
 
 
79
            if restxt:
 
80
                if dot == True:
 
81
                    restxt = restxt[:-6]
 
82
                elif dot:
 
83
                    restxt = restxt[:-len(dot)]
 
84
        lt = False
 
85
 
 
86
        if type(txt) == types.ListType and not result:
 
87
            result = txt
 
88
            origtxt = ""
 
89
            lt = True
 
90
        else:
 
91
            origtxt = txt
 
92
 
 
93
        if result:
 
94
            lt = True
 
95
 
 
96
        if self.queues:
 
97
            for i in self.queues:
 
98
                if lt:
 
99
                    for j in result:
 
100
                        i.put_nowait(j)
 
101
                else:
 
102
                    i.put_nowait(txt)
 
103
            if self.onlyqueues:
 
104
                return
 
105
 
 
106
        pretxt = origtxt
 
107
 
 
108
        if lt and not restxt:
 
109
            res = []
 
110
            for i in result:
 
111
                if type(i) == types.ListType or type(i) == types.TupleType:
 
112
                    try:
 
113
                        res.append(dotchars.join(i))
 
114
                    except TypeError:
 
115
                        res.append(unicode(i))
 
116
                else:
 
117
                    res.append(i)
 
118
            result = res
 
119
            if nritems:
 
120
                if len(txt) > 1:
 
121
                    pretxt = "(%s items) .. " % len(result)
 
122
            txtlist = [unicode(i) for i in result]
 
123
            if not nr is False:
 
124
                try:
 
125
                    start = int(nr)
 
126
                except ValueError:
 
127
                    start = 0
 
128
                txtlist2 = []
 
129
                teller = start
 
130
                for i in txtlist:
 
131
                    txtlist2.append("%s) %s" % (teller, i))
 
132
                    teller += 1
 
133
                txtlist = txtlist2
 
134
            if dot == True:
 
135
                restxt = dotchars.join(txtlist)
 
136
            elif dot:
 
137
                restxt = dot.join(txtlist)
 
138
            else:
 
139
                restxt = ' '.join(txtlist)
 
140
 
 
141
        if pretxt:
 
142
            restxt = pretxt + restxt
 
143
 
 
144
        txt = jabberstrip(restxt)
 
145
 
 
146
        if not txt:
 
147
            return
 
148
 
 
149
        what = txt
 
150
        txtlist = []
 
151
        start = 0
 
152
        end = 900
 
153
        length = len(what)
 
154
 
 
155
        for i in range(length/end+1):
 
156
            endword = what.find(' ', end)
 
157
            if endword == -1:
 
158
                endword = end
 
159
            txtlist.append(what[start:endword])
 
160
            start = endword
 
161
            end = start + 900
 
162
 
 
163
        size = 0
 
164
 
 
165
        # see if we need to store output in less cache
 
166
        if len(txtlist) > 1:
 
167
            self.bot.less.add(self.userhost, txtlist)
 
168
            size = len(txtlist) - 1
 
169
            result = txtlist[:1][0]
 
170
            if size:
 
171
                result += " (+%s)" % size
 
172
        else:
 
173
            result = txtlist[0]
 
174
 
 
175
        if self.filtered(result):
 
176
            return
 
177
 
 
178
        try:
 
179
            to = self.options['--to']
 
180
        except KeyError:
 
181
            to = None
 
182
 
 
183
        outtype = self.type
 
184
 
 
185
        if to and to in self.bot.state['joinedchannels']:
 
186
            outtype = 'groupchat' 
 
187
            self.groupchat = True
 
188
            self.msg = False
 
189
 
 
190
        repl = Message({'from': self.me, 'to': to or self.jid, 'type': outtype, 'txt': result})
 
191
 
 
192
        if self.groupchat:
 
193
            if self.resource == self.bot.nick:
 
194
                return
 
195
            if to:
 
196
                pass
 
197
            elif nick:
 
198
                repl.type = 'chat'
 
199
            elif private:
 
200
                repl.to = self.userhost
 
201
            elif self.printto:
 
202
                repl.to = self.printto
 
203
            else:
 
204
                repl.to = self.channel
 
205
 
 
206
        #repl['from'] = self.bot.me
 
207
 
 
208
        if nick:
 
209
            repl.type = 'normal'
 
210
        elif not repl.type:
 
211
            repl.type = 'chat'
 
212
 
 
213
        self['bot'].send(repl)
 
214
 
 
215
    def toirc(self):
 
216
 
 
217
        """ set ircevent compat attributes. """
 
218
 
 
219
        self.jidchange = False
 
220
        self.cmnd = 'Message'
 
221
 
 
222
        try:
 
223
            self.resource = self.fromm.split('/')[1]
 
224
        except IndexError:
 
225
            pass
 
226
 
 
227
        self.channel = self['fromm'].split('/')[0]
 
228
        self.origchannel = self.channel
 
229
        self.nick = self.resource
 
230
 
 
231
        try:
 
232
            if self.bot:
 
233
                self.jid = self.bot.jids[self.channel][self.resource]
 
234
                self.jidchange = True
 
235
            else:
 
236
                self.jid = self.fromm
 
237
        except KeyError:
 
238
            self.jid = self.fromm
 
239
 
 
240
        self.ruserhost = self.jid
 
241
        self.userhost = self.jid
 
242
        self.stripped = self.jid.split('/')[0]
 
243
        self.printto = self.channel
 
244
 
 
245
        for node in self.subelements:
 
246
            try:
 
247
                self.txt = node.body.data
 
248
            except (AttributeError, ValueError):
 
249
                continue
 
250
        self.origtxt = self.txt
 
251
        self.time = time.time()
 
252
 
 
253
        if self.type == 'groupchat':
 
254
            self.groupchat = True
 
255
            if self.jidchange:
 
256
                self.userhost = self.stripped
 
257
        else:
 
258
            self.groupchat = False
 
259
            self.userhost = self.stripped
 
260
 
 
261
        self.msg = not self.groupchat
 
262
 
 
263
    def errorHandler(self):
 
264
        try:
 
265
            code = self.get('error').code
 
266
        except Exception, ex:
 
267
            handle_exception()
 
268
        try:
 
269
            method = getattr(self, "handle_%s" % code)
 
270
            if method:
 
271
                rlog(10, 'message', 'dispatching error to handler %s' % str(method))
 
272
                method(self)
 
273
        except AttributeError, ex:
 
274
            rlog(10, 'message', 'unhandled error %s' % code)
 
275
        except:
 
276
            handle_exception()
 
277