aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Twisted/py2/twisted/words/im/ircsupport.py
blob: e16bfcd0d77001b3b216d433551c2f6b4dfdb391 (plain) (blame)
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
IRC support for Instance Messenger.
"""

from twisted.words.protocols import irc
from twisted.words.im.locals import ONLINE
from twisted.internet import defer, reactor, protocol
from twisted.internet.defer import succeed
from twisted.words.im import basesupport, interfaces, locals
from zope.interface import implementer


class IRCPerson(basesupport.AbstractPerson):

    def imperson_whois(self):
        if self.account.client is None:
            raise locals.OfflineError
        self.account.client.sendLine("WHOIS %s" % self.name)


    ### interface impl
    def isOnline(self):
        return ONLINE


    def getStatus(self):
        return ONLINE


    def setStatus(self,status):
        self.status=status
        self.chat.getContactsList().setContactStatus(self)


    def sendMessage(self, text, meta=None):
        if self.account.client is None:
            raise locals.OfflineError
        for line in text.split('\n'):
            if meta and meta.get("style", None) == "emote":
                self.account.client.ctcpMakeQuery(self.name,[('ACTION', line)])
            else:
                self.account.client.msg(self.name, line)
        return succeed(text)



@implementer(interfaces.IGroup)
class IRCGroup(basesupport.AbstractGroup):
    def imgroup_testAction(self):
        pass


    def imtarget_kick(self, target):
        if self.account.client is None:
            raise locals.OfflineError
        reason = "for great justice!"
        self.account.client.sendLine("KICK #%s %s :%s" % (
            self.name, target.name, reason))


    ### Interface Implementation
    def setTopic(self, topic):
        if self.account.client is None:
            raise locals.OfflineError
        self.account.client.topic(self.name, topic)


    def sendGroupMessage(self, text, meta={}):
        if self.account.client is None:
            raise locals.OfflineError
        if meta and meta.get("style", None) == "emote":
            self.account.client.ctcpMakeQuery(self.name,[('ACTION', text)])
            return succeed(text)
        #standard shmandard, clients don't support plain escaped newlines!
        for line in text.split('\n'):
            self.account.client.say(self.name, line)
        return succeed(text)


    def leave(self):
        if self.account.client is None:
            raise locals.OfflineError
        self.account.client.leave(self.name)
        self.account.client.getGroupConversation(self.name,1)



class IRCProto(basesupport.AbstractClientMixin, irc.IRCClient):
    def __init__(self, account, chatui, logonDeferred=None):
        basesupport.AbstractClientMixin.__init__(self, account, chatui,
                                                 logonDeferred)
        self._namreplies={}
        self._ingroups={}
        self._groups={}
        self._topics={}


    def getGroupConversation(self, name, hide=0):
        name = name.lower()
        return self.chat.getGroupConversation(self.chat.getGroup(name, self),
                                              stayHidden=hide)


    def getPerson(self,name):
        return self.chat.getPerson(name, self)


    def connectionMade(self):
        # XXX: Why do I duplicate code in IRCClient.register?
        try:
            self.performLogin = True
            self.nickname = self.account.username
            self.password = self.account.password
            self.realname = "Twisted-IM user"

            irc.IRCClient.connectionMade(self)

            for channel in self.account.channels:
                self.joinGroup(channel)
            self.account._isOnline=1
            if self._logonDeferred is not None:
                self._logonDeferred.callback(self)
            self.chat.getContactsList()
        except:
            import traceback
            traceback.print_exc()


    def setNick(self,nick):
        self.name=nick
        self.accountName="%s (IRC)"%nick
        irc.IRCClient.setNick(self,nick)


    def kickedFrom(self, channel, kicker, message):
        """
        Called when I am kicked from a channel.
        """
        return self.chat.getGroupConversation(
            self.chat.getGroup(channel[1:], self), 1)


    def userKicked(self, kickee, channel, kicker, message):
        pass


    def noticed(self, username, channel, message):
        self.privmsg(username, channel, message, {"dontAutoRespond": 1})


    def privmsg(self, username, channel, message, metadata=None):
        if metadata is None:
            metadata = {}
        username = username.split('!',1)[0]
        if username==self.name: return
        if channel[0]=='#':
            group=channel[1:]
            self.getGroupConversation(group).showGroupMessage(username, message, metadata)
            return
        self.chat.getConversation(self.getPerson(username)).showMessage(message, metadata)


    def action(self,username,channel,emote):
        username = username.split('!',1)[0]
        if username==self.name: return
        meta={'style':'emote'}
        if channel[0]=='#':
            group=channel[1:]
            self.getGroupConversation(group).showGroupMessage(username, emote, meta)
            return
        self.chat.getConversation(self.getPerson(username)).showMessage(emote,meta)


    def irc_RPL_NAMREPLY(self,prefix,params):
        """
        RPL_NAMREPLY
        >> NAMES #bnl
        << :Arlington.VA.US.Undernet.Org 353 z3p = #bnl :pSwede Dan-- SkOyg AG
        """
        group = params[2][1:].lower()
        users = params[3].split()
        for ui in range(len(users)):
            while users[ui][0] in ["@","+"]: # channel modes
                users[ui]=users[ui][1:]
        if group not in self._namreplies:
            self._namreplies[group]=[]
        self._namreplies[group].extend(users)
        for nickname in users:
            try:
                self._ingroups[nickname].append(group)
            except:
                self._ingroups[nickname]=[group]


    def irc_RPL_ENDOFNAMES(self,prefix,params):
        group=params[1][1:]
        self.getGroupConversation(group).setGroupMembers(self._namreplies[group.lower()])
        del self._namreplies[group.lower()]


    def irc_RPL_TOPIC(self,prefix,params):
        self._topics[params[1][1:]]=params[2]


    def irc_333(self,prefix,params):
        group=params[1][1:]
        self.getGroupConversation(group).setTopic(self._topics[group],params[2])
        del self._topics[group]


    def irc_TOPIC(self,prefix,params):
        nickname = prefix.split("!")[0]
        group = params[0][1:]
        topic = params[1]
        self.getGroupConversation(group).setTopic(topic,nickname)


    def irc_JOIN(self,prefix,params):
        nickname = prefix.split("!")[0]
        group = params[0][1:].lower()
        if nickname!=self.nickname:
            try:
                self._ingroups[nickname].append(group)
            except:
                self._ingroups[nickname]=[group]
            self.getGroupConversation(group).memberJoined(nickname)


    def irc_PART(self,prefix,params):
        nickname = prefix.split("!")[0]
        group = params[0][1:].lower()
        if nickname!=self.nickname:
            if group in self._ingroups[nickname]:
                self._ingroups[nickname].remove(group)
                self.getGroupConversation(group).memberLeft(nickname)


    def irc_QUIT(self,prefix,params):
        nickname = prefix.split("!")[0]
        if nickname in self._ingroups:
            for group in self._ingroups[nickname]:
                self.getGroupConversation(group).memberLeft(nickname)
            self._ingroups[nickname]=[]


    def irc_NICK(self, prefix, params):
        fromNick = prefix.split("!")[0]
        toNick = params[0]
        if fromNick not in self._ingroups:
            return
        for group in self._ingroups[fromNick]:
            self.getGroupConversation(group).memberChangedNick(fromNick, toNick)
        self._ingroups[toNick] = self._ingroups[fromNick]
        del self._ingroups[fromNick]


    def irc_unknown(self, prefix, command, params):
        pass


    # GTKIM calls
    def joinGroup(self,name):
        self.join(name)
        self.getGroupConversation(name)



@implementer(interfaces.IAccount)
class IRCAccount(basesupport.AbstractAccount):
    gatewayType = "IRC"

    _groupFactory = IRCGroup
    _personFactory = IRCPerson

    def __init__(self, accountName, autoLogin, username, password, host, port,
                 channels=''):
        basesupport.AbstractAccount.__init__(self, accountName, autoLogin,
                                             username, password, host, port)
        self.channels = [channel.strip() for channel in channels.split(',')]
        if self.channels == ['']:
            self.channels = []


    def _startLogOn(self, chatui):
        logonDeferred = defer.Deferred()
        cc = protocol.ClientCreator(reactor, IRCProto, self, chatui,
                                    logonDeferred)
        d = cc.connectTCP(self.host, self.port)
        d.addErrback(logonDeferred.errback)
        return logonDeferred