File: circ.py

package info (click to toggle)
circuits 3.2.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,980 kB
  • sloc: python: 17,583; javascript: 3,226; makefile: 100
file content (324 lines) | stat: -rwxr-xr-x 9,325 bytes parent folder | download | duplicates (2)
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/env python
"""
Circuits IRC Client

A circuits based IRC Client demonstrating integration with urwid - a curses
application development library and interacting with and processing irc
events from an IRC server.

NB: This is not a full featured client.

For usage type:

   ./circ.py --help
"""

import os
import sys
from optparse import OptionParser
from re import compile as compile_regex
from select import select
from socket import gethostname

from urwid import AttrWrap, Edit, Frame, ListBox, Pile, SimpleListWalker, Text
from urwid.raw_display import Screen

from circuits import Component, __version__ as systemVersion, handler
from circuits.net.sockets import TCPClient, connect
from circuits.protocols.irc import (
    ERR_NICKNAMEINUSE,
    ERR_NOMOTD,
    IRC,
    JOIN,
    NICK,
    PART,
    PRIVMSG,
    QUIT,
    RPL_ENDOFMOTD,
    USER,
    Message,
    request,
)
from circuits.tools import getargspec


USAGE = '%prog [options] host [port]'
VERSION = '%prog v' + systemVersion

MAIN_TITLE = f'cIRC - {systemVersion:s}'

HELP_STRINGS = {
    'main': 'For help, type: /help',
}

CMD_REGEX = compile_regex(
    r'\/(?P<command>[a-z]+) ?' '(?P<args>.*)(?iu)',
)


def back_merge(line, n, t=' '):
    return line[:-n].extend([t.join(line[-n:])])


def parse_options():
    parser = OptionParser(usage=USAGE, version=VERSION)

    parser.add_option(
        '-c',
        '--channel',
        action='store',
        default='#circuits',
        dest='channel',
        help='Channel to join',
    )

    parser.add_option(
        '',
        '--debug',
        action='store_true',
        default=False,
        dest='debug',
        help='Enable debug mode',
    )

    parser.add_option(
        '-n',
        '--nick',
        action='store',
        default=os.environ['USER'],
        dest='nick',
        help='Nickname to use',
    )

    opts, args = parser.parse_args()

    if len(args) < 1:
        parser.print_help()
        raise SystemExit(1)

    return opts, args


