]> git.donarmstrong.com Git - bin.git/blob - bibtex_to_paper
select by pmid as well
[bin.git] / bibtex_to_paper
1 #!/usr/bin/perl
2 # bibtex_to_paper opens the paper corresponding to a bibtex key
3 # and is released under the terms of the GNU GPL version 3, or any
4 # later version, at your option. See the file README and COPYING for
5 # more information.
6 # Copyright 2014 by Don Armstrong <don@donarmstrong.com>.
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 use File::Find;
16 use File::Basename qw(basename);
17 use File::Spec qw(rel2abs);
18 use Text::BibTeX;
19 use User;
20 use Data::Printer;
21
22 use DBI;
23
24 =head1 NAME
25
26 bibtex_to_paper - opens the paper corresponding to a bibtex key
27
28 =head1 SYNOPSIS
29
30 bibtex_to_paper [options] bibtexkey
31
32  Options:
33   --bibtex, -b bibtex file to look up key in
34   --bibtex-cache, -c bibtex cache file
35   --build-cache, -B build cache using bibtex files
36   --pdf-dir pdf directory
37   --pdfviewer, -p pdf viewer to use
38   --debug, -d debugging level (Default 0)
39   --help, -h display this help
40   --man, -m display manual
41
42 =head1 OPTIONS
43
44 =over
45
46 =item B<--bibtex, -b>
47
48 Bibtex file to look key up in
49
50 =item B<--bibtex-cache, -c>
51
52 Bibtex cache file; rebuilt if bibtex file changes
53
54 =item B<--pdfviewer, -p>
55
56 PDF viewer to use; defaults to evince unless a .xoj exists, in which
57 case xournal is used.
58
59 =item B<--debug, -d>
60
61 Debug verbosity. (Default 0)
62
63 =item B<--help, -h>
64
65 Display brief usage information.
66
67 =item B<--man, -m>
68
69 Display this manual.
70
71 =back
72
73 =head1 EXAMPLES
74
75 bibtex_to_paper
76
77 =cut
78
79
80 use vars qw($DEBUG);
81
82 my %options = (debug           => 0,
83                help            => 0,
84                man             => 0,
85                'bibtex_cache'  => File::Spec->catfile(User->Home,'.bibtex_to_paper_cache'),
86               );
87
88 GetOptions(\%options,
89            'build_cache|build-cache!',
90            'bibtex|b=s@',
91            'bibtex_cache|bibtex-cache|c=s',
92            'pdfviewer|p=s',
93            'clear_cache|clear-cache!',
94            'papers_directory|papers-directory=s@',
95            'debug|d+','help|h|?','man|m');
96
97 pod2usage() if $options{help};
98 pod2usage({verbose=>2}) if $options{man};
99
100 $DEBUG = $options{debug};
101
102 my @USAGE_ERRORS;
103 if (not exists $options{bibtex} and
104     not exists $options{bibtex_cache}) {
105     push @USAGE_ERRORS,
106         "You must give at least one of --bibtex".
107         "or --bibtex-cache";
108 }
109
110 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
111
112 main();
113
114 sub main{
115
116     my $dbh;
117     my $sth;
118     if (exists $options{bibtex_cache}) {
119         my $initialize = 0;
120         if (-e $options{bibtex_cache}) {
121             ($dbh,$sth) = open_cache($options{bibtex_cache});
122         } else {
123             ($dbh,$sth) = initialize_database($options{bibtex_cache});
124         }
125     }
126
127     if (exists $options{clear_cache}) {
128         clear_cache($dbh,$sth);
129     }
130     my %entries;
131     if (exists $options{build_cache}) {
132         $options{bibtex} //= [];
133         $options{bibtex} =
134             [@ARGV,
135              @{ref $options{bibtex}?$options{bibtex}:[$options{bibtex}]},
136             ];
137         @ARGV = ();
138     }
139     if (exists $options{bibtex}) {
140         for my $bibtex_file (@{ref $options{bibtex}?$options{bibtex}:[$options{bibtex}]}) {
141             parse_bibtex_file($bibtex_file,\%entries);
142         }
143     }
144
145     if (exists $options{papers_directory} and
146         defined $dbh
147        ) {
148         load_papers_into_database($dbh,$sth,$options{papers_directory});
149     }
150
151     p %entries if $DEBUG;
152     if (keys %entries and
153         defined $dbh) {
154         load_bibtex_entries_into_database($dbh,$sth,\%entries);
155     }
156
157     p @ARGV if $DEBUG;
158     for my $bibtex_key (@ARGV) {
159         open_bibtex_key(\%options,$dbh,$sth,\%entries,$bibtex_key);
160     }
161
162 }
163
164 sub clear_cache {
165     my ($dbh,$sth) = @_;
166     $sth->{clear_papers_cache}->execute();
167     $sth->{clear_bibtex_cache}->execute();
168 }
169
170 sub load_papers_into_database {
171     my ($dbh,$sth,$dir) = @_;
172
173     my @dirs = ref($dir)?@{$dir}:$dir;
174
175     my $actually_load_it = sub {
176         return unless /\.pdf$/;
177         my $xoj = 0;
178         if (-e "${_}.xoj") {
179             $xoj = 1;
180         }
181         insert_or_replace_papers($dbh,$sth,basename($File::Find::name),File::Spec->rel2abs($_),$xoj);
182     };
183
184     my @pdfs;
185     find($actually_load_it,@dirs);
186 }
187
188 sub insert_or_replace_papers {
189     my ($dbh,$sth,$file_name,$file_loc,$has_xoj) = @_;
190     $sth->{insert_papers}->execute($file_name,$file_loc,$has_xoj);
191     $sth->{insert_papers}->finish();
192 }
193
194 sub load_bibtex_entries_into_database {
195     my ($dbh,$sth,$entries) = @_;
196     for my $entry (keys %{$entries}) {
197         next unless defined $entries->{$entry};
198         $sth->{insert_bibtex}->execute($entry,@{$entries->{$entry}}{qw(file_name doi html)});
199         $sth->{insert_bibtex}->finish();
200         print STDERR "inserted $entry {".join(',',map {defined $_?"'$_'":"'undef'"} %{$entries->{$entry}})."}\n" if $DEBUG;
201     }
202 }
203
204 sub open_bibtex_key {
205     my ($options,$dbh,$sth,$entries,$bibtex_key) = @_;
206     if (not defined $dbh) {
207         open_entry($dbh,$sth,$entries->{$bibtex_key},$options);
208     } else {
209         my $entry = select_entry_from_bibtex_key($dbh,$sth,$bibtex_key);
210         p $entry if $DEBUG;
211         open_entry($dbh,$sth,$entry,$options);
212     }
213 }
214
215 sub fork_exec {
216     my (@cmd) = @_;
217     my $child = fork();
218     if (not defined $child) {
219         die "Unable to fork for some reason: $!";
220     }
221     if ($child == 0) {
222         exec(@cmd);
223     } else {
224         return $child;
225     }
226
227 }
228
229 sub open_pdf {
230     my ($file_name,$options,$has_xoj) = @_;
231     print STDERR "opening $file_name\n" if $DEBUG;
232     if ($has_xoj) {
233         fork_exec('xournal',$file_name);
234     } else {
235         fork_exec('evince',$file_name)
236     }
237 }
238
239 sub open_browser{
240     my ($file) = @_;
241     fork_exec('sensible-browser',$file);
242 }
243
244 sub open_entry{
245     my ($dbh,$sth,$entry,$options) = @_;
246
247     return unless defined $entry and ref $entry and keys %{$entry};
248     if (defined $entry->{file_name} and length $entry->{file_name}) {
249         my $paper = select_one($dbh,$sth->{select_papers_by_name},$entry->{file_name});
250         if (not defined $paper) {
251             my ($pmid) = $entry->{file_name} =~ /pmid_(\d+)/;
252             if (defined $pmid and length $pmid) {
253                 $paper = select_one($dbh,$sth->{select_papers_by_pmid},'%pmid_'.$pmid.'.%');
254             }
255         }
256         p $paper if $DEBUG;
257         print STDERR $entry->{file_name} if $DEBUG;
258         if (defined $paper) {
259             open_pdf($paper->{path},$options,$paper->{has_xoj});
260             return;
261         }
262     }
263     if (defined $entry->{doi}) {
264         my $url = $entry->{doi};
265         $url =~ s{^doi://}{http://dx.doi.org/};
266         open_browser($url,$options);
267         return;
268     }
269     if (defined $entry->{html}) {
270         open_browser($entry->{html},$options);
271         return;
272     }
273 }
274
275 sub select_entry_from_bibtex_key{
276     my ($dbh,$sth,$bibtex_key) = @_;
277
278     my $entry = select_one($dbh,$sth->{select_bibtex_by_key},$bibtex_key);
279     if (not defined $entry) {
280         $bibtex_key =~ s/:.*$//;
281         $entry = select_one($dbh,$sth->{select_bibtex_by_approximate_key},$bibtex_key.'%');
282     }
283     return $entry;
284 }
285
286 sub select_one{
287     my ($dbh,$sth,@bind_vals) = @_;
288     $sth->execute(@bind_vals) or
289         die "Unable to select one: ".$dbh->errstr();
290     my $results = $sth->fetchall_arrayref({});
291     $sth->finish();
292     return ref($results)?$results->[0]:undef;
293 }
294
295 sub parse_bibtex_file {
296     my ($file,$entries) = @_;
297
298     my $bibfile = Text::BibTeX::File->new($file)
299         or die "Unable to open $file for reading: $!";
300     my @entry_comments;
301     my $entry;
302     while ($entry = Text::BibTeX::Entry->new($bibfile)) {
303         print STDERR "In Entry ".$entry->metatype() if $DEBUG;
304         if ($entry->metatype() == BTE_COMMENT) {
305             push @entry_comments,$entry->value();
306         } elsif ($entry->metatype() == BTE_REGULAR) {
307             my $entry_key = $entry->key();
308             if (not defined $entry_key) {
309                 @entry_comments = ();
310                 next;
311             }
312             my %entry_data;
313             # if there is a file comment, use it as the file name
314             for my $comment (@entry_comments) {
315                 next unless $comment =~ /^\s*file(?:name)?:?\s*(.+?)\s*$/i;
316                 next unless length $1;
317                 $entry_data{file_name} = $1.'.pdf';
318                 last;
319             }
320             my %field_prefix = (doi => 'doi://',
321                                 html => 'http://',
322                                 file => '',
323                                );
324             my %field_name = (doi => 'doi',
325                               html => 'html',
326                               file => 'file_name',);
327             for my $field (qw(file doi html)) {
328                 my $field_value = $entry->get($field);
329                 if (defined $field_value and $field_value =~ /\S+/) {
330                     $entry_data{$field_name{$field}} =
331                         $field_prefix{$field}.$field_value if
332                         not defined $entry_data{$field_name{$field}};
333                 }
334             }
335             $entries->{$entry_key} = {} if not defined $entries->{$entry_key};
336             for my $field (keys %entry_data) {
337                 $entries->{$entry_key}{$field} = $entry_data{$field} if
338                     defined $entry_data{$field};
339             }
340             # reset the entry comments
341             @entry_comments = ();
342         } else {
343             # do nothing
344         }
345         print STDERR "\n" if $DEBUG;
346     }
347     return $entries;
348 }
349
350
351 sub initialize_database {
352     my ($cache) = @_;
353     return open_cache($cache,1);
354 }
355
356 sub open_cache {
357     my ($cache,$initialize) = @_;
358     my $dbh = DBI->connect("dbi:SQLite:dbname=$cache","","") or
359         die "Unable to open/create database $cache";
360     if ($initialize) {
361         $dbh->do("DROP TABLE IF EXISTS bibtex;");
362         $dbh->do("DROP TABLE IF EXISTS papers;");
363         $dbh->do(<<EOF);
364 CREATE TABLE bibtex (
365 bibtex_key TEXT PRIMARY KEY,
366 file_name TEXT,
367 doi TEXT,
368 html TEXT
369 );
370 EOF
371         $dbh->do(<<EOF);
372 CREATE UNIQUE INDEX bibtex_file_name ON bibtex(file_name);
373 EOF
374         $dbh->do(<<EOF);
375 CREATE UNIQUE INDEX bibtex_bibtex_key ON bibtex(bibtex_key);
376 EOF
377         $dbh->do(<<EOF);
378 CREATE TABLE papers (
379 file_name TEXT PRIMARY KEY,
380 path TEXT,
381 has_xoj BOOLEAN
382 );
383 EOF
384         $dbh->do(<<EOF);
385 CREATE UNIQUE INDEX papers_path ON papers(path);
386 EOF
387         $dbh->do(<<EOF);
388 CREATE UNIQUE INDEX papers_file_name ON papers(file_name);
389 EOF
390     }
391     my %s =
392         (insert_papers => <<'EOF',
393 INSERT OR REPLACE INTO papers(file_name,path,has_xoj) VALUES (?,?,?);
394 EOF
395          insert_bibtex => <<'EOF',
396 INSERT OR REPLACE INTO bibtex (bibtex_key,file_name,doi,html) VALUES (?,?,?,?);
397 EOF
398          select_papers_by_name => <<'EOF',
399 SELECT * FROM papers WHERE file_name = ?;
400 EOF
401          select_papers_by_pmid => <<'EOF',
402 SELECT * FROM papers WHERE file_name LIKE ?;
403 EOF
404          select_papers_by_path => <<'EOF',
405 SELECT * FROM papers WHERE path = ?;
406 EOF
407          select_bibtex_by_key => <<'EOF',
408 SELECT * FROM bibtex WHERE bibtex_key = ?;
409 EOF
410          select_bibtex_by_approximate_key => <<'EOF',
411 SELECT * FROM bibtex WHERE bibtex_key LIKE ?;
412 EOF
413          select_bibtex_by_file_name => <<'EOF',
414 SELECT * FROM bibtex WHERE file_name = ?;
415 EOF
416          clear_papers_cache => <<'EOF',
417 DELETE FROM papers;
418 EOF
419          clear_bibtex_cache => <<'EOF',
420 DELETE FROM bibtex;
421 EOF
422         );
423     my $st;
424     for my $key (keys %s) {
425         $st->{$key}=$dbh->prepare($s{$key}) //
426             die "Unable to prepare sql statement: ".$dbh->errstr;
427     }
428     return ($dbh,$st);
429 }
430
431
432 __END__