/
BookWeb.pm
139 lines (106 loc) · 2.8 KB
/
BookWeb.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package BookWeb;
use Dancer2;
#use Dancer2::Session;
use Dancer2::Plugin::DBIC;
use Net::Amazon;
use DateTime;
our $VERSION = '0.1';
sub get_amazon {
return Net::Amazon->new(
token => $ENV{AMAZON_KEY},
secret_key => $ENV{AMAZON_SECRET},
associate_tag => $ENV{AMAZON_ASSTAG},
locale => 'uk',
) or die "Cannot connect to Amazon\n";
}
my %public_path = map { $_ => 1 } ('/', '/login', '/search');
hook before => sub {
if (! session('logged_in') and
! $public_path{request->path_info}) {
var requested_path => request->path_info;
forward '/login';
}
};
get '/' => sub {
my $books_rs = schema->resultset('Book');
my @reading = $books_rs->search({
started => { '!=', undef },
ended => undef,
});
my @read = $books_rs->search({
ended => { '!=', undef },
});
my @to_read = $books_rs->search({
started => undef,
});
template 'index', {
reading => \@reading,
read => \@read,
to_read => \@to_read,
};
};
get '/start/:isbn' => sub {
my $books_rs = schema->resultset('Book');
my $book = $books_rs->find({ isbn => param('isbn')});
if ($book) {
$book->update({started => DateTime->now});
}
return redirect '/';
};
get '/end/:isbn' => sub {
my $books_rs = schema->resultset('Book');
my $book = $books_rs->find({ isbn => param('isbn')});
if ($book) {
$book->update({ended => DateTime->now});
}
return redirect '/';
};
get '/add/:isbn' => sub {
my $author_rs = schema->resultset('Author');
my $amz = get_amazon();
# Search for the book at Amazon
my $resp = $amz->search(asin => param('isbn'));
unless ($resp->is_success) {
die 'Error: ', $resp->message;
}
my $book = $resp->properties;
my $title = $book->ProductName;
my $author_name = ($book->authors)[0];
my $imgurl = $book->ImageUrlMedium;
# Find or create the author
my $author = $author_rs->find_or_create({
name => $author_name,
});
# Add the book to the author
$author->add_to_books({
isbn => param('isbn'),
title => $title,
image_url => $imgurl,
});
return redirect '/';
};
post '/search' => sub {
my $amz = get_amazon();
my $resp = $amz->search(
keyword => param('search'),
mode => 'books',
);
my %data;
$data{search} = param('search');
if ($resp->is_success) {
$data{books} = [ $resp->properties ];
} else {
$data{error} = $resp->message;
}
template 'results', \%data;
};
get '/login' => sub {
template 'login', { path => vars->{requested_path } };
};
post '/login' => sub {
if (params->{user} eq 'reader' && params->{pass} eq 'letmein') {
session 'logged_in' => 1;
}
redirect params->{path} || '/';
};
true;