class Client(Component):
    channel = 'client'

    def init(self, host, port=6667, opts=None):
        self.host = host
        self.port = port
        self.opts = opts
        self.hostname = gethostname()

        self.nick = opts.nick
        self.ircchannel = opts.channel

        # Add TCPClient and IRC to the system.
        TCPClient(channel=self.channel).register(self)
        IRC(channel=self.channel).register(self)

        self.create_interface()

    def create_interface(self):
        self.screen = Screen()
        self.screen.start()

        self.screen.register_palette(
            [('title', 'white', 'dark blue', 'standout'), ('line', 'light gray', 'black'), ('help', 'white', 'dark blue')],
        )

        self.body = ListBox(SimpleListWalker([]))
        self.lines = self.body.body

        self.title = Text(MAIN_TITLE)
        self.header = AttrWrap(self.title, 'title')

        self.help = AttrWrap(
            Text(HELP_STRINGS['main']),
            'help',
        )

        self.input = Edit(caption='%s> ' % self.ircchannel)
        self.footer = Pile([self.help, self.input])

        self.top = Frame(self.body, self.header, self.footer)

    def ready(self, component):
        """
        Ready Event

        This event is triggered by the underlying ``TCPClient`` Component
        when it is ready to start making a new connection.
        """
        self.fire(connect(self.host, self.port))

    def connected(self, host, port):
        """
        connected Event

        This event is triggered by the underlying ``TCPClient`` Component
        when a successfully connection has been made.
        """
        nick = self.nick
        hostname = self.hostname
        name = f'{nick} on {hostname} using circuits/{systemVersion}'

        self.fire(NICK(nick))
        self.fire(USER(nick, hostname, host, name))

    def numeric(self, source, numeric, *args):
        """
        Numeric Event

        This event is triggered by the ``IRC`` Protocol Component when we have
        received an IRC Numberic Event from server we are connected to.
        """
        if numeric == ERR_NICKNAMEINUSE:
            self.fire(NICK(f'{args[0]:s}_'))
        elif numeric in (RPL_ENDOFMOTD, ERR_NOMOTD):
            self.fire(JOIN(self.ircchannel))

    @handler('stopped', channel='*')
    def _on_stopped(self, component):
        self.screen.stop()

    @handler('generate_events')
    def _on_generate_events(self, event):
        event.reduce_time_left(0)

        size = self.screen.get_cols_rows()

        if select(self.screen.get_input_descriptors(), [], [], 0.1)[0] != []:
            _timeout, keys, _raw = self.screen.get_input_nonblocking()

            for k in keys:
                if k == 'window resize':
                    size = self.screen.get_cols_rows()
                    continue
                if k == 'enter':
                    self.processCommand(self.input.get_edit_text())
                    self.input.set_edit_text('')
                    continue

                self.top.keypress(size, k)
                self.input.set_edit_text(self.input.get_edit_text() + k)

        self.update_screen(size)

    def unknownCommand(self, command):
        self.lines.append(Text('Unknown command: %s' % command))

    def syntaxError(self, command, args, expected):
        self.lines.append(
            Text(
                f'Syntax error ({command:s}): {args:s} Expected: {expected:s}',
            ),
        )

    def processCommand(self, s):  # noqa
        match = CMD_REGEX.match(s)
        if match is not None:
            command = match.groupdict()['command']
            tokens = match.groupdict()['args'].split(' ') if match.groupdict()['args'] != '' else []

            fn = 'cmd' + command.upper()
            if hasattr(self, fn):
                f = getattr(self, fn)
                if callable(f):
                    args, vargs, _kwargs, default = getargspec(f)
                    args.remove('self')
                    if len(args) == len(tokens):
                        if len(args) == 0:
                            f()
                        else:
                            f(*tokens)
                    else:
                        if len(tokens) > len(args):
                            if vargs is None:
                                if len(args) > 0:
                                    factor = len(tokens) - len(args) + 1
                                    f(*back_merge(tokens, factor))
                                else:
                                    self.syntaxError(
                                        command,
                                        ' '.join(tokens),
                                        ' '.join(x for x in args + [vargs] if x is not None),
                                    )
                            else:
                                f(*tokens)
                        elif default is not None and len(args) == (len(tokens) + len(default)):
                            f(*(tokens + list(default)))
                        else:
                            self.syntaxError(
                                command,
                                ' '.join(tokens),
                                ' '.join(x for x in args + [vargs] if x is not None),
                            )
        else:
            if self.ircchannel is not None:
                self.lines.append(Text(f'<{self.nick}> {s}'))
                self.fire(PRIVMSG(self.ircchannel, s))
            else:
                self.lines.append(Text('No channel joined. Try /join #<channel>'))

    def cmdEXIT(self, message=''):
        self.fire(QUIT(message))
        raise SystemExit(0)

    def cmdSERVER(self, host, port=6667):
        self.fire(connect(host, port))

    def cmdSSLSERVER(self, host, port=6697):
        self.fire(connect(host, port, secure=True))

    def cmdJOIN(self, channel):
        if self.ircchannel is not None:
            self.cmdPART(self.ircchannel, 'Joining %s' % channel)
        self.fire(JOIN(channel))
        self.ircchannel = channel

    def cmdPART(self, channel=None, message='Leaving'):
        if channel is None:
            channel = self.ircchannel
        if channel is not None:
            self.fire(PART(channel, message))
            self.ircchannel = None

    def cmdQUOTE(self, message):
        self.fire(request(Message(message)))

    def cmdQUIT(self, message='Bye'):
        self.fire(QUIT(message))

    def update_screen(self, size):
        canvas = self.top.render(size, focus=True)
        self.screen.draw_screen(size, canvas)

    @handler('notice', 'privmsg')
    def _on_notice_or_privmsg(self, event, source, target, message):
        nick, _ident, _host = source

        if event.name == 'notice':
            self.lines.append(Text(f'-{nick}- {message}'))
        else:
            self.lines.append(Text(f'<{nick}> {message}'))


def main():
    opts, args = parse_options()

    host = args[0]
    port = int(args[1]) if len(args) > 1 else 6667

    # Configure and run the system.

    client = Client(host, port, opts=opts)

    if opts.debug:
        from circuits import Debugger

        Debugger(file=sys.stderr).register(client)

    client.run()


if __name__ == '__main__':
    main()