]> git.donarmstrong.com Git - bin.git/blob - bibtex_to_paper
fix rebuild cache and pdf opening
[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            'papers_directory|papers-directory=s@',
94            'debug|d+','help|h|?','man|m');
95
96 pod2usage() if $options{help};
97 pod2usage({verbose=>2}) if $options{man};
98
99 $DEBUG = $options{debug};
100
101 my @USAGE_ERRORS;
102 if (not exists $options{bibtex} and
103     not exists $options{bibtex_cache}) {
104     push @USAGE_ERRORS,
105         "You must give at least one of --bibtex".
106         "or --bibtex-cache";
107 }
108
109 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
110
111 main();
112
113 sub main{
114
115     my $dbh;
116     my $sth;
117     if (exists $options{bibtex_cache}) {
118         my $initialize = 0;
119         if (-e $options{bibtex_cache}) {
120             ($dbh,$sth) = open_cache($options{bibtex_cache});
121         } else {
122             ($dbh,$sth) = initialize_database($options{bibtex_cache});
123         }
124     }
125
126     my %entries;
127     if (exists $options{build_cache}) {
128         $options{bibtex} //= [];
129         $options{bibtex} =
130             [@ARGV,
131              @{ref $options{bibtex}?$options{bibtex}:[$options{bibtex}]},
132             ];
133         @ARGV = ();
134     }
135     if (exists $options{bibtex}) {
136         for my $bibtex_file (@{ref $options{bibtex}?$options{bibtex}:[$options{bibtex}]}) {
137             parse_bibtex_file($bibtex_file,\%entries);
138         }
139     }
140
141     if (exists $options{papers_directory} and
142         defined $dbh
143        ) {
144         load_papers_into_database($dbh,$sth,$options{papers_directory});
145     }
146
147     p %entries if $DEBUG;
148     if (keys %entries and
149         defined $dbh) {
150         load_bibtex_entries_into_database($dbh,$sth,\%entries);
151     }
152
153     p @ARGV if $DEBUG;
154     for my $bibtex_key (@ARGV) {
155         open_bibtex_key(\%options,$dbh,$sth,\%entries,$bibtex_key);
156     }
157
158 }
159
160 sub load_papers_into_database {
161     my ($dbh,$sth,$dir) = @_;
162
163     my @dirs = ref($dir)?@{$dir}:$dir;
164
165     my $actually_load_it = sub {
166         return unless /\.pdf$/;
167         my $xoj = 0;
168         if (-e "${_}.xoj") {
169             $xoj = 1;
170         }
171         insert_or_replace_papers($dbh,$sth,basename($File::Find::name),File::Spec->rel2abs($_),$xoj);
172     };
173
174     my @pdfs;
175     find($actually_load_it,@dirs);
176 }
177
178 sub insert_or_replace_papers {
179     my ($dbh,$sth,$file_name,$file_loc,$has_xoj) = @_;
180     $sth->{insert_papers}->execute($file_name,$file_loc,$has_xoj);
181     $sth->{insert_papers}->finish();
182 }
183
184 sub load_bibtex_entries_into_database {
185     my ($dbh,$sth,$entries) = @_;
186     for my $entry (keys %{$entries}) {
187         next unless defined $entries->{$entry};
188         $sth->{insert_bibtex}->execute($entry,@{$entries->{$entry}}{qw(file_name doi html)});
189         $sth->{insert_bibtex}->finish();
190         print STDERR "inserted $entry {".join(',',map {defined $_?"'$_'":"'undef'"} %{$entries->{$entry}})."}\n" if $DEBUG;
191     }
192 }
193
194 sub open_bibtex_key {
195     my ($options,$dbh,$sth,$entries,$bibtex_key) = @_;
196     if (not defined $dbh) {
197         open_entry($dbh,$sth,$entries->{$bibtex_key},$options);
198     } else {
199         my $entry = select_entry_from_bibtex_key($dbh,$sth,$bibtex_key);
200         p $entry if $DEBUG;
201         open_entry($dbh,$sth,$entry,$options);
202     }
203 }
204
205 sub fork_exec {
206     my (@cmd) = @_;
207     my $child = fork();
208     if (not defined $child) {
209         die "Unable to fork for some reason: $!";
210     }
211     if ($child == 0) {
212         exec(@cmd);
213     } else {
214         return $child;
215     }
216
217 }
218
219 sub open_pdf {
220     my ($file_name,$options,$has_xoj) = @_;
221     print STDERR "opening $file_name\n" if $DEBUG;
222     if ($has_xoj) {
223         fork_exec('xournal',$file_name);
224     } else {
225         fork_exec('evince',$file_name)
226     }
227 }
228
229 sub open_browser{
230     my ($file) = @_;
231     fork_exec('sensible-browser',$file);
232 }
233
234 sub open_entry{
235     my ($dbh,$sth,$entry,$options) = @_;
236
237     return unless defined $entry and ref $entry and keys %{$entry};
238     if (defined $entry->{file_name} and length $entry->{file_name}) {
239         my $paper = select_one($dbh,$sth->{select_papers_by_name},$entry->{file_name});
240         p $paper if $DEBUG;
241         print STDERR $entry->{file_name} if $DEBUG;
242         if (defined $paper) {
243             open_pdf($paper->{path},$options,$paper->{has_xoj});
244             return;
245         }
246     }
247     if (defined $entry->{doi}) {
248         my $url = $entry->{doi};
249         $url =~ s{^doi://}{http://dx.doi.org/};
250         open_browser($url,$options);
251         return;
252     }
253     if (defined $entry->{html}) {
254         open_browser($entry->{html},$options);
255         return;
256     }
257 }
258
259 sub select_entry_from_bibtex_key{
260     my ($dbh,$sth,$bibtex_key) = @_;
261
262     my $entry = select_one($dbh,$sth->{select_bibtex_by_key},$bibtex_key);
263     if (not defined $entry) {
264         $bibtex_key =~ s/:.*$//;
265         $entry = select_one($dbh,$sth->{select_bibtex_by_approximate_key},$bibtex_key.'%');
266     }
267     return $entry;
268 }
269
270 sub select_one{
271     my ($dbh,$sth,@bind_vals) = @_;
272     $sth->execute(@bind_vals) or
273         die "Unable to select one: ".$dbh->errstr();
274     my $results = $sth->fetchall_arrayref({});
275     $sth->finish();
276     return ref($results)?$results->[0]:undef;
277 }
278
279 sub parse_bibtex_file {
280     my ($file,$entries) = @_;
281
282     my $bibfile = Text::BibTeX::File->new($file)
283         or die "Unable to open $file for reading: $!";
284     my @entry_comments;
285     my $entry;
286     while ($entry = Text::BibTeX::Entry->new($bibfile)) {
287         print STDERR "In Entry ".$entry->metatype() if $DEBUG;
288         if ($entry->metatype() == BTE_COMMENT) {
289             push @entry_comments,$entry->value();
290         } elsif ($entry->metatype() == BTE_REGULAR) {
291             my $entry_key = $entry->key();
292             if (not defined $entry_key) {
293                 @entry_comments = ();
294                 next;
295             }
296             my %entry_data;
297             # if there is a file comment, use it as the file name
298             for my $comment (@entry_comments) {
299                 next unless $comment =~ /^\s*file(?:name)?:?\s*(.+?)\s*$/i;
300                 next unless length $1;
301                 $entry_data{file_name} = $1.'.pdf';
302                 last;
303             }
304             my %field_prefix = (doi => 'doi://',
305                                 html => 'http://',
306                                 file => '',
307                                );
308             my %field_name = (doi => 'doi',
309                               html => 'html',
310                               file => 'file_name',);
311             for my $field (qw(file doi html)) {
312                 my $field_value = $entry->get($field);
313                 if (defined $field_value and $field_value =~ /\S+/) {
314                     $entry_data{$field_name{$field}} =
315                         $field_prefix{$field}.$field_value if
316                         not defined $entry_data{$field_name{$field}};
317                 }
318             }
319             $entries->{$entry_key} = {} if not defined $entries->{$entry_key};
320             for my $field (keys %entry_data) {
321                 $entries->{$entry_key}{$field} = $entry_data{$field} if
322                     defined $entry_data{$field};
323             }
324             # reset the entry comments
325             @entry_comments = ();
326         } else {
327             # do nothing
328         }
329         print STDERR "\n" if $DEBUG;
330     }
331     return $entries;
332 }
333
334
335 sub initialize_database {
336     my ($cache) = @_;
337     return open_cache($cache,1);
338 }
339
340 sub open_cache {
341     my ($cache,$initialize) = @_;
342     my $dbh = DBI->connect("dbi:SQLite:dbname=$cache","","") or
343         die "Unable to open/create database $cache";
344     if ($initialize) {
345         $dbh->do("DROP TABLE IF EXISTS bibtex;");
346         $dbh->do("DROP TABLE IF EXISTS papers;");
347         $dbh->do(<<EOF);
348 CREATE TABLE bibtex (
349 bibtex_key TEXT PRIMARY KEY,
350 file_name TEXT,
351 doi TEXT,
352 html TEXT
353 );
354 EOF
355         $dbh->do(<<EOF);
356 CREATE UNIQUE INDEX bibtex_file_name ON bibtex(file_name);
357 EOF
358         $dbh->do(<<EOF);
359 CREATE UNIQUE INDEX bibtex_bibtex_key ON bibtex(bibtex_key);
360 EOF
361         $dbh->do(<<EOF);
362 CREATE TABLE papers (
363 file_name TEXT PRIMARY KEY,
364 path TEXT,
365 has_xoj BOOLEAN
366 );
367 EOF
368         $dbh->do(<<EOF);
369 CREATE UNIQUE INDEX papers_path ON papers(path);
370 EOF
371         $dbh->do(<<EOF);
372 CREATE UNIQUE INDEX papers_file_name ON papers(file_name);
373 EOF
374     }
375     my %s =
376         (insert_papers => <<'EOF',
377 INSERT OR REPLACE INTO papers(file_name,path,has_xoj) VALUES (?,?,?);
378 EOF
379          insert_bibtex => <<'EOF',
380 INSERT OR REPLACE INTO bibtex (bibtex_key,file_name,doi,html) VALUES (?,?,?,?);
381 EOF
382          select_papers_by_name => <<'EOF',
383 SELECT * FROM papers WHERE file_name = ?;
384 EOF
385          select_papers_by_path => <<'EOF',
386 SELECT * FROM papers WHERE path = ?;
387 EOF
388          select_bibtex_by_key => <<'EOF',
389 SELECT * FROM bibtex WHERE bibtex_key = ?;
390 EOF
391          select_bibtex_by_approximate_key => <<'EOF',
392 SELECT * FROM bibtex WHERE bibtex_key LIKE ?;
393 EOF
394          select_bibtex_by_file_name => <<'EOF',
395 SELECT * FROM bibtex WHERE file_name = ?;
396 EOF
397         );
398     my $st;
399     for my $key (keys %s) {
400         $st->{$key}=$dbh->prepare($s{$key}) //
401             die "Unable to prepare sql statement: ".$dbh->errstr;
402     }
403     return ($dbh,$st);
404 }
405
406
407 __END__