-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc_client_service.rb
650 lines (580 loc) · 18.9 KB
/
irc_client_service.rb
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
module IrcClientService
require 'timeout'
require "socket"
require 'thread'
require 'ircreplies'
require 'netutils'
include IRCReplies
# The irc class, which talks to the server and holds the main event loop
class IrcActor
include NetUtils
attr_reader :channels
#===========================================================
#events
#===========================================================
def initialize(client)
@client = client
@eventqueue = ConditionVariable.new
@eventlock = Mutex.new
@events = []
@channels = {}
@store = {
:ping =>
Proc.new {|server|
client.send_pong server
},
:pong =>
Proc.new {|server|
puts "pong:#{server}"
},
:notice=>
[Proc.new {|user,channel,msg|
puts "Server:#{msg}"
#client.msg_channel channel,"message from #{user} on #{channel} : #{msg}"
}],
:privmsg =>
[Proc.new {|user,channel,msg|
#puts "message from #{user} on #{channel} : #{msg}"
#client.msg_channel channel,"message from #{user} on #{channel} : #{msg}"
}],
:connect =>
[Proc.new {|server,port,nick,pass|
#puts "on connect #{server}:#{port}"
client.send_pass pass
client.send_nick nick
client.send_user nick,'0','*',"#{server} Net Bot"
}],
:numeric =>
[Proc.new {|server,numeric,msg,detail|
#puts "on numeric #{server}:#{numeric}"
}],
:join=>
[Proc.new {|nick,channel|
#puts "on join"
}],
:part=>
[Proc.new {|nick,channel,msg|
#puts "on part"
}],
:quit=>
[Proc.new {|nick,msg|
#puts "on quit"
}],
:unknown =>
[Proc.new {|line|
puts ">unknown message #{line}"
}]
}
end
#===========================================================
#on_xxx appends to registered callbacks
#use [] to reset callbacks
#===========================================================
def on_connect(&block)
raise IrcError.new('wrong arity') if block.arity != 4
self[:connect] << block
end
def on_ping(&block)
raise IrcError.new('wrong arity') if block.arity != 1
self[:ping] << block
end
def on_privmsg(&block)
raise IrcError.new('wrong arity') if block.arity != 3
self[:privmsg] << block
end
def on_numeric(numarray,&block)
raise IrcError.new('wrong arity') if block.arity != 4
self[:numeric] << Proc.new {|server,numeric,msg,detail|
case numeric
when *numarray
block.call(server,numeric,msg,detail)
end
}
end
def on_rpl(num,&block)
raise IrcError.new('wrong arity') if block.arity != 3
self[:numeric] << Proc.new {|server,numeric,msg,detail|
block.call(server,msg,detail) if num == numeric
}
end
def on_err(num,&block)
on_rpl(num,block)
end
def on(method,&block)
self[method] << block
end
#===========================================================
def [](method)
@store[method] = [] if @store[method].nil?
return @store[method]
end
def push(method,*args)
@eventlock.synchronize {
@events << [method,args]
@eventqueue.signal
}
end
def send_names(channel)
@client.send_names channel
channel
end
def send_message(user,message)
@client.msg_user user, message
user
end
def send(message)
@client.send message
message
end
def run
while true
begin
method,args = :unknown,''
@eventlock.synchronize {
@eventqueue.wait(@eventlock) if @events.empty?
method,args = @events.shift
}
self[method].each {|block| block[*args] }
rescue SystemExit => e
exit 0
rescue Exception => e
carp e
end
end
end
def join(channel)
@client.send_join channel
@channels[channel] = Time.now
channel
end
def part(channel)
if @channels.delete(channel)
@client.send_part channel
channel
else
'not member'
end
end
def nick
return @nick
end
def names(channel)
return @client.names(channel)
end
end
class PrintActor < IrcActor
def initialize(client)
super(client)
on(:connect) {|server,port,nick,pass|
client.send_join '#db'
}
on(:numeric) {|server,numeric,msg,detail|
#puts "-:#{numeric}"
}
on(:join) {|nick,channel|
#puts "#{nick} join-:#{channel}"
#client.msg_channel '#markee', "heee"
}
on(:part) {|nick,channel,msg|
#puts "#{nick} part-:#{channel}"
}
on(:quit) {|nick,msg|
#puts "#{nick} quit-:#{channel}"
}
end
end
class TestActor < IrcActor
def initialize(client)
super(client)
on(:connect) {|server,port,nick,pass|
client.send_join '#db'
}
on(:numeric) {|server,numeric,msg,detail|
puts "-:#{numeric}"
}
on(:join) {|nick,channel|
puts "#{nick} join-:#{channel}"
}
on(:part) {|nick,channel,msg|
puts "#{nick} part-:#{channel}"
}
on(:quit) {|nick,msg|
puts "#{nick} quit-:#{nick}:#{msg}"
}
on(:privmsg) {|nick,channel,msg|
case msg
when /^ *!who +([^ ]+) *$/
names = names($1)
send_message channel, "names: #{names.join(',')}"
end
}
end
end
require 'rubygems'
require 'xmpp4r-simple'
class JabberActor < IrcActor
def initialize(client)
super(client)
config = YAML.load(open("jabber.yml"))
im = Jabber::Simple.new(config["jid"], config["password"])
Thread.new do
begin
while true do
sleep 3
im.received_messages do |m|
puts "I got a message, #{m.body}"
if m.type == :chat
client.msg_channel "##{config["channel"]}", "#{m.from}: #{m.body}"
config["recipients"].each do |r|
im.deliver(r, "#{m.from}: #{m.body}")
end
end
end
end
rescue Exception
puts $!
end
end
on(:connect) {|server,port,nick,pass|
client.send_join "##{config['channel']}"
puts "joint #{config['channel']}"
}
on(:privmsg) do |nick, channel, msg|
puts "delivering #{msg}"
config["recipients"].each do |r|
im.deliver(r, "#{nick}: #{msg}")
end
end
end
end
class IrcConnector
include IRCReplies
include NetUtils
extend NetUtils
attr_reader :server, :port, :nick, :socket
attr_writer :actor, :socket
def initialize(server, port, nick, pass)
@server = server
@port = port
@nick = nick
@pass = pass
@actor = IrcActor.new(self)
@readlock = Mutex.new
@writelock = Mutex.new
@inputlock = Mutex.new
@inputqueue = ConditionVariable.new
end
def run
connect()
@eventloop = Thread.new { @actor.run }
listen_loop
end
def connect()
begin
#allow socket to be handed over from elsewhere.
@socket = @socket || TCPSocket.open(@server, @port)
@actor[:connect].each{|c| c[ @server, @port, @nick, @pass]}
rescue
raise "Cannot connect #{@server}:#{@port}"
end
end
#===========================================================
def process(input)
input.untaint
s = input
prefix = ''
user = ''
if input =~ /^:([^ ]+) +(.*)$/
s = $2
prefix = $1
user = if prefix =~ /^([^!]+)!(.+)/
$1
else
prefix
end
end
cmd = s
suffix = ''
if s =~ /([^:]+):(.*)$/
cmd = $1.strip
suffix = $2
end
case cmd
when /^PING$/i
#dont bother about event loop here.
@actor[:ping][suffix]
when /^PONG$/i
@actor[:pong][suffix]
when /^NOTICE +(.+)$/i
@actor.push :notice, user, $1, suffix
when /^PRIVMSG +(.+)$/i
@actor.push :privmsg, user, $1, suffix
when /^JOIN$/i
#the confirmation join channel will come in suffix
@actor.push :join, user, suffix
when /^PART +(.+)$/i
#the confirmation part channel will come in cmd arg.
@actor.push :part, user, $1, suffix
when /^QUIT$/i
@actor.push :quit, user, suffix
when /^([0-9]+) +(.+)$/i
server,numeric,msg,detail = prefix, $1.to_i,$2, suffix
@actor.push :numeric, server,numeric,msg,detail if !local_numeric(numeric,msg,detail)
else
@actor.push :unknown, input
end
end
def listen_loop()
process(gets) while [email protected]?
end
#WARNING: UGLY HACK.
def local_numeric(numeric,msg,detail)
if @capture_numeric
case numeric
when ERR_NOSUCHNICK
if msg =~ / *[^ ]+ +([^ ]+)*$/
if $1 == @capture_channel
@inputlock.synchronize {
@args << [numeric,msg,detail]
@inputqueue.signal
}
return true
end
end
when RPL_ENDOFNAMES
if msg =~ / *[^ ]+ +([^ ]+)*$/
if $1 == @capture_channel
@inputlock.synchronize {
@args << [numeric,msg,detail]
@inputqueue.signal
}
return true
end
end
when RPL_NAMREPLY
if msg =~ / *[^ ]+ *= +([^ ]+)*$/
if $1 == @capture_channel
@inputlock.synchronize {
@args << [numeric,msg,detail]
@inputqueue.signal
}
return true
end
end
end
end
return false #continue with processing
end
#will be invoked from a thread different from that of the
#primary IrcConnector thread.
def names(channel)
carp "invoke names for #{channel}"
@names = []
@args = []
@capture_channel = channel.chomp
@capture_numeric = true
send_names channel
while true
numeric, msg, detail = 0,'',''
@inputlock.synchronize {
@inputqueue.wait(@inputlock) if @args.empty?
numeric, msg, detail = @args.shift
}
case numeric
when ERR_NOSUCHNICK
carp ERR_NOSUCHNICK
break
when RPL_ENDOFNAMES
carp "#{RPL_ENDOFNAMES} #{@names}"
break
when RPL_NAMREPLY
nicks = detail.split(/ +/)
nicks.each {|n| @names << $1.strip if n =~ /^@?([^ ]+)/ }
carp "nicks #{nicks}"
end
end
carp "returning #{@names}"
@capture_numeric = false
return @names
end
#=====================================================
def lock_read
@readlock.lock
end
def unlock_read
@readlock.unlock
end
def lock_write
@writelock.lock
end
def unlock_write
@writelock.unlock
end
#=====================================================
def send_pong(arg)
send "PONG :#{arg}"
end
def send_pass(pass)
send "PASS #{pass}"
end
def send_nick(nick)
send "NICK #{nick}"
end
def send_user(user,mode,unused,real)
send "USER #{user} #{mode} #{unused} :#{real}"
end
def send_names(channel)
send "NAMES #{channel}"
end
def send(msg)
send "#{msg}"
end
#=====================================================
def send_join(channel)
send "JOIN #{channel}"
end
def send_part(channel)
send "PART #{channel} :"
end
def msg_user(user,data)
msg_channel(user, data)
end
def msg_channel(channel, data)
send "PRIVMSG #{channel} :#{data}"
end
def notice_channel(channel, data)
send "NOTICE #{channel} :#{data}"
end
def gets
s = nil
@readlock.synchronize {
s = @socket.gets
}
#carp "<#{s}"
return s
end
def send(s)
#carp ">#{s}"
@writelock.synchronize { @socket << "#{s}\n" }
end
#=====================================================
def IrcConnector.start(opts={})
server = opts[:server] or raise 'No server defined.'
nick = opts[:nick] || '_' + Socket.gethostname.split(/\./).shift
port = opts[:port] || 6667
pass = opts[:pass] || 'netserver'
irc = IrcConnector.new(server, port , nick, pass)
#irc.actor = PrintActor.new(irc)
#irc.actor = TestActor.new(irc)
irc.actor = JabberActor.new(irc)
begin
irc.run
rescue SystemExit => e
puts "exiting..#{e.message()}"
exit 0
rescue Interrupt
exit 0
rescue Exception => e
carp e
end
end
end
#=====================================================
class ProxyConnector
attr_reader :server, :nick
attr_writer :actor
def initialize(nick, pass, server, actor)
@server = 'service'
@nick = nick
@pass = pass
@actor = actor.new(self)
@ircserver = server
end
#=====================================================
def invoke(method, *args)
@actor[method].each{|c| c[*args]}
end
#called during connection.
def connect
@actor[:connect].each{|c| c[ @server, @port, @nick, @pass]}
end
def ping(arg)
@actor[:ping].each{|c| c[arg]}
end
def privmsg(nick, channel, msg)
@actor[:privmsg].each{|c| c[nick, channel, msg]}
end
def notice(nick, channel, msg)
@actor[:notice].each{|c| c[nick, channel, msg]}
end
def join(nick, channel)
@actor[:join].each{|c| c[nick, channel]}
end
def part(nick, channel, msg)
@actor[:part].each{|c| c[nick, channel, msg]}
end
def quit(nick, msg)
@actor[:quit].each{|c| c[nick, msg]}
end
def numeric(server,numeric,msg, detail)
@actor[:numeric].each{|c| c[server,numeric,msg,detail]}
end
def unknown(arg)
@actor[:unknown].each{|c| c[arg]}
end
#=====================================================
def send_pong(arg)
@ircserver.invoke :pong,arg
end
def send_pass(arg)
@ircserver.invoke :pass,arg
end
def send_nick(arg)
@ircserver.invoke :nick,arg
end
def send_user(user,mode,unused,real)
@ircserver.invoke :user, user, mode, unused, real
end
def send_names(arg)
@ircserver.invoke :names,arg
end
def send_join(arg)
@ircserver.invoke :join,arg
end
def send_part(channel)
@ircserver.invoke :part,arg
end
def msg_channel(channel, data)
@ircserver.invoke :privmsg,channel, data
end
#=====================================================
def names(channel)
return @ircserver.names(channel)
end
def msg_user(user,data)
msg_channel(user, data)
end
end
#=====================================================
if __FILE__ == $0
server = 'localhost'
port = 6667
nick = 'bot'
while arg = ARGV.shift
case arg
when /-s/
server = ARGV.shift
when /-p/
port = ARGV.shift
when /-n/
nick = ARGV.shift
when /-v/
$verbose = true
end
end
IrcConnector.start :server => server,
:port => port,
:nick => nick,
:pass => 'netserver'
end
end