ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/Net-IRC3/samples/jsonsrv
Revision: 1.1
Committed: Wed Dec 6 13:12:11 2006 UTC (19 years, 9 months ago) by elmex
Branch: MAIN
Log Message:
added the json irc sample application

File Contents

# User Rev Content
1 elmex 1.1 #!/usr/bin/perl
2     use strict;
3     use AnyEvent::Impl::Perl;
4     use JSON::Syck;
5     use JSONConnection;
6     use Net::IRC3::Client::Connection;
7     $Net::IRC3::Client::Connection::DEBUG = 1;
8    
9     our $CFG;
10     our %CONNS;
11    
12     sub load_cfg {
13     $CFG ||= {};
14     return unless -e "$ENV{HOME}/.jsonircrc";
15     open CFGH, "<", "$ENV{HOME}/.jsonircrc" or die "Couldn't open ~/.jsonircrc: $!";
16     $::CFG = JSON::Syck::Load (do { local $/; <CFGH> });
17     }
18    
19     sub save_cfg {
20     open CFGH, ">", "$ENV{HOME}/.jsonircrc" or die "Couldn't open for writing ~/.jsonircrc: $!";
21     print CFGH (JSON::Syck::Dump ($::CFG));
22     close CFGH;
23     }
24    
25     load_cfg;
26    
27     my $c = AnyEvent->condvar;
28    
29     my $js =
30     JSONConnection->new (
31     packet_cb => sub {
32     my ($js, $lid, $data) = @_;
33     my $con = $CONNS{$data->{con}};
34    
35     if ($data->{type} eq 'public') {
36     $con->send_srv (PRIVMSG => $data->{message} => $data->{channel});
37     } elsif ($data->{type} eq 'private') {
38     $con->send_srv (PRIVMSG => $data->{message} => $data->{target});
39     }
40     },
41     connect_cb => sub {
42     my ($js, $lid) = @_;
43     $js->send_data ($lid,
44     { type => "channels", map { $_ => [ keys %{$CONNS{$_}->channel_list} ] } keys %CONNS }
45     );
46     });
47    
48     for my $con (@{$CFG->{servers}}) {
49     my ($host, $port) = ($con->{host}, $con->{port} || 6667);
50     my $ircid = "$host:$port";
51     my $pc = $CONNS{$ircid} = Net::IRC3::Client::Connection->new;
52     $pc->reg_cb (
53     publicmsg => sub {
54     my ($pc, $chan, $msg) = @_;
55     my ($nick) = Net::IRC3::Util::split_prefix ($msg->{prefix});
56     $js->broadcast ({
57     con => $ircid,
58     type => "public",
59     channel => $chan,
60     message => $msg->{trailing},
61     from => { nick => $nick, info => $msg->{prefix} },
62     });
63     1;
64     },
65     privatemsg => sub {
66     my ($pc, $dsgnick, $msg) = @_;
67     my ($nick) = Net::IRC3::Util::split_prefix ($msg->{prefix});
68     $js->broadcast ({
69     con => $ircid,
70     type => "private",
71     message => $msg->{trailing},
72     from => { nick => $nick, info => $msg->{prefix} },
73     });
74     1;
75     },
76     );
77    
78     $pc->connect ($host, $port);
79     $pc->register (qw/elmex2 elmex2 elmex2/);
80    
81     for (@{$con->{channels}}) {
82     $pc->send_srv (JOIN => undef => $_);
83     }
84     }
85    
86     $js->start_listener;
87    
88     $c->wait;