#!/usr/bin/perl
#Omegle client
#By James Stanley

#configuration

my $host = "http://omegle.com";

#end config

use LWP;
use JSON;
use Text::ParseWords;

my $response, $sessid;
my $ua = LWP::UserAgent->new;
my $pid;

sub handle {
    my ($text) = @_;

    if($text eq null) {
        return;
    }

    #remove the enclosing brackets
    $text =~ s/^\[//;
    $text =~ s/\]$//;
    $text =~ s/^$//;

    @item = quotewords("], ", 0, $text);

    foreach (@item) {
        s/^\[//;
    }

    if($#item == -1) {
        return;
    }

    @item[$#item] =~ s/\]$//;

    foreach (@item) {
        if($_ =~ m/^gotMessage/) {
            $_ =~ s/^gotMessage, *//;
            print "Stranger: $_\n";
        } elsif($_ =~ m/^waiting/) {
            print "Waiting for someone to connect to...\n";
        } elsif($_ =~ m/^connected/) {
            print "Got a conversation partner!\n";
        } elsif($_ =~ m/^strangerDisconnected/) {
            print "Stranger disconnected. Reconnecting...\n";
            $response = $ua->post($host."/start");
            $sessid = $response->content;

            $sessid =~ s/\"//g;
        } elsif($_ =~ m/^typing/) {
            print "Stranger is typing\n";
        } elsif($_ =~ m/^stoppedTyping/) {
            print "Stranger has stopped typing\n";
        }
    }
}

sub disconnect {
    print "\nDisconnecting from Omegle...\n";
    $ua->post($host."/disconnect");
    kill ABRT, $$;
    kill ABRT, $pid;
}

$SIG{INT} = \&disconnect;
$SIG{CHLD} = "IGNORE";

$response = $ua->post($host."/start");
$sessid = $response->content;

$sessid =~ s/\"//g;

$response = $ua->get($host."/count?rand=".rand());
print $response->content." users connected.\n";

$pid = fork();

if($pid) {#Server stuff
    while(1) {
        $response = $ua->post($host."/events",
                              ["id" => $sessid]);

        #print "{".$response->content."}\n";
    
        handle($response->content);

        time.sleep(0.5);
    }
} else {#User input
    while(1) {
        $text = <>;
        chomp($text);
        #print "Sending text...";
        $response = $ua->post($host."/send",
                              ["msg" => $text, "id" => $sessid]);
        #print $response->content."\n";
    }
}
