#!/usr/bin/perl -w

use constant USERNAME => 'twoje konto';
use constant PASSWORD => 'twoje haso';

use strict;
use File::Path;
use Getopt::Long;
use WWW::Yahoo::Groups;
$SIG{PIPE} = 'IGNORE';

# definicja opcji wiersza polece; 
# sprawdzenie, czy wskazano grup.
my ($debug, $group, $last, $first, $stats);
GetOptions(
    "debug"     => \$debug,
    "group=s"   => \$group,
    "stats"     => \$stats,
    "first=i"   => \$first,
    "last=i"    => \$last,
); (defined $group) or die "Trzeba poda grup!\n";

# rejestracja w Yahoo! Groups.
my $w = WWW::Yahoo::Groups->new(  );
$w->debug( $debug );
$w->login( USERNAME, PASSWORD );
$w->list( $group );
$w->agent->requests_redirectable( [] ); # bez przekierowa

# pierwszy i ostatni identyfikatory grupy.
my $first_id = $w->first_msg_id(  );
my $last_id = $w->last_msg_id(  );
print "Wiadomoci z $group: $first_id do $last_id\n";
exit 0 if $stats; # tylko liczby.

# domylnie bierzemy identyfikatory od pierwszego
# do ostatniego z danej grupy; jeli ich brak,
# korzystamy z opcji z wiersza polece.
$first = $first_id unless $first;
$last  = $last_id  unless $last;
warn "Pobieranie $first do $last\n";

# pobieramy wskazane komunikaty
.
for my $msgnum ($first..$last) {
    fetch_message( $w, $msgnum );
}

sub fetch_message {
    my $w = shift;
    my $msgnum = shift;

    # Wiadomoci wstawiamy do katalogw co 100.
    my $dirname = int($msgnum/100)*100;

    # W razie potrzeby tworzymy katalog.
    my $dir = "$group/$dirname";
    mkpath( $dir ) unless -d $dir;

    # Nie pobieramy wiadomoci, ktre ju mamy...
    my $filename = "$dir/$msgnum";
    return if -f $filename;

    # pobieramy tre, sprawdzamy bdy.
    my $content = eval { $w->fetch_message($msgnum) };
    if ( $@ ) {
        if ( $@->isa('X::WWW::Yahoo::Groups') ) {
            warn "Niedostpna wiadomo $msgnum: ",$@->error,"\n";
        } else { warn "Niemoliwe pobranie wiadomoci $msgnum\n"; }
    } else {
        open(FH, ">$filename") 
          or return warn "Niemoliwe utworzenie pliku $filename: $!\n";
        print FH $content; close FH; # dane s ju zapisane.
        $w->autosleep( 5 ); # teraz przerwa, aby nie przecia.
    }
}

