ダイアリーのバックアップ

use strict;
use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Cookies;

my $mode = 'export';
my $username = 'oppara';
my $password = 'pass';
my $cookie_file = '/path/to/cookie.txt';
my $bak_file = '/path/to/hatena.bak';

my $export_url = 'http://d.hatena.ne.jp/' . $username . '/' . $mode;
my $login_url = 'https://www.hatena.ne.jp/login';

my $ua = LWP::UserAgent->new();
$ua->cookie_jar( HTTP::Cookies->new( file => $cookie_file,
                                     autosave => 1 ) );

if ( -e $cookie_file ) {
    backup();
    exit(0);
}

if ( login() ) {
    backup();
    exit(0);
}

die( "cannot login?n" );


sub backup {
    my $res = $ua->request( HTTP::Request->new( GET => $export_url ) );
#     print $res->status_line(), "?n";
    open( BAK, '>', $bak_file ) or die( "$!?n" );
    print BAK $res->content();
    close( BAK ) or die( "$!?n" );
}

sub login {
    my %form;
    $form{key} = $username;
    $form{password} = $password;
    $form{mode} = 'enter';
    $form{autologin} = '1';
    my $res = $ua->request(
        HTTP::Request::Common::POST( $login_url, ?%form )
    );

    return $res->is_success();
}

__END__