]> git.donarmstrong.com Git - bin.git/blob - get_pdf
Abstract out GIT_HOST
[bin.git] / get_pdf
1 #! /usr/bin/perl
2 # get_pdf tries to get pdfs, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2008 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 1352 2009-01-25 02:04:38Z don $
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 =head1 NAME
16
17 get_pdf - try to get a pdf
18
19 =head1 SYNOPSIS
20
21 get_pdf [options] reference [references]
22
23  Options:
24   --debug, -d debugging level (Default 0)
25   --help, -h display this help
26   --man, -m display manual
27
28 =head1 OPTIONS
29
30 =over
31
32 =item B<--pmid, -p>
33
34 The reference is a pmid
35
36 =item B<--cgi-proxy, -C>
37
38 Use this cgi proxy style proxy
39
40 =item B<--debug, -d>
41
42 Debug verbosity. (Default 0)
43
44 =item B<--help, -h>
45
46 Display brief usage information.
47
48 =item B<--man, -m>
49
50 Display this manual.
51
52 =back
53
54 =head1 EXAMPLES
55
56
57 =cut
58
59
60 use vars qw($DEBUG);
61
62 use Cwd;
63 use WWW::Mechanize;
64 use Data::Printer;
65
66 my %options = (debug           => 0,
67                help            => 0,
68                man             => 0,
69                use_links       => 1,
70                );
71
72 my %REFERENCE_TYPES = (pmid => 'pmid|p');
73
74 GetOptions(\%options,
75            values %REFERENCE_TYPES,
76            'use_links|use-links!',
77            'cgi_proxy|cgi-proxy|C=s',
78            'http_proxy|http-proxy|H=s',
79            'debug|d+','help|h|?','man|m');
80
81 pod2usage() if $options{help};
82 pod2usage({verbose=>2}) if $options{man};
83
84 $DEBUG = $options{debug};
85
86
87
88 if (not grep {exists $options{$_} and
89                   defined $options{$_} and
90                       $options{$_}} keys %REFERENCE_TYPES) {
91     $options{pmid} = 1;
92 }
93 my @USAGE_ERRORS;
94 if (grep {exists $options{$_}
95               and defined $options{$_}
96                   and $options{$_}} keys %REFERENCE_TYPES > 1) {
97     push @USAGE_ERRORS,"You can only specify exactly one of the ".(map { "--$_"} keys %REFERENCE_TYPES)." options";
98 }
99
100 if (not @ARGV) {
101     push @USAGE_ERRORS,"You must specify at least one reference";
102 }
103
104 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
105
106
107 if (exists $options{http_proxy}) {
108     $ENV{http_proxy} = $options{http_proxy};
109     $ENV{HTTP_PROXY} = $options{http_proxy};
110     $ENV{CGI_HTTP_PROXY} = $options{http_proxy};
111 }
112
113 if ($options{pmid}) {
114     my $m = WWW::Mechanize->new(agent => 'Mozilla',cookie_jar => {});
115     for my $pmid (@ARGV) {
116         $pmid =~ s/\D//g;
117         next unless length $pmid;
118         my $url = "www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids=${pmid}&dopt=Abstract";
119         if (exists $options{cgi_proxy}) {
120             $url = $options{cgi_proxy}.$url;
121         }
122         $url = "http://${url}";
123         eval {
124             $m->get($url) or die "Unable to get $url";
125             my $orig_mech = $m->clone();
126             use Data::Dumper;
127             my @possible_links = $m->find_all_links(text_regex => qr/to\s*read/i);
128             # try to find the other links
129             push @possible_links,
130                 grep {my $attr = $_->attrs(); exists $attr->{title} and $attr->{title} =~ qr/(?:Full\s*Text|PMC)/i}
131                     $m->links();
132             print STDERR map {"article link: ".$_->url_abs()."\n"} @possible_links if $DEBUG;
133             die "No links" unless @possible_links;
134             do {
135                 $m = $orig_mech;
136                 eval {
137                     print "trying ".$possible_links[0]->url()."\n" if $DEBUG;
138                     $m->get($possible_links[0]->url()) or
139                         die "Unable to follow link";
140                     # try to find pdf link
141                     my $pdf_m = find_pdf_link($m) or
142                         die "Unable to find pdf";
143                     my $fh = IO::File->new($pmid.'.pdf','w') or
144                         die "Unable to open ${pmid}.pdf for writing: $!";
145                     print {$fh} $pdf_m->content or
146                         die "Unable to write to ${pmid}.pdf: $!";
147                     close $fh or
148                         die "Unable to close ${pmid}.pdf filehandle: $!";
149                 };
150                 shift @possible_links;
151             } while ($@ and @possible_links);
152             if ($@) {
153                 die "$@";
154             }
155         };
156         if ($@) {
157             print STDERR "$@\n" if $DEBUG;
158             if ($options{use_links}) {
159                 system('links2',
160                        # links2 doesn't like the leading http:// of proxies for some reason
161                        exists $options{http_proxy}?('-http-proxy',(map {s{http://}{}; $_} $options{http_proxy})):(),
162                        $url
163                       ) == 0 or next;
164                 rename('temp.pdf',"${pmid}.pdf") if -e 'temp.pdf';
165             }
166         }
167     }
168 }
169
170
171 sub check_subframes {
172     my ($m,$call) = @_;
173     my @sub_frames = $m->find_all_links(tag_regex=>qr/^i?frame$/);
174     print STDERR "subframes: \n" if $DEBUG;
175     p @sub_frames if $DEBUG;
176     for my $frame (@sub_frames) {
177         my $r = $m->get($frame->url_abs());
178         print STDERR "trying: ".$frame->url_abs()."\n" if $DEBUG;
179         if ($r->header('Content-Type') =~ /pdf/) {
180             return $m;
181         }
182         print STDERR "failed: ".$r->header('Content-Type')."\n" if $DEBUG;
183     }
184     for my $frame (@sub_frames) {
185         my $r = $m->get($frame->url_abs());
186         my $pdf_m = find_pdf_link($m,
187                                   0,
188                                   $call+1,
189                                  );
190         if (defined $pdf_m) {
191             return $pdf_m;
192         }
193     }
194     return undef;
195 }
196
197
198 sub find_pdf_link {
199     my ($mech,$guess,$call) = @_;
200     $guess = 1 unless defined $guess;
201     $call = 0 unless defined $call;
202     # avoid looping endlessly
203     return undef if $call > 5;
204     my $m = $mech->clone();
205     if ($m->content =~ /select\s*a\s*website\s*below/i) {
206         print STDERR $m->uri() if $DEBUG;
207         print STDERR $m->content() if $DEBUG > 1;
208         my @inputs = $m->find_all_inputs(type => 'hidden',
209                                          name => q(urls['sd']),
210                                         );
211         return unless @inputs;
212         $m->get($inputs[0]->value);
213         print STDERR $m->content() if $DEBUG > 1;
214     }
215     my @possible_links;
216     # this brings forward the actual link at Science
217     push @possible_links,
218         grep {my $temp = $_->attrs();
219               exists $temp->{rel} and $temp->{rel} =~ qr/view-/i and
220                   defined $_->text() and $_->text() =~ qr/Full\s*Text.*PDF/i
221               }
222         $m->find_all_links(text_regex => qr/PDF/i);
223     # this is to prioritize the real link at science direct
224     push @possible_links,
225         grep {my $temp = $_->attrs();
226               use Data::Dumper;
227               print STDERR Dumper($temp);
228               (exists $temp->{title} and $temp->{title} =~ qr/(Download|Full\s*Text)\s*PDF/i) or
229                   (defined $_->text() and $_->text() =~ qr/(Full\s*Text|Download).*PDF/i)
230               }
231         $m->find_all_links(text_regex => qr/PDF/i);
232     my $possible_links = 0;
233     if ($DEBUG) {
234         $possible_links++;
235         print STDERR "possible links[$possible_links]:\n";
236         p @possible_links;
237     }
238     push @possible_links, grep { $_->url_abs() !~ /_orig(?:in)?=article/} $m->find_all_links(text_regex => qr/PDF/i);
239     if ($DEBUG) {
240         $possible_links++;
241         print STDERR "possible links[$possible_links]:\n";
242         p @possible_links;
243     }
244     push @possible_links, $m->find_all_links(tag_regex => qr/meta/,
245                                              url_regex  => qr/(reprint|\.pdf)/i,
246                                             );
247     if ($DEBUG) {
248         $possible_links++;
249         print STDERR "possible links[$possible_links]:\n";
250         p @possible_links;
251     }
252     # The masthead grep here is to handle PNAS, which has a link to their masthead in every article.
253     push @possible_links,
254         grep {my $temp = $_->attrs(); (not defined $temp->{title}) or $temp->{title} !~ qr/Masthead/i;}
255         $m->find_all_links(text_regex => qr/pdf/i);
256     if ($DEBUG) {
257         $possible_links++;
258         print STDERR "possible links[$possible_links]:\n";
259         p @possible_links;
260     }
261     push @possible_links,$m->find_all_links(text_regex => qr/manual\s*download/i);
262     if ($DEBUG) {
263         $possible_links++;
264         print STDERR "possible links[$possible_links]:\n";
265         p @possible_links;
266     }
267     print STDERR $m->uri() if $DEBUG;
268     print STDERR $m->content() if $DEBUG > 1;
269     print STDERR map{"possible pdf link: ".$_->url_abs().qq(\n)} @possible_links if $DEBUG;
270     if (not @possible_links and $DEBUG) {
271         print STDERR $m->content();
272     }
273     my $best_guess = $possible_links[0] if @possible_links;
274     for my $link (@possible_links) {
275         print STDERR "trying ".$link->url_abs()."..." if $DEBUG;
276         my $r = $m->get($link->url_abs());
277         my $content = $m->content();
278         if ($r->header('Content-Type') =~ /pdf/) {
279             print STDERR "success\n" if $DEBUG;
280             return $m;
281         }
282         my $ret = check_subframes($m,$call);
283         return $ret if defined $ret;
284         print STDERR "failure; content type ".$r->header('Content-Type')."\n" if $DEBUG;
285         print STDERR $content if $DEBUG;
286     }
287     my $ret = check_subframes($m,$call);
288     return $ret if defined $ret;
289 #     if ($guess and defined $best_guess) {
290 #       $m->get($best_guess->url_abs());
291 #       return $m;
292 #     }
293     return undef;
294 }
295
296
297 __END__