1 | #!/usr/bin/perl -w |
---|
2 | use strict; |
---|
3 | |
---|
4 | use FindBin; |
---|
5 | use lib "$FindBin::RealBin/lib"; |
---|
6 | |
---|
7 | use YAML; |
---|
8 | use Getopt::Long; |
---|
9 | |
---|
10 | use Bookmarks; |
---|
11 | |
---|
12 | GetOptions( |
---|
13 | 'file|f=s' => \my $DBNAME, |
---|
14 | 'title=s' => \my $TITLE, |
---|
15 | ); |
---|
16 | |
---|
17 | my $dbname = $DBNAME || $ENV{BKMK_DBNAME}; |
---|
18 | die "Usage: $0 --file <dbname> <command>\n" unless $dbname; |
---|
19 | |
---|
20 | my $bookmarks = Bookmarks->new({ |
---|
21 | dbname => $dbname, |
---|
22 | }); |
---|
23 | |
---|
24 | my $command = shift; |
---|
25 | |
---|
26 | my %action_for = ( |
---|
27 | init => sub { |
---|
28 | $bookmarks->create_tables; |
---|
29 | }, |
---|
30 | |
---|
31 | get => sub { |
---|
32 | my $identifier = shift; |
---|
33 | my $bookmark = find_bookmark($identifier); |
---|
34 | print $bookmark ? Dump($bookmark->TO_JSON) : "Not Found\n"; |
---|
35 | }, |
---|
36 | |
---|
37 | add => sub { |
---|
38 | my ($uri, @tags) = @_; |
---|
39 | my $title = defined $TITLE ? $TITLE : fetch_title($uri); |
---|
40 | my $bookmark = $bookmarks->add({ uri => $uri, title => $title, tags => \@tags }); |
---|
41 | print Dump($bookmark->TO_JSON); |
---|
42 | }, |
---|
43 | |
---|
44 | list => sub { |
---|
45 | my @tags = @_; |
---|
46 | my $resources = $bookmarks->get_bookmarks({ |
---|
47 | tags => \@tags |
---|
48 | }); |
---|
49 | # TODO: list by tags, date, etc. |
---|
50 | # TODO: coordinate this commandline script with the CGI app |
---|
51 | print Dump([ map { $_->TO_JSON } @{ $resources->results } ]); |
---|
52 | }, |
---|
53 | |
---|
54 | tag => sub { |
---|
55 | my ($identifier, @tags) = @_; |
---|
56 | my $bookmark = find_bookmark($identifier); |
---|
57 | if ($bookmark) { |
---|
58 | $bookmark->tags(\@tags); |
---|
59 | $bookmarks->update($bookmark); |
---|
60 | print Dump($bookmark->TO_JSON); |
---|
61 | } else { |
---|
62 | die "Not found\n"; |
---|
63 | } |
---|
64 | }, |
---|
65 | |
---|
66 | #TODO: interactive editing of a bookmark |
---|
67 | |
---|
68 | # bulk loading |
---|
69 | load => sub { |
---|
70 | my ($src_file) = @_; |
---|
71 | my $src_bookmarks = YAML::LoadFile($src_file); |
---|
72 | for my $bookmark (@{ $src_bookmarks }) { |
---|
73 | $bookmarks->add($bookmark); |
---|
74 | } |
---|
75 | }, |
---|
76 | ); |
---|
77 | |
---|
78 | $action_for{$command}->(@ARGV); |
---|
79 | |
---|
80 | sub find_bookmark { |
---|
81 | my $identifier = shift; |
---|
82 | my $query = $identifier =~ /^\d+$/ ? { id => $identifier } : { uri => $identifier }; |
---|
83 | return $bookmarks->get_bookmark($query); |
---|
84 | } |
---|
85 | |
---|
86 | sub fetch_title { |
---|
87 | my $uri = shift; |
---|
88 | require WWW::Mechanize; |
---|
89 | my $mech = WWW::Mechanize->new; |
---|
90 | $mech->get($uri); |
---|
91 | return $mech->title || $uri; |
---|
92 | } |
---|