Skip to content

Instantly share code, notes, and snippets.

@t-kashima
Created September 20, 2011 18:09
Show Gist options
  • Save t-kashima/1229831 to your computer and use it in GitHub Desktop.
Save t-kashima/1229831 to your computer and use it in GitHub Desktop.
package Kadai::Library;
use strict;
use warnings;
use base qw(Class::Accessor::Fast);
use Carp qw(croak);
use WWW::Mechanize;
use Web::Scraper;
use DateTime;
use URI;
__PACKAGE__->mk_accessors(qw(crid));
my $baseurl = 'http://www.lib.kagawa-u.ac.jp';
sub new {
my ($class, %args) = @_;
my $self = bless {}, $class;
$self->{crid} = $self->login($args{username}, $args{password}) or croak 'failed login';
return $self;
}
sub login {
my ($self, $username, $password) = @_;
my $mech = WWW::Mechanize->new;
$mech->get(URI->new($baseurl.'/mylibrary/'));
$mech->submit_form(
form_number => 1,
fields => {
username => $username,
password => $password,
},
);
return undef unless ($mech->success);
return $mech->form_name('mylibrary')->find_input('crid')->value;
}
sub lending_books {
my $self = shift;
croak 'required login' unless $self->{crid};
my $res = scraper {
process '//form[@name="re"]//tr', 'books[]' => scraper {
process '//td[3]', 'begin_date' => \&parse_datetime;
process '//td[5]', 'end_date' => \&parse_datetime;
process '//td[6]', 'delay_day' => \&parse_number;
process '//td[7]', 'title' => 'TEXT';
};
}->scrape(URI->new($baseurl.'/service/request-query?idkey='.$self->crid));
return [ map {
Kadai::Library::Book->new(%$_);
} grep { %$_ } @{ $res->{books} } ];
}
sub parse_datetime {
my $node = shift;
my ($year, $month, $day) = split /\./, $node->as_text;
DateTime->new(
time_zone => 'Asia/Tokyo',
year => $year,
month => $month,
day => $day,
);
}
sub parse_number {
my $node = shift;
return $1 if ($node->as_text =~ /(\d+)/);
return 0;
}
package Kadai::Library::Book;
use strict;
use warnings;
use base qw(Class::Accessor::Fast);
use Carp qw(croak);
use URI;
__PACKAGE__->mk_accessors(qw(title begin_date end_date delay_day));
sub new {
my ($class, %args) = @_;
my $self = bless {
title => $args{title},
begin_date => $args{begin_date},
end_date => $args{end_date},
delay_day => $args{delay_day},
}, $class;
return $self;
}
sub browse {
my $self = shift;
my $baseurl = 'http://google.co.jp/search';
my $title = $self->title;
my $url = URI->new("$baseurl?q=$title&btnI=I'm Feeling Lucky");
system("open -a Safari \"$url\"");
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment